query
stringlengths
7
9.55k
document
stringlengths
10
363k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
This is a tad meh. We basically need to meta program our test methods as we'll want individual meths for each check so we get this easy to read in jenkins, but since we only know which lister to use once the program runs we'll have to extend ourselves lazily via class_eval which allows us to edit the class from within a class method. The ultimate result is a bunch of test_pkg_version methods.
def define_tests @ours.each do |pkg| their = @theirs.find { |x| x.name == pkg.name } class_eval do define_method("test_#{pkg.name}_#{pkg.version}") do PackageVersionCheck.new(ours: pkg, theirs: their).run end end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def define_tests\n Apt.update if Process.uid.zero? # update if root\n @lister.packages.each do |pkg|\n class_eval do\n define_method(\"test_#{pkg.name}_#{pkg.version}\") do\n PackageVersionCheck.new(pkg).run\n end\n end\n end\n end", "def test_list\n list = []\n instance_methods.each do |m|\n next unless m.to_s =~ /^(ok|no)[_ ]/\n list << m\n end\n list\n end", "def final_test_methods\n return []\n end", "def method_missing(sym, *args, &block)\n m = sym.to_s\n if m =~ /^check$/ or m =~ /^check_.+$/\n new_method = m.gsub(/^check/, 'assert')\n begin\n self.send(new_method.to_sym, *args, &block)\n rescue AssertionFailedError => e\n add_failure(e.message, e.backtrace)\n false\n end\n else\n if sym == :setup\n return\n end\n if m !~ /(.*)__([A-Z_]+)$/\n super(sym, *args, &block)\n end\n test_name = self.class.modified_test_methods[m][0]\n param_key = self.class.modified_test_methods[m][1]\n test_params = self.class.testparameters[param_key]\n if test_params.nil?\n raise \"Could not find parameters for test '#{test_name}'\"\n end\n\n param_setup test_params\n send test_name\n end\n end", "def generate_test_class(data: [], linkstatus_url_log: {}, w_pipe: {})\n test_cond = @test_cond\n # Common proccessing\n # e.g.) TestSampleAppPcE2e1, TestSampleAppPcHttpstatus1\n test_class_name = make_test_class_name(data)\n # Select super class by test category\n super_suite_class = eval format('Bucky::TestEquipment::TestCase::%<test_category>sTestCase', test_category: data[:test_category].capitalize)\n # Define test suite class\n test_classes.const_set(test_class_name.to_sym, Class.new(super_suite_class) do |_klass|\n extend TestClassGeneratorHelper\n include TestClassGeneratorHelper\n define_method(:suite_data, proc { data[:suite] })\n define_method(:suite_id, proc { data[:test_suite_id] })\n define_method(:simple_test_class_name) do |original_name|\n match_obj = /\\Atest_(.+)\\(.+::(Test.+)\\)\\z/.match(original_name)\n \"#{match_obj[1]}(#{match_obj[2]})\"\n end\n define_method(:w_pipe, proc { w_pipe })\n\n # Class structure is different for each test category\n case data[:test_category]\n when 'linkstatus' then\n data[:suite][:cases].each_with_index do |t_case, i|\n method_name = make_test_method_name(data, t_case, i)\n description(\n t_case[:case_name],\n define_method(method_name) do\n puts \"\\n#{simple_test_class_name(name)}\"\n t_case[:urls].each do |url|\n linkstatus_check_args = { url: url, device: data[:suite][:device], exclude_urls: data[:suite][:exclude_urls], link_check_max_times: test_cond[:link_check_max_times], url_log: linkstatus_url_log }\n linkstatus_check(linkstatus_check_args)\n end\n end\n )\n end\n\n when 'e2e' then\n if data[:suite][:setup_each]\n def setup\n super\n puts \"[setup]#{simple_test_class_name(name)}\"\n add_test_procedure(suite_data[:setup_each][:procs])\n end\n end\n\n if data[:suite][:teardown_each]\n def teardown\n puts \"[teardown]#{simple_test_class_name(name)}\"\n add_test_procedure(suite_data[:teardown_each][:procs])\n super\n end\n end\n\n # Generate test case method\n data[:suite][:cases].each_with_index do |t_case, i|\n # e.g.) test_sample_app_pc_e2e_1_2\n method_name = make_test_method_name(data, t_case, i)\n method_obj = proc do\n puts \"\\n#{simple_test_class_name(name)}\\n #{t_case[:desc]} ....\"\n add_test_procedure(t_case[:procs])\n end\n description(t_case[:case_name], define_method(method_name, method_obj))\n end\n end\n end)\n end", "def run_checks\n methods.keep_if { |m| m.match(/^check_/) }.each do |check|\n send check.to_sym unless @skip.include? check.to_s.sub 'check_', ''\n end\n end", "def __list_check_methods\n methods.grep(/^#{@@checks_start_with}/) do |method|\n method.to_s\n end\n end", "def test_methods()\n tests = []\n stack = [@contexts.first]\n until stack.empty? do\n item = stack.pop\n stack += item.tests_and_subcontexts.reverse if item.is_a?(Context)\n tests << item if item.is_a?(String)\n end\n tests\n end", "def run_tests()\n @loaded_modules.each do |module_name|\n module_class = Object.const_get(module_name.to_s).const_get(module_name.to_s).new\n if module_class.respond_to?( 'run' )\n module_class.run()\n else\n puts \"\\e[31mWARNING\\e[0m: Module #{(module_name)} not implemented\"\n end\n end\n end", "def testmethods\n @test_methods ||= []\n end", "def test_Enviroment_004_SortMethods\r\n\r\n puts2(\"\")\r\n puts2(\"#######################\")\r\n puts2(\"Testcase: test_Enviroment_004_SortMethods\")\r\n puts2(\"#######################\")\r\n puts2(\" Sorted list of Methods in use:\")\r\n puts2(Object.new.methods.sort)\r\n puts2(\"######################\")\r\n\r\n end", "def tests; end", "def tests; end", "def tests\n @tests ||= begin\n require \"m/test_collection\"\n require \"m/test_method\"\n # With each suite and array of tests,\n # and with each test method present in this test file,\n # shove a new test method into this collection.\n suites.each_with_object TestCollection.new do |(suite_class, test_methods), collection|\n test_methods.each do |test_method|\n collection << TestMethod.create(suite_class, test_method)\n end\n end\n end\n end", "def patch_class!(klass)\n klass.class_eval do\n #\n # Make the check status accessible as a reader method.\n #\n attr_reader :status\n\n #\n # Patch the output method so it returns the output string instead of\n # sending it to stdout.\n #\n def output(msg = @message)\n @output ||= self.class.check_name + (msg ? \": #{msg}\" : '')\n end\n end\n end", "def test_multiple_classes_using_module\n other = Class.new do\n extend Puppet::Util::SubclassLoader\n handle_subclasses :other, \"puppet/other\"\n end\n Object.const_set(\"OtherLoader\", other)\n\n mk_subclass(\"multipletest\", \"puppet/other\", \"OtherLoader\")\n mk_subclass(\"multipletest\", \"puppet/fakeloaders\", \"TestPuppetUtilSubclassLoader::LoadTest\")\n #system(\"find #{@basedir}\")\n #puts File.read(File.join(@basedir, \"puppet/fakeloaders/multipletest.rb\"))\n #puts File.read(File.join(@basedir, \"puppet/other/multipletest.rb\"))\n\n othersub = mainsub = nil\n assert_nothing_raised(\"Could not look up other sub\") do\n othersub = OtherLoader.other(:multipletest)\n end\n assert_nothing_raised(\"Could not look up main sub\") do\n mainsub = LoadTest.faker(:multipletest)\n end\n assert(othersub, \"did not get other sub\")\n assert(mainsub, \"did not get main sub\")\n assert(othersub.ancestors.include?(OtherLoader), \"othersub is not a subclass of otherloader\")\n assert(mainsub.ancestors.include?(LoadTest), \"mainsub is not a subclass of loadtest\")\n end", "def each\n methods.each do |m|\n next unless m.to_s.start_with?('test_')\n yield(TestMethod.new(self, method(m)))\n end\n end", "def test_class_for(*mods, &blk)\n klass = Class.new\n klass.class_eval { include(*mods) }\n klass.class_eval(&blk) unless blk.blank?\n return klass\n end", "def testing desc, &block\n cls = Class.new(self)\n \n cls.reset_tests!\n Object.const_set self.name + desc.to_s.split(/\\W+/).map { |s| s.capitalize }.join, cls\n cls.setup_chained = self.setup_chained\n cls.teardown_chained = self.teardown_chained\n cls.desc = self.desc + \" \" + desc\n cls.tests($1.constantize) if defined?(Rails) && \n self.name =~ /^(.*(Controller|Helper|Mailer))Test/ && \n self < ActiveSupport::TestCase\n cls.class_eval(&block)\n self.testcases << cls\n end", "def list_checks\n load_dsl_if_available\n\n puts 'Available checks:'\n puts\n puts all_check_classes.map { |i| ' ' + i.identifier.to_s }.sort.join(\"\\n\")\n end", "def get_tests\n t = []\n\n defmod = Module.new{self.name='default'}\n\n selection = [@selection].flatten ; selection = [defmod] if selection.empty?\n crossover = [@crossover].flatten ; crossover = [defmod] if crossover.empty?\n mutator = [@mutator].flatten ; mutator = [defmod] if mutator.empty?\n\n selection.each{|s|\n crossover.each{|c| \n mutator.each{|m|\n t << [s,c,m]\n }\n }\n }\n t\n end", "def build_tests_array\n tests_array = []\n build_tests_list.each do |test|\n\npre_test_code = <<CODE\nrequire 'RubySelenium'\nrequire 'methods/selenium_methods'\n\nclass SeleniumTest < SeleniumMethods\n def run_test\n # test code goes here\nCODE\n\npost_test_code = <<CODE\n end\nend\n\ntestname = \\'#{File.basename(test, '.test')}\\'\ns = RubySelenium.new(testname)\nt = SeleniumTest.new(s)\nt.run_test\ns.complete\ns.go\nCODE\n\n code_array = StringIO.new(pre_test_code).readlines +\n File.readlines(test) +\n StringIO.new(post_test_code).readlines\n tests_array << code_array\n#\t code_array.each_with_index { |line,line_num| puts \"#{line_num+1} #{line}\\n\" }\n end\n tests_array\n end", "def define_test_tasks\n default_tasks = []\n\n if File.directory? \"test\" then\n desc 'Run the test suite. Use FILTER or TESTOPTS to add flags/args.'\n task :test do\n ruby make_test_cmd\n end\n\n desc 'Run the test suite using multiruby.'\n task :multi do\n ruby make_test_cmd(:multi)\n end\n\n desc 'Show which test files fail when run alone.'\n task :test_deps do\n tests = Dir[\"test/**/test_*.rb\"] + Dir[\"test/**/*_test.rb\"]\n\n paths = ['bin', 'lib', 'test'].join(File::PATH_SEPARATOR)\n null_dev = Hoe::WINDOZE ? '> NUL 2>&1' : '&> /dev/null'\n\n tests.each do |test|\n if not system \"ruby -I#{paths} #{test} #{null_dev}\" then\n puts \"Dependency Issues: #{test}\"\n end\n end\n end\n\n default_tasks << :test\n end\n\n if File.directory? \"spec\" then\n begin\n require 'spec/rake/spectask'\n\n desc \"Run all specifications\"\n Spec::Rake::SpecTask.new(:spec) do |t|\n t.libs = self.rspec_dirs\n t.spec_opts = self.rspec_options\n end\n rescue LoadError\n # do nothing\n end\n default_tasks << :spec\n end\n\n desc 'Run the default task(s).'\n task :default => default_tasks\n\n desc 'Run ZenTest against the package.'\n task :audit do\n libs = %w(lib test ext).join(File::PATH_SEPARATOR)\n sh \"zentest -I=#{libs} #{spec.files.grep(/^(lib|test)/).join(' ')}\"\n end\n end", "def test_to_normal(name, klassname=nil)\n unmunge(name.to_s.sub(/^test_/, '')) do |n|\n if defined? @inherited_methods then\n known_methods = (@inherited_methods[klassname] || {}).keys.sort.reverse\n known_methods_re = known_methods.map {|s| Regexp.escape(s) }.join(\"|\")\n n = n.sub(/^(#{known_methods_re})(_.*)?$/) { $1 } unless\n known_methods_re.empty?\n n\n end\n end\n end", "def stest_method_1(test); end", "def ptest_method_1(test); end", "def describe_internally *args, &block\n example = describe *args, &block\n klass = args[0]\n if klass.is_a? Class\n saved_private_instance_methods = klass.private_instance_methods\n example.before do\n klass.class_eval { public *saved_private_instance_methods }\n end\n example.after do\n klass.class_eval { private *saved_private_instance_methods }\n end\n end\nend", "def populate_queue\n Test.classes.flat_map do |klass, line_numbers|\n list = klass.test_list\n\n unless line_numbers.empty?\n list.select! do |method_name|\n line_numbers.include?(klass.instance_method(method_name).source_location.last.to_s)\n end\n end\n\n list.map! { |method| [klass, method] }.shuffle!\n end\n end", "def spike_query_test\n PipeProc.new do |coll|\n BaseSpike.descendants.map do |klass|\n [klass, klass.tests]\n end\n end\nend", "def test_method_features\n @providers = {:numbers => @features[:numeric], :letters => @features[:alpha]}\n @providers[:both] = @features[:numeric] + @features[:alpha]\n @providers[:mixed] = [:one, :b]\n @providers[:neither] = [:something, :else]\n\n @providers.each do |name, methods|\n assert_nothing_raised(\"Could not create provider #{name}\") do\n @type.provide(name) do\n methods.each do |name|\n define_method(name) {}\n end\n end\n end\n end\n\n resource = @type.new(:name => \"foo\")\n {:numbers => [:numeric], :letters => [:alpha], :both => [:numeric, :alpha], :mixed => [], :neither => []}.each do |name, should|\n should.sort! { |a,b| a.to_s <=> b.to_s }\n provider = @type.provider(name)\n assert(provider, \"Could not find provider #{name}\")\n assert_equal(should, provider.features, \"Provider #{name} has incorrect features\")\n\n inst = provider.new(resource)\n # Make sure the boolean methods work on both the provider and\n # instance.\n @features.keys.each do |feature|\n method = feature.to_s + \"?\"\n assert(inst.respond_to?(method), \"No boolean instance method for #{name} on #{feature}\")\n assert(provider.respond_to?(method), \"No boolean class method for #{name} on #{feature}\")\n\n if should.include?(feature)\n assert(provider.feature?(feature), \"class missing feature? #{feature}\")\n assert(inst.feature?(feature), \"instance missing feature? #{feature}\")\n assert(provider.send(method), \"class missing feature #{feature}\")\n assert(inst.send(method), \"instance missing feature #{feature}\")\n assert(inst.satisfies?(feature), \"instance.satisfy #{feature} returned false\")\n else\n assert(! provider.feature?(feature), \"class has feature? #{feature}\")\n assert(! inst.feature?(feature), \"instance has feature? #{feature}\")\n assert(! provider.send(method), \"class has feature #{feature}\")\n assert(! inst.send(method), \"instance has feature #{feature}\")\n assert(! inst.satisfies?(feature), \"instance.satisfy #{feature} returned true\")\n end\n end\n\n end\n\n Puppet[:trace] = true\n Puppet::Type.loadall\n Puppet::Type.eachtype do |type|\n assert(type.respond_to?(:feature), \"No features method defined for #{type.name}\")\n end\n end", "def my_tests\n end", "def verify_methods(test_data)\n test_methods = test_data[UseOfCollections::METHOD_LIST.name]\n test_methods = [{ UseOfCollections::METHOD.name => ''}] unless test_methods\n test_methods.each_with_index { |test_method, index| verify_values_match(test_method[UseOfCollections::METHOD.name], element_value(method_input index)) }\n end", "def it desc = \"anonymous\", &block\n block ||= proc { skip \"(no tests defined)\" }\n\n @specs ||= 0\n @specs += 1\n\n name = \"test_%04d_%s\" % [ @specs, desc ]\n\n undef_klasses = self.children.reject { |c| c.public_method_defined? name }\n\n define_method name, &block\n\n undef_klasses.each do |undef_klass|\n undef_klass.send :undef_method, name\n end\n\n name\n end", "def make_assertions_on_tests( tests, method )\n assert_equal false, tests[:bad].__send__( method )\n assert_equal true, tests[:good].__send__( method )\n assert_equal true, tests[:extra_good].__send__( method )\n end", "def test_setup\r\n \r\n end", "def suite_classes\n suite_names.map(&:safe_constantize).compact\n end", "def test desc, &block\n self.setup {}\n desc = Testing::Functions.make_constantizeable(desc)\n if block_given?\n test = \"test_#{desc.gsub(/\\W+/, '_').downcase}\"\n define_method(test, &lambda {$current_spec = self; instance_eval(&block)})\n (@@_tests ||= []) << test.to_sym\n (@own_tests ||= []) << test.to_sym\n end\n self.teardown {}\n end", "def initTestDetails\n @Type = nil\n @ProductID = nil\n @ToolID = nil\n @ScriptID = nil\n @TestName = 'unknown'\n @InstallTest = nil\n\n # Get the ID of the test, based on its class name\n lClassName = self.class.name\n if (lClassName.match(/^WEACE::Test::Install::.*$/) != nil)\n @InstallTest = true\n if (lClassName.match(/^WEACE::Test::Install::Master::.*$/) != nil)\n @Type = 'Master'\n else\n @Type = 'Slave'\n end\n lMatchData = lClassName.match(/^WEACE::Test::Install::Slave::Adapters::(.*)::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Adapters::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Adapters::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Listeners::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Providers::(.*)$/)\n if (lMatchData == nil)\n log_debug \"Unable to parse test case name: #{lClassName}.\"\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID, @ToolID = lMatchData[1..2]\n end\n else\n @ProductID, @ToolID, @ScriptID = lMatchData[1..3]\n end\n else\n @InstallTest = false\n if (lClassName.match(/^WEACE::Test::Master::.*$/) != nil)\n @Type = 'Master'\n else\n @Type = 'Slave'\n end\n lMatchData = lClassName.match(/^WEACE::Test::Slave::Adapters::(.*)::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Adapters::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Adapters::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Listeners::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Providers::(.*)$/)\n if (lMatchData == nil)\n log_debug \"Unable to parse test case name: #{lClassName}.\"\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID, @ToolID = lMatchData[1..2]\n end\n else\n @ProductID, @ToolID, @ScriptID = lMatchData[1..3]\n end\n end\n end", "def test_methods(patterns=[])\n return @test_methods if !@test_methods.nil?\n\n @test_methods = create.public_methods.find_all { |m|\n m.to_s =~ /^test_/\n }\n\n if !(patterns.nil? or patterns.empty?) then\n # filter\n @test_methods.reject!{ |m|\n patterns.find{ |t| m.to_s.include?(t.to_s) }.nil?\n }\n end\n\n @test_methods\n end", "def help options = { :pattern => /.*/, :target => nil}\n puts \"Global helper methods (available on all services): \"\n puts JavaHelpers.format_help_line 'boolean', 'allow_colors', 'true|false', \"Turn coloring on/off\"\n puts JavaHelpers.format_help_line 'EzSecurityToken', 'fake_token', '[auths=TS,S,U]', 'Return a fake security token.'\n puts JavaHelpers.format_help_line 'Visibility', 'fake_vis', 'String - visibility', 'Return a fake Visibility constructed from the given string.'\n puts JavaHelpers.format_help_line 'void', 'write', 'Filename, Stuff to write', 'Write content to a file.'\n puts JavaHelpers.format_help_line 'Set', 'set_of', 'Comma-separated items', 'Get a Java Set of items.'\n puts JavaHelpers.format_help_line 'List', 'list_of', 'Comma-separated items', 'Get a Java List of items.'\n puts \"\\n\"\n\n options[:target] = @artifact_obj.java_class if options[:target].nil?\n actual_methods = JavaHelpers.method_help options[:target], options[:pattern]\n if actual_methods.any?\n puts \"Available methods on #{options[:target]} are:\\n#{actual_methods.join(\"\\n\")}\"\n else\n puts \"No service methods found that match /#{pattern}/!\"\n end\n if @artifact_module.respond_to?(:method_help)\n puts \"\\nCLI Helpers: \"\n puts @artifact_module.method_help.join(\"\\n\")\n end\nend", "def get_test_names\n if defined?(MiniTest::Unit::TestCase) && self.ancestors.include?(MiniTest::Unit::TestCase)\n self.test_methods\n else\n self.suite.tests.map {|t| t.method_name}\n end\n end", "def build_tests_list\n if ! @test_list.nil?\n return @test_list\n end\n @test_list = []\n Find.find(@ruby_tests_location) do |path|\n if FileTest.directory?(path)\n if File.basename(path)[0] == \".\"\n Find.prune # ignore . .. and .svn\n else\n next\n end\n elsif File.extname(path) == \".test\"\n puts \"Processing: \" + path\n @test_list << path\n end\n end\n\n if @test_list.size == 0\n raise MissingRubyTestFiles, \"Can't find any rubySelenium tests in directory #{@ruby_tests_location}\"\n else\n return @test_list.sort!\n end\n end", "def run_specific(check_class_names)\n load_dsl_if_available\n\n run_check_classes(check_classes_named(check_class_names))\n end", "def make_test impl_mod, test_mod\n test_unit = <<-STRING\n module Test#{test_mod}\n include #{impl_mod}\n end\n class #{impl_mod}#{test_mod} < Test::Unit::TestCase\n include Test#{test_mod}\n end\n STRING\n eval test_unit\nend", "def pytest_generate_tests(metafunc)\n if Set.new([test_rh_updates, test_rhsm_registration_check_repo_names]).include?(metafunc.function)\n return\n end\n # Generates tests specific to RHSM or SAT6 with proxy-on or off \n argnames = [\"reg_method\", \"reg_data\", \"proxy_url\", \"proxy_creds\"]\n argvalues = []\n idlist = []\n begin\n holder = metafunc.config.pluginmanager.get_plugin(\"appliance-holder\")\n stream = holder.held_appliance.version.stream()\n all_reg_data = conf.cfme_data.get(\"redhat_updates\", {})[\"streams\"][stream]\n rescue KeyError\n logger.warning(\"Could not find rhsm data for stream in yaml\")\n metafunc.parametrize(argnames, [pytest.param(nil, nil, nil, nil, marks: pytest.mark.skip(\"Could not find rhsm data for stream in yaml\"))])\n return\n end\n if metafunc.fixturenames.include?(\"reg_method\")\n for reg_method in REG_METHODS\n reg_data = all_reg_data.get(reg_method)\n if is_bool(!reg_data || !reg_data.get(\"test_registration\", false))\n next\n end\n proxy_data = conf.cfme_data.get(\"redhat_updates\", {}).get(\"http_proxy\", false)\n if is_bool(proxy_data && reg_data.get(\"use_http_proxy\", false))\n proxy_url = proxy_data[\"url\"]\n proxy_creds_key = proxy_data[\"credentials\"]\n proxy_creds = conf.credentials[proxy_creds_key]\n argval = [reg_method, reg_data, proxy_url, proxy_creds]\n argid = (\"{}-{}\").format(reg_method, \"proxy_on\")\n idlist.push(argid)\n argvalues.push(argval)\n end\n argval = [reg_method, reg_data, nil, nil]\n argid = (\"{}-{}\").format(reg_method, \"proxy_off\")\n idlist.push(argid)\n argvalues.push(argval)\n end\n return metafunc.parametrize(argnames, argvalues, ids: idlist, scope: \"function\")\n end\nend", "def verify_methods(test_data)\n test_methods = test_data[CoreUseOfCollectionsData::METHOD_LIST.name]\n test_methods = [{CoreUseOfCollectionsData::METHOD.name => ''}] unless test_methods\n test_methods.each_with_index { |test_method, index| verify_values_match(test_method[CoreUseOfCollectionsData::METHOD.name], element_value(method_input index)) }\n end", "def methods_available_to_script\n [ 'program', 'version', 'updated, :maintainer',\n 'build_size', 'noarch', 'system_files',\n 'resource.categories', 'resource.dependencies', 'resource.conflicts',\n 'resource.compliment', 'resource.supplement' \n ].collect { |m| \"#{m}\" }\n end", "def test_get_class\n assert_equal Test::Unit::TestCase,\n OneLiner.get_class(\"Test::Unit::TestCase\")\n end", "def test_only_adds_methods_to_host_that_are_part_of_public_api\n host_class = Class.new { include ::NewRelic::Agent::MethodTracer }\n plain_class = Class.new\n\n host_instance_methods = host_class.new.methods\n plain_instance_methods = plain_class.new.methods\n\n added_methods = host_instance_methods - plain_instance_methods\n\n public_api_methods = %w[\n trace_execution_unscoped\n trace_execution_scoped\n ]\n\n assert_equal(public_api_methods.sort, added_methods.map(&:to_s).sort)\n end", "def build_Method_List(fpath_in, fpath_Out = nil)\r\n \r\n #########################\r\n # build: out path\r\n #########################\r\n if fpath_Out == nil\r\n\r\n # use => fpath_in string\r\n fpath_Out = fpath_in + \".METHODS\"\r\n \r\n end#if fpath_Out == nil\r\n\r\n #########################\r\n # build: methods list\r\n #########################\r\n # open file\r\n f_in = File.open(fpath_in, \"r\")\r\n \r\n #REF gets http://www.abbeyworkshop.com/howto/ruby/rb-readfile/index.html\r\n line = f_in.gets\r\n\r\n # pattern (if multiple, add 'm' after the right hand of '/' char)\r\n # what to detect => 1) method name, 2) parameters \r\n #REF multiple http://stackoverflow.com/questions/5239997/regex-how-to-match-multiple-lines answered Mar 9 '11 at 0:36\r\n pattern = /void (.+)(\\(.*\\)) {/\r\n\r\n # array for method strings \r\n methods = Array.new\r\n \r\n # read lines\r\n while(line)\r\n \r\n res = (line=~ pattern)\r\n \r\n match = line.match pattern\r\n \r\n # match?\r\n if match\r\n\r\n # push matched strings into the array \r\n methods << match[1] + \"\\t\" + match[2]\r\n# methods << match[1] + match[2]\r\n \r\n end\r\n \r\n # next line\r\n #REF gets http://www.abbeyworkshop.com/howto/ruby/rb-readfile/index.html\r\n line = f_in.gets\r\n \r\n end#while(line)\r\n \r\n #########################\r\n # close files: input file\r\n #########################\r\n f_in.close\r\n \r\n #########################\r\n # write: output\r\n #########################\r\n # open file\r\n f_Out = File.open(fpath_Out, \"w\")\r\n\r\n # sort: use '!' for destructive effect\r\n methods.sort!\r\n \r\n # counter\r\n counter = 0\r\n \r\n # write each method string (with a new-line char '\\n')\r\n methods.each_with_index do |m, i|\r\n \r\n f_Out.write(\"#{i + 1}.\\t#{m}\" + \"\\n\")\r\n# f_Out.write(m + \"\\n\")\r\n \r\n counter = counter + 1\r\n \r\n end\r\n \r\n #########################\r\n # close files: input file\r\n #########################\r\n f_Out.close\r\n \r\n #########################\r\n # return\r\n #########################\r\n return counter\r\n \r\nend", "def test_cases; end", "def get_class_descriptions(klass)\n available_versions.map do |version|\n get_class_description(klass, version)\n end.compact\n end", "def test_case; end", "def define_test_tasks\n default_tasks = []\n\n task :test\n\n if File.directory? \"test\" then\n case testlib\n when :minitest then\n require \"minitest/test_task\" # in minitest 5.16+\n\n test_prelude = self.test_prelude\n self.test_task = Minitest::TestTask.create :test do |t|\n t.test_prelude = test_prelude\n t.libs.prepend Hoe.include_dirs.uniq\n end\n when :none then\n # do nothing\n else\n warn \"Unsupported? Moving to Minitest::TestTask. Let me know if you use this!\"\n end\n\n desc \"Run the test suite using multiruby.\"\n task :multi do\n skip = with_config do |config, _|\n config[\"multiruby_skip\"] + self.multiruby_skip\n end\n\n ENV[\"EXCLUDED_VERSIONS\"] = skip.join(\":\")\n system \"multiruby -S rake\"\n end\n\n default_tasks << :test\n end\n\n desc \"Run the default task(s).\"\n task :default => default_tasks\n\n desc \"Run ZenTest against the package.\"\n task :audit do\n libs = %w[lib test ext].join(File::PATH_SEPARATOR)\n sh \"zentest -I=#{libs} #{spec.files.grep(/^(lib|test)/).join(\" \")}\"\n end\n end", "def test_order; end", "def test_code(flight_planner_instance)\n planner = flight_planner_instance\n tests = [\n [:can_i_fly?, [\"MIA\", \"JFK\"], true],\n [:can_i_fly?, [\"MIA\", \"ORD\"], false],\n [:can_i_fly?, [\"MIA\", \"XXX\"], false]\n]\n puts \"All tests passing? Yes!\" if tests.all? {|t| planner.send(t[0], *t[1]) == t[2]}\n #the 'send' method calls the method on the flight planner instance at the first index of tests array\n #with the arguments at the second index of tests, and checks if it's true to the third index\n\n failed_tests = tests.reject {|t| planner.send(t[0], *t[1]) == t[2]}\n response = \"All tests passing? No...\\n\"\n response << \"tests fail for: #{failed_tests.map{|t| t[1]}}\"\n puts response if failed_tests != []\n \nend", "def initialize(suite, opts=nil)\n @suite = suite\n @inits = []\n @options = opts || {}\n @count = @options[:count] || Hash.new(0)\n @provided = [] # Array's set operations are the fastest\n @include_tags = @options[:include_tags] # nil is ok here\n @exclude_tags = @options[:exclude_tags] # nil is ok here\n include_states = @options[:include_states] # nil is ok here\n exclude_states = @options[:exclude_states] # nil is ok here\n @states = [nil, *BareTest::StatusOrder]\n @skipped = {}\n @last_run_states = {}\n @persistence = @options[:persistence]\n\n if (include_states || exclude_states) && !((include_states && include_states.empty?) && (exclude_states && exclude_states.empty?)) then\n [include_states, exclude_states].compact.each do |states|\n states << nil if states.include?(:new)\n states.push(:error, :skipped, :pending) if states.include?(:failure)\n states.delete(:new)\n if states.include?(:skipped) then\n states.delete(:skipped)\n states.push(:pending, :manually_skipped, :dependency_missing, :library_missing, :component_missing)\n end\n states.uniq!\n end\n @states = (include_states || @states) - (exclude_states || [])\n end\n\n (BareTest.extender+Array(@options[:extender])).each do |extender|\n extend(extender)\n end\n\n # Extend with the output formatter\n format = @options[:format]\n if format.is_a?(String) then\n require \"baretest/run/#{format}\"\n extend(BareTest.format[\"baretest/run/#{format}\"])\n elsif format.is_a?(Module) then\n extend(format)\n end\n\n # Extend with irb dropout code\n extend(BareTest::IRBMode) if @options[:interactive]\n\n # Initialize extenders\n @inits.each { |init| instance_eval(&init) }\n end", "def running_test_case; end", "def default_test; end", "def get_test_fns\n fns = {}\n basename = File.basename(@parts[:fn], @parts[:ext]) + Cpp::get_source_ext(@parts[:ext])\n ['src', 'inc'].each do |type|\n fns[type] = File.join(@parts[:base_dir],\n @parts[:module],\n 'test',\n type,\n @parts[:namespaces],\n basename)\n end\n fns\n end", "def test_required_class_constants\n @cmds.each do |cmd_name, cmd|\n if cmd.is_a?(Trepan::SubcommandMgr)\n cmd.subcmds.subcmds.each do |subcmd_name, subcmd|\n where = \"of subcommand #{subcmd_name} in command #{cmd_name}\"\n %w(HELP NAME SHORT_HELP).each do\n |const|\n value = subcmd.my_const(const)\n assert_equal(true, value.is_a?(String),\n \"#{const} #{where} should be a String; got #{value}.\")\n end\n value = subcmd.my_const('MIN_ABBREV')\n assert(value.is_a?(Fixnum),\n \"MIN_ABBREV #{where} should be a Fixnum; got #{value}.\")\n\n if 'show' == cmd_name\n short_help = subcmd.my_const('SHORT_HELP')\n needed_start = 'Show '\n assert_equal(needed_start, short_help[0..needed_start.size-1],\n \"Short help #{where} should start: \\\"#{needed_start}\\\"; got #{short_help}\")\n end\n end\n end\n end\n end", "def test_method_parts\n value_ = ::Versionomy.create([1, 9, 2, 'a', 2], :rubygems)\n assert_equal([1, 9, 2, 'a', 2], value_.parts)\n value_ = ::Versionomy.create([1, 9, 0], :rubygems)\n assert_equal([1, 9], value_.parts)\n end", "def functionals_changed_tests(test_changed_files, t)\n test_changed_files = test_changed_files.split(\"\\n\") if test_changed_files.is_a?(String)\n test_files = FileList['test/functional/**/*_test.rb'].select{|file| test_changed_files.any?{|changed_file| file==changed_file }}\n test_files = test_files.uniq\n test_files = test_files.reject{ |f| Smokescreen.critical_tests.include?(f) }\n\n t.libs << \"test\"\n t.verbose = true\n if !test_files.empty?\n t.test_files = test_files\n else\n t.test_files = []\n end\n end", "def tests=(_arg0); end", "def tests=(_arg0); end", "def defclassmatch(method,*args,&block)\n @defclassmatch_dispatch_info ||= {} # setup the methods in an instance variable\n @defclassmatch_dispatch_info[method] ||= [] # setup the ordered array for the method the first time\n @defclassmatch_dispatch_info[method] << {:test => Defmatch.signiture_match(method,args), :block => block} # add the hash for the test proc and the run proc (block given) to the list of matchers\n\n # define dispatch method the first time\n unless respond_to?(method)\n eigenclass = class << self; self; end\n eigenclass.instance_eval do\n define_method(method) do |*args|\n self.instance_variable_get(:@defclassmatch_dispatch_info)[method].each do |hash|\n if hash[:test].call(*args)\n return self.instance_exec(*args,&hash[:block])\n end\n end\n raise ArgumentError, \"No function clause matching arguments\"\n end\n end\n end\n end", "def parse_respec_tests_list(str, opts)\n str = str.strip\n if RESPECTESTS_ANNOTATIONS.include?(str)\n opts['class'] = \"#{str}\"\n else\n opts['data-tests'] = \"#{str}\"\n end\n end", "def check_class\n @check_class ||= begin\n c = ObjectSpace.each_object(Class).find do |klass|\n klass < Sensu::Plugin::Check::CLI && \\\n klass != self.class && \\\n !klass.ancestors.include?(self.class)\n end\n patch_class!(c)\n c\n end\n end", "def test_case(target, &block)\n case target\n when Class\n $TEST_SUITE << Lemon::TestClass.new(:target=>target, &block)\n when Module\n $TEST_SUITE << Lemon::TestModule.new(:target=>target, &block)\n else\n if defined?(super)\n super(target, &block)\n else\n raise\n end\n end\n end", "def test_uplink_class2\n start(\"tests/verify_uplink_class2.rb\")\n end", "def compare_tests(test_a, test_b); end", "def compare_tests(test_a, test_b); end", "def test_Method_InstanceMethods_to_proc\n\t\tpass\n\tend", "def test_set_method_types\n end", "def run\n test_files.each do |file|\n eval File.read(file)\n end\n\n results = []\n @tests.each_pair do |name, test|\n results << test.call(@config)\n end\n results.reject!(&:nil?)\n results.reject!(&:empty?)\n results.flatten!\n results\n end", "def test_downlink_class1\n # Test Class 2 downlink capabilities\n start(\"tests/verify_downlink_class1.rb\")\n end", "def define_helpers(list)\n list.each do |method_name, method_info|\n # puts \"define #{method_name}\"\n params = parse_param(method_info[\"params\"])\n if method_name[0] == \".\"\n class_eval %(\n private def #{method_name[1..-1]} (params = { #{params} })\n request(\"#{method_name}\", params)\n end\n ), __FILE__, __LINE__ - 4\n else\n class_eval %(\n def #{method_name} (params = { #{params} })\n request(\"#{method_name}\", params)\n end\n ), __FILE__, __LINE__ - 4\n end\n end\n end", "def new\n @smoke_test = SmokeTest.new\n # package builders\n @smoke_test.build_nova_package_builder\n @smoke_test.nova_package_builder.merge_trunk = false\n @smoke_test.build_glance_package_builder\n @smoke_test.glance_package_builder.merge_trunk = false\n @smoke_test.build_keystone_package_builder\n @smoke_test.keystone_package_builder.merge_trunk = false\n @smoke_test.build_swift_package_builder\n @smoke_test.swift_package_builder.merge_trunk = false\n @smoke_test.build_cinder_package_builder\n @smoke_test.cinder_package_builder.merge_trunk = false\n @smoke_test.build_neutron_package_builder\n @smoke_test.neutron_package_builder.merge_trunk = false\n @smoke_test.build_ceilometer_package_builder\n @smoke_test.ceilometer_package_builder.merge_trunk = false\n @smoke_test.build_heat_package_builder\n @smoke_test.heat_package_builder.merge_trunk = false\n\n # config modules\n @smoke_test.build_nova_config_module\n @smoke_test.nova_config_module.merge_trunk = false\n @smoke_test.build_glance_config_module\n @smoke_test.glance_config_module.merge_trunk = false\n @smoke_test.build_keystone_config_module\n @smoke_test.keystone_config_module.merge_trunk = false\n @smoke_test.build_swift_config_module\n @smoke_test.swift_config_module.merge_trunk = false\n @smoke_test.build_cinder_config_module\n @smoke_test.cinder_config_module.merge_trunk = false\n @smoke_test.build_neutron_config_module\n @smoke_test.neutron_config_module.merge_trunk = false\n @smoke_test.build_ceilometer_config_module\n @smoke_test.ceilometer_config_module.merge_trunk = false\n @smoke_test.build_heat_config_module\n @smoke_test.heat_config_module.merge_trunk = false\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @smoke_test }\n format.xml { render :xml => @smoke_test }\n end\n end", "def generate_alltest\n\n end", "def test_get_class\n assert_equal Test::Unit::TestCase,\n OneLiner.get_class(\"Test::Unit::TestCase\")\n end", "def build_test\n \n return if skip_method(__method__)\n \n build_test_fixtures\n build_test_helper\n build_functional_test\n build_integration_test\n build_unit_test\n end", "def default_test\r\n end", "def action_run\n notifying_block do\n # Top level directory for this test.\n directory new_resource.path do\n mode '777'\n end\n\n # Install and log the version.\n python_runtime new_resource.name do\n provider new_resource.runtime_provider if new_resource.runtime_provider\n version new_resource.version\n end\n test_version\n\n # Test python_package.\n python_package 'argparse' do\n # Needed for sqlparse but not in the stdlib until 2.7.\n python new_resource.name\n end\n python_package 'sqlparse remove before' do\n action :remove\n package_name 'sqlparse'\n python new_resource.name\n end\n test_import('sqlparse', 'sqlparse_before')\n python_package 'sqlparse' do\n python new_resource.name\n notifies :create, sentinel_file('sqlparse'), :immediately\n end\n test_import('sqlparse', 'sqlparse_mid')\n python_package 'sqlparse again' do\n package_name 'sqlparse'\n python new_resource.name\n notifies :create, sentinel_file('sqlparse2'), :immediately\n end\n python_package 'sqlparse remove after' do\n action :remove\n package_name 'sqlparse'\n python new_resource.name\n end\n test_import('sqlparse', 'sqlparse_after')\n\n # Use setuptools to test something that should always be installed.\n python_package 'setuptools' do\n python new_resource.name\n notifies :create, sentinel_file('setuptools'), :immediately\n end\n\n # Multi-package install.\n python_package ['pep8', 'pytz'] do\n python new_resource.name\n end\n test_import('pep8')\n test_import('pytz')\n\n # Create a virtualenv.\n python_virtualenv ::File.join(new_resource.path, 'venv') do\n python new_resource.name\n end\n\n # Install a package inside a virtualenv.\n python_package 'Pytest' do\n virtualenv ::File.join(new_resource.path, 'venv')\n end\n test_import('pytest')\n test_import('pytest', 'pytest_venv', python: nil, virtualenv: ::File.join(new_resource.path, 'venv'))\n\n # Create and install a requirements file.\n # Running this in a venv because of pip 8.0 and Ubuntu packaing\n # both requests and six.\n python_virtualenv ::File.join(new_resource.path, 'venv2') do\n python new_resource.name\n end\n file ::File.join(new_resource.path, 'requirements.txt') do\n content <<-EOH\nrequests==2.7.0\nsix==1.8.0\nEOH\n end\n pip_requirements ::File.join(new_resource.path, 'requirements.txt') do\n virtualenv ::File.join(new_resource.path, 'venv2')\n end\n test_import('requests', python: nil, virtualenv: ::File.join(new_resource.path, 'venv2'))\n test_import('six', python: nil, virtualenv: ::File.join(new_resource.path, 'venv2'))\n\n # Install a non-latest version of a package.\n python_virtualenv ::File.join(new_resource.path, 'venv3') do\n python new_resource.name\n end\n python_package 'requests' do\n version '2.8.0'\n virtualenv ::File.join(new_resource.path, 'venv3')\n end\n test_import('requests', 'requests_version', python: nil, virtualenv: ::File.join(new_resource.path, 'venv3'))\n\n # Don't run the user tests on Windows.\n unless node.platform_family?('windows')\n # Create a non-root user and test installing with it.\n test_user = \"py#{new_resource.name}\"\n test_home = ::File.join('', 'home', test_user)\n group 'g'+test_user do\n system true\n end\n user test_user do\n comment \"Test user for python_runtime_test #{new_resource.name}\"\n gid 'g'+test_user\n home test_home\n shell '/bin/false'\n system true\n end\n directory test_home do\n mode '700'\n group 'g'+test_user\n user test_user\n end\n test_venv = python_virtualenv ::File.join(test_home, 'env') do\n python new_resource.name\n user test_user\n end\n python_package 'docopt' do\n user test_user\n virtualenv test_venv\n end\n test_import('docopt', python: nil, virtualenv: test_venv, user: test_user)\n end\n\n end\n end", "def tests\n @tests ||= @spec['tests'].collect do |test|\n Test.new(@data, test)\n end\n end", "def suite_test_names suite_class\n s = /^#{suite_class.name}#/\n test_names.select {|tn| tn.match(s) }.map{|tn| tn.split('#',2).last }.uniq\n end", "def run(files)\n file = files.first\n puts \"** Running #{file}\"\n \n class_filename = file.sub(self.class::CLASS_MAP, '')\n \n # get the class\n test_class = resolve_classname(class_filename)\n \n # create dummy wrapper modules if test is in subfolder\n test_class.split('::').each do |part|\n eval \"module ::#{part}; end\" if !part.match('Test')\n end\n \n begin \n clear_class(test_class.constantize) \n rescue NameError \n \n end\n \n # TODO: make this reload use load_file\n $\".delete(file)\n \n begin\n require file\n rescue LoadError\n notifier.error(\"Error in #{file}\", $!)\n puts $!\n return\n rescue ArgumentError\n notifier.error(\"Error in #{file}\", $!)\n puts $!\n return\n rescue SyntaxError\n notifier.error(\"Error in #{file}\", $!)\n puts $!\n return\n end\n \n # TODO: change that to run multiple suites\n #klass = Kernel.const_get(test_class) - this threw errors\n klass = eval(test_class)\n \n Test::Unit::UI::Console::TestRunner.run(klass)\n Test::Unit.run = false\n \n # Invoke method to test that writes to stdout.\n result = test_io.string.to_s.dup\n\n # clear the buffer \n test_io.truncate(0)\n \n # sent result to notifier\n notifier.result(file, result.split(\"\\n\").compact.last)\n\n # sent result to stdio\n puts result\n \n end", "def _test_numbers ; process_test_case(\"numbers\") ; end", "def load_test(tc)\n data = Hash.new\n File.open(tc, \"r\") do |infile|\n while (line = infile.gets)\n #test = /^.*\\/(.*\\.rb)/.match(tc)[1]\n test = /^.*\\/([A-Za-z0-9_-]*[T|t]est.*)/.match(tc)[1]\n data['execute_class'] = /^([A-Za-z0-9_-]*[T|t]est.*)/.match(tc)[1]\n data['path'] = /(.*)\\/#{test}/.match(tc)[1]\n data['execute_args'] = /^#[\\s]*@executeArgs[\\s]*(.*)/.match(line)[1] if /^#[\\s]*@executeArgs/.match(line)\n data['author'] = /^#[\\s]*@author[\\s]*(.*)/.match(line)[1] if /^#[\\s]*@author/.match(line)\n data['keywords'] = /^#[\\s]*@keywords[\\s]*(.*)/.match(line)[1].gsub(/,/,'').split if /^#[\\s]*@keywords/.match(line)\n data['description'] = /^#[\\s]*@description[\\s]*(.*)/.match(line)[1] if /^#[\\s]*@description/.match(line)\n end\n end\n @tests << Test.new(data, @test_data) if data['keywords'] != nil and data['keywords'] != \"\"\nend", "def run_one_method(klass, method_name, reporter); end", "def import test_cases\n raise TypeError, \"File list must be an Array, got #{test_cases.class}\" unless test_cases.is_a? Array\n test_cases.each do |test_case|\n puts \"%20s : %s\" % ['Adding ' + self.class.type, test_case] if RubyUnit.debug\n require test_case\n end\n end", "def run_namelist_tests(namelist, hash, enum = nil)\n ext = enum ? \"_#{enum}\" : \"\"\n hash[:must_pass].each do |tst|\n error(namelist_test_failed(namelist, tst)) unless instance_eval(tst[:test])\n end if hash[:must_pass]\n hash[:should_pass].each do |tst|\n warning(namelist_test_failed(namelist, tst)) unless instance_eval(tst[:test])\n end if hash[:should_pass]\n hash[:variables].each do |var, var_hash|\n #gs2_var = (var_hash[:gs2_name] or var)\n cr_var = var+ext.to_sym\n value = send(cr_var)\n if value.kind_of? Array\n value.each{|v| test_variable(namelist, var, var_hash, ext, v)}\n else\n test_variable(namelist, var, var_hash, ext, value)\n end\n end\nend", "def units_changed_tests(test_changed_files, t)\n test_changed_files = test_changed_files.split(\"\\n\") if test_changed_files.is_a?(String)\n test_files = FileList['test/unit/*_test.rb'].select{|file| test_changed_files.any?{|changed_file| file==changed_file }}\n test_files = test_files.uniq\n\n t.libs << \"test\"\n t.verbose = true\n if !test_files.empty?\n t.test_files = test_files\n else\n t.test_files = []\n end\n end", "def define_checkers(name) # rubocop:disable Metrics/MethodLength, Metric/AbcSize\n define_method(\"#uncheck_#{name}_checkbox\") do\n @browser.send :uncheck, @browser.find(selector)[:id]\n end\n\n define_method(\"check_#{name}_checkbox\") do\n @browser.send :check, @browser.find(selector)[:id]\n end\n\n define_method(\"#uncheck_#{name}\") do\n @browser.send :uncheck, @browser.find(selector)[:id]\n end\n\n define_method(\"check_#{name}\") do\n @browser.send :check, @browser.find(selector)[:id]\n end\n end", "def suites\n # Since we're not using `ruby -Itest -Ilib` to run the tests, we need to add this directory to the `LOAD_PATH`\n $LOAD_PATH.unshift \"./test\", \"./spec\", \"./lib\"\n\n begin\n # Fire up this Ruby file. Let's hope it actually has tests.\n require \"./#{testable.file}\"\n rescue LoadError => e\n # Fail with a happier error message instead of spitting out a backtrace from this gem\n warn \"Failed loading test file:\\n#{e.message}\"\n return []\n end\n\n suites = runner.suites\n\n # Use some janky internal APIs to group test methods by test suite.\n suites.each_with_object({}) do |suite_class, test_suites|\n # End up with a hash of suite class name to an array of test methods, so we can later find them and ignore empty test suites\n test_suites[suite_class] = runner.test_methods(suite_class) if runner.test_methods(suite_class).any?\n end\n end", "def summarize_suite(suite, tests); end", "def summarize_suite(suite, tests); end", "def process(files) #called at end of script\n if files.class==Array \n files.each {|f| \n puts \"\\n\\n--------------------\\n#{f}:\\n\\n\"\n result=system(\"#{$PROGRAM_NAME} #{f} #{ARGV}\")\n puts \"\\n\\nERRORS IN TEST #{f}!!!\\n\\n\" unless result\n }\n else\n test_name=File.basename(files).sub(/\\..*?$/,'')\n test_case=Class.new(Test::Unit::TestCase)\n Object.const_set(:\"Test#{test_name.capitalize}\", test_case)\n mk_test_context(files, test_case)\n end\nend", "def spec_tests(&block)\n require 'onceover/testconfig'\n\n # Load up all of the tests and deduplicate them\n testconfig = Onceover::TestConfig.new(@onceover_yaml, @opts)\n testconfig.spec_tests.each { |tst| testconfig.verify_spec_test(self, tst) }\n tests = testconfig.run_filters(Onceover::Test.deduplicate(testconfig.spec_tests))\n\n # Loop over each test, executing the user's block on each\n tests.each do |tst|\n block.call(tst.classes[0].name, tst.nodes[0].name, tst.nodes[0].fact_set, tst.nodes[0].trusted_set, tst.nodes[0].trusted_external_set, testconfig.pre_condition)\n end\n end", "def test_add_class\n\t\t@new_driver.class 1\n\t\t@new_driver.class 1\n\t\tassert_equal 4, @new_driver.class(1)\n\tend", "def run(*args) #:nodoc:\n return if @method_name == \"default_test\"\n super\n end" ]
[ "0.79935706", "0.6560548", "0.6069621", "0.59919196", "0.5881773", "0.5833435", "0.57638437", "0.5743722", "0.57084703", "0.5570949", "0.5548126", "0.5516116", "0.5516116", "0.5495896", "0.54355466", "0.54307795", "0.54260075", "0.54138124", "0.5409251", "0.53974664", "0.5383305", "0.53775287", "0.5362509", "0.5360846", "0.53358954", "0.53357685", "0.53355145", "0.53239465", "0.53000194", "0.5282014", "0.5266899", "0.52603704", "0.52574486", "0.5246745", "0.52249694", "0.52178216", "0.5197569", "0.51885206", "0.5186521", "0.517679", "0.5173015", "0.5155594", "0.51546437", "0.5154352", "0.5153922", "0.5149902", "0.5149314", "0.5144907", "0.5144104", "0.51380336", "0.5134031", "0.5127886", "0.51228607", "0.5112339", "0.5100364", "0.50996035", "0.509212", "0.5081248", "0.50797135", "0.507133", "0.5069953", "0.5069525", "0.50590336", "0.5055426", "0.5055426", "0.5041832", "0.5033459", "0.50198406", "0.50194", "0.5001966", "0.50006247", "0.50006247", "0.49999416", "0.49884456", "0.49883842", "0.49864018", "0.49798143", "0.49701715", "0.49688417", "0.49656618", "0.49654013", "0.49559057", "0.4954072", "0.49466965", "0.49464577", "0.4945164", "0.49440673", "0.4941908", "0.49360013", "0.49333715", "0.49319285", "0.49276242", "0.4925769", "0.49176812", "0.49147978", "0.49147978", "0.49139366", "0.49062145", "0.49056834", "0.49040112" ]
0.7360373
1
Added ERB parsing for the config file. Kinda of nice for more dynamic features that could be required.
def deserialize(config) config.present? ? YAML.safe_load(ERB.new(config).result, [], [], false, content_path) : {} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_config_for apps\n\t\t\t\tr = ERB.new(erb_template).\n\t\t\t\t\tresult(erb_template_binding(apps, Nacreon::Config.domain,\n\t\t\t\t\t Nacreon::Config.nginx_port))\n\t\t\t\t# In case the gsub looks funny, it's there to allow both the\n\t\t\t\t# template and the output at least semi-readable:\n\t\t\t\tr.gsub!(/(\\n\\s+)+\\n/, \"\\n\\n\")\n\t\t\t\tr\n\t\t\tend", "def parse_config \n path = \"#{Rails.root}/config/mebla.yml\"\n return unless File.exists?(path)\n \n conf = YAML::load(ERB.new(IO.read(path)).result)[Rails.env]\n \n conf.each do |key,value|\n self.send(\"#{key}=\", value) if self.respond_to?(\"#{key}=\")\n end unless conf.nil?\n end", "def parse_config(config); end", "def load_erb(erb)\n # @tmpl = ERB.new(erb)\n @tmpl = ERB.new(erb,0,\"<>\")\n end", "def new_config_content\n return <<-VHOST\n\n# vh configuration file\nInclude #{@target}\n# /vh configuration file\n VHOST\n end", "def generate_ironbee_configuration(context, template = nil)\n template ||= DEFAULT_TEMPLATE\n template = expand_path(template)\n CLIPPTest::fatal \"Could not read #{template}\" if ! File.readable?(template)\n\n erb = ERB.new(IO.read(template))\n config = erb.result(context)\n end", "def template_config\n File.read(options['puppet_config_template'])\nend", "def read_config_file; end", "def __in_erb_template;\n end", "def __in_erb_template;\n end", "def default_config_template_string(filepath)\n if filepath\n filepath = filepath.to_s\n if filepath.end_with?('haml')\n Haml::Engine.new(IO.read(filepath)).render\n else\n IO.read(filepath)\n end\n else\n nil\n end\n end", "def import_config()\n # The config is top down.. anything after a [group] gets added as part\n # of that group until a new [group] is found. \n group = nil\n open(self.config_file).each do |line| \n line.strip!\n unless (/^\\#/.match(line))\n if(/\\s*=\\s*/.match(line))\n param, value = line.split(/\\s*=\\s*/, 2) \n var_name = \"#{param}\".chomp.strip\n value = value.chomp.strip\n new_value = ''\n if (value)\n if value =~ /^['\"](.*)['\"]$/\n new_value = $1\n else\n new_value = value\n end\n else\n new_value = ''\n end \n\n if group\n self.add_to_group(group, var_name, new_value)\n else\n self.add(var_name, new_value)\n end\n \n elsif(/^\\[(.+)\\]$/.match(line).to_a != [])\n group = /^\\[(.+)\\]$/.match(line).to_a[1]\n self.add(group, {})\n \n end\n end\n end \n end", "def configure_parser; end", "def erb_render( yml )\n # b = binding\n ERB.new( yml ).result binding \n end", "def config_content(tparam, tvalue)\n fparam = tparam.split('_').map { |e|\n case e\n when 'backuppc'\n 'BackupPC'\n when 'email'\n 'EMail'\n when 'url', 'mmdd'\n e.upcase\n else\n e.capitalize\n end\n }.join\n\n fvalue = case tvalue\n when FalseClass, TrueClass\n tvalue ? 1 : 0\n else\n Regexp.escape(PP.pp(tvalue, '').chomp.tr('\"', \"'\"))\n end\n\n %r{^\\$Conf{#{fparam}}\\s+=\\s+#{fvalue};}m\nend", "def parse_config_file(path)\n return unless File.exists?(path)\n \n conf = YAML::load(ERB.new(IO.read(path)).result)[Rails.env]\n \n conf.each do |key,value|\n self.send(\"#{key}=\", value) if self.respond_to?(\"#{key}=\")\n end unless conf.nil?\n end", "def config_file_contents\n config = Brightbox::BBConfig.new\n File.read(config.config_filename)\n end", "def create_file_config\n # template \"config/express_translate.yml\", \"config/express_translate.yml\"\n end", "def install_config\n template(\"config_template.rb\", \"config/initializers/hes-reports-yaml_config.rb\")\n end", "def app_config_content\n buf = []\n buf << 'class AppConfig'\n buf << \" APP_NAME='#{@project_name.camel_case}'\"\n buf << \" APP_CONTROLLERS=%w(#{@parser.descriptions.collect{|model| model.singularize.snake_case.pluralize}.join(' ')})\"\n buf << 'end'\n buf.join(\"\\n\")\n end", "def read_configuration filename\n puts \"Reading configuration from #{filename}\"\n lines=File.readlines(filename)\n cfg={}\n #change in the dir of the file to calculate paths correctly\n cfg_dir=File.dirname(filename)\n lines.each do |l|\n l.gsub!(\"\\t\",\"\")\n l.chomp!\n #ignore if it starts with a hash\n unless l=~/^#/ || l.empty?\n #clean up by trimming whitespaces\n l.gsub!(/\\s*=\\s*/,'=')\n l.gsub!(/\\s*,\\s*/,',')\n #\n if l=~/=$/\n trailing_equals=true\n end\n #split on equals\n fields=l.split('=')\n #more than one part needed\n if fields.size>1\n #the key is the first\n key=fields.first\n #take the key out of the array\n values=fields.drop(1)\n #the value to each key is the values array joined with space\n case key \n when \"include\",\"depend\",\"interface\",\"external\" \n cfg[key]||=[]\n #here we want to handle a comma separated list of prefixes\n incs=values.join\n cfg[key]+=incs.split(',')\n cfg[key].uniq!\n when \"out_dir\",\"base_dir\",\"model\" \n cfg[key]=File.expand_path(File.join(cfg_dir,values.join))\n else\n cfg[key]=values.join('=')\n end#case\n cfg[key]<<'=' if trailing_equals\n else\n puts \"ERROR - Configuration syntax error in #{filename}:\\n'#{l}'\"\n end#if size>1\n end#unless\n end#lines.each\n return cfg\nend", "def import_config_content_from_file\n open(self.config_file) {|f| f.each_with_index do |line, i|\n\n line.strip!\n\n # force_encoding not available in all versions of ruby\n begin\n if i.eql? 0 and line.include?(\"\\xef\\xbb\\xbf\".force_encoding(\"UTF-8\"))\n line.delete!(\"\\xef\\xbb\\xbf\".force_encoding(\"UTF-8\"))\n end\n rescue NoMethodError\n end\n\n # validate if line is comment or not\n is_comment = false\n @comments.each do |comment|\n if (/^#{comment}/.match(line))\n is_comment = true\n break\n end\n end\n\n unless is_comment\n if(/#{@splitRegex}/.match(line))\n param, value = line.split(/#{@splitRegex}/, 2)\n var_name = \"#{param}\".chomp.strip\n\n # just in case value has trailing comments\n value = value.split('#').first.chomp.strip\n\n new_value = ''\n if (value)\n if value =~ /^['\"](.*)['\"]$/\n new_value = $1\n else\n new_value = value\n end\n end\n self.params[var_name] = new_value\n end\n end\n end}\n end", "def generate_configuration\n template \"mebla.yml\", \"config/mebla.yml\"\n end", "def config_for name\n yaml = SpaceScrape.root.join 'config', \"#{ name }.yml\"\n\n unless yaml.exist?\n raise \"Could not load configuration. No such file - #{ yaml }\"\n end\n\n erb = ERB.new(yaml.read).result\n erbd_yaml = YAML.load erb\n\n erbd_yaml[SpaceScrape.environment.to_s] || {}\n rescue YAML::SyntaxError => e\n raise \"YAML syntax error occurred while parsing #{ yaml }. \" \\\n \"Please note that YAML must be consistently indented using spaces. Tabs are not allowed. \" \\\n \"Error: #{ e.message }\"\n end", "def process config\n replace_variables config.template_location\n\n replace_variables config.generate_settings.command unless config.generate_settings == nil || config.generate_settings.command == nil\n replace_variables config.generate_settings.docker_file unless config.generate_settings == nil || config.generate_settings.docker_file == nil\n\n replace_variables config.build_settings.build_commands.fetch unless config.build_settings == nil || config.build_settings.build_commands.fetch == nil\n replace_variables config.build_settings.build_commands.build unless config.build_settings == nil || config.build_settings.build_commands.build == nil\n replace_variables config.build_settings.build_commands.test unless config.build_settings == nil || config.build_settings.build_commands.test == nil\n\n replace_variables config.build_settings.docker_settings.image unless config.build_settings == nil || config.build_settings.docker_settings.image == nil\n replace_variables config.build_settings.docker_settings.env unless config.build_settings == nil || config.build_settings.docker_settings.env == nil\n replace_variables config.build_settings.docker_settings.binds unless config.build_settings == nil || config.build_settings.docker_settings.binds == nil\n replace_variables config.build_settings.docker_settings.working_directory unless config.build_settings == nil || config.build_settings.docker_settings.working_directory == nil\n\n return config\n end", "def create_database_yml\n return unless File.directory?(\"/app/#{ENV['app_dir']}/config\")\n topic \"Writing config/database.yml to read from DATABASE_URL\"\n File.open(\"/app/#{ENV['app_dir']}/config/database.yml\", \"w\") do |file|\n file.puts <<-DATABASE_YML\n<%\n\nrequire 'cgi'\nrequire 'uri'\n\nbegin\nuri = URI.parse(ENV[\"DATABASE_URL\"])\nrescue URI::InvalidURIError\nraise \"Invalid DATABASE_URL\"\nend\n\nraise \"No RACK_ENV or RAILS_ENV found\" unless ENV[\"RAILS_ENV\"] || ENV[\"RACK_ENV\"]\n\ndef attribute(name, value, force_string = false)\nif value\nvalue_string =\nif force_string\n '\"' + value + '\"'\nelse\n value\nend\n\"\\#{name}: \\#{value_string}\"\nelse\n\"\"\nend\nend\n\nadapter = uri.scheme\nadapter = \"postgresql\" if adapter == \"postgres\"\n\ndatabase = (uri.path || \"\").split(\"/\")[1]\n\nusername = uri.user\npassword = uri.password\n\nhost = uri.host\nport = uri.port\n\nparams = CGI.parse(uri.query || \"\")\n\n%>\n\ntest:\n<%= attribute \"adapter\", adapter %>\n<%= attribute \"database\", database %>\n<%= attribute \"username\", username %>\n<%= attribute \"password\", password, true %>\n<%= attribute \"host\", host %>\n<%= attribute \"port\", port %>\n\n<% params.each do |key, value| %>\n<%= key %>: <%= value.first %>\n<% end %>\n DATABASE_YML\n end\nend", "def create_file_config\n template \"config/smart_editor.yml\", \"config/smart_editor.yml\"\n end", "def load_config_file( filename )\n\n begin\n config_erb = ERB.new( IO.read( filename ) ).result( binding )\n rescue StandardError => ex\n raise( \"#{filename} could not be parsed with ERB. \\n#{ex.inspect}\" )\n end\n\n begin\n yml = YAML.load( config_erb )\n rescue Psych::SyntaxError => ex\n raise \"#{filename} could not be parsed as YAML. \\nError #{ex.message}\"\n end\n\n config = yml.symbolize_keys\n return config.symbolize_keys || {}\n end", "def database_configuration\n require 'erb'\n YAML::load(ERB.new(IO.read(database_configuration_file)).result) if File.exists?(database_configuration_file)\n end", "def load_config( filename )\n\n fullname = \"#{Rails.application.root}/config/#{filename}\"\n begin\n config_erb = ERB.new( IO.read( fullname ) ).result( binding )\n rescue StandardError => ex\n raise( \"#{filename} could not be parsed with ERB. \\n#{ex.inspect}\" )\n end\n\n begin\n yml = YAML.load( config_erb )\n rescue Psych::SyntaxError => ex\n raise \"#{filename} could not be parsed as YAML. \\nError #{ex.message}\"\n end\n\n config = yml.symbolize_keys\n @configuration = config[ Rails.env.to_sym ].symbolize_keys || {}\n end", "def parse_file_as_erb(source_file, locals={})\n helpers = locals.delete(:helpers)\n erb_struct = Class.new(OpenStruct) do\n include ERB::Util\n include helpers if helpers\n end\n\n contents = File.read(source_file)\n b = erb_struct.new(locals).instance_eval { binding }\n ERB.new(contents).result(b)\nend", "def configure!(parser); end", "def process_config(widget_name)\n system_config = Ruhoh::Utils.parse_yaml_file(@system_path, widget_name, \"config.yml\") || {}\n user_config = Ruhoh::Utils.parse_yaml_file(@path, widget_name, \"config.yml\") || {}\n config = Ruhoh::Utils.deep_merge(system_config, user_config)\n config['layout'] ||= widget_name\n config['stylesheet'] ||= widget_name\n config\n end", "def config\n \n # TODO: Re-enable:\n # # Display the value for a specific machine.\n # $ rudy -e prod -r db config param-name\n \n if @@config.nil? || @@config.empty?\n return if @@global.quiet\n raise Rudy::NoConfig\n end\n\n outform = @@global.format == :json ? :to_json : :to_yaml\n \n types = @option.marshal_dump.keys & @@config.keys # Intersections only\n types = @@config.keys if @option.all\n types = [:machines] if types.empty?\n \n if @option.project\n rf = File.join(RUDY_HOME, 'Rudyfile')\n raise \"Cannot find: #{rf}\" unless File.exists?(rf)\n li File.read(rf)\n \n elsif @option.script\n conf = fetch_script_config\n li conf.to_hash.send(outform) if conf\n \n else\n #li \"# ACCOUNTS: [not displayed]\" if types.delete(:accounts)\n types.each do |conftype|\n li \"# #{conftype.to_s.upcase}\"\n next unless @@config[conftype] # Nothing to output\n if conftype == :accounts\n skey = @@config[conftype][:aws][:secretkey]\n @@config[conftype][:aws][:secretkey] = hide_secret_key(skey)\n end\n \n li @@config[conftype].to_hash.send(outform)\n end\n end\n \n end", "def template(file, template)\n config = Environment.load(source: file)\n template = File.read(template)\n result = template.gsub(/{{([^}:]+)(:([^}]+))?}}/) do |_|\n key = $1\n default_value = ENV[key] || $3\n if default_value\n config.fetch(key, default_value)\n else\n config.fetch(key)\n end\n end\n puts result\n end", "def base_config\n if engine_config.config\n ::HamlLint::ConfigurationLoader.load_file(engine_config.config)\n else\n ::HamlLint::ConfigurationLoader.load_applicable_config\n end\n end", "def config_load(config); end", "def evaluate_erb; end", "def parse_config\n %w(/etc/steel/steel.yml steel.yml).each do |cfg|\n if File.exist?(cfg)\n begin\n y = YAML.load_file(cfg)\n rescue Psych::SyntaxError => e\n error \"[#{e.class}] Failed to parse '#{cfg}'!!\"\n error e.message\n exit 1\n end\n # Merge the contents of the config into @config.\n config.merge!(y)\n end\n end\n end", "def config_body_for(config)\n res = <<-EOH.gsub(/^ +/, '')\n # This file is managed by Chef.\n # Any changes to it will be overwritten.\n EOH\n res << Hash[config.sort].map { |k, v| config_for(k, v) }.compact\n .join(\"\\n\")\n end", "def erb!(vars = {})\n ERBResolve.new(vars).resolve!(self)\n end", "def erb!(vars = {})\n ERBResolve.new(vars).resolve!(self)\n end", "def erb!(vars = {})\n ERBResolve.new(vars).resolve!(self)\n end", "def database_configuration\n require 'erb'\n database_configurations = IO.read(database_configuration_file)\n\n client_config_path = \"/#{client_folder}/#{env_client_code}\\\\1\"\n client_database_configuration_file = database_configuration_file.gsub(/(\\/config\\/)/, client_config_path)\n database_configurations << IO.read(client_database_configuration_file) if File.exists?(client_database_configuration_file)\n \n YAML::load(ERB.new(database_configurations).result)\n end", "def read_config_file(file); end", "def config(value)\n # require value if File.exists?(value)\n if File.exists?(value)\n fc = File.read(value)\n self.instance_eval(fc)\n end\n end", "def load_config(filename)\n yml = YAML.load_file(filename)\n yml.each do |key, value| \n next if key == 'Templates'\n\n if key == 'PackageDirs'\n # PackageDirs.register value\n elsif key == 'AppDirs' \n # ApplicationDirMatcher.register value\n else\n app_matcher.register value\n end \n end\n end", "def config_from_raw(raw_config)\n config = Hash.new\n\n raw_config.split(\"\\n\").select { |line| line.match(/:\\s/) }.each do |line|\n key, value = line.split(/:\\s+/)\n config[key] = value\n end\n\n config\nend", "def parse(argv)\n rdoc_parse(argv)\n if %w{redfish twofish blackfish longfish onefish newfish}.include?(@template)\n require \"webri/generators/#{template}\"\n @generator = WebRI.const_get(@template.capitalize)\n end\n end", "def render_knife_config\n template File.join(cluster_data_dir, 'knife.rb') do\n variables lazy {\n {\n chef_server_url: chef_server_url,\n client_key: \"#{cluster_data_dir}/delivery.pem\",\n analytics_server_url: if analytics_enabled?\n \"https://#{analytics_server_fqdn}/organizations\" \\\n \"/#{node['delivery-cluster']['chef-server']['organization']}\"\n else\n ''\n end,\n supermarket_site: supermarket_enabled? ? \"https://#{supermarket_server_fqdn}\" : ''\n }\n }\n end\n end", "def config_read\n f = File.expand_path(CONFIG_FILE)\n return unless File.readable? f\n\n hash = loadYML(f)\n @used_dirs = hash['DIRS']\n @visited_files = hash['FILES']\n @bookmarks = hash['BOOKMARKS']\n @used_dirs.concat get_env_paths\nend", "def erb(vars = {})\n ERBResolve.new(vars).resolve(self)\n end", "def erb(vars = {})\n ERBResolve.new(vars).resolve(self)\n end", "def generate_vagrant_config\n template = Souffle::Template.new('Vagrantfile.erb')\n temp_binding = OpenStruct.new\n temp_binding.version = Souffle::VERSION\n \n template.render(temp_binding)\n end", "def allow_erb?\n ComfortableMexicanSofa.config.allow_erb\n end", "def configs(cfg)\n Dir.glob(cfg[\"tile_engines\"][\"conf_dir\"] + \"/*.conf.yml\").each do |item|\n\t engine_cfg = File.open(item){|fd| YAML.load(fd)}\n\t engine_cfg[\"mailer_config\"] = cfg[\"tile_engines\"][\"mailer_config\"]\n\t engine_cfg[\"config_path\"]=item\n\t yield engine_cfg\n end\n end", "def parse_config(\n config_file=File.expand_path(File.join(File.dirname(__FILE__), 'config.yml'))\n)\n require 'yaml'\n config = {\n 'sites' => \"sites\",\n 'webroot_subdir' => \"\",\n 'databases' => \"databases\",\n 'memory' => '2048',\n 'cpus' => '1',\n 'use_nfs' => true,\n 'with_gui' => false,\n 'ip' => \"192.168.50.4\",\n 'box_name' => 'Parrot-Trusty',\n 'varnish_enabled' => false,\n 'local_user_uid' => Process.uid,\n 'local_user_gid' => Process.gid,\n 'forward_solr' => true,\n 'forward_mysql' => true,\n 'forward_varnish' => true,\n 'forward_apache' => true,\n 'forward_https' => true,\n 'forward_dovecot' => true,\n 'solr_port' => 8983,\n 'mysql_port' => 3306,\n 'varnish_port' => 8181,\n 'apache_port' => 8080,\n 'https_port' => 1443,\n 'dovecot_port' => 1143,\n 'drush_version' => 'drush/drush',\n }\n if File.exists?(config_file)\n overrides = YAML.load_file(config_file)\n config.merge!(overrides)\n end\n config\nend", "def parse_config\n \n # Make sure there are site definitions\n if not @config.has_key?('remotes')\n puts \"Please add at least one remote definitions to your deploy-to.yml file.\"\n exit 1\n end\n \n # Check for a site_name.\n if @remote_name.nil?\n puts \"Specify which remote you woud like to deploy:\\n\"\n @config['remotes'].each do |remote_name,remote|\n puts \"\\s\\s*\\s\" + remote_name + \" (#{remote['host']})\" + \"\\n\"\n end\n exit 1\n end\n\n # Make sure the site_name is defined.\n if not @config['remotes'].has_key?(@remote_name)\n puts \"There is no definitions for \\\"#{@remote_name}\\\" in your deploy-to.yml file.\"\n exit 1\n end\n \n @remote = @config['remotes'][@remote_name]\n \n get_base # Use the get base method to get the base from the config\n \n set_ignore # Set ignore\n \n # Check that your remote has all the options we need\n if not @remote.has_key?('host') or not @remote.has_key?('path')\n puts \"Your remote: #{@remote_name}, must at least contain host and path.\"\n exit 1\n end\n \n # Build the URI\n @remote_uri = ''\n @remote_uri += \"#{@remote['user']}@\" if @remote.has_key?('user')\n @remote_uri += \"#{@remote['host']}:#{@remote['path']}\"\n @remote_uri += \"/\" if not @remote_uri[-1,1] == \"/\"\n rescue\n puts \"There was a problem parsing your config file\"\n exit 1\n end", "def yml_config\n return @yml_config if @yml_config\n\n require 'yaml'\n data = File.open(options[:config_path]).read\n\n require 'erb'\n data = ERB.new(data).result(binding)\n\n @yml_config ||= YAML.load(data)\n end", "def get_configcontent(format, appname, node = self.node, stackname = 'getcourse')\n settings = {}\n unless node.fetch(stackname, {})['env'].nil?\n Chef::Log.info(\"env settings for stack #{stackname} found\")\n settings = streamline_appenv(node[stackname]['env'])\n end\n if node.attribute?(appname) && node[appname].attribute?('env')\n Chef::Log.info(\"env settings for app #{appname} found\")\n settings.merge!(streamline_appenv(node[appname]['env']))\n end\n Chef::Log.info(\"no env settings found - appname was #{appname}, stack #{stackname}\") if settings.empty?\n\n unless node.fetch('deploy', {}).fetch(appname, {}).fetch('database', {})['host'].nil?\n # add configuration from the RDS resource management in opsworks\n Chef::Log.info('found configured rds resource, adding to envvars')\n dbconfig = streamline_appenv('db' => node['deploy'][appname]['database'])\n settings.merge!(dbconfig)\n end\n\n data = {\n 'deployed_application' => get_appdata(node, appname),\n 'deployed_stack' => get_stackdata(node),\n 'settings' => settings\n }\n to_configformat(format, data)\n end", "def availConfigFile(app)\n # Set variables for template:\n appUrl = app[\"url\"] #ERB\n appName = app[\"name\"]\n appPorts = app[\"ports\"]\n upstream = \"\"\n appPorts.each {|value|\n upstream += \" server 127.0.0.1:#{value};\\n\"\n }\n\n # Saving file:\n @put.normal \"Saving Nginx configuration file\"\n\n file = \"#{@templatesFolder}nginx.erb\"\n nginxTemplate = ERB.new(File.read(file))\n nginxConfig = nginxTemplate.result(binding)\n nginxCommand = File.open(\"#{@nginxAvailableFolder}#{appName}.conf\", 'w') {|f| f.write(nginxConfig) }\n\n unless nginxCommand.nil?\n @put.confirm\n return 0\n else\n @put.error \"Could not save Nginx configuration\"\n return 1\n end\n end", "def config_file_template_variables\n init_config_template unless config_template_exist?\n find_resource!(:template, ::File.join(new_resource.config_file)).variables[:config]\n end", "def parse_config\n @parsed_hash = Settings.load! @config_file\n validate @parsed_hash\n HadoopConfigParser.new(HADOOP_CONF, @log, @debug)\n HBaseConfigParser.new(HBASE_CONF, @log, @debug)\n unless @errors_count == 0\n @log.error \"Number of Errors: #{@errors_count}\"\n @log.error 'Parsing config file ... ' + '[Failed]'.red\n raise(Ankus::Errors::ParseError.new(\"\\rParsing Configuration Failed\".red))\n end\n create_req_files\n @parsed_hash\n rescue Ankus::Errors::ParseError, Ankus::Errors::ParseError::NoKey\n @log.error \"#{$!.message} (#{$!.class})\"\n exit\n rescue\n @log.error \"#{$!.message} (#{$!.class})\"\n puts $@ if @debug\n exit\n end", "def generate_config\n\n # Tell the user what's going on\n puts \"> Generating the config file\".green\n\n config = <<CONF_END\n\n# Configuration for the ServerUtility\n# Created by Christopher Hindefjord - chris@hindefjord.se - http://chris@hindefjord.se - 2014\n# Licensed under the MIT License (see LICENSE file)\n\nDEFAULT_ID = #{$DEFAULT_ID}\nBASE_PATH = '#{$BASE_PATH}'\nBASE_PATH_MAIL = BASE_PATH + 'maildir/'\nBASE_PATH_HOME = BASE_PATH + 'home/'\nUSER_PATH = '%domain/mails/%user'\nMAILBOX_RIGHTS = 0770 # \"ug=wrx\"\nDB_DATABASE_NAME = '#{$DB_NAME}'\nDB_ACCOUNTS_TABLE = '#{$DB_ACC_TABLE}'\nDB_DOMAINS_TABLE = '#{$DB_DOM_TABLE}'\nDB_ALIAS_TABLE = '#{$DB_VIRT_TABLE}'\nDB_USER = '#{$DB_USER}'\nDB_PASSWORD = '#{$DB_PASSWORD}'\n\nCONF_END\n\n # If this is a simulation\n if $simulate\n puts \"We're not writing to a file, so here's the config file in text:\".green\n # Just output the config file\n print config.yellow\n # Not a simulation\n else\n # Open a \"file stream\" and write to it\n File.open(CONFIG_FILE, 'w') { |f| f.write config }\n\n # Tell the user\n puts \"> Wrote the config to '#{CONFIG_FILE}'.\".green\n end\n\nend", "def read_config(conf_file)\n elt_names = nil\n in_continuation = false\n saved_line = \"\"\n # Load config file from classpath\n # f = java.lang.Object.new\n # stream = f.java_class.get_class_loader.resource_as_stream(\"docbook.conf\")\n print \"Config File is: \"\n print conf_file\n fh = java.io.BufferedReader.new(java.io.InputStreamReader.new(conf_file))\n while (line = fh.read_line())\n # File.open(\"/docbook.conf\") do |fh|\n # fh.each_line do |line|\n line.chomp!\n next if line =~ /^\\s*($|#)/ # skip blank lines, comments\n if in_continuation\n line = saved_line + \" \" + line\n saved_line = \"\"\n in_continuation = false\n end\n if line !~ /^\\s/\n # Line doesn't begin with whitespace, so it lists element names.\n # Names are separated by whitespace or commas, possibly followed\n # by a continuation character or comment.\n if line =~ /\\\\$/\n in_continuation = true\n saved_line = line.sub(/\\\\$/, \"\") # remove continuation character\n next\n end\n line.sub!(/\\s*#.*$/, \"\") # remove any trailing comment\n elt_names = line.split(/[\\s,]+/)\n # make sure each name has an entry in the elt_opts structure\n elt_names.each do |elt_name|\n @elt_opts[elt_name] = { } unless @elt_opts.has_key?(elt_name)\n end\n else\n # Line begins with whitespace, so it contains an option\n # to apply to the current element list, possibly followed by\n # a comment. First check that there is a current list.\n # Then parse the option name/value.\n\n if elt_names.nil?\n raise \"#{conf_file}:#{$.}: Option setting found before any \" +\n \"elements were named.\\n\"\n end\n line.sub!(/\\s*#.*$/, \"\")\n line =~ /^\\s*(\\S+)(?:\\s+|\\s*=\\s*)(\\S+)$/\n opt_name, opt_val = $1, $2\n raise \"#{conf_file}:#{$.}: Malformed line: #{$_}\" if opt_val.nil?\n\n # Check option. If illegal, die with message. Otherwise,\n # add option to each element in current element list\n\n opt_val, err_msg = check_option(opt_name, opt_val)\n raise \"#{conf_file}:#{$.}: #{err_msg}\\n\" unless err_msg.nil?\n elt_names.each do |elt_name|\n @elt_opts[elt_name][opt_name] = opt_val\n end\n\n # end\n end\n end\n\n # For any element that has missing option values, fill in the values\n # using the options for the *DEFAULT pseudo-element. This speeds up\n # element option lookups later. It also makes it unnecessary to test\n # each option to see if it's defined: All element option structures\n # will have every option defined.\n\n def_opts = @elt_opts[\"*DEFAULT\"]\n\n @elt_opts.keys.each do |elt_name|\n next if elt_name == \"*DEFAULT\"\n def_opts.keys.each do |opt_name|\n next if @elt_opts[elt_name].has_key?(opt_name) # already set\n @elt_opts[elt_name][opt_name] = def_opts[opt_name]\n end\n end\n\n end", "def load_template\n\t\traw = IO.read( __FILE__ ).split( /^__END__$/m, 2 ).last\n\t\treturn ERB.new( raw, nil, '<%>' )\n\tend", "def initialize(config_file='../config_parser/example_config.conf', comments=%w{# ;})\n @config_file = config_file\n @params = {}\n @splitRegex = '\\s*=\\s*'\n @comments = comments\n\n # validate the file and extract the content\n self.validate_file\n self.import_config_content_from_file\n end", "def parse(config_file)\n open(config_file) do |f|\n parse_string(f.read, config_file)\n end\n end", "def ReadGlobalConfig()\n\n # Load config file\n begin\n conf = YAML.load_file(\"#{$confdir}/#{$globalConfFile}\")\n rescue\n puts \"Unable to locate #{$confdir}/#{$globalConfFile}\"\n conf = {}\n end\n\n Dir.glob(\"#{$confdir}/#{$globalConfDir}/*.yaml\") {|f|\n begin\n conf.merge!(YAML.load_file(f))\n rescue\n puts \"Unable to locate #{f}\"\n conf = {}\n end\n }\n\n $sections.each {|o|\n conf[o] = [] if conf[o].nil?\n }\n conf[:globalConfFile] = \"#{$confdir}/#{$globalConfFile}\"\n conf[:globalConfDir] = \"#{$confdir}/#{$globalConfDir}\"\n\n altConfFile = \"#{$curdir}/.rake/#{$globalConfFile}\"\n if File.exists?(altConfFile)\n begin\n puts \"Reading local config file #{altConfFile}\" if $verbose\n c = YAML.load_file(altConfFile)\n raise \"Invalid yaml file\" if not c\n\n # surcharge d'options\n $sections.each {|s|\n next if c[s].nil?\n if $sections_uniq.include?(s)\n # remove then add option\n c[s].each {|o|\n o2 = o.gsub(/=.*/, \"=\")\n conf[s].delete_if {|o3| o3.start_with?(o2)}\n conf[s].push o\n }\n else\n c[s].each {|o|\n if o[0] == \"!\"\n # delete option\n conf[s].delete o[1..-1]\n else\n # just add option\n conf[s].push o\n end\n }\n end\n }\n rescue\n puts \"Error loading #{altConfFile}\"\n end\n end\n \n conf.each {|k,v|\n if v.class == Array\n conf[k].each_index {|i|\n conf[k][i].gsub!(/%B/, $basedir) if conf[k][i].class == String\n conf[k][i].gsub!(/%b/, $confdir) if conf[k][i].class == String\n }\n else\n conf[k].gsub!(/%B/, $basedir) if conf[k].class == String\n conf[k].gsub!(/%b/, $confdir) if conf[k].class == String\n end\n }\n\n return conf\nend", "def render_erb\n require 'erb'\n\n renderer = ERB.new(template_content, trim_mode: '-')\n renderer.filename = @template_file\n renderer.result(binding)\n end", "def read_configuration\n @config = {}\n @config_paths.map do |file|\n @section = nil; @pattern = nil; @mailto = nil\n # section, pattern, mailto are reset for every file (but not when included by 'include')\n parse_file( file )\n end.join($/)\n end", "def parse(eval_ui = false)\n begin\n defaults = @config['defaults']\n\n ################################################################\n # Cluster\n ################################################################\n\n if @config['cluster'].nil?\n @config['cluster'] = { 'name' => @config['name'] }\n end\n\n @config['cluster']['provision'] ||= {}\n\n if defaults && defaults.key?('provision')\n @config['cluster']['provision'].merge!(\n defaults['provision']\n )\n end\n\n ################################################################\n # Hosts\n ################################################################\n\n if @config['hosts']\n sections = ['connection', 'provision', 'configuration']\n\n @config['hosts'].map! do |host|\n sections.each do |section|\n data = CONFIG_DEFAULTS[section] || {}\n\n if @config['defaults']\n defaults = @config['defaults'][section]\n end\n\n h_sec = host[section]\n\n # merge defaults with globals\n # and device specific params\n data.merge!(defaults) unless defaults.nil?\n data.merge!(h_sec) unless h_sec.nil?\n\n host[section] = data\n end\n\n host\n end\n end\n\n ################################################################\n # Datastores & Networks\n ################################################################\n\n ['datastores', 'networks'].each do |r|\n next unless @config[r]\n\n @config[r].map! do |x|\n x['provision'] ||= {}\n\n if defaults && defaults.key?('provision')\n x['provision'].merge!(defaults['provision'])\n end\n\n x\n end\n end\n\n # Add provision ID into ARs to evaluate it later\n if @config['networks']\n @config['networks'].each do |vnet|\n next unless vnet['ar']\n\n unless vnet['ar'].is_a? Array\n raise 'ar should be an array'\n end\n\n vnet['ar'].each do |ar|\n ar['provision_id'] = '${provision_id}'\n end\n end\n end\n\n ################################################################\n # User inputs\n ################################################################\n return unless eval_ui\n\n eval_user_inputs\n rescue StandardError => e\n Utils.fail(\"Failed to read configuration: #{e}\")\n end\n end", "def config_web_xml()\n web_xml = File.readlines(self.web_xml()).map do |line|\n if line =~ /#{web_xml_token}/\n template = File.open(\"#{DEPLOYER_HOME}/resources/jira_cas_web.xml\") { |f| f.read() }\n line + ERB.new(template).result(self.send(:binding))\n else\n line\n end\n end\n \n File.open(self.web_xml(), \"w\") do |io|\n web_xml.each { |line| io.puts(line) }\n end \n end", "def read_config(fi,conf,curDir)\n\tDir.chdir curDir\n\tbDirs=bFiles=false\n \n\tIO.readlines(fi).each do |line|\n\t\tline.chomp!\n line.strip!\n\t\tnext if line[0,1]=='#' #comment line ?\n\t\tnext if line.empty? # ignore empty lines\n\t\tif line=~/^-exdirs/i\n\t\t\tbDirs,bFiles=true, false\n\t\telsif line=~/^-exfiles/i\n\t\t\tbFiles,bDirs=true, false\n\t\telsif line=~/^-server/i\n\t\t\tconf[:server]=getVal(line)\n\t\telsif line=~/^-user/i\n\t\t\tconf[:user]=getVal(line)\t\t\n\t\telsif line=~/^-port/i\n\t\t\tconf[:port]=getVal(line).to_i\n\t\telsif line=~/^-pass/i\n\t\t\tconf[:pass]=getVal(line)\n\t\telsif line=~/^-ftpdir/i\n\t\t\tconf[:ftpDir]=getVal(line)\n \t\telsif line=~/^-backupDrive/i\n\t\t\tconf[:backupDrive]=getVal(line)\n\n\t\telsif line=~/^-backupFile/i\n\t\t\tconf[:backupFile]=getVal(line)\n \t elsif line=~/^-generations/i\n\t\t\tconf[:generations]=getVal(line).to_i\n unless conf[:generations]>0\n puts 'error in config: generations must be > 0 !'\n puts line\n exit 1\n end\n elsif line=~/^-cryptpass/i\n\tconf[:passphrase]=getVal(line)\n \tif conf[:passphrase].size<8\n \tputs 'error in config: cryptpass minimum length is 8 chars !'\n \t \tputs line\n \texit 1\n end\n elsif bDirs\n\t\t\tconf[:exDirs]<< line # collect directories to exclude/(nclude empty only)\n elsif bFiles\n\t\t\tconf[:exFiles]<< line # collect file masks to exclude\n else\n\t\t\tconf[:saveDirs]<< line # collect directories to backup\n end\n end\nend", "def fill_template\n @log.debug(\"Reading erb template from file: '#{@template}'.\")\n erb = ERB.new(File.read(@template), nil, '-')\n erb.filename = @template\n erb.result(binding)\n end", "def initialize(options={})\n self.mailboxes = []\n self.quiet = options.fetch(:quiet, false)\n\n if options.has_key?(:config_path)\n begin\n erb = ERB.new(File.read(options[:config_path]))\n erb.filename = options[:config_path]\n config_file = YAML.load(erb.result)\n\n set_mailboxes(config_file[:mailboxes])\n rescue => e\n raise e unless quiet\n end\n end\n end", "def process_config\n input = File.open(\"lib/templates/config_template.sh\",\"r\")\n config = input.read\n input.close()\n output = File.new(@bigframe_home + \"/conf/config.sh\", \"w\") \n if output\n output.syswrite(config %[@hadoop_home, @tpchds_local])\n end\n output.close()\n end", "def read_config_file\n if @pretend\n contents = @pretend_input || []\n else\n contents = File.readlines(@config_file)\n end\n\n # add a blank line at the end (sentinal)\n contents << \"\\n\"\n end", "def configurations; end", "def load_config_file\n data = {}\n if File.exists?(@configfile)\n File.open(@configfile, \"r\").each_line do |line|\n # strip blank spaces, tabs etc. off the lines\n line.gsub!(/\\s*$/, \"\")\n \n if (line =~ /^([^=]+)=\"([^=]*)\"$/)\n key = $1.downcase\n val = $2\n \n case key\n when /^ve_(private|root)$/\n data[key] = val.gsub!(/\\$VEID/, @ctid)\n else\n data[key] = val\n end\n end\n end\n end\n data\n end", "def as_config\n Configureasy::Config.new self.parse\n end", "def parsed_config\n @parsed_config ||= begin\n JSON.parse(config[:json_config], symbolize_names: true)\n rescue JSON::ParserError\n JSON.parse(File.read(config[:json_config]),\n symbolize_names: true)\n end\n end", "def display_config\n # Format types and the additional options that apply to each type\n format_opts = {\n \"block\" => [\n \"entry-break\",\n \"element-break\",\n \"exit-break\",\n \"subindent\",\n \"normalize\",\n \"wrap-length\"\n ],\n \"inline\" => [ ],\n \"verbatim\" => [ ]\n }\n @elt_opts.keys.sort.each do |elt_name|\n puts elt_name\n opts = @elt_opts[elt_name]\n format = opts[\"format\"]\n # Write out format type, then options that apply to the format type\n puts \" format = #{format}\"\n format_opts[format].each do |opt_name|\n puts \" #{opt_name} = #{opts[opt_name]}\"\n end\n puts\n end\n end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end" ]
[ "0.6637162", "0.6189307", "0.6046174", "0.6006817", "0.60047555", "0.59642124", "0.59455884", "0.59337044", "0.5888536", "0.5888536", "0.58860826", "0.58402175", "0.582407", "0.5771413", "0.5754093", "0.5748191", "0.5736008", "0.57303756", "0.571367", "0.56876326", "0.56650597", "0.5650855", "0.5647733", "0.55714345", "0.55698067", "0.553997", "0.55367875", "0.55282587", "0.55266935", "0.55106056", "0.5504978", "0.54950845", "0.54847276", "0.5459587", "0.5458896", "0.54583204", "0.54565394", "0.54518414", "0.5451653", "0.5446235", "0.5436389", "0.5436389", "0.5436389", "0.5429501", "0.5422862", "0.54218847", "0.54111874", "0.54084593", "0.5402228", "0.54017705", "0.539873", "0.53970677", "0.53970677", "0.53940666", "0.53907734", "0.5387418", "0.53846306", "0.5380341", "0.5375239", "0.53730845", "0.5372267", "0.5371119", "0.5365737", "0.5358123", "0.5352729", "0.53503686", "0.5345509", "0.5323733", "0.53222317", "0.5314343", "0.5304865", "0.529659", "0.52917737", "0.52801263", "0.52723414", "0.52679336", "0.52633226", "0.526277", "0.52545834", "0.52538055", "0.52399725", "0.52396387", "0.52381754", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901", "0.5236901" ]
0.0
-1
Creates a new Parser. See also ::parse
def initialize @tokens = [] @current_token = nil @debug = false @line = 0 @line_pos = 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parser\n @parser ||= Parser.new(self)\n end", "def parser\n @parser ||= Parser.new(self)\n end", "def parser\n Parser.new(self, :mode=>mode)\n end", "def parser\n @parser ||= Parser.new(self)\n end", "def initialize parser\n @parser = parser\n end", "def parse(params) new(params).parse end", "def parser; end", "def parser; end", "def parser; end", "def parser; end", "def parser( &block )\n nested_class( 'Parser', Yacl::Define::Cli::Parser, &block )\n end", "def parse(body)\n new Nokogiri body\n end", "def parse(source, options = {})\n new.parse(source, options)\n end", "def parser\n @parser ||= parser_klass.new(job_folder)\n end", "def parser\n @parser ||= Sawtooth::Parser.new(:rules => self.rules)\n end", "def create_parser(grammar_paths)\n @search_parser ||=\n grammar_paths.inject(nil) do |parser, lucene_grammar|\n begin\n break parser unless parser.nil?\n # Don't instantiate custom nodes\n Treetop.load_from_string(\n IO.read(lucene_grammar).gsub(/<[^>]+>/, ''))\n LuceneParser.new\n rescue\n # Silently swallow and try the next grammar\n end\n end\n end", "def create_parser(grammar_paths)\n @search_parser ||= grammar_paths.inject(nil) do |parser,lucene_grammar|\n begin\n break parser unless parser.nil?\n # don't instantiate custom nodes\n Treetop.load_from_string(\n IO.read(lucene_grammar).gsub(/<[^>]+>/, ''))\n LuceneParser.new\n rescue\n # silently swallow and try the next grammar\n end\n end\n end", "def initialize(parse_tree)\n @parse_tree = parse_tree\n end", "def parser=(p)\n @@parser = choose_parser(p)\n end", "def parse_from_text(text)\n parser = TextParser.new\n parser.parse_text(text, self)\n return self\n end", "def parse(doc)\n parser = parser_class.new\n parser.run(doc)\n end", "def parse\n fail StandardError.new('parse has not been implemented.')\n end", "def pluggable_parser; end", "def parse text\n raise \"No parser defined for #{self.class}\"\n end", "def parse\n raise NotImplementedError\n end", "def parse(data)\n new.parse(data)\n end", "def parse\n end", "def parse; end", "def parse; end", "def parse; end", "def parser=(_arg0); end", "def build_parser( descriptor, file = nil )\n return RCC::Scanner::Interpreter::Parser.new( @parser_plan, open_source(descriptor, file) )\n end", "def build_parser( descriptor, file = nil )\n return RCC::Scanner::Interpreter::Parser.new( @parser_plan, open_source(descriptor, file) )\n end", "def get_parse(s);end", "def parser(name = T.unsafe(nil)); end", "def initialize(opts={})\n if opts[:parser]\n @parser = opts[:parser]\n elsif opts[:grammar_file] and opts[:grammar_class]\n if @@parsers[opts[:grammar_class]]\n # already compiled the grammar, just use it\n @parser = @@parsers[opts[:grammar_class]]\n else\n # load the grammar\n Treetop.load(opts[:grammar_file])\n cls = eval(opts[:grammar_class])\n @parser = cls.new\n end\n else\n raise ArgumentError.new(\"Specify either :parser or :grammar_file and :grammar_class\")\n end\n end", "def parse(klass)\n Parser.new(self, klass).result\n end", "def parser\n if !defined?(@parser) || !@parser\n DEFAULT_PARSER\n else\n @parser || DEFAULT_PARSER\n end\n end", "def parse\n raise NotImplementedError.new\n end", "def parse(source)\n @root = Document.new(tokenize(source))\n self\n end", "def parse(source); end", "def parse(source)\n Parser.parse(source)\n end", "def initialize\n @parser = Grammar::RootParser.new\n end", "def initialize\n @parser = Grammar::RootParser.new\n end", "def compile_parser(base, grammar_or_parser, opts={})\r\n compile(Class.new(base), grammar_or_parser, opts)\r\n end", "def parser(value = nil)\n setget(:@parser, value)\n end", "def initialize(command_line)\n parse(command_line)\n end", "def parse(str)\n RubyParser.new.parse(str.deep_clone)\n end", "def parsing(parser)\n yield\n resolve parser\n self\n end", "def parser (tokens)\n\n\t# create the new, concrete syntax tree\n\t# making it global to reduce headaches (hopefully XD )\n\t$cst = ConcreteSyntaxTree.new\n\t\n\t# define some other useful, global vars\n\t$tokens = tokens\n\t$index = 0\n\t\n\t# have to ask alan about this\n\tif $tokens.length <= 1\n\t\tputs \"Insufficient code present! There is only #{$tokens.length} token here!\"\n\t\texit\n\tend\t\n\t\n\t\n\t# Engine to full burn!!!\n\t#parse(\"Program\", program)\n\tprogram\n\t\n\t\n\tbegin\n\t\tif $tokens.length != $index\n\t\t\traise EOFDetectionError.new(\"early\", $tokens[$index - 1].lineno, $tokens[$index - 1].pos)\n\t\tend\n\trescue EOFDetectionError\n\tend\n\t\t\n\t\n\t\n\treturn $cst\nend", "def parser\n attributes.fetch(:parser)\n end", "def parser=(parser)\n @parser = parser_from(parser)\n end", "def parser(v)\n @options[:parser] = v\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def initialize(str)\n @raw = str # Keeps th original string for later use\n @buffer = StringScanner.new(str) # Create StringScanner buffer\n @attributes = {} # Initialize the attributes hash\n @stack = [Stacker.new(0)] # Initialize the parser stack with initial \"state\"\n parse # Start parsing\n end", "def parse!\n raise NotImplementedError, \"this class is intended to be a top class, not a useful parser\"\n end", "def initialize(str = nil)\n parse(str) if str\n end", "def parser\n create_option_parser if @parser.nil?\n @parser\n end", "def build_parser\n code = ''\n\n %w[opal/ruby/nodes opal/ruby/parser opal/ruby/ruby_parser].each do |src|\n full = File.join OPAL_PATH, 'opal_lib', src + '.rb'\n compiled = compile_source full\n code += \"opal.register('#{src}.rb', #{compiled});\"\n end\n\n code += build_stdlib 'racc/parser.rb', 'strscan.rb', 'dev.rb'\n code += \"opal.require('dev');\"\n\n code\n end", "def parse(text, options = T.unsafe(nil)); end", "def open_parser(this_file)\n\t\t@file = this_file\n\t\t@parser = PbfParser.new(file)\n\tend", "def initialize\n compiler = Treetop::Compiler::GrammarCompiler.new\n @where = File.expand_path(File.dirname(__FILE__))\n grammar = File.join(@where, 'seqpar.treetop')\n output = File.join(@where, 'seqpar.rb')\n compiler.compile(grammar, output)\n load output\n File.delete(output)\n @parser = SeqParParser.new\n end", "def parse()\n #This is a stub, used for indexing\n end", "def parse(text); end", "def set_parser\n @parser = Parser.find(params[:id])\n end", "def set_parser\n @parser = Parser.find(params[:id])\n end", "def parse\n parse_file\n self\n end", "def parse(code = nil, options = nil, &block)\n Parsing::parse(code, options, &block)\n end", "def parser\n @parser ||= ::Puppet::Pops::Parser::EvaluatingParser.new\n end", "def parser\n @parser ||= ::Puppet::Pops::Parser::EvaluatingParser.new\n end", "def new_parser_with_data\n\tdoc = load_sample_xml\n\tparser = GreenButton::Parser.new(doc)\nend", "def parse(html)\n Parser.new(self.lex(html)).parse()\n end", "def initialize(str, debug=false)\n setup_parser(str, debug)\n end", "def initialize(str, debug=false)\n setup_parser(str, debug)\n end", "def initialize(str, debug=false)\n setup_parser(str, debug)\n end", "def parse(source, options = T.unsafe(nil)); end", "def parse(source, options = T.unsafe(nil)); end", "def parse(input = nil, options = 0)\n end", "def parse(str); end", "def parse()\n merge(rvparse: 'true')\n end", "def parse\n @parsed\n end", "def parse(str)\n DEFAULT_PARSER_CHAIN.parse(str)\n end", "def parse str\n self.ss = scanner_class.new str\n self.lineno = 1\n self.start_of_current_line_pos = 0\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.lineno = 1\n self.start_of_current_line_pos = 0\n self.state ||= nil\n\n do_parse\n end", "def initialize options = {}\n # This is just a placeholder.\n # See parser.c for the C source code to this method.\n end", "def parse\n raise \"absctract method called\"\n end", "def parser\n return nil if self.evaluation_file.nil?\n VivoParser.new(self.evaluation_file.path)\n end", "def to_parser\n parser = Racc::GrammarFileParser.new\n result = parser.parse to_yacc\n nfa = Racc::States.new(result.grammar).nfa\n parsegen = Racc::ParserFileGenerator.new nfa.dfa, result.params\n parser_src = parsegen.generate_parser\n\n if $DEBUG\n puts \"############# PARSED GRAMMAR\"\n puts parser_src\n puts \"############# END PARSED GRAMMAR\"\n end\n\n Module.new { class_eval parser_src }.const_get('GeneratedGrammar')\n end", "def set_parser\n @parser = Parser.find(params[:id])\n end", "def initialize(label = nil, &b)\n self.label = label if label\n @parser = b\n end", "def ruby_parser\n @ruby_parser ||= parser_for_version ruby_version\n end", "def configure_parser; end", "def parse(io, options = T.unsafe(nil)); end", "def parse\n parse_eols\n rules = []\n while rule = parse_rule\n rules << rule\n end\n if !@s.eos?\n raise \"expected eos : #{@s.inspect}\"\n end\n Peg.new @ctx, rules\n end", "def initialize(param={})\n @argv ||= param.delete(:argv) || ARGV\n @stdout ||= param.delete(:stdout) || STDOUT\n @stderr ||= param.delete(:stderr) || STDERR\n @stdin ||= param.delete(:stdin) || STDIN\n @opts ||= param.delete(:opts) || {}\n @parser_got_range=nil\n yield self if block_given?\n make_parser()\n end", "def initialize(str, debug=false)\n setup_parser(str, debug)\n @g = KPeg::Grammar.new\n end", "def rewind\n create_parser\n end", "def create_parser(options)\n parser = OptionParser.new\n\n parser.on \"-o DIR\", \"--output-dir DIR\", \"Specify custom output directory\" do |value|\n options.custom_output_dir_set = true\n options.custom_output_dir_value = value\n end\n parser.on \"-s FILENAME\", \"--single-file FILENAME\", \"Output all quotes in a single file\" do |name|\n options.single_file = true\n options.single_file_name = name\n end\n parser.on \"-l\", \"--list-categories\", \"List all available categories\" do\n options.list_only = true\n end\n\n parser.on \"-h\", \"--help\", \"Print this help text\" do\n puts parser\n exit\n end\n\n parser.on \"-v\", \"--version\", \"Print program version\" do\n puts \"gnomikologikon-fortune #{Gnomika::Ruby::VERSION}\"\n exit\n end\n end" ]
[ "0.7445383", "0.7445383", "0.7397252", "0.7329526", "0.726806", "0.72557133", "0.67240715", "0.67240715", "0.67240715", "0.67240715", "0.66707337", "0.6666743", "0.6568896", "0.6517118", "0.6508107", "0.64593154", "0.6416704", "0.6383697", "0.6375915", "0.6331114", "0.62944186", "0.62644506", "0.62490577", "0.6235795", "0.62209386", "0.6218154", "0.6198454", "0.6190517", "0.6190517", "0.6190517", "0.61806166", "0.6170932", "0.6170932", "0.6170885", "0.6141877", "0.6109188", "0.61047214", "0.606262", "0.60574245", "0.6054069", "0.6046968", "0.60445464", "0.60409737", "0.60380465", "0.60366124", "0.60360926", "0.60300726", "0.60242784", "0.6014202", "0.6003133", "0.59994686", "0.59925425", "0.5991472", "0.59856933", "0.59856933", "0.59856933", "0.59856933", "0.59690547", "0.59677494", "0.5965069", "0.59469795", "0.59300745", "0.5922981", "0.5915546", "0.5901066", "0.58905506", "0.5890281", "0.5882337", "0.5882337", "0.5877822", "0.58662", "0.5859036", "0.5859036", "0.5838743", "0.58268887", "0.58246726", "0.58246726", "0.58246726", "0.58215463", "0.58215463", "0.5814415", "0.5808093", "0.5797159", "0.57732975", "0.57720846", "0.5771946", "0.5771946", "0.57685447", "0.5752861", "0.5733655", "0.5728379", "0.57247883", "0.57223076", "0.5708643", "0.5698573", "0.5697637", "0.5676301", "0.5663407", "0.5663292", "0.5645516", "0.5645151" ]
0.0
-1
Builds a Heading of +level+
def build_heading level heading = RDoc::Markup::Heading.new level, text skip :NEWLINE heading end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_heading level\n type, text, = get\n\n text = case type\n when :TEXT then\n skip :NEWLINE\n text\n else\n unget\n ''\n end\n\n RDoc::Markup::Heading.new level, text\n end", "def build_heading level\n heading = super\n\n @section = heading.text\n\n heading\n end", "def heading(level, title)\n @io << @templates[:heading_3].result(binding) if level == 3\n @io << @templates[:heading_4].result(binding) if level == 4\n end", "def make_headline level, text\n super_headline([4, level + 1].min, text)\n end", "def header(text, level)\n h = headers.add(text, level += 1)\n navigation.append(text, h.name) if level == 2\n nest h\n h.render\n end", "def header(text, header_level, *args)\n if header_level > 1\n new_node = Jekyll::Node.new text\n if header_level == @last.level\n new_node.parent = @last.parent\n @last.sibling = new_node\n elsif header_level > @last.level\n new_node.parent = @last\n @last.child = new_node\n elsif header_level < @last.level\n new_node.parent = @last.parent.parent\n @last.parent.sibling = new_node\n end\n @last = new_node\n\n \"<h#{header_level} id='#{new_node.slug}'>#{text}</h#{header_level}>\"\n elsif header_level == 1\n @title = text\n \"<h#{header_level} class='big' id='top'>#{text}</h#{header_level}>\"\n end\n end", "def header(level = 1, txt)\n enclose(\"h#{level}\", txt)\n end", "def header(text, header_level)\n\t\t\"h#{header_level}. #{text}\\n\"\n\tend", "def header\n tag! \"h#{options[:level]}\".intern\n end", "def display_heading(text, level, indent)\n text = strip_attributes(text)\n case level\n when 1\n puts \"= \" + text.upcase\n when 2\n puts \"-- \" + text\n else\n print indent, text, \"\\n\"\n end\n end", "def header(text, level)\n if text =~ /^\\^([a-zA-Z0-9-]+) /\n anchor_prefix = $1\n text = text.sub(\"^#{anchor_prefix} \", \"\")\n end\n anchor = FormatHelpersWrapper.strip_tags(text).parameterize\n anchor = \"#{anchor_prefix}-#{anchor}\" if anchor_prefix\n %(<h%s><span class=\"anchor\" id=\"%s\"></span><a href=\"#%s\">%s</a></h%s>) % [level, anchor, anchor, text, level]\n end", "def random_h( level = 1 )\n \"<h#{level}>#{texter.random_title}</h#{level}>\"\n end", "def header(text, header_level)\n # clean string from html\n stringHeader = Sanitize.clean(text)\n\n # replace all unwanted characters to space\n stringHeader = stringHeader.downcase.gsub(/[^a-z0-9_-]+/i, \" \")\n\n # strip whitespaces from the beginning and end of a string\n stringHeader = stringHeader.strip\n\n # replace all unwanted characters to -\n stringHeader = stringHeader.downcase.gsub(/[^a-z0-9_-]+/i, \"-\")\n\n # convert number to string\n stringHeaderNum = header_level.to_s\n\n # create header\n result = '<h' + stringHeaderNum + ' id=\"' + stringHeader + '\">' + text + '</h' + stringHeaderNum + '>'\n\n return result\n end", "def draw_level_text\n reset_font_settings\n level = QuestData::LEVEL_SIGNALS && QuestData::LEVEL_SIGNALS[@quest.level - 1] ? \n QuestData::LEVEL_SIGNALS[@quest.level - 1] : @quest.level.to_s\n align = QuestData::HEADING_ALIGN[:level]\n tw = text_size(QuestData::VOCAB[:level]).width + 4\n tw2 = text_size(level).width + 2\n space = contents_width - tw - tw2\n x = align == 2 ? space : align == 1 ? space / 2 : 0\n clear_and_draw_text(x, @draw_y, tw, line_height, QuestData::VOCAB[:level])\n set_data_font(:level_signal)\n clear_and_draw_text(x + tw, @draw_y, tw2, line_height, level, 2)\n end", "def new_heading match\n \"<h#{match[:level]} id=\\\"#{match[:slug]}\\\">#{match[:title]}</h#{match[:level]}>\"\nend", "def draw_header\n x = (contents.width - 240) / 2\n ml = 0\n p1 = @old_level\n p2 = @actor.level\n ml = contents.text_size(p1).width if contents.text_size(p1).width > ml\n ml = contents.text_size(p2).width if contents.text_size(p2).width > ml\n ml += 4\n mo = 236 - ml\n change_color(system_color)\n draw_text(x + 2, 0, mo - ml - 22, line_height, CP::VICTORY::LEVEL_UP, 0)\n draw_text(x + mo - 22, 0, 22, line_height, \"→\", 1)\n change_color(normal_color)\n draw_text(x + mo - ml - 22, 0, ml, line_height, p1, 2)\n change_color(power_up_color)\n draw_text(x + mo, 0, ml, line_height, p2, 2)\n end", "def heading_level\n self.get_heading_level\n end", "def current_level=( level )\n if @base_level.nil?\n @base_level = @cur_level = level\n @level[@base_level-1] = @numbering_start-1\n end\n\n if level < @base_level\n raise ::Webby::Error, \"heading tags are not in order, cannot outline\"\n end\n\n if level == @cur_level\n @level[level-1] += 1\n elsif level > @cur_level\n @cur_level.upto(level-1) {|ii| @level[ii] += 1}\n else\n @cur_level.downto(level+1) {|ii| @level[ii-1] = 0}\n @level[level-1] += 1\n end\n\n @cur_level = level\n end", "def output_header_level(level); end", "def html_output(head, level)\n classes = \"class='level-tag level-tag-#{@level}'\"\n \"<div #{classes}>#{head}<span>#{level}</span></div>\"\n end", "def start_section(level, title)\n end", "def level_text2\n \"#{text_get(27, 29)}#@level\"\n end", "def heading_info( elem )\n m = @h_rgxp.match(elem.name)\n level = Integer(m[1])\n\n self.current_level = level\n text = elem.inner_text\n\n lbl = label\n if numbering?\n elem.children.first.before %Q{<span class=\"heading-num\">#{lbl}</span>}\n end\n elem['id'] = \"h#{lbl.tr('.','_')}\" if elem['id'].nil?\n\n return [text, elem['id']]\n end", "def header_level=(level)\n if self.type != :header\n raise NodeError, \"can't set header_level for non-header\"\n end\n if !level.kind_of?(Integer) || level < 0 || level > 6\n raise NodeError, \"level must be between 1-6\"\n end\n res = CMark.node_set_header_level(@pointer, level)\n if res == 0 then raise NodeError, \"could not set header level\" end\n end", "def header(title, level)\r\n @headers ||= []\r\n permalink = title.downcase.gsub(/\\W+/, '-')\r\n\r\n if @headers.include? permalink\r\n permalink += '_1'\r\n permalink = permalink.succ while @headers.include? permalink\r\n end\r\n @headers << permalink\r\n %(\r\n <h#{level}><a name=\"#{permalink}\" class=\"anchor\" href=\"##{permalink}\"><span class=\"anchor-icon\"></span></a>#{title}</h#{level}>\r\n )\r\n end", "def heading_to_lvl(heading)\n heading.name.gsub('h','').to_i\n end", "def increment_level(level)\n\n if !@last_heading_counter[level] \n @last_heading_counter[level] = 0\n end\n @last_heading_counter[level] += 1\n\n for i in 0..(@last_heading_counter.length - 1) do\n if i > level + 1\n @last_heading_counter[i] = 0\n elsif [0, nil].include?(@last_heading_counter[i])\n @last_heading_counter[i] = 1\n end\n end\nend", "def get_heading_level(element)\n tag = element.get_tag_name\n return 1 if tag == 'H1'\n return 2 if tag == 'H2'\n return 3 if tag == 'H3'\n return 4 if tag == 'H4'\n return 5 if tag == 'H5'\n return 6 if tag == 'H6'\n -1\n end", "def initialize(level, title)\n super()\n @level = level\n @title = title\n end", "def add(text, level=1)\n name = text.parameterize\n if @headers.include? name\n name += '-%d' % (@headers[name] += 1)\n else @headers[name] = 0 end\n Header.new(text, level, name)\n end", "def initialize(level, title)\n super()\n @level, @title = level, title\n end", "def heading(title = @title, opts={})\n \n heading = @renderer.heading(title, opts)\n \n puts \"[Cutlist.heading]: #{heading}\" if $cutlister_debug\n \n heading\n \n end", "def find_parent_heading_for_level(heading, level)\n return if heading.nil?\n level_up = level - 1\n if heading[:level] == level_up\n heading\n else\n find_parent_heading_for_level(heading[:parent], level)\n end\n end", "def heading str\n write \">>>>> #{str}\\n\"\n end", "def accept_heading heading\n level = [6, heading.level].min\n\n label = heading.label @code_object\n\n @res << if @options.output_decoration\n \"\\n<h#{level} id=\\\"#{label}\\\">\"\n else\n \"\\n<h#{level}>\"\n end\n @res << to_html(heading.text)\n unless @options.pipe then\n @res << \"<span><a href=\\\"##{label}\\\">&para;</a>\"\n @res << \" <a href=\\\"#top\\\">&uarr;</a></span>\"\n end\n @res << \"</h#{level}>\\n\"\n end", "def level_declaration\n \"integer :: #@level_name = #@level_number\"\n end", "def heading?(level = nil)\n parent?(Tree::Heading, level: level)\n end", "def section_heading(label)\n \n \"#{label}\\n\"\n \n end", "def section_heading(label)\n \n \"#{label}\\n\"\n \n end", "def get_head(config)\n config['level_tag_level'] || \"Level: \"\n end", "def heading_tag(content_or_options_with_block = nil, options = {}, &block)\n if block_given?\n options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)\n value = capture(&block).strip\n else\n value = content_or_options_with_block\n end\n\n level = options.delete(:level) { 1 }\n\n content_tag(\"h#{level}\", value.html_safe, options.merge('role' => :heading, 'aria-level' => level))\n end", "def title()\n el = to_xml.at_css(\"heading[level=1] > text\")\n raise \"No level-1 heading in document.\" if el.nil? || el.text.blank?\n el.text\n end", "def get_next_headline_number(level)\n raise \"Headline level not valid: #{level}\" if level <= 0\n while level > @headline_number_stack.length do\n @headline_number_stack.push 0\n end\n while level < @headline_number_stack.length do\n @headline_number_stack.pop\n end\n raise \"Oops, shouldn't happen\" unless level == @headline_number_stack.length\n @headline_number_stack[@headline_number_stack.length - 1] += 1\n @headline_number_stack.join(\".\")\n end", "def get_next_headline_number(level)\n raise \"Headline level not valid: #{level}\" if level <= 0\n while level > @headline_number_stack.length do\n @headline_number_stack.push 0\n end\n while level < @headline_number_stack.length do\n @headline_number_stack.pop\n end\n raise \"Oops, shouldn't happen\" unless level == @headline_number_stack.length\n @headline_number_stack[@headline_number_stack.length - 1] += 1\n @headline_number_stack.join(\".\")\n end", "def title_for_heading(parent_titles = Array.new)\n if parent_titles.length > 0\n [parent_titles, self.term_to_html(\"unittitle\")].join(\" >> \")\n else\n self.term_to_html(\"unittitle\")\n end\n end", "def section_heading(label)\n \n \"<h3>#{label}</h3>\"\n \n end", "def build_header \n pdf_writer.margins_in(1)\n if timespan == \"Weekly\"\n add_text \"Status Report for the Week of \" + Time.now.to_formatted_s(:date)\n else\n add_text \"Status Report for \" + Time.now.to_formatted_s(:date)\n end\n end", "def level_text\n @level.to_s\n end", "def build_header\n @pdf.text_box(\n @labels[:name],\n size: 20,\n align: :left,\n at: [0, y(720) - @push_down],\n width: x(300),\n )\n\n if used? @labels[:sublabels][:name]\n @pdf.text_box(\n @labels[:sublabels][:name],\n size: 12,\n at: [0, y(720) - @push_down - 22],\n width: x(300),\n align: :left\n )\n end\n\n @pdf.text_box(\n @document.number,\n size: 20,\n at: [x(240), y(720) - @push_down],\n width: x(300),\n align: :right\n )\n\n @pdf.move_down(250)\n\n if used? @labels[:sublabels][:name]\n @pdf.move_down(12)\n end\n end", "def turtle level\n if level.zero? then @level_0\n elsif level == 1 then @level_1\n else\n s = ''\n @level_1.each_byte do |b|\n b == @level_0_byte ? s += turtle(level-1) : s += b.chr\n end\n s\n end\n end", "def new_level\n @level = Level.new(Settings.leveldata[Game.next_level])\n @message = @level.message.downcase.split(\"\")\n @target, @completed = @message, \"\"\n Tail.clear\n @head = Tail.new(@player.x, @player.y, :none, Image.new(Settings.spacer)) \n Grid.populate\n @player.x, @player.y = 0, 0\n @active_tile = Grid.tile_at(0, 0)\n @mailbox = \"\"\n @enemy_timer = Time.new\n end", "def section_heading(label)\n \n @renderer.section_heading(label)\n \n end", "def level_name\n name = (Membership::LEVELS.respond_to?(:key) ? Membership::LEVELS.key(level) : Membership::LEVELS.index(level)).to_s\n end", "def level= level\n if (0..6).include? level then @level = level\n elsif LEVEL.include? level.to_s then @level = LEVEL.index level\n else @level = UNKNOWN\n end\n end", "def build_header \n pdf_writer.margins_in(1)\n \n pad_bottom(10) do\n if allflag\n add_text \"All Goals\"\n else\n add_text \"Current Goals\"\n end\n end \n \n end", "def heading (str)\n h1 = \"--------------------\"\n $h2 = h1 + h1 + h1 + h1\n len = str.length\n len2 = len % 2\n hlen = (79 - (len + 2))/2\n result = $h2.slice(0,hlen) + \" \" + str + \" \" + $h2.slice(0,hlen)\n if len2 == 0 then result = result + \"-\" end\n return result\nend", "def extract_heading(line)\n if line =~ /^(#+)\\s(.*)/\n prefix = $1\n title = $2\n depth = prefix.size\n anchor = \"#\" + title.\n downcase.\n gsub(/[\\/:]/,\"\"). # titles like \"/url/:id\" are transformed by Github into \"#urlid\" anchors\n gsub(/\\W+/,\"-\").gsub(/(\\d)\\-(\\d)/,\"\\\\1\\\\2\").\n gsub(/^\\-+/,\"\").\n gsub(/\\-+$/,\"\")\n\n [depth, title, anchor]\n end \nend", "def build_levels(build)\n\t\tlevels = \"#{build.name}\\n\" + build.lvls.reduce(\"\") {|str,(k,v)| str + \"#{k.to_s}: #{v}\\n\"} \n\tend", "def generate top_levels\n super\n @project_name = \"#{@outputdir.basename}.hhp\"\n generate_help_project\n end", "def format_name(level, full_name)\n lnname = ' '*level+full_name\n if (lnname.length > 60)\n lnname[0..3]+'...'+lnname[-54,lnname.length-1]\n else\n lnname\n end\n end", "def print_heading\n @report_file.puts\n @report_file.puts(' ##### ######')\n @report_file.puts(' # # ## # ###### #### # # ###### ##### #### ##### #####')\n @report_file.puts(' # # # # # # # # # # # # # # # #')\n @report_file.puts(' ##### # # # ##### #### ###### ##### # # # # # # #')\n @report_file.puts(' # ###### # # # # # # ##### # # ##### #')\n @report_file.puts(' # # # # # # # # # # # # # # # # #')\n @report_file.puts(' ##### # # ###### ###### #### # # ###### # #### # # #')\n @report_file.puts('********************************************************************************')\n @report_file.puts\n end", "def about\n @main_heading='<span>Hello</span> <span>my</span> <span>name</span> <span>is</span> <span>Jim</span><span class=\"punctuation\">.</span>'\n end", "def draw_heading(data_type, y)\n set_data_font(:heading)\n clear_and_draw_text(40, y, contents_width - 80, line_height, \n QuestData::VOCAB[data_type], QuestData::HEADING_ALIGN[data_type])\n reset_font_settings\n end", "def label\n rv = @level.dup\n rv.delete(0)\n rv.join('.')\n end", "def send_level_name(event)\n level = parse_highscoreable(event.content.gsub(/level/, \"\"))\n raise OutteError.new \"Episodes and stories don't have a name!\" if level.is_a?(Episode) || level.is_a?(Story)\n event << \"#{level.name} is called #{level.longname}.\"\nrescue => e\n lex(e, \"Error getting name.\", event: event)\nend", "def initialize(level)\n @level_name = level\n\t\t@level_sub_name = level + '_subroutine'\n @module_name = case level\n when 'dist_fn_layouts' \n 'gs2_layouts' \n when /^dist_fn_*/\n 'dist_fn'\n when /^fields_level_[12]/\n 'fields'\n when /^antenna_level_[12]/\n 'antenna'\n when /^kt_grids*/\n 'kt_grids'\n when /^fields_parameters/\n 'fields'\n else\n @level_name\n end\n @level_number = @@level_counter\n @@level_counter += 1\n end", "def levelname\n\t\t\tlevel.level_name\n\t\tend", "def level_with_descript\n\t\t\"#{level}, #{description}\"\n\tend", "def heading\n\t\tname\n\tend", "def heading\n\t\tname\n\tend", "def headline_chapter(input)\n $headline_chapter_counting_from += 1\n style = {:upper_space => $headline_chapter_upper_space,\n :font_variable => $headline_chapter_font,\n :font_size_variable => $headline_chapter_text_size,\n :font_style => $headline_chapter_font_style\n }\n indent = \"\\xC2\\xA0\" * $headline_chapter_indent\n print_out(style, \"#{indent}#{$headline_chapter_counting_from}. #{input}\".rjust(10))\nend", "def format_level(level)\n @level_cache[level] ||= level.to_s.upcase\n end", "def heading(title, opts)\n \n # Default CSS location (relative).\n css_location = \"Cutlister/css/html-cutlist.css\"\n \n # Check to see if the css_location option was passed to the heading method.\n opts.each { |key, value|\n \n # Check to see if the css_location key exists in the option hash.\n if key.to_s == \"css_location\"\n\n css_location = value\n\n end\n\n }\n\n # Find the support file (absolute).\n css_file_path = File.join(CUTLISTER_BASE_PATH, css_location)\n \n css_file_contents = IO.read(css_file_path)\n \n puts \"[HTMLRenderer.heading] css_location: #{css_location}\" if $cutlister_debug\n puts \"[HTMLRenderer.heading] css_file_path: #{css_file_path}\" if $cutlister_debug\n \n return <<-EOS\n \n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\"xml:lang=\"en\" lang=\"en\">\n <head>\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/>\n\n <title>#{title}</title>\n\n <!-- Stylesheets -->\n <!--<link type=\"text/css\" rel=\"stylesheet\" href=\"#{css_file_path}\" media=\"all\" />-->\n <style type=\"text/css\">\n \n #{css_file_contents}\n \n </style>\n\n </head>\n <body>\n\n EOS\n \n end", "def convert_header(el, indent)\n res = \"\"\n current_header_level = el.options[:level]\n if @respec_first_section\n @respec_first_section = false\n @respec_last_header_level = current_header_level\n else\n if @respec_last_header_level < current_header_level\n @respec_last_header_level = current_header_level\n else\n while @respec_last_header_level > current_header_level\n res += \"#{' ' * indent}</section>\\n\\n\"\n @respec_last_header_level -= 1\n end\n res += \"#{' ' * indent}</section>\\n\\n\"\n end\n end\n if el.options[:respec_section]\n res += \"#{' ' * indent}<section#{html_attributes(el.options[:respec_section])}>\\n\"\n else\n res += \"#{' ' * indent}<section>\\n\"\n end\n # res + super\n\n attr = el.attr.dup\n if @options[:auto_ids] && !attr['id']\n attr['id'] = generate_id(el.options[:raw_text])\n end\n @toc << [el.options[:level], attr['id'], el.children] if attr['id'] && in_toc?(el)\n level = output_header_level(el.options[:level])\n res + format_as_block_html(\"h#{level}\", attr, inner(el, indent), indent)\n end", "def heading\n @invoice.project.account.account_setting.logo_file_name ? move_down(220) : move_down(100)\n\n formatted_text([\n { :text => \"Invoice\",\n :color => \"111111\",\n :size => 35,\n :style => [:bold]\n },\n { :text => \" #{@invoice.invoice_number}\",\n :color => \"999999\",\n :size => 35,\n :style => [:bold]\n }\n ])\n move_down 20\n end", "def h(heading)\n puts \"\"\n puts \"-\"*10\n puts heading\n puts \"-\"*10\nend", "def header_level\n @pairs.fetch(\"level\", \"1\").to_i\n end", "def session_heading(session)\n puts \"\\nAdding session heading for session #{session.id}...\"\n add_to_index(session.moderator.person.lastname_first)\n @content << '\\vspace{1em}' + \"\\n\" + '\\begin{minipage}{\\columnwidth}' + \"\\n\\n\" + '\\Large\\begin{center}'\n in_column_line\n @content << \"\\n\" + '\\vspace{10pt}{\\scshape\\bfseries{' + \"Session #{session.identifier}\" + '}}' + \"\\n\\n\" + '\\vspace{1pt}'\n in_column_line\n @content << '\\vspace{10pt}{\\scshape\\bfseries{' + \"#{session.title}\" + '}}' + \"\\n\\n\" + '\\vspace{0.2em}'\n @content << '\\normalsize'\n @content << '\\textit{'\n @content << \"Session Moderator: #{session.moderator.fullname}, #{session.moderator.department_name}\" + '}' + \"\\n\\n\"\n @content << '\\textbf{' + \"#{session.location}\" + '}' + \"\\n\\n\" + '\\vspace{0.2em}'\n @content << '\\end{center}'\n @content << '\\small' + \"* Note: Titles in order of presentation.\\n\\n\" + '\\end{minipage}' + \"\\n\\n\" + '\\normalsize \\normalsize'\n move_to_newline\n end", "def make_header\n name = @player.player_name\n score = @player.player_score\n label = TkLabel.new(@main_frame) { text \"Player: #{name} Score: #{score}\" }\n label.pack(\"side\"=>\"top\")\n end", "def create_header(my_name)\n\t\"<h1>#{my_name}</h1>\"\nend", "def heading_for(w)\n w.refresh\n w.read_text.split(\"\\n\")[0,2]\n end", "def guess_heading(node)\n return nil if node.font_size == nil\n [*1...HEADING_DEPTH].each do |heading|\n return \"h#{heading}\" if node.font_size >= h(heading)\n end\n nil\n end", "def buildup_template_header(basename, hash)\n header = []\n type = hash[:type] || :script\n header << filename_for(basename, type)\n header << \"\"\n description = hash[:description] || \"no description\"\n header << teardown_to_oneline(description)\n header << \"\"\n date = hash[:date] || Time.now\n header << \"created on : %04d.%02d.%02d\" % [date.year, date.month, date.day]\n header << \"last update: %04d.%02d.%02d\" % [date.year, date.month, date.day]\n header << \"\"\n author = hash[:author] || AUTHOR_NAME\n header << teardown_to_oneline(\"by \" + author)\n return header.flatten\n end", "def heading\n \"Court #{number}\"\n end", "def heading\n\t\t\"Works\"\n\tend", "def name_with_difficulty_level\r\n self.name + \" - \" + self.difficulty_level\r\n end", "def initialize(level)\n case level\n when \"heroes\"\n @word = Faker::Overwatch.unique.hero.upcase\n when \"locations\"\n @word = Faker::Overwatch.unique.location.upcase\n when \"quotes\"\n @word = Faker::Overwatch.unique.quote.upcase\n end\n @letters = @word.split('')\n @guess = 0\n @word_display = []\n @letters.each do |letter|\n if [\" \",\"!\",\",\",\".\",\"?\",\"\\\"\",\"'\",\":\",\";\",\"$\"].include?(letter)\n @word_display << letter\n else\n @word_display << \"_\"\n end\n end\n cat_position\n @guessed_letters = []\n end", "def generate_list_heading\n local = @parser.find('body').first_result\n\n return if local.nil?\n\n container_before = @parser.find(\n \"##{ID_CONTAINER_HEADING_BEFORE}\"\n ).first_result\n if container_before.nil? && !@elements_heading_before.empty?\n container_before = @parser.create_element('div')\n container_before.set_attribute('id', ID_CONTAINER_HEADING_BEFORE)\n\n text_container_before = @parser.create_element('span')\n text_container_before.set_attribute('class', CLASS_TEXT_HEADING)\n text_container_before.append_text(@elements_heading_before)\n\n container_before.append_element(text_container_before)\n local.prepend_element(container_before)\n end\n unless container_before.nil?\n @list_heading_before = @parser.find(\n container_before\n ).find_children('ol').first_result\n if @list_heading_before.nil?\n @list_heading_before = @parser.create_element('ol')\n container_before.append_element(@list_heading_before)\n end\n end\n\n container_after = @parser.find(\n \"##{ID_CONTAINER_HEADING_AFTER}\"\n ).first_result\n if container_after.nil? && !@elements_heading_after.empty?\n container_after = @parser.create_element('div')\n container_after.set_attribute('id', ID_CONTAINER_HEADING_AFTER)\n\n text_container_after = @parser.create_element('span')\n text_container_after.set_attribute('class', CLASS_TEXT_HEADING)\n text_container_after.append_text(@elements_heading_after)\n\n container_after.append_element(text_container_after)\n local.append_element(container_after)\n end\n unless container_after.nil?\n @list_heading_after = @parser.find(\n container_after\n ).find_children('ol').first_result\n if @list_heading_after.nil?\n @list_heading_after = @parser.create_element('ol')\n container_after.append_element(@list_heading_after)\n end\n end\n\n @list_heading_added = true\n end", "def make_load_header(text_line)\n EdiHelper::edi_log.write \"LI PreProcessor: Creating missing LH record from LD record...\",0\n\n detail_data = RawFixedLenRecord.new('LI', 'LD', text_line)\n header_data = RawFixedLenRecord.new('LI', 'LH')\n ignore_fields = ['load_date', 'instruction_quantity']\n line = header_data.populate_with_values_from( detail_data, ignore_fields )\n\n EdiHelper::edi_log.write \"LI PreProcessor: Created missing LH record from LD record.\",0\n line\n end", "def level; end", "def level; end", "def level; end", "def level; end", "def level; end", "def level; end", "def header(label)\n @lines << ''\n @lines << TColor.blue { label }\n end", "def guess_heading(node)\n return nil if node.font_size.nil?\n\n [*1...HEADING_DEPTH].each do |heading|\n return \"h#{heading}\" if node.font_size >= h(heading)\n end\n nil\n end", "def old_heading match\n if match[:had_slug?]\n \"<h#{match[:level]} id=\\\"#{match[:slug]}\\\">#{match[:title]}</h#{match[:level]}>\"\n else\n \"<h#{match[:level]}>#{match[:title]}</h#{match[:level]}>\"\n end\nend", "def to_prawn_header(header)\n size = { 1 => 16, 2 => 12 }[header.level]\n @pdf.text header.children.join(\"\\n\"), :size => size, :style => :bold\n @pdf.text ' '\n end", "def level\n init unless @initialized\n level = level_to_sym(@level)\n end" ]
[ "0.8417932", "0.7992036", "0.766331", "0.72736394", "0.7115193", "0.7091424", "0.70675504", "0.68406266", "0.6820763", "0.67263156", "0.6411727", "0.64061326", "0.6369527", "0.6271758", "0.6270927", "0.6246594", "0.62451506", "0.61768943", "0.61630785", "0.61508495", "0.6132298", "0.6130503", "0.6127049", "0.60700774", "0.6069004", "0.59953356", "0.59807587", "0.58805925", "0.5864782", "0.5832361", "0.58236617", "0.57793593", "0.5763178", "0.57497805", "0.57195485", "0.57151526", "0.57033056", "0.56913", "0.56913", "0.5673641", "0.56651676", "0.5597892", "0.55929416", "0.55929416", "0.55884737", "0.5582186", "0.55654705", "0.5561031", "0.55587447", "0.5546952", "0.5536448", "0.5531949", "0.55254465", "0.5502163", "0.5499588", "0.548497", "0.5474312", "0.5472696", "0.545827", "0.54569715", "0.5412628", "0.54088145", "0.53813946", "0.53710586", "0.53627646", "0.5360179", "0.5343058", "0.5334024", "0.532776", "0.532776", "0.53044075", "0.52969474", "0.52926946", "0.5291407", "0.5290373", "0.5285096", "0.52840674", "0.5262702", "0.52619946", "0.52389216", "0.52346647", "0.52123314", "0.5204768", "0.5195846", "0.5191611", "0.51896197", "0.5185898", "0.5182869", "0.5154377", "0.51428217", "0.51428217", "0.51428217", "0.51428217", "0.51428217", "0.51428217", "0.5139179", "0.5135301", "0.512794", "0.51263297", "0.51253885" ]
0.8584473
0
Builds a List flush to +margin+
def build_list margin p :list_start => margin if @debug list = RDoc::Markup::List.new until @tokens.empty? do type, data, column, = get case type when :BULLET, :LABEL, :LALPHA, :NOTE, :NUMBER, :UALPHA then list_type = type if column < margin then unget break end if list.type and list.type != list_type then unget break end list.type = list_type case type when :NOTE, :LABEL then _, indent, = get # SPACE if :NEWLINE == peek_token.first then get peek_type, new_indent, peek_column, = peek_token indent = new_indent if peek_type == :INDENT and peek_column >= column unget end else data = nil _, indent, = get end list_item = build_list_item(margin + indent, data) list << list_item if list_item else unget break end end p :list_end => margin if @debug return nil if list.empty? list end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_list margin\n p :list_start => margin if @debug\n\n list = RDoc::Markup::List.new\n label = nil\n\n until @tokens.empty? do\n type, data, column, = get\n\n case type\n when *LIST_TOKENS then\n if column < margin || (list.type && list.type != type) then\n unget\n break\n end\n\n list.type = type\n peek_type, _, column, = peek_token\n\n case type\n when :NOTE, :LABEL then\n label = [] unless label\n\n if peek_type == :NEWLINE then\n # description not on the same line as LABEL/NOTE\n # skip the trailing newline & any blank lines below\n while peek_type == :NEWLINE\n get\n peek_type, _, column, = peek_token\n end\n\n # we may be:\n # - at end of stream\n # - at a column < margin:\n # [text]\n # blah blah blah\n # - at the same column, but with a different type of list item\n # [text]\n # * blah blah\n # - at the same column, with the same type of list item\n # [one]\n # [two]\n # In all cases, we have an empty description.\n # In the last case only, we continue.\n if peek_type.nil? || column < margin then\n empty = true\n elsif column == margin then\n case peek_type\n when type\n empty = :continue\n when *LIST_TOKENS\n empty = true\n else\n empty = false\n end\n else\n empty = false\n end\n\n if empty then\n label << data\n next if empty == :continue\n break\n end\n end\n else\n data = nil\n end\n\n if label then\n data = label << data\n label = nil\n end\n\n list_item = RDoc::Markup::ListItem.new data\n parse list_item, column\n list << list_item\n\n else\n unget\n break\n end\n end\n\n p :list_end => margin if @debug\n\n if list.empty? then\n return nil unless label\n return nil unless [:LABEL, :NOTE].include? list.type\n\n list_item = RDoc::Markup::ListItem.new label, RDoc::Markup::BlankLine.new\n list << list_item\n end\n\n list\n end", "def pad_list\n pg = [LIST_START]\n\n pg += items\n\n pg << LIST_END\n\n dx = items.each_with_index.to_h\n\n scroll_content(pg, dx) && select_content(pg, dx)\n\n pg.each_slice(4).count\n end", "def create_list\n @linkedList.append(cols/2, lines/2)\n @linkedList.append(cols/2 - 1, lines/2)\n @linkedList.append(cols/2 - 2, lines/2)\n # @linkedList.print\n end", "def list_style(item); end", "def pretty_list(list)\r\n\tputs \"Grocery List\".center(30)\r\n\tlist.each do |item, quantity|\r\n\t\tputs \"#{item} \".ljust(20) + \"#{quantity}\".rjust(10)\r\n\tend\r\nend", "def format_list(items); end", "def setItems(list, list_size, numbers)\n if self.createItemList(numbers, list, list_size) <= 0\n return\n end\n\n # Clean up the display.\n (0...@view_size).each do |x|\n Draw.writeBlanks(@win, 1, x, CDK::HORIZONTAL, 0, @box_width - 2);\n end\n\n self.setViewSize(list_size)\n self.setPosition(0)\n @left_char = 0\n end", "def list(padding = 5)\n puts \"\\nTACOS:\"\n puts '-'*(max_length(:text) + max_length(:context) + padding + 3)\n\n items.each_with_index do |item, index|\n if item.context.to_s == @options[:filter] || @options[:filter].nil?\n printf(\"[%s] %-#{max_length(:text)+padding}s%s\\n\",\n index+1, item.text, colorize(item.context.gsub('@',''), :cyan))\n end\n end\n\n puts '-'*(max_length(:text) + max_length(:context) + padding + 3)\n puts \"\"\n end", "def list_with_limit(id, list, options = {}, &block)\n # backwards compatible to when third argument was just a number\n # for limit.\n options = {:limit => options} unless options.kind_of?(Hash)\n options[:limit] ||= 5\n options[:ul_class] ||= \"list-unstyled\"\n return \"\" if list.empty?\n visible_list = (list.length > options[:limit]) ? list.slice(0, options[:limit]-1) : list\n hidden_list = (list.length > options[:limit]) ? list.slice((options[:limit]-1)..list.length-1) : []\n parts =[]\n parts << content_tag(:ul, :class => options[:ul_class]) do\n safe_join(\n visible_list.enum_for(:each_with_index).collect do |item, index|\n yield(item, index)\n end, \" \\n \"\n )\n end\n if (hidden_list.present?)\n parts << expand_contract_section(\"#{hidden_list.length} more\", id) do\n content_tag(:ul, :class=>options[:ul_class]) do\n safe_join(\n hidden_list.enum_for(:each_with_index).collect do |item, index|\n yield(item, index + options[:limit] - 1)\n end, \" \\n \"\n )\n end\n end\n end\n return safe_join(parts, \"\\n\")\n end", "def wrap_list(list, width)\n list.map do |text|\n wrap_text(text, width)\n end.flatten\n end", "def add_list_definition(style); end", "def render\n buffer = []\n _guess_col_widths\n rows = @list.size.to_s.length\n @rows = rows\n _prepare_format\n \n str = \"\"\n if @numbering\n str = \" \"*(rows+1)+@y\n end\n str << @fmstr % @columns\n buffer << str\n #puts \"-\" * str.length\n buffer << separator\n if @list\n if @numbering\n @fmstr = \"%#{rows}d \"+ @y + @fmstr\n end\n #@list.each { |e| puts e.join(@y) }\n count = 0\n @list.each_with_index { |r,i| \n value = convert_value_to_text r, count\n buffer << value\n count += 1\n }\n end\n buffer\n end", "def build_list\n students = input_students\n print_header\n print(students)\n print_footer(students)\nend", "def render\n rendered_items = ''\n\n list.list_items.each do |list_item|\n rendered_items += render_item(list_item)\n end\n\n if opts[:wrapper_element]\n content_tag opts[:wrapper_element], rendered_items, html_options, false\n else\n rendered_items\n end\n end", "def build_list_item indent, item_type = nil\n p :list_item_start => [indent, item_type] if @debug\n\n list_item = RDoc::Markup::ListItem.new item_type\n\n until @tokens.empty? do\n type, data, column = get\n\n if column < indent and\n not type == :NEWLINE and\n (type != :INDENT or data < indent) then\n unget\n break\n end\n\n case type\n when :INDENT then\n unget\n list_item.push(*parse(indent))\n when :TEXT then\n unget\n list_item << build_paragraph(indent)\n when :HEADER then\n list_item << build_heading(data)\n when :NEWLINE then\n list_item << RDoc::Markup::BlankLine.new\n when *LIST_TOKENS then\n unget\n list_item << build_list(column)\n else\n raise ParseError, \"Unhandled token #{@current_token.inspect}\"\n end\n end\n\n p :list_item_end => [indent, item_type] if @debug\n\n return nil if list_item.empty?\n\n list_item.parts.shift if\n RDoc::Markup::BlankLine === list_item.parts.first and\n list_item.length > 1\n\n list_item\n end", "def make_item_list\n end", "def list_layout( project_list )\n # define results and top\n results = []\n top = 0\n\n # each project list item\n project_list.each do |item|\n if item[ 'display' ][ 0 ] == 'b'\n # item is block\n bcl = block_csv_line( item[ 'name' ], item[ 'uuid' ], 0, top, 0 )\n results << bcl[ :line ]\n top += bcl[ :height ]\n else\n # item is package of blocks\n max_height = 0\n item[ 'blocks' ].each do |bk|\n bcl = block_csv_line( bk[ 'name' ], bk[ 'uuid' ], bk[ 'x' ],\n bk[ 'y'] + top, bk[ 'z' ] )\n results << bcl[ :line ]\n if max_height < bcl[ :height ]\n max_height = bcl[ :height ]\n end\n end\n top += max_height\n end\n end\n return results.join( \"\\n\" )\nend", "def format_list_item(out, options)\n if options[:list] == :ul\n out << \"#{'*' * (options[:ul] + 1)} \"\n elsif options[:list] == :ol\n number = options[:number]\n options[:number] = number.next\n out << \"#{number}. \"\n end\n end", "def list_creator(list)\n\tsorted_list = list.sort\n\tsorted_list.each do |item|\n\tputs \"* \" + item\n\tend\nend", "def generate_list_skippers\n container = @parser.find(\"##{ID_CONTAINER_SKIPPERS}\").first_result\n html_list = nil\n if container.nil?\n local = @parser.find('body').first_result\n unless local.nil?\n container = @parser.create_element('div')\n container.set_attribute('id', ID_CONTAINER_SKIPPERS)\n local.prepend_element(container)\n end\n end\n unless container.nil?\n html_list = @parser.find(container).find_children('ul').first_result\n if html_list.nil?\n html_list = @parser.create_element('ul')\n container.append_element(html_list)\n end\n end\n @list_skippers_added = true\n\n html_list\n end", "def list_of(items=[], *args, &block)\n renderer = ListRenderer.new(items,self,*args,&block)\n unless block_given? \n renderer.to_html\n end\n end", "def build_verbatim margin\n p :verbatim_begin => margin if @debug\n verbatim = RDoc::Markup::Verbatim.new\n\n min_indent = nil\n generate_leading_spaces = true\n line = ''.dup\n\n until @tokens.empty? do\n type, data, column, = get\n\n if type == :NEWLINE then\n line << data\n verbatim << line\n line = ''.dup\n generate_leading_spaces = true\n next\n end\n\n if column <= margin\n unget\n break\n end\n\n if generate_leading_spaces then\n indent = column - margin\n line << ' ' * indent\n min_indent = indent if min_indent.nil? || indent < min_indent\n generate_leading_spaces = false\n end\n\n case type\n when :HEADER then\n line << '=' * data\n _, _, peek_column, = peek_token\n peek_column ||= column + data\n indent = peek_column - column - data\n line << ' ' * indent\n when :RULE then\n width = 2 + data\n line << '-' * width\n _, _, peek_column, = peek_token\n peek_column ||= column + width\n indent = peek_column - column - width\n line << ' ' * indent\n when :BREAK, :TEXT then\n line << data\n else # *LIST_TOKENS\n list_marker = case type\n when :BULLET then data\n when :LABEL then \"[#{data}]\"\n when :NOTE then \"#{data}::\"\n else # :LALPHA, :NUMBER, :UALPHA\n \"#{data}.\"\n end\n line << list_marker\n peek_type, _, peek_column = peek_token\n unless peek_type == :NEWLINE then\n peek_column ||= column + list_marker.length\n indent = peek_column - column - list_marker.length\n line << ' ' * indent\n end\n end\n\n end\n\n verbatim << line << \"\\n\" unless line.empty?\n verbatim.parts.each { |p| p.slice!(0, min_indent) unless p == \"\\n\" } if min_indent > 0\n verbatim.normalize\n\n p :verbatim_end => margin if @debug\n\n verbatim\n end", "def lister(list)\n\tlist.each do |item|\n\t\tputs \"* #{item}\"\n\tend\nend", "def build_verbatim margin\n p :verbatim_begin => margin if @debug\n verbatim = RDoc::Markup::Verbatim.new\n\n until @tokens.empty? do\n type, data, column, = get\n\n case type\n when :INDENT then\n if margin >= data then\n unget\n break\n end\n\n indent = data - margin\n\n verbatim << ' ' * indent\n when :HEADER then\n verbatim << '=' * data\n\n _, _, peek_column, = peek_token\n peek_column ||= column + data\n verbatim << ' ' * (peek_column - column - data)\n when :RULE then\n width = 2 + data\n verbatim << '-' * width\n\n _, _, peek_column, = peek_token\n peek_column ||= column + data + 2\n verbatim << ' ' * (peek_column - column - width)\n when :TEXT then\n verbatim << data\n when *LIST_TOKENS then\n if column <= margin then\n unget\n break\n end\n\n list_marker = case type\n when :BULLET then '*'\n when :LABEL then \"[#{data}]\"\n when :LALPHA, :NUMBER, :UALPHA then \"#{data}.\"\n when :NOTE then \"#{data}::\"\n end\n\n verbatim << list_marker\n\n _, data, = get\n\n verbatim << ' ' * (data - list_marker.length)\n when :NEWLINE then\n verbatim << data\n break unless [:INDENT, :NEWLINE].include? peek_token[0]\n else\n unget\n break\n end\n end\n\n verbatim.normalize\n\n p :verbatim_end => margin if @debug\n\n verbatim\n end", "def build_toc_list(entries, last_ul_used: false)\n i = 0\n toc_list = ''\n min_h_num = entries.map { |e| e[:h_num] }.min\n\n while i < entries.count\n entry = entries[i]\n if entry[:h_num] == min_h_num\n # If the current entry should not be indented in the list, add the entry to the list\n toc_list << %(<li class=\"toc-entry toc-#{entry[:node_name]}\"><a href=\"##{entry[:id]}#{entry[:uniq]}\">#{entry[:text]}</a>)\n # If the next entry should be indented in the list, generate a sublist\n if i + 1 < entries.count\n next_entry = entries[i + 1]\n if next_entry[:h_num] > min_h_num\n nest_entries = get_nest_entries(entries[i + 1, entries.count], min_h_num)\n toc_list << %(\\n<ul>\\n#{build_toc_list(nest_entries, last_ul_used: true)}</ul>\\n)\n i += nest_entries.count\n end\n end\n # Add the closing tag for the current entry in the list\n toc_list << %(</li>\\n)\n elsif entry[:h_num] > min_h_num\n # If the current entry should be indented in the list, generate a sublist\n nest_entries = get_nest_entries(entries[i, entries.count], min_h_num)\n if last_ul_used\n toc_list << build_toc_list(nest_entries, last_ul_used: true)\n else\n toc_list << %(<ul>\\n#{build_toc_list(nest_entries, last_ul_used: true)}</ul>\\n)\n end\n i += nest_entries.count - 1\n end\n i += 1\n end\n\n toc_list\n end", "def pretty_list(list)\n # new_list = \"\"\n # list.each { |item, quantity| new_list << \"You want #{quantity} #{item}\\n\" }\n # return new_list\n list.each { |item, quantity| puts \"You want #{quantity} #{item}\\n\" }\nend", "def towerBuilder(n_floors)\n layer = width = n_floors + (n_floors - 1)\n result = []\n\n while layer > 0\n result.unshift((\"*\" * layer).center(width))\n layer -= 2\n end\n result\nend", "def render(list=yaml, space_count=0)\n list.each do |nav_item|\n # nav_item is a single element hash\n key, value = nav_item.keys.first, nav_item.values.first\n if value.is_a?(Array)\n self.buffer += \"#{' ' * space_count}#{key}\\n\"\n render value, space_count + 4\n else\n self.buffer += \"#{' ' * space_count}#{key} = #{value}\\n\"\n end\n end\n buffer\n end", "def create_list\n list = SinglyLinkedList.new\n list.insert_at_start 1\n list.insert_at_start 2\n list.insert_at_start 3\n list.insert_at_end 4\n list.insert_at_start 4\n list.insert_at_end 5\n list\nend", "def make_list_possibly_grouped_impl(fnt_list)\n r = \"<table class='method-table table-wrapper'> \\n\"\n fnt_list.each do |name|\n r += '<tr><td class=\"method-name\" align=\"right\"><a href=\"%s\">%s</a></td>' % [name, get_fancy_name(name)]\n r += '<td class=\"method-brief\">%s</td>' % markdownify(get_brief(name)).gsub('<p>','').gsub('</p>', '')\n r += \"</tr>\\n\"\n end\n return r + \"</table>\"\n end", "def display_list_of_items_packed\n output = []\n output << \"Melinda, here's your packing list!\"\n output << \"Day: #{@attributes[:day_of_week]}, Weather: #{@attributes[:weather]}\"\n output << \"\"\n\n @items.each do |item|\n output << \"- #{item}\"\n end\n output.join(\"\\n\")\n end", "def print_list(glist)\n\tputs \"Grocery Shopping list\"\n\tglist.each do |item, count|\n\t\tputs \"#{item}: \".ljust(20) + \" #{count}\".rjust(20)\n\tend\nend", "def fb_css\n '<style>\n .lists th {\n text-align: left;\n padding: 5px 10px;\n background: #6d84b4;\n }\n\n .lists .spacer {\n background: none;\n border: none;\n padding: 0px;\n margin: 0px;\n width: 10px; \n }\n\n .lists th h4 { float: left; color: white; }\n .lists th a { float: right; font-weight: normal; color: #d9dfea; }\n .lists th a:hover { color: white; }\n\n .lists td {\n margin:0px 10px;\n padding:0px;\n vertical-align:top;\n }\n\n .lists .list {\n background:white none repeat scroll 0%;\n border-color:-moz-use-text-color #BBBBBB;\n border-style:none solid;\n border-width:medium 1px;\n }\n .lists .list .list_item { border-top:1px solid #E5E5E5; padding: 10px; }\n .lists .list .list_item.first { border-top: none; }\n\n .lists .see_all {\n background:white none repeat scroll 0%;\n border-color:-moz-use-text-color #BBBBBB rgb(187, 187, 187);\n border-style:none solid solid;\n border-width:medium 1px 1px;\n text-align:left;\n }\n\n .lists .see_all div { border-top:1px solid #E5E5E5; padding:5px 10px; }\n \n </style>' \n end", "def accept_list_start list\n case list.type\n when :BULLET then\n @list_index << nil\n @list_width << 1\n when :LABEL, :NOTE then\n @list_index << nil\n @list_width << 2\n when :LALPHA then\n @list_index << 'a'\n @list_width << list.items.length.to_s.length\n when :NUMBER then\n @list_index << 1\n @list_width << list.items.length.to_s.length\n when :UALPHA then\n @list_index << 'A'\n @list_width << list.items.length.to_s.length\n else\n raise RDoc::Error, \"invalid list type #{list.type}\"\n end\n\n @list_type << list.type\n end", "def list_text\n prepend_list_tag + list + append_list_tag\n end", "def print_pretty (list_name, list)\n p list_name.upcase.center (100)\n list.each do |x,y|\n p \"#{x.rjust(50)} : #{y.to_s.ljust(50)} \"\n end\nend", "def list_of(things,opts={})\n raise ArgumentError, 'got nil list of things' if things.nil?\n if !opts.delete(:force_list) && things.empty?\n content_tag(:span,'none',opts)\n else\n kind = things.first.table_name rescue 'items'\n add_class_to_html_options(opts, kind)\n add_class_to_html_options(opts, 'records') if things.first.andand.is_a?(ActiveRecord::Base)\n add_class_to_html_options(opts, 'list')\n add_class_to_html_options(opts, 'empty') if things.blank?\n content_tag(\n :ul,\n things.andand.collect do |thing|\n list_item(thing, opts)\n end.andand.join(' '),\n opts\n )\n end\n end", "def print_list\n \t\tputs \"\\n----------------------------\"\n \t\tputs \"#{@date_created.month}/#{@date_created.day}/#{date_created.year}\"\n \t\tputs \"Your Grocery List:\\n\\n\" \t\t\n \t\tif @list.empty?\n \t\t\tputs \"The List Is Empty!\"\n \t\telse\n\n \t@list.each_with_index { |item, index| puts \"#{index+1}. #{item.qty} #{item.name}\" }\n end\n puts \"\\n----------------------------\"\n end", "def print_list(list)\r\n puts \"-\"*20\r\n list.each do |item,quantity|\r\n puts \"Item:#{item} quantity:#{quantity}\"\r\n end\r\n puts \"-\"*20\r\n list\r\nend", "def pretty_list(list)\n\tlist.each do |item, quantity|\n\t\tputs \"There are #{quantity} #{item} on the grocery list.\"\n\tend\nend", "def print_list; end", "def make_list(list, points)\n res = \"\"\n pts = points >= 0 ? \"(+ #{points})\" : \"(- #{-points})\" \n if list.length != 0\n list.each { |ch| res << (\" * #{ch} #{pts}\\n\") }\n else\n res << (\"(nothing)\\n\")\n end\n res\n end", "def create_list(list)\n print_list(list)\n return list\nend", "def draw_items\n main.newpad items\n @displayed_items = items[current_page * max_items, max_items]\n main.display current_page\n header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages\n end", "def render_list( items, type: :ul, *args )\n non_empty_content_tag( type, *args ) { render_items( items }\n end", "def build_items\n @pdf.move_down(23 + @push_items_table + @push_down)\n\n items_params = determine_items_structure\n items = build_items_data(items_params)\n headers = build_items_header(items_params)\n data = items.prepend(headers)\n\n options = {\n header: true,\n row_colors: [nil, 'ededed'],\n width: x(540, 2),\n cell_style: {\n borders: []\n }\n }\n\n unless items.empty?\n @pdf.font_size(10) do\n @pdf.table(data, options) do\n row(0).background_color = 'e3e3e3'\n row(0).border_color = 'aaaaaa'\n row(0).borders = [:bottom]\n row(items.size - 1).borders = [:bottom]\n row(items.size - 1).border_color = 'd9d9d9'\n end\n end\n end\n end", "def closed_begin_list(list); end", "def listing(list)\n list.each {|item|puts \"* #{item}\"}\n print \"\\n\"\nend", "def render_list(cat)\n\tlink_list = []\n\tc = 1\n\tcat.each do |k,v|\n\t\tputs k\n\t\tv.each do |e|\n\t\t\ttitle = e[:title]\n\t\t\tauthor = e[:author]\n\t\t\tduration = e[:duration]\n\t\t\tlink = e[:link]\n\t\t\ttmp = \" [\" + c.to_s + \"] \" + author + \" — \" + title\n\t\t\ttmp += \" \"*(200-tmp.length) # Crappy right alignment for duration\n\t\t\ttmp += duration\n\t\t\tputs tmp\n\t\t\tc+=1\n\t\t\tlink_list << { :title => title, :author => author, :link => link }\n\t\tend\n\tend\n\treturn link_list\nend", "def createItemList(numbers, list, list_size)\n status = 0\n if list_size > 0\n widest_item = 0\n x = 0\n have = 0\n temp = ''\n if allocListArrays(0, list_size)\n # Create the items in the scrolling list.\n status = 1\n (0...list_size).each do |x|\n number = if numbers then x + 1 else 0 end\n if !self.allocListItem(x, temp, have, number, list[x])\n status = 0\n break\n end\n\n widest_item = [@item_len[x], widest_item].max\n end\n\n if status\n self.updateViewWidth(widest_item);\n\n # Keep the boolean flag 'numbers'\n @numbers = numbers\n end\n end\n else\n status = 1 # null list is ok - for a while\n end\n\n return status\n end", "def block_docbook_lists( text )\n orig_text = text.dup\n delimiter = \"\"\n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ LISTS_CONTENT_RE \n tl,continuation,atts,content = $~[1..4]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</para></listitem>\\n</#{ lD( depth[i] ) }>\\n\"\n depth.pop\n end\n end\n if depth.last.length == tl.length\n lines[line_id - 1] << \"</para></listitem>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = docbook_pba( atts )\n atts = shelve( atts ) if atts\n delimiter = lD(tl)\n lines[line_id] = \"<#{ delimiter }#{ atts }>\\n<listitem><para>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n else\n lines[line_id] = \"<listitem><para>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</para></listitem>\\n</#{ lD( v ) }>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n text != orig_text\n end", "def list_items_in_collection(collection, terminate=false, options={})\n content_tag :ul, class: 'collection-listing' do\n collection.members.inject('') do |output, member|\n output << member_line_item(collection, member, terminate, options)\n end.html_safe\n end\n end", "def list_groceries(list)\n\tlist.each {|item| puts \"* #{item}\"}\n\tputs \"---------------------------\"\nend", "def create_list\n list = SinglyLinkedList.new\n list.insert_at_end 1\n list.insert_at_end 2\n list.insert_at_end 3\n list.insert_at_end 4\n list.insert_at_end 5\n list.insert_at_end 6\n list.insert_at_end 7\n list\nend", "def dump\n current_size = size\n dumped_items = redis.lrange list_id, 0, current_size - 1\n redis.ltrim list_id, current_size, size - 1 \n dumped_items\n end", "def create_list\n @list = Array.new(6) { |i| DexButton.new(@viewport, i) }\n end", "def display_list(list)\n\tlist.each do |list_item|\n\t\tputs \"* #{list_item}\"\n\tend\n\nend", "def list\n longest = @items.map(&:text).max_by(&:length) || 0\n @items.each_with_index do |todo, index|\n printf \"%s: %-#{longest.size+5}s %s\\n\", index+1, todo.text, todo.context\n end\n end", "def print_list\n\t puts \"\"\n\t puts \"\"\n\t\tputs \"#{@list_name}\"\n\t\tprint \"-\" * 40\n\t\t@grocery_list.each {|k, v| puts \"#{k} #{v}\"}\n\t\tputs \"\"\n\t\tget_item\n\tend", "def list_dashboards(lista)\n container = \"<div class='box dashboard'>\"\n unless lista.empty?\n container << '<ul>'\n lista.each do |l|\n container << '<li>'\n container << \"<a href='#{l.url}' alt='#{l.name}' title='clique para ir para o atalho : #{l.name}'>\"\n container << image_tag(l.icon,:alt => l.name)\n container << \"<em>#{l.name}</em>\"\n container << \"</a>\"\n container << '</li>'\n end\n container << '</ul>'\n end\n container << '</div>'\n container.html_safe\n end", "def unordered_list(list_items)\n drapper(\"<ul>#{list.map{ |list_item| \"<li>#{list_item}</li>\" }.join}</ul>\")\n\n\n def button(button_text, class_hash = nil)\n if class_hash\n drapper(\"<button class='#{class_hash[:class]}'>#{button_text}</button>\")\n else\n drapper(\"<button>#{button_text}</button>\")\n end\n end\n end", "def print_list(list)\n\tmax_index = list.length;\n\ti=1\n\twhile i<=max_index\n\tprint \"#{i}. #{hash_to_string(list[i-1])}\".center(get_winsize)\n\tprint \"\\n\"\n\ti +=1\n\tend\nend", "def printHTML(entriesList, out)\n id = 0\n entriesList.each { |heading,entries|\n out.puts \"<h3>#{heading}</h3>\" if heading\n out.puts \"<ul>\"\n entries.each { |entry|\n out.puts \"<li>\"+entry.toHTML(id)+\"</li>\"\n id += 1\n }\n out.puts \"</ul>\"\n }\nend", "def block_docbook_simple_lists( text )\n orig_text = text.dup\n delimiter = \"\"\n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ /^([_]+)(#{A}#{C}) (.*)$/m\n tl,atts,content = $~[1..4]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</member>\\n</simplelist>\\n\"\n depth.pop\n end\n end\n if depth.last.length == tl.length\n lines[line_id - 1] << \"</member>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = docbook_pba( atts )\n atts = shelve( atts ) if atts\n lines[line_id] = \"<simplelist#{ atts }>\\n<member>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n else\n lines[line_id] = \"<member>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</member>\\n</simplelist>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n text != orig_text\n end", "def set(list, list_size, filler_char, highlight, box)\n self.setContents(list, list_size)\n self.setFillerChar(filler_char)\n self.setHighlight(highlight)\n self.setBox(box)\n end", "def append_to_list(found_list, index_num)\r\n\tputs (\"#{(found_list[index_num][6]+', '+found_list[index_num][7]).truncate(25).ljust(25, \" \")} #{found_list[index_num][1].truncate(40).ljust(40,\" \")} #{found_list[index_num][3].truncate(15).ljust(15,\" \")} #{found_list[index_num][0].to_s.truncate(5).ljust(5,\" \")} #{found_list[index_num][4]}\")\t\r\nend", "def create_list(items)\n\titem_list = {}\n\titem_array = items.split(\" \")\n\tdefault_quantity = 1\n\titem_array.each do |item|\n\t\titem_list[item] = default_quantity\n\tend\n\tpretty_list(item_list) \nend", "def draw\n lines = []\n\n indent = @height - 1\n draw_braches(lines, indent)\n\n lines\n end", "def render_items\n @items.reverse_each_with_index do |item, index|\n # Skip if item is already in\n next if item.parent\n\n next_item = @items[index + 1]\n if next_item\n # If there is a nex item isert before it\n next_id = next_item.data[key]\n el = @items.find { |element| element.data[key] == next_id }\n insert_before item, el\n else\n # Else append at the end\n item >> self\n end\n end\n end", "def comment_list(list, base_indent='')\n commented_list = \"\"\n ids = list.split(/,/)\n ids.each do |id|\n id.gsub!(/\\s*$/, '')\n id.gsub!(/^\\s*/, '')\n list_id = \"#{id}\"\n list_id += ',' if id != ids.last\n id.gsub!(/\\=.*$/, '') \n id.gsub!(/\\[.*\\]/, '') \n id.gsub!(/\\s*$/, '')\n id.gsub!(/^\\s*/, '') \n id.gsub!(/;/, '') \n id.gsub!(/\\s*\\:\\s*\\d+/,'') \n doc_id = id.split(/\\s/).last\n doc_id.gsub!(/\\*/, '') \n commented_list += \"#{base_indent}\" if id != ids.first \n commented_list += \"#{@indent}\\t#{list_id} /**< <##{doc_id} description#> */\"\n commented_list += \"\\n\" if id != ids.last \n end\n commented_list \n end", "def createDisplaysList\n for x in 1..@numberOfFloors do\n @floorDisplaysList.append(Display.new(x, DisplayStatus::ON, x))\n # puts \"elevator#{@id} display floor #{@floorDisplaysList[x - 1].id} created\"\n end\n end", "def build\n \n data = heading(:css_location => \"css/html-cutlist.css\").to_s\n \n data += page_title().to_s\n \n # Get all the parts in an array of part hashes.\n all_parts = @parts.grouped\n\n # # Sort parts.\n # all_parts = all_parts.sort { |a, b|\n # a['material'] <=> b['material']\n # # a['thickness'] <=> b['thickness']\n # # a['width'] <=> b['width']\n # # a['length'] <=> b['length']\n # }\n\n # Create an empty array of materials.\n materials = []\n\n # Put all the materials in the list\n all_parts.each { |p|\n materials.push(p['material']) \n }\n\n # Make sure there is only one of each material.\n materials = materials.uniq\n\n # Create a blank hash to put sorted parts into.\n grouped_parts = {}\n\n # Create a new list of hashes that represent the material and then the parts \n # that are of that material (a blank hash).\n materials.each { |m| \n grouped_parts[m] = {}\n }\n\n # Loop through each part, adding it to the right key in the sorted_list.\n all_parts.each { |p| \n\n # Go through the list of materials.\n materials.each { |m|\n\n if p['material'] == m\n \n # If the \"round_dimensions\" setting is on, round the dimension to \n # three decimal places so we don't have a lot of entries in the \n # grouped_parts list like \"3.750000001\", \"3.750000002\", etc... but \n # instead have one entry like \"3.750\". This way grouping behaves \n # as expected.\n rounded_thickness = @options['round_dimensions'] ? format(\"%0.3f\", p['thickness']).to_f : p['thickness']\n \n # Check to see if there is a key for this thickness and if there is \n # append the part to the array of parts.\n if grouped_parts[m][rounded_thickness]\n grouped_parts[m][rounded_thickness] += [p]\n # If there isn't a key for this thickness, create it now and add the \n # part array.\n else\n grouped_parts[m][rounded_thickness] = [p]\n end\n\n end\n\n }\n\n }\n \n # Sort by materials.\n parts_by_material = grouped_parts.sort { |a,b|\n a[0] <=> b[0]\n }\n\n # List all the parts, grouped.\n parts_by_material.each { |t| # t for thickness.\n\n # Sort thicknesses.\n parts_by_thickness = t[1].sort { |a,b|\n a[0] <=> b[0]\n }\n parts_by_thickness.reverse!\n\n # Go through each thickness key.\n parts_by_thickness.each { |p| # p for parts\n\n # Sort parts by width, then length.\n parts = p[1].sort { |a,b|\n a['width'] <=> b['width']\n # TODO: Get sub-sorting by length.\n # a['length'] <=> b['length']\n }\n parts.reverse!\n \n # Create a parts array to store the parts in.\n parts_array = []\n \n # Go through the parts that are of a specific thickness.\n parts.each { |part| \n \n # Check if part is a sheet good.\n if @options[\"show_sheets\"] && part['is_sheet']\n parts_array.push(part)\n end\n\n # Check if part is solid stock.\n if @options[\"show_solids\"] && part['is_solid']\n parts_array.push(part)\n end\n\n # Check if part is hardware.\n if @options[\"show_hardware\"] && part['is_hardware']\n parts_array.push(part)\n end\n # puts \"#{p['sub_assembly']} -- #{p['part_name']} -- #{p['quantity']} -- #{p['material']} -- Sheet? #{p['is_sheet']} -- Solid? #{p['is_solid']} -- Hardware? #{p['is_hardware']} -- #{p['width']} x #{p['length']} x #{p['thickness']}\"\n \n }\n \n # If there are items in the parts_array, then add the section heading \n # and the array of parts. If there are no parts, show nothing.\n if parts_array.length != 0\n data += section_heading(\"#{p[0].to_fraction(true)} #{t[0]}\")\n data += rows(parts_array)\n end\n \n # TODO: Put section footer here, if needed...\n \n }\n }\n \n data += footer().to_s\n \n # Return the results.\n data\n \n end", "def createlist(items)\n new_items = items.split(\" \")\n list = Hash.new\n new_items.each {|item| list[item] = 1}\n prettylist(list)\n # use print_list method\nend", "def unordered_list; end", "def block_textile_lists( text ) \n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ LISTS_CONTENT_RE \n tl,atts,content = $~[1..3]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</li>\\n\\t</#{ lT( depth[i] ) }l>\\n\\t\"\n depth.pop\n end\n end\n if depth.last and depth.last.length == tl.length\n lines[line_id - 1] << '</li>'\n end\n end\n unless depth.last == tl\n depth << tl\n atts = pba( atts )\n atts = shelve( atts ) if atts\n lines[line_id] = \"\\t<#{ lT(tl) }l#{ atts }>\\n\\t<li>#{ content }\"\n else\n lines[line_id] = \"\\t\\t<li>#{ content }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</li>\\n\\t</#{ lT( v ) }l>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n end", "def setContents(list, list_size)\n if !self.createList(list, list_size)\n return\n end\n\n # Set the information in the scrolling list.\n @scroll_field.set(@list, @list_size, false,\n @scroll_field.highlight, @scroll_field.box)\n\n # Clean out the entry field.\n self.setCurrentItem(0)\n @entry_field.clean\n\n # Redraw the widget.\n self.erase\n self.draw(@box)\n end", "def list\n @list_helper ||= ListWrapper.new(self)\n end", "def pretty_in_print(list)\n puts \"---------------------------------------\"\n puts \"These are the items we are gonna buy\"\n list.each {|item, qty| puts \"#{qty} pieces of #{item}\" }\nend", "def print_list(grocery_list)\n line_width = 30\n puts\n puts ('Grocery List'.center(line_width))\n puts\n puts (\"ITEMS\".ljust(line_width/2)) + \"QTY\".rjust(line_width/2)\n puts (\"------------------------------\").center(line_width)\n grocery_list.each { |item, quantity| \n puts (item.ljust(line_width/2)) + quantity.to_s.rjust(line_width/2)\n puts (\"------------------------------\") }\nend", "def accept_list_item_start list_item\n bullet = case @list_type.last\n when :BULLET then\n '*'\n when :NOTE, :LABEL then\n labels = Array(list_item.label).map do |label|\n attributes(label).strip\n end.join \"\\n\"\n\n labels << \":\\n\" unless labels.empty?\n\n labels\n else\n @list_index.last.to_s + '.'\n end\n\n case @list_type.last\n when :NOTE, :LABEL then\n @indent += 2\n @prefix = bullet + (' ' * @indent)\n else\n @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1)\n\n width = bullet.gsub(/\\e\\[[\\d;]*m/, '').length + 1\n\n @indent += width\n end\n end", "def ordered_list; end", "def initialize\n super\n flight_results_list.define_list_elements(list_item: \"div[class*='flightRow']\")\n end", "def make_list(array)\n string = \"\"\n array.each_with_index do |item, index|\n index < array.length-1? c = \", \": c = \"\"\n formatted_item = \"#{index +1}. #{item}#{c}\"\n string = string.concat(formatted_item)\n end\n string\nend", "def remove_whitespace_from_list_items!\n @document.tree.search('li span').each { |span| span.inner_html.strip! }\n end", "def list(name, entries)\n values = entries[0..11].collect do |item|\n {\"listItem\" => item}\n end\n\n push(name, {\"list\" => values})\n end", "def from_list_to_html(list, depth_to_traverse=1000, start_depth=0)\n depth = start_depth\n if list.is_a?(Array) && !list.empty?\n str =''\n str << '<ul>'\n depth += 1\n list.each do |value|\n unless depth > depth_to_traverse\n str << \"<li> #{value} </li> \"\n if value.is_a?(Array) \n str << from_hash_to_html(value, depth_to_traverse, depth)\n end\n end\n end\n str << '</ul> '\n return str\n end\n return ''\n end", "def list_formatter(list)\n\tlist.each do |item, quanity|\n\t\tputs \"we need #{quanity} of #{item}\"\n\tend\nend", "def print_list(list)\r\n puts \"_-\" *25 + \"\\n\\n\"\r\n puts \"Here is your Grocery List: \\n\\n\"\r\n list.each do |item, quantity|\r\n puts \"\\tItem: #{item} \\tAmount: #{quantity}\"\r\n end\r\n puts \"_-\" *25\r\nend", "def humanize_file_list( list, indent=FILE_INDENT )\n\tlisttext = list[0..5].join( \"\\n#{indent}\" )\n\tif list.length > 5\n\t\tlisttext << \" (and %d other/s)\" % [ list.length - 5 ]\n\tend\n\t\n\treturn listtext\nend", "def _non_summary_list(list)\n list_for_display = []\n list.each do |item|\n list_for_display += [item.to_hash]\n end\n\n list_for_display\n end", "def compile_dlist(list_tag, lexer)\n first = lexer.peek\n items = []\n loop do\n term_line = lexer.read\n break if term_line.tag == :eof\n unless term_line.lead_space.size == first.lead_space.size && term_line.tag == list_tag\n lexer.unread term_line\n break\n end\n inner = inner_indent(term_line)\n term = term_line.string[inner.size..-1]\n desc = compile_blocks(lexer, nil){|line|\n line.tag == list_tag && line.lead_space.size == term_line.lead_space.size\n }\n items << [term, desc]\n end\n {list_tag => {line: first.lineno, items: items.compact}}\n end", "def list; end", "def list; end", "def list; end", "def list; end", "def list; end", "def list\n @element.content.map do |paragraph_element|\n line_item = paragraph_element.content.map do |text_element|\n text_exporter.new(text_element).export\n end.join\n\n \"<li>#{line_item}</li>\"\n end.join\n end", "def pretty_list(list)\r\n\tlist.each { |item, quantity| puts \"Item: #{item.capitalize} - Amount: #{quantity}\" }\r\nend", "def accept_list_item_end list_item\n width = case @list_type.last\n when :BULLET then\n 2\n when :NOTE, :LABEL then\n if @prefix then\n @res << @prefix.strip\n @prefix = nil\n end\n\n @res << \"\\n\"\n 2\n else\n bullet = @list_index.last.to_s\n @list_index[-1] = @list_index.last.succ\n bullet.length + 2\n end\n\n @indent -= width\n end", "def closed_end_list(list); end" ]
[ "0.7264258", "0.6973062", "0.6146951", "0.6004018", "0.5907188", "0.5867355", "0.5827932", "0.5822188", "0.5780602", "0.5739241", "0.56009376", "0.5592616", "0.5541733", "0.5504484", "0.54857427", "0.54697794", "0.5468899", "0.54651374", "0.5457361", "0.5425007", "0.5424739", "0.5424047", "0.5396234", "0.53900474", "0.5346268", "0.53446215", "0.53433794", "0.53332955", "0.5325943", "0.5303541", "0.5302786", "0.530101", "0.530027", "0.5283121", "0.5282716", "0.5279954", "0.5279485", "0.5278388", "0.5270881", "0.5270544", "0.5255655", "0.525189", "0.5241428", "0.52409756", "0.5234083", "0.52106446", "0.5203353", "0.52010304", "0.5198225", "0.51947254", "0.5182975", "0.5170781", "0.51706046", "0.5166504", "0.516071", "0.5160393", "0.51554406", "0.5153341", "0.51425236", "0.5127925", "0.5123249", "0.51212305", "0.5120833", "0.51170087", "0.51030976", "0.5090958", "0.50884116", "0.50707155", "0.50616837", "0.50532126", "0.50478256", "0.50462973", "0.50415814", "0.5038469", "0.5035869", "0.50357634", "0.50304043", "0.5023929", "0.5020426", "0.5016858", "0.5016672", "0.50142926", "0.50133884", "0.5009214", "0.49962986", "0.49905628", "0.49900475", "0.498825", "0.49868318", "0.4976296", "0.49750802", "0.4968166", "0.4968166", "0.4968166", "0.4968166", "0.4968166", "0.4966803", "0.49662542", "0.49641767", "0.49583083" ]
0.74732697
0
Builds a ListItem that is flush to +indent+ with type +item_type+
def build_list_item indent, item_type = nil p :list_item_start => [indent, item_type] if @debug list_item = RDoc::Markup::ListItem.new item_type until @tokens.empty? do type, data, column = get if column < indent and not type == :NEWLINE and (type != :INDENT or data < indent) then unget break end case type when :INDENT then unget list_item.push(*parse(indent)) when :TEXT then unget list_item << build_paragraph(indent) when :HEADER then list_item << build_heading(data) when :NEWLINE then list_item << RDoc::Markup::BlankLine.new when *LIST_TOKENS then unget list_item << build_list(column) else raise ParseError, "Unhandled token #{@current_token.inspect}" end end p :list_item_end => [indent, item_type] if @debug return nil if list_item.empty? list_item.parts.shift if RDoc::Markup::BlankLine === list_item.parts.first and list_item.length > 1 list_item end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept_list_item_start list_item\n type = @list_type.last\n\n case type\n when :NOTE, :LABEL then\n bullets = Array(list_item.label).map do |label|\n attributes(label).strip\n end.join \"\\n\"\n\n bullets << \"\\n:\"\n\n @prefix = ' ' * @indent\n @indent += 4\n @prefix << bullets + (' ' * (@indent - 1))\n else\n bullet = type == :BULLET ? '*' : @list_index.last.to_s + '.'\n @prefix = (' ' * @indent) + bullet.ljust(4)\n\n @indent += 4\n end\n end", "def accept_list_item_start list_item\n type = @list_type.last\n\n case type\n when :NOTE, :LABEL then\n bullets = Array(list_item.label).map do |label|\n attributes(label).strip\n end.join \"\\n\"\n\n bullets << \":\\n\" unless bullets.empty?\n\n @prefix = ' ' * @indent\n @indent += 2\n @prefix << bullets + (' ' * @indent)\n else\n bullet = type == :BULLET ? '*' : @list_index.last.to_s + '.'\n @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1)\n width = bullet.length + 1\n @indent += width\n end\n end", "def list_item_start(list_item, list_type)\n case list_type\n when :BULLET, :LALPHA, :NUMBER, :UALPHA then\n \"<li>\"\n when :LABEL, :NOTE then\n Array(list_item.label).map do |label|\n \"<dt>#{to_html label}\\n\"\n end.join << \"<dd>\"\n else\n raise RDoc::Error, \"Invalid list type: #{list_type.inspect}\"\n end\n end", "def accept_list_item_end list_item\n width = case @list_type.last\n when :BULLET then\n 2\n when :NOTE, :LABEL then\n if @prefix then\n @res << @prefix.strip\n @prefix = nil\n end\n\n @res << \"\\n\"\n 2\n else\n bullet = @list_index.last.to_s\n @list_index[-1] = @list_index.last.succ\n bullet.length + 2\n end\n\n @indent -= width\n end", "def accept_list_item_end list_item\n width = case @list_type.last\n when :BULLET then\n 4\n when :NOTE, :LABEL then\n use_prefix\n\n 4\n else\n @list_index[-1] = @list_index.last.succ\n 4\n end\n\n @indent -= width\n end", "def accept_list_item_end list_item\n width = case @list_type.last\n when :BULLET then\n 2\n when :NOTE, :LABEL then\n if @prefix then\n @res << @prefix.strip\n @prefix = nil\n end\n\n @res << \"\\n\" unless res.length == 1\n 2\n else\n bullet = @list_index.last.to_s\n @list_index[-1] = @list_index.last.succ\n bullet.length + 2\n end\n\n @indent -= width\n end", "def accept_list_item_start list_item\n bullet = case @list_type.last\n when :BULLET then\n '*'\n when :NOTE, :LABEL then\n labels = Array(list_item.label).map do |label|\n attributes(label).strip\n end.join \"\\n\"\n\n labels << \":\\n\" unless labels.empty?\n\n labels\n else\n @list_index.last.to_s + '.'\n end\n\n case @list_type.last\n when :NOTE, :LABEL then\n @indent += 2\n @prefix = bullet + (' ' * @indent)\n else\n @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1)\n\n width = bullet.gsub(/\\e\\[[\\d;]*m/, '').length + 1\n\n @indent += width\n end\n end", "def list_style(item); end", "def list_item_with_icon(icon_type, item, caption, truncate_to, custom_tooltip=nil, size=nil)\n list_item = \"<li>\"\n if icon_type.downcase == \"flag\"\n list_item += flag_icon(item.country)\n elsif icon_type == \"data_file\" || icon_type == \"sop\"\n list_item += file_type_icon(item)\n else\n list_item += image_tag_for_key(icon_type.downcase, nil, icon_type.camelize, nil, \"\", false, size)\n end\n item_caption = \" \" + h(caption.blank? ? item.name : caption)\n list_item += link_to truncate(item_caption, :length=>truncate_to), url_for(item), :title => tooltip_title_attrib(custom_tooltip.blank? ? item_caption : custom_tooltip)\n list_item += \"</li>\"\n \n return list_item\n end", "def list_item_with_icon(icon_type, item, caption, truncate_to, custom_tooltip = nil, size = nil)\n list_item = '<li>'\n list_item += if icon_type.casecmp('flag').zero?\n flag_icon(item.country)\n elsif icon_type == 'data_file' || icon_type == 'sop'\n file_type_icon(item)\n else\n image_tag_for_key(icon_type.downcase, nil, icon_type.camelize, nil, '', false, size)\n end\n item_caption = ' ' + (caption.blank? ? item.title : caption)\n list_item += link_to truncate(item_caption, length: truncate_to), url_for(item), 'data-tooltip' => tooltip(custom_tooltip.blank? ? item_caption : custom_tooltip)\n list_item += '</li>'\n\n list_item.html_safe\n end", "def list_item_with_icon(icon_type, item, caption, truncate_to, custom_tooltip = nil, size = nil)\n list_item = '<li>'\n list_item += if icon_type.casecmp('flag').zero?\n flag_icon(item.country)\n elsif icon_type == 'data_file' || icon_type == 'sop'\n file_type_icon(item)\n else\n image_tag_for_key(icon_type.downcase, nil, icon_type.camelize, nil, '', false, size)\n end\n item_caption = ' ' + (caption.blank? ? item.title : caption)\n list_item += link_to truncate(item_caption, length: truncate_to), url_for(item), 'data-tooltip' => tooltip(custom_tooltip.blank? ? item_caption : custom_tooltip)\n list_item += '</li>'\n\n list_item.html_safe\n end", "def list_item_start list_item, list_type\n throw :done if @characters >= @character_limit\n\n case list_type\n when :BULLET, :LALPHA, :NUMBER, :UALPHA then\n \"<p>\"\n when :LABEL, :NOTE then\n labels = Array(list_item.label).map do |label|\n to_html label\n end.join ', '\n\n labels << \" &mdash; \" unless labels.empty?\n\n start = \"<p>#{labels}\"\n @characters += 1 # try to include the label\n start\n else\n raise RDoc::Error, \"Invalid list type: #{list_type.inspect}\"\n end\n end", "def format_list_item(out, options)\n if options[:list] == :ul\n out << \"#{'*' * (options[:ul] + 1)} \"\n elsif options[:list] == :ol\n number = options[:number]\n options[:number] = number.next\n out << \"#{number}. \"\n end\n end", "def list_item_with_icon(icon_type, item, caption, truncate_to, custom_tooltip=nil)\n list_item = \"<li>\"\n unless icon_type.downcase == \"flag\"\n list_item += icon(icon_type.downcase, nil, icon_type.camelize, nil, \"\")\n else\n list_item += flag_icon(item.country)\n end\n item_caption = h(caption.blank? ? item.name : caption)\n list_item += link_to truncate(item_caption, :length=>truncate_to), url_for(item), :title => custom_tooltip.blank? ? item_caption : custom_tooltip\n list_item += \"</li>\"\n return list_item\n end", "def construct_item type, description, options\n type = type.downcase\n if type_allowed? type\n # Create and return a new item of the type passed in\n @@list_types[type.to_sym].new(description, options)\n else\n # Raise the invalid item type error if the type does not exist\n raise UdaciListErrors::InvalidItemType if !type_allowed? type\n end\n end", "def build_list margin\n p :list_start => margin if @debug\n\n list = RDoc::Markup::List.new\n label = nil\n\n until @tokens.empty? do\n type, data, column, = get\n\n case type\n when *LIST_TOKENS then\n if column < margin || (list.type && list.type != type) then\n unget\n break\n end\n\n list.type = type\n peek_type, _, column, = peek_token\n\n case type\n when :NOTE, :LABEL then\n label = [] unless label\n\n if peek_type == :NEWLINE then\n # description not on the same line as LABEL/NOTE\n # skip the trailing newline & any blank lines below\n while peek_type == :NEWLINE\n get\n peek_type, _, column, = peek_token\n end\n\n # we may be:\n # - at end of stream\n # - at a column < margin:\n # [text]\n # blah blah blah\n # - at the same column, but with a different type of list item\n # [text]\n # * blah blah\n # - at the same column, with the same type of list item\n # [one]\n # [two]\n # In all cases, we have an empty description.\n # In the last case only, we continue.\n if peek_type.nil? || column < margin then\n empty = true\n elsif column == margin then\n case peek_type\n when type\n empty = :continue\n when *LIST_TOKENS\n empty = true\n else\n empty = false\n end\n else\n empty = false\n end\n\n if empty then\n label << data\n next if empty == :continue\n break\n end\n end\n else\n data = nil\n end\n\n if label then\n data = label << data\n label = nil\n end\n\n list_item = RDoc::Markup::ListItem.new data\n parse list_item, column\n list << list_item\n\n else\n unget\n break\n end\n end\n\n p :list_end => margin if @debug\n\n if list.empty? then\n return nil unless label\n return nil unless [:LABEL, :NOTE].include? list.type\n\n list_item = RDoc::Markup::ListItem.new label, RDoc::Markup::BlankLine.new\n list << list_item\n end\n\n list\n end", "def create_item\n @item = Fox_Item.new(self, @content.join(\"\\t\"), @icon, @icon)\n end", "def create_items items\n list = RDoc::Markup::List.new :NOTE\n\n items.each do |item|\n item =~ /\\A(.*?(?:\\([^)]+\\))?):\\s*/\n\n title = $1\n body = $'\n\n paragraph = RDoc::Markup::Paragraph.new body\n list_item = RDoc::Markup::ListItem.new title, paragraph\n list << list_item\n end\n\n list\n end", "def create_items items\n list = RDoc::Markup::List.new :NOTE\n\n items.each do |item|\n item =~ /\\A(.*?(?:\\([^)]+\\))?):\\s*/\n\n title = $1\n body = $'\n\n paragraph = RDoc::Markup::Paragraph.new body\n list_item = RDoc::Markup::ListItem.new title, paragraph\n list << list_item\n end\n\n list\n end", "def make_item_list\n end", "def <<(line)\n add(UnorderedListItem.new(line))\n end", "def create_list(items)\n\titem_list = {}\n\titem_array = items.split(\" \")\n\tdefault_quantity = 1\n\titem_array.each do |item|\n\t\titem_list[item] = default_quantity\n\tend\n\tpretty_list(item_list) \nend", "def build_list margin\n p :list_start => margin if @debug\n\n list = RDoc::Markup::List.new\n\n until @tokens.empty? do\n type, data, column, = get\n\n case type\n when :BULLET, :LABEL, :LALPHA, :NOTE, :NUMBER, :UALPHA then\n list_type = type\n\n if column < margin then\n unget\n break\n end\n\n if list.type and list.type != list_type then\n unget\n break\n end\n\n list.type = list_type\n\n case type\n when :NOTE, :LABEL then\n _, indent, = get # SPACE\n if :NEWLINE == peek_token.first then\n get\n peek_type, new_indent, peek_column, = peek_token\n indent = new_indent if\n peek_type == :INDENT and peek_column >= column\n unget\n end\n else\n data = nil\n _, indent, = get\n end\n\n list_item = build_list_item(margin + indent, data)\n\n list << list_item if list_item\n else\n unget\n break\n end\n end\n\n p :list_end => margin if @debug\n\n return nil if list.empty?\n\n list\n end", "def create\n lip = list_item_params list_type_id: params[:list_type_id]\n new_item = current_user.list_items.create(lip)\n respond_with new_item\n end", "def generate_itemdef_drill(type,name)\n generate_itemdef_line(type,name,true,true)\n end", "def list_end_for(list_type)\n case list_type\n when :BULLET, :LALPHA, :NUMBER, :UALPHA then\n \"</li>\"\n when :LABEL, :NOTE then\n \"</dd>\"\n else\n raise RDoc::Error, \"Invalid list type: #{list_type.inspect}\"\n end\n end", "def format_list(items); end", "def create_item(index)\n item = @data[index]\n rect = item_rect(index)\n # Lists\n $game_system.outline_enable = [] if $game_system.outline_enable == nil\n $game_system.outline_complete = [] if $game_system.outline_complete == nil\n \n # Generate Title\n text = ($game_system.outline_complete[item.index] ?\n KGC::Outline::OLINE_COMPLETION_SYMBOL : KGC::Outline::OLINE_INCOMPLETION_SYMBOL) +\n (KGC::Outline::OLINE_SERIAL_NUMBER ? sprintf(\"%0*d : \",\n KGC::Outline::OLINE_SERIAL_NUMBER_DIGITS, item.index + 1) : \"\") +\n item.title\n\n cOutline = CLabel.new(self, rect, text)\n cOutline.active = $game_system.outline_enable[item.index]\n \n return cOutline\n end", "def list_item_from unparsed\n parsed = inner_parse unparsed.join\n RDoc::Markup::ListItem.new nil, *parsed\n end", "def print_list(type='all')\n\n\t\tputs \"{#name} List - #{type} items\"\n\t\tprint '-' * 30 + \"\\n\"\n\n\n\n\t\ttodo_items.each do |item|\n\t\t\tcase type\n\t\t\twhen 'all'\n\t\t\tputs item\n\t\twhen 'complete'\n\t\t\tputs item if item.complete?\n\t\twhen 'incomplete'\n\t\t\tputs item unless item.complete?\n\t\tend\n\t\tend\n\tend", "def random_list( type = 'ul', paragraphs = false, item_num = 2 + rand(7) )\n items = (1..item_num).collect do\n \"<li>\" + (paragraphs ? self.random_p : @texter.random_sentence) + \"</li>\"\n end\n \"<#{type}>\\n\" + items.join(\"\\n\") + \"\\n</#{type}>\"\n end", "def list_item(str, opts = { print: true })\n bullet = color? ? ANSI_CODES[:bold] + ANSI_CODES[:color][:white] + GLYPHS[:bullet] + ANSI_CODES[:reset] : \"*\"\n result = \" \" + bullet + \" \" + str.to_s + \"\\n\"\n print_or_return(result, opts[:print])\n end", "def build_xml(p_item)\r\n xml = \"<#{ELE_ITEM}>\\n\"\r\n unless p_item.id.nil?\r\n xml += \"\\t<#{ELE_ID}>#{p_item.id}</#{ELE_ID}>\\n\"\r\n end\r\n xml += \"\\t<#{ELE_TITLE}>#{p_item.title}</#{ELE_TITLE}>\\n\"\r\n xml += \"\\t<#{ELE_CREATED_ON}><![CDATA[#{format_date(p_item.created_on)}]]></#{ELE_CREATED_ON}>\\n\"\r\n xml += \"\\t<#{ELE_LAST_UPDATED_ON}><![CDATA[#{format_date(p_item.last_updated_on)}]]></#{ELE_LAST_UPDATED_ON}>\\n\"\r\n xml += \"\\t<#{ELE_FIELDS}>\\n\"\r\n p_item.get_fields.each do |name, value|\r\n xml += \"\\t\\t<#{ELE_FIELD} #{ATTR_NAME}='#{name}'><![CDATA[#{value}]]></#{ELE_FIELD}>\\n\"\r\n end\r\n xml += \"\\t</#{ELE_FIELDS}>\\n\"\r\n\r\n # add related items\r\n related_items = p_item.get_related_items\r\n unless related_items.nil? and related_items.empty?\r\n xml += \"<#{ELE_RELATED_ITEMS}>\\n\"\r\n related_items.each do |key, item_ids|\r\n xml += \"<#{key}>\\n\"\r\n item_ids.each do |item_id|\r\n xml += \"<#{ELE_ITEM}>\"\r\n xml += item_id.to_s\r\n xml += \"</#{ELE_ITEM}>\\n\"\r\n end\r\n xml += \"</#{key.to_s.downcase}>\\n\"\r\n end\r\n xml += \"</#{ELE_RELATED_ITEMS}>\\n\"\r\n end\r\n\r\n # set target class\r\n unless p_item.target_class.nil?\r\n xml += \"<#{ELE_TARGET_CLASS}>\"\r\n xml += p_item.target_class\r\n xml += \"</#{ELE_TARGET_CLASS}>\"\r\n end\r\n\r\n xml += \"</#{ELE_ITEM}>\\n\"\r\n end", "def generate_itemdef_line(type,name,isData,isDrill)\n itemdef=File.new('itemdef.csv','a')\n itemdef << name.underscore.humanize << \",\" << name << \",\" << type << \",\" << isData << \",\" << isDrill << \"\\n\"\n itemdef.close;\n end", "def build_item(item,doc)\n xml_item = Nokogiri::XML::Node.new(\"item\",doc)\n\n # Loop through each attributes of item\n item.each do |k,v|\n new_node = Nokogiri::XML::Node.new(\"#{k}\",doc)\n new_node.content = v\n xml_item.add_child(new_node)\n end\n xml_item\n end", "def html_list_item(item)\n tag :li, yield, :id => \"nav_#{item.name}\",\n :title => item.title(@inject[item.name]),\n :class => @current == item ? 'active' : ''\n end", "def create_subitem(item, levels)\n @current_level ||= 0\n\n subitems = item.node.children.accessible.public.shown_in_menu.include_content.order(:position).all.map { |n| n.content }\n\n if item.node.leaf? || subitems.empty? || @current_level == levels\n @current_level = 0 if @current_level == levels\n content = link_to(h(item.content_title), content_node_path(item.node), :title => h(item.content_title))\n content_tag(:li, content, :class => 'link')\n else\n @current_level += 1\n ul = content_tag(:ul, subitems.map { |subitem| create_subitem(subitem, levels) }.join(\"\\n\").html_safe)\n content = link_to(h(item.content_title), content_node_path(item.node), :title => h(item.content_title))\n content_tag(:li, content + ul, :class => 'subitem')\n end\n end", "def build_items(item, limit, index, hierarchical = false, root_path = \"\")\n return \"\" if index > limit || !item.children.present?\n\n html = \"<ul class='#{index == 1 ? \"menu\" : \"sub-menu\"}'>\"\n item.children.order_default.each do |i|\n if i.visible && i.active\n html << \"<li class='#{\"menu-item-has-children\" if i.children.present?} #{\"active\" if i.slug == params[:menu_id] || i.slug == request.original_fullpath.match(/(\\D+\\/{1}|\\D+)/)[0].gsub('/', '')}'>\"\n\n if i.external_link.blank?\n if hierarchical\n html << \"<a href='#{root_path}/#{i.slug}'>#{i.name}</a>\"\n else\n html << \"<a href='/#{i.slug}'>#{i.name}</a>\"\n end\n else\n html << \"<a href='#{i.external_link}' rel='#{(i.follow || i.follow.nil?) ? \"follow\" : \"nofollow\"}' target='#{i.target.blank? ? '_self' : i.target}'>#{i.name}</a>\"\n end\n\n html << build_items(i, limit, index + 1, hierarchical, root_path + \"/#{i.slug}\")\n html << \"</li>\"\n end\n end\n html << \"</ul>\"\n html.html_safe\n end", "def start_special_list_item\n end", "def build_menu_items_extended (i, index, active_ids = [], options)\n\n return \"\" if index > options[:limit]\n html = \"\"\n if i.visible && i.active\n item_class = build_item_class(i, options, active_ids)\n html << \"<li #{\"class='#{item_class}'\" unless item_class.blank?} >\"\n\n locale_prefix = \"/#{I18n.locale.to_s}\" if options[:with_locale]\n locale_prefix ||= ''\n if i.external_link.blank?\n html << \"<a #{\"class='#{options[:a_class]}'\" if options[:a_class]} href='#{locale_prefix}#{i.real_slug(options[:hierarchical])}'>#{i.name}</a>\"\n else\n html << \"<a #{\"class='#{options[:a_class]}'\" if options[:a_class]} href='#{i.external_link}' #{\"rel='nofollow'\" unless i.follow || i.follow.nil?} #{\"target='#{i.target}'\" unless (i.target.blank? || i.target == '_self') }>#{i.name}</a>\"\n end\n\n items_html = \"\"\n\n i.children.order_default.each do |item_child|\n items_html << build_menu_items_extended(item_child, index + 1, active_ids, options)\n end\n\n content_item_class = [item_class, options[:content_item_class]].compact.join(\" \")\n i.contents.displayed.order_default.each do |content|\n next if ((options[:content_type].blank? || (options[:content_type].exclude?(content.type.to_s))) && (!options[:all_content_types]))\n items_html << \"<li #{\"class='#{content_item_class}'\" unless content_item_class.blank?}>\"\n items_html << \"<a #{\"class='#{options[:a_class]}'\" if options[:a_class]} href='#{locale_prefix}#{content.slug}'>#{content.title}</a>\" if content.respond_to?(\"slug\")\n items_html << \"</li>\"\n end\n\n unless items_html.empty?\n html << \"<div class='#{options[:ul_nested_wrapper_class]}'>\" unless options[:ul_nested_wrapper_class].nil?\n html << \"<ul #{\"class='#{options[:ul_nested_class]}'\" if options[:ul_nested_class]}>\"\n html << items_html\n html << \"</ul>\"\n html << \"</div>\" unless options[:ul_nested_wrapper_class].nil?\n end\n html << \"</li>\"\n end\n html.html_safe\n end", "def special_list_item_line(text)\n end", "def generate_itemdef_profile(type,name)\n generate_itemdef_line(type,name,false,false)\n end", "def generate_itemdef_data(type,name)\n generate_itemdef_line(type,name,true,false)\n end", "def to_s type = nil\n @items.join( get_separator( type ) )\n end", "def add_list_definition(style); end", "def render_list( items, type: :ul, *args )\n non_empty_content_tag( type, *args ) { render_items( items }\n end", "def addItem(item)\n item_number = @list_size\n widest_item = self.WidestItem\n temp = ''\n have = 0\n\n if self.allocListArrays(@list_size, @list_size + 1) &&\n self.allocListItem(item_number, temp, have,\n if @numbers then item_number + 1 else 0 end,\n item)\n # Determine the size of the widest item.\n widest_item = [@item_len[item_number], widest_item].max\n\n self.updateViewWidth(widest_item)\n self.setViewSize(@list_size + 1)\n end\n end", "def length(item_type = nil)\n item_type ||= :item\n # List items return an item length of 1 to enable summation of list/section lengths\n item_type == :item ? 1 : super(item_type)\n end", "def generate_item(item)\n item\n end", "def change_indent plus\n super(plus)\n puts plus ? \"<li><ul class=\\\"pre\\\">\" : \"<li class =\\\"none\\\">LAST</li> </ul></li>\"\n end", "def heredoc_indent_type(node); end", "def insertItem(item)\n widest_item = self.WidestItem\n temp = ''\n have = 0\n\n if self.allocListArrays(@list_size, @list_size + 1) &&\n self.insertListItem(@current_item) &&\n self.allocListItem(@current_item, temp, have,\n if @numbers then @current_item + 1 else 0 end,\n item)\n # Determine the size of the widest item.\n widest_item = [@item_len[@current_item], widest_item].max\n\n self.updateViewWidth(widest_item)\n self.setViewSize(@list_size + 1)\n self.resequence\n end\n end", "def parse_list_marker(line, offset, indent)\n rest = line.slice(offset, line.length)\n match = nil\n spaces_after_marker = nil\n data = OpenStruct.new({\n :type => nil,\n :tight => true, # lists are tight by default\n :bullet_char => nil,\n :start => nil,\n :delimiter => nil,\n :padding => nil,\n :markerOffset => indent \n })\n\n return nil if rest.match(HRULE_REGEX)\n \n if match = rest.match(BULLET_LIST_MARKER_REGEX)\n spaces_after_marker = match[1].length\n data.type = 'Bullet'\n data.bullet_char = match[0][0]\n\n elsif match = rest.match(ORDERED_LIST_MARKER_REGEX)\n spaces_after_marker = match[3].length\n data.type = 'Ordered'\n data.start = match[1].to_i\n data.delimiter = match[2]\n else\n return nil\n end\n\n blank_item = (match[0].length == rest.length)\n\n if (spaces_after_marker >= 5 || spaces_after_marker < 1 || blank_item)\n data.padding = match[0].length - spaces_after_marker + 1\n else\n data.padding = match[0].length\n end\n data\n end", "def fb_list_item(options={}, &block)\n content = capture(&block)\n options.merge!(:class=>'list_item clearfix')\n concat(content_tag(:div,content,stringify_vals(options)),block.binding)\n end", "def create_item(index)\n item = @data[index]\n rect = item_rect(index, true)\n\n case index\n when 0\n if @actor.two_swords_style\n kindDesc = Vocab::weapon1\n else\n kindDesc = Vocab::weapon\n end\n when 1\n if @actor.two_swords_style\n kindDesc = Vocab::weapon2\n else\n kindDesc = Vocab::armor1\n end\n when 2\n kindDesc = Vocab::armor2\n when 3\n kindDesc = Vocab::armor3\n when 4\n kindDesc = Vocab::armor4\n end\n \n rect.y += WLH*index \n equipItem = UCEquipItem.new(self, item, rect, kindDesc)\n \n f = Font.new()\n f.color = system_color\n equipItem.cEquipKind.font = f\n return equipItem\n end", "def test_it_replaces_asterisks_with_li_tags_in_ordered_lists\n ordered = OrderedListParser.new(\"1. Sushi\\n2. Barbeque\\n3. Mexican\")\n expected = \"\\t<li>Sushi</li>\\n\\t<li>Barbeque</li>\\n\\t<li>Mexican</li>\\n\"\n result = ordered.list_item_marker\n assert_equal expected, result\n end", "def pbItemEditor\n selection = 0\n items = [\n [_INTL(\"Internal Name\"),ReadOnlyProperty,_INTL(\"Internal name that appears in constructs like PBItems::XXX.\")],\n [_INTL(\"Item Name\"),ItemNameProperty,_INTL(\"Name of the item as displayed by the game.\")],\n [_INTL(\"Item Name Plural\"),ItemNameProperty,_INTL(\"Plural name of the item as displayed by the game.\")],\n [_INTL(\"Pocket\"),PocketProperty,_INTL(\"Pocket in the bag where the item is stored.\")],\n [_INTL(\"Purchase price\"),LimitProperty.new(999999),_INTL(\"Purchase price of the item.\")],\n [_INTL(\"Description\"),StringProperty,_INTL(\"Description of the item\")],\n [_INTL(\"Use Out of Battle\"),EnumProperty.new([\n _INTL(\"Can't Use\"),_INTL(\"On a Jermon\"),_INTL(\"Use directly\"),\n _INTL(\"TM\"),_INTL(\"HM\"),_INTL(\"On Jermon reusable\")]),\n _INTL(\"Specifies how this item can be used outside of battle.\")],\n [_INTL(\"Use In Battle\"),EnumProperty.new([\n _INTL(\"Can't Use\"),_INTL(\"On a Jermon\"),_INTL(\"Use directly\"),\n _INTL(\"On Jermon reusable\"),_INTL(\"Use directly reusable\")]),\n _INTL(\"Specifies how this item can be used within a battle.\")],\n [_INTL(\"Special Items\"),EnumProperty.new([\n _INTL(\"None of Below\"),_INTL(\"Mail\"),_INTL(\"Mail with Pictures\"),\n _INTL(\"Snag Ball\"),_INTL(\"Jermo Ball\"),_INTL(\"Plantable Berry\"),\n _INTL(\"Key Item\"),_INTL(\"Evolution Stone\"),_INTL(\"Fossil\"),\n _INTL(\"Apricorn\"),_INTL(\"Type-boosting Gem\"),_INTL(\"Mulch\"),\n _INTL(\"Mega Stone\")]),\n _INTL(\"For special kinds of items.\")],\n [_INTL(\"Machine\"),MoveProperty,_INTL(\"Move taught by this TM or HM.\")]\n ]\n pbListScreenBlock(_INTL(\"Items\"),ItemLister.new(selection,true)){|button,trtype|\n if trtype\n if button==Input::A\n if trtype>=0\n if Kernel.pbConfirmMessageSerious(\"Delete this item?\")\n data = readSerialRecords(\"Data/items.dat\")\n removeConstantValue(PBItems,trtype)\n data.delete_if{|item| item[0]==trtype }\n for x in data\n p x if data[0]==0\n end\n writeSerialRecords(\"Data/items.dat\",data)\n pbSaveItems\n Kernel.pbMessage(_INTL(\"The item was deleted.\"))\n end\n end\n elsif button==Input::C\n selection = trtype\n if selection<0\n newid = pbItemEditorNew(nil)\n if newid>=0\n selection = newid\n end\n else\n data = [getConstantName(PBItems,selection)]\n itemdata = readItemList(\"Data/items.dat\")\n data.push(itemdata[selection][ITEMNAME])\n data.push(itemdata[selection][ITEMPLURAL])\n data.push(itemdata[selection][ITEMPOCKET])\n data.push(itemdata[selection][ITEMPRICE])\n data.push(itemdata[selection][ITEMDESC])\n data.push(itemdata[selection][ITEMUSE])\n data.push(itemdata[selection][ITEMBATTLEUSE])\n data.push(itemdata[selection][ITEMTYPE])\n data.push(itemdata[selection][ITEMMACHINE])\n save = pbPropertyList(data[ITEMNAME],data,items,true)\n if save\n itemdata[selection][ITEMNAME] = data[ITEMNAME]\n itemdata[selection][ITEMPLURAL] = data[ITEMPLURAL]\n itemdata[selection][ITEMPOCKET] = data[ITEMPOCKET]\n itemdata[selection][ITEMPRICE] = data[ITEMPRICE]\n itemdata[selection][ITEMDESC] = data[ITEMDESC]\n itemdata[selection][ITEMUSE] = data[ITEMUSE]\n itemdata[selection][ITEMBATTLEUSE] = data[ITEMBATTLEUSE]\n itemdata[selection][ITEMTYPE] = data[ITEMTYPE]\n itemdata[selection][ITEMMACHINE] = data[ITEMMACHINE]\n writeSerialRecords(\"Data/items.dat\",itemdata)\n pbSaveItems\n end\n end\n end\n end\n }\nend", "def assign_types_to_lines(margin = 0, level = 0)\n while line = @lines.next\n if line.blank? then\n line.stamp :BLANK, level\n next\n end\n\n # if a line contains non-blanks before the margin, then it must belong\n # to an outer level\n\n text = line.text\n\n for i in 0...margin\n if text[i] != SPACE\n @lines.unget\n return\n end\n end\n\n active_line = text[margin..-1]\n\n # Rules (horizontal lines) look like\n #\n # --- (three or more hyphens)\n #\n # The more hyphens, the thicker the rule\n #\n\n if /^(---+)\\s*$/ =~ active_line\n line.stamp :RULE, level, $1.length-2\n next\n end\n\n # Then look for list entries. First the ones that have to have\n # text following them (* xxx, - xxx, and dd. xxx)\n\n if SIMPLE_LIST_RE =~ active_line\n offset = margin + $1.length\n prefix = $2\n prefix_length = prefix.length\n\n flag = case prefix\n when \"*\",\"-\" then :BULLET\n when /^\\d/ then :NUMBER\n when /^[A-Z]/ then :UPPERALPHA\n when /^[a-z]/ then :LOWERALPHA\n else raise \"Invalid List Type: #{self.inspect}\"\n end\n\n line.stamp :LIST, level+1, prefix, flag\n text[margin, prefix_length] = \" \" * prefix_length\n assign_types_to_lines(offset, level + 1)\n next\n end\n\n if LABEL_LIST_RE =~ active_line\n offset = margin + $1.length\n prefix = $2\n prefix_length = prefix.length\n\n next if handled_labeled_list(line, level, margin, offset, prefix)\n end\n\n # Headings look like\n # = Main heading\n # == Second level\n # === Third\n #\n # Headings reset the level to 0\n\n if active_line[0] == ?= and active_line =~ /^(=+)\\s*(.*)/\n prefix_length = $1.length\n prefix_length = 6 if prefix_length > 6\n line.stamp :HEADING, 0, prefix_length\n line.strip_leading(margin + prefix_length)\n next\n end\n\n # If the character's a space, then we have verbatim text,\n # otherwise\n\n if active_line[0] == SPACE\n line.strip_leading(margin) if margin > 0\n line.stamp :VERBATIM, level\n else\n line.stamp :PARAGRAPH, level\n end\n end\n end", "def opening(type, parent)\n case type.name.to_sym\n when :h1\n \"# \"\n when :li\n parent.eql?(:ul) ? \" - \" : \" \"+(@li_counter+=1).to_s+\". \"\n when :ol\n @li_counter = 0\n \"\"\n when :ul\n \"\"\n when :h2\n \"## \"\n when :h3\n \"### \"\n when :h4\n \"#### \"\n when :h5\n \"##### \"\n when :h6\n \"###### \"\n when :em\n \"*\"\n when :strong\n \"**\"\n when :blockquote\n # remove leading newline\n type.children.first.value = \"\"\n \"> \"\n when :code\n parent.eql?(:pre) ? \" \" : \"`\"\n when :a\n \"[\"\n when :img\n \"![\"\n when :hr\n \"----------\\n\\n\"\n when :root\n \"\"\n else\n @errors << \"unknown start tag: \"+type.name.to_s\n \"\"\n end\n end", "def li(node)\n level = node[:parent][:level]\n type = node[:parent][:type]\n if node[:close]\n \"<ParaStyle:#{type}#{level}>#{node[:value]}\"\n else\n \"<ParaStyle:#{type}#{level}>#{node[:value]}\\n\"\n end\n end", "def start_special_list(list_type)\n end", "def transform_list_items( str, rs )\n\t\t\t@log.debug \" Transforming list items\"\n\n\t\t\t# Trim trailing blank lines\n\t\t\tstr = str.sub( /\\n{2,}\\z/, \"\\n\" )\n\t\t\tstr.gsub( ListItemRegexp ) {|line|\n\t\t\t\t@log.debug \" Found item line %p\" % line\n\t\t\t\tleading_line, item = $1, $4\n\t\t\t\tseparating_lines = $5\n\n\t\t\t\tif leading_line or /\\n{2,}/.match(item) or not separating_lines.empty? then\n\t\t\t\t\t@log.debug \" Found leading line or item has a blank\"\n\t\t\t\t\titem = apply_block_transforms( outdent(item), rs )\n\t\t\t\telse\n\t\t\t\t\t# Recursion for sub-lists\n\t\t\t\t\t@log.debug \" Recursing for sublist\"\n\t\t\t\t\titem = transform_lists( outdent(item), rs ).chomp\n\t\t\t\t\titem = apply_span_transforms( item, rs )\n\t\t\t\tend\n\n\t\t\t\t%{<li>%s</li>\\n} % item\n\t\t\t}\n\t\tend", "def li; self.list_item = true; self; end", "def make_item(object_type_name)\n\n ot = ObjectType.find_by(name: object_type_name)\n raise \"Could not find object type #{name}\" unless ot\n\n Item.make({ quantity: 1, inuse: 0 }, sample: self, object_type: ot)\n\n end", "def new_nav_helper style, tag_type\n nav_links = ''\n\n nav_items.each do |item|\n nav_links << \"<#{tag_type}><a href='#{item[:url]}' class='#{style} #{active? item[:url]}'>#{item[:title]}</a></#{tag_type}>\"\n end\n\n nav_links.html_safe \n end", "def add(type, description, options={})\n type = type.downcase\n if type == 'todo' then @items.push TodoItem.new(description, options) #uses ToDoItem class in todo.rb\n elsif type == 'event' then @items.push EventItem.new(description, options) #uses EventItem class in event.rb\n elsif type == 'link' then @items.push LinkItem.new(description, options) #usesLinkItem class in event.rb\n else raise UdaciListErrors::InvalidItemType,\n \"'#{type}' is not a valid data type\" #raise error if type is not one of the 3 required\n end\n end", "def accept_list_item_start list_item\n case @list_type.last\n when :NOTE, :LABEL then\n Array(list_item.label).map do |label|\n tt_sections label\n end.flatten\n end\n end", "def initialize type = nil, *items\n @type = type\n @items = []\n @items.concat items\n end", "def print_item(item)\n content = item.value\n\n case item.type\n when :string, :float, :integer then print content\n when :ident then print value_of(content)\n when :separator then print \"\\t\" if content == ','\n end\n end", "def mobile_list_item(item, options = {})\n raise \"Hash with keys :name and :url needed\" unless item.has_key?(:name) && item.has_key?(:url)\n effect = options.delete(:effect) || nil\n icon_class = item.delete(:icon) || nil\n options[:class] = effect if effect \n options[:target] = item[:target] if item.has_key?(:target)\n counter = item.has_key?(:count) ? item_count(item.delete(:count)) : \"\"\n \n content_tag(:li, link_to(item[:name], item[:url], options) + counter, :class => icon_class)\n end", "def add(type, description, options={})\n type = type.downcase\n add_item construct_item(type, description, options)\n end", "def add_item(payload)\n if @first_item.nil?\n @first_item = LinkedListItem.new(payload)\n @size += 1\n # else\n # @first_item\n # until item.last?\n # item = item.next_list_item\n # end\n # item.next_list_item = LinkedListItem.new(payload)\n # @size += 1\n end\n end", "def add_line_item(params)\r\n # Creates line items counter necessary for prefix.\r\n @LINE_ITEMS = 0 if !@LINE_ITEMS \r\n @LINE_ITEMS += 1 # VALUE REQUIRED IN:\r\n prefix = \"LV3_ITEM#{@LINE_ITEMS}_\" # USA | CANADA\r\n @PARAM_HASH[prefix + 'UNIT_COST'] = params[:unit_cost] # * *\r\n @PARAM_HASH[prefix + 'QUANTITY'] = params[:quantity] # * *\r\n @PARAM_HASH[prefix + 'ITEM_SKU'] = params[:item_sku] || '' # *\r\n @PARAM_HASH[prefix + 'ITEM_DESCRIPTOR'] = params[:descriptor] || '' # * *\r\n @PARAM_HASH[prefix + 'COMMODITY_CODE'] = params[:commodity_code] || '' # * *\r\n @PARAM_HASH[prefix + 'PRODUCT_CODE'] = params[:product_code] || '' # * \r\n @PARAM_HASH[prefix + 'MEASURE_UNITS'] = params[:measure_units] || '' # * *\r\n @PARAM_HASH[prefix + 'ITEM_DISCOUNT'] = params[:item_discount] || '' # *\r\n @PARAM_HASH[prefix + 'TAX_RATE'] = params[:tax_rate] || '' # * \r\n @PARAM_HASH[prefix + 'GOODS_TAX_RATE'] = params[:goods_tax_rate] || '' # *\r\n @PARAM_HASH[prefix + 'TAX_AMOUNT'] = params[:tax_amount] || '' # * \r\n @PARAM_HASH[prefix + 'GOODS_TAX_AMOUNT'] = params[:goods_tax_amount] || '' # *\r\n @PARAM_HASH[prefix + 'CITY_TAX_RATE'] = params[:city_tax_rate] || '' #\r\n @PARAM_HASH[prefix + 'CITY_TAX_AMOUNT'] = params[:city_tax_amount] || '' #\r\n @PARAM_HASH[prefix + 'COUNTY_TAX_RATE'] = params[:county_tax_rate] || '' #\r\n @PARAM_HASH[prefix + 'COUNTY_TAX_AMOUNT'] = params[:county_tax_amount] || '' #\r\n @PARAM_HASH[prefix + 'STATE_TAX_RATE'] = params[:state_tax_rate] || '' #\r\n @PARAM_HASH[prefix + 'STATE_TAX_AMOUNT'] = params[:state_tax_amount] || '' #\r\n @PARAM_HASH[prefix + 'CUST_SKU'] = params[:cust_sku] || '' #\r\n @PARAM_HASH[prefix + 'CUST_PO'] = params[:cust_po] || '' #\r\n @PARAM_HASH[prefix + 'SUPPLEMENTAL_DATA'] = params[:supplemental_data] || '' #\r\n @PARAM_HASH[prefix + 'GL_ACCOUNT_NUMBER'] = params[:gl_account_number] || '' #\r\n @PARAM_HASH[prefix + 'DIVISION_NUMBER'] = params[:division_number] || '' #\r\n @PARAM_HASH[prefix + 'PO_LINE_NUMBER'] = params[:po_line_number] || '' #\r\n @PARAM_HASH[prefix + 'LINE_ITEM_TOTAL'] = params[:line_item_total] || '' # * \r\n end", "def line_item_builder(key)\n line_items = \"\"\n number_of_items = @basket[key] unless key == :TOTAL\n\n case key\n when :CH1\n for i in 1..number_of_items \n line_items += \"#{key} #{get_item_price(key)}\\n\"\n end\n when :MK1\n for i in 1..number_of_items \n line_items += \"#{key} #{get_item_price(key)}\\n\"\n line_items += \" CHMK #{get_discount_price(:CHMK)}\\n\" if number_of_items > 0 && i == 1 && @basket[:CH1]\n end\n when :CF1\n for i in 1..number_of_items \n line_items += \"#{key} #{get_item_price(key)}\\n\"\n line_items += \" BOGO #{get_discount_price(:BOGO)}\\n\" if number_of_items >= 2 && i <= number_of_items / 2 \n end\n when :AP1\n for i in 1..number_of_items\n line_items += \"#{key} #{get_item_price(key)}\\n\"\n line_items += \" APPL #{get_discount_price(:APPL)}\\n\" if number_of_items >= 3 \n end\n when :TOTAL\n line_items += \" #{get_basket_total}\\n\"\n else\n line_items += \"Invalid item\"\n end\n\n line_items\n end", "def create_list(item, quantity = 1)\n\tlist = {}\n\tsplit_item = item.split(\" \")\n\tsplit_item.each do |item_name|\n\t\tlist[item_name] = quantity\n\tend\n\treturn list\nend", "def html_index(item_type)\n @item_type = item_type\n @items = @list.list_items.by_type(item_type, order: true).includes(:item)\n body_class << (body_class.delete(item_type) + '-list')\n render :index\n end", "def navigation_item(item, url = {}, separate = false, &block)\n if block_given?\n return unless yield\n end\n path = (url.empty? ? self.send(\"#{item}_path\".to_sym) : url)\n item_class = (separate ? 'separate' : '')\n out = \"<li id=\\\"#{item}_nav\\\" class=\\\"#{item_class}\\\">\" \n out << link_to(\"#{item.to_s.split('_').collect{|e| e.capitalize}.join(' ')}\", \n path, :class => (@active == \"#{item}\" ? 'active' : ''))\n out << \"</li>\"\n end", "def indent str\n if @format == :markdown\n ' ' + CGI.escapeHTML(str)\n else\n if str.end_with?(\"</li>\")\n str\n else\n \"<br />\" + str\n end\n end\nend", "def generate_header_item(item)\n item\n end", "def block_docbook_lists( text )\n orig_text = text.dup\n delimiter = \"\"\n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ LISTS_CONTENT_RE \n tl,continuation,atts,content = $~[1..4]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</para></listitem>\\n</#{ lD( depth[i] ) }>\\n\"\n depth.pop\n end\n end\n if depth.last.length == tl.length\n lines[line_id - 1] << \"</para></listitem>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = docbook_pba( atts )\n atts = shelve( atts ) if atts\n delimiter = lD(tl)\n lines[line_id] = \"<#{ delimiter }#{ atts }>\\n<listitem><para>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n else\n lines[line_id] = \"<listitem><para>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</para></listitem>\\n</#{ lD( v ) }>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n text != orig_text\n end", "def create(type, *args)\n if type.kind_of?(Class) && type < TkcItem\n # do nothing\n elsif TkcItem.type2class(type.to_s)\n type = TkcItem.type2class(type.to_s)\n else\n fail ArgumentError, \"type must a subclass of TkcItem class, or a string in CItemTypeToClass\"\n end\n type.create(self, *args)\n end", "def initialize(children = [], properties = {})\n super(ListItem.ast_type, children, properties)\n end", "def new_list(item_String, quantity = 1)\n $list = []\n array_strings = item_String.split\n array_strings.each do |element|\n \tlist_item = {\n \t\tquantity: quantity,\n \t\titem: element\n \t}\n \t $list.push(list_item) \n \tend\nend", "def build_items\n @pdf.move_down(23 + @push_items_table + @push_down)\n\n items_params = determine_items_structure\n items = build_items_data(items_params)\n headers = build_items_header(items_params)\n data = items.prepend(headers)\n\n options = {\n header: true,\n row_colors: [nil, 'ededed'],\n width: x(540, 2),\n cell_style: {\n borders: []\n }\n }\n\n unless items.empty?\n @pdf.font_size(10) do\n @pdf.table(data, options) do\n row(0).background_color = 'e3e3e3'\n row(0).border_color = 'aaaaaa'\n row(0).borders = [:bottom]\n row(items.size - 1).borders = [:bottom]\n row(items.size - 1).border_color = 'd9d9d9'\n end\n end\n end\n end", "def create_item(index)\n item = @data[index]\n rect = item_rect(index, true)\n \n shopItem = UCShopItem.new(self, item, rect,\n SHOP_CONFIG::ITEM_NUMBER_PATTERN)\n \n shopItem.cItemPrice.align = 2\n shopItem.cItemPossess.align = 2 \n shopItem.cItemPossess.font = Font.shop_possess_font\n shopItem.ucItemNumber.cLabelNumber.align = 2\n shopItem.ucItemNumber.min = 0\n shopItem.ucItemNumber.max = shopItem.inventory_quantity\n return shopItem\n end", "def add_item_text(text, id, type)\n # return normal text if range is 0 or the option isn't used for this type\n return text if Items.range(id) == 0\n # get scope\n scope = $data_items[id].scope\n # iterate through configuration\n Config::ITEM_DATA_MODE.each_index {|i|\n # if current option was set up for this type\n if Config::ITEM_DATA_MODE[i] == type\n # add extra information to result text\n case i\n when 0\n next if scope == 0 || scope == 7\n text += case Items.type(id)[0]\n when SHOOT then Cache::ScopeOne.include?(scope) ? ' (Shooter)' : ' (Thruster)'\n when HOMING then Cache::ScopeOne.include?(scope) ? ' (Homing)' : ' (S. Homing)'\n when DIRECT then Cache::ScopeOne.include?(scope) ? ' (Selector)' : ' (Shockwave)'\n when BEAM then Cache::ScopeOne.include?(scope) ? ' (Beam)' : ' (Fullscreen)'\n when TRAP then ' (Trap)'\n when TIMED then ' (Timed)'\n when SUMMON then ' (Summoner)'\n end\n when 1 then text += ' (explodes)' if Items.type(id)[1] > 0\n when 2\n number = Items.range(id)\n number = 1.0 if number < 1.0\n text += \" R: #{number}\"\n end\n end}\n # return result text\n return text\n end", "def create_item(index)\n item = @data[index]\n rect = item_rect(index, true)\n \n ucItem = UCItem.new(self, item, rect)\n ucItem.active = enable?(item)\n \n if $game_party.newest_items.include?(item)\n ucItem.cItemName.font.color = Color.new_item_color\n ucItem.cItemNumber.font.color = Color.new_item_color\n end\n \n return ucItem\n end", "def build_item_class(i, options, active_ids)\n\n item_class = []\n\n item_class << options[:item_class]\n item_class << i.css_class\n\n if i.has_children?\n item_class << options[:item_with_children_class]\n else\n item_class << options[:item_without_children_class]\n end\n\n item_class << options[:active_class] if i.slug == params[:menu_id] || i.slug == request.original_fullpath.match(/(\\D+\\/{1}|\\D+)/)[0].gsub('/', '') || active_ids.include?(i.id)\n item_class.compact.join(\" \")\n end", "def create\n\n nested = params[:list].delete(:list_items_attributes)\n\n @list = List.new( params[:list] )\n @list.user = current_user\n\n records = nested.collect do |_, fields| \n\n ListItem.new( { \"list\" => @list }.merge( fields ) ) if !item_blank?( fields )\n\n end.compact\n\n respond_to do |format|\n if @list.save && records.map( &:save ).all?\n\n format.html { redirect_to @list, notice: 'List was successfully created.' }\n format.json { render json: @list, status: :created, location: @list }\n\n else\n\n format.html { render action: \"new\" }\n format.json { render json: @list.errors, status: :unprocessable_entity }\n\n end\n end\n end", "def create_todo_item(name, list_id)\n data = {\n item: {\n name: name\n }\n }\n rest(\"post\", \"lists/#{list_id}/items\", data)\n end", "def generate_object_types_list\n #@items = options.objects if options.objects\n @items = [\n \"App Level Classes\",\n \"Entity Classes\",\n \"Collection Classes\",\n \"Geom Classes\",\n \"UI Classes\",\n \"Observer Classes\",\n \"Core Ruby Classes\"\n ]\n @list_title = \"Object Index\"\n @list_type = \"object_types\"\n\n # optional: the specified stylesheet class\n # when not specified it will default to the value of @list_type\n @list_class = \"class\"\n\n # Generate the full list html file with named feature_list.html\n # @note this file must be match the name of the type\n asset(url_for_list(@list_type), erb(:full_list))\nend", "def pretty_list(list)\n # new_list = \"\"\n # list.each { |item, quantity| new_list << \"You want #{quantity} #{item}\\n\" }\n # return new_list\n list.each { |item, quantity| puts \"You want #{quantity} #{item}\\n\" }\nend", "def new_item(item)\n unless item.include?(File::SEPARATOR)\n prefixes = [\n config.get(:sfn_parameters, :directory),\n \"infrastructure\",\n \"stacks\",\n ].compact\n prefix = prefixes.find_all do |dir|\n File.directory?(dir)\n end\n if prefix.size > 1\n raise ArgumentError.new \"Unable to auto-determine directory for item! Multiple directories found. \" \\\n \"(detected: #{prefix.join(\", \")})\"\n elsif prefix.empty?\n raise ArgumentError.new \"No existing parameter directories found. Please create required directory. \" \\\n \"(checked: #{prefixes.join(\", \")})\"\n end\n File.join(prefix.first, \"#{item}.json\")\n end\n end", "def item\n case item_type\n when 'group'\n group\n end\n end", "def item\n case item_type\n when 'group'\n group\n end\n end", "def define_menu_items\n check_attributes\n @menu_description.concat(\"\\n #{set_boundaries}\")\n add_menu_item(\"All tasks to a person in the given #{time_string}.\", 1)\n add_menu_item(\"Worktime of a person in that #{time_string}.\", 2)\n add_menu_item(\"All tasks running during the interval.\", 3)\n add_menu_item(\"Write Query result to csv-file.\", 4)\n add_menu_item(\"Cancel and return to previous menu.\", 5)\n end", "def add_indentation(p_size, p_type)\n delimiter_result = p_size.send(p_type)\n self.insert(0, delimiter_result)\n end", "def saw_item(item); end", "def pretty_list(list)\r\n\tputs \"Grocery List\".center(30)\r\n\tlist.each do |item, quantity|\r\n\t\tputs \"#{item} \".ljust(20) + \"#{quantity}\".rjust(10)\r\n\tend\r\nend", "def add_an_item\n item = Item.new\n item.description = \"Task number #{to_do_list.size+1}\"\n to_do_list << item\n end" ]
[ "0.6534294", "0.64756286", "0.63982606", "0.6332178", "0.6300186", "0.6280757", "0.62803835", "0.6182565", "0.61383456", "0.6061238", "0.6061238", "0.60265017", "0.6007495", "0.59631926", "0.58516514", "0.5837462", "0.57548285", "0.57481664", "0.57481664", "0.56823754", "0.5628326", "0.5587655", "0.5566953", "0.55579424", "0.54857695", "0.5477283", "0.5460063", "0.5372191", "0.5363679", "0.53337735", "0.5320084", "0.53016967", "0.5291587", "0.52799124", "0.52464795", "0.5245565", "0.52389103", "0.523774", "0.52282465", "0.5198366", "0.51484144", "0.5147458", "0.51383847", "0.5100772", "0.5087686", "0.5058877", "0.5032231", "0.49857682", "0.49830222", "0.49754333", "0.49753526", "0.49465576", "0.4941129", "0.4939468", "0.49345958", "0.4926696", "0.49112153", "0.49109867", "0.4901312", "0.4898161", "0.48914188", "0.48732728", "0.48633656", "0.48433656", "0.48412067", "0.4834048", "0.48272437", "0.48086008", "0.4807325", "0.48021886", "0.47992933", "0.4797228", "0.47762623", "0.47703686", "0.47671124", "0.47653964", "0.47541007", "0.4753094", "0.47519177", "0.47490948", "0.47489515", "0.4741524", "0.47408155", "0.47388265", "0.47373384", "0.47362894", "0.47356266", "0.4729864", "0.47267383", "0.47000855", "0.46989724", "0.469194", "0.4688962", "0.4685511", "0.4685511", "0.46813414", "0.46716502", "0.4671142", "0.46706575", "0.46696097" ]
0.81515324
0
Builds a Paragraph that is flush to +margin+
def build_paragraph margin p :paragraph_start => margin if @debug paragraph = RDoc::Markup::Paragraph.new until @tokens.empty? do type, data, column, = get case type when :INDENT then next if data == margin and peek_token[0] == :TEXT unget break when :TEXT then if column != margin then unget break end paragraph << data skip :NEWLINE else unget break end end p :paragraph_end => margin if @debug paragraph end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_paragraph margin\n p :paragraph_start => margin if @debug\n\n paragraph = RDoc::Markup::Paragraph.new\n\n until @tokens.empty? do\n type, data, column, = get\n\n if type == :TEXT and column == margin then\n paragraph << data\n\n break if peek_token.first == :BREAK\n\n data << ' ' if skip :NEWLINE\n else\n unget\n break\n end\n end\n\n paragraph.parts.last.sub!(/ \\z/, '') # cleanup\n\n p :paragraph_end => margin if @debug\n\n paragraph\n end", "def build_paragraph margin\n p :paragraph_start => margin if @debug\n\n paragraph = RDoc::Markup::Paragraph.new\n\n until @tokens.empty? do\n type, data, = get\n\n case type\n when :TEXT then\n @section = 'Returns' if data =~ /\\A(Returns|Raises)/\n\n paragraph << data\n when :NEWLINE then\n if :TEXT == peek_token[0] then\n # Lines beginning with 'Raises' in the Returns section should not be\n # treated as multiline text\n if 'Returns' == @section and\n peek_token[1].start_with?('Raises') then\n break\n else\n paragraph << ' '\n end\n else\n break\n end\n else\n unget\n break\n end\n end\n\n p :paragraph_end => margin if @debug\n\n paragraph\n end", "def newParagraphSpacer(n) \n n.times {puts \" \" }\nend", "def build_verbatim margin\n p :verbatim_begin => margin if @debug\n verbatim = RDoc::Markup::Verbatim.new\n\n until @tokens.empty? do\n type, data, column, = get\n\n case type\n when :INDENT then\n if margin >= data then\n unget\n break\n end\n\n indent = data - margin\n\n verbatim << ' ' * indent\n when :HEADER then\n verbatim << '=' * data\n\n _, _, peek_column, = peek_token\n peek_column ||= column + data\n verbatim << ' ' * (peek_column - column - data)\n when :RULE then\n width = 2 + data\n verbatim << '-' * width\n\n _, _, peek_column, = peek_token\n peek_column ||= column + data + 2\n verbatim << ' ' * (peek_column - column - width)\n when :TEXT then\n verbatim << data\n when *LIST_TOKENS then\n if column <= margin then\n unget\n break\n end\n\n list_marker = case type\n when :BULLET then '*'\n when :LABEL then \"[#{data}]\"\n when :LALPHA, :NUMBER, :UALPHA then \"#{data}.\"\n when :NOTE then \"#{data}::\"\n end\n\n verbatim << list_marker\n\n _, data, = get\n\n verbatim << ' ' * (data - list_marker.length)\n when :NEWLINE then\n verbatim << data\n break unless [:INDENT, :NEWLINE].include? peek_token[0]\n else\n unget\n break\n end\n end\n\n verbatim.normalize\n\n p :verbatim_end => margin if @debug\n\n verbatim\n end", "def build_verbatim margin\n p :verbatim_begin => margin if @debug\n verbatim = RDoc::Markup::Verbatim.new\n\n min_indent = nil\n generate_leading_spaces = true\n line = ''.dup\n\n until @tokens.empty? do\n type, data, column, = get\n\n if type == :NEWLINE then\n line << data\n verbatim << line\n line = ''.dup\n generate_leading_spaces = true\n next\n end\n\n if column <= margin\n unget\n break\n end\n\n if generate_leading_spaces then\n indent = column - margin\n line << ' ' * indent\n min_indent = indent if min_indent.nil? || indent < min_indent\n generate_leading_spaces = false\n end\n\n case type\n when :HEADER then\n line << '=' * data\n _, _, peek_column, = peek_token\n peek_column ||= column + data\n indent = peek_column - column - data\n line << ' ' * indent\n when :RULE then\n width = 2 + data\n line << '-' * width\n _, _, peek_column, = peek_token\n peek_column ||= column + width\n indent = peek_column - column - width\n line << ' ' * indent\n when :BREAK, :TEXT then\n line << data\n else # *LIST_TOKENS\n list_marker = case type\n when :BULLET then data\n when :LABEL then \"[#{data}]\"\n when :NOTE then \"#{data}::\"\n else # :LALPHA, :NUMBER, :UALPHA\n \"#{data}.\"\n end\n line << list_marker\n peek_type, _, peek_column = peek_token\n unless peek_type == :NEWLINE then\n peek_column ||= column + list_marker.length\n indent = peek_column - column - list_marker.length\n line << ' ' * indent\n end\n end\n\n end\n\n verbatim << line << \"\\n\" unless line.empty?\n verbatim.parts.each { |p| p.slice!(0, min_indent) unless p == \"\\n\" } if min_indent > 0\n verbatim.normalize\n\n p :verbatim_end => margin if @debug\n\n verbatim\n end", "def wrapped_by_paragraph; end", "def wrap_paragraph(par)\n [\"\\n\\n\"] + par + [\"\\n\\n\"]\n end", "def paragraph(&block)\n section(:top => 1, :bottom => 1, &block)\n end", "def create_paragraph(content)\n text = Text.new(content)\n run = Run.new\n run << text\n paragraph = Paragraph.new\n paragraph << run\n paragraph\nend", "def test_paragraph(x, y, width, paragraph)\n draw_formatted_text(x, y, width, paragraph, nil, true)\n end", "def paragraph(\n word_count: rand(DEFAULT_WORD_COUNT_RANGE),\n sentence_count: rand(DEFAULT_SENTENCE_COUNT_RANGE),\n fillers: dictionnary.fillers\n )\n sentence_count = 0 if sentence_count.negative?\n paragraph = []\n sentence_count.times do\n s = sentence(word_count: word_count, fillers: fillers)\n paragraph << s unless s.empty?\n end\n paragraph.join(' ')\n end", "def paragraph(&block)\n section(:top => 1, :bottom => 1, &block)\n end", "def paragraphs(\n word_count: rand(DEFAULT_WORD_COUNT_RANGE),\n sentence_count: rand(DEFAULT_SENTENCE_COUNT_RANGE),\n paragraph_count: rand(DEFAULT_PARAGRAPH_COUNT_RANGE),\n fillers: dictionnary.fillers,\n seperator: DEFAULT_PARAGRAPH_SEPARATOR\n )\n paragraph_count = 0 if paragraph_count.negative?\n paragraphs = []\n paragraph_count.times do\n p = paragraph(word_count: word_count, sentence_count: sentence_count, fillers: fillers)\n paragraphs << p unless p.empty?\n end\n paragraphs.join(seperator)\n end", "def fold_paragraph(paragraph, max_width)\n # Gradually build our output\n str, *rest = paragraph\n width = str.length\n\n rest.each do |word|\n if width + word.length + 1 <= max_width\n str << ' ' << word\n width += word.length + 1\n else\n str << \"\\n\" << word\n width = word.length\n end\n end\n\n str\nend", "def build_verbatim margin\n verbatim = super\n\n verbatim.format = :ruby if @section == 'Examples'\n\n verbatim\n end", "def mapf_format_paragraph(text, max_width = contents_width)\n text = text.clone\n # Create a Dummy Contents - I wanted to boost compatibility by using the \n # default process method for escape codes. It may have the opposite effect, \n # for some :( \n real_contents = contents # Preserve Real Contents\n self.contents = Bitmap.new(contents_width, 24)\n reset_font_settings\n paragraph = \"\"\n while !text.empty?\n text.lstrip!\n oline, nline, tw = mapf_format_by_line(text.clone, max_width)\n # Replace old line with the new one\n text.sub!(/#{Regexp.escape(oline)}/m, nline)\n paragraph += text.slice!(/.*?(\\n|$)/)\n end\n contents.dispose # Dispose dummy contents\n self.contents = real_contents # Restore real contents\n return paragraph\n end", "def mapf_format_paragraph(text, max_width = contents_width)\n text = text.clone\n # Create a Dummy Contents - I wanted to boost compatibility by using the\n # default process method for escape codes. It may have the opposite effect,\n # for some :(\n real_contents = contents # Preserve Real Contents\n self.contents = Bitmap.new(24, 24)\n reset_font_settings\n paragraph = \"\"\n while !text.empty?\n text.lstrip!\n oline, nline, tw = mapf_format_by_line(text.clone, max_width)\n # Replace old line with the new one\n text.sub!(/#{Regexp.escape(oline)}/m, nline)\n paragraph += text.slice!(/.*?(\\n|$)/)\n end\n contents.dispose # Dispose dummy contents\n self.contents = real_contents # Restore real contents\n return paragraph\n end", "def build_footer\n pad(10) do\n pdf_writer.y = pdf_writer.absolute_bottom_margin + 10\n add_text \"Copyright 2010 - Sand Bridge Software\", :font_size => 8\n end\n end", "def build_footer\n pad(10) do\n pdf_writer.y = pdf_writer.absolute_bottom_margin + 10\n add_text \"Copyright 2010 - Sand Bridge Software\", :font_size => 8\n end\n end", "def build_footer\n pad(10) do\n pdf_writer.y = pdf_writer.absolute_bottom_margin + 10\n add_text \"Copyright 2010 - Sand Bridge Software\", :font_size => 8\n end\n end", "def word_p(*args, &block)\n content = if block_given? then\n capture(&block).strip\n else\n args.shift.to_s\n end\n\n options = args.shift || {}\n\n xml = \"<w:p><w:pPr>\"\n \n unless no_keep = options.delete(:no_keep) then\n xml += \"<w:keepLines/><w:keepNext/>\"\n end\n\n if style = options.delete(:style) then\n xml += \"<w:pStyle w:val=\\\"#{style}\\\"/>\"\n end\n\n if justification = options.delete(:justify) then\n xml += \"<w:jc w:val=\\\"#{justification}\\\"/>\"\n end\n xml += \"</w:pPr><w:r>\"\n \n bold = options.delete(:bold)\n italic = options.delete(:italic)\n\n if bold || italic then\n xml += \"<w:rPr>\"\n xml += \"<w:b/>\" if bold\n xml += \"<w:i/>\" if italic\n xml += \"</w:rPr>\"\n end\n\n xml += \"<w:t>\" + content + \"</w:t></w:r></w:p>\"\n\n if block_given? then\n concat xml\n else\n return xml\n end\n end", "def add_paragraphs\n lines = seperate_lines\n max_index = lines.size - 1\n (1..(max_index)).each do |index|\n previous_line = lines[index -1]\n current_line = lines[index]\n next_line = lines[index + 1]\n if current_line[0] != (\"#\" || \"\\n\" || \"</p>\")\n if previous_line[0] == \"\\n\"\n lines.insert(index, \"<p>\\n\")\n elsif next_line[0] == \"\\n\"\n lines.insert(index + 1, \"\\n</p>\")\n elsif next_line == nil\n lines << \"\\n</p>\"\n else\n lines\n end\n end\n end\n @doc = lines.join\n end", "def body_paragraph(num)\n puts \"#{num} little monkeys jumping on the bed,\nOne fell off and bumped his head,\nMama called the doctor and the doctor said,\n'No more monkeys jumping on the bed!'\n\n\"\nend", "def keep_together(content, size = nil, before = 0, after = 0)\n test_width = @pdf.columns? ? @pdf.column_width : @pdf.absolute_right_margin - @pdf.left_margin\n total_height = before\n more_to_add = true\n t = content\n while more_to_add\n total_height += @pdf.font_height(size)\n t = @pdf.add_text_wrap(0, 0, test_width, t, size, :left, 0, true)\n more_to_add = false if t.blank?\n end\n total_height += after\n # puts \"pdf.y = #{@pdf.y}, total_height = #{total_height}, bottom margin = #{@pdf.bottom_margin}\"\n if @pdf.y - total_height < @pdf.bottom_margin\n start_new_page\n @x = @pdf.left_margin\n print \"[newline:keep]\"\n end\n end", "def paragraph parts\n parts = parts.map do |part|\n if \"\\n\" == part then\n RDoc::Markup::HardBreak.new\n else\n part\n end\n end if break_on_newline?\n\n RDoc::Markup::Paragraph.new(*parts)\n end", "def new_paragraph(env); end", "def wrap(text, length, indent=0, padding=0)\n if text.length > length - indent\n paragraphs = []\n line = ''\n text.split(/\\s+/).map(&:chomp).reject(&:empty?).each do |fragment|\n if line.length < length - indent\n line << fragment + ' '\n else\n paragraphs << line\n line = padding + fragment + ' '\n end\n end\n paragraphs << line\n text = paragraphs.join(\"\\n\")\n end\n text\n end", "def paragraph value\n content = cut_off(value).join(' ').rstrip\n contents = @inline_parser.parse content\n\n RDoc::Markup::Paragraph.new(*contents)\nend", "def margins_pt(top, left = top, bottom = top, right = left)\n # Set the margins to new values\n @top_margin = top\n @bottom_margin = bottom\n @left_margin = left\n @right_margin = right\n # Check to see if this means that the current writing position is\n # outside the writable area\n if @y > (@page_height - top)\n # Move y down\n @y = @page_height - top\n end\n\n start_new_page if @y < bottom # Make a new page\n end", "def parse_text parent, indent # :nodoc:\n parent << build_paragraph(indent)\n end", "def get_paragraph\n wo = self.words_from_markov_data\n\n self.paragraph_from_words(wo).strip\n end", "def heredoc_text(lines, leading, has_margin, remove_break)\n if has_margin\n leading_pattern = /^#{Regexp.escape(leading)}/\n lines = lines.collect {|s| s.gsub(leading_pattern, '') }\n end\n result = lines.join('')\n result.gsub!(/\\r?\\n$/, '') if remove_break\n result\n end", "def make_paragraph(title, link)\n paragraph = \"Title: #{title}\\n\"\n paragraph + \"Link: #{link}\\n\\n\"\n end", "def move_to_newline(height = @pdf.font_height, filler = false)\n fix_margins\n @pdf.move_pointer(height.to_f) unless filler && @pdf.y == @pdf.absolute_top_margin\n @pdf.start_new_page if @pdf.y < @pdf.bottom_margin\n fix_margins\n @x = @pdf.left_margin\n end", "def paragraph; end", "def text hard_break = nil\n @parts.map do |part|\n if RDoc::Markup::HardBreak === part then\n '%1$s%3$*2$s' % [hard_break, @indent, ' '] if hard_break\n else\n part\n end\n end.join\n end", "def paragraphize(input)\n \"#{input.lstrip.rstrip.gsub(/\\n\\n/, '</p><p>').gsub(/\\n/, '')}\"\n end", "def justify_again\n content = ['Table of Contents', 'Chapter 1: Numbers', 'page 1', 'Chapter 2: Letters', 'page 72', 'Chapter 3: Variables', 'page 118']\n lineWidth = 40\n puts (content[0].center(lineWidth))\n puts (content[1].ljust(lineWidth/2) + content[2].rjust(lineWidth/2))\n puts (content[3].ljust(lineWidth/2) + content[4].rjust(lineWidth/2))\n puts (content[5].ljust(lineWidth/2) + content[6].rjust(lineWidth/2))\nend", "def wrap_with_paragraphs(env, nodes); end", "def random_p\n \"<p>#{texter.random_paragraph}</p>\"\n end", "def horizontalSpacer(n , text)\n n.times {print \" \"}\n puts text\nend", "def output_paragraphs\n if @number <= self.class.total_included_paragraphs\n PARAGRAPHS[0, @number].join(\"\\n\\n\")\n else\n repeat = (@number / self.class.total_included_paragraphs.to_f).ceil\n (PARAGRAPHS * repeat)[0, @number].join(\"\\n\\n\")\n end\n end", "def paragraph(text, options={})\n cur_page.paragraph(text, options)\n end", "def to_html\r\n html = ''\r\n text_runs.each { |text_run| html << text_run.to_html }\r\n styles = {}\r\n styles['font-size'] = \"#{font_size}pt\" unless font_size.nil?\r\n styles['text-align'] = @style.text_align unless @style.aligned_left?\r\n html_tag(:p, content: html, styles: styles)\r\n end", "def spacer\n puts \"\\n----------------------------\\n\"\nend", "def accept_paragraph paragraph\n @res << \"\\n<p>\"\n text = paragraph.text @hard_break\n text = text.gsub(/\\r?\\n/, ' ')\n @res << to_html(text)\n @res << \"</p>\\n\"\n end", "def paragraph(options = {}, &block)\n par = DocxGenerator::DSL::Paragraph.new(options)\n yield par if block\n @objects << par\n end", "def draw_text_block(x, y, text, left_margin, right_margin_from_right_edge, options = {})\n options[:font] ||= default_font\n options[:font_color] ||= RFPDF::COLOR_PALETTE[:black]\n options[:font_size] ||= 10\n options[:font_style] ||= ''\n set_text_color_a(options[:font_color], options[:colorspace])\n SetFont(options[:font], options[:font_style], options[:font_size])\n SetXY(x, y)\n SetLeftMargin(left_margin)\n SetRightMargin(right_margin_from_right_edge)\n Write(options[:font_size] + 4, text)\n SetMargins(0,0,0)\n end", "def driver\n paragraph = ParagraphTruncate.new\n puts \"This is going to be the sentence that I'll truncate.\".truncate(40, omission: \"... (continued)\")\n end", "def accept_paragraph paragraph\n text = paragraph.text @hard_break\n wrap attributes text\n end", "def add_text_wrap(x, y, width, text, size = nil, justification = :left, angle = 0, test = false)\n if text.kind_of?(Numeric) and size.kind_of?(String)\n text, size = size, text\n warn PDF::Writer::Lang[:add_textw_parameters_reversed] % caller[0]\n end\n\n if size.nil? or size <= 0\n size = @font_size\n end\n\n # Need to store the initial text state, as this will change during the\n # width calculation, but will need to be re-set before printing, so\n # that the chars work out right\n t_CTS = @current_text_state.dup\n\n select_font(\"Helvetica\") if @fonts.empty?\n return \"\" if width <= 0\n\n w = brk = brkw = 0\n font = @current_font\n tw = width / size.to_f * 1000\n\n pos = -1\n loop do\n pos += 1\n break if pos == text.size\n font_change = true\n tag_size, text, font_change = quick_text_tags(text, pos, font_change)\n if tag_size != 0\n if font_change\n current_font!\n font = @current_font\n end\n pos += (tag_size - 1)\n else\n w += char_width(font, text[pos, 1])\n\n if w > tw # We need to truncate this line\n if brk > 0 # There is somewhere to break the line.\n if text[brk] == \" \"\n tmp = text[0, brk]\n else\n tmp = text[0, brk + 1]\n end\n x, adjust = adjust_wrapped_text(tmp, brkw, width, x, justification)\n\n # Reset the text state\n @current_text_state = t_CTS.dup\n current_font!\n add_text(x, y, tmp, size, angle, adjust) unless test\n return text[brk + 1..-1]\n else # just break before the current character\n tmp = text[0, pos]\n# tmpw = (w - char_width(font, text[pos, 1])) * size / 1000.0\n x, adjust = adjust_wrapped_text(tmp, brkw, width, x, justification)\n\n # Reset the text state\n @current_text_state = t_CTS.dup\n current_font!\n add_text(x, y, tmp, size, angle, adjust) unless test\n return text[pos..-1]\n end\n end\n\n if text[pos] == ?-\n brk = pos\n brkw = w * size / 1000.0\n end\n\n if text[pos, 1] == \" \"\n brk = pos\n ctmp = text[pos]\n ctmp = @fonts[font].differences[ctmp] unless @fonts[font].differences.nil?\n z = @fonts[font].c[tmp].nil? ? 0 : @fonts[font].c[tmp]['WX']\n brkw = (w - z) * size / 1000.0\n end\n end\n end\n\n # There was no need to break this line.\n justification = :left if justification == :full\n tmpw = (w * size) / 1000.0\n x, adjust = adjust_wrapped_text(text, tmpw, width, x, justification)\n # reset the text state\n @current_text_state = t_CTS.dup\n current_font!\n add_text(x, y, text, size, angle, adjust) unless test\n return \"\"\n end", "def justify\n lineWidth = 40\n puts (\"Table of Contents\".center(lineWidth))\n puts (\"Chapter 1: Numbers\".ljust(lineWidth/2) + \"page 1\".rjust(lineWidth/2))\n puts (\"Chapter 2: Letters\".ljust(lineWidth/2) + \"page 72\".rjust(lineWidth/2))\n puts (\"Chapter 3: Variables\".ljust(lineWidth/2) + \"page 118\".rjust(lineWidth/2))\nend", "def render_spacer\n puts \"\\n\"\n end", "def parse_paragraph document, par, env\n paragraph = Paragraph.new(par)\n\n if env == nil\n is_indented, env = BasicFormatting::indented(paragraph, @creator)\n if !is_indented\n # ---- first remarks, so later HTML expansion does not break off\n BasicFormatting::remarks(paragraph, @creator)\n # ---- next urls, as we don't want expansion and to allow '[' expansion later\n UrlFormatting::markup(paragraph, @creator)\n # ---- parse \\ruby{} and evaluate\n Ruby::parse(paragraph)\n # ---- expand bullets and lists\n ListFormatting::markup(paragraph, @creator)\n # ---- expand functions TeX style \n Functions::expand(paragraph, document)\n # ---- create titles from wiki type markup\n Headers::markup(document, paragraph, proc {|titlenumber,level,buf| @creator.title(titlenumber,level,buf) } )\n # ---- standard wiki style markup (bold, italics etc.)\n BasicFormatting::markup(paragraph, @creator)\n # ---- some markup when in Draft mode\n DraftModeFormatting::markup(paragraph, @creator)\n # ---- special markup, for example highlighting FIXME\n KeywordFormatting::markup(paragraph, @creator) \n end\n end\n return paragraph, env\n end", "def _Paragraph\n\n _save = self.pos\n while true # choice\n _tmp = apply(:_ExplicitParagraph)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_ImplicitParagraph)\n break if _tmp\n self.pos = _save\n break\n end # end choice\n\n set_failed_rule :_Paragraph unless _tmp\n return _tmp\n end", "def paragraph_by_chars(characters: 256, supplemental: false)\n paragraph = paragraph(sentence_count: 3, supplemental: supplemental)\n\n paragraph += \" #{paragraph(sentence_count: 3, supplemental: supplemental)}\" while paragraph.length < characters\n\n \"#{paragraph[0...characters - 1]}.\"\n end", "def paragraph(text)\n add_custom_tags(\"<p>#{text.strip}</p>\\n\")\n end", "def margin_between para\n [self.margin_bottom(:next_para => para),\n para.margin_top(:prev_para => self)].max\n end", "def paragraph(text)\n \"<p>#{text}</p>\"\n end", "def paragraph(sentence_count: T.unsafe(nil), supplemental: T.unsafe(nil), random_sentences_to_add: T.unsafe(nil), exclude_words: T.unsafe(nil)); end", "def accept_indented_paragraph paragraph\n @indent += paragraph.indent\n text = paragraph.text @hard_break\n wrap attributes text\n @indent -= paragraph.indent\n end", "def wrap(text, length)\n cur_page.wrap(text, length)\n end", "def write_paragraph last_env, environments, paragraph\n # $stderr.print last_env,\",\",paragraph,\"\\n\" if last_env != nil\n case last_env\n when 'listing'\n writeln '\\begin{listing}'\n paragraph.each { | line | write line }\n writeln '\\end{listing}'\n when 'verbatim'\n writeln '\\begin{verbatim}'\n paragraph.each { | line | write line }\n writeln '\\end{verbatim}'\n when 'quote'\n writeln '\\begin{verbatim}'\n paragraph.each { | line | write line }\n writeln '\\end{verbatim}'\n when 'quotation'\n writeln '\\begin{verbatim}'\n paragraph.each { | line | write line }\n writeln '\\end{verbatim}'\n when 'cmake'\n code_box paragraph, last_env, 'shell'\n when 'perl' \n code_box paragraph, last_env\n when 'scala' \n code_box paragraph, last_env\n when 'python' \n code_box paragraph, last_env\n when 'c' \n code_box paragraph, last_env\n when 'swig'\n code_box paragraph, last_env, 'c'\n when 'r'\n code_box paragraph, last_env, 'slang'\n when 'ruby'\n code_box paragraph, last_env\n when 'shell'\n code_box paragraph, last_env\n else\n paragraph.each do | line |\n write line\n # write '<br />' if environments.has?('verbatim')\n end\n end\n end", "def append_paragraph_breaks(out)\n out.sub!(TRAILING_WHITESPACE, EMPTY)\n if out.end_with?(NEWLINE)\n out << NEWLINE unless out.end_with?(\"\\n\\n\")\n else\n out << \"\\n\\n\"\n end\n end", "def paragraph_end; end", "def pdf_margin\n [ margin_top, margin_right, margin_bottom, margin_left ]\n end", "def generate(pdf, heading)\n pdf.move_down(heading[:top_padding])\n pdf.formatted_text([text_properties(heading)])\n end", "def p_wrap(text, opts={})\n # Actually if opts[:truncate], we might wanna remove the bad tags entirely instead of escaping...\n my_allowed_tags = opts[:tags].is_a?(Array) ? opts[:tags] : (allowed_tags - %w(p))\n # Basically these are types that cannot exist within a P tag. P is not allowed, however.\n # TODO: Style h1-h3 so that they are at greatest the size of an h3.\n block_levels = \"pre|blockquote|h1|h2|h3|h4|h5|h6|ol|ul\"\n res = text.to_s.\n gsub(/(<\\/?(\\w+)[^>]*>)/) {|t| my_allowed_tags.include?($2) ? $1 : h($1)}.\n gsub(/\\r\\n?/, \"\\n\").\n gsub(/\\n\\n+/, \"</p>\\n\\n<p>\")\n res = \"<p>\" + res + \"</p>\"\n\n res.gsub(/(<(?:#{block_levels})>)/, \"</p>\\n\\\\1\").gsub(/(<\\/(?:#{block_levels})>)/, \"\\\\1\\n<p>\").\n gsub(/\\s*<p><\\/p>\\s*/, \"\\n\"). # Fuck. This performs within a PRE tag...\n gsub(/([^\\n|>]\\n)(?!\\n)/, \"\\\\1<br />\\n\").strip\n end", "def add_margins(input, output)\n `pdfcrop --margins 18 #{input.shellescape} #{output.shellescape}`\n end", "def draw_both\n \t\" #{@spaces[:space_1]} | #{@spaces[:space_2]} | #{@spaces[:space_3]}\\t\\t\" +\n \t\" #{@sample[:space_1]} | #{@sample[:space_2]} | #{@sample[:space_3]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\t\\t\" + \" _____|_____|____\\n\" + \t\n \t\" #{@spaces[:space_4]} | #{@spaces[:space_5]} | #{@spaces[:space_6]}\\t\\t\" +\n \t\" #{@sample[:space_4]} | #{@sample[:space_5]} | #{@sample[:space_6]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\t\\t\" + \" _____|_____|____\\n\" +\n \t\" #{@spaces[:space_7]} | #{@spaces[:space_8]} | #{@spaces[:space_9]}\\t\\t\" +\n \t\" #{@sample[:space_7]} | #{@sample[:space_8]} | #{@sample[:space_9]}\\n\" +\n \t\t\t\t\t \" | | \\t\\t\" + \" | | \\n\\n\"\n end", "def pad_around(text, padding, fill: SPACE)\n fill * padding.left + text + fill * padding.right\n end", "def paragraph(sentence_count: T.unsafe(nil), random_sentences_to_add: T.unsafe(nil)); end", "def push_para para, force=false\n prev_para= @paras.last\n if prev_para.nil? && (para.is_a?(Dialog) || para.is_a?(Parenthetical))\n prev_para= CharacterCue.new(para.screenplay,\n para.last_character_cue.input_line,\n nil,\n :widow)\n self.push_para(prev_para)\n end\n margin_between= (prev_para.nil?? 0.points : prev_para.margin_between(para))\n height_before_para= self.body_height + margin_between\n # para overruns the current page. need to start a new page.\n curr_page_para, new_page_para=\n if (height_before_para + para.height > self.max_body_height) && !force\n if height_before_para >= self.max_body_height\n [nil, para]\n else\n orphan, widow= para.split(self.max_body_height - height_before_para)\n if orphan.nil?\n [nil, para]\n else\n [orphan, widow]\n end\n end\n else\n [para, nil]\n end\n unless curr_page_para.nil?\n curr_page_para.is_first_on_page= true if @paras.empty?\n @paras << curr_page_para\n end\n new_page_para\n end", "def text(text, options = {})\n # Apply the filtering which will make underlining (and other items)\n # function.\n text = preprocess_text(text)\n\n options ||= {}\n\n new_page_required = false\n __y = @y\n\n if options[:absolute_left]\n left = options[:absolute_left]\n else\n left = @left_margin\n left += options[:left] if options[:left]\n end\n\n if options[:absolute_right]\n right = options[:absolute_right]\n else\n right = absolute_right_margin\n right -= options[:right] if options[:right]\n end\n\n size = options[:font_size] || 0\n if size <= 0\n size = @font_size\n else\n @font_size = size\n end\n\n just = options[:justification] || :left\n\n if options[:leading] # leading instead of spacing\n height = options[:leading]\n elsif options[:spacing]\n height = options[:spacing] * font_height(size)\n else\n height = font_height(size)\n end\n\n text.each do |line|\n start = true\n loop do # while not line.empty? or start\n break if (line.nil? or line.empty?) and not start\n\n start = false\n\n @y -= height\n\n if @y < @bottom_margin\n if options[:test]\n new_page_required = true\n else\n # and then re-calc the left and right, in case they have\n # changed due to columns\n start_new_page\n @y -= height\n\n if options[:absolute_left]\n left = options[:absolute_left]\n else\n left = @left_margin\n left += options[:left] if options[:left]\n end\n\n if options[:absolute_right]\n right = options[:absolute_right]\n else\n right = absolute_right_margin\n right -= options[:right] if options[:right]\n end\n end\n end\n\n line = add_text_wrap(left, @y, right - left, line, size, just, 0, options[:test])\n end\n end\n\n if options[:test]\n @y = __y\n new_page_required\n else\n @y\n end\n end", "def draw\n\t\t# NOTE: consider adjusting margins for Text resize, such that the bottom margin matches up with the baseline of the text.\n\t\tsuper()\n\tend", "def generate_content\n @pdf = Prawn::Document.new(\n info: self.metadata,\n top_margin: @format[:header_size] + @format[:top_margin],\n bottom_margin: @format[:footer_size] + @format[:bottom_margin]\n )\n add_page_body\n add_page_header\n add_page_footer\n add_page_numbering\n end", "def pad(text, padding, fill: SPACE, separator: nil)\n padding = Strings::Padder.parse(padding)\n text_copy = text.dup\n sep = separator || text[LINE_BREAK] || NEWLINE\n line_width = max_line_length(text, sep)\n output = []\n\n filler_line = fill * line_width\n\n padding.top.times do\n output << pad_around(filler_line, padding, fill: fill)\n end\n\n text_copy.split(sep).each do |line|\n line = line.empty? ? filler_line : line\n output << pad_around(line, padding, fill: fill)\n end\n\n padding.bottom.times do\n output << pad_around(filler_line, padding, fill: fill)\n end\n\n output.join(sep)\n end", "def text hard_break = ''\n @parts.map do |part|\n if RDoc::Markup::HardBreak === part then\n hard_break\n else\n part\n end\n end.join\n end", "def form_paragraphs( str, rs )\n\t\t\t@log.debug \" Forming paragraphs\"\n\t\t\tgrafs = str.\n\t\t\t\tsub( /\\A\\n+/, '' ).\n\t\t\t\tsub( /\\n+\\z/, '' ).\n\t\t\t\tsplit( /\\n{2,}/ )\n\n\t\t\trval = grafs.collect {|graf|\n\n\t\t\t\t# Unhashify HTML blocks if this is a placeholder\n\t\t\t\tif rs.html_blocks.key?( graf )\n\t\t\t\t\trs.html_blocks[ graf ]\n\n\t\t\t\t# no output if this is block separater\n\t\t\t\telsif graf == '~' then\n\t\t\t\t\t''\n\n\t\t\t\t# Otherwise, wrap in <p> tags\n\t\t\t\telse\n\t\t\t\t\tapply_span_transforms(graf, rs).\n\t\t\t\t\t\tsub( /^[ ]*/, '<p>' ) + '</p>'\n\t\t\t\tend\n\t\t\t}.join( \"\\n\\n\" )\n\n\t\t\t@log.debug \" Formed paragraphs: %p\" % rval\n\t\t\treturn rval\n\t\tend", "def flush_left text\n indent = 9999\n\n text.each_line do |line|\n line_indent = line =~ /\\S/ || 9999\n indent = line_indent if indent > line_indent\n end\n\n empty = ''\n empty = RDoc::Encoding.change_encoding empty, text.encoding\n\n text.gsub(/^ {0,#{indent}}/, empty)\n end", "def print_in_box(text)\n width = text.size\n result = <<EOS\n+-#{'-' * width}-+\n| #{' ' * width} |\n| #{text} |\n| #{' ' * width} |\n+-#{'-' * width}-+\nEOS\n result\nend", "def center(p0, padstr=\"\") end", "def ljust(p0, padstr=\"\") end", "def draw(text)\n printf \"%s %-#{(columns / 3) - 5}s \" % [V_SEP, text]\n end", "def padded_line(iteration, elapsed_time)\n meter_line = line(iteration, elapsed_time)\n pad_size = [@last_printed_length - meter_line.size, 0].max\n @last_printed_length = meter_line.size\n meter_line + ' ' * pad_size\n end", "def to_html\n paragraphs.map(&:to_html).join('\\n')\n end", "def center(width)\n spaces_needed = width - self.print_width\n left_side = spaces_needed / 2\n right_side = spaces_needed - left_side\n (\" \" * left_side) << self << (\" \" * right_side)\n end", "def to_html\n html = ''\n text_runs.each do |text_run|\n html << text_run.to_html\n end\n styles = {}\n #styles = { 'font-size' => \"#{font_size}pt\" }\n styles['text-align'] = @alignment if @alignment\n html_tag(:p, content: html, styles: styles)\n end", "def poem &block\n annotate block do |c|\n c.split(\"\\n\").join(\" \\n\")\n end\nend", "def simple_format_with_quote(text)\n text = '' if text.nil?\n text = text.dup\n start_tag = \"<p>\"\n text = text.to_str\n text.gsub!(/\\r\\n?/, \"\\n\") # \\r\\n and \\r -> \\n\n text.gsub!(/\\n\\n+/, \"</p>\\n\\n#{start_tag}\") # 2+ newline -> paragraph\n text.gsub!(/([^\\n]\\n)(?=[^\\n])/, '\\1<br />') # 1 newline -> br\n text.insert 0, start_tag\n text.concat(\"</p>\")\n end", "def maatsf_paragraph_new_line(orig_method, text, pos, *args, &block)\n tw = nil\n tw = maatsf_set_next_line(text, pos) if $game_message.paragraph_format && !text.nil? && !text.empty?\n orig_method.call(text, pos, *args, &block) # Call original Method\n # Alignment\n next_line = text[/^[^\\n\\f]*/]\n align = maatsf_line_alignment(next_line)\n if align != 0 # If not left aligned\n if tw.nil?\n @atsf_testing = true\n tw = mapf_calc_line_width(next_line)\n @atsf_testing = false\n end\n space = maatsf_total_line_width(pos[:y]) - tw\n pos[:x] = [pos[:x] + (space / (align == 1 ? 2 : 1)), pos[:x]].max\n end\n end", "def draw\n margin = @border_width / 2.0\n \n if @background_color \n old_color = @document.fill_color || \"000000\"\n @document.fill_color(@background_color)\n h = borders.include?(:bottom) ? \n height - ( 2 * margin ) : height + margin\n @document.fill_rectangle [x, y ], width, h \n\n @document.fill_color(old_color)\n end\n\n if @border_width > 0\n @document.mask(:line_width) do\n @document.line_width = @border_width\n\n @document.mask(:stroke_color) do\n @document.stroke_color @border_color if @border_color\n\n if borders.include?(:left)\n @document.stroke_line [x, y + margin], \n [x, y - height - margin ]\n end\n\n if borders.include?(:right)\n @document.stroke_line( \n [x + width, y + margin],\n [x + width, y - height - margin] )\n end\n\n if borders.include?(:top)\n @document.stroke_line(\n [ x, y ], \n [ x + width, y ])\n end\n\n if borders.include?(:bottom)\n @document.stroke_line [x, y - height ],\n [x + width, y - height]\n end\n end\n\n end\n \n borders\n\n end\n\n @document.bounding_box( [x + @horizontal_padding, \n y - @vertical_padding], \n :width => text_area_width,\n :height => height - @vertical_padding) do\n @document.move_down((@document.font.line_gap +\n @document.font.descender) / 2)\n\n options = {:align => @align, :final_gap => false}\n\n options[:size] = @font_size if @font_size\n options[:style] = @font_style if @font_style\n\n old_color = @document.fill_color || \"000000\"\n @document.fill_color @text_color if @text_color \n @document.text @text, options\n @document.fill_color old_color\n end\n end", "def paragraph(string)\n puts \"No info available...\" if string == \"\" #technically useless now...\n loop do\n puts paragraph_line = string.truncate(80, separator: ' ', omission: '') #prints the first 80 characters, stopping at the nearest space before\n string = string.from (paragraph_line.length + 1) #removes that first line from the original string, and then the loop repeats\n break if string == nil #not entrirely sure why this works, but ends the loop when there is no string left.\n end\nend", "def para(stylename, content = nil)\n end_element = ( content ? \">#{content}</text:p>\" : \"/>\" )\n %Q(<text:p text:style-name=\"#{stylename}\"#{end_element})\n end", "def pdf_bracket(pdf, x, y, w, h)\n r = 5\n\n pdf.stroke_style( PDF::Writer::StrokeStyle.new(1) )\n pdf.stroke_color( Color::RGB::Grey )\n pdf.rounded_rectangle(x, y, w, h, r).stroke # x, y, w, h, r\n \n pdf.stroke_style( PDF::Writer::StrokeStyle.new(8) )\n pdf.stroke_color( Color::RGB::White )\n pdf.rectangle(x + r + 6, y + 2, w - (2 * (r + 6)), -(h + 2) ).stroke\n end", "def generate(pdf, headline)\n pdf.move_down(headline[:top_padding])\n pdf.text(headline[:text], size: headline[:size])\n end", "def to_html\n paragraphs.map(&:to_html).join(\"\\n\")\n end", "def paragraph(sentence_count: 3, supplemental: false, random_sentences_to_add: 3)\n sentences(number: resolve(sentence_count) + rand(random_sentences_to_add.to_i).to_i, supplemental: supplemental).join(' ')\n end", "def padded_box(margin, &block)\n bounding_box [bounds.left + margin, bounds.top - margin],\n :width => bounds.width - (margin * 2), \n :height => bounds.height - (margin * 2), &block \n end", "def test_renders_as_a_paragraph\n render_inline(Primer::BaseComponent.new(tag: :p))\n\n refute_text(\"[\")\n end" ]
[ "0.828294", "0.7077012", "0.6331948", "0.6310281", "0.63017106", "0.62282985", "0.6197009", "0.6139939", "0.61095005", "0.60806936", "0.6039721", "0.60332686", "0.5999385", "0.59649974", "0.5960489", "0.59318346", "0.5919193", "0.5900154", "0.5900154", "0.5900154", "0.5884583", "0.5832155", "0.5820187", "0.5804944", "0.579122", "0.5773655", "0.5737712", "0.5733031", "0.56993264", "0.5677763", "0.56453884", "0.56134987", "0.5579761", "0.5577419", "0.5565966", "0.5549935", "0.55454296", "0.55170345", "0.5511481", "0.5499999", "0.54981047", "0.54887116", "0.5481358", "0.5447895", "0.54449046", "0.54445654", "0.5432468", "0.54205513", "0.5416944", "0.54167044", "0.5412158", "0.54044735", "0.5394112", "0.53693026", "0.5367094", "0.53651667", "0.5351091", "0.53248227", "0.53084874", "0.5305128", "0.5302011", "0.5279325", "0.52579683", "0.52534235", "0.5247333", "0.52324194", "0.52287006", "0.52010125", "0.5195954", "0.51918536", "0.5188374", "0.51778364", "0.51704365", "0.5157736", "0.5156065", "0.51473945", "0.5139412", "0.51360816", "0.51335436", "0.51199204", "0.511891", "0.5107973", "0.5063264", "0.50487536", "0.5047765", "0.5043442", "0.50405174", "0.50267696", "0.5017027", "0.5016759", "0.5013324", "0.5013067", "0.5009203", "0.5008618", "0.500516", "0.50030416", "0.49989656", "0.49989143", "0.49959338", "0.4992851" ]
0.8040784
1
Builds a Verbatim that is flush to +margin+
def build_verbatim margin p :verbatim_begin => margin if @debug verbatim = RDoc::Markup::Verbatim.new until @tokens.empty? do type, data, column, = get case type when :INDENT then if margin >= data then unget break end indent = data - margin verbatim << ' ' * indent when :HEADER then verbatim << '=' * data _, _, peek_column, = peek_token peek_column ||= column + data verbatim << ' ' * (peek_column - column - data) when :RULE then width = 2 + data verbatim << '-' * width _, _, peek_column, = peek_token peek_column ||= column + data + 2 verbatim << ' ' * (peek_column - column - width) when :TEXT then verbatim << data when *LIST_TOKENS then if column <= margin then unget break end list_marker = case type when :BULLET then '*' when :LABEL then "[#{data}]" when :LALPHA, :NUMBER, :UALPHA then "#{data}." when :NOTE then "#{data}::" end verbatim << list_marker _, data, = get verbatim << ' ' * (data - list_marker.length) when :NEWLINE then verbatim << data break unless [:INDENT, :NEWLINE].include? peek_token[0] else unget break end end verbatim.normalize p :verbatim_end => margin if @debug verbatim end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_verbatim margin\n p :verbatim_begin => margin if @debug\n verbatim = RDoc::Markup::Verbatim.new\n\n min_indent = nil\n generate_leading_spaces = true\n line = ''.dup\n\n until @tokens.empty? do\n type, data, column, = get\n\n if type == :NEWLINE then\n line << data\n verbatim << line\n line = ''.dup\n generate_leading_spaces = true\n next\n end\n\n if column <= margin\n unget\n break\n end\n\n if generate_leading_spaces then\n indent = column - margin\n line << ' ' * indent\n min_indent = indent if min_indent.nil? || indent < min_indent\n generate_leading_spaces = false\n end\n\n case type\n when :HEADER then\n line << '=' * data\n _, _, peek_column, = peek_token\n peek_column ||= column + data\n indent = peek_column - column - data\n line << ' ' * indent\n when :RULE then\n width = 2 + data\n line << '-' * width\n _, _, peek_column, = peek_token\n peek_column ||= column + width\n indent = peek_column - column - width\n line << ' ' * indent\n when :BREAK, :TEXT then\n line << data\n else # *LIST_TOKENS\n list_marker = case type\n when :BULLET then data\n when :LABEL then \"[#{data}]\"\n when :NOTE then \"#{data}::\"\n else # :LALPHA, :NUMBER, :UALPHA\n \"#{data}.\"\n end\n line << list_marker\n peek_type, _, peek_column = peek_token\n unless peek_type == :NEWLINE then\n peek_column ||= column + list_marker.length\n indent = peek_column - column - list_marker.length\n line << ' ' * indent\n end\n end\n\n end\n\n verbatim << line << \"\\n\" unless line.empty?\n verbatim.parts.each { |p| p.slice!(0, min_indent) unless p == \"\\n\" } if min_indent > 0\n verbatim.normalize\n\n p :verbatim_end => margin if @debug\n\n verbatim\n end", "def build_verbatim margin\n verbatim = super\n\n verbatim.format = :ruby if @section == 'Examples'\n\n verbatim\n end", "def render_spacer\n puts \"\\n\"\n end", "def build_paragraph margin\n p :paragraph_start => margin if @debug\n\n paragraph = RDoc::Markup::Paragraph.new\n\n until @tokens.empty? do\n type, data, column, = get\n\n if type == :TEXT and column == margin then\n paragraph << data\n\n break if peek_token.first == :BREAK\n\n data << ' ' if skip :NEWLINE\n else\n unget\n break\n end\n end\n\n paragraph.parts.last.sub!(/ \\z/, '') # cleanup\n\n p :paragraph_end => margin if @debug\n\n paragraph\n end", "def build_paragraph margin\n p :paragraph_start => margin if @debug\n\n paragraph = RDoc::Markup::Paragraph.new\n\n until @tokens.empty? do\n type, data, column, = get\n\n case type\n when :INDENT then\n next if data == margin and peek_token[0] == :TEXT\n\n unget\n break\n when :TEXT then\n if column != margin then\n unget\n break\n end\n\n paragraph << data\n skip :NEWLINE\n else\n unget\n break\n end\n end\n\n p :paragraph_end => margin if @debug\n\n paragraph\n end", "def heredoc_text(lines, leading, has_margin, remove_break)\n if has_margin\n leading_pattern = /^#{Regexp.escape(leading)}/\n lines = lines.collect {|s| s.gsub(leading_pattern, '') }\n end\n result = lines.join('')\n result.gsub!(/\\r?\\n$/, '') if remove_break\n result\n end", "def build_paragraph margin\n p :paragraph_start => margin if @debug\n\n paragraph = RDoc::Markup::Paragraph.new\n\n until @tokens.empty? do\n type, data, = get\n\n case type\n when :TEXT then\n @section = 'Returns' if data =~ /\\A(Returns|Raises)/\n\n paragraph << data\n when :NEWLINE then\n if :TEXT == peek_token[0] then\n # Lines beginning with 'Raises' in the Returns section should not be\n # treated as multiline text\n if 'Returns' == @section and\n peek_token[1].start_with?('Raises') then\n break\n else\n paragraph << ' '\n end\n else\n break\n end\n else\n unget\n break\n end\n end\n\n p :paragraph_end => margin if @debug\n\n paragraph\n end", "def draw_both\n \t\" #{@spaces[:space_1]} | #{@spaces[:space_2]} | #{@spaces[:space_3]}\\t\\t\" +\n \t\" #{@sample[:space_1]} | #{@sample[:space_2]} | #{@sample[:space_3]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\t\\t\" + \" _____|_____|____\\n\" + \t\n \t\" #{@spaces[:space_4]} | #{@spaces[:space_5]} | #{@spaces[:space_6]}\\t\\t\" +\n \t\" #{@sample[:space_4]} | #{@sample[:space_5]} | #{@sample[:space_6]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\t\\t\" + \" _____|_____|____\\n\" +\n \t\" #{@spaces[:space_7]} | #{@spaces[:space_8]} | #{@spaces[:space_9]}\\t\\t\" +\n \t\" #{@sample[:space_7]} | #{@sample[:space_8]} | #{@sample[:space_9]}\\n\" +\n \t\t\t\t\t \" | | \\t\\t\" + \" | | \\n\\n\"\n end", "def spacer\n puts \"\\n----------------------------\\n\"\nend", "def wring_heredoc\n encode(universal_newline: true)\n .split(\"\\n\") # split into lines\n .map( &:strip ) # strip them\n .delete_if( &:blank? ) # delete blank lines\n .join \" \" # and join with whitspace\n end", "def text hard_break = nil\n @parts.map do |part|\n if RDoc::Markup::HardBreak === part then\n '%1$s%3$*2$s' % [hard_break, @indent, ' '] if hard_break\n else\n part\n end\n end.join\n end", "def print_in_box(text)\n width = text.size\n result = <<EOS\n+-#{'-' * width}-+\n| #{' ' * width} |\n| #{text} |\n| #{' ' * width} |\n+-#{'-' * width}-+\nEOS\n result\nend", "def newParagraphSpacer(n) \n n.times {puts \" \" }\nend", "def center(width)\n spaces_needed = width - self.print_width\n left_side = spaces_needed / 2\n right_side = spaces_needed - left_side\n (\" \" * left_side) << self << (\" \" * right_side)\n end", "def wrap_in_border\n puts border if border?\n yield\n print border if border?\n end", "def draw_current \t \n \t\" #{@spaces[:space_1]} | #{@spaces[:space_2]} | #{@spaces[:space_3]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\n\" +\n \t\" #{@spaces[:space_4]} | #{@spaces[:space_5]} | #{@spaces[:space_6]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\n\" +\n \t\" #{@spaces[:space_7]} | #{@spaces[:space_8]} | #{@spaces[:space_9]}\\n\" +\n \t\t\t\t\t\t \" | | \\n\\n\"\n end", "def horizontalSpacer(n , text)\n n.times {print \" \"}\n puts text\nend", "def unindent line\n if @options[:unindent] and\n @program.new_line? and\n margin = @margins.last and\n crown = @crowns.first\n then\n line.gsub(/^#{margin}/, crown)\n else\n line\n end\n end", "def standard_gap\n \" \"\n end", "def draw_sample\n \t\" #{@sample[:space_1]} | #{@sample[:space_2]} | #{@sample[:space_3]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\n\" +\n \t\" #{@sample[:space_4]} | #{@sample[:space_5]} | #{@sample[:space_6]}\\n\" +\n \t\t\t\t\t \" _____|_____|____\\n\" +\n \t\" #{@sample[:space_7]} | #{@sample[:space_8]} | #{@sample[:space_9]}\\n\" +\n \t\t\t\t\t\t \" | | \\n\\n\"\n\n end", "def spacing\n puts \"\"\n puts \"\"\n puts \"\"\n end", "def print_in_box(text)\n length = text.size\n horizontal_border = \"+-\" + (\"-\" * length) + \"-+\"\n empty_border = \"| \" + (\" \" * length) + \" |\"\n content = \"| #{text} |\"\n \n puts horizontal_border\n puts empty_border\n puts content\n puts empty_border\n puts horizontal_border\nend", "def accept_verbatim verbatim\n indent = ' ' * (@indent + 2)\n\n verbatim.parts.each do |part|\n @res << indent unless part == \"\\n\"\n @res << part\n end\n\n @res << \"\\n\"\n end", "def accept_verbatim verbatim\n indent = ' ' * (@indent + 4)\n\n verbatim.parts.each do |part|\n @res << indent unless part == \"\\n\"\n @res << part\n end\n\n @res << \"\\n\"\n end", "def generate_separators()\n command = \"echo '================================================================================'\"\n return command + \"\\n\"\nend", "def indent_atom; \" \"; end", "def surround\n\tputs \"{\"\n\tyield\n\tputs \"}\"\nend", "def wrap(text)\n return text if @done\n\n text = \"#{@pre_wrap.values}#{text}\" if @pre_wrap\n\n if dyn_params[:id]\n @tag ||= 'div'\n end\n\n if @tag\n if text.blank? && EMPTY_TAGS.include?(@tag)\n res = \"#{@pre_wrap}<#{@tag}#{params_to_html}#{@append}/>\"\n else\n res = \"<#{@tag}#{params_to_html}#{@append}>#{text}</#{@tag}>\"\n end\n else\n res = text\n end\n @done = true\n\n (@space_before || '') + res + (@space_after || '')\n end", "def short_vertical_line\n html = <<-eol\n <div class=\"short-line-container\">\n <div class=\"fam-tree-marked-right\"></div>\n <div class=\"fam-tree-unmarked\"></div>\n </div>\n eol\n html.html_safe\n end", "def indent\n return unless blank?\n write(' ' * @indentation)\n self\n end", "def escape\n puts \"\"\n puts \" \" + \"_\" * 40\n puts \"\"\n end", "def pretty_console_block(text, custom_delimiter_color=nil)\n line_width = 20\n result = \"\"\n delimiter = \"\\n#{\"-\" * line_width}\\n\"\n colored_delimiter = delimiter.send(custom_delimiter_color&.to_sym || :green)\n result += colored_delimiter\n result += text.rjust(line_width / 2).ljust(line_width)\n result += colored_delimiter\n result\n end", "def margin(indicator = nil)\n lines = self.dup.split($/)\n \n min_margin = 0\n lines.each do |line|\n if line =~ /^(\\s+)/ && (min_margin == 0 || $1.size < min_margin)\n min_margin = $1.size\n end\n end\n lines.map { |line| line.sub(/^\\s{#{min_margin}}/, '') }.join($/)\n end", "def keep_together(content, size = nil, before = 0, after = 0)\n test_width = @pdf.columns? ? @pdf.column_width : @pdf.absolute_right_margin - @pdf.left_margin\n total_height = before\n more_to_add = true\n t = content\n while more_to_add\n total_height += @pdf.font_height(size)\n t = @pdf.add_text_wrap(0, 0, test_width, t, size, :left, 0, true)\n more_to_add = false if t.blank?\n end\n total_height += after\n # puts \"pdf.y = #{@pdf.y}, total_height = #{total_height}, bottom margin = #{@pdf.bottom_margin}\"\n if @pdf.y - total_height < @pdf.bottom_margin\n start_new_page\n @x = @pdf.left_margin\n print \"[newline:keep]\"\n end\n end", "def go\n puts Rainbow(<<-PARAGRAPH # hyphen allows the end marker to be indented\n \\n\\n\\n\n /$$ /$$ /$$ /$$$$$$$$ /$$ /$$\n | $$ | $$ |__/|__ $$__/ |__/| $$\n | $$ | $$ /$$$$$$ /$$$$$$ /$$$$$$ /$$ | $$ /$$$$$$ /$$| $$ /$$$$$$$\n | $$$$$$$$ |____ $$ /$$__ $$ /$$__ $$| $$ | $$ |____ $$| $$| $$ /$$_____/\n | $$__ $$ /$$$$$$$| $$ \\ $$| $$ \\ $$| $$ | $$ /$$$$$$$| $$| $$| $$$$$$\n | $$ | $$ /$$__ $$| $$ | $$| $$ | $$| $$ | $$ /$$__ $$| $$| $$ \\____ $$\n | $$ | $$| $$$$$$$| $$$$$$$/| $$$$$$$/| $$ | $$| $$$$$$$| $$| $$ /$$$$$$$/\n |__/ |__/ \\_______/| $$____/ | $$____/ |__/ |__/ \\_______/|__/|__/|_______/\n | $$ | $$\n | $$ | $$\n |__/ |__/ \\n\n PARAGRAPH\n ).blue.bright.blink\nend", "def justify_again\n content = ['Table of Contents', 'Chapter 1: Numbers', 'page 1', 'Chapter 2: Letters', 'page 72', 'Chapter 3: Variables', 'page 118']\n lineWidth = 40\n puts (content[0].center(lineWidth))\n puts (content[1].ljust(lineWidth/2) + content[2].rjust(lineWidth/2))\n puts (content[3].ljust(lineWidth/2) + content[4].rjust(lineWidth/2))\n puts (content[5].ljust(lineWidth/2) + content[6].rjust(lineWidth/2))\nend", "def margin(indicator = nil)\n lines = self.dup.split($/)\n\n min_margin = 0\n lines.each do |line|\n if line =~ /^(\\s+)/ && (min_margin == 0 || $1.size < min_margin)\n min_margin = $1.size\n end\n end\n lines.map { |line| line.sub(/^\\s{#{min_margin}}/, '') }.join($/)\n end", "def print_in_box(text)\n top_bottom_border = \"+\" + (\"-\" * (text.size + 2)) + \"+\"\n spacer_line = \"|\" + (\" \" * (text.size + 2)) + \"|\"\n message_line = \"| \" + text + \" |\"\n\n puts top_bottom_border\n puts spacer_line\n puts message_line\n puts spacer_line\n puts top_bottom_border\nend", "def accept_verbatim verbatim\n throw :done if @characters >= @character_limit\n input = verbatim.text.rstrip\n\n text = truncate input\n text << ' ...' unless text == input\n\n super RDoc::Markup::Verbatim.new text\n\n add_paragraph\n end", "def spacing; 0; end", "def spacing(element)\n return NEWLINE * 2 if BLOCK.include? element\n return NEWLINE if ROW.include? element\n ''\n end", "def test_block_quotes_preceded_by_spaces\n markdown = @markdown.render(\n \"A wise man once said:\\n\\n\" +\n \" > Isn't it wonderful just to be alive.\\n\"\n )\n html_equal \"<p>A wise man once said:</p>\\n\\n\" +\n \"<blockquote><p>Isn't it wonderful just to be alive.</p>\\n</blockquote>\\n\",\n markdown\n end", "def test_block_quotes_preceded_by_spaces\n markdown = @markdown.render(\n \"A wise man once said:\\n\\n\" +\n \" > Isn't it wonderful just to be alive.\\n\"\n )\n html_equal \"<p>A wise man once said:</p>\\n\\n\" +\n \"<blockquote><p>Isn't it wonderful just to be alive.</p>\\n</blockquote>\\n\",\n markdown\n end", "def generate_white_spaces\n #Plain background\n if values_bits[Constants::V_Type_of_BG] > 4.5 \n if @vertical\n @white_space_w = @width - @sides_margin*2 \n @white_space_h = @height - (@main_image.height + @upper_img_margin + @upper_margin*2)\n @white_space_x = @sides_margin\n @white_space_y = values_bits[Constants::V_Image_position] < 4.5 ? @main_image.height+@upper_margin+@upper_img_margin : @upper_margin\n else\n @white_space_w = @width - (@main_image.width + @sides_img_margin + @sides_margin*2)\n @white_space_h = @height - @upper_margin*2\n @white_space_x = values_bits[Constants::V_Image_position] < 4.5 ? @main_image.width+2*@sides_margin : @sides_margin\n @white_space_y = @upper_margin\n end\n #Image as background\n else \n @white_space_w= @width - @sides_margin*2\n @white_space_h= @height - @upper_margin*2\n @white_space_x= @sides_margin\n @white_space_y= @upper_margin\n end\n \n @max_width = (@white_space_w.to_f * 0.60).to_i \n @max_width -= max_width%20 == 0 ? 0 : max_width%20\n # @groups.each do |g|\n # g.max_width = @max_width\n # end\n end", "def wrap(width)\n width ||= 80\n output = []\n indent = ''\n\n text = gsub(/\\t/, ' ')\n\n text.lines do |line|\n line.chomp! \"\\n\"\n if line.length > width\n indent = if line.uncolor =~ /^(\\s*(?:[+\\-*]|\\d+\\.) )/\n ' ' * Regexp.last_match[1].length\n else\n ''\n end\n new_lines = line.split_line(width)\n\n while new_lines.length > 1 && new_lines[1].length + indent.length > width\n output.push new_lines[0]\n\n new_lines = new_lines[1].split_line(width, indent)\n end\n output += [new_lines[0], indent + new_lines[1]]\n else\n output.push line\n end\n end\n output.map!(&:rstrip)\n output.join(\"\\n\")\n end", "def draw\n\t\tputs \"\\n\"\n\t\tmid = (@height/2.0).ceil\n\t\tfor line in 1..@height\n\t\t\tspace0 = (mid - (mid-line).abs).abs\n\t\t\tspace1 = (mid - line).abs * 2 - 1\n\t\t\tputs space1 > 0 ?\n\t\t\t\t \" \" * space0 + \"X \" + \" \" * space1 + \"X\" :\n\t\t\t\t \" \" * space0 + \"X\"\n\t\tend\n\tend", "def surround\r\n puts '{'\r\n yield\r\n puts '}'\r\nend", "def verbatim(input)\n @stream.print \"#{current_indent}#{input}\"\n end", "def separator\n puts \" \"\n puts pastel.bright_magenta(\"======================================================\")\n puts \" \"\n end", "def separator\n puts \" \"\n puts pastel.bright_magenta(\"======================================================\")\n puts \" \"\n end", "def separator\n puts \" \"\n puts pastel.bright_magenta(\"======================================================\")\n puts \" \"\n end", "def format_as_indented_block_html(name, attr, body, indent); end", "def pdf_bracket(pdf, x, y, w, h)\n r = 5\n\n pdf.stroke_style( PDF::Writer::StrokeStyle.new(1) )\n pdf.stroke_color( Color::RGB::Grey )\n pdf.rounded_rectangle(x, y, w, h, r).stroke # x, y, w, h, r\n \n pdf.stroke_style( PDF::Writer::StrokeStyle.new(8) )\n pdf.stroke_color( Color::RGB::White )\n pdf.rectangle(x + r + 6, y + 2, w - (2 * (r + 6)), -(h + 2) ).stroke\n end", "def build\n CGI.escapeHTML(@text).gsub(\"\\n\", '<br>')\n end", "def justify\n lineWidth = 40\n puts (\"Table of Contents\".center(lineWidth))\n puts (\"Chapter 1: Numbers\".ljust(lineWidth/2) + \"page 1\".rjust(lineWidth/2))\n puts (\"Chapter 2: Letters\".ljust(lineWidth/2) + \"page 72\".rjust(lineWidth/2))\n puts (\"Chapter 3: Variables\".ljust(lineWidth/2) + \"page 118\".rjust(lineWidth/2))\nend", "def center_with_strlen(strlen)\n linefill_length = TermInfo.screen_size[1]\n len = linefill_length - strlen\n len = 0 if len < 0\n \" \" * (len / 2) + self\n end", "def banner(text, line_width=40)\n banner_text = \"=\" * line_width\n banner_text << \"\\n\"\n banner_text << text.center(line_width)\n banner_text << \"\\n\"\n banner_text << \"=\" * line_width\n puts banner_text\n nil\n end", "def emit_break(indent)\n\n # number of newlines to emit\n break_value = block_break_value\n\n add_to_doc(\"\\n\" * break_value)\n # add indent if there *was* a break\n add_to_doc(\" \" * indent) if indent >0 && break_value > 0\n end", "def print_in_box(str)\n dash_inserts = '-' * str.length\n horiz_border = '+-' + dash_inserts + '-+'\n space_inserts = ' ' * str.length\n padding_border = '| ' + space_inserts + ' |'\n puts horiz_border\n puts padding_border\n puts '| ' + str + ' |'\n puts padding_border\n puts horiz_border\nend", "def surround\n puts '{'\n yield\n puts '}'\nend", "def draw\n\t\t# NOTE: consider adjusting margins for Text resize, such that the bottom margin matches up with the baseline of the text.\n\t\tsuper()\n\tend", "def build_footer\n pad(10) do\n pdf_writer.y = pdf_writer.absolute_bottom_margin + 10\n add_text \"Copyright 2010 - Sand Bridge Software\", :font_size => 8\n end\n end", "def build_footer\n pad(10) do\n pdf_writer.y = pdf_writer.absolute_bottom_margin + 10\n add_text \"Copyright 2010 - Sand Bridge Software\", :font_size => 8\n end\n end", "def build_footer\n pad(10) do\n pdf_writer.y = pdf_writer.absolute_bottom_margin + 10\n add_text \"Copyright 2010 - Sand Bridge Software\", :font_size => 8\n end\n end", "def border\n puts \"--------------------------------\".center(75)\nend", "def context_line(lines, index, padding, prefix=nil)\n return '' if index < 1 || index > lines.size\n margin = prefix ? prefix * index.to_s.size : index.to_s\n \"#{margin}#{' ' * ([padding - margin.size, 0].max)} #{lines[index - 1]}\"\n end", "def write_html(indent,part)\n# \"<!-- #{indent} --> #{' '*(if indent<0 then 0 else indent end)}#{part}\\n\"\n \"#{' '*(if indent<0 then 0 else indent end)}#{part}\\n\"\n end", "def draw_segment(character, offset)\n puts \"#{' ' * offset}#{character}\"\nend", "def wrap text\n return unless text && !text.empty?\n\n text_len = @width - @indent\n\n text_len = 20 if text_len < 20\n\n re = /^(.{0,#{text_len}})[ \\n]/\n next_prefix = ' ' * @indent\n\n prefix = @prefix || next_prefix\n @prefix = nil\n\n @res << prefix\n\n while text.length > text_len\n if text =~ re then\n @res << $1\n text.slice!(0, $&.length)\n else\n @res << text.slice!(0, text_len)\n end\n\n @res << \"\\n\" << next_prefix\n end\n\n if text.empty? then\n @res.pop\n @res.pop\n else\n @res << text\n @res << \"\\n\"\n end\n end", "def draw(text)\n printf \"%s %-#{(columns / 3) - 5}s \" % [V_SEP, text]\n end", "def print_in_box(message)\n width = message.length + 2\n line = '++'\n space = '||'\n banner = \"| #{message} |\"\n\n (width).times do |i|\n line.insert(1,'-')\n space.insert(1,' ')\n end\n\n puts line\n puts space\n puts banner\n puts space\n puts line\nend", "def wrap(s, width=80)\n s.gsub(/(.{1,#{width}})(\\s+|\\Z)/, \"\\\\1\\n\")\nend", "def body_formatted\n return \"\" if body == nil || body == \"\"\n start_pos = body.downcase.index(constraint.phrase.downcase)\n return body if start_pos == nil\n\n end_pos = start_pos + constraint.phrase.length\n\n # Increment end_pos until we've reached the end of the current word (due to pluralization issues) or reached the end of the body\n until end_pos == body.length || /[^A-Za-z]/.match(body[end_pos])\n end_pos += 1\n end\n\n\n new_body = body.clone\n new_body.insert end_pos, '</strong>'\n new_body.insert start_pos, '<strong>'\n return new_body\n end", "def print_in_box(string)\n lines = string.scan(/.{1,76}/)\n width = lines.first.to_s.size + 2\n top_bot = \"+#{'-' * width}+\"\n padding = \"|#{' ' * width}|\"\n text = lines.map { |line| \"| #{line.ljust(width - 2)} |\" }\n puts [top_bot, padding, text, padding, top_bot]\nend", "def print_in_box(str)\n size = str.size\n border_line = '+-' + ('-' * size) + '-+'\n empty_line = '| ' + (' ' * size) + ' |'\n text_line = '| ' + str + ' |'\n \n puts border_line\n puts empty_line\n puts text_line\n puts empty_line\n puts border_line\nend", "def draw()\n @vc.content_tag(:table) do\n @left = true\n @vc.capture do\n for col in columns do\n @vc.concat col.field(@record, self)\n end\n @vc.concat('<td colspan=3></td>'.html_safe) if !@left\n end\n end\n end", "def titleSlide()\n=begin \n print \"\\n-------------------------------------------------------------------------\\n\"\n print $titleSlideFont.write(\"Console Light Show\")\n print \"\\nA program for Joshua Bruce\\nWritten with love by Robert Leslie\\n\"\n print \"---------------------------------------------------------------------------\\n\"\n=end\n titleSlideFont = TTY::Font.new(:standard)\n titleBox = TTY::Box.frame(\n width: TTY::Screen.width-1,\n height: 15,\n border: :thick,\n align: :center,\n padding: 1\n )do\n \"#{titleSlideFont.write(\"Console Light Show\")}\n \\nA program for Joshua Bruce\\nWritten with love by Robert Leslie\\n2019\"\n end\n print titleBox\n menu()\nend", "def markup\n unless @text.empty?\n line = fix_markup(\"#{@text.join(\"\").strip}#{@last_tag_end}\")\n @lines << line\n @text = []\n end\n if @footer.join(\"\").strip.empty?\n if @lines.last.empty?\n output = @lines[0..-2].join(\"\\n\")\n else\n output = @lines.join(\"\\n\")\n end\n else\n output = %Q|#{@lines.join(\"\\n\")}\\n#{@footer.join(\"\")}|\n end\n output\n end", "def wrap(text, line_width = 100)\n text.gsub(/(.{1,#{line_width}})/, \"\\\\1\\n\")\n end", "def bob_left_span\n raw '<div class=\"row\">' \\\n ' <div class=\"large-8 medium-6 small-12 columns\">'\n end", "def indent_out\n @indent << \" \"\n end", "def wrap(width, width2 = nil)\n lines = []\n line = \"\"\n line_len = 0\n fragments.each do |frag|\n frag_len = frag.gsub(/\\e\\[\\d+(;\\d+)*m/, \"\").size\n if line_len.zero?\n line = frag\n line_len = frag_len\n elsif width && line_len + 1 + frag_len > width\n lines << line\n line = frag\n line_len = frag_len\n width = width2 if width2\n else\n line_len += frag_len + 1\n line = \"#{line} #{frag}\"\n end\n end\n lines << line if line_len.positive?\n lines\n end", "def print_in_box(str)\n str_length = str.length\n puts first_horizontal_line = \"+ #{\"-\" * str_length} +\"\n puts second_horizontal_line = \"| #{\" \" * str_length} |\"\n puts third_horizontal_line = \"| #{str} |\"\n puts fourth_horizontal_line = \"| #{\" \" * str_length} |\"\n puts fifth_horizontal_line = \"+ #{\"-\" * str_length} +\"\nend", "def print_in_box(text)\n text = text[0, MAX_SIZE]\n pad1 = ''.center(text.size, '-')\n pad2 = ''.center(text.size, ' ')\n\n puts(\"+-#{pad1}-+\n| #{pad2} |\n| #{text} |\n| #{pad2} |\n+-#{pad1}-+\")\nend", "def spacing\n return 8\n end", "def spacing\n return 8\n end", "def to_s # {{{\n c = wrap( self.content.to_s.chomp )\n t = wrap( self.title.to_s.chomp )\n\n<<EOS\n|^\\___________________ [ #{self.source.to_s } ] _________________________________/^|\n\n\\t'#{t}'\n\n\\t#{c}\n\n|/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\|\n\nEOS\n end", "def frame(text, char)\n width = text.max { |a,b| a.length <=> b.length }.size + 4\n output = \"\" << \"#{char}\" * width << \"\\n\"\n text.each { |line| output << \"#{char} #{line}\" << \"%0#{width - line.size - 2}s\" % char << \"\\n\" }\n output << \"#{char}\" * width\nend", "def indent_text( text, mod, first_line = true )\n\t\t\treturn \"\" if text.to_s.empty?\n spacing = indent( mod )\n text = text.gsub( /\\A([^\\n])/, \"#{ spacing }\\\\1\" ) if first_line\n\t\t\treturn text.gsub( /\\n^([^\\n])/, \"\\n#{spacing}\\\\1\" )\n\t\tend", "def indent()\n file = Tempfile.new(\"out\")\n infile = Tempfile.new(\"in\")\n file.write(self.to_s)\n file.flush\n bufc = \"FOO\"\n\n tmppos = @pos\n\n message(\"Auto format #{@fname}\")\n\n if [\"chdr\", \"c\", \"cpp\"].include?(get_file_type())\n\n #C/C++/Java/JavaScript/Objective-C/Protobuf code\n system(\"clang-format -style='{BasedOnStyle: LLVM, ColumnLimit: 100, SortIncludes: false}' #{file.path} > #{infile.path}\")\n bufc = IO.read(infile.path)\n elsif get_file_type() == \"Javascript\"\n cmd = \"clang-format #{file.path} > #{infile.path}'\"\n debug cmd\n system(cmd)\n bufc = IO.read(infile.path)\n elsif get_file_type() == \"ruby\"\n cmd = \"rufo #{file.path}\"\n debug cmd\n system(cmd)\n bufc = IO.read(file.path)\n else\n return\n end\n self.update_content(bufc)\n center_on_current_line #TODO: needed?\n file.close; file.unlink\n infile.close; infile.unlink\n end", "def tidy(data)\n indent = 0\n data.split(/\\n/).map do |line|\n line.gsub!(/^\\s*/, '')\n next if line.empty?\n indent -= 1 if line =~ /^\\s*\\}\\s*$/\n line = (' ' * (indent * 2)) + line\n indent += 1 if line =~ /\\{\\s*$/\n line\n end.compact.join(\"\\n\") + \"\\n\"\n end", "def inner(el, indent); end", "def _block(color, text, size)\n\t\t\"#{_fmt(:white, '[')}#{_fmt(color, text, size)}#{_fmt(:white, ']')}\"\n\tend", "def html\n #this is a way to create longer strings in place easily.\n x = <<DELIM\n<html>\n<body>\n#{yield}\n</body>\n</html>\nDELIM\nend", "def to_html\n # output the segments, but adjust the indentation\n indent = 0\n html = \"<!-- begin generated output -->\\n\"\n @out.each do |part|\n case\n when part =~ /^<\\/.*>$/\n indent -= 1\n html << write_html(indent,part)\n when part =~ /^<.*<\\/.*>$/\n html << write_html(indent,part)\n when part =~ /^<.*\\/>$/\n html << write_html(indent,part)\n when part =~ /^<.*>$/\n html << write_html(indent,part)\n indent += 1\n else\n html << write_html(indent,part)\n end\n end\n # return the formatted string\n html << \"<!-- end generated output -->\\n\"\n return html\n end", "def prettybox_bottomonly(html_options, &proc)\n raise ArgumentError, \"Missing block\" unless block_given?\n concat(tag(\"div\", html_options, true), proc.binding)\n concat(\"<div class=\\\"prettybox_inside\\\">\", proc.binding)\n yield\n concat(\"</div><div class=\\\"prettybox_bot\\\">\n <div>&nbsp;</div>\n </div>\n </div>\", proc.binding)\n end", "def print_in_box(str)\n border = '+' + ('-' * (str.size + 2)) + '+'\n padding = '|' + (' ' * (str.size + 2)) + '|'\n text = '| ' + str + ' |'\n puts border, padding, text, padding, border\nend", "def spacing\r\n return 8\r\n end", "def decoration(number, line_length)\n (\"=\" * number * (line_length+1)) << \"\\n\"\nend", "def to_pdf\n indent = @lines.first.match(/\\$\\s*/)[0].length\n source = @lines.map{|line| escape_xml(line[indent..-1])}.join(\"\\n\")\n \"<table width='100%' border='0' cellpadding='10'><tr>\"+\n \"<td bgcolor='#F0F0F0'><pre>#{source}</pre>\"+\n \"</td></tr></table><p></p>\"\n end" ]
[ "0.78023046", "0.71912265", "0.61379147", "0.61276263", "0.58679205", "0.57041734", "0.5671685", "0.5600203", "0.5551709", "0.5530641", "0.55081743", "0.5490407", "0.5484892", "0.5384266", "0.5378512", "0.53358114", "0.5310175", "0.52667063", "0.5237795", "0.52332526", "0.52236503", "0.52044165", "0.5184852", "0.51824236", "0.5170267", "0.51693374", "0.51554203", "0.5133554", "0.51300293", "0.5127379", "0.51222837", "0.51215875", "0.5090241", "0.50885016", "0.5085972", "0.50854254", "0.507799", "0.5067324", "0.5060582", "0.50592464", "0.5056825", "0.5052037", "0.5052037", "0.5049256", "0.5040869", "0.50402784", "0.50376105", "0.5026492", "0.5022614", "0.5022614", "0.5022614", "0.5016008", "0.5012864", "0.5007557", "0.50049967", "0.49950162", "0.49938574", "0.49852479", "0.49787423", "0.49767512", "0.49713206", "0.49694684", "0.49694684", "0.49694684", "0.4965028", "0.49632144", "0.49621063", "0.495594", "0.49547437", "0.49497414", "0.49466917", "0.49414647", "0.49405038", "0.4940468", "0.49365726", "0.49298832", "0.4929206", "0.4923343", "0.4918967", "0.49068332", "0.49066612", "0.4902781", "0.4895431", "0.48860353", "0.48707208", "0.48707208", "0.48702946", "0.4868795", "0.48582363", "0.48556516", "0.48507437", "0.48456582", "0.4842957", "0.48399317", "0.48355103", "0.48324051", "0.4831521", "0.48306033", "0.48288128", "0.48275948" ]
0.7935075
0
Pulls the next token from the stream.
def get @current_token = @tokens.shift p :get => @current_token if @debug @current_token end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def next\n\t\tif @next_token\n\t\t\ttoken = @next_token\n\t\t\t@next_token = nil\n\t\t\treturn token\n\t\telse\n\t\t\ttoken = read_token\n\t\t\treturn token\n\t\tend\n\tend", "def next\n token = next_token\n token = next_token while token&.empty?\n token\n end", "def get_token\n @tokenbuf << read_token if @tokenbuf.length == 0\n return @tokenbuf.shift\n end", "def next_token\n @tokens.shift\n end", "def next_token\n tokens.shift\n end", "def next_token\r\n if !@token.following.nil?\r\n\t\t\t@token = @token.following\r\n\t\t\treturn @token.value\r\n\t\tend\r\n\r\n\t\tscan(@token)\r\n\t\treturn @token.value\r\n end", "def next\n catch :done do\n while !(info = progress)\n # do nothing - waiting for token\n end\n return info # got token\n end\n return nil # got end of sequence\n end", "def next\n @tok ||= read_token\n @tok, tok = nil, @tok\n @prev = tok\n return tok\n end", "def pop_token\n @token_stream.pop\n end", "def pop_token\n @token_stream.pop\n end", "def next_token\n\t\t@token = @input.next_token\n\tend", "def next_token\n\t\tif (token = @tokens.shift) != nil\n\t\t\t@copy << token\n\t\t\treturn token.get_token\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend", "def next_token\n\t\t@tokens.next_token\n\tend", "def next_token; end", "def peek\n @tok ||= read_token\n end", "def consume\n cur = @current_token\n next_token\n return cur\n end", "def peek_next(token)\r\n\t\tif !token.following.nil?\r\n\t\t return token.following\r\n\t\tend\r\n\r\n\t\tpeekToken = Token.new\r\n\t\tscan(peekToken)\r\n\t\ttoken.following = peekToken\r\n\t\treturn peekToken\r\n\tend", "def next\n if @state == :start && @scanner.eos?\n return nil\n else\n scan_next_token\n end\n end", "def next()\n @stream.next\n end", "def peek_token(n=1)\n n.times{|x| @tokenbuf << read_token if @tokenbuf.length == 0 }\n return @tokenbuf[n-1]\n end", "def next_token\n @state = 1\n value = \"\"\n recovery_data = [0, 0]\n\n while !@stream.eof?\n char = @stream.read(1)\n next_state = get_next_state(char)\n\n # Move to the next state.\n if next_state\n if recognizable?\n recovery_data = [@state, 0]\n end\n\n value << char\n recovery_data[1] += 1\n @state = next_state\n else\n # Recognise the final token.\n if recognizable?\n @stream.seek(@stream.pos - 1)\n break\n else\n # Recoverable error.\n if recovery_data[0] > 0\n value = recover_from_error!(recovery_data, value)\n break\n # Fatal lexical error.\n else\n raise Bolverk::ASM::LexicalError, \"Disallowed token: #{char} on line #{@stream.line_number}\"\n end\n end\n end\n end\n\n build_token(value)\n end", "def token\n item = read\n return item['token'] if item['token']\n token_reset\n read['token']\n end", "def next_token\n @current_token = @lexer.next_token\n end", "def next\n if @next.is_a? TokenSource\n @next = @next.next\n return @next \n end\n @next\n end", "def next()\n if @ss.scan_until(token_re)\n term = @ss.matched\n term_end = @ss.pos\n term_start = term_end - term.size\n else\n return nil\n end\n\n return Token.new(normalize(term), term_start, term_end)\n end", "def next_token; @stack.shift; end", "def next_token\n raise NotImplementedError\n end", "def current_token\n @stream.current_token\n end", "def next_token\n\t\tif ((tok = @tokensList.shift) != nil)\n\t\t\t@tokensAux << tok\n\t\t\treturn tok.idAndValue\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend", "def read_next_token(token_class)\n if @next_token\n return @next_token\n else\n # check for a match on the specified class first\n if match(token_class)\n return @next_token\n else\n # now check all the tokens for a match\n Taxonifi::Splitter::Tokens.send(@token_list).each {|t|\n return @next_token if match(t)\n }\n end\n # no match, either end of string or lex-error\n if @input != ''\n raise(Taxonifi::Splitter::SplitterError, \"Lexer Error, unknown token at |#{@input[0..20]}...\", caller)\n else\n return nil\n end\n end\n end", "def peek_token(amount = 1)\n index = @token_index + amount\n @tokens[index]\n end", "def next_token()\n raise LexicalError.new(\"No input text was provided.\", LexemePosition::at_start) if token_recognition_state == :waiting_for_input\n\n\t\tif queue.empty?\n unless token_recognition_state == :ready\n error_message = \"#{__method__} may not be called when state is #{token_recognition_state}\"\n raise LexerSetupError.new(error_message)\n end\n\n enqueue_next_tokens() # Retrieve token(s) from the input text & enqueue them\n end\n theToken = queue.dequeue()\n\t\treturn theToken\n end", "def next_token\n @sy = @tokenizer.next_token\n \n # ignore EOL tokens since no productions would accept them\n while @sy.type == TokenType::EOL_TOKEN\n @sy = @tokenizer.next_token\n end\n end", "def next_token\n token = @enum[@pointer]\n raise NonstringTokenError unless token.nil? || token.kind_of?(String) \n @pointer += 1\n token\n end", "def next\n raise IOError.new(\"Stream is at the end of file.\") if eof?\n end_of_token = false\n token = \"\"\n while not end_of_token\n c = @file.getc\n puts \"next c: #{c.inspect} v: #{valid_char?(c)} s: #{single_char?(c)} e: #{is_end_character?(c)}\" if @debug\n if eof? then\n end_of_token = true\n elsif (single_char?(c)) then\n if (token.empty?) then\n token = c\n next_token = @file.getc\n if ('#' == token and '#' == next_token) then\n token << next_token\n else\n @file.seek(-1, IO::SEEK_CUR)\n end\n else\n @file.seek(-1, IO::SEEK_CUR)\n end\n end_of_token = true\n elsif (valid_char?(c)) then\n token << c\n elsif is_end_character?(c) then\n move_till_next_token\n end_of_token = (not token.empty?)\n end\n end\n puts \"next\" if @debug\n build_token(token)\n end", "def peek\n @tokens.at(@current)\n end", "def token_stream # :nodoc:\n end", "def peek # :nodoc:\n @tokens.peek\n end", "def consume\n @current = @tokens[@pos]\n @pos += 1 if @current\n @current\n end", "def get_next\n return if eof?\n\n @buffer << @io.gets if @buffer.empty?\n\n until @io.eof?\n line = @io.gets\n next unless line\n\n if @parser.start_new?(line) || @buffer.empty?\n @buffer << line\n break\n else\n @buffer.last << line\n end\n end\n\n return if @buffer.empty?\n @parser.parse(@buffer.slice!(0)) || self.get_next\n end", "def get_next\n return if eof?\n\n @buffer << gets if @buffer.empty?\n\n until @io.eof? && @io_buf.empty?\n line = gets\n next unless line\n\n if @parser.start_new?(line) || @buffer.empty?\n @buffer << line\n break\n else\n @buffer.last << line\n end\n end\n\n return if @buffer.empty?\n @parser.parse(@buffer.slice!(0)) || self.get_next\n end", "def peek_next()\n return nil if @at_end\n\n begin\n @reader.peek\n rescue StopIteration\n nil\n end\n end", "def peek\n @tokens[@position]\n end", "def next_token\n result = peek_token\n @start = @finish\n return result if @start >= @expr.length\n\n if @expr[@start].numeric?\n @finish = @start + 1\n while @finish < @expr.length && @expr[@finish].to_s.numeric?\n @finish = @finish + 1\n end\n else\n @finish = @start + 1\n end\n result\n end", "def peek_token\n token = @tokens.first || []\n p :peek => token if @debug\n token\n end", "def peek_token\n token = @tokens.first || []\n p :peek => token if @debug\n token\n end", "def peek\n @tokens[@pos]\n end", "def read\n return nil if self.payload.empty?\n self.offset += 1\n return self.payload.shift\n end", "def skip token_type, error = true\n type, data, = get\n\n return unless type # end of stream\n\n return @current_token if token_type == type\n\n unget\n\n raise ParseError, \"expected #{token_type} got #{@current_token.inspect}\" if\n error\n end", "def next\n ret = peek_next\n @str.slice! @last_re if ret.type != :eos\n\n ret\n end", "def peak\n\t\tif not @next_token\n\t\t\t@next_token = read_token\n\t\tend\n\t\treturn @next_token\n\tend", "def read_until_token_source\n %Q|\n var readUntilToken = function(cb) {\n Components.utils.import(\"resource://gre/modules/NetUtil.jsm\");\n\n var buffer = '', m = null;\n return function(request, context, stream, offset, count) {\n buffer += NetUtil.readInputStreamToString(stream, count);\n if (buffer.match(/^(\\\\[\\\\[\\\\w{8}\\\\]\\\\])/)) {\n if (m = buffer.match(/^(\\\\[\\\\[\\\\w{8}\\\\]\\\\])([\\\\s\\\\S]*)\\\\1/)) {\n cb(m[2]);\n buffer = '';\n }\n } else if (buffer.indexOf(\"\\\\n\") > -1) {\n cb(buffer);\n buffer = '';\n }\n };\n };\n |\n end", "def next_token\n #dputs \"@line: \" + @line\n if @state == :normal\n while true\n temp = _next_token\n unless temp == \"#white_space\" || temp == \"#comment\"\n break\n end\n end\n #dputs \"token: \" + temp\n @current_token = temp\n return temp\n else\n return :Terminate\n end\n \n end", "def next_page_token\n return if @response.nil?\n\n @response.next_page_token\n end", "def skip token_type, error = true\n type, = get\n return unless type # end of stream\n return @current_token if token_type == type\n unget\n raise ParseError, \"expected #{token_type} got #{@current_token.inspect}\" if error\n end", "def next_token(options = { should_advance?: true })\n if @current_scope.type == Scope::TYPE_MAIN && @current_scope.current_token.nil?\n token = @lexer.next_token\n @current_scope.tokens << token unless token.nil?\n end\n\n token = @current_scope.current_token\n\n advance token if options[:should_advance?] && token\n\n token\n end", "def next\n displacement = @file.gets.try(:chomp).try(:to_f)\n return nil unless displacement\n\n ret = @curr_val\n @curr_val += displacement\n ret\n end", "def each(stream)\n stream.each do |token|\n yield token if isToken? token\n end\n end", "def next\n peek.tap { @position += 1 }\n end", "def token\n @@token ||= fetch_token\n end", "def next\n fil_header[:next]\n end", "def get_token_stream\n raise NotImplementedError\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when text = ss.scan(/#{DIGIT}/) then\n action { [:DIGIT, text.to_i] }\n when text = ss.scan(/#{ADDITION}/) then\n action { [:ADDITION, text] }\n when text = ss.scan(/#{SUBSTRACTION}/) then\n action { [:SUBSTRACTION, text] }\n when text = ss.scan(/#{MULTIPLICATION}/) then\n action { [:MULTIPLICATION, text] }\n when text = ss.scan(/#{DIVISION}/) then\n action { [:DIVISION, text] }\n when text = ss.scan(/#{OPENING_PARANTHESIS}/) then\n action { [:OPENING_PARANTHESIS, text] }\n when text = ss.scan(/#{CLOSING_PARANTHESIS}/) then\n action { [:CLOSING_PARANTHESIS, text] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def peek_token(n = 0)\n raise ArgumentError.new(\"can't look back in the token stream\") if n < 0\n @enum[@pointer + n]\n end", "def shift\n ret = @tokens.shift\n get_next_tokens\n ret\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n if ss.peek(1) == \"\\n\"\n self.lineno += 1\n # line starts 1 position after the newline\n self.start_of_current_line_pos = ss.pos + 1\n end\n self.old_pos = ss.pos\n token =\n case state\n when nil then\n case\n when ss.skip(/[ \\t]+/) then\n # do nothing\n when ss.skip(/\\/\\/[^\\r\\n]*/) then\n # do nothing\n when text = ss.scan(/\\r|\\n/) then\n newline text\n when text = ss.scan(/[!=<>]=?/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/[(){},;.\\-+\\/*]/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/#{DIGIT}+(\\.#{DIGIT}+)?/) then\n action { [:NUMBER, text] }\n when text = ss.scan(/nil/) then\n action { [:NIL, text] }\n when text = ss.scan(/false/) then\n action { [:FALSE, text] }\n when text = ss.scan(/true/) then\n action { [:TRUE, text] }\n when text = ss.scan(/#{ALPHA}(#{ALPHA}|#{DIGIT})*/) then\n action { [:IDENTIFIER, text] }\n when ss.skip(/\"\"/) then\n action { [:STRING, '\"\"'] }\n when ss.skip(/\"/) then\n [:state, :IN_STRING]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :IN_STRING then\n case\n when text = ss.scan(/[^\"]+/) then\n action { [:STRING, \"\\\"#{text}\\\"\"] }\n when ss.skip(/\"/) then\n [:state, nil]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def each\n while (token = next_token)\n yield token\n end\n end", "def next_page_token\n @response.next_page_token\n end", "def pop(token_class)\n token = read_next_token(token_class)\n @next_token = nil\n if token.class != token_class\n raise(Taxonifi::Splitter::SplitterError, \"expected #{token_class.to_s} but received #{token.class.to_s} at #{@input[0..10]}...\", caller)\n else\n return token\n end\n end", "def token\n ready_token\n\n i = @buffer.index(/[\\[\\]()<>{}\\s\\/]/) || @buffer.size\n\n token_chars =\n if i == 0 and @buffer[i,2] == \"<<\" then 2\n elsif i == 0 and @buffer[i,2] == \">>\" then 2\n elsif i == 0 then 1\n else i\n end\n\n strip_space = !(i == 0 and @buffer[0,1] == '(')\n tok = head(token_chars, strip_space)\n\n if tok == \"\"\n nil\n elsif tok[0,1] == \"%\"\n @buffer = \"\"\n token\n else\n tok\n end\n end", "def next\n\t\t@ibuf = (@ibuf+1).modulo(@nbuf)\n\t\t@buffers[@ibuf]\n\tend", "def current_token\n @tokens[@token_index]\n end", "def gets\n\t\t\t\tif @buffer.nil?\n\t\t\t\t\treturn read_next\n\t\t\t\telse\n\t\t\t\t\tbuffer = @buffer\n\t\t\t\t\t@buffer = nil\n\t\t\t\t\treturn buffer\n\t\t\t\tend\n\t\t\tend", "def token\n @token\n end", "def racc_read_token(t, tok, val); end", "def next_token\n\n if @ss.bol?\n @line+=1\n @old_pos=@ss.pos\n end\n\n position=[@line,@ss.pos-@old_pos+1]\n\n return :eos if @ss.eos?\n\n case\n when text = @ss.scan(NEWLINE)\n next_token()\n when text = @ss.scan(SPACE)\n next_token()\n when text = @ss.scan(COMMENT)\n next_token()\n when text = @ss.scan(ARROW)\n return Token.new [:arrow,text,position]\n when text = @ss.scan(LT)\n return Token.new [:lt,text,position]\n when text = @ss.scan(LBRACK)\n return Token.new [:lbrack,text,position]\n when text = @ss.scan(RBRACK)\n return Token.new [:rbrack,text,position]\n when text = @ss.scan(IDENTIFIER)\n case\n when value = text.match(IDENT)\n return Token.new [:IDENT,text,position]\n when value = text.match(FLOAT)\n return Token.new [:FLOAT,text,position]\n when value = text.match(INT)\n return Token.new [:INT,text,position]\n when value = text.match(STRING)\n return Token.new [:STRING,text,position]\n when value = text.match(MODULE)\n return Token.new [:module,text,position]\n when value = text.match(CLASS)\n return Token.new [:class,text,position]\n when value = text.match(END_)\n return Token.new [:end,text,position]\n when value = text.match(ATTR)\n return Token.new [:attr,text,position]\n when value = text.match(LPAREN)\n return Token.new [:lparen,text,position]\n when value = text.match(RPAREN)\n return Token.new [:rparen,text,position]\n else\n return Token.new [:identifier,text,position]\n end\n else\n x = @ss.getch\n return Token.new [x, x,position]\n end\n end", "def peek_token\n return nil if @start >= @expr.length\n if @start == 0 && @finish == 0\n return @expr[0]\n else\n token = @expr[@start...@finish]\n\n if token.empty?\n @finish = @finish + 1\n peek_token\n else\n return token\n end\n end\n end", "def token_get()\n\t\tputs \"Here is the token \" + @token\n\tend", "def get_next()\n\t\t\treturn @next\n\t\tend", "def token\n @data[:token]\n end", "def next!() end", "def next() end", "def next() end", "def retrieve_token\n puts \"Picking up new token.\"\n parsed_json = {}\n until parsed_json[\"access_token\"]\n results = `curl -X -vvv -d 'client_id=MY_CLIENT_KEY&client_secret=MY_CLIENT_SECRET&grant_type=client_credentials' -X POST 'https://connect.gettyimages.com/oauth2/token/'`\n parsed_json = JSON.parse results\n end\n @token = parsed_json[\"access_token\"]\n end", "def next_page_token\n @page.next_page_token\n end", "def has_next_token\n\t\t@input.has_next\n\tend", "def token\n @token\n end", "def unget token = @current_token\n p :unget => token if @debug\n raise Error, 'too many #ungets' if token == @tokens.first\n @tokens.unshift token if token\n end", "def consume()\n la(1)\n return @lookahead.shift\n end", "def next\n\t\tlines.shift\n\tend", "def peek_next\n fail 'No string specified' unless @str\n\n return Token.new(:eos) if skip_space == :eos\n\n PATTERNS.each do |re, func|\n re.match(@str) do |mat|\n @last_re = re # This is what will be removed\n mat = mat.to_s\n return func.is_a?(Symbol) ? send(func, mat) : instance_exec(mat, &func)\n end\n end\n end", "def next\n connection.write(\"next\")\n end", "def next\n connection.write(\"next\")\n end", "def next\n return nil unless next?\n ensure_zone!\n @zone.records token: token\n end", "def unshift(token); end", "def token_from(data)\n extract_from(data, /Token token='(.+)'/).first rescue nil\n end", "def next\n if has_next?\n node = @stack.pop\n # keep next ready\n look_left node.right if node.right\n node.data\n end\n end", "def next_page_token\n @page&.next_page_token\n end", "def next_message\n socket.get_packet\n end" ]
[ "0.80374205", "0.7607829", "0.7580852", "0.7458197", "0.7431326", "0.7334023", "0.7309964", "0.7282369", "0.72726494", "0.72726494", "0.720337", "0.7139261", "0.7130224", "0.7061388", "0.69352496", "0.69222224", "0.68793917", "0.6832228", "0.68298364", "0.68203497", "0.6786535", "0.6773116", "0.6703368", "0.6687703", "0.6651949", "0.6638124", "0.66129625", "0.6522973", "0.6477579", "0.64771235", "0.6429677", "0.63510513", "0.6310743", "0.63067794", "0.6294412", "0.62763894", "0.6237077", "0.62301725", "0.61871266", "0.6148712", "0.6128217", "0.6068126", "0.60678196", "0.6032003", "0.60131085", "0.60131085", "0.6010291", "0.5978265", "0.5967206", "0.5964697", "0.59410447", "0.5931226", "0.5931059", "0.5904584", "0.5878403", "0.5878077", "0.58676106", "0.5862673", "0.5853231", "0.5845156", "0.58440363", "0.5842322", "0.5783224", "0.5778363", "0.57653725", "0.57627314", "0.5761609", "0.57481766", "0.5707424", "0.5697501", "0.5688199", "0.5677545", "0.5668629", "0.56593746", "0.565434", "0.56452847", "0.56442", "0.5621931", "0.56197023", "0.558933", "0.5576718", "0.5575592", "0.5575592", "0.5575038", "0.55663544", "0.5557253", "0.5556036", "0.5548152", "0.55383337", "0.5529765", "0.5506018", "0.5501043", "0.5501043", "0.549592", "0.54957926", "0.5455924", "0.54528946", "0.54464257", "0.54436535" ]
0.6346298
33
Parses the tokens into a Document
def parse indent = 0 p :parse_start => indent if @debug document = [] until @tokens.empty? do type, data, column, = get if type != :INDENT and column < indent then unget break end case type when :HEADER then document << build_heading(data) when :INDENT then if indent > data then unget break elsif indent == data then next end unget document << build_verbatim(indent) when :NEWLINE then document << RDoc::Markup::BlankLine.new skip :NEWLINE, false when :RULE then document << RDoc::Markup::Rule.new(data) skip :NEWLINE when :TEXT then unget document << build_paragraph(indent) # we're done with this paragraph (indent mismatch) break if peek_token[0] == :TEXT when *LIST_TOKENS then unget list = build_list(indent) document << list if list # we're done with this list (indent mismatch) break if LIST_TOKENS.include? peek_token.first and indent > 0 else type, data, column, line = @current_token raise ParseError, "Unhandled token #{type} (#{data.inspect}) at #{line}:#{column}" end end p :parse_end => indent if @debug document end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse(doc)\n parser = parser_class.new\n parser.run(doc)\n end", "def parse(tokenizer)\n @doc = REXML::Document.new\n @pos = @doc\n while node=tokenizer.next\n append(node)\n end\n end", "def parse_doc\n @parse_started = true\n nil while @lexer.get and parse_children\n # in case there was an error and there is still data stuff\n parse_tail\n @cc = nil\n @ret.call nil\n end", "def shallow_parse(xml_document)\n @tokens = xml_document.scan(@@xml_spe)\n end", "def tokenize(document)\n validate_document(document)\n return [] if document.empty?\n {}.tap do |hash|\n document.each_pair do |k, v|\n hash[k.to_s] = tokenize_value(k, v)\n end\n end\n end", "def process_doc(doc, verbose, check_parser, canonize_only,\n show_unconf_elts)\n\n init_doc_vars\n\n # Perform lexical parse to split document into list of tokens\n warn \"Parsing document...\\n\" if verbose\n shallow_parse(doc)\n\n if (check_parser)\n warn \"Checking parser...\\n\" if verbose\n # concatentation of tokens should be identical to original document\n if doc == tokens.join(\"\")\n puts \"Parser is okay\"\n else\n puts \"PARSER ERROR: document token concatenation differs from document\"\n end\n return nil\n end\n\n # Assign input line number to each token\n assign_line_numbers\n\n # Look for and report any error tokens returned by parser\n warn \"Checking document for errors...\\n\" if verbose\n if report_errors > 0\n warn \"Cannot continue processing document.\\n\"\n return nil\n end\n\n # Convert the token list to a tree structure\n warn \"Convert document tokens to tree...\\n\" if verbose\n if tokens_to_tree > 0\n warn \"Cannot continue processing document.\\n\"\n return nil\n end\n\n # Check: Stringify the tree to convert it back to a single string,\n # then compare to original document string (should be identical)\n # (This is an integrity check on the validity of the to-tree and stringify\n # operations; if one or both do not work properly, a mismatch should occur.)\n #str = tree_stringify\n #print str\n #warn \"ERROR: mismatch between document and resulting string\\n\" if doc != str\n\n # Canonize tree to remove extraneous whitespace\n warn \"Canonizing document tree...\\n\" if verbose\n tree_canonize\n\n if (canonize_only)\n puts tree_stringify\n return nil\n end\n\n # One side-effect of canonizing the tree is that the formatting\n # options are looked up for each element in the document. That\n # causes the list of elements that have no explicit configuration\n # to be built. Display the list and return if user requested it.\n\n if show_unconf_elts\n display_unconfigured_elements\n return nil\n end\n\n # Format the tree to produce formatted XML as a single string\n warn \"Formatting document tree...\\n\" if verbose\n tree_format\n\n # If the document is not empty, add a newline and emit a warning if\n # reformatting failed to add a trailing newline. This shouldn't\n # happen if the *DOCUMENT options are set up with exit-break = 1,\n # which is the reason for the warning rather than just silently\n # adding the newline.\n\n str = out_doc\n if !str.empty? && str !~ /\\n\\z/\n warn \"LOGIC ERROR: trailing newline had to be added\\n\"\n str << \"\\n\"\n end\n\n return str\n end", "def tokenize(doc, h)\n begin\n PlanR::TokenStream.from_array(name, doc, \n doc.plaintext_ascii.split(/\\s/) )\n rescue Exception => e\n # FIXME: log\n $stderr.puts \"[PLAINTEXT PARSER] ERROR: #{e.message}\"\n $stderr.puts e.backtrace[0,4].join(\"\\n\")\n # FIXME: better default return value\n PlanR::TokenStream.from_array(name, doc, [])\n end\n end", "def tokens\n @tokens ||= Tokeniser.instance.tokenise(text)\n end", "def tokenize\n \n end", "def index_document(repo, doc, h_tok)\n # create searchable text from tokens. this is needed because\n # lucene calls the tokenizer *anyways*.\n # NOTE: parsed_doc is in toks.doc\n toks = h_tok[name]\n text = toks.join(' ')\n # TODO: use parsed_doc.plaintext if toks.empty?\n # or use toks.join if ! toks.doc?\n # which is better?\n\n Index::lucene_index(index_path(repo), doc.path, text, \n doc.properties.to_h, ANALYZER, ANALYZER_ARGS)\n end", "def tokenize ; end", "def tokenize ; end", "def tokenize\n # Slice each character if there's a symbol there; this leaves the symbol\n # at the end of the character array\n sliced_strings = split_on_symbol_locations(text)\n\n # Convert the final character of each string into a :symbol token, and\n # the rest into a :text token\n tokens = sliced_strings.zip(symbol_locations).flat_map do |text, sym_loc|\n if sym_loc.nil?\n # If the document doesn't end with a symbol, just return text\n Token.new(:text, text) \n else\n # If it does, return both text minus symbol, and then a symbol token\n [\n Token.new(:text, text[0...-1]),\n Token.new(:symbol, sym_loc.symbol)\n ]\n end\n end\n\n # Strip any empty tokens (can occur when symbols are adjacent)\n tokens_without_empty = reject_empty_text(tokens)\n\n # Add a :nil token to the beginning to make each_cons work properly\n tokens_without_empty.unshift(Token.new(:nil, nil))\n\n # Convert spaces at the beginning of lines to :space_count tokens\n tokens_with_space_counts = tokens_without_empty.each_cons(2).flat_map do |token1, token2|\n # We're only looking for :text tokens with :newline tokens before them\n next token2 unless token1 == Token.new(:symbol, :newline) \\\n && token2.type == :text\n\n # Count the number of spaces at the beginning of the string\n spaces_at_start = token2.value.scan(/^ */).first.length\n\n # Return a space count and a text token\n [\n Token.new(:space_count, spaces_at_start),\n Token.new(:text, token2.value.gsub(/^ +/, ''))\n ]\n end\n\n # Convert :space_count tokens to indents and dedents\n indent_level = 0 # current level of indentation\n indent_amount = nil # spaces required for an indent\n tokens_with_space_counts.flat_map do |token|\n # Only look for :space_count tokens\n next token unless token.type == :space_count\n\n # If this is any form of indentation and we don't know an indent amount\n # yet, set it\n indent_amount = token.value if indent_amount.nil? && !token.value.zero?\n\n # If we still don't know, skip\n next nil if indent_amount.nil?\n\n # Work out an indent delta\n # +x = indent by x levels, -x = dedent by x levels; x must be int\n indent_delta = token.value.to_f / indent_amount - indent_level\n raise 'invalid indentation' unless indent_delta % 1 == 0.0\n\n indent_level += indent_delta.to_i\n\n # Output tokens\n [Token.new(indent_delta.positive? ? :indent : :dedent, nil)] \\\n * indent_delta.abs\n end.reject(&:nil?)\n end", "def tokens_to_tree\n\n tag_stack = [ ] # stack for element tags\n children_stack = [ ] # stack for lists of children\n children = [ ] # current list of children\n err_count = 0\n\n # Note: the text token pattern test assumes that all text tokens\n # are non-empty. This should be true, because REX doesn't create\n # empty tokens.\n\n @tokens.each_index do |i|\n token = @tokens[i]\n line_num = @line_num[i]\n tok_err = \"Error near line #{line_num}, token #{i+1} (#{token})\"\n case token\n when /\\A[^<]/ # text\n children << text_node(token)\n when /\\A<!--/ # comment\n children << comment_node(token)\n when /\\A<\\?/ # processing instruction\n children << pi_node(token)\n when /\\A<!DOCTYPE/ # DOCTYPE\n children << doctype_node(token)\n when /\\A<!\\[/ # CDATA\n children << cdata_node(token)\n when /\\A<\\// # element close tag\n if tag_stack.empty?\n warn \"#{tok_err}: Close tag w/o preceding open tag; malformed document?\\n\"\n err_count += 1\n next\n end\n if children_stack.empty?\n warn \"#{tok_err}: Empty children stack; malformed document?\\n\"\n err_count += 1\n next\n end\n tag = tag_stack.pop\n open_tag_name = extract_tag_name(tag)\n close_tag_name = extract_tag_name(token)\n if open_tag_name != close_tag_name\n warn \"#{tok_err}: Tag mismatch; malformed document?\\n\"\n warn \" open tag: #{tag}\\n\"\n warn \" close tag: #{token}\\n\"\n print_tag_stack(\"enclosing tags\", tag_stack)\n err_count += 1\n next\n end\n elt = element_node(tag, token, children)\n children = children_stack.pop\n children << elt\n else # element open tag\n # If we reach here, we're seeing the open tag for an element:\n # - If the tag is also the close tag (e.g., <abc/>), close the\n # element immediately, giving it an empty child list.\n # - Otherwise, push tag and child list on stacks, begin new child\n # list for element body.\n case token\n when /\\/>\\Z/ # tag is of form <abc/>\n children << element_node(token, \"\", [ ])\n else # tag is of form <abc>\n tag_stack << token\n children_stack << children\n children = [ ]\n end\n end\n end\n\n # At this point, the stacks should be empty if the document is\n # well-formed.\n\n if !tag_stack.empty?\n warn \"Error at EOF: Unclosed tags; malformed document?\\n\"\n print_tag_stack(\"unclosed tags\", tag_stack)\n err_count += 1\n end\n if !children_stack.empty?\n warn \"Error at EOF: Unprocessed child elements; malformed document?\\n\"\n# TODO: print out info about them\n err_count += 1\n end\n\n @tree = children\n return err_count\n end", "def parse\n _build_document\n _close_open_block_commands\n @document\n end", "def parse(tokens)\n @nodelist ||= []\n @nodelist.clear\n\n while token = tokens.shift\n\n case token\n when IsTag\n if token =~ FullToken\n\n # if we found the proper block delimitor just end parsing here and let the outer block\n # proceed\n if block_delimiter == $1\n end_tag\n return\n end\n\n # fetch the tag from registered blocks\n if tag = Template.tags[$1]\n @nodelist << tag.new($1, $2, tokens)\n else\n # this tag is not registered with the system\n # pass it to the current block for special handling or error reporting\n unknown_tag($1, $2, tokens)\n end\n else\n raise SyntaxError, \"Tag '#{token}' was not properly terminated with regexp: #{TagEnd.inspect} \"\n end\n when IsVariable\n @nodelist << create_variable(token)\n when ''\n # pass\n else\n @nodelist << token\n end\n end\n\n # Make sure that its ok to end parsing in the current block.\n # Effectively this method will throw and exception unless the current block is\n # of type Document\n assert_missing_delimitation!\n end", "def parse(source)\n @root = Document.new(tokenize(source))\n self\n end", "def parse(document_xml)\n @xml = Nokogiri::XML(document_xml)\n\n # Iterate over each element node and dispatch it to the appropriate parser\n @xml.xpath('//w:body').children.each do |node|\n case node.name\n when 'p'\n no_numbering_prop = node.xpath('.//w:numPr').length.zero? || node.xpath('.//w:numPr/w:ilvl | .//w:numPr/w:numId').length.zero?\n not_multiparagraph_list_item = (@buffer.is_a?(Swordfish::Node::List) ? node.xpath('.//w:ind[@w:left]').length.zero? : true)\n if no_numbering_prop && not_multiparagraph_list_item\n # Regular paragraph\n # (The buffer check makes sure that this isn't an indented paragraph immediately after a list item,\n # which means we're most likely dealing with a multi-paragraph list item)\n flush\n @swordfish_doc.append _node_parse_paragraph(node)\n elsif node.xpath('.//w:numPr/ancestor::w:pPrChange').length.zero?\n # List paragraph\n # (must have a numPr node, but cannot have a pPrChange ancestor, since that means\n # we are just looking at historical changes)\n # (Don't flush because we need to first ensure the list is fully parsed)\n _node_parse_list(node)\n end\n when 'tbl'\n flush\n @swordfish_doc.append _node_parse_table(node)\n end\n end\n flush\n end", "def tokenize; end", "def tokenize; end", "def parse\n return @document if @document\n\n @document = super @text, @format\n @document.file = @location\n @document\n end", "def tokenize\n @root.jso_token\n end", "def parse!(markup)\n doc(markup)\n end", "def parse_tokens(tokens)\n debug 'Starting parse of tokens received..'\n if @state != :ready\n raise_parser_error \"Attempting to start parser while already running/not in ready state (state found #{@state})\"\n end\n\n @tokens = tokens\n @token_index = 0\n reset_state :root\n\n # Continue parse loop until method returns false\n loop do\n begin\n res = parse\n break unless res\n\n step_forward\n rescue StandardError => e\n reset_state\n\n raise e\n end\n end\n\n debug 'Parsing complete'\n reset_state\n end", "def parse(text); end", "def tokens!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 59)\n\n type = TOKENS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 596:4: 'tokens' WS_LOOP '{'\n match(\"tokens\")\n ws_loop!\n match(?{)\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 59)\n\n end", "def new_token(doc, xml_token)\n token_object = Pils::Tcf::Token.new(doc, xml_token)\n if xml_token.has_attribute?('start') && xml_token.has_attribute?('end')\n token_object.boundaries= [xml_token['start'].to_i, xml_token['end'].to_i]\n end\n token_object\n end", "def parse(text)\n text = pre_proccess(text)\n text = pre_normalize(text)\n puts text.inspect if Chronic.debug\n\n tokens = Tokenizer::tokenize(' ' + text + ' ')\n tag(tokens, options)\n\n puts \"+#{'-' * 51}\\n| #{tokens}\\n+#{'-' * 51}\" if Chronic.debug\n\n token_group = TokenGroup.new(tokens, definitions(options), @now, options)\n span = token_group.to_span\n\n guess(span, options[:guess]) if span\n end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def parse(sentence)\n tokens, root = get_parse(sentence)\n base_noun_chunks = get_base_noun_chunks(tokens)\n focus = get_focus(tokens, base_noun_chunks)\n relations = get_relations(tokens, base_noun_chunks)\n \n { :tokens => tokens, # The array of token parses\n :root => root, # The index of the root word\n # The index of the focus word, \n # i.e., the one modified by a _wh_-modifier\n :focus => focus, \n :base_noun_chunks => base_noun_chunks, # the array of base noun chunks\n :relations => relations # Shortest paths between two heads\n } \n end", "def parse_whole_document(doc, base)\n base = doc_base(base)\n if (base)\n # Strip any fragment from base\n base = base.to_s.split(\"#\").first\n base = uri(base)\n add_debug(\"\") {\"parse_whole_doc: base='#{base}'\"}\n end\n\n # initialize the evaluation context with the appropriate base\n evaluation_context = EvaluationContext.new(base, @host_defaults)\n\n if @version != :\"rdfa1.0\"\n # Process default vocabularies\n load_initial_contexts(@host_defaults[:initial_contexts]) do |which, value|\n add_debug(root) { \"parse_whole_document, #{which}: #{value.inspect}\"}\n case which\n when :uri_mappings then evaluation_context.uri_mappings.merge!(value)\n when :term_mappings then evaluation_context.term_mappings.merge!(value)\n when :default_vocabulary then evaluation_context.default_vocabulary = value\n end\n end\n end\n\n traverse(root, evaluation_context)\n add_debug(\"\", \"parse_whole_doc: traversal complete'\")\n end", "def parse_paragraph; end", "def parse\n self.data = BdlFile.strip_comments self.data\n save!\n tokenize\n Instruction.create_references!\n end", "def tokens\n @tokens ||= tokenize_input\n end", "def tokens\n @tokens ||= scanner.tokenize(input)\n end", "def read_tokens()\n\n # By adding @ to tokens, we're saving it also in the instance. We're not\n # going to use that, but it might be useful later.\n @tokens = []\n\n File.open(@filename) do |input_file|\n input_file.each do |line|\n line.split.each do |word|\n word = normalize(word)\n @tokens << word unless word.empty?\n end\n end\n end\n\n @tokens\n end", "def parse(sentence)\n tokens, root = get_parse(sentence)\n base_noun_chunks = get_base_noun_chunks(tokens)\n relations = get_relations(tokens, base_noun_chunks)\n focus = get_focus(tokens, base_noun_chunks, relations)\n\n {\n :tokens => tokens, # The array of token parses\n :root => root, # The index of the root word\n :focus => focus, # The index of the focus word, i.e., the one modified by a _wh_-modifier\n :base_noun_chunks => base_noun_chunks, # the array of base noun chunks\n :relations => relations # Shortest paths between two heads\n }\n end", "def parse(program)\n return read_the_tokens(tokenize(program))\nend", "def parse_doc_data\n begin\n raw_data = File.open(\"doc_data.txt\", \"r\").read\n ary_data = raw_data.split(/\\n/)\n\n parsed_info = []\n\n ary_data.each_with_index do |elem, i|\n next_elem = ary_data[i + 1]\n\n if (elem.match(/InfoKey/) && (next_elem.match(/InfoValue/)))\n parsed_info.push(elem.split(/\\:/, 2)[1].strip => next_elem.split(/\\:/, 2)[1].strip)\n else\n if (!elem.match(/InfoValue/))\n parsed_info.push(elem.split(/\\:/, 2)[0].strip => elem.split(/\\:/, 2)[1].strip)\n end\n end\n end\n rescue\n parsed_info = []\n @convert_errors.push(\"There is no generated 'doc_data.txt' file during converting file\")\n end\n\n return parsed_info\n end", "def tokenize input\n setup_scanner input\n\n until @s.eos? do\n pos = @s.pos\n\n # leading spaces will be reflected by the column of the next token\n # the only thing we loose are trailing spaces at the end of the file\n next if @s.scan(/ +/)\n\n # note: after BULLET, LABEL, etc.,\n # indent will be the column of the next non-newline token\n\n @tokens << case\n # [CR]LF => :NEWLINE\n when @s.scan(/\\r?\\n/) then\n token = [:NEWLINE, @s.matched, *pos]\n @s.newline!\n token\n # === text => :HEADER then :TEXT\n when @s.scan(/(=+)(\\s*)/) then\n level = @s[1].length\n header = [:HEADER, level, *pos]\n\n if @s[2] =~ /^\\r?\\n/ then\n @s.unscan(@s[2])\n header\n else\n pos = @s.pos\n @s.scan(/.*/)\n @tokens << header\n [:TEXT, @s.matched.sub(/\\r$/, ''), *pos]\n end\n # --- (at least 3) and nothing else on the line => :RULE\n when @s.scan(/(-{3,}) *\\r?$/) then\n [:RULE, @s[1].length - 2, *pos]\n # * or - followed by white space and text => :BULLET\n when @s.scan(/([*-]) +(\\S)/) then\n @s.unscan(@s[2])\n [:BULLET, @s[1], *pos]\n # A. text, a. text, 12. text => :UALPHA, :LALPHA, :NUMBER\n when @s.scan(/([a-z]|\\d+)\\. +(\\S)/i) then\n # FIXME if tab(s), the column will be wrong\n # either support tabs everywhere by first expanding them to\n # spaces, or assume that they will have been replaced\n # before (and provide a check for that at least in debug\n # mode)\n list_label = @s[1]\n @s.unscan(@s[2])\n list_type =\n case list_label\n when /[a-z]/ then :LALPHA\n when /[A-Z]/ then :UALPHA\n when /\\d/ then :NUMBER\n else\n raise ParseError, \"BUG token #{list_label}\"\n end\n [list_type, list_label, *pos]\n # [text] followed by spaces or end of line => :LABEL\n when @s.scan(/\\[(.*?)\\]( +|\\r?$)/) then\n [:LABEL, @s[1], *pos]\n # text:: followed by spaces or end of line => :NOTE\n when @s.scan(/(.*?)::( +|\\r?$)/) then\n [:NOTE, @s[1], *pos]\n # >>> followed by end of line => :BLOCKQUOTE\n when @s.scan(/>>> *(\\w+)?$/) then\n [:BLOCKQUOTE, @s[1], *pos]\n # anything else: :TEXT\n else\n @s.scan(/(.*?)( )?\\r?$/)\n token = [:TEXT, @s[1], *pos]\n\n if @s[2] then\n @tokens << token\n [:BREAK, @s[2], pos[0] + @s[1].length, pos[1]]\n else\n token\n end\n end\n end\n\n self\n end", "def do_parse\n while token = next_token do\n type, *vals = token\n\n send \"lex_#{type}\", *vals\n end\n end", "def extracted_text\n tokenstream.text\n end", "def parse(doc)\n pdoc = PlanR::ParsedDocument.new(name, doc)\n\n begin\n safe_fname = Shellwords.escape(doc.abs_path)\n # FIXME: capture STDERR so these messages disappear:\n # Syntax Error: Invalid object stream\n # Syntax Error: Expected the optional content group list, but wasn't able to find it, or it isn't an Array\n info = %x{#{INFO_UTIL} -enc UTF-8 #{safe_fname}}.chomp\n properties_from_info(pdoc, info)\n # TODO: support pdftotext options?\n text = %x{#{PARSE_UTIL} -q -enc UTF-8 #{safe_fname} - }.chomp\n pdoc.add_text_block(text)\n rescue Exception => e\n # FIXME: log\n $stderr.puts \"[POPPLER] ERROR #{e.message}\"\n $stderr.puts \"INPUT: #{doc.abs_path}\"\n $stderr.puts e.backtrace[0,4].join(\"\\n\")\n end\n pdoc\n end", "def parse_document(file)\n\n hpricot_doc = create_doc(file)\n raise \"Feature not saved!\" if hpricot_doc.nil?\n\n feature = extract_feature(hpricot_doc)\n xml_document = store_xml_document(feature)\n\n feature_object_types = extract_feature_object_types(hpricot_doc, feature)\n feature_relations = extract_feature_relations(hpricot_doc, feature)\n\n #feature_names = extract_feature_names(hpricot_doc, feature)\n extract_feature_names(hpricot_doc, feature)\n\n # When a feature is saved, it caches all of its ancestor ids. \n # You need to make sure this happens for all of the features every time\n # a new batch has been imported. \n features = Feature.all\n features.each do |f|\n f.save\n end\n end", "def parse(document, options = {})\n hash = document.is_a?(Hash) ? document : JSON.parse(document)\n\n Parser::Document.new(hash, options)\n end", "def tokenize\n post(\"token\")[\"token\"]\n end", "def parse_doc doc\n # strip leading comment to margin and any implementation details (!)\n doc.gsub!(/^; */, '').gsub!(/^!.+\\n/, '')\n\n head, specs = doc.split \"\\n\\n\"\n *desc, effect = head.split ?\\n\n desc *= ?\\n\n\n cases = []\n specs.scan(StackRx).each_slice 2 do |spec|\n cases << spec.map { parse_stack _1 }\n end if specs\n\n {full: doc, desc: desc, effect: effect, cases: cases}\nend", "def parse_DOCX input_file\n\n begin\n reader = Docx::Document.open(input_file.tempfile)\n \n # Catch common error to invalid DOCX\n rescue Zip::ZipError => error\n flash[:alert] = \"Error parsing document. Is this a Word Docuemnt (docx)?\"\n return \"\"\n end\n document = Nokogiri::HTML(reader.to_html).text\n \n flash[:notice] = \"Word Document (docx) Processed.\"\n return document\n \n end", "def parser (tokens)\n\n\t# create the new, concrete syntax tree\n\t# making it global to reduce headaches (hopefully XD )\n\t$cst = ConcreteSyntaxTree.new\n\t\n\t# define some other useful, global vars\n\t$tokens = tokens\n\t$index = 0\n\t\n\t# have to ask alan about this\n\tif $tokens.length <= 1\n\t\tputs \"Insufficient code present! There is only #{$tokens.length} token here!\"\n\t\texit\n\tend\t\n\t\n\t\n\t# Engine to full burn!!!\n\t#parse(\"Program\", program)\n\tprogram\n\t\n\t\n\tbegin\n\t\tif $tokens.length != $index\n\t\t\traise EOFDetectionError.new(\"early\", $tokens[$index - 1].lineno, $tokens[$index - 1].pos)\n\t\tend\n\trescue EOFDetectionError\n\tend\n\t\t\n\t\n\t\n\treturn $cst\nend", "def parse document_file_name\n raise ParserNotDefined if @@document_parser.nil?\n \n ext = ActiveDocument::FileUtils.extension_name(document_file_name)\n io = read(document_file_name)\n \n if not @@document_parsers.empty?\n document_parser = parser_for_extension(ext)\n document_data = document_parser.parse(io)\n else\n document_data = @@document_parser.parse(io)\n end\n \n document_data.parser_added_args[:filename] = document_file_name\n \n new document_data\n end", "def parse(text)\n Rdoc.parser.convert(text).force_encoding(\"UTF-8\")\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when text = ss.scan(/select/i) then\n action { [:kw_select, text] }\n when text = ss.scan(/from/i) then\n action { [:kw_from, text] }\n when text = ss.scan(/where/i) then\n action { [:kw_where, text] }\n when text = ss.scan(/null/i) then\n action { [:kw_null, text] }\n when text = ss.scan(/not/i) then\n action { [:kw_not, text] }\n when text = ss.scan(/limit/i) then\n action { [:kw_limit, text] }\n when text = ss.scan(/offset/i) then\n action { [:kw_offset, text] }\n when text = ss.scan(/insert/i) then\n action { [:kw_insert, text] }\n when text = ss.scan(/into/i) then\n action { [:kw_into, text] }\n when text = ss.scan(/values/i) then\n action { [:kw_values, text] }\n when text = ss.scan(/create/i) then\n action { [:kw_create, text] }\n when text = ss.scan(/table/i) then\n action { [:kw_table, text] }\n when text = ss.scan(/constraint/i) then\n action { [:kw_constraint, text] }\n when text = ss.scan(/key/i) then\n action { [:kw_key, text] }\n when text = ss.scan(/primary/i) then\n action { [:kw_primary, text] }\n when text = ss.scan(/\\*/) then\n action { [:star, text] }\n when text = ss.scan(/\\(/) then\n action { [:lparen, text] }\n when text = ss.scan(/\\)/) then\n action { [:rparen, text] }\n when ss.skip(/\\s+/) then\n # do nothing\n when text = ss.scan(/or/i) then\n action { [:op_or, text] }\n when text = ss.scan(/and/i) then\n action { [:op_and, text] }\n when text = ss.scan(/[a-zA-Z]\\w*/) then\n action { [:identifier, text] }\n when text = ss.scan(/=/) then\n action { [:op_equal, text] }\n when text = ss.scan(/<=/) then\n action { [:op_lte, text] }\n when text = ss.scan(/>=/) then\n action { [:op_gte, text] }\n when text = ss.scan(/</) then\n action { [:op_lt, text] }\n when text = ss.scan(/>/) then\n action { [:op_gt, text] }\n when text = ss.scan(/;/) then\n action { [:semicolon, text] }\n when text = ss.scan(/,/) then\n action { [:comma, text] }\n when text = ss.scan(/\\./) then\n action { [:period, text] }\n when text = ss.scan(/\\d+/) then\n action { [:integer, text.to_i] }\n when ss.skip(/'/) then\n [:state, :QUOTE]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :QUOTE then\n case\n when ss.skip(/'/) then\n [:state, nil]\n when text = ss.scan(/[^']+/) then\n action { [:string, text] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def parse(source, options = {})\n parse_context = configure_options(options)\n tokenizer = parse_context.new_tokenizer(source, start_line_number: @line_numbers && 1)\n @root = Document.parse(tokenizer, parse_context)\n self\n end", "def parse\n self.class.rules.each do |target, (selector, delegate, plural)|\n if plural\n @doc.search(selector).each do |node|\n send(target) << parse_result(node, delegate)\n end\n else\n send(\"#{target}=\", parse_result(@doc.at(selector), delegate))\n end\n end\n self\n end", "def process_token(tk); end", "def scan_tokens(tokens, options); end", "def get_parse(sentence)\n return [[], nil] if sentence.nil? || sentence.strip.empty?\n sentence = sentence.strip\n\n response = @enju.get :params => {:sentence=>sentence, :format=>'conll'}\n case response.code\n when 200 # 200 means success\n raise EnjuAccess::EnjuError, \"Empty input.\" if response.body =~/^Empty line/\n raise EnjuAccess::EnjuError, 'Enju CGI server returns html instead of tsv' if response.headers[:content_type] === 'text/html'\n\n tokens = []\n\n # response is a parsing result in CONLL format.\n response.body.split(/\\r?\\n/).each_with_index do |t, i| # for each token analysis\n dat = t.split(/\\t/, 7)\n token = Hash.new\n token[:idx] = i - 1 # use 0-oriented index\n token[:lex] = dat[1].force_encoding('UTF-8')\n token[:base] = dat[2]\n token[:pos] = dat[3]\n token[:cat] = dat[4]\n token[:type] = dat[5]\n token[:args] = dat[6].split.collect{|a| type, ref = a.split(':'); [type, ref.to_i - 1]} if dat[6]\n tokens << token # '<<' is push operation\n end\n\n root = tokens.shift[:args][0][1]\n\n # get span offsets\n i = 0\n tokens.each do |t|\n i += 1 until sentence[i] !~ /[ \\t\\n]/\n t[:beg] = i\n t[:end] = i + t[:lex].length\n i = t[:end]\n end\n\n [tokens, root]\n else\n raise EnjuAccess::EnjuError, \"Enju CGI server dose not respond.\"\n end\n end", "def parsed_document\n @parsed_document ||= Nokogiri::HTML(document)\n rescue Exception => e\n add_fatal_error \"Parsing exception: #{e.message}\"\n end", "def parse\n length = @chars.length\n @index = 0\n while @index < length\n @tokens << if custom?\n parse_custom\n else\n parse_char\n end\n @index += 1\n end\n @tokens\n end", "def parse(doc)\n document = Nokogiri::XML(doc).remove_namespaces!\n @formats.each do |key, format|\n if document.xpath(format.finder).length > 0\n return self.send(\"parse_#{key}\".to_sym, doc)\n end\n end\n raise \"Error: Parser not found!\"\n end", "def parserDidStartDocument(parser)\n puts \"starting parsing..\"\n end", "def doc \n Nokogiri.parse(page.body)\n end", "def parser; end", "def parser; end", "def parser; end", "def parser; end", "def parse_doc(doc)\n doc.xpath('//div[@class = \"z-list\"]').each do |node|\n\n story_content = Hash.new\n\n # get an array of the all the links\n links = Array.new\n node.xpath('./a').each do |link_node|\n links.push(link_node)\n end\n # the first link is the title\n story_content[\"title\"] = links[0].content\n\n # get story id\n url_split = links[0]['href'].split('/')\n story_content['ff_id'] = url_split[url_split.length-3]\n\n # the last link is reviews link or the author link\n last_link = links[links.length-1]\n # remove the link if its a review link\n if ((last_link.content <=> \"reviews\") == 0)\n # remove it and do it again\n links.pop()\n last_link = links[links.length-1]\n end\n\n # Set the author\n author_name = last_link.content\n author_url_split = last_link['href'].split('/')\n author_ff_id = author_url_split[author_url_split.length-2]\n story_content['author'] = generate_author(author_name, author_ff_id)\n\n # get the gray section (details)\n gray = \"\"\n node.xpath('./div//div').each do |div_node|\n gray=div_node.content\n # remove the node for the summary later\n div_node.remove\n end\n\n details = gray.split(\" - \")\n\n tags = Hash.new\n # split each of those by :\n count = 1\n story_content['reviews'] = '0'\n details.each do |detail|\n detail_split = detail.split(\":\")\n # If there is nothing in the second one that it isn't a set\n if(detail_split[1] != nil)\n story_content[detail_split[0].downcase] = detail_split[1].strip\n else# we need to do something differnt\n # complete status\n if ((detail_split[0] <=> \"Complete\") == 0)\n story_content['complete'] = true\n # language\n elsif count == 2\n story_content['language'] = detail_split[0]\n # Theme\n elsif count == 3\n story_content['theme'] = detail_split[0].split(\"/\")\n end\n\n # Main Characters\n if (count == details.length)\n if (details[details.length-1] <=> \"Complete\") != 0\n # story isn't complete characters are the last one (or published)\n detail_split = detail.split(\":\")\n if !detail_split[1] # Not published there are no characters\n story_content['characters'] = detail_split[0].split(\" & \")\n end\n else\n # story is complete characters are the second to last one\n detail_split = details[details.length-2].split(\":\")\n if !detail_split[1] # Not published there are no characters\n story_content['characters'] = details[details.length-2].split(\" & \")\n end\n end\n end\n\n # defaulting to false if complete isn't set\n if story_content['complete'] != true\n story_content['complete'] = false\n end\n end\n count+=1\n end\n\n # get the summary\n node.xpath('./div').each do |summary_node|\n story_content['summary'] = summary_node.content\n end\n\n generate_story(story_content)\nend\n\n\n\n#\n# Stores a datastructure with the list of the current ships\n#\ndef update_ships\n # A data structure to store the ships in\n\n ships = [\n [\"Brittana\", [\"Brittany P.\", \"Santana L.\"]],\n [\"Faberry\", [\"Quinn F.\", \"Rachel B.\"]],\n [\"Flanamotta\", [\"Rory F.\", \"Sugar\"]],\n [\"Sory\", [\"Rory F.\", \"Sam E.\"]],\n [\"Seblaine\", [\"Sebastian S.\", \"Blaine A.\"]],\n [\"Santofsky\", [\"D. Karofsky\", \"Santana L.\"]],\n [\"Bartie\", [\"Brittany P.\", \"Artie A.\"]],\n [\"Tike\", [\"Mike C.\", \"Tina C.\"]],\n [\"Pezberry\", [\"Santana L.\", \"Rachel B.\"]],\n [\"Pizes\", [\"Lauren Z.\", \"Puck\"]],\n [\"St. Berry\", [\"Jesse sJ.\", \"Rachel B.\"]],\n [\"Kill\", [\"Kurt H.\", \"Will S.\"]],\n [\"Puckurt\", [\"Kurt H.\", \"Puck\"]],\n [\"Artina\", [\"Tina C.\", \"Artie A.\"]],\n [\"Partie\", [\"Puck\", \"Artie A.\"]],\n [\"Blainofskyve\", [\"Blaine A.\", \"D. Karofsky\"]],\n [\"Klaine\", [\"Kurt H.\", \"Blaine A.\"]],\n [\"Hummelberry\", [\"Kurt H.\", \"Rachel B.\"]],\n [\"Furt\", [\"Kurt H.\", \"Finn H.\"]],\n [\"Pinn\", [\"Puck\", \"Finn H.\"]],\n [\"Samcedes\", [\"Sam E.\", \"Mercedes J.\"]],\n [\"Artcedes\", [\"Artie A.\", \"Mercedes J.\"]],\n [\"Finchel\", [\"Finn H.\", \"Rachel B.\"]],\n [\"Puckleberry\", [\"Puck\", \"Rachel B.\"]],\n [\"Wemma\", [\"Will S.\", \"Emma P.\"]]\n ]\n\n ships.each do |ship_data|\n ship = Ship.find_by_name(ship_data[0])\n\n # Make sure the ship doesn't already exist\n if !ship\n\n # create a new ship\n ship = Ship.new()\n ship.name = ship_data[0]\n ship.save\n\n # For each character in the ship\n ship_characters = ship_data[1]\n generate_log(\"Generating New Ship: #{ship_data[0]} between #{ship_data[1]}\")\n ship_characters.each do |ship_character|\n character = generate_character(ship_character)\n # Save the relationship\n relationship = Relationship.new()\n relationship.ship = ship\n relationship.character = character\n relationship.save\n\n end\n else\n ship.update_attributes(:name => ship_data[0])\n ship.save\n generate_log(\"Updating: #{ship_data[0]} between #{ship_data[1]}\")\n\n\n end\n end\nend\n\n\nend", "def XMLTokenization(tokens)\n realTokens = []\n j=0\n stringDetected = false\n\n @createTokensFile.tokens{\n for i in 0...tokens.size\n\n\ttag = tokenType(tokens[i])\n\tstring = \"\"\n\n\tif tag == :stringConstant and j == 0 then\n\t j=i+1\n\t stringDetected = true\n\n\telsif tag == :stringConstant and j > 0 then\n\t for k in j...i\n\t string << tokens[k] << \" \"\n\t end\n\n\t n = Node.new(string,:stringConstant)\n\t @createTokensFile.tag!(:stringConstant, \" #{string}\")\n\t j=0\n\t stringDetected = false\n\t realTokens.push(n)\n\n\telsif tag != :stringConstant and stringDetected == false\n\t @createTokensFile.tag!(tag, \" #{tokens[i]} \")\n\t n = Node.new(tokens[i],tag)\n\t realTokens.push(n)\n\tend\n\n end\n }\n\n# puts realTokens.inspect\n return realTokens\n end", "def tokenize\n @stack = [ TokenList.new ]\n @num_open_brackets = 0\n @token_buffer = nil\n until content.eos?\n if @num_open_brackets > 0\n _build_token_list_inside_sub\n else\n _build_token_list_outside_sub\n end\n end\n _flush_token_buffer\n _flush_stack\n\n @tokens = @stack.first\n end", "def parse(buffer = :begin)\n buffer = [buffer]\n saved = save\n eat_ws_and_comments\n until eof?\n t = term\n break if t == :\"\"\n buffer += [t]\n end\n buffer = flatten_begin buffer\n A(*saved, *buffer)\n end", "def initialize(document)\n @root = Node.new\n\n document.length.times do |i|\n substring = document[i..-1]\n substring.chars.inject(root) do |node, c|\n node.add(c)\n end.add(EOS)\n end\n end", "def parse(tokens)\n if tokens.length == 1\n tokens[0]\n elsif tokens.length > 2\n [\n tokens[1],\n [ tokens[0], parse(tokens[2..-1]) ]\n ]\n else\n raise RuntimeError, \"Fucked Tokens\"\n end\n end", "def parse_to_kramdown_document\n # Initialize processing i_vars\n @data_output = {}\n @deleted_text_output = []\n @notes_output = []\n @warnings_output = []\n # Parse\n @ke_context = Folio::KeContext.new(\n { 'root' => Kramdown::ElementRt.new(:root, nil, nil, :encoding => 'UTF-8') },\n self\n )\n @xml_document = Nokogiri::XML(@folio_xml) # Can't do { |config| config.noblanks }, it breaks parsing\n\n # Transform the XML tree\n @xml_document.css('record').each do |record_xn|\n process_xml_node(record_xn)\n end\n kramdown_doc = Kramdown::Document.new('', @kramdown_options)\n kramdown_doc.root = @ke_context.get('root', nil)\n post_process_kramdown_tree!(kramdown_doc.root)\n kramdown_doc\n end", "def tokenize_text(text)\n data = Doc.new(text)\n featurize(data)\n classify(data)\n return data.segment\n end", "def parse_kramdown(content)\n ::Kramdown::Document.new content, :input => 'QuickStartParser' \n end", "def tokens=(_arg0); end", "def tokens=(_arg0); end", "def tokens=(_arg0); end", "def validate(doc)\n raw_text = doc.gsub(\"\\n\", '')\n tfr = TextIn::TextTransformer.new(raw_text, @flow_type, nil, nil, nil, 'out')\n res = tfr.parse\n res.nil? # parse returns nil on success\n end", "def parse\n kramdown_doc = parse_to_kramdown_document\n\n # Prepare return value\n kramdown_string = kramdown_doc.send(kramdown_conversion_method_name)\n json_state = JSON::State.new(array_nl: \"\\n\") # to format json output\n {\n 'folio.at' => kramdown_string,\n 'folio.data.json' => @data_output.to_json(json_state) + \"\\n\",\n 'folio.deleted_text.json' => @deleted_text_output.to_json(json_state) + \"\\n\",\n 'folio.notes.json' => @notes_output.to_json(json_state) + \"\\n\",\n 'folio.warnings.json' => @warnings_output.to_json(json_state) + \"\\n\",\n }\n end", "def tokenize_text(text)\n data = Doc.new(text)\n featurize(data)\n classify(data)\n return data.segment\n end", "def text_token(text, kind); end", "def text_token(text, kind); end", "def parse\n case node.name\n when 'document'\n Plex::Parser.new(parent, node.root).parse\n when 'MediaContainer'\n parse_media_container\n when 'Video'\n parse_video\n when 'Directory'\n parse_directory\n when 'text'\n nil\n else\n end\n end", "def tokenize text\n text = text.sub(/\\A(Public|Internal|Deprecated):\\s+/, '')\n\n setup_scanner text\n\n until @s.eos? do\n pos = @s.pos\n\n # leading spaces will be reflected by the column of the next token\n # the only thing we loose are trailing spaces at the end of the file\n next if @s.scan(/ +/)\n\n @tokens << case\n when @s.scan(/\\r?\\n/) then\n token = [:NEWLINE, @s.matched, *pos]\n @s.newline!\n token\n when @s.scan(/(Examples|Signature)$/) then\n @tokens << [:HEADER, 3, *pos]\n\n [:TEXT, @s[1], *pos]\n when @s.scan(/([:\\w][\\w\\[\\]]*)[ ]+- /) then\n [:NOTE, @s[1], *pos]\n else\n @s.scan(/.*/)\n [:TEXT, @s.matched.sub(/\\r$/, ''), *pos]\n end\n end\n\n self\n end", "def parse(doc)\n c32_patient = {}\n entries = create_hash(doc)\n get_demographics(c32_patient, doc)\n process_events(c32_patient, entries)\n end", "def parse(script)\n next_token_id = 0\n\n token_records = []\n\n # Maps token name to token entry\n @tokenNameMap = {}\n\n script_lines = script.split(\"\\n\")\n @original_line_numbers = []\n\n # Join lines that have been ended with '\\' to their following lines;\n # only do this if there's an odd number of '\\' at the end\n\n @lines = []\n accum = nil\n accum_start_line = nil\n\n script_lines.each_with_index do |line, original_line_number|\n\n trailing_backslash_count = 0\n while line.length > trailing_backslash_count && line[-1-trailing_backslash_count] == '\\\\'\n trailing_backslash_count += 1\n end\n\n if accum.nil?\n accum = \"\"\n accum_start_line = original_line_number\n end\n\n if (trailing_backslash_count % 2 == 1)\n accum << line[0...-1]\n else\n accum << line\n @lines << accum\n @original_line_numbers << accum_start_line\n accum = nil\n end\n end\n\n if !accum.nil?\n raise ParseException, \"Incomplete final line: #{script}\"\n end\n\n # Now that we've stitched together lines where there were trailing \\ characters,\n # process each line as a complete token definition\n\n @lines.each_with_index do |line, line_index|\n line_number = 1 + @original_line_numbers[line_index]\n\n # Strip whitespace only from the left side (which will strip all of\n # it, if the entire line is whitespace). We want to preserve any\n # special escaped whitespace on the right side.\n line.lstrip!\n\n # If line is empty, or starts with '#', it's a comment\n if line.length == 0 || line[0] == '#'\n next\n end\n\n if !(line =~ TOKENNAME_EXPR)\n raise ParseException.build(\"Syntax error\", line_number, line)\n end\n\n pos = line.index(\":\")\n\n tokenName = line[0,pos].strip()\n\n expr = line[pos+1..-1]\n\n rex = RegParse.new(expr, @tokenNameMap, line_number)\n\n # Give it the next available token id, if it's not an anonymous token; else -1\n\n token_id = -1\n if tokenName[0] != '_'\n token_id = next_token_id\n next_token_id += 1\n end\n\n entry = TokenEntry.new(tokenName, rex, token_id)\n\n if @tokenNameMap.has_key?(tokenName)\n raise ParseException.build(\"Duplicate token name\",line_number,line)\n end\n @tokenNameMap[entry.name] = entry\n\n next if entry.id < 0\n\n if accepts_zero_characters(rex.start_state, rex.endState)\n raise ParseException.build(\"Zero-length tokens accepted\",line_number,line)\n end\n\n token_records << entry\n end\n\n combined = combine_token_nfas(token_records)\n\n builder = NFAToDFA.new(combined)\n builder.generate_pdf = @generate_pdf\n dfa = builder.nfa_to_dfa\n\n apply_redundant_token_filter(token_records, dfa)\n\n Tokn::DFA.new(token_records.map{|x| x.name}, dfa)\n end", "def read_from(tokens)\n\t\t\tif tokens.length == 0\n\t\t\t\traise SyntaxError, \"unexpected EOF while reading\"\n\t\t\tend\n\t\t\ttokens.delete_if { |item| item.strip == \"\" || item == []}\n\t\t\ttmp, expression = restructure tokens\n\t\t\treturn expression\n\t\tend", "def doc!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 97 )\n\n type = DOC\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 887:5: '`' (~ ( '`' | '\\\\\\\\' | '#' ) | '\\\\\\\\' . | {...}? => INTERPOLATION | '#' )* '`'\n match( 0x60 )\n # at line 888:5: (~ ( '`' | '\\\\\\\\' | '#' ) | '\\\\\\\\' . | {...}? => INTERPOLATION | '#' )*\n while true # decision 13\n alt_13 = 5\n alt_13 = @dfa13.predict( @input )\n case alt_13\n when 1\n # at line 888:7: ~ ( '`' | '\\\\\\\\' | '#' )\n if @input.peek( 1 ).between?( 0x0, 0x22 ) || @input.peek( 1 ).between?( 0x24, 0x5b ) || @input.peek( 1 ).between?( 0x5d, 0x5f ) || @input.peek( 1 ).between?( 0x61, 0xff )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n when 2\n # at line 889:7: '\\\\\\\\' .\n match( 0x5c )\n match_any\n\n when 3\n # at line 890:7: {...}? => INTERPOLATION\n raise FailedPredicate( \"DOC\", \" at_interpolation? \" ) unless ( ( at_interpolation? ) )\n interpolation!\n # --> action\n type = DDOC \n # <-- action\n\n when 4\n # at line 891:7: '#'\n match( 0x23 )\n\n else\n break # out of loop for decision 13\n end\n end # loop for decision 13\n match( 0x60 )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 97 )\n\n end", "def tokenize\n # Array to contain all tokens.\n tokenArray = []\n # While getChar returns anything other than \"\"\n while getChar\n # Loop to next character until not a space.\n while charIsWhitespace\n nextChar\n end\n # Breaks if it hits the dreaded empty string.\n if getChar.nil?\n break\n end\n # If character is a letter.\n if(charIsAlpha) \n # Initialize local variables for scope.\n m = \"\"\n line = @line\n column = @column \n # While character is letter or number or underscore,\n # add to string \"m\" current character.\n while(charIsAlpha or charIsDigit or getChar == '_')\n m += getChar\n nextChar\n end\n # If the keywords include \"m\" string in hash array,\n # add to tokenArray a new token with the keywords having \"m\" as an index key,\n # its column and line as well for future use and debugging.\n if(Tokens::KEYWORDS.include?(m))\n tokenArray.push Token.new(Tokens::KEYWORDS[m], m, column, line)\n # Must be identifier, add to array as identifier.\n else\n tokenArray.push Token.new(Tokens::IDENT, m, column, line)\n end\n # If the current character is a number.\n elsif(charIsDigit)\n # Initialize local variables for scope.\n m = \"\"\n line = @line\n column = @column\n # Bool is for exception checking on periods. Most likely will be removed,\n # have yet to decide on ranges.\n dot = false\n # While char is number or period,\n while(charIsDigit or getChar == '.')\n # if period\n if(getChar == '.')\n # if dot is true\n if(dot)\n # Create exception class message.\n TokenizerException.new(column, line, \"Number literal contains too many dots.\")\n end\n # Sets flag for second dot if it happens before leaving scope.\n dot = true\n end\n # String adds new character and increments\n m += getChar\n nextChar\n end\n # Token complete, push token as number into tokenArray\n tokenArray.push Token.new(Tokens::NUMBER, m, column, line)\n # Current character doesn't fit into letter or number parameters.\n else\n # More instance variables\n column = @column\n line = @line\n # Starts off by saying this is a character, then moving to the next to check.\n m = getChar\n nextChar\n # While the string is in the operators add and increment character.\n while(Tokens::OPERATORS.include?(m))\n m += getChar if !getChar.nil?\n m += \" \" if getChar.nil?\n nextChar\n end\n # Jump back to the last character\n prevChar()\n # Take of the last character.\n m = m.slice(0, m.size - 1)\n # Pushes another token into the array.\n tokenArray.push Token.new(Tokens::OPERATORS[m], m, column, line)\n end\n end\n return tokenArray\n end", "def parse(stream, encoding=nil)\n _parse(stream, false, encoding)\n @tree.get_document\n end", "def parse\n\t\t\tGlyph.info \"Parsing: #{@context[:source][:name]}\" if Glyph.debug? && @context[:info] && @context[:source][:name]\n\t\t\t@tree = @parser.parse\n\t\t\t@document = Glyph::Document.new @tree, @context\n\t\t\t@document.inherit_from @context[:document] if @context[:document]\n\t\t\t@tree\n\t\tend", "def token(content, kind); end" ]
[ "0.653267", "0.65123236", "0.6499569", "0.6481074", "0.60657245", "0.6042443", "0.5962066", "0.5953052", "0.59506637", "0.5946258", "0.59429085", "0.59429085", "0.59322566", "0.5908728", "0.5899579", "0.58761257", "0.5867523", "0.5834811", "0.5768888", "0.5768888", "0.5766613", "0.5746384", "0.57455575", "0.5732107", "0.5692463", "0.5670163", "0.5657662", "0.5643602", "0.5631798", "0.5631798", "0.5631798", "0.5631798", "0.5631798", "0.5631798", "0.5631798", "0.5631798", "0.5622204", "0.5572051", "0.5551241", "0.55421233", "0.5512631", "0.55083", "0.55075055", "0.5507225", "0.5502966", "0.55023456", "0.5478376", "0.5455274", "0.5434142", "0.543091", "0.54295397", "0.5422204", "0.54192847", "0.54136103", "0.5409888", "0.539949", "0.53994477", "0.5390064", "0.5380717", "0.53720164", "0.53688675", "0.53639126", "0.53626764", "0.53532577", "0.5335776", "0.5330039", "0.5322611", "0.53113943", "0.53051686", "0.5298351", "0.5298351", "0.5298351", "0.5298351", "0.5286306", "0.52837586", "0.52762264", "0.52605057", "0.5257492", "0.52536994", "0.5251039", "0.5248847", "0.5246678", "0.5245775", "0.5245775", "0.5245775", "0.52442485", "0.5237189", "0.52329314", "0.5231326", "0.5231326", "0.522614", "0.5222251", "0.5220716", "0.52178454", "0.52171314", "0.5206848", "0.5203525", "0.51976657", "0.51898366", "0.5187904" ]
0.6449262
4
Returns the next token on the stream without modifying the stream
def peek_token token = @tokens.first || [] p :peek => token if @debug token end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def next\n\t\tif @next_token\n\t\t\ttoken = @next_token\n\t\t\t@next_token = nil\n\t\t\treturn token\n\t\telse\n\t\t\ttoken = read_token\n\t\t\treturn token\n\t\tend\n\tend", "def next\n token = next_token\n token = next_token while token&.empty?\n token\n end", "def next_token\n tokens.shift\n end", "def get_token\n @tokenbuf << read_token if @tokenbuf.length == 0\n return @tokenbuf.shift\n end", "def next_token\n @tokens.shift\n end", "def next\n @tok ||= read_token\n @tok, tok = nil, @tok\n @prev = tok\n return tok\n end", "def next_token\n\t\tif (token = @tokens.shift) != nil\n\t\t\t@copy << token\n\t\t\treturn token.get_token\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend", "def next_token\n\t\t@token = @input.next_token\n\tend", "def next_token; end", "def next_token\n\t\t@tokens.next_token\n\tend", "def next_token\r\n if !@token.following.nil?\r\n\t\t\t@token = @token.following\r\n\t\t\treturn @token.value\r\n\t\tend\r\n\r\n\t\tscan(@token)\r\n\t\treturn @token.value\r\n end", "def next()\n if @ss.scan_until(token_re)\n term = @ss.matched\n term_end = @ss.pos\n term_start = term_end - term.size\n else\n return nil\n end\n\n return Token.new(normalize(term), term_start, term_end)\n end", "def next_token\n @state = 1\n value = \"\"\n recovery_data = [0, 0]\n\n while !@stream.eof?\n char = @stream.read(1)\n next_state = get_next_state(char)\n\n # Move to the next state.\n if next_state\n if recognizable?\n recovery_data = [@state, 0]\n end\n\n value << char\n recovery_data[1] += 1\n @state = next_state\n else\n # Recognise the final token.\n if recognizable?\n @stream.seek(@stream.pos - 1)\n break\n else\n # Recoverable error.\n if recovery_data[0] > 0\n value = recover_from_error!(recovery_data, value)\n break\n # Fatal lexical error.\n else\n raise Bolverk::ASM::LexicalError, \"Disallowed token: #{char} on line #{@stream.line_number}\"\n end\n end\n end\n end\n\n build_token(value)\n end", "def next\n catch :done do\n while !(info = progress)\n # do nothing - waiting for token\n end\n return info # got token\n end\n return nil # got end of sequence\n end", "def peek\n @tok ||= read_token\n end", "def peek_token(n=1)\n n.times{|x| @tokenbuf << read_token if @tokenbuf.length == 0 }\n return @tokenbuf[n-1]\n end", "def next\n if @next.is_a? TokenSource\n @next = @next.next\n return @next \n end\n @next\n end", "def consume\n cur = @current_token\n next_token\n return cur\n end", "def peek_next(token)\r\n\t\tif !token.following.nil?\r\n\t\t return token.following\r\n\t\tend\r\n\r\n\t\tpeekToken = Token.new\r\n\t\tscan(peekToken)\r\n\t\ttoken.following = peekToken\r\n\t\treturn peekToken\r\n\tend", "def next()\n @stream.next\n end", "def next_token; @stack.shift; end", "def token_stream # :nodoc:\n end", "def next_token\n raise NotImplementedError\n end", "def next_token\n @current_token = @lexer.next_token\n end", "def next\n if @state == :start && @scanner.eos?\n return nil\n else\n scan_next_token\n end\n end", "def next_token\n token = @enum[@pointer]\n raise NonstringTokenError unless token.nil? || token.kind_of?(String) \n @pointer += 1\n token\n end", "def next_token\n @sy = @tokenizer.next_token\n \n # ignore EOL tokens since no productions would accept them\n while @sy.type == TokenType::EOL_TOKEN\n @sy = @tokenizer.next_token\n end\n end", "def peek_token(amount = 1)\n index = @token_index + amount\n @tokens[index]\n end", "def current_token\n @stream.current_token\n end", "def pop_token\n @token_stream.pop\n end", "def pop_token\n @token_stream.pop\n end", "def next_token\n\t\tif ((tok = @tokensList.shift) != nil)\n\t\t\t@tokensAux << tok\n\t\t\treturn tok.idAndValue\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend", "def next\n raise IOError.new(\"Stream is at the end of file.\") if eof?\n end_of_token = false\n token = \"\"\n while not end_of_token\n c = @file.getc\n puts \"next c: #{c.inspect} v: #{valid_char?(c)} s: #{single_char?(c)} e: #{is_end_character?(c)}\" if @debug\n if eof? then\n end_of_token = true\n elsif (single_char?(c)) then\n if (token.empty?) then\n token = c\n next_token = @file.getc\n if ('#' == token and '#' == next_token) then\n token << next_token\n else\n @file.seek(-1, IO::SEEK_CUR)\n end\n else\n @file.seek(-1, IO::SEEK_CUR)\n end\n end_of_token = true\n elsif (valid_char?(c)) then\n token << c\n elsif is_end_character?(c) then\n move_till_next_token\n end_of_token = (not token.empty?)\n end\n end\n puts \"next\" if @debug\n build_token(token)\n end", "def peek\n @tokens.at(@current)\n end", "def peek # :nodoc:\n @tokens.peek\n end", "def token\n item = read\n return item['token'] if item['token']\n token_reset\n read['token']\n end", "def peek\n @tokens[@position]\n end", "def peek\n @tokens[@pos]\n end", "def next_token\n result = peek_token\n @start = @finish\n return result if @start >= @expr.length\n\n if @expr[@start].numeric?\n @finish = @start + 1\n while @finish < @expr.length && @expr[@finish].to_s.numeric?\n @finish = @finish + 1\n end\n else\n @finish = @start + 1\n end\n result\n end", "def consume\n @current = @tokens[@pos]\n @pos += 1 if @current\n @current\n end", "def next_token\n #dputs \"@line: \" + @line\n if @state == :normal\n while true\n temp = _next_token\n unless temp == \"#white_space\" || temp == \"#comment\"\n break\n end\n end\n #dputs \"token: \" + temp\n @current_token = temp\n return temp\n else\n return :Terminate\n end\n \n end", "def read_next_token(token_class)\n if @next_token\n return @next_token\n else\n # check for a match on the specified class first\n if match(token_class)\n return @next_token\n else\n # now check all the tokens for a match\n Taxonifi::Splitter::Tokens.send(@token_list).each {|t|\n return @next_token if match(t)\n }\n end\n # no match, either end of string or lex-error\n if @input != ''\n raise(Taxonifi::Splitter::SplitterError, \"Lexer Error, unknown token at |#{@input[0..20]}...\", caller)\n else\n return nil\n end\n end\n end", "def get\n @current_token = @tokens.shift\n p :get => @current_token if @debug\n @current_token\n end", "def get\n @current_token = @tokens.shift\n p :get => @current_token if @debug\n @current_token\n end", "def next\n ret = peek_next\n @str.slice! @last_re if ret.type != :eos\n\n ret\n end", "def get_token_stream\n raise NotImplementedError\n end", "def token\n ready_token\n\n i = @buffer.index(/[\\[\\]()<>{}\\s\\/]/) || @buffer.size\n\n token_chars =\n if i == 0 and @buffer[i,2] == \"<<\" then 2\n elsif i == 0 and @buffer[i,2] == \">>\" then 2\n elsif i == 0 then 1\n else i\n end\n\n strip_space = !(i == 0 and @buffer[0,1] == '(')\n tok = head(token_chars, strip_space)\n\n if tok == \"\"\n nil\n elsif tok[0,1] == \"%\"\n @buffer = \"\"\n token\n else\n tok\n end\n end", "def peek_next\n fail 'No string specified' unless @str\n\n return Token.new(:eos) if skip_space == :eos\n\n PATTERNS.each do |re, func|\n re.match(@str) do |mat|\n @last_re = re # This is what will be removed\n mat = mat.to_s\n return func.is_a?(Symbol) ? send(func, mat) : instance_exec(mat, &func)\n end\n end\n end", "def next!() end", "def next_token()\n raise LexicalError.new(\"No input text was provided.\", LexemePosition::at_start) if token_recognition_state == :waiting_for_input\n\n\t\tif queue.empty?\n unless token_recognition_state == :ready\n error_message = \"#{__method__} may not be called when state is #{token_recognition_state}\"\n raise LexerSetupError.new(error_message)\n end\n\n enqueue_next_tokens() # Retrieve token(s) from the input text & enqueue them\n end\n theToken = queue.dequeue()\n\t\treturn theToken\n end", "def skip token_type, error = true\n type, = get\n return unless type # end of stream\n return @current_token if token_type == type\n unget\n raise ParseError, \"expected #{token_type} got #{@current_token.inspect}\" if error\n end", "def skip token_type, error = true\n type, data, = get\n\n return unless type # end of stream\n\n return @current_token if token_type == type\n\n unget\n\n raise ParseError, \"expected #{token_type} got #{@current_token.inspect}\" if\n error\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n if ss.peek(1) == \"\\n\"\n self.lineno += 1\n # line starts 1 position after the newline\n self.start_of_current_line_pos = ss.pos + 1\n end\n self.old_pos = ss.pos\n token =\n case state\n when nil then\n case\n when ss.skip(/[ \\t]+/) then\n # do nothing\n when ss.skip(/\\/\\/[^\\r\\n]*/) then\n # do nothing\n when text = ss.scan(/\\r|\\n/) then\n newline text\n when text = ss.scan(/[!=<>]=?/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/[(){},;.\\-+\\/*]/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/#{DIGIT}+(\\.#{DIGIT}+)?/) then\n action { [:NUMBER, text] }\n when text = ss.scan(/nil/) then\n action { [:NIL, text] }\n when text = ss.scan(/false/) then\n action { [:FALSE, text] }\n when text = ss.scan(/true/) then\n action { [:TRUE, text] }\n when text = ss.scan(/#{ALPHA}(#{ALPHA}|#{DIGIT})*/) then\n action { [:IDENTIFIER, text] }\n when ss.skip(/\"\"/) then\n action { [:STRING, '\"\"'] }\n when ss.skip(/\"/) then\n [:state, :IN_STRING]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :IN_STRING then\n case\n when text = ss.scan(/[^\"]+/) then\n action { [:STRING, \"\\\"#{text}\\\"\"] }\n when ss.skip(/\"/) then\n [:state, nil]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def current_token\n @tokens[@token_index]\n end", "def peek_token\n return nil if @start >= @expr.length\n if @start == 0 && @finish == 0\n return @expr[0]\n else\n token = @expr[@start...@finish]\n\n if token.empty?\n @finish = @finish + 1\n peek_token\n else\n return token\n end\n end\n end", "def next_token\n\n if @ss.bol?\n @line+=1\n @old_pos=@ss.pos\n end\n\n position=[@line,@ss.pos-@old_pos+1]\n\n return :eos if @ss.eos?\n\n case\n when text = @ss.scan(NEWLINE)\n next_token()\n when text = @ss.scan(SPACE)\n next_token()\n when text = @ss.scan(COMMENT)\n next_token()\n when text = @ss.scan(ARROW)\n return Token.new [:arrow,text,position]\n when text = @ss.scan(LT)\n return Token.new [:lt,text,position]\n when text = @ss.scan(LBRACK)\n return Token.new [:lbrack,text,position]\n when text = @ss.scan(RBRACK)\n return Token.new [:rbrack,text,position]\n when text = @ss.scan(IDENTIFIER)\n case\n when value = text.match(IDENT)\n return Token.new [:IDENT,text,position]\n when value = text.match(FLOAT)\n return Token.new [:FLOAT,text,position]\n when value = text.match(INT)\n return Token.new [:INT,text,position]\n when value = text.match(STRING)\n return Token.new [:STRING,text,position]\n when value = text.match(MODULE)\n return Token.new [:module,text,position]\n when value = text.match(CLASS)\n return Token.new [:class,text,position]\n when value = text.match(END_)\n return Token.new [:end,text,position]\n when value = text.match(ATTR)\n return Token.new [:attr,text,position]\n when value = text.match(LPAREN)\n return Token.new [:lparen,text,position]\n when value = text.match(RPAREN)\n return Token.new [:rparen,text,position]\n else\n return Token.new [:identifier,text,position]\n end\n else\n x = @ss.getch\n return Token.new [x, x,position]\n end\n end", "def peek_token(n = 0)\n raise ArgumentError.new(\"can't look back in the token stream\") if n < 0\n @enum[@pointer + n]\n end", "def next\n peek.tap { @position += 1 }\n end", "def next_token(options = { should_advance?: true })\n if @current_scope.type == Scope::TYPE_MAIN && @current_scope.current_token.nil?\n token = @lexer.next_token\n @current_scope.tokens << token unless token.nil?\n end\n\n token = @current_scope.current_token\n\n advance token if options[:should_advance?] && token\n\n token\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when ss.skip(/\\s+/) then\n # do nothing\n when ss.skip(/:(#{SYMBOL_NAME})/o) then\n action { emit :tSYMBOL, &:to_sym }\n when ss.skip(/\"(.+?)\"/) then\n action { emit :tSTRING }\n when ss.skip(/[-+]?\\d+\\.\\d+/) then\n action { emit :tNUMBER, &:to_f }\n when ss.skip(/[-+]?\\d+/) then\n action { emit :tNUMBER, &:to_i }\n when ss.skip(/#{Regexp.union(\n %w\"( ) { | } [ ] < > $ ! ^ ` ... + * ? ,\"\n )}/o) then\n action { emit ss.matched, &:to_sym }\n when ss.skip(/#{REGEXP}/o) then\n action { emit_regexp }\n when ss.skip(/%?(#{CONST_NAME})/o) then\n action { emit :tPARAM_CONST }\n when ss.skip(/%([a-z_]+)/) then\n action { emit :tPARAM_NAMED }\n when ss.skip(/%(\\d*)/) then\n action { emit(:tPARAM_NUMBER) { |s| s.empty? ? 1 : s.to_i } } # Map `%` to `%1`\n when ss.skip(/_(#{IDENTIFIER})/o) then\n action { emit :tUNIFY }\n when ss.skip(/_/o) then\n action { emit :tWILDCARD }\n when ss.skip(/\\#(#{CALL})/o) then\n action { @state = :ARG; emit :tFUNCTION_CALL, &:to_sym }\n when ss.skip(/#{IDENTIFIER}\\?/o) then\n action { @state = :ARG; emit :tPREDICATE, &:to_sym }\n when ss.skip(/#{NODE_TYPE}/o) then\n action { emit :tNODE_TYPE, &:to_sym }\n when ss.skip(/\\#.*/) then\n action { emit_comment }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :ARG then\n case\n when ss.skip(/\\(/) then\n action { @state = nil; emit :tARG_LIST }\n when ss.skip(//) then\n action { @state = nil }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when text = ss.scan(/#{DIGIT}/) then\n action { [:DIGIT, text.to_i] }\n when text = ss.scan(/#{ADDITION}/) then\n action { [:ADDITION, text] }\n when text = ss.scan(/#{SUBSTRACTION}/) then\n action { [:SUBSTRACTION, text] }\n when text = ss.scan(/#{MULTIPLICATION}/) then\n action { [:MULTIPLICATION, text] }\n when text = ss.scan(/#{DIVISION}/) then\n action { [:DIVISION, text] }\n when text = ss.scan(/#{OPENING_PARANTHESIS}/) then\n action { [:OPENING_PARANTHESIS, text] }\n when text = ss.scan(/#{CLOSING_PARANTHESIS}/) then\n action { [:CLOSING_PARANTHESIS, text] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def get_next\n return if eof?\n\n @buffer << @io.gets if @buffer.empty?\n\n until @io.eof?\n line = @io.gets\n next unless line\n\n if @parser.start_new?(line) || @buffer.empty?\n @buffer << line\n break\n else\n @buffer.last << line\n end\n end\n\n return if @buffer.empty?\n @parser.parse(@buffer.slice!(0)) || self.get_next\n end", "def each(stream)\n stream.each do |token|\n yield token if isToken? token\n end\n end", "def shift\n ret = @tokens.shift\n get_next_tokens\n ret\n end", "def next() end", "def next() end", "def peek_next()\n return nil if @at_end\n\n begin\n @reader.peek\n rescue StopIteration\n nil\n end\n end", "def get_next\n return if eof?\n\n @buffer << gets if @buffer.empty?\n\n until @io.eof? && @io_buf.empty?\n line = gets\n next unless line\n\n if @parser.start_new?(line) || @buffer.empty?\n @buffer << line\n break\n else\n @buffer.last << line\n end\n end\n\n return if @buffer.empty?\n @parser.parse(@buffer.slice!(0)) || self.get_next\n end", "def key()\n begin\n @stream.peek\n rescue StopIteration\n nil\n end\n end", "def next\n displacement = @file.gets.try(:chomp).try(:to_f)\n return nil unless displacement\n\n ret = @curr_val\n @curr_val += displacement\n ret\n end", "def next(pointer); end", "def next(pointer); end", "def unshift(token); end", "def has_next_token\n\t\t@input.has_next\n\tend", "def peak\n\t\tif not @next_token\n\t\t\t@next_token = read_token\n\t\tend\n\t\treturn @next_token\n\tend", "def which_token_next\n moves.count.even? ? \"X\" : \"O\" \n # if moves.count.even?\n # return \"x\"\n # else\n # return \"o\"\n # end\n end", "def token\n @token\n end", "def next_token(w)\n\tif w[0] != '('\n\t\treturn w.slice!(0)\n\tend\n\n\tw.slice!(0) #remove that leading '('\n\n\ttoken = \"\"\n\twhile true\n\t\tc = w.slice!(0)\n\t\tif c == ')'\n\t\t\tbreak\n\t\tend\n\n\t\ttoken << c\n\tend\n\n\treturn token\nend", "def next_token\n \n # Early return if there is nothing to be read. This means we've reached the end of the file.\n \n unless @file[@pos]\n return nil\n end\n \n # This is the token that will be returned.\n token = Compiler::Token.new\n \n # Initializes a new instance of the automaton.\n automaton = Automaton.new\n \n # Will be set inside the loop, if necessary.\n increment_next = false\n \n # Will be set inside the loop. Marks whether we've reached the end of the file.\n eof = false\n \n # Build a new token while we don't have a new word yet and isn't in the failed state\n while ((automaton.state != :A || automaton.word.empty?) && automaton.state != :failed)\n \n # The next input for the automaton\n char = @file[@pos]\n \n if char\n \n # Moves the pointer to the next char\n @pos += 1\n \n automaton.transition(char)\n \n # While the automaton hasn't started to build a new word yet, increments the line and column numbers.\n # In this phase, we're just skipping blank characters\n if automaton.word.empty?\n if increment_next\n if char == \"\\n\"\n increment_next = true\n else\n increment_next = false\n end\n @line += 1\n @column = 0\n elsif char == \"\\n\"\n @column += 1\n increment_next = true\n else\n @column += 1\n end\n end\n \n else\n eof = true\n puts \"breaking\"\n break\n end\n end\n \n \n \n if eof\n automaton.transition(\"\\n\")\n else\n @pos -= 1\n end\n \n if (automaton.type == :identifier) && (Compiler.reserved_words.is_reserved?(automaton.word))\n token.type = :reserved_word\n else\n token.type = automaton.type\n end\n \n token.value = automaton.word\n token.line = @line\n token.column = @column\n \n return token\n \n end", "def racc_read_token(t, tok, val); end", "def next\n fil_header[:next]\n end", "def next\n\t\tlines.shift\n\tend", "def consume()\n la(1)\n return @lookahead.shift\n end", "def getNextToken\n \n #Check if the end has been reached\n if @currentChar == nil\n return\n end\n if @currentChar.match(/\\s/) != nil\n skipWhitespaces\n end\n \n if @currentChar == '%'\n comment\n if @currentChar.match(/\\s/) != nil\n skipWhitespaces\n end\n end \n \n if @currentChar.match(/[A-Za-z0-9_]/) != nil\n return Token.new(NAME, name)\n end\n \n if @currentChar == \"\\\"\"\n return Token.new(STRING, string)\n end\n \n if @currentChar == '{'\n advance\n return Token.new(OPENING_BRACE,'{')\n end\n \n if @currentChar == '}'\n advance\n return Token.new(CLOSING_BRACE,'}')\n end\n \n if @currentChar == '['\n advance\n return Token.new(OPENING_BRACKET,'[')\n end\n \n if @currentChar == ']'\n advance\n return Token.new(CLOSING_BRACKET,']')\n end\n \n if @currentChar == ':'\n advance\n return Token.new(COLON,':')\n end\n \n if @currentChar == '*'\n advance\n return Token.new(ASTERIX,'*')\n end\n \n if @currentChar == '='\n advance\n return Token.new(EQUALS,'=')\n end\n \n if @currentChar == ';'\n advance\n return Token.new(SEMICOLON,';')\n end\n \n if @currentChar == '^'\n advance\n return Token.new(CIRCUMFLEX,'^')\n end\n \n if @currentChar == '+'\n advance\n return Token.new(PLUS,'+')\n end\n if @currentChar == '('\n advance\n return Token.new(OPENING_PARANTHESIS,'(')\n end\n if @currentChar == ')'\n advance\n return Token.new(CLOSING_PARANTHESIS,')')\n end\n if @currentChar == '.'\n advance\n return Token.new(DOT,'.')\n end\n if @currentChar == '#'\n advance\n return Token.new(HASH,'#')\n end\n if @currentChar == ','\n advance\n return Token.new(COMMA,',')\n end\n error\n \n return Token.new(EOF,'EOF') \n \n end", "def next\n\t\t@ibuf = (@ibuf+1).modulo(@nbuf)\n\t\t@buffers[@ibuf]\n\tend", "def peek()\n lookaheadChar = @source_io.getc\n @source_io.ungetc(lookaheadChar)\n return lookaheadChar.chr\n end", "def advance\n @lookahead = next_token()\n end", "def read\n return nil if self.payload.empty?\n self.offset += 1\n return self.payload.shift\n end", "def find_token\n shift_token || find_regex_token || find_string_token\n end", "def each\n while (token = next_token)\n yield token\n end\n end", "def token; end", "def token; end", "def token; end", "def token; end", "def token; end", "def token; end", "def next\r\n next_values[0]\r\n end", "def get_next()\n\t\t\treturn @next\n\t\tend", "def token\n @token\n end" ]
[ "0.8332876", "0.80467963", "0.7955034", "0.7954132", "0.79513747", "0.7866707", "0.7755758", "0.7742991", "0.76905787", "0.7653205", "0.76486", "0.7551597", "0.75150716", "0.73619646", "0.7355825", "0.72566706", "0.72470903", "0.72424835", "0.7221907", "0.71813124", "0.7140405", "0.7134071", "0.71201575", "0.7118343", "0.7115887", "0.7041123", "0.701323", "0.70119286", "0.6985193", "0.697937", "0.697937", "0.69642746", "0.68933964", "0.6883768", "0.6880495", "0.6866927", "0.6820587", "0.6790392", "0.66550976", "0.6634301", "0.66324234", "0.66292155", "0.6528796", "0.6528796", "0.65282196", "0.6510304", "0.6508299", "0.6501466", "0.6478183", "0.64745504", "0.6464544", "0.6462804", "0.6453028", "0.64263743", "0.6410626", "0.64036125", "0.6379798", "0.6372698", "0.636836", "0.6361713", "0.63537705", "0.63513017", "0.6300801", "0.6298681", "0.6295998", "0.6295998", "0.6199694", "0.6198491", "0.6175246", "0.61579525", "0.613361", "0.613361", "0.61302024", "0.61084205", "0.60934305", "0.6090508", "0.60558444", "0.60411286", "0.6027064", "0.6014003", "0.5991389", "0.59890074", "0.59877837", "0.5981031", "0.5980836", "0.5976774", "0.59624934", "0.59597397", "0.59596866", "0.5958839", "0.59536463", "0.59536463", "0.59536463", "0.59536463", "0.59536463", "0.59536463", "0.5945161", "0.59403306", "0.59273547" ]
0.6509945
47
Skips a token of +token_type+, optionally raising an error.
def skip token_type, error = true type, data, = get return unless type # end of stream return @current_token if token_type == type unget raise ParseError, "expected #{token_type} got #{@current_token.inspect}" if error end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def skip token_type, error = true\n type, = get\n return unless type # end of stream\n return @current_token if token_type == type\n unget\n raise ParseError, \"expected #{token_type} got #{@current_token.inspect}\" if error\n end", "def skip_token(nocov_token = T.unsafe(nil)); end", "def consume(token_type, message)\n return advance if check?(token_type)\n raise error(peek, message)\n end", "def parse_skip_token(next_link)\n return nil unless next_link\n next_link[/.*?skipToken=(.*?)$/i, 1]\n end", "def tokenizer\n yield\n\n rescue RangeError, RuntimeError => ex\n $stderr.print 'invalid token detected around '\n fail ex.message\n end", "def parse_token_type\n token_type = get_element('//t:RequestSecurityTokenResponse/t:TokenType')\n @validation_errors << \"TokenType field is empty.\" and return if token_type.nil?\n @validation_errors << \"Invalid token type.\" unless token_type == self.class.token_type\n end", "def unexpected_token(aPosition)\n unexpected = tokens[aPosition]\n expected = chart.sets[aPosition].expected_terminals\n reason = UnexpectedToken.new(aPosition, unexpected, expected)\n faulty(reason)\n end", "def skip\n @scanner.skip(@skip)\n end", "def skip_this_when(enabled:, expected_exception:)\n yield\n rescue expected_exception => e\n e.tap do\n skip e.message if enabled && e.is_a?(expected_exception)\n end\n end", "def skip\n ParsletOmission.new self.to_parseable\n end", "def pop(expected_type, expected_tokens = [])\n next_type, next_token, raw = tokenizer{ @tokens.next } # Consumes the next token\n @current_line = raw[:line]\n @current_index = raw[:index]\n\n # Checks token type\n primitive = next_type == :KEYWORD && [:INT, :CHAR, :BOOLEAN].include?(next_token)\n type_valid = if expected_type == :TYPE\n # Variable type consists of diferrent token types\n primitive || next_type == :IDENTIFIER\n else\n next_type == expected_type\n end\n\n expected_tokens = [expected_tokens].flatten\n token_str = expected_tokens.join(\"' or '\")\n error_message = \"#{expected_type} '#{token_str}' expected but was #{next_type} '#{next_token}'\"\n\n if !type_valid\n fail error_message\n end\n\n # Checks token content\n if expected_tokens.empty? || expected_tokens.include?(next_token)\n write_token_as_xml(next_type, next_token)\n next_token\n else\n fail error_message\n end\n end", "def skip reason = nil\n throw(:__tiramisu_status__, Tiramisu::Skip.new(reason, caller[0]))\n end", "def skip_session\n request.session_options[:skip] = true if token\n end", "def skip_session\n request.session_options[:skip] = true if token\n end", "def consume_hidden_token(t)\n raise NotImplementedError\n end", "def discard_result token\n interpret_result token\n end", "def test_token(token_type, offset = 0)\n debug \"Testing for #{token_type} with offset #{offset}\", :verbose\n\n peeked = peek_token(offset)\n !peeked.nil? && peeked.type == token_type\n end", "def token_err(line, column)\n abort(\"Error in line #{line}, column #{column}!\")\n end", "def xxxtest_a_symbol_is_not_an_operator\n tok = initialize_tokenizer( <<-EOD\n #\n EOD\n )\n assert_not_equal(Token::OP, tok.next.token.type)\n end", "def skip_session\n request.session_options[:skip] = true if token\n end", "def token_type; end", "def consume_token(t)\n raise NotImplementedError\n end", "def skip\n end", "def skip\n end", "def should_be_skipped?(word)\n reject?(word) || hashtag?(word) || uri?(word) || mention?(word)\n end", "def skip reason = nil\n throw(:__tiramisu_skip__, Tiramisu::Skip.new(reason, caller[0]))\n end", "def skip_page!\n raise(SkipPage)\n end", "def skip(pattern)\n _scan_headonly(pattern, true, false)\n end", "def next_token\n raise NotImplementedError\n end", "def check?(token_type)\n return false if at_end?\n return peek.type == token_type\n end", "def throw_unexpected_token(symbol, line, column)\n line_source = @string.split('\\n')[line - 1]\n\n pad = ' ' * column;\n line_data = \"\\n\\n\" + line_source + \"\\n\" + pad + \"^\\n\"\n\n raise (\n line_data + 'Unexpected token: \"' + symbol.to_s + '\" at ' +\n line.to_s + ':' + column.to_s + '.'\n )\n end", "def invalid_token\n\t\t\tredirect_to login_url\n\t\tend", "def expect_token(token_types, offset = 0, consume: true)\n print_token_stack\n\n debug \"Asserting that token at offset #{offset} must be of type #{token_types} - consume? #{consume}\"\n\n if token_types.instance_of? Array\n token_types.each do |t|\n next unless test_token(t, offset)\n\n tk = peek_token offset\n step_forward(1 + offset) if consume\n\n return tk\n end\n elsif test_token token_types, offset\n tk = peek_token offset\n step_forward(1 + offset) if consume\n\n return tk\n end\n\n pk_tk = peek_token offset\n raise_parser_error \"Unexpected #{pk_tk.nil? ? 'END OF INPUT' : \"#{pk_tk.type} token (#{pk_tk.value})\"}, expected #{token_types} token..\"\n end", "def fail!(type)\n suffix = type == :http ? \" (Error Code #{@current_request.response_header.status})\" : \"\"\n logger.debug \"Streaming failed with #{type}#{suffix}\"\n if @failure_count == 0 || @failure_reason != type\n logger.debug \"Instantly restarting (#{@failure_count == 0 ? \"First failure\" : \"Different type of failure\"})\"\n EM.next_tick { perform }\n else\n @failure_delay ||= INITIAL_DELAYS[type]\n logger.debug \"Restarting stream in #{@failure_delay} seconds\"\n logger.debug \"Adding timer to restart in #{@failure_delay} seconds\"\n EM.add_timer(@failure_delay) { perform }\n potential_new_delay = DELAY_CALCULATOR[type].call(@failure_delay)\n @failure_delay = [potential_new_delay, MAX_DELAYS[type]].min\n logger.debug \"Next delay is #{@failure_delay}\"\n end\n @failure_count += 1\n @failure_reason = type\n logger.debug \"Failed #{@failure_count} times with #{@failure_reason}\"\n end", "def skip &block\n annotate block do |c|\n c unless @item_rep.name == :wordcount\n end\nend", "def skip!\n @skip ||= true\n end", "def log_skip(_entity); end", "def log_skip(context)\n logger.debug \"Skipped record #{context.position}: #{context.skipmessage}\"\n end", "def log_skip(context)\n logger.debug \"Skipped record #{context.position}: #{context.skipmessage}\"\n end", "def skip\n @page_handler.skip\n end", "def skip(pattern)\n @skips << pattern\n end", "def skip()\n lines = send_message(\"SKIP\", message)\n end", "def skip(msg = T.unsafe(nil), bt = T.unsafe(nil)); end", "def skip=(reason)\n @skip = reason\n end", "def skip(num)\n @skip = num\n self\n end", "def skip(value)\n\t\t\tparam(\"skip\", value)\n\t\tend", "def skip!(msg = '(no message given)')\n @skipmessage = msg\n @skip = true\n end", "def skip!(msg = '(no message given)')\n @skipmessage = msg\n @skip = true\n end", "def skip!(skip = nil)\n mutate(:skip, skip)\n end", "def unget_token(t)\n @tokenbuf.unshift(t)\n end", "def type_error(line_number, message)\n\tputs \"ERROR: #{line_number}: Type-Check: #{message}\"\n\texit\nend", "def type_error(line_number, message)\n\tputs \"ERROR: #{line_number}: Type-Check: #{message}\"\n\texit\nend", "def skip?\n raise NotImplementedError\n end", "def skip(skip_msg = nil, called_from = nil)\n raise Result::TestSkipped, (skip_msg || \"\"), called_from\n end", "def next_skip_line_number\n first = self.next\n first.type == :integer ? self.next : first\n end", "def skip(amount = 1)\n @read_index += amount\n end", "def skip\n @str.slice! @last_re if peek_next_type != :eos\n end", "def test_get_token_error\n # iterate through all the test cases\n token_error_test_cases.each do |t|\n assert_raises(RLTK::LexingError) do\n IR.new.get_token_str([t[:str]])\n end\n end\n end", "def next_token\n tokens.shift\n end", "def command_skip\r\n @index += 1 while @list[@index + 1].indent > @indent\r\n end", "def next_tokens_until(token_type, options = { inclusive?: true })\n [].tap do |tokens|\n open_count = 0\n\n loop do\n peeked_token = peek_next_token\n\n open_count += 1 if token_type == Token::SCOPE_CLOSE && peeked_token.type == Token::SCOPE_BEGIN\n\n if peeked_token.type == token_type\n break if open_count.zero?\n open_count -= 1\n end\n\n tokens << next_token\n end\n\n tokens << next_token if options[:inclusive?]\n end\n end", "def skip_header\n @skip_header = true\n end", "def skip(*args)\n log(*args)\n skip_now\n end", "def error(message, options = {})\n if brace = @lexer.expected\n message += \"; expected '%s'\"\n end\n except = Puppet::ParseError.new(message)\n except.line = options[:line] || @lexer.line\n except.file = options[:file] || @lexer.file\n\n raise except\n end", "def scan_for_t(token); end", "def parse_skip(src, current_pos)\n group = 1\n while (true)\n case(src[current_pos])\n when '{' then group += 1\n when '}' then\n group -= 1\n break if group == 0\n end\n current_pos += 1\n end\n\n current_pos\n end", "def opposite_token\n token == \"X\" ? \"O\" : \"X\"\n end", "def consume?(type)\n token = @tokens[@p]\n return false unless token && token[0] == type\n @p += 1\n token[1]\n end", "def skip\n @skip = true\n end", "def lex_error; end", "def lex_error; end", "def lex_error; end", "def lex_error; end", "def skip( n=1 )\n\t\t# Jump back into #each with the number of iterations to skip\n\t\tthrow( :skip, n ) if @iterating\n\tend", "def token_not_found_response(err)\n error_with_data(\n err,\n 'token_not_found',\n GlobalConstant::ErrorAction.default\n )\n end", "def set_Skip(value)\n set_input(\"Skip\", value)\n end", "def set_Skip(value)\n set_input(\"Skip\", value)\n end", "def set_Skip(value)\n set_input(\"Skip\", value)\n end", "def set_Skip(value)\n set_input(\"Skip\", value)\n end", "def set_Skip(value)\n set_input(\"Skip\", value)\n end", "def set_Skip(value)\n set_input(\"Skip\", value)\n end", "def throw_error(msg, cur_tok)\n\t\tif cur_tok == nil\n\t\t\traise \"PARSING ERROR WITH NIL TOKEN (SHOULD NOT HAPPEN) >> \" + msg\n\t\tend\n\t\traise \"PARSING ERROR: At line: #{cur_tok.line}, col: #{cur_tok.col}, token: #{cur_tok} >> \" + msg\n\tend", "def next_token(options = { should_advance?: true })\n if @current_scope.type == Scope::TYPE_MAIN && @current_scope.current_token.nil?\n token = @lexer.next_token\n @current_scope.tokens << token unless token.nil?\n end\n\n token = @current_scope.current_token\n\n advance token if options[:should_advance?] && token\n\n token\n end", "def skip_leader\n raise NotImplementedError\n end", "def token(type, text)\n value = case type\n when :INTEGER then text.to_i\n when :REAL then text.to_f\n when :STRING then text[1..-2]\n else text\n end\n\n token = Token.new(value, text, @line, @column)\n\n update_counter(token.source)\n\n [type, token]\n end", "def tokenize (p_token, type, lineno, pos)\n\t\n\tif type == \"op\"\n\t\treturn op_tokenize(p_token, lineno, pos)\n\t\n\telsif type == \"character\"\n\t\treturn char_tokenize(p_token, lineno, pos)\n\t\n\telsif type == \"string\"\n\t\treturn string_tokenize(p_token, lineno, pos)\n\t\n\telsif type == \"digit\"\n\t\treturn digit_tokenize(p_token, lineno, pos)\n\t\n\telse\n\t\t# should create an error here, just for thoroughness\n\tend\nend", "def skip(reason=true)\n if block_given?\n @_skip = reason\n yield\n @_skip = nil\n else\n @_skip = reason\n end\n end", "def skip\n self[:skip]\n end", "def _skip_next\n @index += 1\n\n self\n end", "def skip?(line)\n line[0] == '#' || !line.include?(@delimeter) || line.split(@delimeter).size < 2\n end", "def skip(skip = nil)\n set_option(:skip, skip)\n end", "def parse_skipline\n s0 = @scanner.pos\n s1 = match_str('#')\n if s1 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n s2 = parse_nonls\n s3 = parse_newline\n s0 = if s3 == :failed\n @scanner.pos = s0\n :failed\n else\n [s1, s2, s3]\n end\n end\n s0\n end", "def validate!(token)\n raise ArgumentError, \"Invalid search token\" if !token || token.strip.empty?\n end", "def create_token(token_type, token_value)\n debug \"Creating token type #{token_type} -> #{token_value}\"\n Token.new(token_type, token_value)\n rescue TokenError => e\n raise_tokenizer_error e.message\n end", "def markSkipped message = nil\n raise SkippedTest, message\n end", "def unget(token) # :nodoc:\n @tokens.unshift token\n end", "def skip!\n not_implemented\n end", "def peek_token(amount = 1)\n index = @token_index + amount\n @tokens[index]\n end", "def skip_this_scenario(message = \"Scenario skipped\")\n raise Cucumber::Core::Test::Result::Skipped, message\n end", "def invalid_token?\n @code == 401\n end" ]
[ "0.8023859", "0.57336855", "0.5639974", "0.55563164", "0.546961", "0.5462235", "0.53580624", "0.51876", "0.5172979", "0.5165891", "0.51409113", "0.5130443", "0.5073701", "0.5073701", "0.5043363", "0.50416476", "0.50350356", "0.49987578", "0.49729186", "0.49450994", "0.49297428", "0.49221247", "0.49207145", "0.49207145", "0.48841983", "0.48763195", "0.48676512", "0.48654044", "0.48332447", "0.47495475", "0.47173882", "0.4694385", "0.46554515", "0.4650754", "0.4647112", "0.46391985", "0.46381846", "0.4623653", "0.4623653", "0.46126184", "0.46126124", "0.45942077", "0.45894808", "0.45765027", "0.45561764", "0.45554814", "0.4553707", "0.4553707", "0.45444536", "0.45398217", "0.4512989", "0.4512989", "0.45098367", "0.44916755", "0.44881812", "0.44864443", "0.44851902", "0.44785184", "0.44690624", "0.4467613", "0.44664538", "0.44647714", "0.44625112", "0.4457446", "0.44536313", "0.44501925", "0.44495076", "0.44449624", "0.44407934", "0.44325057", "0.44325057", "0.44325057", "0.44325057", "0.44192895", "0.44135213", "0.4412268", "0.4412268", "0.4412268", "0.4412268", "0.4412268", "0.4412268", "0.4410477", "0.4410435", "0.44098353", "0.44091278", "0.44083625", "0.44075823", "0.43905655", "0.43900436", "0.4388113", "0.43836898", "0.43805447", "0.43787065", "0.43783092", "0.43740344", "0.43726742", "0.4370646", "0.43683577", "0.43658212", "0.43574736" ]
0.7890535
1
Consumes tokens until NEWLINE and turns them back into text
def text text = '' loop do type, data, = get text << case type when :BULLET then _, space, = get # SPACE "*#{' ' * (space - 1)}" when :LABEL then _, space, = get # SPACE "[#{data}]#{' ' * (space - data.length - 2)}" when :LALPHA, :NUMBER, :UALPHA then _, space, = get # SPACE "#{data}.#{' ' * (space - 2)}" when :NOTE then _, space = get # SPACE "#{data}::#{' ' * (space - data.length - 2)}" when :TEXT then data when :NEWLINE then unget break when nil then break else raise ParseError, "unhandled token #{@current_token.inspect}" end end text end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tokenize ; end", "def tokenize ; end", "def tokenize\n \n end", "def tokenize; end", "def tokenize; end", "def remove_leading_newlines\n @tokens.shift if @tokens[0][0] == \"\\n\"\n end", "def text_token(text, kind); end", "def text_token(text, kind); end", "def do__raw token\r\n if token.line and token.line.size > 0\r\n token.line.chomp + \"\\n\"\r\n else\r\n \"\\n\"\r\n end\r\n end", "def suppress_newlines\n @tokens.pop if value[0] == ?\\\n end", "def st_lex(raw)\n @tokens = raw.delete(' ').gsub(\"\\n\", '')\n end", "def consume!\n empty_line ||\n name_token ||\n comment_token ||\n whitespace_token ||\n line_token ||\n heredoc_token ||\n string_token ||\n number_token ||\n regex_token ||\n literal_token\n end", "def convert_to tokens\r\n join( tokens.map{|t| process(t.to_s) })\r\n end", "def tokenize\n @s.reset\n\n tokens = []\n\n while token = consume\n tokens << token\n end\n\n tokens\n end", "def tokenize\n @s.reset\n\n tokens = []\n\n while token = consume\n tokens << token\n end\n\n tokens\n end", "def extracted_text\n tokenstream.text\n end", "def tokens!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 59)\n\n type = TOKENS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 596:4: 'tokens' WS_LOOP '{'\n match(\"tokens\")\n ws_loop!\n match(?{)\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 59)\n\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n if ss.peek(1) == \"\\n\"\n self.lineno += 1\n # line starts 1 position after the newline\n self.start_of_current_line_pos = ss.pos + 1\n end\n self.old_pos = ss.pos\n token =\n case state\n when nil then\n case\n when ss.skip(/[ \\t]+/) then\n # do nothing\n when ss.skip(/\\/\\/[^\\r\\n]*/) then\n # do nothing\n when text = ss.scan(/\\r|\\n/) then\n newline text\n when text = ss.scan(/[!=<>]=?/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/[(){},;.\\-+\\/*]/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/#{DIGIT}+(\\.#{DIGIT}+)?/) then\n action { [:NUMBER, text] }\n when text = ss.scan(/nil/) then\n action { [:NIL, text] }\n when text = ss.scan(/false/) then\n action { [:FALSE, text] }\n when text = ss.scan(/true/) then\n action { [:TRUE, text] }\n when text = ss.scan(/#{ALPHA}(#{ALPHA}|#{DIGIT})*/) then\n action { [:IDENTIFIER, text] }\n when ss.skip(/\"\"/) then\n action { [:STRING, '\"\"'] }\n when ss.skip(/\"/) then\n [:state, :IN_STRING]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :IN_STRING then\n case\n when text = ss.scan(/[^\"]+/) then\n action { [:STRING, \"\\\"#{text}\\\"\"] }\n when ss.skip(/\"/) then\n [:state, nil]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def call\n text\n .split\n .map { |token| convert_sym_to_punct(token) }\n .flat_map { |token| \n token = should_downcase(token)\n remove_symbols(token)\n }\n .flat_map { |token| token.split(Regex::COMMAS_OR_PUNCTUATION) }\n .flat_map { |token| token.split(Regex::VARIOUS) }\n .flat_map { |token| token.split(Regex::ENDS_WITH_PUNCTUATION2) }\n .flat_map { |token| split_dotted_email_or_digit(token) }\n .flat_map { |token| split_abbreviations(token) }\n .flat_map { |token| split_period_after_last_word(token) }\n .flat_map { |token| remove_slash_start_and_end(token) }\n end", "def process_token(tk); end", "def text_token text, kind\n @out << text\n end", "def parse(text)\n text = pre_proccess(text)\n text = pre_normalize(text)\n puts text.inspect if Chronic.debug\n\n tokens = Tokenizer::tokenize(' ' + text + ' ')\n tag(tokens, options)\n\n puts \"+#{'-' * 51}\\n| #{tokens}\\n+#{'-' * 51}\" if Chronic.debug\n\n token_group = TokenGroup.new(tokens, definitions(options), @now, options)\n span = token_group.to_span\n\n guess(span, options[:guess]) if span\n end", "def next_token\n\n if @ss.bol?\n @line+=1\n @old_pos=@ss.pos\n end\n\n position=[@line,@ss.pos-@old_pos+1]\n\n return :eos if @ss.eos?\n\n case\n when text = @ss.scan(NEWLINE)\n next_token()\n when text = @ss.scan(SPACE)\n next_token()\n when text = @ss.scan(COMMENT)\n next_token()\n when text = @ss.scan(ARROW)\n return Token.new [:arrow,text,position]\n when text = @ss.scan(LT)\n return Token.new [:lt,text,position]\n when text = @ss.scan(LBRACK)\n return Token.new [:lbrack,text,position]\n when text = @ss.scan(RBRACK)\n return Token.new [:rbrack,text,position]\n when text = @ss.scan(IDENTIFIER)\n case\n when value = text.match(IDENT)\n return Token.new [:IDENT,text,position]\n when value = text.match(FLOAT)\n return Token.new [:FLOAT,text,position]\n when value = text.match(INT)\n return Token.new [:INT,text,position]\n when value = text.match(STRING)\n return Token.new [:STRING,text,position]\n when value = text.match(MODULE)\n return Token.new [:module,text,position]\n when value = text.match(CLASS)\n return Token.new [:class,text,position]\n when value = text.match(END_)\n return Token.new [:end,text,position]\n when value = text.match(ATTR)\n return Token.new [:attr,text,position]\n when value = text.match(LPAREN)\n return Token.new [:lparen,text,position]\n when value = text.match(RPAREN)\n return Token.new [:rparen,text,position]\n else\n return Token.new [:identifier,text,position]\n end\n else\n x = @ss.getch\n return Token.new [x, x,position]\n end\n end", "def tokens_to_s\n token_stream.compact.map { |token| token[:text] }.join ''\n end", "def text_tokens_texts\n @text_tokens_texts ||= linearize(text_tokens).map(&:to_s).map(&:strip)\n end", "def parse_text\r\n @text_nodes.map(&:content).join('')\r\n end", "def parse_text\r\n @text_nodes.map(&:content).join('')\r\n end", "def parse_text\n text.split(\"\\n\").map { |r| r.scan(/.../) } \n end", "def token_received()\n ret = []\n while @ss.rest? do\n if s = @ss.scan(/[\\s]+/) then\n # ignore blank\n elsif s = @ss.scan(/\\(/) then\n begin\n pos = @ss.pos\n cfws(@ss)\n rescue ParseError\n @ss.pos = pos\n ret.last << s unless ret.empty?\n end\n elsif s = @ss.scan(/\\\"([\\s]*(\\\\[#{TEXT_RE}]|[#{QTEXT_RE}]))*[\\s]*\\\"/o)\n ret << s\n elsif s = @ss.scan(/;/)\n ret << s\n else\n ret << @ss.scan(/[^\\s\\(\\;]+/o)\n end\n end\n return ret\n end", "def next_token\n return process_string if lex_strterm\n self.cmd_state = self.command_start\n self.command_start = false\n self.space_seen = false # TODO: rename token_seen?\n self.last_state = lex_state\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when ss.skip(/[\\ \\t\\r\\f\\v]/) then\n action { self.space_seen = true; next }\n when text = ss.scan(/\\n|\\#/) then\n process_newline_or_comment text\n when text = ss.scan(/[\\]\\)\\}]/) then\n process_brace_close text\n when ss.match?(/\\!/) then\n case\n when is_after_operator? && (ss.skip(/\\!\\@/)) then\n action { result EXPR_ARG, :tUBANG, \"!@\" }\n when text = ss.scan(/\\![=~]?/) then\n action { result :arg_state, TOKENS[text], text }\n end # group /\\!/\n when ss.match?(/\\./) then\n case\n when text = ss.scan(/\\.\\.\\.?/) then\n action { result EXPR_BEG, TOKENS[text], text }\n when ss.skip(/\\.\\d/) then\n action { rb_compile_error \"no .<digit> floating literal anymore put 0 before dot\" }\n when ss.skip(/\\./) then\n action { self.lex_state = EXPR_BEG; result EXPR_DOT, :tDOT, \".\" }\n end # group /\\./\n when text = ss.scan(/\\(/) then\n process_paren text\n when text = ss.scan(/\\,/) then\n action { result EXPR_PAR, TOKENS[text], text }\n when ss.match?(/=/) then\n case\n when text = ss.scan(/\\=\\=\\=|\\=\\=|\\=~|\\=>|\\=(?!begin\\b)/) then\n action { result arg_state, TOKENS[text], text }\n when bol? && (text = ss.scan(/\\=begin(?=\\s)/)) then\n process_begin text\n when text = ss.scan(/\\=(?=begin\\b)/) then\n action { result arg_state, TOKENS[text], text }\n end # group /=/\n when ruby22_label? && (text = ss.scan(/\\\"#{SIMPLE_STRING}\\\":/o)) then\n process_label text\n when text = ss.scan(/\\\"(#{SIMPLE_STRING})\\\"/o) then\n action { result EXPR_END, :tSTRING, text[1..-2].gsub(ESC) { unescape $1 } }\n when text = ss.scan(/\\\"/) then\n action { string STR_DQUOTE; result nil, :tSTRING_BEG, text }\n when text = ss.scan(/\\@\\@?\\d/) then\n action { rb_compile_error \"`#{text}` is not allowed as a variable name\" }\n when text = ss.scan(/\\@\\@?#{IDENT_CHAR}+/o) then\n process_ivar text\n when ss.match?(/:/) then\n case\n when not_end? && (text = ss.scan(/:([a-zA-Z_]#{IDENT_CHAR}*(?:[?]|[!](?!=)|=(?==>)|=(?![=>]))?)/o)) then\n process_symbol text\n when not_end? && (text = ss.scan(/\\:\\\"(#{SIMPLE_STRING})\\\"/o)) then\n process_symbol text\n when not_end? && (text = ss.scan(/\\:\\'(#{SSTRING})\\'/o)) then\n process_symbol text\n when text = ss.scan(/\\:\\:/) then\n process_colon2 text\n when text = ss.scan(/\\:/) then\n process_colon1 text\n end # group /:/\n when ss.skip(/->/) then\n action { result EXPR_ENDFN, :tLAMBDA, nil }\n when text = ss.scan(/[+-]/) then\n process_plus_minus text\n when ss.match?(/[+\\d]/) then\n case\n when ss.skip(/#{NUM_BAD}/o) then\n action { rb_compile_error \"Invalid numeric format\" }\n when ss.skip(/#{INT_DEC}/o) then\n action { int_with_base 10 }\n when ss.skip(/#{INT_HEX}/o) then\n action { int_with_base 16 }\n when ss.skip(/#{INT_BIN}/o) then\n action { int_with_base 2 }\n when ss.skip(/#{INT_OCT_BAD}/o) then\n action { rb_compile_error \"Illegal octal digit.\" }\n when ss.skip(/#{INT_OCT}/o) then\n action { int_with_base 8 }\n when ss.skip(/#{FLOAT_BAD}/o) then\n action { rb_compile_error \"Trailing '_' in number.\" }\n when text = ss.scan(/#{FLOAT}/o) then\n process_float text\n when ss.skip(/#{INT_DEC2}/o) then\n action { int_with_base 10 }\n when ss.skip(/[0-9]/) then\n action { rb_compile_error \"Bad number format\" }\n end # group /[+\\d]/\n when text = ss.scan(/\\[/) then\n process_square_bracket text\n when was_label? && (text = ss.scan(/\\'#{SSTRING}\\':?/o)) then\n process_label_or_string text\n when ss.match?(/\\|/) then\n case\n when ss.skip(/\\|\\|\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"||\" }\n when ss.skip(/\\|\\|/) then\n action { result EXPR_BEG, :tOROP, \"||\" }\n when ss.skip(/\\|\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"|\" }\n when ss.skip(/\\|/) then\n action { state = is_after_operator? ? EXPR_ARG : EXPR_PAR; result state, :tPIPE, \"|\" }\n end # group /\\|/\n when text = ss.scan(/\\{/) then\n process_brace_open text\n when ss.match?(/\\*/) then\n case\n when ss.skip(/\\*\\*=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"**\" }\n when ss.skip(/\\*\\*/) then\n action { result(:arg_state, space_vs_beginning(:tDSTAR, :tDSTAR, :tPOW), \"**\") }\n when ss.skip(/\\*\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"*\") }\n when ss.skip(/\\*/) then\n action { result(:arg_state, space_vs_beginning(:tSTAR, :tSTAR, :tSTAR2), \"*\") }\n end # group /\\*/\n when ss.match?(/</) then\n case\n when ss.skip(/\\<\\=\\>/) then\n action { result :arg_state, :tCMP, \"<=>\" }\n when ss.skip(/\\<\\=/) then\n action { result :arg_state, :tLEQ, \"<=\" }\n when ss.skip(/\\<\\<\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"<<\" }\n when text = ss.scan(/\\<\\</) then\n process_lchevron text\n when ss.skip(/\\</) then\n action { result :arg_state, :tLT, \"<\" }\n end # group /</\n when ss.match?(/>/) then\n case\n when ss.skip(/\\>\\=/) then\n action { result :arg_state, :tGEQ, \">=\" }\n when ss.skip(/\\>\\>=/) then\n action { result EXPR_BEG, :tOP_ASGN, \">>\" }\n when ss.skip(/\\>\\>/) then\n action { result :arg_state, :tRSHFT, \">>\" }\n when ss.skip(/\\>/) then\n action { result :arg_state, :tGT, \">\" }\n end # group />/\n when ss.match?(/\\`/) then\n case\n when expr_fname? && (ss.skip(/\\`/)) then\n action { result(EXPR_END, :tBACK_REF2, \"`\") }\n when expr_dot? && (ss.skip(/\\`/)) then\n action { result((cmd_state ? EXPR_CMDARG : EXPR_ARG), :tBACK_REF2, \"`\") }\n when ss.skip(/\\`/) then\n action { string STR_XQUOTE, '`'; result(nil, :tXSTRING_BEG, \"`\") }\n end # group /\\`/\n when text = ss.scan(/\\?/) then\n process_questionmark text\n when ss.match?(/&/) then\n case\n when ss.skip(/\\&\\&\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"&&\") }\n when ss.skip(/\\&\\&/) then\n action { result(EXPR_BEG, :tANDOP, \"&&\") }\n when ss.skip(/\\&\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"&\" ) }\n when ss.skip(/\\&\\./) then\n action { result(EXPR_DOT, :tLONELY, \"&.\") }\n when text = ss.scan(/\\&/) then\n process_amper text\n end # group /&/\n when text = ss.scan(/\\//) then\n process_slash text\n when ss.match?(/\\^/) then\n case\n when ss.skip(/\\^=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"^\") }\n when ss.skip(/\\^/) then\n action { result(:arg_state, :tCARET, \"^\") }\n end # group /\\^/\n when ss.skip(/\\;/) then\n action { self.command_start = true; result(EXPR_BEG, :tSEMI, \";\") }\n when ss.match?(/~/) then\n case\n when is_after_operator? && (ss.skip(/\\~@/)) then\n action { result(:arg_state, :tTILDE, \"~\") }\n when ss.skip(/\\~/) then\n action { result(:arg_state, :tTILDE, \"~\") }\n end # group /~/\n when ss.match?(/\\\\/) then\n case\n when ss.skip(/\\\\\\r?\\n/) then\n action { self.lineno += 1; self.space_seen = true; next }\n when ss.skip(/\\\\/) then\n action { rb_compile_error \"bare backslash only allowed before newline\" }\n end # group /\\\\/\n when text = ss.scan(/\\%/) then\n process_percent text\n when ss.match?(/\\$/) then\n case\n when text = ss.scan(/\\$_\\w+/) then\n process_gvar text\n when text = ss.scan(/\\$_/) then\n process_gvar text\n when text = ss.scan(/\\$[~*$?!@\\/\\\\;,.=:<>\\\"]|\\$-\\w?/) then\n process_gvar text\n when in_fname? && (text = ss.scan(/\\$([\\&\\`\\'\\+])/)) then\n process_gvar text\n when text = ss.scan(/\\$([\\&\\`\\'\\+])/) then\n process_backref text\n when in_fname? && (text = ss.scan(/\\$([1-9]\\d*)/)) then\n process_gvar text\n when text = ss.scan(/\\$([1-9]\\d*)/) then\n process_nthref text\n when text = ss.scan(/\\$0/) then\n process_gvar text\n when text = ss.scan(/\\$[^[:ascii:]]+/) then\n process_gvar text\n when text = ss.scan(/\\$\\W|\\$\\z/) then\n process_gvar_oddity text\n when text = ss.scan(/\\$\\w+/) then\n process_gvar text\n end # group /\\$/\n when text = ss.scan(/\\_/) then\n process_underscore text\n when text = ss.scan(/#{IDENT}/o) then\n process_token text\n when ss.skip(/\\004|\\032|\\000|\\Z/) then\n action { [RubyLexer::EOF, RubyLexer::EOF] }\n when text = ss.scan(/./) then\n action { rb_compile_error \"Invalid char #{text.inspect} in expression\" }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def next_token\n #dputs \"@line: \" + @line\n if @state == :normal\n while true\n temp = _next_token\n unless temp == \"#white_space\" || temp == \"#comment\"\n break\n end\n end\n #dputs \"token: \" + temp\n @current_token = temp\n return temp\n else\n return :Terminate\n end\n \n end", "def consume\n @current = @tokens[@pos]\n @pos += 1 if @current\n @current\n end", "def tokenize input\n setup_scanner input\n\n until @s.eos? do\n pos = @s.pos\n\n # leading spaces will be reflected by the column of the next token\n # the only thing we loose are trailing spaces at the end of the file\n next if @s.scan(/ +/)\n\n # note: after BULLET, LABEL, etc.,\n # indent will be the column of the next non-newline token\n\n @tokens << case\n # [CR]LF => :NEWLINE\n when @s.scan(/\\r?\\n/) then\n token = [:NEWLINE, @s.matched, *pos]\n @s.newline!\n token\n # === text => :HEADER then :TEXT\n when @s.scan(/(=+)(\\s*)/) then\n level = @s[1].length\n header = [:HEADER, level, *pos]\n\n if @s[2] =~ /^\\r?\\n/ then\n @s.unscan(@s[2])\n header\n else\n pos = @s.pos\n @s.scan(/.*/)\n @tokens << header\n [:TEXT, @s.matched.sub(/\\r$/, ''), *pos]\n end\n # --- (at least 3) and nothing else on the line => :RULE\n when @s.scan(/(-{3,}) *\\r?$/) then\n [:RULE, @s[1].length - 2, *pos]\n # * or - followed by white space and text => :BULLET\n when @s.scan(/([*-]) +(\\S)/) then\n @s.unscan(@s[2])\n [:BULLET, @s[1], *pos]\n # A. text, a. text, 12. text => :UALPHA, :LALPHA, :NUMBER\n when @s.scan(/([a-z]|\\d+)\\. +(\\S)/i) then\n # FIXME if tab(s), the column will be wrong\n # either support tabs everywhere by first expanding them to\n # spaces, or assume that they will have been replaced\n # before (and provide a check for that at least in debug\n # mode)\n list_label = @s[1]\n @s.unscan(@s[2])\n list_type =\n case list_label\n when /[a-z]/ then :LALPHA\n when /[A-Z]/ then :UALPHA\n when /\\d/ then :NUMBER\n else\n raise ParseError, \"BUG token #{list_label}\"\n end\n [list_type, list_label, *pos]\n # [text] followed by spaces or end of line => :LABEL\n when @s.scan(/\\[(.*?)\\]( +|\\r?$)/) then\n [:LABEL, @s[1], *pos]\n # text:: followed by spaces or end of line => :NOTE\n when @s.scan(/(.*?)::( +|\\r?$)/) then\n [:NOTE, @s[1], *pos]\n # >>> followed by end of line => :BLOCKQUOTE\n when @s.scan(/>>> *(\\w+)?$/) then\n [:BLOCKQUOTE, @s[1], *pos]\n # anything else: :TEXT\n else\n @s.scan(/(.*?)( )?\\r?$/)\n token = [:TEXT, @s[1], *pos]\n\n if @s[2] then\n @tokens << token\n [:BREAK, @s[2], pos[0] + @s[1].length, pos[1]]\n else\n token\n end\n end\n end\n\n self\n end", "def remove_mid_expression_newlines\n scan_tokens do |prev, token, post, i|\n next 1 unless post && EXPRESSION_CLOSE.include?(post[0]) && token[0] == \"\\n\"\n @tokens.delete_at(i)\n next 0\n end\n end", "def pre_tokenize(text)\n normalized_text = text.gsub(/^every\\s\\b/, '')\n normalized_text = text.gsub(/^each\\s\\b/, '')\n normalized_text = text.gsub(/^on the\\s\\b/, '')\n normalized_text.downcase\n end", "def tokens_to_s\n token_stream.compact.map { |token| token.text }.join ''\n end", "def tokenize(doc, h)\n begin\n PlanR::TokenStream.from_array(name, doc, \n doc.plaintext_ascii.split(/\\s/) )\n rescue Exception => e\n # FIXME: log\n $stderr.puts \"[PLAINTEXT PARSER] ERROR: #{e.message}\"\n $stderr.puts e.backtrace[0,4].join(\"\\n\")\n # FIXME: better default return value\n PlanR::TokenStream.from_array(name, doc, [])\n end\n end", "def tokens\n @tokens ||= Tokeniser.instance.tokenise(text)\n end", "def _lex_eof_trans; end", "def _lex_eof_trans; end", "def _lex_eof_trans; end", "def _lex_eof_trans; end", "def parse(text); end", "def ready_token (with_strip=true, skip_blanks=true)\n while (@buffer.nil? or @buffer.empty?) && !@io.eof?\n @buffer = @io.readline\n @buffer.force_encoding(\"BINARY\") if @buffer.respond_to?(:force_encoding)\n #@buffer.sub!(/%.*$/, '') if strip_comments\n @buffer.chomp!\n break unless skip_blanks\n end\n @buffer.lstrip! if with_strip\n end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def process(input_stream)\n debug 'Beginning tokenization of input'\n\n @stream = input_stream\n @stream_char = 1\n\n @output = [] if @state == :root\n\n until @stream.strip.empty?\n tk = tokenize\n @output.append(tk) if tk.instance_of? Token\n end\n\n @output\n end", "def tokenize text\r\n m = text.match(@regexp)\r\n return nil if m.nil?\r\n arguments = []\r\n # HACK: Skip the first word if the verb is not nil.\r\n # This is ugly.\r\n b = @verb.nil? ? 0 : 1\r\n @replace.to_s.split_words[b..-1].each { |r|\r\n if r.match(/^\\{\\$[0-9]+\\}$/)\r\n arguments.push m[r[2..-2].to_i]\r\n else\r\n arguments.push r\r\n end\r\n }\r\n Command.new @verb, arguments\r\n end", "def next_token; end", "def strip_newlines(input); end", "def prep_newlines(text)\n\ttext.gsub!(/^[\\w\\<][^\\n]*\\n+/) do |x|\n\t\tx =~ /\\n{2}/ ? x : (x.strip!; x << \" \\n\")\n\tend\n\ttext\nend", "def parse\n tagify(decommentify(@input)).strip\n end", "def text\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 54 )\n return_value = TextReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n text_start_index = @input.index\n\n success = false # flag used for memoization\n\n begin\n # rule memoization\n if @state.backtracking > 0 and already_parsed_rule?( __method__ )\n success = true\n return return_value\n end\n # at line 344:23: (~ EOL )+\n # at file 344:23: (~ EOL )+\n match_count_38 = 0\n while true\n alt_38 = 2\n alt_38 = @dfa38.predict( @input )\n case alt_38\n when 1\n # at line 344:24: ~ EOL\n if @input.peek(1) == WS || @input.peek( 1 ).between?( DIGIT, T__59 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n\n else\n match_count_38 > 0 and break\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n eee = EarlyExit(38)\n\n\n raise eee\n end\n match_count_38 += 1\n end\n\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n return_value.value = @input.to_s( return_value.start, @input.look( -1 ) )\n # <-- action\n end\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n success = true\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 54 )\n memoize( __method__, text_start_index, success ) if @state.backtracking > 0\n\n end\n \n return return_value\n end", "def tokenize text\r\n m = text.match(@regexp)\r\n return nil if m.nil?\r\n arguments = []\r\n b = @verb.nil? ? 0 : 1\r\n xverb = @verb\r\n @replace.to_s.split_words[b..-1].each { |r|\r\n if r.match(/^\\{\\$[0-9]+\\}$/)\r\n arguments.push m[r[2..-2].to_i]\r\n elsif arguments.empty? && xverb.nil?\r\n xverb = r.to_sym\r\n else\r\n arguments.push r\r\n end\r\n }\r\n Command.new xverb, arguments\r\n end", "def parse_line_break; end", "def tokenize(content, ptype = T.unsafe(nil)); end", "def pre_proccess(text)\n text.to_s.strip.gsub(/[[:space:]]+/, ' ').gsub(/\\s{2,}/, ' ')\n end", "def handle_regexp_HARD_BREAK target\n \"\\n\"\n end", "def tokenize\n # Slice each character if there's a symbol there; this leaves the symbol\n # at the end of the character array\n sliced_strings = split_on_symbol_locations(text)\n\n # Convert the final character of each string into a :symbol token, and\n # the rest into a :text token\n tokens = sliced_strings.zip(symbol_locations).flat_map do |text, sym_loc|\n if sym_loc.nil?\n # If the document doesn't end with a symbol, just return text\n Token.new(:text, text) \n else\n # If it does, return both text minus symbol, and then a symbol token\n [\n Token.new(:text, text[0...-1]),\n Token.new(:symbol, sym_loc.symbol)\n ]\n end\n end\n\n # Strip any empty tokens (can occur when symbols are adjacent)\n tokens_without_empty = reject_empty_text(tokens)\n\n # Add a :nil token to the beginning to make each_cons work properly\n tokens_without_empty.unshift(Token.new(:nil, nil))\n\n # Convert spaces at the beginning of lines to :space_count tokens\n tokens_with_space_counts = tokens_without_empty.each_cons(2).flat_map do |token1, token2|\n # We're only looking for :text tokens with :newline tokens before them\n next token2 unless token1 == Token.new(:symbol, :newline) \\\n && token2.type == :text\n\n # Count the number of spaces at the beginning of the string\n spaces_at_start = token2.value.scan(/^ */).first.length\n\n # Return a space count and a text token\n [\n Token.new(:space_count, spaces_at_start),\n Token.new(:text, token2.value.gsub(/^ +/, ''))\n ]\n end\n\n # Convert :space_count tokens to indents and dedents\n indent_level = 0 # current level of indentation\n indent_amount = nil # spaces required for an indent\n tokens_with_space_counts.flat_map do |token|\n # Only look for :space_count tokens\n next token unless token.type == :space_count\n\n # If this is any form of indentation and we don't know an indent amount\n # yet, set it\n indent_amount = token.value if indent_amount.nil? && !token.value.zero?\n\n # If we still don't know, skip\n next nil if indent_amount.nil?\n\n # Work out an indent delta\n # +x = indent by x levels, -x = dedent by x levels; x must be int\n indent_delta = token.value.to_f / indent_amount - indent_level\n raise 'invalid indentation' unless indent_delta % 1 == 0.0\n\n indent_level += indent_delta.to_i\n\n # Output tokens\n [Token.new(indent_delta.positive? ? :indent : :dedent, nil)] \\\n * indent_delta.abs\n end.reject(&:nil?)\n end", "def consume\n return nil if @s.eos?\n\n @s.mark\n return create_token(:whitespace) if @s.scan(RE_WHITESPACE)\n\n char = @s.consume\n\n case char.to_sym\n when :'\"'\n consume_string('\"')\n\n when :'#'\n if @s.peek =~ RE_NAME || valid_escape?\n create_token(:hash,\n :type => start_identifier? ? :id : :unrestricted,\n :value => consume_name)\n else\n create_token(:delim, :value => char)\n end\n\n when :'$'\n if @s.peek == '='\n @s.consume\n create_token(:suffix_match)\n else\n create_token(:delim, :value => char)\n end\n\n when :\"'\"\n consume_string(\"'\")\n\n when :'('\n create_token(:'(')\n\n when :')'\n create_token(:')')\n\n when :*\n if @s.peek == '='\n @s.consume\n create_token(:substring_match)\n\n elsif @options[:preserve_hacks] && @s.peek =~ RE_NAME_START\n # NON-STANDARD: IE * hack\n @s.reconsume\n consume_ident\n\n else\n create_token(:delim, :value => char)\n end\n\n when :+\n if start_number?(char + @s.peek(2))\n @s.reconsume\n consume_numeric\n else\n create_token(:delim, :value => char)\n end\n\n when :','\n create_token(:comma)\n\n when :-\n if start_number?(char + @s.peek(2))\n @s.reconsume\n consume_numeric\n elsif start_identifier?(char + @s.peek(2))\n @s.reconsume\n consume_ident\n elsif @s.peek(2) == '->'\n @s.consume\n @s.consume\n create_token(:cdc)\n else\n create_token(:delim, :value => char)\n end\n\n when :'.'\n if start_number?(char + @s.peek(2))\n @s.reconsume\n consume_numeric\n else\n create_token(:delim, :value => char)\n end\n\n when :/\n if @s.peek == '*'\n @s.consume\n\n if text = @s.scan_until(RE_COMMENT_CLOSE)\n text.slice!(-2, 2)\n else\n text = @s.consume_rest\n end\n\n if @options[:preserve_comments]\n create_token(:comment, :value => text)\n else\n consume\n end\n else\n create_token(:delim, :value => char)\n end\n\n when :':'\n create_token(:colon)\n\n when :';'\n create_token(:semicolon)\n\n when :<\n if @s.peek(3) == '!--'\n @s.consume\n @s.consume\n @s.consume\n\n create_token(:cdo)\n else\n create_token(:delim, :value => char)\n end\n\n when :'@'\n if start_identifier?\n create_token(:at_keyword, :value => consume_name)\n else\n create_token(:delim, :value => char)\n end\n\n when :'['\n create_token(:'[')\n\n when :'\\\\'\n if valid_escape?(char + @s.peek)\n @s.reconsume\n consume_ident\n else\n create_token(:delim,\n :error => true,\n :value => char)\n end\n\n when :']'\n create_token(:']')\n\n when :'^'\n if @s.peek == '='\n @s.consume\n create_token(:prefix_match)\n else\n create_token(:delim, :value => char)\n end\n\n when :'{'\n create_token(:'{')\n\n when :'}'\n create_token(:'}')\n\n when :U, :u\n if @s.peek(2) =~ RE_UNICODE_RANGE_START\n @s.consume\n consume_unicode_range\n else\n @s.reconsume\n consume_ident\n end\n\n when :|\n case @s.peek\n when '='\n @s.consume\n create_token(:dash_match)\n\n when '|'\n @s.consume\n create_token(:column)\n\n else\n create_token(:delim, :value => char)\n end\n\n when :~\n if @s.peek == '='\n @s.consume\n create_token(:include_match)\n else\n create_token(:delim, :value => char)\n end\n\n else\n case char\n when RE_DIGIT\n @s.reconsume\n consume_numeric\n\n when RE_NAME_START\n @s.reconsume\n consume_ident\n\n else\n create_token(:delim, :value => char)\n end\n end\n end", "def unconsume_tokens!\n consumed_tokens.each do |token|\n kase.restore_token(token)\n end\n end", "def _pop_token(body)\n indx = body.index(' ') || body.length\n token = body[0...indx]\n body[0..indx] = ''\n return token\nend", "def tokenize(source = T.unsafe(nil), options = T.unsafe(nil)); end", "def unwrap_text(text)\n text.gsub(/([^\\n])\\n([^\\n])/, '\\1 \\2')\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n if ss.check(/\\n/) then\n self.lineno += 1\n # line starts 1 position after the newline\n self.start_of_current_line_pos = ss.pos + 1\n end\n self.old_pos = ss.pos\n token =\n case state\n when nil, :option, :inner, :start, :macro, :rule, :group then\n case\n when ss.skip(/options?.*/) then\n [:state, :option]\n when ss.skip(/inner.*/) then\n [:state, :inner]\n when ss.skip(/macros?.*/) then\n [:state, :macro]\n when ss.skip(/rules?.*/) then\n [:state, :rule]\n when ss.skip(/start.*/) then\n [:state, :start]\n when ss.skip(/end/) then\n [:state, :END]\n when ss.skip(/\\A((?:.|\\n)*)class ([\\w:]+.*)/) then\n action { [:class, *matches] }\n when ss.skip(/\\n+/) then\n # do nothing\n when text = ss.scan(/\\s*(\\#.*)/) then\n action { [:comment, text] }\n when (state == :option) && (ss.skip(/\\s+/)) then\n # do nothing\n when (state == :option) && (text = ss.scan(/stub/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/debug/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/do_parse/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/lineno/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/column/i)) then\n action { [:option, text] }\n when (state == :inner) && (text = ss.scan(/.*/)) then\n action { [:inner, text] }\n when (state == :start) && (text = ss.scan(/.*/)) then\n action { [:start, text] }\n when (state == :macro) && (ss.skip(/\\s+(\\w+)\\s+#{RE}/o)) then\n action { [:macro, *matches] }\n when (state == :rule) && (ss.skip(/\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:rule, *matches] }\n when (state == :rule) && (ss.skip(/\\s*:[\\ \\t]*#{RE}/o)) then\n action { [:grouphead, *matches] }\n when (state == :group) && (ss.skip(/\\s*:[\\ \\t]*#{RE}/o)) then\n action { [:grouphead, *matches] }\n when (state == :group) && (ss.skip(/\\s*\\|\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:group, *matches] }\n when (state == :group) && (ss.skip(/\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:groupend, *matches] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :END then\n case\n when ss.skip(/\\n+/) then\n # do nothing\n when text = ss.scan(/.*/) then\n action { [:end, text] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def next_token\n tokens.shift\n end", "def consume\n return nil if @s.eos?\n\n @s.mark\n\n # Consume comments.\n if comment_token = consume_comments\n if @options[:preserve_comments]\n return comment_token\n else\n return consume\n end\n end\n\n # Consume whitespace.\n return create_token(:whitespace) if @s.scan(RE_WHITESPACE)\n\n char = @s.consume\n\n case char.to_sym\n when :'\"'\n consume_string\n\n when :'#'\n if @s.peek =~ RE_NAME || valid_escape?(@s.peek(2))\n create_token(:hash,\n :type => start_identifier?(@s.peek(3)) ? :id : :unrestricted,\n :value => consume_name)\n else\n create_token(:delim, :value => char)\n end\n\n when :'$'\n if @s.peek == '='\n @s.consume\n create_token(:suffix_match)\n else\n create_token(:delim, :value => char)\n end\n\n when :\"'\"\n consume_string\n\n when :'('\n create_token(:'(')\n\n when :')'\n create_token(:')')\n\n when :*\n if @s.peek == '='\n @s.consume\n create_token(:substring_match)\n\n # Non-standard: Preserve the IE * hack.\n elsif @options[:preserve_hacks] && @s.peek =~ RE_NAME_START\n @s.reconsume\n consume_ident\n\n else\n create_token(:delim, :value => char)\n end\n\n when :+\n if start_number?\n @s.reconsume\n consume_numeric\n else\n create_token(:delim, :value => char)\n end\n\n when :','\n create_token(:comma)\n\n when :-\n nextTwoChars = @s.peek(2)\n nextThreeChars = char + nextTwoChars\n\n if start_number?(nextThreeChars)\n @s.reconsume\n consume_numeric\n elsif nextTwoChars == '->'\n @s.consume\n @s.consume\n create_token(:cdc)\n elsif start_identifier?(nextThreeChars)\n @s.reconsume\n consume_ident\n else\n create_token(:delim, :value => char)\n end\n\n when :'.'\n if start_number?\n @s.reconsume\n consume_numeric\n else\n create_token(:delim, :value => char)\n end\n\n when :':'\n create_token(:colon)\n\n when :';'\n create_token(:semicolon)\n\n when :<\n if @s.peek(3) == '!--'\n @s.consume\n @s.consume\n @s.consume\n\n create_token(:cdo)\n else\n create_token(:delim, :value => char)\n end\n\n when :'@'\n if start_identifier?(@s.peek(3))\n create_token(:at_keyword, :value => consume_name)\n else\n create_token(:delim, :value => char)\n end\n\n when :'['\n create_token(:'[')\n\n when :'\\\\'\n if valid_escape?\n @s.reconsume\n consume_ident\n else\n # Parse error.\n create_token(:delim,\n :error => true,\n :value => char)\n end\n\n when :']'\n create_token(:']')\n\n when :'^'\n if @s.peek == '='\n @s.consume\n create_token(:prefix_match)\n else\n create_token(:delim, :value => char)\n end\n\n when :'{'\n create_token(:'{')\n\n when :'}'\n create_token(:'}')\n\n when :U, :u\n if @s.peek(2) =~ RE_UNICODE_RANGE_START\n @s.consume\n consume_unicode_range\n else\n @s.reconsume\n consume_ident\n end\n\n when :|\n case @s.peek\n when '='\n @s.consume\n create_token(:dash_match)\n\n when '|'\n @s.consume\n create_token(:column)\n\n else\n create_token(:delim, :value => char)\n end\n\n when :~\n if @s.peek == '='\n @s.consume\n create_token(:include_match)\n else\n create_token(:delim, :value => char)\n end\n\n else\n case char\n when RE_DIGIT\n @s.reconsume\n consume_numeric\n\n when RE_NAME_START\n @s.reconsume\n consume_ident\n\n else\n create_token(:delim, :value => char)\n end\n end\n end", "def parse_text(text)\n\n end", "def get_text\n text = ''\n sep = ''\n @lexemes.each { |lexeme|\n if lexeme == '.'\n text << lexeme\n sep = ''\n else\n text << sep\n text << lexeme\n sep = ' '\n end\n }\n\t@lexemes = []\n text\n end", "def next_token\n @sy = @tokenizer.next_token\n \n # ignore EOL tokens since no productions would accept them\n while @sy.type == TokenType::EOL_TOKEN\n @sy = @tokenizer.next_token\n end\n end", "def token(content, kind); end", "def reduce_new_line(_production, _range, _tokens, _children)\n # TODO: control portability\n Regex::Character.new('\\n')\n end", "def handle_regexp_HARD_BREAK target\n \" \\n\"\n end", "def newline!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 100 )\n\n type = NEWLINE\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 914:5: ( '\\\\n' | '\\\\r' )+\n # at file 914:5: ( '\\\\n' | '\\\\r' )+\n match_count_29 = 0\n while true\n alt_29 = 2\n look_29_0 = @input.peek( 1 )\n\n if ( look_29_0 == 0xa || look_29_0 == 0xd )\n alt_29 = 1\n\n end\n case alt_29\n when 1\n # at line \n if @input.peek(1) == 0xa || @input.peek(1) == 0xd\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n else\n match_count_29 > 0 and break\n eee = EarlyExit(29)\n\n\n raise eee\n end\n match_count_29 += 1\n end\n\n # --> action\n channel = HIDDEN \n # <-- action\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 100 )\n\n end", "def nl!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 51 )\n\n\n\n type = NL\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 230:5: ( '\\\\n' )+\n # at file 230:5: ( '\\\\n' )+\n match_count_8 = 0\n while true\n alt_8 = 2\n look_8_0 = @input.peek( 1 )\n\n if ( look_8_0 == 0xa )\n alt_8 = 1\n\n end\n case alt_8\n when 1\n # at line 230:5: '\\\\n'\n match( 0xa )\n\n else\n match_count_8 > 0 and break\n eee = EarlyExit(8)\n\n\n raise eee\n end\n match_count_8 += 1\n end\n\n\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 51 )\n\n\n end", "def parse text\n text.gsub(/^%.*$/,'').split(/\\n\\n/).map do |s|\n s.chomp!\n s.gsub(/^#{$/}/,'') unless s.empty?\n end . compact\n end", "def lex_en_plain_backslash_delimited_words; end", "def lex_en_plain_backslash_delimited_words; end", "def lex_en_plain_backslash_delimited_words; end", "def suspend(token_names = nil)\n token_names = token_names || token_library.map { |t| t.name }\n active_tokens = token_library.select { |t|\n \ttoken_names.map(&:to_sym).include?(t.name.to_sym)\n }\n @suspended_tokens = AbsoluteSuspendedTokens.new\n @filtered_text = \"\"\n token_start = 0\n effective_bol = nil\n previous_token_was_at_bol_and_transparent = nil\n s = StringScanner.new(@original_doc)\n while !s.eos? do\n if debug\n puts\n puts '-' * 40\n puts \"New ss pos: #{ (s.post_match || s.rest).inspect }\"\n end\n match_found = false\n # Compute effective_bol flag. The current position is considered\n # beginning of line if any of the following ist true:\n # * Current pos is at beginning of line.\n # * Previous token was at bol and was removed.\n # * Next char is `\\n`, so effectively it's at beginning of line. This\n # is required for block level tokens that are preceded by only one,\n # not two `\\n`, but should still consume the leading `\\n`.\n # See repositext_tokens.rb BLOCK_START for more details.\n effective_bol = (\n s.beginning_of_line? ||\n previous_token_was_at_bol_and_transparent ||\n \"\\n\" == s.peek(1)\n )\n if debug\n puts \"effective_bol: #{ effective_bol.inspect }\"\n puts \" - s.beginning_of_line?: #{ s.beginning_of_line?.inspect }\"\n puts \" - previous_token_was_at_bol_and_transparent: #{ previous_token_was_at_bol_and_transparent.inspect }\"\n puts \" - \\\"\\\\n\\\" == s.peek(1): #{ \"\\n\" == s.peek(1) }\"\n puts \"Trying tokens:\"\n end\n active_tokens.each { |token|\n if debug\n puts \" - trying token #{ token.name }\"\n puts \" token.must_be_start_of_line: #{ token.must_be_start_of_line.inspect }\"\n puts \" token.is_transparent_to_beginning_of_line: #{ token.is_transparent_to_beginning_of_line.inspect }\"\n puts \" #{ !token.must_be_start_of_line } || #{ effective_bol }\"\n end\n previous_token_was_at_bol_and_transparent = false\n if(\n !token.must_be_start_of_line || effective_bol) &&\n (contents = s.scan(token.regex)\n )\n # Token doesn't need to be at beginning of line or\n # current pos is effectively at beginning of line\n # and rest matches token's regex\n match_found = true\n if token.is_plaintext\n if debug\n puts ' - found plaintext '\n puts \" #{ contents.inspect }\"\n end\n @filtered_text << contents\n token_start += contents.length\n else\n if debug\n puts ' - found token '\n puts \" start: #{ token_start }, name: #{ token.name }, contents: #{ contents.inspect }, is_transparent_to_beginning_of_line: #{ token.is_transparent_to_beginning_of_line.inspect }\"\n end\n @suspended_tokens << SuspendedToken.new(token_start, token.name, contents)\n previous_token_was_at_bol_and_transparent = token.is_transparent_to_beginning_of_line && effective_bol\n break # OPTIMIZE: investigate if moving break after this if statement makes things faster. Shouldn't we break on plaintext matches, too?\n end\n end\n }\n if !match_found\n ch = s.getch # Is a multi-byte character counted as length=1?\n if debug\n puts '- no match, getch '\n puts \" #{ ch.inspect }\"\n end\n @filtered_text << ch\n token_start += ch.length\n end\n end\n self\n end", "def content_tokens\n [preamble, body].join(' ')\n end", "def content_tokens\n [preamble, body].join(' ')\n end", "def parse\n length = @chars.length\n @index = 0\n while @index < length\n @tokens << if custom?\n parse_custom\n else\n parse_char\n end\n @index += 1\n end\n @tokens\n end", "def tokenize\n for c in @code.split(\" \").map(&:to_s)\n $tokens << getToken\n @code = @code.strip\n end\n $tokens\n end", "def post_process(doc)\n doc.gsub(\"\\n\",'')\n end", "def tokenize\n\t\tout_tokens = Array.new\n\t\t\n\t\t@token_offset = 0\n\t\tuntil @token_offset >= (self.length - 1)\n\t\t\tout_tokens << next_token\n\t\tend\n\t\t\n\t\tout_tokens.reject {|token| token.empty? }\n\tend", "def full_tokenize(pattern)\n PatternTokenizer.new(data_reader, full_tokenizer).tokenize(pattern)\n end", "def parse(text)\n tokens = tokenize(text, options)\n span = tokens_to_span(tokens, options.merge(:text => text))\n\n puts \"+#{'-' * 51}\\n| #{tokens}\\n+#{'-' * 51}\" if Chronic.debug\n\n guess(span, options[:guess]) if span\n end", "def strip_newlines text\n text.gsub(/\\A\\n*(.*?)\\n*\\z/m, '\\1')\n end", "def next_token\n \n # Early return if there is nothing to be read. This means we've reached the end of the file.\n \n unless @file[@pos]\n return nil\n end\n \n # This is the token that will be returned.\n token = Compiler::Token.new\n \n # Initializes a new instance of the automaton.\n automaton = Automaton.new\n \n # Will be set inside the loop, if necessary.\n increment_next = false\n \n # Will be set inside the loop. Marks whether we've reached the end of the file.\n eof = false\n \n # Build a new token while we don't have a new word yet and isn't in the failed state\n while ((automaton.state != :A || automaton.word.empty?) && automaton.state != :failed)\n \n # The next input for the automaton\n char = @file[@pos]\n \n if char\n \n # Moves the pointer to the next char\n @pos += 1\n \n automaton.transition(char)\n \n # While the automaton hasn't started to build a new word yet, increments the line and column numbers.\n # In this phase, we're just skipping blank characters\n if automaton.word.empty?\n if increment_next\n if char == \"\\n\"\n increment_next = true\n else\n increment_next = false\n end\n @line += 1\n @column = 0\n elsif char == \"\\n\"\n @column += 1\n increment_next = true\n else\n @column += 1\n end\n end\n \n else\n eof = true\n puts \"breaking\"\n break\n end\n end\n \n \n \n if eof\n automaton.transition(\"\\n\")\n else\n @pos -= 1\n end\n \n if (automaton.type == :identifier) && (Compiler.reserved_words.is_reserved?(automaton.word))\n token.type = :reserved_word\n else\n token.type = automaton.type\n end\n \n token.value = automaton.word\n token.line = @line\n token.column = @column\n \n return token\n \n end", "def tokenize\n super.merge(:tags => tags.taggify(\" \", \" \"))\n end", "def tokenize\n @stack = [ TokenList.new ]\n @num_open_brackets = 0\n @token_buffer = nil\n until content.eos?\n if @num_open_brackets > 0\n _build_token_list_inside_sub\n else\n _build_token_list_outside_sub\n end\n end\n _flush_token_buffer\n _flush_stack\n\n @tokens = @stack.first\n end", "def tokenize\n return [] if unencoded_text.blank?\n # kill off all punctuation except [stuff]'s or [stuff]'t\n # this includes hyphens (words are split)\n str = unencoded_text.\n downcase.\n gsub(/[^a-zA-Z0-9\\']+/, ' ').\n gsub(/(\\w)\\'([st])\\b/, '\\1!\\2').gsub(/\\'/, ' ').gsub(/!/, \"'\")\n # Busticate at whitespace\n words = str.strip.split(/\\s+/)\n words.reject!{|w| w.length < 3 }\n words.map!{|w| Wukong::encode_str(w) }\n end", "def strip_newlines text\n text.gsub(/\\A\\n*(.*?)\\n*\\z/m) do $1 end # block preserves String encoding\n end" ]
[ "0.6738388", "0.6738388", "0.66725445", "0.66034937", "0.66034937", "0.64914036", "0.63945186", "0.63945186", "0.63693213", "0.6359327", "0.62989026", "0.6160446", "0.60512424", "0.6021501", "0.6021501", "0.60016537", "0.5986833", "0.5967097", "0.5902801", "0.58961946", "0.58659154", "0.58640766", "0.5849841", "0.5818095", "0.58173966", "0.5799588", "0.5799588", "0.5762339", "0.5758418", "0.5746099", "0.5712118", "0.5682888", "0.5681012", "0.5679017", "0.56727225", "0.5667799", "0.5658085", "0.5634239", "0.561124", "0.561124", "0.561124", "0.561124", "0.56057906", "0.5604688", "0.55957925", "0.55957925", "0.55957925", "0.55957925", "0.55957925", "0.55957925", "0.55957925", "0.55957925", "0.55916035", "0.55869544", "0.5583082", "0.55737", "0.55703634", "0.5556435", "0.55525345", "0.5547119", "0.5516966", "0.55051816", "0.5502455", "0.5502374", "0.5489409", "0.5471766", "0.54657906", "0.54294574", "0.54276246", "0.542306", "0.5419079", "0.5418", "0.54158205", "0.54020333", "0.53925586", "0.53884566", "0.5388177", "0.5383053", "0.53748137", "0.5374125", "0.53515804", "0.5348054", "0.53398025", "0.53398025", "0.53398025", "0.5311909", "0.53104013", "0.53104013", "0.5309413", "0.52958566", "0.5295058", "0.5294331", "0.5284958", "0.5279834", "0.52764153", "0.52708584", "0.52699214", "0.52697915", "0.5263723", "0.52597314" ]
0.5282788
93
Calculates the column and line of the current token based on +offset+.
def token_pos offset [offset - @line_pos, @line] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def token_pos(byte_offset) # :nodoc:\n [byte_offset - @line_pos, @line]\n end", "def offset_on_line(offset)\n end", "def pos_on_line(offset)\n end", "def line_for_offset(offset)\n end", "def get_line_and_column_from_chunk(offset)\n if offset.zero?\n return [@chunk_line, @chunk_column]\n end\n\n string =\n offset >= @chunk.size ? @chunk : @chunk[0..offset-1]\n\n line_count = string.count(\"\\n\")\n\n column = @chunk_column\n if line_count > 0\n lines = string.split(\"\\n\")\n column = lines.empty? ? 0 : lines[-1].size\n else\n column += string.size\n end\n\n [@chunk_line + line_count, column]\n end", "def pos_on_line(offset)\n offset_on_line(offset) +1\n end", "def pos_on_line(offset)\n offset_on_line(offset) +1\n end", "def char_offset(offset)\n effective_line = @locator.line_for_offset(offset)\n locator.char_offset(offset) + (effective_line * @leading_line_offset) + @leading_offset\n end", "def line_and_column(pos); end", "def line_for_offset(token, offset = nil)\n locator_method_with_offset(token, :line_for_offset, offset || token.offset)\n end", "def line_for_offset(offset)\n if line_nbr = line_index.index {|x| x > offset}\n return line_nbr\n end\n # If not found it is after last\n return line_index.size\n end", "def current_line_pos\n pos - col\n end", "def offset_on_line(offset)\n line_offset = line_index[line_for_offset(offset)-1]\n if multibyte?\n @string.byteslice(line_offset, offset-line_offset).length\n else\n offset - line_offset\n end\n end", "def elmt_offset_at token_index\n # Defaults to the character position BEYOND the last text element\n (self[token_index]&.last if token_index) || (last.last + self.last.first.to_s.length)\n end", "def offset_on_line(offset)\n line_offset = line_index[ line_for_offset(offset)-1 ]\n @string.byteslice(line_offset, offset-line_offset).length\n end", "def line_char_to_offset(text, line, character); end", "def offset_on_line(offset)\n @locator.offset_on_line + @leading_line_offset\n end", "def line_for_offset(offset)\n @locator.line_for_offset(offset) + @leading_line_count\n end", "def column\n old_pos - start_of_current_line_pos\n end", "def column\n old_pos - start_of_current_line_pos\n end", "def current_offset; end", "def lines_offset\n @starting_line - 1\n end", "def line_offset\n\t\t\t@offset - @line_range.min\n\t\tend", "def line_and_column(position = T.unsafe(nil)); end", "def line_for_offset(offset)\n if @prev_offset == offset\n # use cache\n return @prev_line\n end\n line_nbr = ary_bsearch_i(line_index, offset)\n if line_nbr\n # cache\n @prev_offset = offset\n @prev_line = line_nbr\n return line_nbr\n end\n # If not found it is after last\n # clear cache\n @prev_offset = @prev_line = nil\n return line_index.size\n end", "def line_column(string, offset)\n return 1,1 if string.length==0 || offset==0\n lines = (string[0..offset-1] + \" \").split(\"\\n\")\n return lines.length, lines[-1].length\n end", "def to_offset(text, position); end", "def build_position(target = :lexeme)\n\t\toffset = (target == :lexeme)? @token_pos : scanner.pos()\n begin\n\t\tlinepos = offset - @line_offset # Position relative to start of line\n rescue NoMethodError => exc\n STDERR.puts \"@token_pos = #{@token_pos}\"\n STDERR.puts \"scanner.pos = #{scanner.pos}\"\n STDERR.puts \"@line_offset = #{@line_offset}\"\n raise exc\n end\n\t\tposition = LexemePosition.new(offset, @lineno, linepos)\n\t\treturn position\n\tend", "def pos_on_line(obj, offset)\n # TODO: Should really use the SourceAdpater\n # https://github.com/puppetlabs/puppet-strings/blob/ede2b0e76c278c98d57aa80a550971e934ba93ef/lib/puppet-strings/yard/parsers/puppet/statement.rb#L22-L25\n\n # Puppet 5 exposes the source locator on the Pops object\n return obj.locator.pos_on_line(offset) if obj.respond_to?(:locator)\n\n # Revert to Puppet 4.x location information. A little more expensive to call\n obj_loc = Puppet::Pops::Utils.find_closest_positioned(obj)\n obj_loc.locator.pos_on_line(offset)\n end", "def line_for_position(position); end", "def line_for_position(position); end", "def line_for_position(position); end", "def current_column\n @col_offset\n end", "def character_at(source_position, offset = 0)\n actual_line = source_position.line - 1\n actual_offset = source_position.offset + offset - 1\n\n # Return a newline if offset points at the very end of the line\n return \"\\n\" if actual_offset == engine.lines[actual_line].length\n\n engine.lines[actual_line][actual_offset]\n end", "def char_offset(offset)\n raise \"Should not be called\"\n end", "def get_current_offset\n @offset < 0 ? 0 : @offset\n end", "def col\r\n @lines[@line_num].cursor\r\n end", "def column\n\t return -1 if @inputStack.empty? # only if initialize() arg is bogus\n\n\t input = @inputStack[0] # not @inputStack.last\n\t currLineStart = input.string.rindex(\"\\n\", input.pos)\n\t return input.pos + 1 if currLineStart.nil?\n\t return input.pos - currLineStart + 1\n\tend", "def _calculate_column_offsets\n total = 0\n coffsets = []\n ctr = 0\n ## ix will have gaps in between for hidden fields\n each_column { | c, ix|\n v = c.width\n coffsets[ctr] = total\n ctr += 1\n total += v + 2 ## blank space plus separator\n }\n return coffsets\n end", "def byte_offset(loc) loc.y * line_byte_size + loc.x * pixel_byte_size; end", "def offset_to(source_position, pattern, offset = 0)\n actual_line = source_position.line - 1\n actual_offset = source_position.offset + offset - 1\n\n return nil if actual_line >= engine.lines.size\n\n actual_index = engine.lines[actual_line].index(pattern, actual_offset)\n\n actual_index && actual_index + 1 - source_position.offset\n end", "def get_char_position_in_line\n raise NotImplementedError\n end", "def offset; end", "def offset; end", "def offset; end", "def line\n return 1 unless lexing_context && locator\n locator.line_for_offset(lexing_context[:end_offset])\n end", "def each_line_with_offset\n return to_enum(:each_line_with_offset) unless block_given?\n\n offset = 0\n\n each_line do |line|\n yield line, offset\n offset = tell\n end\n end", "def offset(*) end", "def position_in_source\n pos = @locator.pos_on_line(lexing_context[:offset])\n offset = @locator.char_offset(lexing_context[:offset])\n length = @locator.char_length(lexing_context[:offset], lexing_context[:end_offset])\n start_line = @locator.line_for_offset(lexing_context[:offset])\n\n return { :line => start_line, :pos => pos, :offset => offset, :length => length}\n end", "def offset\n\t\t\t@position + @offset\n\t\tend", "def line_offset(pos=pos())\n p = 0\n string.each_line do |line|\n len = line.length\n return (pos - p) if p + len >= pos\n p += len\n end\n 0\n end", "def first_offset; end", "def first_offset; end", "def line_offset(pos=pos)\n p = 0\n string.each_line do |line|\n len = line.length\n return (pos - p) if p + len >= pos\n p += len\n end\n 0\n end", "def line_index()\n end", "def get_offset\n @offset\n end", "def offset_after_match\n offset + match_length\n end", "def offset()\n @offset__\n end", "def tokenizer_result_row_result_position\n TokenExtractor.new(\n :result_position,\n #/(?<=\\n:)\\s*(fc|fg|\\d{1,3}|\\s+)\\s(?=:)/ix,\n #/(?<=:)\\s.{20,27}\\s:\\s\\d{2}\\s:\\s.{20,27}\\s:/i\n 1,\n 3\n )\n end", "def x_offset; end", "def line_for_offset(obj, offset)\n # TODO: Should really use the SourceAdpater\n # https://github.com/puppetlabs/puppet-strings/blob/ede2b0e76c278c98d57aa80a550971e934ba93ef/lib/puppet-strings/yard/parsers/puppet/statement.rb#L22-L25\n\n # Puppet 5 exposes the source locator on the Pops object\n return obj.locator.line_for_offset(offset) if obj.respond_to?(:locator)\n\n # Revert to Puppet 4.x location information. A little more expensive to call\n obj_loc = Puppet::Pops::Utils.find_closest_positioned(obj)\n obj_loc.locator.line_for_offset(offset)\n end", "def char_offset(byte_offset)\n end", "def _lex_index_offsets; end", "def _lex_index_offsets; end", "def _lex_index_offsets; end", "def _lex_index_offsets; end", "def row_col(pos)\n _pos = 0\n row = 0\n col = 1\n @codes.each do |code|\n break if _pos >= pos\n if line_terminator?(code)\n row += 1\n col = 0\n else\n col += 1\n end\n _pos += 1\n end\n return [row+1, col+1]\n end", "def offset\n 1\n end", "def xy(offset_x, offset_y)\n @board[3 * offset_y + offset_x - 4]\n end", "def index_line_and_col(index) \n\t\ti = 0\n\t\ti += 1 while index_of_position(i) <= index\n\t\ti -= 1\n\t\t[i, index - index_of_position(i)]\n\tend", "def get_line_and_col_pos(pos)\n pos = self.size if pos > self.size\n pos = 0 if pos < 0\n\n lpos = get_line_pos(pos)\n\n lpos = @line_ends.size if lpos == nil\n cpos = pos\n cpos -= @line_ends[lpos - 1] + 1 if lpos > 0\n\n return [lpos, cpos]\n end", "def advance_position\n matched_fragment = @str[@pos...@s.pos]\n new_lines = matched_fragment.count(\"\\n\")\n if new_lines > 0\n characters_after_last_newline = matched_fragment.size - matched_fragment.rindex(\"\\n\") - 1\n [@line + new_lines, 1 + characters_after_last_newline]\n else\n [@line, @char + matched_fragment.size]\n end\n end", "def parse_and_set_offset(offset)\n if @handle.ptr == nil\n raise \"this is disposed\"\n end\n result = Native.RunEditor_parse_and_set_offset(@handle.ptr, offset)\n result\n end", "def location_of(offset, group)\n log_no, log_offset = offset.divmod(group.size)\n block_no, block_offset = (log_offset - LOG_HEADER_SIZE).divmod(LOG_BLOCK_SIZE)\n [log_no, block_no, block_offset]\n end", "def tell\n @offset\n end", "def first_position_from_expression(node)\n expression = node.loc.expression\n if node.parent && node.parent.loc.expression.line != expression.line\n expression.begin_pos - expression.column\n else\n expression.begin_pos\n end\n end", "def line_token\n return nil unless md = MULTI_DENT.match(@chunk)\n\n @tokens.last.last.push newLine: true\n token :Terminator, \"\\n\"\n\n indent = md.to_a[0]\n num_newlines = count(indent, \"\\n\")\n spaces = indent.length - num_newlines\n\n @line += num_newlines\n\n movement = spaces - @indent\n if movement > 0\n @indents.push movement\n token :Indent, movement\n elsif movement < 0\n outdent_token movement.abs, num_newlines\n end\n\n @indent += movement\n indent.length\n end", "def view_offset\n @position + @view.position\n end", "def offset\n execute['offset']\n end", "def tokenizer_relay_row_result_position\n TokenExtractor.new(\n :result_position,\n /^\\s+(\\d|fuori|fg|f\\.g\\.)/i,\n# 8, # (starting idx)\n /(?<=\\d\\s)\\s|(?<=fuori gara)\\s|(?<=f\\.g\\.)\\s|(?<=fg)\\s/i\n# 10 # (max size)\n )\n end", "def normalize_offset(offset); end", "def index_of_position(row, col = 0)\n\t\tline_index(row) + col + 1\n\tend", "def current_line\n # get the actual offset\n start = @buffer.get_iter_at_offset(@@offset)\n\n # get the command\n line = @buffer.get_text(start, @buffer.end_iter)\n\n return line\n end", "def offset\n fil_header[:offset]\n end", "def determine_end_offset_relative_to_source(end_offset, last_line_length)\n end_offset - last_line_length - 1\n end", "def from_line_index\n from_line - 1\n end", "def line_num_to_coord(n)\n\t\t(n + 1) * font_metrics.height\n\tend", "def line_offset(line_index)\n return unless line_exists?(line_index)\n line_index == 0 ? 0 : @line_lengths[0..(line_index - 1)].sum\n end", "def location\n\t\treturn \"line %s, column %s\" % [\n\t\t\tself.linenum || '??',\n\t\t\tself.colnum || '??',\n\t\t]\n\tend", "def line_before\n line[0..column - 1].to_s\n end", "def offset_of_regexp_in_line(line, regexp)\n if match = regexp.match(line)\n match.offset(match.size > 1 ? 1 : 0)[0]\n else\n -1\n end\n end", "def current_line_number; end", "def tree_at(line, column); end", "def next_line(input=[])\r\n @tokens = input\r\n @column = -1\r\n @line += 1\r\n end", "def line_token\n return unless match = @chunk.match(MULTI_DENT)\n\n indent, _ = *match\n size = indent.size - 1\n incomplete = unfinished\n\n #\n # elements.\n # ...foo. <- size: 4, indebt: 0, indent: 0\n # ...bar. <- size: 4, indebt: 4, indent: 4\n # -- case 1. finished && outdented\n # batman <- size: 0, indebt: 4, indent: 0\n # -- case 2. finished && same indent\n # ...batman size: 4, indebt: 4, indent: 4\n #\n if size - @indebt == @indent\n incomplete ? suppress_newlines : newline_token(0)\n return indent.size\n end\n\n if size > @indent\n if incomplete\n @indebt = size - @indent\n suppress_newlines\n return indent.size\n end\n if @tokens.size.zero?\n @base_indent = @indent = size\n return indent.size\n end\n indent_token(size, indent.size - size)\n elsif size < @base_indent\n raise_syntax_error! 'missing indentation'\n else\n @indebt = 0\n outdent_token(@indent - size, incomplete, indent.size)\n end\n\n indent.size\n end", "def newline_token(offset)\n @tokens.pop while value == ';'\n\n # 1. function prototype\n if tag == ':'\n indent_token(@indent+2)\n outdent_token(2)\n\n # 2. prevent doubles terminators\n # 3. prevent terminator after indent\n # 4. prevent starting with a term on an empty file\n elsif ![:TERM, :INDENT].include?(tag) && !tokens.empty?\n token(:TERM, \"\\n\", offset, 0)\n end\n end", "def parse_index_offset\n return -1 if @isMzData\n r = %r{\\<indexOffset\\>(\\d+)\\<\\/indexOffset\\>}\n seekoffset = -120\n while true \n self.seek(seekoffset, IO::SEEK_END)\n if (r.match(self.read)) then \n return $1.to_i\n end\n seekoffset -= 10\n return -1 if seekoffset <= -1000\n end\n end", "def y_offset; end", "def tokenizer_relay_row_result_position\n TokenExtractor.new(\n :result_position,\n 0,\n /\\s[a-z]+/uix\n )\n end", "def start_line_number=(_); end" ]
[ "0.7708019", "0.75606894", "0.750005", "0.7395713", "0.7213591", "0.71804374", "0.71804374", "0.7128925", "0.6958157", "0.6950198", "0.688341", "0.68291587", "0.68017244", "0.67835814", "0.6753973", "0.6700305", "0.6678214", "0.65833074", "0.6564007", "0.6564007", "0.65455973", "0.65243673", "0.6444381", "0.64127177", "0.6389056", "0.6344151", "0.63075745", "0.6264308", "0.6260729", "0.624638", "0.624638", "0.624638", "0.62453425", "0.622549", "0.620552", "0.6203319", "0.6181163", "0.6163281", "0.61447346", "0.6137008", "0.6136016", "0.61185735", "0.61001694", "0.61001694", "0.61001694", "0.6097649", "0.6088225", "0.6072649", "0.6067571", "0.60461086", "0.6032182", "0.60007787", "0.60007787", "0.5998027", "0.5989043", "0.5951985", "0.5926464", "0.5915361", "0.59091073", "0.5894377", "0.588681", "0.58543205", "0.57887584", "0.57887584", "0.57887584", "0.57887584", "0.5788708", "0.57634926", "0.5762116", "0.57549167", "0.5753146", "0.57475424", "0.5742603", "0.57306504", "0.57018024", "0.5695497", "0.5689225", "0.56892157", "0.5688489", "0.56852686", "0.5678912", "0.56781375", "0.5674129", "0.5671522", "0.5670046", "0.5643914", "0.5639378", "0.5628438", "0.5618103", "0.56037045", "0.5600728", "0.55958503", "0.55918926", "0.5590838", "0.5588975", "0.55832815", "0.55724037", "0.5552165", "0.5541042", "0.5535167" ]
0.82562107
0
Turns text +input+ into a stream of tokens
def tokenize input s = StringScanner.new input @line = 0 @line_pos = 0 until s.eos? do pos = s.pos @tokens << case when s.scan(/\r?\n/) then token = [:NEWLINE, s.matched, *token_pos(pos)] @line_pos = s.pos @line += 1 token when s.scan(/ +/) then [:INDENT, s.matched_size, *token_pos(pos)] when s.scan(/(=+)\s*/) then level = s[1].length level = 6 if level > 6 @tokens << [:HEADER, level, *token_pos(pos)] pos = s.pos s.scan(/.*/) [:TEXT, s.matched, *token_pos(pos)] when s.scan(/^(-{3,}) *$/) then [:RULE, s[1].length - 2, *token_pos(pos)] when s.scan(/([*-])\s+/) then @tokens << [:BULLET, :BULLET, *token_pos(pos)] [:SPACE, s.matched_size, *token_pos(pos)] when s.scan(/([a-z]|\d+)\.[ \t]+\S/i) then list_label = s[1] width = s.matched_size - 1 s.pos -= 1 # unget \S list_type = case list_label when /[a-z]/ then :LALPHA when /[A-Z]/ then :UALPHA when /\d/ then :NUMBER else raise ParseError, "BUG token #{list_label}" end @tokens << [list_type, list_label, *token_pos(pos)] [:SPACE, width, *token_pos(pos)] when s.scan(/\[(.*?)\]( +|$)/) then @tokens << [:LABEL, s[1], *token_pos(pos)] [:SPACE, s.matched_size, *token_pos(pos)] when s.scan(/(.*?)::( +|$)/) then @tokens << [:NOTE, s[1], *token_pos(pos)] [:SPACE, s.matched_size, *token_pos(pos)] else s.scan(/.*/) [:TEXT, s.matched, *token_pos(pos)] end end self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tokens\n @tokens ||= scanner.tokenize(input)\n end", "def process(input_stream)\n debug 'Beginning tokenization of input'\n\n @stream = input_stream\n @stream_char = 1\n\n @output = [] if @state == :root\n\n until @stream.strip.empty?\n tk = tokenize\n @output.append(tk) if tk.instance_of? Token\n end\n\n @output\n end", "def lex(input)\n input = input.clone\n tokens = []\n\n until input.empty? do\n input.sub!(NEXT_TOKEN, '') || fail(Error, \"Can't lex input here '#{input}'\")\n\n tokens.push($1)\n end\n tokens\n end", "def tokens\n @tokens ||= tokenize_input\n end", "def tokenize_input\n token_list = []\n standardize_input\n tokenized_input = Tokens.new\n @user_input.scan(/\\S/).each do |token|\n case\n when token =~ /[A-Z]/\n tokenized_input << Token.new(:proposition, token.to_sym)\n when token =~ /[x\\!\\|\\&\\+\\>]/\n tokenized_input << Token.new(token.to_sym)\n when token =~ /[\\(]/\n tokenized_input << Token.new(:lparen)\n when token =~ /[\\)]/\n tokenized_input << Token.new(:rparen)\n when token =~ /[\\,]/\n tokenized_input << Token.new(:comma)\n else raise \"Unexpected token: #{token}\"\n end\n end\n tokenized_input\n end", "def tokenize ; end", "def tokenize ; end", "def tokenize\n \n end", "def tokenize; end", "def tokenize; end", "def tokenize\n @s.reset\n\n tokens = []\n\n while token = consume\n tokens << token\n end\n\n tokens\n end", "def tokenize\n @s.reset\n\n tokens = []\n\n while token = consume\n tokens << token\n end\n\n tokens\n end", "def convert_to tokens\r\n join( tokens.map{|t| process(t.to_s) })\r\n end", "def tokenize input\n setup_scanner input\n\n until @s.eos? do\n pos = @s.pos\n\n # leading spaces will be reflected by the column of the next token\n # the only thing we loose are trailing spaces at the end of the file\n next if @s.scan(/ +/)\n\n # note: after BULLET, LABEL, etc.,\n # indent will be the column of the next non-newline token\n\n @tokens << case\n # [CR]LF => :NEWLINE\n when @s.scan(/\\r?\\n/) then\n token = [:NEWLINE, @s.matched, *pos]\n @s.newline!\n token\n # === text => :HEADER then :TEXT\n when @s.scan(/(=+)(\\s*)/) then\n level = @s[1].length\n header = [:HEADER, level, *pos]\n\n if @s[2] =~ /^\\r?\\n/ then\n @s.unscan(@s[2])\n header\n else\n pos = @s.pos\n @s.scan(/.*/)\n @tokens << header\n [:TEXT, @s.matched.sub(/\\r$/, ''), *pos]\n end\n # --- (at least 3) and nothing else on the line => :RULE\n when @s.scan(/(-{3,}) *\\r?$/) then\n [:RULE, @s[1].length - 2, *pos]\n # * or - followed by white space and text => :BULLET\n when @s.scan(/([*-]) +(\\S)/) then\n @s.unscan(@s[2])\n [:BULLET, @s[1], *pos]\n # A. text, a. text, 12. text => :UALPHA, :LALPHA, :NUMBER\n when @s.scan(/([a-z]|\\d+)\\. +(\\S)/i) then\n # FIXME if tab(s), the column will be wrong\n # either support tabs everywhere by first expanding them to\n # spaces, or assume that they will have been replaced\n # before (and provide a check for that at least in debug\n # mode)\n list_label = @s[1]\n @s.unscan(@s[2])\n list_type =\n case list_label\n when /[a-z]/ then :LALPHA\n when /[A-Z]/ then :UALPHA\n when /\\d/ then :NUMBER\n else\n raise ParseError, \"BUG token #{list_label}\"\n end\n [list_type, list_label, *pos]\n # [text] followed by spaces or end of line => :LABEL\n when @s.scan(/\\[(.*?)\\]( +|\\r?$)/) then\n [:LABEL, @s[1], *pos]\n # text:: followed by spaces or end of line => :NOTE\n when @s.scan(/(.*?)::( +|\\r?$)/) then\n [:NOTE, @s[1], *pos]\n # >>> followed by end of line => :BLOCKQUOTE\n when @s.scan(/>>> *(\\w+)?$/) then\n [:BLOCKQUOTE, @s[1], *pos]\n # anything else: :TEXT\n else\n @s.scan(/(.*?)( )?\\r?$/)\n token = [:TEXT, @s[1], *pos]\n\n if @s[2] then\n @tokens << token\n [:BREAK, @s[2], pos[0] + @s[1].length, pos[1]]\n else\n token\n end\n end\n end\n\n self\n end", "def lexer(input)\n\t# We're gonna run a nice Lexer now\n\t# Get ourselves some tokens\n\t\n\ttokens = [] # Startin' with the input code in a mighty nice array\n\tc_line = 0 # current line in program\n\tspecial_case = false\n\teof_reached = false\n\t\n\tc_string = \"\"\t# the current string of chars\n\tc_pos = 1\t\t# current position in file\n\ts_pos = nil \t# current position of string\n\t\n\t# get a line of input\n\tfor line in input\n\t\t\n\t\t# check characters in line of input\n\t\tfor i in 0...line.length\n\t\t\n\t\t\t# checks for special cases\n\t\t\tif special_case\n\t\t\t\t\n\t\t\t\tlast_token = tokens[tokens.length - 1].type\n\t\t\t\t\n\t\t\t\t# Boolop\n\t\t\t\tif last_token == \"T_BOOLOP\"\n\t\t\t\t\t\n\t\t\t\t\tspecial_case = false\n\t\t\t\t\tnext\n\t\t\t\t\n\t\t\t\t# String time!\n\t\t\t\telsif last_token == \"T_QUOTE\"\n\t\t\t\t\n\t\t\t\t\t# make sure that we're not going to be using nil for tokenize\n\t\t\t\t\tif s_pos == nil\n\t\t\t\t\t\ts_pos = i\n\t\t\t\t\tend\n\t\t\t\n\t\t\t\t\t# check the different options\n\t\t\t\t\tcase line[i]\n\t\t\t\t\n\t\t\t\t\t# found a closing quotation mark\n\t\t\t\t\twhen /\"/\n\t\t\t\t\t\ttokens.push(tokenize(c_string, \"string\", c_line, s_pos))\n\t\t\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\t\t\tc_string = \"\"\n\t\t\t\t\t\tspecial_case = false\n\t\t\t\t\t\n\t\t\t\t\t# space or letter\n\t\t\t\t\twhen /( )/, $character\n\t\t\t\t\t\tc_string = c_string + line[i]\n\t\t\t\t\t\n\t\t\t\t\t# invalid options\n\t\t\t\t\telse\n\t\t\t\t\t\n\t\t\t\t\t\t# checks for end of line, else it's a bad character\n\t\t\t\t\t\tif i == line.length - 1\n\t\t\t\t\t\t\traise StringDetectionError.new(\"unclosed\", line[i], c_line, i)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\traise StringDetectionError.new(\"char\", line[i], c_line, i)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\n\t\t\n\t\t\t# test here for EOF symbol\n\t\t\telsif $eof.match(line[i])\n\t\t\t\t\n\t\t\t\t# tokenize current string\n\t\t\t\tif c_string != \"\"\n\t\t\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\t\t\t\t\n\t\t\t\t\tc_string = \"\"\n\t\t\t\t\ts_pos = nil\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\teof_reached = true\n\t\t\t\t\n\t\t\t\t# tokenize '$'\n\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\t\n\t\t\t# Testin' for whitespace\n\t\t\telsif $space.match(line[i])\n\t\t\t\n\t\t\t\tif c_string != \"\"\n\t\t\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\t\t\t\t\n\t\t\t\t\tc_string = \"\"\n\t\t\t\t\ts_pos = nil\n\t\t\t\tend\n\t\t\t\n\t\t\t# Testin' for operators\n\t\t\t# note: the whitespace issue was handled with the previous elsif\n\t\t\telsif $operator.match(line[i])\n\t\t\t\n\t\t\t\t# tokenize c_string if applicable\n\t\t\t\tif c_string != \"\"\n\t\t\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\t\t\t\t\n\t\t\t\t\tc_string = \"\"\n\t\t\t\t\ts_pos = nil\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# test for that elusive boolop...\n\t\t\t\t# make sure we don't access a non-existent item...\n\t\t\t\tif i != line.length - 1\n\t\t\t\t\tif /[!|=]/.match(line[i]) and /=/.match(line[i + 1])\n\t\t\t\t\t\t# attempt to tokenize the operator\n\t\t\t\t\t\ttokens.push(tokenize(line[i] + line[i + 1], \"op\", c_line, i))\n\t\t\t\t\t\tspecial_case = true\n\t\t\t\t\telse\n\t\t\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# if op is \", start the string gathering process\n\t\t\t\tif /\"/.match(line[i])\n\t\t\t\t\tspecial_case = true\n\t\t\t\tend\n\t\t\t\t\n\t\t\t# Testin' for alpha numeric characters\n\t\t\telsif $character.match(line[i])\n\t\t\t\n\t\t\t\t# set position of current string\n\t\t\t\tif c_string == \"\" and s_pos == nil\n\t\t\t\t\ts_pos = c_pos\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# add new character to current string\n\t\t\t\tc_string = c_string + String(line[i])\n\t\t\t\t\n\t\t\telsif $digit.match(line[i])\n\t\t\t\n\t\t\t\t# test for more than one digit\n\t\t\t\t# make sure we don't access a non-existent item...\n\t\t\t\tif i != line.length - 1\n\t\t\t\t\tif $digit.match(line[i + 1])\n\t\t\t\t\t\traise UnknownSymbolError.new(line[i + 1], c_line, c_pos + 1)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\ttokens.push(tokenize(line[i], \"digit\", c_line, i))\n\t\t\t\n\t\t\t# else raise error for unknown symbol\n\t\t\telse\n\t\t\t\tif s_pos != nil\n\t\t\t\t\traise UnknownSymbolError.new(line[i], c_line, s_pos)\n\t\t\t\telse\n\t\t\t\t\traise UnknownSymbolError.new(line[i], c_line, c_pos)\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\t# update current position\n\t\t\tc_pos = update_cpos(c_pos, line[i])\n\n\t\tend\n\t\t\n\t\t\n\t\t# check for loose ends\n\t\tif special_case\n\t\t\n\t\t\t# check to make sure that all strings on this line are finished\n\t\t\tif tokens[tokens.length - 1] == \"T_QUOTE\" or tokens[tokens.length - 1] == \"T_STRING\"\n\t\t\t\traise StringDetectionError.new(\"unclosed\", \"\", c_line, 0)\n\t\t\t\n\t\t\t# if boolop, reset special_case\n\t\t\telsif tokens[tokens.length - 1] == \"T_BOOLOP\"\n\t\t\t\tspecial_case = false\n\t\t\tend\n\t\t\n\t\tend\n\t\t\n\t\t# check to make sure no current strings are left\n\t\tif c_string != \"\"\n\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\tend\n\t\t\n\t\t# reset for next line\n\t\tc_string = \"\"\n\t\tc_pos = 0\n\t\ts_pos = nil\n\t\t\n\t\t# increment the line number\n\t\tc_line = c_line + 1\n\tend\n\t\n\t# if no EOF symbol ($) detected\n\tif !eof_reached\n\t\tbegin\n\t\t\traise EOFDetectionError.new(\"dne\", 0, 0)\n\t\trescue EOFDetectionError\n\t\t\ttokens.push(tokenize(\"$\", \"op\", c_line, 0))\n\t\tend\n\tend\n\t\n\t# return token list\n\treturn tokens\n\t\nend", "def stream(input)\n rest = input\n a = []\n loop do\n token, value, new_rest = lex(rest)\n a << [token, value]\n break if [:end, :open, :error].include?(token)\n raise \"software errror: infinite loop on input: #{rest}\" if new_rest == rest\n rest = new_rest\n end\n a\n end", "def process(input)\n\n str = convert(input)\n # Sanitize strings.\n str = sanitize(str)\n # Mark the beginning of the text.\n if not @inside_input\n str = \"#{BEGIN_MARKER}\\n#{str}\\n\"\n @inside_input = true\n else\n str = str + \"\\n\"\n end\n @mutex.synchronize { @enqueued_tokens += 1 }\n @pipe.print(str)\n end", "def token_stream(*args)\n args.map do |value|\n type = type_for(value)\n Dentaku::Token.new(type, value)\n end\nend", "def base_tokenize(text) #:nodoc:\n text.split(' ').map { |word| Token.new(word) }\n end", "def base_tokenize(text) #:nodoc:\n text.split(' ').map { |word| Token.new(word) }\n end", "def tokens\n @tokens ||= Tokeniser.instance.tokenise(text)\n end", "def tokens(input_string)\n token_strings = input_string.split(\" \")\n token_strings.map do |element|\n puts element\n if ['+', '-', '*', '/'].include? element\n case element\n when \"+\"\n :+\n when \"-\"\n :-\n when \"*\"\n :*\n when \"/\"\n :/\n end\n else\n element.to_i\n end\n end\n end", "def tokenize(source = T.unsafe(nil), options = T.unsafe(nil)); end", "def st_lex(raw)\n @tokens = raw.delete(' ').gsub(\"\\n\", '')\n end", "def text_token(text, kind); end", "def text_token(text, kind); end", "def tokenize\n\t\tout_tokens = Array.new\n\t\t\n\t\t@token_offset = 0\n\t\tuntil @token_offset >= (self.length - 1)\n\t\t\tout_tokens << next_token\n\t\tend\n\t\t\n\t\tout_tokens.reject {|token| token.empty? }\n\tend", "def tokenize input\n\n\t# Different regex parts for smiley faces\n\teyes = \"[8:=;]\"\n\tnose = \"['`\\-]?\"\n\n\tinput = input\n\t\t.gsub(/https?:\\/\\/\\S+\\b|www\\.(\\w+\\.)+\\S*/,\"<URL>\")\n\t\t.gsub(\"/\",\" / \") # Force splitting words appended with slashes (once we tokenized the URLs, of course)\n\t\t.gsub(/@\\w+/, \"<USER>\")\n\t\t.gsub(/#{eyes}#{nose}[)d]+|[)d]+#{nose}#{eyes}/i, \"<SMILE>\")\n\t\t.gsub(/#{eyes}#{nose}p+/i, \"<LOLFACE>\")\n\t\t.gsub(/#{eyes}#{nose}\\(+|\\)+#{nose}#{eyes}/, \"<SADFACE>\")\n\t\t.gsub(/#{eyes}#{nose}[\\/|l*]/, \"<NEUTRALFACE>\")\n\t\t.gsub(/<3/,\"<HEART>\")\n\t\t.gsub(/[-+]?[.\\d]*[\\d]+[:,.\\d]*/, \"<NUMBER>\")\n\t\t.gsub(/#\\S+/){ |hashtag| # Split hashtags on uppercase letters\n\t\t\t# TODO: also split hashtags with lowercase letters (requires more work to detect splits...)\n\n\t\t\thashtag_body = hashtag[1..-1]\n\t\t\tif hashtag_body.upcase == hashtag_body\n\t\t\t\tresult = \"<HASHTAG> #{hashtag_body} <ALLCAPS>\"\n\t\t\telse\n\t\t\t\tresult = ([\"<HASHTAG>\"] + hashtag_body.split(/(?=[A-Z])/)).join(\" \")\n\t\t\tend\n\t\t\tresult\n\t\t} \n\t\t.gsub(/([!?.]){2,}/){ # Mark punctuation repetitions (eg. \"!!!\" => \"! <REPEAT>\")\n\t\t\t\"#{$~[1]} <REPEAT>\"\n\t\t}\n\t\t.gsub(/\\b(\\S*?)(.)\\2{2,}\\b/){ # Mark elongated words (eg. \"wayyyy\" => \"way <ELONG>\")\n\t\t\t# TODO: determine if the end letter should be repeated once or twice (use lexicon/dict)\n\t\t\t$~[1] + $~[2] + \" <ELONG>\"\n\t\t}\n\t\t.gsub(/([^a-z0-9()<>'`\\-]){2,}/){ |word|\n\t\t\t\"#{word.downcase} <ALLCAPS>\"\n\t\t}\n\n\treturn input\nend", "def tokenize\n return consume_string if @state == :string\n\n trim_stream\n\n # Check if we're dealing with a keyword!\n return create_token(:keyword, consume_pattern(KEYWORD_DEF)) unless @stream.match(KEYWORD_DEF).nil?\n\n # Now we must check to see what else we could be finding. Remember whatever we\n # encounter here is the *start* of whatever token it is; a \" character here means\n # the start of a string..\n if @stream[0].match STRING_START_DEF\n @state = :string\n @partial_string['delimiter'] = @stream[0]\n consume\n\n return nil\n end\n\n return create_token(:terminator, consume) if @stream[0] == ';'\n return create_token(:operator, consume) if @stream[0] == '+'\n\n return create_token(:name, consume_pattern(NAME_DEF)) unless @stream.match(NAME_DEF).nil?\n\n raise_tokenizer_error \"Illegal character '#{@stream[0]}' - unable to form a token with this character!\"\n end", "def tokens!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 59)\n\n type = TOKENS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 596:4: 'tokens' WS_LOOP '{'\n match(\"tokens\")\n ws_loop!\n match(?{)\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 59)\n\n end", "def tokenize\n post(\"token\")[\"token\"]\n end", "def parse_input(input)\n\tinput.split(\" \")\nend", "def lex(input)\n line = 1\n offset = 0\n ending = input.length\n\n until offset == ending do\n next_token(input, offset, line).tap do |token|\n raise UnconsumedInputError,\n \"Unmatched input #{input[offset..-1].inspect} on line #{line}\" if token.nil?\n\n token[:offset] = offset\n line, token[:line] = token[:line], line\n offset += token[:value].length\n yield token unless token[:discarded]\n end\n end\n\n yield ({ :name => :$end, :line => line, :value => nil, :offset => offset })\n end", "def scan_tokens(encoder, options); end", "def scan_tokens(encoder, options); end", "def tokenize\n for c in @code.split(\" \").map(&:to_s)\n $tokens << getToken\n @code = @code.strip\n end\n $tokens\n end", "def scan_tokens(tokens, options); end", "def parse(input)\n # Save for error msgs\n @input = input.clone\n @tokens = lex(input)\n @rpn = parse_expr\n\n assert_eos\n\n self\n end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokenize(content, ptype = T.unsafe(nil)); end", "def tokenize(in_name) \n\t\tmulti_line = false\n\t\t@in_file = File.new(in_name, \"r\");\n\t\tout_name = in_name.gsub /.jack$/, \"Tgen.xml\"\n\t\t@out_file = File.new(out_name,\"w\")\n\t\t@out_file.puts \"<tokens>\"\t\t\n\t\tfor i in @in_file #none of these regexes are readable or debugable, never again\n\t\t\ti.gsub! %r!/\\*.*\\*/!, '' #incase a multiline format is only used for a single line after code on same line\n\t\t\tif multi_line\n\t\t\t\t#p \"de #{i}\"\n\t\t\t\tnext unless i.match %r!\\*/!\n\t\t\t\ti.gsub! %r!.*\\*/!, ''\n\t\t\t\tmulti_line = false\n\t\t\tend\n\t\t\t\n\t\t\tif i.match %r!/\\*!\n\t\t\t\t#p \"re #{i}\"\n\t\t\t\ti.gsub! %r!/\\*.*!, ''\n\t\t\t\tmulti_line = true\n\t\t\tend\n\t\t\t\n\t\t\t# hahahahaha %r!! makes finding comments easier because it looks neater and is eaiser to read\n\t\t\ti.gsub! %r!//.*!, ''\n\t\t\ti.gsub! /(\\{|\\}|\\(|\\)|\\[|\\]|\\.|,|;|\\+|-|\\*|\\/|&|\\||<|>|=|~)/, ' \\1 '\n\t\t\t#p i\n\t\t\ti.strip! #ba chica wa wa\n\t\t\ti.scan /\\S+/ do |j|\n\t\t\t\ttype = token_type j\n\t\t\t\tj.gsub! /&/, '&amp;'\n\t\t\t\tj.gsub! /\"/, ''\n\t\t\t\tj.gsub! />/, '&gt;'\n\t\t\t\tj.gsub! /</, '&lt;'\n\t\t\t\twrite_toke type, j\n\t\t\tend\n\t\tend\n\n\t\t@out_file.puts \"</tokens>\"\t\t\n\t\t#SHould always close even if it is done at program's terminations\n\t\t@in_file.close() \n\t\t@out_file.close()\n\tend", "def parse (input)\n\t\treturn parse_tail(input.gsub('(', ' ( ').gsub(')', ' ) ').split)\n\tend", "def token(content, kind); end", "def tokenize\n @stack = [ TokenList.new ]\n @num_open_brackets = 0\n @token_buffer = nil\n until content.eos?\n if @num_open_brackets > 0\n _build_token_list_inside_sub\n else\n _build_token_list_outside_sub\n end\n end\n _flush_token_buffer\n _flush_stack\n\n @tokens = @stack.first\n end", "def parse(text)\n text = pre_proccess(text)\n text = pre_normalize(text)\n puts text.inspect if Chronic.debug\n\n tokens = Tokenizer::tokenize(' ' + text + ' ')\n tag(tokens, options)\n\n puts \"+#{'-' * 51}\\n| #{tokens}\\n+#{'-' * 51}\" if Chronic.debug\n\n token_group = TokenGroup.new(tokens, definitions(options), @now, options)\n span = token_group.to_span\n\n guess(span, options[:guess]) if span\n end", "def initialize(input)\n initialize__antlrstring_stream()\n @data = input.to_char_array\n @n = input.length\n end", "def parse(input)\n norm = self.class.normalize(input)\n paragraphs = split_paragraphs(input)\n result = []\n for paragraph in paragraphs do\n result << parse_paragraph(paragraph)\n end \n return result\n end", "def parse(program)\n return read_the_tokens(tokenize(program))\nend", "def tokenize\n return [] if unencoded_text.blank?\n # kill off all punctuation except [stuff]'s or [stuff]'t\n # this includes hyphens (words are split)\n str = unencoded_text.\n downcase.\n gsub(/[^a-zA-Z0-9\\']+/, ' ').\n gsub(/(\\w)\\'([st])\\b/, '\\1!\\2').gsub(/\\'/, ' ').gsub(/!/, \"'\")\n # Busticate at whitespace\n words = str.strip.split(/\\s+/)\n words.reject!{|w| w.length < 3 }\n words.map!{|w| Wukong::encode_str(w) }\n end", "def scan_for_t(token); end", "def tokenizer(aTextToParse)\n offset = -1\n tokens = aTextToParse.scan(/\\S+/).map do |word|\n term_name = Lexicon[word]\n raise StandardError, \"Word '#{word}' not found in lexicon\" if term_name.nil?\n\n pos = Rley::Lexical::Position.new(1, offset + 1)\n offset += word.length\n Rley::Lexical::Token.new(word, term_name, pos)\n end\n\n return tokens\nend", "def makeTokens(line)\n # print(line)\n tokens=line.split(/(\\W)/).select { |s| s != '' } #scan(/\\W|[\\w.]+/).select { |s| s != \" \" }\n # print(\"Tokens: \")\n # puts(tokens.length)\n \n #handle negative numbers \n i = 0 \n j = i+1\n length = tokens.length \n while i < length \n if ( tokens[i]==\"-\" or tokens[i]==\"(\" or tokens[i]==\"+\") and tokens[j]==\"-\" \n tokens[j+1]=\"-\"+tokens[j+1] #merge minus with the next token\n tokens[j]=nil #setup space \n end\n i+=1\n j+=1\n end\n tokens = tokens.compact #remove spaces \n # print(tokens)\n # puts\n return tokens\nend", "def convert_buffer_to_token(token_type); end", "def tokenize\n # Array to contain all tokens.\n tokenArray = []\n # While getChar returns anything other than \"\"\n while getChar\n # Loop to next character until not a space.\n while charIsWhitespace\n nextChar\n end\n # Breaks if it hits the dreaded empty string.\n if getChar.nil?\n break\n end\n # If character is a letter.\n if(charIsAlpha) \n # Initialize local variables for scope.\n m = \"\"\n line = @line\n column = @column \n # While character is letter or number or underscore,\n # add to string \"m\" current character.\n while(charIsAlpha or charIsDigit or getChar == '_')\n m += getChar\n nextChar\n end\n # If the keywords include \"m\" string in hash array,\n # add to tokenArray a new token with the keywords having \"m\" as an index key,\n # its column and line as well for future use and debugging.\n if(Tokens::KEYWORDS.include?(m))\n tokenArray.push Token.new(Tokens::KEYWORDS[m], m, column, line)\n # Must be identifier, add to array as identifier.\n else\n tokenArray.push Token.new(Tokens::IDENT, m, column, line)\n end\n # If the current character is a number.\n elsif(charIsDigit)\n # Initialize local variables for scope.\n m = \"\"\n line = @line\n column = @column\n # Bool is for exception checking on periods. Most likely will be removed,\n # have yet to decide on ranges.\n dot = false\n # While char is number or period,\n while(charIsDigit or getChar == '.')\n # if period\n if(getChar == '.')\n # if dot is true\n if(dot)\n # Create exception class message.\n TokenizerException.new(column, line, \"Number literal contains too many dots.\")\n end\n # Sets flag for second dot if it happens before leaving scope.\n dot = true\n end\n # String adds new character and increments\n m += getChar\n nextChar\n end\n # Token complete, push token as number into tokenArray\n tokenArray.push Token.new(Tokens::NUMBER, m, column, line)\n # Current character doesn't fit into letter or number parameters.\n else\n # More instance variables\n column = @column\n line = @line\n # Starts off by saying this is a character, then moving to the next to check.\n m = getChar\n nextChar\n # While the string is in the operators add and increment character.\n while(Tokens::OPERATORS.include?(m))\n m += getChar if !getChar.nil?\n m += \" \" if getChar.nil?\n nextChar\n end\n # Jump back to the last character\n prevChar()\n # Take of the last character.\n m = m.slice(0, m.size - 1)\n # Pushes another token into the array.\n tokenArray.push Token.new(Tokens::OPERATORS[m], m, column, line)\n end\n end\n return tokenArray\n end", "def tokenize(doc, h)\n begin\n PlanR::TokenStream.from_array(name, doc, \n doc.plaintext_ascii.split(/\\s/) )\n rescue Exception => e\n # FIXME: log\n $stderr.puts \"[PLAINTEXT PARSER] ERROR: #{e.message}\"\n $stderr.puts e.backtrace[0,4].join(\"\\n\")\n # FIXME: better default return value\n PlanR::TokenStream.from_array(name, doc, [])\n end\n end", "def preprocess(input); end", "def token!\n # at line 1:8: ( T__8 | T__9 | T__10 | T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | DIGIT | WS | EOL | LETTER )\n alt_3 = 40\n alt_3 = @dfa3.predict( @input )\n case alt_3\n when 1\n # at line 1:10: T__8\n t__8!\n\n when 2\n # at line 1:15: T__9\n t__9!\n\n when 3\n # at line 1:20: T__10\n t__10!\n\n when 4\n # at line 1:26: T__11\n t__11!\n\n when 5\n # at line 1:32: T__12\n t__12!\n\n when 6\n # at line 1:38: T__13\n t__13!\n\n when 7\n # at line 1:44: T__14\n t__14!\n\n when 8\n # at line 1:50: T__15\n t__15!\n\n when 9\n # at line 1:56: T__16\n t__16!\n\n when 10\n # at line 1:62: T__17\n t__17!\n\n when 11\n # at line 1:68: T__18\n t__18!\n\n when 12\n # at line 1:74: T__19\n t__19!\n\n when 13\n # at line 1:80: T__20\n t__20!\n\n when 14\n # at line 1:86: T__21\n t__21!\n\n when 15\n # at line 1:92: T__22\n t__22!\n\n when 16\n # at line 1:98: T__23\n t__23!\n\n when 17\n # at line 1:104: T__24\n t__24!\n\n when 18\n # at line 1:110: T__25\n t__25!\n\n when 19\n # at line 1:116: T__26\n t__26!\n\n when 20\n # at line 1:122: T__27\n t__27!\n\n when 21\n # at line 1:128: T__28\n t__28!\n\n when 22\n # at line 1:134: T__29\n t__29!\n\n when 23\n # at line 1:140: T__30\n t__30!\n\n when 24\n # at line 1:146: T__31\n t__31!\n\n when 25\n # at line 1:152: T__32\n t__32!\n\n when 26\n # at line 1:158: T__33\n t__33!\n\n when 27\n # at line 1:164: T__34\n t__34!\n\n when 28\n # at line 1:170: T__35\n t__35!\n\n when 29\n # at line 1:176: T__36\n t__36!\n\n when 30\n # at line 1:182: T__37\n t__37!\n\n when 31\n # at line 1:188: T__38\n t__38!\n\n when 32\n # at line 1:194: T__39\n t__39!\n\n when 33\n # at line 1:200: T__40\n t__40!\n\n when 34\n # at line 1:206: T__41\n t__41!\n\n when 35\n # at line 1:212: T__42\n t__42!\n\n when 36\n # at line 1:218: T__43\n t__43!\n\n when 37\n # at line 1:224: DIGIT\n digit!\n\n when 38\n # at line 1:230: WS\n ws!\n\n when 39\n # at line 1:233: EOL\n eol!\n\n when 40\n # at line 1:237: LETTER\n letter!\n\n end\n end", "def parse\n tagify(decommentify(@input)).strip\n end", "def tokenize(string)\n @tokens = scanner.operate(tag_prefix, string)\n end", "def tokens(tokens, options = T.unsafe(nil)); end", "def tokenizer(aTextToParse)\n scanner = StringScanner.new(aTextToParse)\n tokens = []\n\n loop do\n scanner.skip(/\\s+/)\n curr_pos = scanner.pos\n word = scanner.scan(/\\S+/)\n break unless word\n\n term_name = Lexicon[word]\n raise StandardError, \"Word '#{word}' not found in lexicon\" if term_name.nil?\n\n pos = Rley::Lexical::Position.new(1, curr_pos + 1)\n tokens << Rley::Lexical::Token.new(word, term_name, pos)\n end\n\n return tokens\nend", "def tokenize\n if match = TOKENIZE_REGEXP.match(@string)\n pre = match.pre_match\n post = match.post_match\n tokens = match[1].split(TOKENIZE_SEPARATOR)\n tokens.each do |token|\n yield(self.class.new(\"#{pre}#{token}#{post}\"))\n end\n else\n yield(self.class.new(@string))\n end\n\n nil\n end", "def initialize(input)\r\n @length = input.length\r\n @input = input\r\n @p = 0\r\n @token = Token.new\r\n end", "def input_text\n with_input_io{|io| io.readlines.join}\n end", "def token_stream # :nodoc:\n end", "def token!\n # at line 1:8: ( T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | T__47 | T__48 | T__49 | T__50 | T__51 | T__52 | T__53 | T__54 | INTEGER | FLOAT | BOOLEAN | STRING | CHAR | INIT | OPEN | CLOSE | TYPE_INT | TYPE_FLOAT | TYPE_STRING | TYPE_BOOL | TYPE_VOID | ENTITY | COMPONENT | SYSTEM | ENUM | IF | ELSE | RETURN | WHILE | IDENT | WS | COMMENT | MULTILINE_COMMENT | NL )\n alt_9 = 51\n alt_9 = @dfa9.predict( @input )\n case alt_9\n when 1\n # at line 1:10: T__30\n t__30!\n\n\n when 2\n # at line 1:16: T__31\n t__31!\n\n\n when 3\n # at line 1:22: T__32\n t__32!\n\n\n when 4\n # at line 1:28: T__33\n t__33!\n\n\n when 5\n # at line 1:34: T__34\n t__34!\n\n\n when 6\n # at line 1:40: T__35\n t__35!\n\n\n when 7\n # at line 1:46: T__36\n t__36!\n\n\n when 8\n # at line 1:52: T__37\n t__37!\n\n\n when 9\n # at line 1:58: T__38\n t__38!\n\n\n when 10\n # at line 1:64: T__39\n t__39!\n\n\n when 11\n # at line 1:70: T__40\n t__40!\n\n\n when 12\n # at line 1:76: T__41\n t__41!\n\n\n when 13\n # at line 1:82: T__42\n t__42!\n\n\n when 14\n # at line 1:88: T__43\n t__43!\n\n\n when 15\n # at line 1:94: T__44\n t__44!\n\n\n when 16\n # at line 1:100: T__45\n t__45!\n\n\n when 17\n # at line 1:106: T__46\n t__46!\n\n\n when 18\n # at line 1:112: T__47\n t__47!\n\n\n when 19\n # at line 1:118: T__48\n t__48!\n\n\n when 20\n # at line 1:124: T__49\n t__49!\n\n\n when 21\n # at line 1:130: T__50\n t__50!\n\n\n when 22\n # at line 1:136: T__51\n t__51!\n\n\n when 23\n # at line 1:142: T__52\n t__52!\n\n\n when 24\n # at line 1:148: T__53\n t__53!\n\n\n when 25\n # at line 1:154: T__54\n t__54!\n\n\n when 26\n # at line 1:160: INTEGER\n integer!\n\n\n when 27\n # at line 1:168: FLOAT\n float!\n\n\n when 28\n # at line 1:174: BOOLEAN\n boolean!\n\n\n when 29\n # at line 1:182: STRING\n string!\n\n\n when 30\n # at line 1:189: CHAR\n char!\n\n\n when 31\n # at line 1:194: INIT\n init!\n\n\n when 32\n # at line 1:199: OPEN\n open!\n\n\n when 33\n # at line 1:204: CLOSE\n close!\n\n\n when 34\n # at line 1:210: TYPE_INT\n type_int!\n\n\n when 35\n # at line 1:219: TYPE_FLOAT\n type_float!\n\n\n when 36\n # at line 1:230: TYPE_STRING\n type_string!\n\n\n when 37\n # at line 1:242: TYPE_BOOL\n type_bool!\n\n\n when 38\n # at line 1:252: TYPE_VOID\n type_void!\n\n\n when 39\n # at line 1:262: ENTITY\n entity!\n\n\n when 40\n # at line 1:269: COMPONENT\n component!\n\n\n when 41\n # at line 1:279: SYSTEM\n system!\n\n\n when 42\n # at line 1:286: ENUM\n enum!\n\n\n when 43\n # at line 1:291: IF\n if!\n\n\n when 44\n # at line 1:294: ELSE\n else!\n\n\n when 45\n # at line 1:299: RETURN\n return!\n\n\n when 46\n # at line 1:306: WHILE\n while!\n\n\n when 47\n # at line 1:312: IDENT\n ident!\n\n\n when 48\n # at line 1:318: WS\n ws!\n\n\n when 49\n # at line 1:321: COMMENT\n comment!\n\n\n when 50\n # at line 1:329: MULTILINE_COMMENT\n multiline_comment!\n\n\n when 51\n # at line 1:347: NL\n nl!\n\n\n end\n end", "def token!\n # at line 1:8: ( T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | T__47 | T__48 | T__49 | T__50 | T__51 | T__52 | T__53 | T__54 | T__55 | T__56 | T__57 | T__58 | T__59 | ST | ND | RD | TH | DIGIT | WS | EOL | LETTER )\n alt_7 = 56\n alt_7 = @dfa7.predict( @input )\n case alt_7\n when 1\n # at line 1:10: T__12\n t__12!\n\n when 2\n # at line 1:16: T__13\n t__13!\n\n when 3\n # at line 1:22: T__14\n t__14!\n\n when 4\n # at line 1:28: T__15\n t__15!\n\n when 5\n # at line 1:34: T__16\n t__16!\n\n when 6\n # at line 1:40: T__17\n t__17!\n\n when 7\n # at line 1:46: T__18\n t__18!\n\n when 8\n # at line 1:52: T__19\n t__19!\n\n when 9\n # at line 1:58: T__20\n t__20!\n\n when 10\n # at line 1:64: T__21\n t__21!\n\n when 11\n # at line 1:70: T__22\n t__22!\n\n when 12\n # at line 1:76: T__23\n t__23!\n\n when 13\n # at line 1:82: T__24\n t__24!\n\n when 14\n # at line 1:88: T__25\n t__25!\n\n when 15\n # at line 1:94: T__26\n t__26!\n\n when 16\n # at line 1:100: T__27\n t__27!\n\n when 17\n # at line 1:106: T__28\n t__28!\n\n when 18\n # at line 1:112: T__29\n t__29!\n\n when 19\n # at line 1:118: T__30\n t__30!\n\n when 20\n # at line 1:124: T__31\n t__31!\n\n when 21\n # at line 1:130: T__32\n t__32!\n\n when 22\n # at line 1:136: T__33\n t__33!\n\n when 23\n # at line 1:142: T__34\n t__34!\n\n when 24\n # at line 1:148: T__35\n t__35!\n\n when 25\n # at line 1:154: T__36\n t__36!\n\n when 26\n # at line 1:160: T__37\n t__37!\n\n when 27\n # at line 1:166: T__38\n t__38!\n\n when 28\n # at line 1:172: T__39\n t__39!\n\n when 29\n # at line 1:178: T__40\n t__40!\n\n when 30\n # at line 1:184: T__41\n t__41!\n\n when 31\n # at line 1:190: T__42\n t__42!\n\n when 32\n # at line 1:196: T__43\n t__43!\n\n when 33\n # at line 1:202: T__44\n t__44!\n\n when 34\n # at line 1:208: T__45\n t__45!\n\n when 35\n # at line 1:214: T__46\n t__46!\n\n when 36\n # at line 1:220: T__47\n t__47!\n\n when 37\n # at line 1:226: T__48\n t__48!\n\n when 38\n # at line 1:232: T__49\n t__49!\n\n when 39\n # at line 1:238: T__50\n t__50!\n\n when 40\n # at line 1:244: T__51\n t__51!\n\n when 41\n # at line 1:250: T__52\n t__52!\n\n when 42\n # at line 1:256: T__53\n t__53!\n\n when 43\n # at line 1:262: T__54\n t__54!\n\n when 44\n # at line 1:268: T__55\n t__55!\n\n when 45\n # at line 1:274: T__56\n t__56!\n\n when 46\n # at line 1:280: T__57\n t__57!\n\n when 47\n # at line 1:286: T__58\n t__58!\n\n when 48\n # at line 1:292: T__59\n t__59!\n\n when 49\n # at line 1:298: ST\n st!\n\n when 50\n # at line 1:301: ND\n nd!\n\n when 51\n # at line 1:304: RD\n rd!\n\n when 52\n # at line 1:307: TH\n th!\n\n when 53\n # at line 1:310: DIGIT\n digit!\n\n when 54\n # at line 1:316: WS\n ws!\n\n when 55\n # at line 1:319: EOL\n eol!\n\n when 56\n # at line 1:323: LETTER\n letter!\n\n end\n end", "def start(raw)\n typ = Tokenizer::DEFAULT_TOKEN_TABLE\n letters = raw.dup.split(\"\")\n tokens = []\n\n while (ch = letters.shift) != nil\n tokens.push(typ[ch])\n end\n\n return tokens\n end", "def tokenize (p_token, type, lineno, pos)\n\t\n\tif type == \"op\"\n\t\treturn op_tokenize(p_token, lineno, pos)\n\t\n\telsif type == \"character\"\n\t\treturn char_tokenize(p_token, lineno, pos)\n\t\n\telsif type == \"string\"\n\t\treturn string_tokenize(p_token, lineno, pos)\n\t\n\telsif type == \"digit\"\n\t\treturn digit_tokenize(p_token, lineno, pos)\n\t\n\telse\n\t\t# should create an error here, just for thoroughness\n\tend\nend", "def tokenize text\r\n m = text.match(@regexp)\r\n return nil if m.nil?\r\n arguments = []\r\n b = @verb.nil? ? 0 : 1\r\n xverb = @verb\r\n @replace.to_s.split_words[b..-1].each { |r|\r\n if r.match(/^\\{\\$[0-9]+\\}$/)\r\n arguments.push m[r[2..-2].to_i]\r\n elsif arguments.empty? && xverb.nil?\r\n xverb = r.to_sym\r\n else\r\n arguments.push r\r\n end\r\n }\r\n Command.new xverb, arguments\r\n end", "def separate_by_spaces_and_parens(input)\n output = []\n input.each do |token|\n unless token.is_a? ::String\n output.push token\n next\n end\n token = token.gsub '(', ' ( '\n token = token.gsub ')', ' ) '\n token = token.split(' ')\n output += token\n end\n output\n end", "def tokenize # rubocop:disable Metrics/MethodLength\n if match = TOKENIZE_REGEXP.match(@string) # rubocop:disable Lint/AssignmentInCondition\n pre = match.pre_match\n post = match.post_match\n tokens = match[1].split(TOKENIZE_SEPARATOR)\n tokens.each do |token|\n yield(self.class.new(\"#{pre}#{token}#{post}\"))\n end\n else\n yield(self.class.new(@string))\n end\n\n nil\n end", "def token!\n # at line 1:8: ( STRING | SHELL_STRING | CMD_OUTPUT | SPACE | COMMAND_END | VARIABLE | GLOB | CHUNK | OPEN_PAR | CLOSE_PAR | PIPELINE_OPERATOR | REDIRECT | COMMENT )\n alt_25 = 13\n alt_25 = @dfa25.predict( @input )\n case alt_25\n when 1\n # at line 1:10: STRING\n string!\n\n when 2\n # at line 1:17: SHELL_STRING\n shell_string!\n\n when 3\n # at line 1:30: CMD_OUTPUT\n cmd_output!\n\n when 4\n # at line 1:41: SPACE\n space!\n\n when 5\n # at line 1:47: COMMAND_END\n command_end!\n\n when 6\n # at line 1:59: VARIABLE\n variable!\n\n when 7\n # at line 1:68: GLOB\n glob!\n\n when 8\n # at line 1:73: CHUNK\n chunk!\n\n when 9\n # at line 1:79: OPEN_PAR\n open_par!\n\n when 10\n # at line 1:88: CLOSE_PAR\n close_par!\n\n when 11\n # at line 1:98: PIPELINE_OPERATOR\n pipeline_operator!\n\n when 12\n # at line 1:116: REDIRECT\n redirect!\n\n when 13\n # at line 1:125: COMMENT\n comment!\n\n end\n end", "def lex(input)\n loop do\n token, value, rest = lex_comment(input)\n if :comment == token\n raise \"infinite loop on input: #{input}\" if input == rest\n input = rest\n else\n return token, value, rest\n end\n end\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when ss.skip(/\\s+/) then\n # do nothing\n when ss.skip(/:(#{SYMBOL_NAME})/o) then\n action { emit :tSYMBOL, &:to_sym }\n when ss.skip(/\"(.+?)\"/) then\n action { emit :tSTRING }\n when ss.skip(/[-+]?\\d+\\.\\d+/) then\n action { emit :tNUMBER, &:to_f }\n when ss.skip(/[-+]?\\d+/) then\n action { emit :tNUMBER, &:to_i }\n when ss.skip(/#{Regexp.union(\n %w\"( ) { | } [ ] < > $ ! ^ ` ... + * ? ,\"\n )}/o) then\n action { emit ss.matched, &:to_sym }\n when ss.skip(/#{REGEXP}/o) then\n action { emit_regexp }\n when ss.skip(/%?(#{CONST_NAME})/o) then\n action { emit :tPARAM_CONST }\n when ss.skip(/%([a-z_]+)/) then\n action { emit :tPARAM_NAMED }\n when ss.skip(/%(\\d*)/) then\n action { emit(:tPARAM_NUMBER) { |s| s.empty? ? 1 : s.to_i } } # Map `%` to `%1`\n when ss.skip(/_(#{IDENTIFIER})/o) then\n action { emit :tUNIFY }\n when ss.skip(/_/o) then\n action { emit :tWILDCARD }\n when ss.skip(/\\#(#{CALL})/o) then\n action { @state = :ARG; emit :tFUNCTION_CALL, &:to_sym }\n when ss.skip(/#{IDENTIFIER}\\?/o) then\n action { @state = :ARG; emit :tPREDICATE, &:to_sym }\n when ss.skip(/#{NODE_TYPE}/o) then\n action { emit :tNODE_TYPE, &:to_sym }\n when ss.skip(/\\#.*/) then\n action { emit_comment }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :ARG then\n case\n when ss.skip(/\\(/) then\n action { @state = nil; emit :tARG_LIST }\n when ss.skip(//) then\n action { @state = nil }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def tokens(string)\n\t\toperators = [\"+\", \"-\", \"*\", \"/\"]\n\t\tinputs = string.split ' '\n\t\ttokenized = inputs.collect do |input|\n\t\t\tif operators.include? input\n\t\t\t\tinput.to_sym\n\t\t\telse\n\t\t\t\tinput.to_i\n\t\t\tend\n\t\tend\n\t\ttokenized\n\tend", "def input\n STDIN.read.split(\"\\n\")\nend", "def token_inputs\n { :id => _id, :name => name }\n end", "def tokenize(data)\n return if data.nil?\n data = data.split(/\\W+/)\n if data.first == ''\n data = data.drop(1)\n end\n (0...data.size).each { |index|\n @total_words_counter += 1\n yield data[index] }\n end", "def do_parse\n while token = next_token do\n type, *vals = token\n\n send \"lex_#{type}\", *vals\n end\n end", "def create_token( text )\n return Scanner::Artifacts::Nodes::Token.new( text, nil, 0, 0, 0, nil )\n end", "def tokenizer(string)\n items = []\n while string.size > 0\n if TOKENS.keys.include?(string[0,1])\n end_index = string.index(TOKENS[string[0,1]], 1)\n raise \"bad end_index for #{string}\" if not end_index\n item = string[0..end_index]\n items << item\n string = string[end_index+1..-1]\n while item.count(item[0,1]) > item.count(TOKENS[item[0,1]])\n end_index = string.index(TOKENS[item[0,1]])\n item << string[0..end_index]\n string = string[end_index+1..-1]\n end\n else\n end_index = string.index(/([\\[({<&*#\"'^\\s]|\\z)/, 1)\n item = string[0..end_index-1].strip\n items << item if not item.empty?\n string = string[end_index..-1]\n end\n end\n items\n end", "def jitter_tokenizer(token)\n toReturn = []\n if (token[1] == \" \" && token[-2] == \" \")\n toReturn << token[0..0]\n toReturn << token[2..-3]\n toReturn << token[-1..-1]\n elsif token[1] == \" \"\n toReturn << token[0..0]\n toReturn << token[2..-1]\n elsif token[-2] == \" \"\n toReturn << token[0..-3]\n toReturn << token[-1..-1]\n else\n toReturn << token\n end\n toReturn\nend", "def token!\n # at line 1:8: ( T__80 | T__81 | T__82 | EOL | LPAR | RPAR | LLAIZQ | LLADER | COMA | PUNTO | CORDER | CORIZQ | DELIM | ASIGNACION | DOUBLEDOT | COMILLA | OP_REL | OP_ARI | OP_LOG | K_ACCIONARCHIVO | K_ACCIONARREGLO | K_PACKAGE | K_CLASS | K_END | K_DEF | K_VAR | K_REQUIRE | K_IMPLEMENTS | K_EXTENDS | K_IMPRIMIR | K_CONVERSION | K_ASIGNACION | K_RETORNO | K_ACCIONSYS | K_INTERFACE | K_IF | K_TIMES | K_DO | K_EACH | K_ELSE | K_INVOKE | K_NEW | TIPO | K_REFERENCIA | K_INSPECCIONAR | K_MATEMATICA | K_NUM | K_RESIZE | K_ORDENAR | ModoOrd | K_BUSQUEDA | K_TIPOBUSQUEDA | K_WHERE | K_SPLIT | K_BEGIN | K_DIR | K_UNION | K_VISIBILIDAD | K_MODIFICADOR | K_ARRAY | K_PROPIEDAD | K_GET | K_SET | K_VALUE | K_INITIALIZE | K_FUNC | K_VOID | HexLiteral | DecimalLiteral | OctalLiteral | WS | LINE_COMMENT | Identificador )\n alt_28 = 73\n alt_28 = @dfa28.predict( @input )\n case alt_28\n when 1\n # at line 1:10: T__80\n t__80!\n\n\n when 2\n # at line 1:16: T__81\n t__81!\n\n\n when 3\n # at line 1:22: T__82\n t__82!\n\n\n when 4\n # at line 1:28: EOL\n eol!\n\n\n when 5\n # at line 1:32: LPAR\n lpar!\n\n\n when 6\n # at line 1:37: RPAR\n rpar!\n\n\n when 7\n # at line 1:42: LLAIZQ\n llaizq!\n\n\n when 8\n # at line 1:49: LLADER\n llader!\n\n\n when 9\n # at line 1:56: COMA\n coma!\n\n\n when 10\n # at line 1:61: PUNTO\n punto!\n\n\n when 11\n # at line 1:67: CORDER\n corder!\n\n\n when 12\n # at line 1:74: CORIZQ\n corizq!\n\n\n when 13\n # at line 1:81: DELIM\n delim!\n\n\n when 14\n # at line 1:87: ASIGNACION\n asignacion!\n\n\n when 15\n # at line 1:98: DOUBLEDOT\n doubledot!\n\n\n when 16\n # at line 1:108: COMILLA\n comilla!\n\n\n when 17\n # at line 1:116: OP_REL\n op_rel!\n\n\n when 18\n # at line 1:123: OP_ARI\n op_ari!\n\n\n when 19\n # at line 1:130: OP_LOG\n op_log!\n\n\n when 20\n # at line 1:137: K_ACCIONARCHIVO\n k_accionarchivo!\n\n\n when 21\n # at line 1:153: K_ACCIONARREGLO\n k_accionarreglo!\n\n\n when 22\n # at line 1:169: K_PACKAGE\n k_package!\n\n\n when 23\n # at line 1:179: K_CLASS\n k_class!\n\n\n when 24\n # at line 1:187: K_END\n k_end!\n\n\n when 25\n # at line 1:193: K_DEF\n k_def!\n\n\n when 26\n # at line 1:199: K_VAR\n k_var!\n\n\n when 27\n # at line 1:205: K_REQUIRE\n k_require!\n\n\n when 28\n # at line 1:215: K_IMPLEMENTS\n k_implements!\n\n\n when 29\n # at line 1:228: K_EXTENDS\n k_extends!\n\n\n when 30\n # at line 1:238: K_IMPRIMIR\n k_imprimir!\n\n\n when 31\n # at line 1:249: K_CONVERSION\n k_conversion!\n\n\n when 32\n # at line 1:262: K_ASIGNACION\n k_asignacion!\n\n\n when 33\n # at line 1:275: K_RETORNO\n k_retorno!\n\n\n when 34\n # at line 1:285: K_ACCIONSYS\n k_accionsys!\n\n\n when 35\n # at line 1:297: K_INTERFACE\n k_interface!\n\n\n when 36\n # at line 1:309: K_IF\n k_if!\n\n\n when 37\n # at line 1:314: K_TIMES\n k_times!\n\n\n when 38\n # at line 1:322: K_DO\n k_do!\n\n\n when 39\n # at line 1:327: K_EACH\n k_each!\n\n\n when 40\n # at line 1:334: K_ELSE\n k_else!\n\n\n when 41\n # at line 1:341: K_INVOKE\n k_invoke!\n\n\n when 42\n # at line 1:350: K_NEW\n k_new!\n\n\n when 43\n # at line 1:356: TIPO\n tipo!\n\n\n when 44\n # at line 1:361: K_REFERENCIA\n k_referencia!\n\n\n when 45\n # at line 1:374: K_INSPECCIONAR\n k_inspeccionar!\n\n\n when 46\n # at line 1:389: K_MATEMATICA\n k_matematica!\n\n\n when 47\n # at line 1:402: K_NUM\n k_num!\n\n\n when 48\n # at line 1:408: K_RESIZE\n k_resize!\n\n\n when 49\n # at line 1:417: K_ORDENAR\n k_ordenar!\n\n\n when 50\n # at line 1:427: ModoOrd\n modo_ord!\n\n\n when 51\n # at line 1:435: K_BUSQUEDA\n k_busqueda!\n\n\n when 52\n # at line 1:446: K_TIPOBUSQUEDA\n k_tipobusqueda!\n\n\n when 53\n # at line 1:461: K_WHERE\n k_where!\n\n\n when 54\n # at line 1:469: K_SPLIT\n k_split!\n\n\n when 55\n # at line 1:477: K_BEGIN\n k_begin!\n\n\n when 56\n # at line 1:485: K_DIR\n k_dir!\n\n\n when 57\n # at line 1:491: K_UNION\n k_union!\n\n\n when 58\n # at line 1:499: K_VISIBILIDAD\n k_visibilidad!\n\n\n when 59\n # at line 1:513: K_MODIFICADOR\n k_modificador!\n\n\n when 60\n # at line 1:527: K_ARRAY\n k_array!\n\n\n when 61\n # at line 1:535: K_PROPIEDAD\n k_propiedad!\n\n\n when 62\n # at line 1:547: K_GET\n k_get!\n\n\n when 63\n # at line 1:553: K_SET\n k_set!\n\n\n when 64\n # at line 1:559: K_VALUE\n k_value!\n\n\n when 65\n # at line 1:567: K_INITIALIZE\n k_initialize!\n\n\n when 66\n # at line 1:580: K_FUNC\n k_func!\n\n\n when 67\n # at line 1:587: K_VOID\n k_void!\n\n\n when 68\n # at line 1:594: HexLiteral\n hex_literal!\n\n\n when 69\n # at line 1:605: DecimalLiteral\n decimal_literal!\n\n\n when 70\n # at line 1:620: OctalLiteral\n octal_literal!\n\n\n when 71\n # at line 1:633: WS\n ws!\n\n\n when 72\n # at line 1:636: LINE_COMMENT\n line_comment!\n\n\n when 73\n # at line 1:649: Identificador\n identificador!\n\n\n end\n end", "def next_token\n\t\t@token = @input.next_token\n\tend", "def tokenize(aText)\n tokenizer = PB_Tokenizer.new(aText)\n tokenizer.tokens\n end", "def initialize(input)\n @lexer = Lexer.new(input)\n @current_token = nil\n forward\n end", "def tokens_to_s\n token_stream.compact.map { |token| token.text }.join ''\n end", "def read_tokens()\n\n # By adding @ to tokens, we're saving it also in the instance. We're not\n # going to use that, but it might be useful later.\n @tokens = []\n\n File.open(@filename) do |input_file|\n input_file.each do |line|\n line.split.each do |word|\n word = normalize(word)\n @tokens << word unless word.empty?\n end\n end\n end\n\n @tokens\n end", "def tokenize(source)\n source = source.source if source.respond_to?(:source)\n return [] if source.to_s.empty?\n tokens = source.split(TemplateParser)\n\n # removes the rogue empty element at the beginning of the array\n tokens.shift if tokens[0] and tokens[0].empty?\n\n tokens\n end", "def tokenize\n # Slice each character if there's a symbol there; this leaves the symbol\n # at the end of the character array\n sliced_strings = split_on_symbol_locations(text)\n\n # Convert the final character of each string into a :symbol token, and\n # the rest into a :text token\n tokens = sliced_strings.zip(symbol_locations).flat_map do |text, sym_loc|\n if sym_loc.nil?\n # If the document doesn't end with a symbol, just return text\n Token.new(:text, text) \n else\n # If it does, return both text minus symbol, and then a symbol token\n [\n Token.new(:text, text[0...-1]),\n Token.new(:symbol, sym_loc.symbol)\n ]\n end\n end\n\n # Strip any empty tokens (can occur when symbols are adjacent)\n tokens_without_empty = reject_empty_text(tokens)\n\n # Add a :nil token to the beginning to make each_cons work properly\n tokens_without_empty.unshift(Token.new(:nil, nil))\n\n # Convert spaces at the beginning of lines to :space_count tokens\n tokens_with_space_counts = tokens_without_empty.each_cons(2).flat_map do |token1, token2|\n # We're only looking for :text tokens with :newline tokens before them\n next token2 unless token1 == Token.new(:symbol, :newline) \\\n && token2.type == :text\n\n # Count the number of spaces at the beginning of the string\n spaces_at_start = token2.value.scan(/^ */).first.length\n\n # Return a space count and a text token\n [\n Token.new(:space_count, spaces_at_start),\n Token.new(:text, token2.value.gsub(/^ +/, ''))\n ]\n end\n\n # Convert :space_count tokens to indents and dedents\n indent_level = 0 # current level of indentation\n indent_amount = nil # spaces required for an indent\n tokens_with_space_counts.flat_map do |token|\n # Only look for :space_count tokens\n next token unless token.type == :space_count\n\n # If this is any form of indentation and we don't know an indent amount\n # yet, set it\n indent_amount = token.value if indent_amount.nil? && !token.value.zero?\n\n # If we still don't know, skip\n next nil if indent_amount.nil?\n\n # Work out an indent delta\n # +x = indent by x levels, -x = dedent by x levels; x must be int\n indent_delta = token.value.to_f / indent_amount - indent_level\n raise 'invalid indentation' unless indent_delta % 1 == 0.0\n\n indent_level += indent_delta.to_i\n\n # Output tokens\n [Token.new(indent_delta.positive? ? :indent : :dedent, nil)] \\\n * indent_delta.abs\n end.reject(&:nil?)\n end", "def tokenizer\n yield\n\n rescue RangeError, RuntimeError => ex\n $stderr.print 'invalid token detected around '\n fail ex.message\n end", "def tokenize(string)\n string.scan(/[+*\\/()-]|\\d+/)\nend" ]
[ "0.7559099", "0.73922145", "0.73162776", "0.7213815", "0.7203481", "0.71423316", "0.71423316", "0.69663167", "0.6958177", "0.6958177", "0.6918021", "0.6918021", "0.68163633", "0.6773894", "0.6629035", "0.66260797", "0.65720826", "0.65361017", "0.6473569", "0.6473569", "0.64353144", "0.63748664", "0.6294796", "0.62879527", "0.627317", "0.627317", "0.62671286", "0.6248338", "0.61912954", "0.6113359", "0.6111544", "0.60929596", "0.60851747", "0.6074916", "0.6074916", "0.60626024", "0.6053417", "0.60516196", "0.60499454", "0.60499454", "0.60499454", "0.60499454", "0.60499454", "0.60499454", "0.60499454", "0.60499454", "0.60100746", "0.6005696", "0.6001793", "0.600112", "0.59367794", "0.5936513", "0.5935086", "0.59008044", "0.5899581", "0.58962524", "0.5890775", "0.58879787", "0.5887731", "0.5875997", "0.5843985", "0.5842865", "0.5824983", "0.5809877", "0.5809833", "0.580335", "0.5801567", "0.57997406", "0.57928103", "0.57916164", "0.5790287", "0.57842594", "0.5779599", "0.5777282", "0.57569104", "0.5748738", "0.574332", "0.5731971", "0.5727232", "0.57107425", "0.5706678", "0.57058", "0.5692006", "0.5685825", "0.5676764", "0.5669441", "0.56657743", "0.56619966", "0.5657324", "0.5654198", "0.56500316", "0.5645807", "0.5639443", "0.5635689", "0.5633821", "0.56280726", "0.56239784", "0.56184745", "0.560072", "0.5585069" ]
0.66031986
16
Returns the current token or +token+ to the token stream
def unget token = @current_token p :unget => token if @debug raise Error, 'too many #ungets' if token == @tokens.first @tokens.unshift token if token end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def current_token\n @stream.current_token\n end", "def get_token\n @tokenbuf << read_token if @tokenbuf.length == 0\n return @tokenbuf.shift\n end", "def current_token\n @current_token\n end", "def current_token\n @tokens[@token_index]\n end", "def token\n @token\n end", "def token\n item = read\n return item['token'] if item['token']\n token_reset\n read['token']\n end", "def token\n @token ||= @context[\"value\"]\n end", "def token\n @token\n end", "def get\n @current_token = @tokens.shift\n p :get => @current_token if @debug\n @current_token\n end", "def get\n @current_token = @tokens.shift\n p :get => @current_token if @debug\n @current_token\n end", "def token\n @token.present? ? @token : token_hash\n end", "def next_token\n\t\tif (token = @tokens.shift) != nil\n\t\t\t@copy << token\n\t\t\treturn token.get_token\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend", "def next\n\t\tif @next_token\n\t\t\ttoken = @next_token\n\t\t\t@next_token = nil\n\t\t\treturn token\n\t\telse\n\t\t\ttoken = read_token\n\t\t\treturn token\n\t\tend\n\tend", "def peek\n @tok ||= read_token\n end", "def token\n @@token ||= fetch_token\n end", "def token_get()\n\t\tputs \"Here is the token \" + @token\n\tend", "def consume\n cur = @current_token\n next_token\n return cur\n end", "def token\n @data[:token]\n end", "def next_token\n\t\t@token = @input.next_token\n\tend", "def token\n return @children['token'][:value]\n end", "def next_token\n @current_token = @lexer.next_token\n end", "def token_stream # :nodoc:\n end", "def token\n ready_token\n\n i = @buffer.index(/[\\[\\]()<>{}\\s\\/]/) || @buffer.size\n\n token_chars =\n if i == 0 and @buffer[i,2] == \"<<\" then 2\n elsif i == 0 and @buffer[i,2] == \">>\" then 2\n elsif i == 0 then 1\n else i\n end\n\n strip_space = !(i == 0 and @buffer[0,1] == '(')\n tok = head(token_chars, strip_space)\n\n if tok == \"\"\n nil\n elsif tok[0,1] == \"%\"\n @buffer = \"\"\n token\n else\n tok\n end\n end", "def next_token\n tokens.shift\n end", "def token; end", "def token; end", "def token; end", "def token; end", "def token; end", "def token; end", "def getTokenText()\r\n return @curr_token.text\r\n end", "def get_token_stream\n raise NotImplementedError\n end", "def next\n token = next_token\n token = next_token while token&.empty?\n token\n end", "def getToken()\n if @verbose\n if @token\n puts((\" \"*@indent) + \" (\" + @token.show(true) + \")\")\n end\n end\n\n @token = @lexer.get()\n end", "def next_token\r\n if !@token.following.nil?\r\n\t\t\t@token = @token.following\r\n\t\t\treturn @token.value\r\n\t\tend\r\n\r\n\t\tscan(@token)\r\n\t\treturn @token.value\r\n end", "def next_token\n\t\t@tokens.next_token\n\tend", "def next_token; end", "def peek\n @tokens.at(@current)\n end", "def next_token\n @tokens.shift\n end", "def token\n @token ||= options[:token] || TokenFetcher.fetch\n end", "def token\n end", "def next()\n if @ss.scan_until(token_re)\n term = @ss.matched\n term_end = @ss.pos\n term_start = term_end - term.size\n else\n return nil\n end\n\n return Token.new(normalize(term), term_start, term_end)\n end", "def find_token\n shift_token || find_regex_token || find_string_token\n end", "def token\n return create_token_object.token if token_object.nil? || Time.now - token_object.updated_at > MAX_TOKEN_AGE\n token_object.token\n end", "def pop_token\n @token_stream.pop\n end", "def pop_token\n @token_stream.pop\n end", "def peek_token\n token = @tokens.first || []\n p :peek => token if @debug\n token\n end", "def peek_token\n token = @tokens.first || []\n p :peek => token if @debug\n token\n end", "def get_Token()\n \t return @outputs[\"Token\"]\n \tend", "def get_Token()\n \t return @outputs[\"Token\"]\n \tend", "def token\n @attributes[:token]\n end", "def peek # :nodoc:\n @tokens.peek\n end", "def next\n @tok ||= read_token\n @tok, tok = nil, @tok\n @prev = tok\n return tok\n end", "def token\n refresh_token if needs_token_refresh?\n return @token\n end", "def next_token; @stack.shift; end", "def message\n @token.message\n end", "def to_param\n self.token\n end", "def to_param\n\t\tself.token\n\tend", "def get_token\n session[:token] if authorized?\n end", "def token_from(data)\n extract_from(data, /Token token='(.+)'/).first rescue nil\n end", "def get_current_token\n if request.headers['Authorization'].present?\n return request.headers['Authorization'].split(' ').last\n end\n raise(ExceptionHandler::MissingToken, Message.missing_token)\n end", "def peek\n @tokens[@position]\n end", "def token!\n raise \"#{username} is not signed in, (token is set to nil).\" unless token\n\n token\n end", "def peek\n @tokens[@pos]\n end", "def token\n _response_word.fetch(\"token\", nil)\n end", "def getToken\n @tokens\n end", "def token\n configuration.token\n end", "def to_s\n token\n end", "def get_token\n get(TOKEN_URL)\n end", "def data\n token\n end", "def next_token\n\t\tif ((tok = @tokensList.shift) != nil)\n\t\t\t@tokensAux << tok\n\t\t\treturn tok.idAndValue\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend", "def current_type\n @token_type[@current_tok]\n end", "def next_token\n raise NotImplementedError\n end", "def token\n @token ||= Token.new(config)\n end", "def get_token\n if params.has_key?(:token) && params[:token] != ''\n return params[:token]\n end\n return nil if !request || !request.headers\n token_response = request.headers['Authorization']\n return nil if !token_response\n token_response[/^Token (.*)/,1]\n end", "def peek_token(amount = 1)\n index = @token_index + amount\n @tokens[index]\n end", "def peek_next(token)\r\n\t\tif !token.following.nil?\r\n\t\t return token.following\r\n\t\tend\r\n\r\n\t\tpeekToken = Token.new\r\n\t\tscan(peekToken)\r\n\t\ttoken.following = peekToken\r\n\t\treturn peekToken\r\n\tend", "def next_token()\n raise LexicalError.new(\"No input text was provided.\", LexemePosition::at_start) if token_recognition_state == :waiting_for_input\n\n\t\tif queue.empty?\n unless token_recognition_state == :ready\n error_message = \"#{__method__} may not be called when state is #{token_recognition_state}\"\n raise LexerSetupError.new(error_message)\n end\n\n enqueue_next_tokens() # Retrieve token(s) from the input text & enqueue them\n end\n theToken = queue.dequeue()\n\t\treturn theToken\n end", "def token\n return @settings.token if @settings.token?\n\n token = token_store.load(token_store_key)\n return token if token\n\n return nil unless @settings.autologin\n\n token = V1.request_auth_token!(auth_connection)\n token_store.store(token_store_key, token)\n token\n end", "def get_operation token\n OPERATOR_MAP[token]\n end", "def token\n authenticated\n end", "def next_token(options = { should_advance?: true })\n if @current_scope.type == Scope::TYPE_MAIN && @current_scope.current_token.nil?\n token = @lexer.next_token\n @current_scope.tokens << token unless token.nil?\n end\n\n token = @current_scope.current_token\n\n advance token if options[:should_advance?] && token\n\n token\n end", "def personal_access_token # :yields: String\n @@token\n end", "def next_token\n #dputs \"@line: \" + @line\n if @state == :normal\n while true\n temp = _next_token\n unless temp == \"#white_space\" || temp == \"#comment\"\n break\n end\n end\n #dputs \"token: \" + temp\n @current_token = temp\n return temp\n else\n return :Terminate\n end\n \n end", "def token=(_arg0); end", "def token=(_arg0); end", "def token=(_arg0); end", "def peek_token\n return nil if @start >= @expr.length\n if @start == 0 && @finish == 0\n return @expr[0]\n else\n token = @expr[@start...@finish]\n\n if token.empty?\n @finish = @finish + 1\n peek_token\n else\n return token\n end\n end\n end", "def peek_token(n=1)\n n.times{|x| @tokenbuf << read_token if @tokenbuf.length == 0 }\n return @tokenbuf[n-1]\n end", "def code\n\t\ttoken\n\tend", "def get\n tok = get_internal\n # NOTE: Only for debug\n # print \"#{tok} #{tok.file&.name || \"(unknown)\"} #{tok.line} #{tok.column}\\n\"\n tok\n end", "def get_token\n LastFM.get( \"auth.getToken\", {}, :secure )\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end", "def token(value)\n merge(token: value.to_s)\n end" ]
[ "0.81498164", "0.7948311", "0.766473", "0.76168036", "0.75251657", "0.7453073", "0.7432192", "0.74250376", "0.7336681", "0.7336681", "0.7268622", "0.7250319", "0.7189824", "0.71562195", "0.7152385", "0.70746887", "0.70031375", "0.6998607", "0.694673", "0.6931011", "0.69286066", "0.69231904", "0.688865", "0.6850888", "0.6849916", "0.6849916", "0.6849916", "0.6849916", "0.6849916", "0.6849916", "0.68288237", "0.6814724", "0.6810393", "0.6799394", "0.67992985", "0.6781", "0.67788076", "0.67780656", "0.6766373", "0.675141", "0.6708102", "0.6640349", "0.6634384", "0.66065794", "0.658737", "0.658737", "0.657365", "0.657365", "0.65729475", "0.65729475", "0.65576166", "0.65446514", "0.6544411", "0.6539099", "0.6514763", "0.65116197", "0.65045345", "0.6503608", "0.6435596", "0.6412293", "0.6407437", "0.64018846", "0.638377", "0.6376472", "0.6366977", "0.6344395", "0.63438517", "0.63428915", "0.63312244", "0.63251495", "0.6324827", "0.6301674", "0.6299569", "0.6279593", "0.6258098", "0.62525845", "0.62396234", "0.6234128", "0.6219191", "0.6186572", "0.6177484", "0.61765754", "0.6166034", "0.6151923", "0.6145424", "0.6145424", "0.6145424", "0.61413133", "0.6133165", "0.6131823", "0.61223125", "0.6088483", "0.60837394", "0.60837394", "0.60837394", "0.60837394", "0.60837394", "0.60837394", "0.60837394", "0.60837394", "0.60837394" ]
0.0
-1
:callseq: ratio + obj > new_obj Performs a symbolic sum between a symbolic rational and `obj`, returning a new symbolic object if the operation creates a new tree branch, or a symbolic number if `obj` is a SymDesc::Number. Simplification is automatic. If b is not a symbolic object, a conversion is attempted
def +(b) b = b.symdescfy case b when Infinity b when Number __sum_number b when BinaryOp b + self else super end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def +(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj)\n return self - obj.val if obj.is_a? Negative\n return Prod.new(Number.new(2),self) if self == obj\n lft = (obj.is_a? Prod) ? (self.left + obj.left) : (self.left + Number.new(1))\n return Prod.new(lft,self.right) if self =~ obj\n return Sum.new(self,obj).reduce\n end", "def + r\r\n ans = MyRational.new(@num,@den)\r\n ans.add! r\r\n ans\r\n end", "def use_rationals\r\n r1 = MyRational.new(3,4)\r\n r2 = r1 + r1 + MyRational.new(-5,2)\r\n puts r2.to_s\r\n (r2.add! r1).add! (MyRational.new(1,-4))\r\n puts r2.to_s\r\n puts r2.to_s2\r\n puts r2.to_s3\r\nend", "def +(object)\n aux=mcm(@denominador,object.denominador)\n Fraccion.new((((aux*@numerador)/@denominador)+(aux*object.numerador)/object.denominador),aux)\n end", "def use_rationals\n r1 = MyRational.new(3, 4)\n r2 = r1 + r1 + MyRational.new(-5, 2)\n puts r2.to_s\n (r2.add! r1).add! (MyRational.new(1, -4))\n puts r2.to_s\n puts r2.to_s2\n puts r2.to_s3\nend", "def +(b)\n return self if b == 0\n return Int.new(@value + b) if b.is_a? Integer\n b = b.symdescfy\n case b\n when Infinity\n b\n when Ratio, BinaryOp\n b + self\n when Int\n Int.new(@value + b.value)\n else\n super\n end\n end", "def use_rationals\n\tr1 = MyRational.new(3, 4)\n\tr2 = r1 + r1 + MyRational.new(-5, 2)\n\tputs r2.to_s\n\n\t(r2.add! r1).add! (MyRational.new(1, -4))\n\tputs r2.to_s\nend", "def add(rational)\n\n\t\t#\tCopy the second rational\n\t\ttemp = RationalNumber.new(rational.numerator, rational.denominator)\n\n\t\t#\tMake sure we have LCD \n\t\tif not self.denominator == rational.denominator\n\t\t\ttemp.denominator = rational.denominator * self.denominator\n\t\t\ttemp.numerator = rational.numerator * self.denominator\n\t\tend\n\n\t\t#\tNow add...\n\t\tself.numerator = self.numerator + temp.numerator\n\n\t\treturn self\n\tend", "def + r\n ans = MyRational.new(@num, @den)\n ans.add! r\n ans\n end", "def +(other)\n\t\tRacional.new(num*other.denom + other.num*denom, denom*other.denom)\n\tend", "def + other\n other = Fraction.new(other) if other.instance_of? Fixnum\n Fraction.new(@numer * other.denom + other.numer * @denom, @denom * other.denom)\n end", "def test_Rational_InstanceMethods_to_r\n\t\tassert_equal(Rational(\"2\"), Rational(\"4/2\").to_r)\n\tend", "def plus(x,y)\n if x.class == Fixnum && y.class == Fixnum then\n B.new\n elsif x.class == Float && y.class == Float then\n x + y\n else\n fail \"nope\"\n end\n end", "def +(obj)\n case obj\n when Numeric\n self.class.new(@val + obj)\n when self.class\n self.class.new(@val + obj.val)\n else\n raise TypeError, \"#{self.class} cannot be added to #{obj.class}\"\n end\n end", "def +(r)\n case r\n when Integer\n self + Fraction[r]\n when Fraction\n Fraction[ r.last*first + r.first*last, r.last*last ]\n else\n raise TypeError.new(\"Sorry, I can't add a Fraction and a #{r.class}. :(\")\n end\n end", "def test_Rational_ArithmeticOperations\n\t\tassert_equal(1.0, Rational(\"1/2\") + Rational(\"1/2\"))\n\t\tassert_equal(0.0, Rational(\"1/2\") - Rational(\"1/2\"))\n\t\tassert_equal(0.25, Rational(\"1/2\") * Rational(\"1/2\"))\n\t\tassert_equal(1.0, Rational(\"1/2\") / Rational(\"1/2\"))\n\t\tassert_equal(0, Rational(\"1/2\") % Rational(\"1/2\"))\n\t\tassert_equal(4.0, Rational(\"2\") ** Rational(\"2\"))\n\t\t# assert_equal(1, -@ Rational(\"2\"))\n\tend", "def coerce(other)\n if other.is_a? Numeric\n [Rational.new(other, 1), self]\n else\n puts \"(Rational failed to coerce object of type #{other.class})\"\n super\n end\n end", "def /(other)\n RDF::Literal(to_d / (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n end", "def +(other)\n RDF::Literal(to_d + (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n end", "def + m2\n return magnitude amount + m2.amount if m2.quantity == quantity.relative\n return quantity.relative.magnitude( amount + m2.amount ) if\n quantity == m2.quantity\n return self if m2.equal? SY::ZERO\n # o1, o2 = m2.coerce( self )\n # return o1 + o2\n raise SY::QuantityError, \"Unable to perform #{quantity} + #{m2.quantity}!\"\n end", "def test_rational_coerce\n assert_respond_to(@rat1, :coerce)\n assert_nothing_raised{ @rat1.coerce(9) }\n assert_nothing_raised{ @rat1.coerce(0.5) }\n #assert_equal(Rational(9,1), @rat1.coerce(9))\n end", "def + b\n 1.plus self.plus(b)\n end", "def **(b)\n b = b.symdescfy\n case b\n when Infinity\n b\n when Int\n return Ratio.new(@numerator ** b.value, @denominator ** b.value)\n else\n super\n end\n end", "def test_rational_inspect\n assert_respond_to(@rat1, :inspect)\n assert_equal(\"Rational(3, 4)\", @rat1.inspect)\n assert_equal(\"Rational(0, 1)\", @rat4.inspect) # Reduced\n assert_equal(\"Rational(9, 1)\", @rat5.inspect)\n end", "def convert(other)\n raise \"Units #{self} and #{other} are not commensurable\" unless commensurable?(other)\n return Rational(1,1) if self == other\n self.factor / other.factor\n end", "def /(object)\n #multiplica numerador con numerador y denominador con denominador\n Fraccion.new(@numerador*object.denominador,@denominador*object.numerador)\n end", "def ==(b)\n case b\n when Rational, Ratio\n (@numerator == b.numerator) &&\n (@denominator == b.denominator)\n when Float\n self == b.symdescfy\n else\n false\n end\n end", "def /(other)\n\t\tRacional.new(num*other.denom,denom*other.num)\n\tend", "def test_Rational_InstanceMethods_rationalize\n\t\tassert_equal(Rational(\"884279719003555/281474976710656\").to_r, Math::PI.to_r)\n\t\t# TODO, Need add some testcases.\n\t\t# r.rationalize #=>(884279719003555/281474976710656)\n\t\t# r.rationalize(0.01)#=>(22/7)\n\tend", "def +(other)\n if other.class == Fraccion\n Fraccion.new(@num*other.denom + other.num*@denom , @denom*other.denom)\n else\n Fraccion.new(@num + other*@denom , @denom)\n end\n end", "def ==(rational)\n end", "def -(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj)\n return self + obj.val if obj.is_a? Negative\n return Number.new 0 if self == obj\n lft = ((self =~ obj) && (obj.is_a? Prod)) ? (self.left - obj.left) : (self.left - Number.new(1))\n return Prod.new(lft,self.right) if self =~ obj\n return Diff.new(self,obj)\n end", "def test_Complex_InstanceMethods_to_r\n\t\tassert_equal(Rational('5/2'), Complex(2.5, 0).to_r)\n\tend", "def mediant(other)\n return SternBrocot::Fraction.new(self.numerator+other.numerator, self.denominator+other.denominator)\n end", "def add(galaxy_id, from_kind, to_kind, from_amount, to_rate)\n model = get(galaxy_id, from_kind, to_kind)\n model.to_rate =\n (model.from_amount * model.to_rate.to_f + from_amount * to_rate.to_f) /\n (model.from_amount + from_amount)\n model.from_amount += from_amount\n model.save!\n\n model\n end", "def test_rational_to_s\n assert_respond_to(@rat1, :to_s)\n assert_nothing_raised{ @rat1.to_s }\n assert_kind_of(String, @rat1.to_s)\n assert_equal(\"3/4\", @rat1.to_s)\n assert_equal(\"3/4\", @rat7.to_s)\n end", "def test_Rational_InstanceMethods_round\n\t\tassert_equal(3, Rational(\"22/7\").round)\n\t\tassert_equal(-3, Rational(\"-22/7\").round)\n\tend", "def test_Rational_InstanceMethods_to_f\n\t\tassert_equal(9.25, Rational(\"37/4\").to_f)\n\tend", "def +(other)\n if self.class == Double || [Double, ::Float].include?(other.class)\n RDF::Literal::Double.new(to_f + other.to_f)\n elsif ((self.class == RDF::Literal::Float || other.class == RDF::Literal::Float) rescue false)\n RDF::Literal::Float.new(to_f + other.to_f)\n elsif self.class == Decimal || other.class == Decimal\n RDF::Literal::Decimal.new(to_d + (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n else\n RDF::Literal::Integer.new(to_i + other.to_i)\n end\n end", "def +(other)\n if self.class == Double || [Double, ::Float].include?(other.class)\n RDF::Literal::Double.new(to_f + other.to_f)\n elsif ((self.class == RDF::Literal::Float || other.class == RDF::Literal::Float) rescue false)\n RDF::Literal::Float.new(to_f + other.to_f)\n elsif self.class == Decimal || other.class == Decimal\n RDF::Literal::Decimal.new(to_d + (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n else\n RDF::Literal::Integer.new(to_i + other.to_i)\n end\n end", "def -(object)\n aux=mcm(@denominador,object.denominador)\n Fraccion.new((((aux*@numerador)/@denominador)-(aux*object.numerador)/object.denominador),aux)\n end", "def rationalize(eps = nil)\n eps ? Q.new(to_r.rationalize(eps)) : self\n end", "def first_chk(obj)\n if (self =~ obj) && (obj.is_a? Pow)\n if self.right.is_a? Pow\n myExp, objExp = self.right.right, obj.right\n myExp.top, objExp.top = true, true\n exp = myExp + objExp\n rht = Pow.new(obj.left,exp).reduce\n return Prod.new(self.left,rht).reduce\n end\n objExp = obj.right\n objExp.top = true\n objExp += Number.new 1\n rht = Pow.new(obj.left,objExp).reduce\n return Prod.new(self.left,rht).reduce\n elsif self =~ obj\n return Prod.new(self.left,Pow.new(self.right,Number.new(2))).reduce\n end\n return nil\n end", "def sum (operator, a, b)\n if operator == \"exponents\"\n a ** b\n elsif operator == \"square root\"\n Math.sqrt(a)\n end\nend", "def convert_and_assign(obj, symbol)\n success, rexp = convert_to_r_object(obj)\n raise RriException.new(\"Failed to convert ruby object to R object for: #{obj}\") unless success\n simple_assign(symbol, rexp)\n end", "def test_Rational_InstanceMethods_Comparison\n\t\tassert_equal(0, Rational(\"4/2\") <=> Rational(\"98/49\"))\n\t\tassert_equal(-1, Rational(\"3/4\") <=> 41)\n\t\tassert_equal(0, Rational(\"0\") <=> 0.0)\n\tend", "def compute(object)\n base = if object.is_a?(Array)\n object.map { |o| o.respond_to?(:amount) ? o.amount : BigDecimal(o.to_s) }.sum\n else\n object.respond_to?(:amount) ? object.amount : BigDecimal(object.to_s)\n end\n\n if base < preferred_minimal_amount\n preferred_normal_amount\n else\n preferred_discount_amount\n end\n end", "def test_NilClass_InstanceMethod_rationalize\n\t\t# TODO, undefined method 'rationalize' under ruby 1.9.1p430 \n\t\t# assert_equal((0/1), nil.rationalize)\n\tend", "def /(other)\n @a=other.b*@a\n @b=other.a*@b\n self.to_s #devuelve el resultado como cadena. la operacion modifica el valor del objeto.\n end", "def fraction_calculator fraction_one, fraction_two, operator\n num_one = Rational(fraction_one)\n num_two = Rational(fraction_two)\n \n final_result = case operator\n when '/' then num_one / num_two\n when '*' then num_one * num_two\n when '+' then num_one + num_two\n when '-' then num_one - num_two\n end\n\n String(final_result)\n\n print String(final_result)\n\nend", "def add m2\n return magnitude( amount + m2.amount ) if quantity == m2.quantity\n return self if m2.equal? SY::ZERO\n # o1, o2 = m2.coerce( self )\n # return o1.add o2\n raise SY::QuantityError, \"Unable to perform #add with #{m2.quantity}!\"\n end", "def add_reciprocal_object(opts, o)\n return if o.frozen?\n return unless reciprocal = opts.reciprocal\n if opts.reciprocal_array?\n if array = o.associations[reciprocal] and !array.include?(self)\n array.push(self)\n end\n else\n o.associations[reciprocal] = self\n end\n end", "def /(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj) || \n (obj == 0) || \n (obj.is_a? Number) ||\n (obj == P_Infinity) ||\n (obj == M_Infinity)\n if self =~ obj\n ret = self.left\n ret.top = self.top\n return ret\n end \n if (obj.is_a? Number) || (obj == P_Infinity) || (obj == M_Infinity)\n lft = self.left\n lft.top = true\n lft /= obj\n puts lft\n return Prod.new(lft,self.right).reduce unless lft == nil\n return nil unless self.top\n end\n return Div.new(self,obj).reduce\n end", "def *(other)\n\t\tRacional.new(num*other.num,denom*other.denom)\n\tend", "def +(other)\n if other.is_a?(Value)\n lcm_div = @div.lcm(other.div)\n Value.new((@val * (lcm_div / @div)) + (other.val * (lcm_div / other.div)), lcm_div)\n elsif other.is_a?(Numeric)\n to_f + other\n else\n raise \"Unexpected argument\"\n end\n end", "def test_Rational_InstanceMethods_fdiv\n\t\t# assert_equal(11/4, Rational(\"11/2\")/2)\n\t\tassert_equal(2.75, Rational(\"11/2\").fdiv(2))\n\tend", "def *(obj) \n return nil unless (self.top) || (self == obj) || (self =~ obj) || \n (obj == 0) || \n (obj.is_a? Number) || \n (obj == P_Infinity) || \n (obj == M_Infinity)\n return Pow.new(self,Number.new(2)).reduce if self == obj\n chk = first_chk(obj)\n return chk unless chk == nil\n return self * obj.left * obj.right if obj.is_a? Prod\n chk = second_chk(obj)\n return chk unless chk == nil\n return Prod.new(self,obj).reduce unless obj.is_a? Number\n return Prod.new(obj,self).reduce\n end", "def /(other)\n Fraccion.new(@num * other.denom, @denom * other.num)\n end", "def +(other)\n if (other.is_a?(Numeric))\n Quantity.new(@value + other, @unit)\n elsif(other.is_a?(Quantity) && @unit.dimension == other.unit.dimension)\n Quantity.new({:unit => @unit,:reference_value => @reference_value + other.reference_value})\n else\n raise ArgumentError,\"Cannot add #{self} to #{other}\"\n end\n end", "def =~(obj)\n return false unless self.left.is_a? Number\n if obj.is_a? Prod\n return false unless obj.left.is_a? Number\n return self.right == obj.right\n end \n return self.right == obj \n end", "def reduce\n if left.reducible?\n Add.new(left.reduce, right)\n elsif right.reducible?\n Add.new(left, right.reduce)\n else\n Number.new(left.value + right.value)\n end\n end", "def rationalize=(rationalize)\n assert_unloaded\n @rationalize = rationalize\n end", "def ratio\n # This call is interesting because it involves converting the\n # cog to a floar instead of both the chainring and the cog.\n # This avoids any uncessary conversions to get the job done!\n chainring / cog.to_f\n end", "def test_NilClass_InstanceMethod_to_r\n\t\tassert_equal(Rational(0,1), nil.to_r)\n\tend", "def to_foorth_r\r\n self.rationalize\r\n end", "def dup_or_calc( array, object, index )\n array[ index ] = object.class.new if ( array[ index ].nil? )\n array[ index ].add!( object )\n end", "def add_subresult(subresult)\n if @result_object[:units_array].last.nil? || [\"*\", \"(\", \")\"].include?(@result_object[:units_array].last)\n @result_object[:factor] *= subresult[:factor]\n else\n @result_object[:factor] /= subresult[:factor]\n end\n\n @result_object[:units_array].concat(subresult[:units_array])\n end", "def to_r\n return Rational(numerator,denominator)\n end", "def add_reciprocal_object(opts, o)\n return unless reciprocal = opts.reciprocal\n if opts.reciprocal_array?\n if array = o.associations[reciprocal] and !array.include?(self)\n array.push(self)\n end\n else\n o.associations[reciprocal] = self\n end\n end", "def + (cn)\n @@addoperation += 1\n real = @real + cn.real\n img = @img + cn.img\n ComplexNumber.new(real, img)\n end", "def /(other)\n Resistor::CombinedResistor.new(1 / (1 / @ohm + 1 / other.ohm))\n end", "def addition\n expr = multiplication\n\n while match?(:minus, :plus)\n operator = previous\n right = multiplication\n expr = Ringo::Binary.new(expr, operator, right)\n end\n\n return expr\n end", "def add_fraction_and_fraction(frac1, frac2)\n\tif frac1.denominator != frac2.denominator\n\t\tnew_frac1_numerator = multiply_unknown_terms_or_term_lists(frac1.numerator, frac2.denominator)\n\t\tnew_frac2_numerator = multiply_unknown_terms_or_term_lists(frac2.numerator, frac1.denominator)\n\t\tnew_numerator = add_unknown_terms_or_term_lists(new_frac1_numerator, new_frac2_numerator)\n\t\tnew_denominator = multiply_unknown_terms_or_term_lists(frac1.denominator, frac2.denominator)\n\t\treturn Fraction.new(frac1.line, frac1.col, numerator: new_numerator, denominator: new_denominator)\n\tend\n\tnew_numerator = add_unknown_terms_or_term_lists(frac1.numerator, frac2.numerator)\n\treturn Fraction.new(frac1.line, frac1.col, numerator: new_numerator, denominator: frac1.denominator)\nend", "def add_ins(obj)\n self.first.value = self.first.value + obj.first.value\n obj.type = 'int'\n self.type = 'int'\n end", "def test_Complex_InstanceMethods_rationalize\n\t\tassert_equal(2.5, Complex(2.5, 0))\n\tend", "def +(object)\n if object.is_a?(Pattern)\n Pattern.new(self, size: size + object.size) { |y, d|\n each { |v| y << v }\n object.each { |v| y << v }\n }\n else\n map { |v| v.respond_to?(:+) ? v + object : v }\n end\n end", "def test_Rational_InstanceMethods_Compare2\n\t\tassert_equal(true, Rational(\"2\") == Rational(\"2\"))\n\t\tassert_equal(false, Rational(\"1\") == Rational(\"2\"))\n\tend", "def test_should_be_able_to_be_added\n currency1 = Currency.new(\"USD\", 1.0)\n currency2 = Currency.new(\"USD\", 5.0)\n\n assert_equal Currency.new(\"USD\", 6.0), currency1.+(currency2)\n end", "def add(o); addObject o end", "def +(other)\n\t\tif other.respond_to?(\"d\")\n\t\t\treturn Fraccion.new(((mcm(@d, other.d) / @d)*@n) + ((mcm(@d, other.d) / other.d)*other.n),mcm(@d, other.d))\n\t\telse\n\t\t\treturn Fraccion.new( ((other*@d) + @n), @d)\n\t\tend\t\n\tend", "def minimizar(a,b)\n mcd = gcd(a,b)\n aux = Fraccion.new(1,1)\n aux.num = a/mcd\n aux.denom = b/mcd\n return aux\n end", "def + (other)\n if other.kind_of?(Complex)\n re = @real + other.real\n im = @image + other.image\n Complex(re, im)\n elsif Complex.generic?(other)\n Complex(@real + other, @image)\n else\n x , y = other.coerce(self)\n x + y\n end\n end", "def to_ref(value)\n result = nil\n if uom_type == 'ref'\n result = value\n elsif uom_type == 'big'\n result = value * ratio\n elsif uom_type == 'small'\n result = value/ratio\n end\n result.to_f\n end", "def compute(object)\n line_items = object_to_line_items(object)\n return nil if line_items.nil?\n\n total_qnty = get_total_qnty(line_items)\n weight_rate = get_rate(get_total_weight(line_items), AdditionalCalculatorRate::WEIGHT)\n\n # NOTE: Maybe that has been fixed in the spree 0.50.x\n # # sometimes the compute method is called without checking if the calculator is available\n # if weight_rate.nil?\n # logger.warn(\"The calculator's #{name} weight_rate is nil - returning. Availability is not checked!\")\n # return nil\n # end\n\n # quantity rate might be nil if the specified range is not available\n qnty_rate = get_rate(total_qnty, AdditionalCalculatorRate::QNTY)\n # find the previous qnty rate or set it to 0 if not found\n qnty_rate = get_previous_rate(total_qnty, AdditionalCalculatorRate::QNTY) || 0 if qnty_rate.nil?\n\n # the total rate is sum of weight and quantity rates\n weight_rate + qnty_rate\n end", "def test_Rational_InstanceMethods_ceil\n\t\tassert_equal(4, Rational(\"22/7\").ceil)\n\t\tassert_equal(-3, Rational(\"-22/7\").ceil)\n\tend", "def inc_frees(diff, bindings = 0)\n case kind\n when :variable\n term > bindings ? variable(term + diff) : self\n when :abstraction\n lamb?(term) ? abstraction(term.inc_frees(diff, bindings + 1)) : self\n when :application\n t = lamb?(term) ? term.inc_frees(diff, bindings) : term\n v = lamb?(var) ? var.inc_frees(diff, bindings) : var\n application(t, v)\n end\n end", "def +(a)\n if self == 0\n return a\n elsif a == 0\n return self\n else\n case a\n when Numeric\n if @sqrt_part == 1\n return @front_part + a\n else\n return self.to_f + a.to_f\n end\n when Sqrt\n if @sqrt_part == a.sqrt_part\n return Sqrt.new(@sqrt_part, @front_part + a.front_part)\n else\n return self.to_f + a.to_f\n end\n else\n return self.to_f + a.to_f\n end\n end\n end", "def test_Rational_InstanceMethods_denominator\n\t\tassert_equal(3, Rational(\"2/3\").denominator)\n\t\tassert_equal(365, Rational(\"343434/365\").denominator)\n\tend", "def +(other); end", "def +(other); end", "def +(other); end", "def / other\n other = Fraction.new(other) if other.instance_of? Fixnum\n self * other.inv\n end", "def *(other)\n RDF::Literal(to_d * (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n end", "def +(addend)\n self.plus(addend).to_sub\n end", "def +(currency_object)\n if @currency_symb == currency_object.currency_symb\n Currency.new(@amount +currency_object.amount)\n else\n raise UnknownCurrencyCodeError\n end\n #puts \"The value of the new curent currecy is #{@amount}.\" #This will print the new amount.\n #puts \"The value of the currency_object's amout is #{currency_object.amount}\"\nend", "def multiply_fraction_and_fraction(left, right)\n\tnew_numerator = multiply_unknown_terms_or_term_lists(left.numerator, right.numerator)\n\tnew_denominator = multiply_unknown_terms_or_term_lists(left.denominator, right.denominator)\n\treturn Fraction.new(left.line, left.col, numerator: new_numerator, denominator: new_denominator)\nend", "def +(obj)\n case obj\n when DateTime\n obj + (Rational === @val ? @val/86400 : @val/86400.0)\n when Time\n obj + @val\n else\n super\n end\n end", "def transform_Object(o, scope)\n raise IllegalRelationshipOperandError.new(o)\n end", "def **(obj)\n return nil unless (self.top) || (self == obj) || (obj == 0) || (obj.is_a? Number) ||\n (obj == P_Infinity) ||\n (obj == M_Infinity)\n \n if (self.left != P_Infinity) || (self.left != M_Infinity) || (self.right != P_Infinity) || (self.right != M_Infinity)\n return Number.new 1 if obj == 0\n else\n raise \"Math Error: ∞^0\" if obj == 0\n end\n if (obj.is_a? Number) || (obj == P_infinity) || (obj == M_Infinity)\n lft = self.left ** obj\n return Prod.new(lft,Pow.new(self.right,obj)).reduce unless lft == nil\n return nil unless self.top\n end\n return Pow.new(self,obj).reduce\n end", "def evaluate(env)\n left = self.left.evaluate(env) \n right =self.right.evaluate(env)\n if left.is_a? Numeric and right.is_a? Numeric then\n return left + right\n else\n raise \" Math Error: cannot sum #{left.class} with #{right.class}\\nFrom line: #{self.line}\"\n end\n end" ]
[ "0.5679484", "0.5571299", "0.5512486", "0.5476463", "0.5472499", "0.54054844", "0.53911597", "0.5385869", "0.53632283", "0.5280221", "0.522032", "0.51102436", "0.5104627", "0.5098812", "0.50042707", "0.49911633", "0.49592084", "0.49476534", "0.4887508", "0.48865855", "0.48839208", "0.48731712", "0.486077", "0.48383182", "0.48162222", "0.48156244", "0.48153117", "0.47629997", "0.47213647", "0.47143552", "0.4714271", "0.47024536", "0.46695358", "0.46686184", "0.46609485", "0.46596", "0.46546537", "0.46405226", "0.46403092", "0.46403092", "0.4593955", "0.45855194", "0.45572257", "0.45450538", "0.45093045", "0.4507137", "0.4500623", "0.44946784", "0.4489516", "0.4488426", "0.44860026", "0.44753546", "0.44663206", "0.4454735", "0.44523808", "0.4450903", "0.44497687", "0.44155195", "0.44113728", "0.44048035", "0.43694663", "0.43659264", "0.4363002", "0.4358474", "0.4356752", "0.43566775", "0.43489078", "0.43365502", "0.4332436", "0.43256292", "0.4324623", "0.43240595", "0.43217316", "0.43199837", "0.43055", "0.43027234", "0.4299813", "0.4298417", "0.4284652", "0.42822406", "0.42782044", "0.42739892", "0.4273755", "0.42668283", "0.42563054", "0.4250726", "0.422842", "0.42250386", "0.42209643", "0.42209643", "0.42209643", "0.42208788", "0.42196557", "0.42189914", "0.42092422", "0.42059088", "0.42004803", "0.4184725", "0.4181576", "0.4181216" ]
0.51447797
11
:callseq: ratio obj > new_obj Performs a symbolic subtraction between a symbolic rational and `obj`, returning a new symbolic object if the operation creates a new tree branch, or a symbolic number if `obj` is a SymDesc::Number. Simplification is automatic. If b is not a symbolic object, a conversion is attempted
def -(b) b = b.symdescfy case b when Infinity -b when Number __sub_number b when BinaryOp __sub_binary_op b when Neg self + b.argument else super end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def -(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj)\n return self + obj.val if obj.is_a? Negative\n return Number.new 0 if self == obj\n lft = ((self =~ obj) && (obj.is_a? Prod)) ? (self.left - obj.left) : (self.left - Number.new(1))\n return Prod.new(lft,self.right) if self =~ obj\n return Diff.new(self,obj)\n end", "def -(object)\n aux=mcm(@denominador,object.denominador)\n Fraccion.new((((aux*@numerador)/@denominador)-(aux*object.numerador)/object.denominador),aux)\n end", "def - other\n other = Fraction.new(other) if other.instance_of? Fixnum\n Fraction.new(@numer * other.denom - other.numer * @denom, @denom * other.denom)\n end", "def -(other)\n RDF::Literal(to_d - (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n end", "def -(other)\n if self.class == Double || [Double, ::Float].include?(other.class)\n RDF::Literal::Double.new(to_f - other.to_f)\n elsif ((self.class == RDF::Literal::Float || other.class == RDF::Literal::Float) rescue false)\n RDF::Literal::Float.new(to_f - other.to_f)\n elsif self.class == Decimal || other.class == Decimal\n RDF::Literal::Decimal.new(to_d - (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n else\n RDF::Literal::Integer.new(to_i - other.to_i)\n end\n end", "def -(other)\n if self.class == Double || [Double, ::Float].include?(other.class)\n RDF::Literal::Double.new(to_f - other.to_f)\n elsif ((self.class == RDF::Literal::Float || other.class == RDF::Literal::Float) rescue false)\n RDF::Literal::Float.new(to_f - other.to_f)\n elsif self.class == Decimal || other.class == Decimal\n RDF::Literal::Decimal.new(to_d - (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n else\n RDF::Literal::Integer.new(to_i - other.to_i)\n end\n end", "def -(b)\n return self if b == 0\n return Int.new(@value - b) if b.is_a? Integer\n b = b.symdescfy\n case b\n when Infinity\n -b\n when Ratio\n __sub_ratio b\n when Int\n Int.new(value - b.value)\n else\n super\n end\n end", "def -(other)\n\t\tRacional.new(num*other.denom - other.num*denom, denom*other.denom)\n\tend", "def -(other)\n n=mcm(b, other.b)\n @a=(@a*n/@b)-(other.a*n/other.b)\n @b=n\n self.to_s #devuelve el resultado como cadena. la operacion modifica el valor del objeto.\n \n end", "def -(other)\n if other.class == Fraccion\n Fraccion.new(@num*other.denom - other.num*@denom , @denom*other.denom)\n else\n Fraccion.new(@num - other*@denom , @denom)\n end\n end", "def test_Rational_InstanceMethods_to_r\n\t\tassert_equal(Rational(\"2\"), Rational(\"4/2\").to_r)\n\tend", "def /(other)\n RDF::Literal(to_d / (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n end", "def convert(other)\n raise \"Units #{self} and #{other} are not commensurable\" unless commensurable?(other)\n return Rational(1,1) if self == other\n self.factor / other.factor\n end", "def -(other)\n if (other.is_a?(Numeric))\n Quantity.new(@value - other, @unit)\n elsif(other.is_a?(Quantity) && @unit.dimension == other.unit.dimension)\n Quantity.new({:unit => @unit,:reference_value => @reference_value - other.reference_value})\n else\n raise ArgumentError, \"Cannot subtract #{other} from #{self}\"\n end\n end", "def test_rational_coerce\n assert_respond_to(@rat1, :coerce)\n assert_nothing_raised{ @rat1.coerce(9) }\n assert_nothing_raised{ @rat1.coerce(0.5) }\n #assert_equal(Rational(9,1), @rat1.coerce(9))\n end", "def use_rationals\r\n r1 = MyRational.new(3,4)\r\n r2 = r1 + r1 + MyRational.new(-5,2)\r\n puts r2.to_s\r\n (r2.add! r1).add! (MyRational.new(1,-4))\r\n puts r2.to_s\r\n puts r2.to_s2\r\n puts r2.to_s3\r\nend", "def coerce(other)\n if other.is_a? Numeric\n [Rational.new(other, 1), self]\n else\n puts \"(Rational failed to coerce object of type #{other.class})\"\n super\n end\n end", "def +(object)\n aux=mcm(@denominador,object.denominador)\n Fraccion.new((((aux*@numerador)/@denominador)+(aux*object.numerador)/object.denominador),aux)\n end", "def /(object)\n #multiplica numerador con numerador y denominador con denominador\n Fraccion.new(@numerador*object.denominador,@denominador*object.numerador)\n end", "def use_rationals\n r1 = MyRational.new(3, 4)\n r2 = r1 + r1 + MyRational.new(-5, 2)\n puts r2.to_s\n (r2.add! r1).add! (MyRational.new(1, -4))\n puts r2.to_s\n puts r2.to_s2\n puts r2.to_s3\nend", "def /(other)\n\t\tRacional.new(num*other.denom,denom*other.num)\n\tend", "def test_Complex_InstanceMethods_to_r\n\t\tassert_equal(Rational('5/2'), Complex(2.5, 0).to_r)\n\tend", "def -@\n\t\tRacional.new(-denom, num)\t\n\tend", "def - m2\n return magnitude amount - m2.amount if m2.quantity == quantity.relative\n return quantity.relative.magnitude( amount - m2.amount ) if\n quantity == m2.quantity\n return self if m2.equal? SY::ZERO\n # o1, o2 = m2.coerce( self )\n # return o1 - o2\n raise( SY::QuantityError, \"Unable to perform #{quantity} - #{m2.quantity}!\" )\n end", "def subtract_term_from_fraction\n\treturn add_fraction_and_term(fraction, flip_sign_on_fraction(term))\nend", "def / other\n other = Fraction.new(other) if other.instance_of? Fixnum\n self * other.inv\n end", "def - b\n 2.plus self.plus(b)\n end", "def -(other)\n if other.is_a?(Value)\n lcm_div = @div.lcm(other.div)\n Value.new((@val * (lcm_div / @div)) - (other.val * (lcm_div / other.div)), lcm_div)\n elsif other.is_a?(Numeric)\n to_f - other\n else\n raise \"Unexpected argument\"\n end\n end", "def diff=(o); end", "def use_rationals\n\tr1 = MyRational.new(3, 4)\n\tr2 = r1 + r1 + MyRational.new(-5, 2)\n\tputs r2.to_s\n\n\t(r2.add! r1).add! (MyRational.new(1, -4))\n\tputs r2.to_s\nend", "def test_Rational_InstanceMethods_fdiv\n\t\t# assert_equal(11/4, Rational(\"11/2\")/2)\n\t\tassert_equal(2.75, Rational(\"11/2\").fdiv(2))\n\tend", "def /(other)\n Fraccion.new(@num * other.denom, @denom * other.num)\n end", "def **(b)\n b = b.symdescfy\n case b\n when Infinity\n b\n when Int\n return Ratio.new(@numerator ** b.value, @denominator ** b.value)\n else\n super\n end\n end", "def test_Rational_ArithmeticOperations\n\t\tassert_equal(1.0, Rational(\"1/2\") + Rational(\"1/2\"))\n\t\tassert_equal(0.0, Rational(\"1/2\") - Rational(\"1/2\"))\n\t\tassert_equal(0.25, Rational(\"1/2\") * Rational(\"1/2\"))\n\t\tassert_equal(1.0, Rational(\"1/2\") / Rational(\"1/2\"))\n\t\tassert_equal(0, Rational(\"1/2\") % Rational(\"1/2\"))\n\t\tassert_equal(4.0, Rational(\"2\") ** Rational(\"2\"))\n\t\t# assert_equal(1, -@ Rational(\"2\"))\n\tend", "def fraction_calculator fraction_one, fraction_two, operator\n num_one = Rational(fraction_one)\n num_two = Rational(fraction_two)\n \n final_result = case operator\n when '/' then num_one / num_two\n when '*' then num_one * num_two\n when '+' then num_one + num_two\n when '-' then num_one - num_two\n end\n\n String(final_result)\n\n print String(final_result)\n\nend", "def +(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj)\n return self - obj.val if obj.is_a? Negative\n return Prod.new(Number.new(2),self) if self == obj\n lft = (obj.is_a? Prod) ? (self.left + obj.left) : (self.left + Number.new(1))\n return Prod.new(lft,self.right) if self =~ obj\n return Sum.new(self,obj).reduce\n end", "def test_Rational_InstanceMethods_to_f\n\t\tassert_equal(9.25, Rational(\"37/4\").to_f)\n\tend", "def subtract_fraction_from_term(fraction, term)\n\treturn add_fraction_and_term(flip_sign_on_fraction(fraction), term)\nend", "def /(other)\n @a=other.b*@a\n @b=other.a*@b\n self.to_s #devuelve el resultado como cadena. la operacion modifica el valor del objeto.\n end", "def demongoize(object)\n new(value_of(object))\n end", "def test_rational_inspect\n assert_respond_to(@rat1, :inspect)\n assert_equal(\"Rational(3, 4)\", @rat1.inspect)\n assert_equal(\"Rational(0, 1)\", @rat4.inspect) # Reduced\n assert_equal(\"Rational(9, 1)\", @rat5.inspect)\n end", "def subtract_fraction_from_fraction(frac1, frac2)\n\treturn add_fraction_and_fraction(frac2, flip_sign_on_fraction(frac1))\nend", "def test_should_be_able_to_subtract\n currency1 = Currency.new(\"USD\", 1.0)\n currency2 = Currency.new(\"USD\", 5.0)\n assert_equal Currency.new(\"USD\", 4.0), currency2.-(currency1)\n end", "def vanilla_object(object)\n type = get_type(object)\n\n # I wanted to call the datatypes String and Float, but VString and VFloat\n # is needed to be able to make a vanilla object. \n if type == String\n type = VString\n elsif type == Float\n type = VFloat\n end\n\n vanilla_object = type.new(object)\n\n return vanilla_object\n end", "def -@\nFraccionario.new(@num*-1, @den)\nend", "def - (other)\n if other.kind_of?(Complex)\n re = @real - other.real\n im = @image - other.image\n Complex(re, im)\n elsif Complex.generic?(other)\n Complex(@real - other, @image)\n else\n x , y = other.coerce(self)\n x - y\n end\n end", "def subtract m2\n return magnitude( amount + m2.amount ) if quantity == m2.quantity\n return self if m2.equal? SY::ZERO\n # o1, o2 = m2.coerce( self )\n # return o1.subtract o2\n raise( SY::QuantityError, \"Unable to perform #add with #{m2.quantity}!\" )\n end", "def -(another_currency)\n\n #converts the given instance in the actual currency and substracts the amounts\n amount= @amount_bigdecimal - another_currency.convert_to(@currency).amount\n\n #returns the result as a new instance\n Xchange.new(amount,@currency)\n\n end", "def operate(operator, other)\n if other.is_a?(Numeric)\n new(value.send(operator, other), unit)\n elsif other.respond_to?(:composition)\n if compatible_with?(other)\n converted = other.convert_to(unit)\n new(value.send(operator, converted.value),\n unit.send(operator, converted.unit))\n else\n new(value.send(operator, other.value),\n unit.send(operator, other.unit))\n end\n end\n end", "def convert(base)\n self.class.new(numerator, denominator, base)\n end", "def -(rvalue)\n values = coerce(rvalue)\n return ( values[1] - values[0])\n end", "def test_Rational_InstanceMethods_rationalize\n\t\tassert_equal(Rational(\"884279719003555/281474976710656\").to_r, Math::PI.to_r)\n\t\t# TODO, Need add some testcases.\n\t\t# r.rationalize #=>(884279719003555/281474976710656)\n\t\t# r.rationalize(0.01)#=>(22/7)\n\tend", "def divide!(other)\n init_base_quantities(other.reciprocalize.to_hash)\n get_description\n return self\n end", "def reciprocal\nFraccionario.new(@den, @num)\nend", "def Complex(a, b = 0)\n if b == 0 and (a.kind_of?(Complex) or defined? Complex::Unify)\n a\n else\n Complex.new( a.real-b.imag, a.imag+b.real )\n end\nend", "def test_Rational_InstanceMethods_denominator\n\t\tassert_equal(3, Rational(\"2/3\").denominator)\n\t\tassert_equal(365, Rational(\"343434/365\").denominator)\n\tend", "def test_Rational_InstanceMethods_round\n\t\tassert_equal(3, Rational(\"22/7\").round)\n\t\tassert_equal(-3, Rational(\"-22/7\").round)\n\tend", "def -(other)\n raise TypeError unless other.is_a?(Money)\n if self.base_currency == other.base_currency\n Money.new(amount - other.amount, base_currency)\n else\n Money.new(amount - other.convert_to(self.base_currency).amount, base_currency)\n end\n end", "def to_ref(value)\n result = nil\n if uom_type == 'ref'\n result = value\n elsif uom_type == 'big'\n result = value * ratio\n elsif uom_type == 'small'\n result = value/ratio\n end\n result.to_f\n end", "def test_NilClass_InstanceMethod_rationalize\n\t\t# TODO, undefined method 'rationalize' under ruby 1.9.1p430 \n\t\t# assert_equal((0/1), nil.rationalize)\n\tend", "def minus(subtrahend)\n minuend = self.dup.to_add\n subtrahend = subtrahend.to_add\n ROMAN_CHARS.each_char do |char|\n while minuend.send(\"has_less_#{char}_than\", subtrahend)\n minuend = minuend.borrow_for(char)\n end\n end\n difference = minuend\n subtrahend.each_char do |char|\n difference.sub!(char, \"\")\n end\n RomanNumeral.new(difference)\n end", "def subtract!(rhs)\n subtract rhs, self\n end", "def test_NilClass_InstanceMethod_to_r\n\t\tassert_equal(Rational(0,1), nil.to_r)\n\tend", "def divide!(rhs)\n divide rhs, self\n end", "def test_Rational_InstanceMethods_Comparison\n\t\tassert_equal(0, Rational(\"4/2\") <=> Rational(\"98/49\"))\n\t\tassert_equal(-1, Rational(\"3/4\") <=> 41)\n\t\tassert_equal(0, Rational(\"0\") <=> 0.0)\n\tend", "def diff(objectish = 'HEAD', obj2 = nil)\n Git::Diff.new(self, objectish, obj2)\n end", "def reciprocal ()\n\tFraccion.new(@denominador,@numerador)\n end", "def -(b)\n return self if b == 0\n b = b.symdescfy\n case b\n when Neg\n self + b.argument\n when Sum\n self - b.left - b.right\n when Sub\n self - b.left + b.right\n else\n __sub_else(b) || super\n end\n end", "def *(other)\n\t\tRacional.new(num*other.num,denom*other.denom)\n\tend", "def multiply_fraction_and_fraction(left, right)\n\tnew_numerator = multiply_unknown_terms_or_term_lists(left.numerator, right.numerator)\n\tnew_denominator = multiply_unknown_terms_or_term_lists(left.denominator, right.denominator)\n\treturn Fraction.new(left.line, left.col, numerator: new_numerator, denominator: new_denominator)\nend", "def + other\n other = Fraction.new(other) if other.instance_of? Fixnum\n Fraction.new(@numer * other.denom + other.numer * @denom, @denom * other.denom)\n end", "def subtract_amount(galaxy_id, from_kind, to_kind, from_amount)\n model = subtracted_model(galaxy_id, from_kind, to_kind, from_amount)\n model.save!\n\n model\n end", "def add(rational)\n\n\t\t#\tCopy the second rational\n\t\ttemp = RationalNumber.new(rational.numerator, rational.denominator)\n\n\t\t#\tMake sure we have LCD \n\t\tif not self.denominator == rational.denominator\n\t\t\ttemp.denominator = rational.denominator * self.denominator\n\t\t\ttemp.numerator = rational.numerator * self.denominator\n\t\tend\n\n\t\t#\tNow add...\n\t\tself.numerator = self.numerator + temp.numerator\n\n\t\treturn self\n\tend", "def minimizar(a,b)\n mcd = gcd(a,b)\n aux = Fraccion.new(1,1)\n aux.num = a/mcd\n aux.denom = b/mcd\n return aux\n end", "def minus_with_coercion(other)\n other = other.comparable_time if other.respond_to?(:comparable_time)\n other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)\n end", "def -( other_object )\n\t\tother_dn = other_object.dn\n\t\treturn self.reject {|branch| branch.dn.downcase == other_dn.downcase }\n\tend", "def test_rational_to_s\n assert_respond_to(@rat1, :to_s)\n assert_nothing_raised{ @rat1.to_s }\n assert_kind_of(String, @rat1.to_s)\n assert_equal(\"3/4\", @rat1.to_s)\n assert_equal(\"3/4\", @rat7.to_s)\n end", "def convert_and_assign(obj, symbol)\n success, rexp = convert_to_r_object(obj)\n raise RriException.new(\"Failed to convert ruby object to R object for: #{obj}\") unless success\n simple_assign(symbol, rexp)\n end", "def mediant(other)\n return SternBrocot::Fraction.new(self.numerator+other.numerator, self.denominator+other.denominator)\n end", "def -(o)\n case o\n when Fixnum, Bignum, Float then\n return self + -o\n when Time\n return self.to_f - o.to_f\n else\n raise \"wtf?:\" + t.inspect + \": \" + t.class\n end\n end", "def test_Rational_InstanceMethods_ceil\n\t\tassert_equal(4, Rational(\"22/7\").ceil)\n\t\tassert_equal(-3, Rational(\"-22/7\").ceil)\n\tend", "def test_Rational_InstanceMethods_Compare2\n\t\tassert_equal(true, Rational(\"2\") == Rational(\"2\"))\n\t\tassert_equal(false, Rational(\"1\") == Rational(\"2\"))\n\tend", "def remove_reciprocal_object(opts, o)\n return unless reciprocal = opts.reciprocal\n if opts.reciprocal_array?\n if array = o.associations[reciprocal]\n array.delete_if{|x| self === x}\n end\n else\n o.associations[reciprocal] = nil\n end\n end", "def + r\r\n ans = MyRational.new(@num,@den)\r\n ans.add! r\r\n ans\r\n end", "def simplificar (fraccion)\n mcd = gcd(fraccion.numerador, fraccion.denominador)\n Fraccion.new( fraccion.numerador/mcd , fraccion.denominador/mcd)\n \n \n end", "def diffObject(num)\n\tputs (\"#{num.object_id}\")\n\tnum=num+2\n\tputs (\"#{num.object_id}\")\n\treturn num\nend", "def /(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj) || \n (obj == 0) || \n (obj.is_a? Number) ||\n (obj == P_Infinity) ||\n (obj == M_Infinity)\n if self =~ obj\n ret = self.left\n ret.top = self.top\n return ret\n end \n if (obj.is_a? Number) || (obj == P_Infinity) || (obj == M_Infinity)\n lft = self.left\n lft.top = true\n lft /= obj\n puts lft\n return Prod.new(lft,self.right).reduce unless lft == nil\n return nil unless self.top\n end\n return Div.new(self,obj).reduce\n end", "def test_Complex_InstanceMethods_denominator\n\t\tassert_equal(12, Complex(\"1/3+1/4i\").denominator)\n\t\tassert_equal(1, Complex(-2, 4).denominator)\n\tend", "def subtract(galaxy_id, from_kind, to_kind, from_amount,\n cancellation_shift, cancellation_amount, cancellation_total_amount)\n model = subtracted_model(galaxy_id, from_kind, to_kind, from_amount)\n\n # To prevent division by zero or negative numbers.\n market_amount_left = model.from_amount < 1 ? 1 : model.from_amount\n model.to_rate += cancellation_shift *\n # How much of your offer has left.\n (from_amount.to_f / cancellation_amount) *\n # How much market has shifted.\n (cancellation_total_amount.to_f / market_amount_left)\n model.save!\n\n model\n end", "def test_Complex_InstanceMethods_rationalize\n\t\tassert_equal(2.5, Complex(2.5, 0))\n\tend", "def convert_to other_unit\n return dup if unit == other_unit\n\n unless self.class.rules.key? other_unit\n raise TypeError, \"no such unit #{self.class}:#{other_unit}\"\n end\n\n if self.class.rules[unit][:rules]\n amount = self.class.follow_rules normalized_amount, unit, other_unit\n return self.class.new amount, other_unit\n else\n amount = normalized_amount\n end\n\n new = self.class.new amount\n new.unit = other_unit\n new\n end", "def / (other)\n if other.kind_of?(Complex)\n self*other.conjugate/other.abs2\n elsif Complex.generic?(other)\n Complex(@real/other, @image/other)\n else\n x, y = other.coerce(self)\n x/y\n end\n end", "def -@\n\t\tself.class.new(-@a, -@b)\n\tend", "def transform_Object(o, scope)\n raise IllegalRelationshipOperandError.new(o)\n end", "def ==(b)\n case b\n when Rational, Ratio\n (@numerator == b.numerator) &&\n (@denominator == b.denominator)\n when Float\n self == b.symdescfy\n else\n false\n end\n end", "def remove_reciprocal_object(opts, o)\n return unless reciprocal = opts.reciprocal\n if opts.reciprocal_array?\n if array = o.associations[reciprocal]\n array.delete_if{|x| self === x}\n end\n else\n o.associations[reciprocal] = nil\n end\n end", "def -(temp)\n self.class.new(in_native - numericalize(temp))\n end", "def test_Complex_InstanceMethods_fdiv\n\t\tc1 = Complex(1, 2)\n\t\tc2 = Complex(2, 2)\n\t\tassert_equal(Complex(\"3/4+1/4i\"), c1/c2)\n\t\t# TODO, why? assert_equal(Complex(0.75,0.25), c1.fdiv(c2))\n\tend", "def +(other)\n\t\tRacional.new(num*other.denom + other.num*denom, denom*other.denom)\n\tend", "def resta (other)\n\t\tres=Fraccion.new(0,0)\n\t\tif @y == other.y # igual denominador\n\t\t\tres.x= @x - other.x\t\t\n\t\t\tres.y= @y\t\n\t\telse\t\t # distinto denominador\n\t\t\t\n\t\t\tres.y=mcm(@y, other.y)\t\t\n\t\t\tres.x=((@x *res.y)/@y)-((other.x * res.y)/other.y) \n\t\tend\n\treturn res\n\tend" ]
[ "0.5755978", "0.5724076", "0.5541179", "0.5344188", "0.5329774", "0.5329774", "0.53283256", "0.531676", "0.53081554", "0.5223408", "0.51430726", "0.49782917", "0.4977166", "0.48819825", "0.4876806", "0.487545", "0.4857826", "0.48467252", "0.48393816", "0.4826154", "0.4767695", "0.4744865", "0.47367996", "0.47288132", "0.47194692", "0.4708898", "0.47044334", "0.468933", "0.46892244", "0.46550438", "0.46500033", "0.4645347", "0.46309498", "0.4615363", "0.46122545", "0.45971036", "0.4595392", "0.4586864", "0.45612547", "0.45575127", "0.45554098", "0.45478538", "0.45448467", "0.45374158", "0.45369712", "0.4535588", "0.45336848", "0.4525505", "0.45153743", "0.45117894", "0.4505919", "0.4504733", "0.45039022", "0.44996348", "0.44822448", "0.44796282", "0.44723988", "0.44483256", "0.44387493", "0.44322875", "0.44315892", "0.44272912", "0.442605", "0.44258136", "0.44182998", "0.44079256", "0.44039157", "0.43999347", "0.43969962", "0.4393874", "0.43899393", "0.4379537", "0.43741086", "0.4372549", "0.43713707", "0.4370959", "0.43688282", "0.4361063", "0.43573987", "0.43565428", "0.4336695", "0.43357185", "0.43353334", "0.4331988", "0.4327349", "0.43249348", "0.42948174", "0.4293792", "0.42873687", "0.4286102", "0.4282796", "0.42817843", "0.42816755", "0.42784938", "0.4276218", "0.4272382", "0.42690462", "0.42645228", "0.4251822", "0.42474306" ]
0.4609807
35
:callseq: ratio obj > new_obj Performs a symbolic power between a symbolic rational and `obj`, returning a new symbolic object if the operation creates a new tree branch, or a symbolic number if `obj` is a SymDesc::Number. Simplification is automatic. If b is not a symbolic object, a conversion is attempted
def **(b) b = b.symdescfy case b when Infinity b when Int return Ratio.new(@numerator ** b.value, @denominator ** b.value) else super end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def /(object)\n #multiplica numerador con numerador y denominador con denominador\n Fraccion.new(@numerador*object.denominador,@denominador*object.numerador)\n end", "def test_Rational_InstanceMethods_to_r\n\t\tassert_equal(Rational(\"2\"), Rational(\"4/2\").to_r)\n\tend", "def coerce(other)\n if other.is_a? Numeric\n [Rational.new(other, 1), self]\n else\n puts \"(Rational failed to coerce object of type #{other.class})\"\n super\n end\n end", "def +(object)\n aux=mcm(@denominador,object.denominador)\n Fraccion.new((((aux*@numerador)/@denominador)+(aux*object.numerador)/object.denominador),aux)\n end", "def use_rationals\r\n r1 = MyRational.new(3,4)\r\n r2 = r1 + r1 + MyRational.new(-5,2)\r\n puts r2.to_s\r\n (r2.add! r1).add! (MyRational.new(1,-4))\r\n puts r2.to_s\r\n puts r2.to_s2\r\n puts r2.to_s3\r\nend", "def use_rationals\n r1 = MyRational.new(3, 4)\n r2 = r1 + r1 + MyRational.new(-5, 2)\n puts r2.to_s\n (r2.add! r1).add! (MyRational.new(1, -4))\n puts r2.to_s\n puts r2.to_s2\n puts r2.to_s3\nend", "def **(obj)\n return nil unless (self.top) || (self == obj) || (obj == 0) || (obj.is_a? Number) ||\n (obj == P_Infinity) ||\n (obj == M_Infinity)\n \n if (self.left != P_Infinity) || (self.left != M_Infinity) || (self.right != P_Infinity) || (self.right != M_Infinity)\n return Number.new 1 if obj == 0\n else\n raise \"Math Error: ∞^0\" if obj == 0\n end\n if (obj.is_a? Number) || (obj == P_infinity) || (obj == M_Infinity)\n lft = self.left ** obj\n return Prod.new(lft,Pow.new(self.right,obj)).reduce unless lft == nil\n return nil unless self.top\n end\n return Pow.new(self,obj).reduce\n end", "def convert(base)\n self.class.new(numerator, denominator, base)\n end", "def -(object)\n aux=mcm(@denominador,object.denominador)\n Fraccion.new((((aux*@numerador)/@denominador)-(aux*object.numerador)/object.denominador),aux)\n end", "def *(object)\n #multiplica numerador con numerador y denominador con denominador\n Fraccion.new(@numerador*object.numerador,@denominador*object.denominador)\n end", "def /(other)\n\t\tRacional.new(num*other.denom,denom*other.num)\n\tend", "def convert_and_assign(obj, symbol)\n success, rexp = convert_to_r_object(obj)\n raise RriException.new(\"Failed to convert ruby object to R object for: #{obj}\") unless success\n simple_assign(symbol, rexp)\n end", "def *(obj) \n return nil unless (self.top) || (self == obj) || (self =~ obj) || \n (obj == 0) || \n (obj.is_a? Number) || \n (obj == P_Infinity) || \n (obj == M_Infinity)\n return Pow.new(self,Number.new(2)).reduce if self == obj\n chk = first_chk(obj)\n return chk unless chk == nil\n return self * obj.left * obj.right if obj.is_a? Prod\n chk = second_chk(obj)\n return chk unless chk == nil\n return Prod.new(self,obj).reduce unless obj.is_a? Number\n return Prod.new(obj,self).reduce\n end", "def test_rational_coerce\n assert_respond_to(@rat1, :coerce)\n assert_nothing_raised{ @rat1.coerce(9) }\n assert_nothing_raised{ @rat1.coerce(0.5) }\n #assert_equal(Rational(9,1), @rat1.coerce(9))\n end", "def /(other)\n RDF::Literal(to_d / (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n end", "def use_rationals\n\tr1 = MyRational.new(3, 4)\n\tr2 = r1 + r1 + MyRational.new(-5, 2)\n\tputs r2.to_s\n\n\t(r2.add! r1).add! (MyRational.new(1, -4))\n\tputs r2.to_s\nend", "def test_Complex_InstanceMethods_to_r\n\t\tassert_equal(Rational('5/2'), Complex(2.5, 0).to_r)\n\tend", "def / other\n other = Fraction.new(other) if other.instance_of? Fixnum\n self * other.inv\n end", "def + r\r\n ans = MyRational.new(@num,@den)\r\n ans.add! r\r\n ans\r\n end", "def /(other)\n @a=other.b*@a\n @b=other.a*@b\n self.to_s #devuelve el resultado como cadena. la operacion modifica el valor del objeto.\n end", "def +(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj)\n return self - obj.val if obj.is_a? Negative\n return Prod.new(Number.new(2),self) if self == obj\n lft = (obj.is_a? Prod) ? (self.left + obj.left) : (self.left + Number.new(1))\n return Prod.new(lft,self.right) if self =~ obj\n return Sum.new(self,obj).reduce\n end", "def object_of_power; end", "def /(other)\n Fraccion.new(@num * other.denom, @denom * other.num)\n end", "def vanilla_object(object)\n type = get_type(object)\n\n # I wanted to call the datatypes String and Float, but VString and VFloat\n # is needed to be able to make a vanilla object. \n if type == String\n type = VString\n elsif type == Float\n type = VFloat\n end\n\n vanilla_object = type.new(object)\n\n return vanilla_object\n end", "def test_Rational_InstanceMethods_to_f\n\t\tassert_equal(9.25, Rational(\"37/4\").to_f)\n\tend", "def *(other)\n\t\tRacional.new(num*other.num,denom*other.denom)\n\tend", "def test_Rational_InstanceMethods_rationalize\n\t\tassert_equal(Rational(\"884279719003555/281474976710656\").to_r, Math::PI.to_r)\n\t\t# TODO, Need add some testcases.\n\t\t# r.rationalize #=>(884279719003555/281474976710656)\n\t\t# r.rationalize(0.01)#=>(22/7)\n\tend", "def convert(other)\n raise \"Units #{self} and #{other} are not commensurable\" unless commensurable?(other)\n return Rational(1,1) if self == other\n self.factor / other.factor\n end", "def /(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj) || \n (obj == 0) || \n (obj.is_a? Number) ||\n (obj == P_Infinity) ||\n (obj == M_Infinity)\n if self =~ obj\n ret = self.left\n ret.top = self.top\n return ret\n end \n if (obj.is_a? Number) || (obj == P_Infinity) || (obj == M_Infinity)\n lft = self.left\n lft.top = true\n lft /= obj\n puts lft\n return Prod.new(lft,self.right).reduce unless lft == nil\n return nil unless self.top\n end\n return Div.new(self,obj).reduce\n end", "def + r\n ans = MyRational.new(@num, @den)\n ans.add! r\n ans\n end", "def test_Rational_ArithmeticOperations\n\t\tassert_equal(1.0, Rational(\"1/2\") + Rational(\"1/2\"))\n\t\tassert_equal(0.0, Rational(\"1/2\") - Rational(\"1/2\"))\n\t\tassert_equal(0.25, Rational(\"1/2\") * Rational(\"1/2\"))\n\t\tassert_equal(1.0, Rational(\"1/2\") / Rational(\"1/2\"))\n\t\tassert_equal(0, Rational(\"1/2\") % Rational(\"1/2\"))\n\t\tassert_equal(4.0, Rational(\"2\") ** Rational(\"2\"))\n\t\t# assert_equal(1, -@ Rational(\"2\"))\n\tend", "def + other\n other = Fraction.new(other) if other.instance_of? Fixnum\n Fraction.new(@numer * other.denom + other.numer * @denom, @denom * other.denom)\n end", "def first_chk(obj)\n if (self =~ obj) && (obj.is_a? Pow)\n if self.right.is_a? Pow\n myExp, objExp = self.right.right, obj.right\n myExp.top, objExp.top = true, true\n exp = myExp + objExp\n rht = Pow.new(obj.left,exp).reduce\n return Prod.new(self.left,rht).reduce\n end\n objExp = obj.right\n objExp.top = true\n objExp += Number.new 1\n rht = Pow.new(obj.left,objExp).reduce\n return Prod.new(self.left,rht).reduce\n elsif self =~ obj\n return Prod.new(self.left,Pow.new(self.right,Number.new(2))).reduce\n end\n return nil\n end", "def test_rational_inspect\n assert_respond_to(@rat1, :inspect)\n assert_equal(\"Rational(3, 4)\", @rat1.inspect)\n assert_equal(\"Rational(0, 1)\", @rat4.inspect) # Reduced\n assert_equal(\"Rational(9, 1)\", @rat5.inspect)\n end", "def test_Rational_InstanceMethods_floor\n\t\tassert_equal(3, Rational(\"22/7\").floor)\n\t\tassert_equal(-4, Rational(\"-22/7\").floor)\n\tend", "def rationalize(eps = nil)\n eps ? Q.new(to_r.rationalize(eps)) : self\n end", "def test_Rational_InstanceMethods_fdiv\n\t\t# assert_equal(11/4, Rational(\"11/2\")/2)\n\t\tassert_equal(2.75, Rational(\"11/2\").fdiv(2))\n\tend", "def multiply_fraction_and_fraction(left, right)\n\tnew_numerator = multiply_unknown_terms_or_term_lists(left.numerator, right.numerator)\n\tnew_denominator = multiply_unknown_terms_or_term_lists(left.denominator, right.denominator)\n\treturn Fraction.new(left.line, left.col, numerator: new_numerator, denominator: new_denominator)\nend", "def new_with_value(value)\n RObject.new self, value\n end", "def add(rational)\n\n\t\t#\tCopy the second rational\n\t\ttemp = RationalNumber.new(rational.numerator, rational.denominator)\n\n\t\t#\tMake sure we have LCD \n\t\tif not self.denominator == rational.denominator\n\t\t\ttemp.denominator = rational.denominator * self.denominator\n\t\t\ttemp.numerator = rational.numerator * self.denominator\n\t\tend\n\n\t\t#\tNow add...\n\t\tself.numerator = self.numerator + temp.numerator\n\n\t\treturn self\n\tend", "def multiply_fraction_and_term(fraction, term)\n\tnew_numerator = multiply_unknown_terms_or_term_lists(fraction.numerator, term)\n\treturn Fraction.new(fraction.line, fraction.col, numerator: new_numerator, denominator: new_denominator)\nend", "def -(obj)\n return nil unless (self.top) || (self == obj) || (self =~ obj)\n return self + obj.val if obj.is_a? Negative\n return Number.new 0 if self == obj\n lft = ((self =~ obj) && (obj.is_a? Prod)) ? (self.left - obj.left) : (self.left - Number.new(1))\n return Prod.new(lft,self.right) if self =~ obj\n return Diff.new(self,obj)\n end", "def fraction_calculator fraction_one, fraction_two, operator\n num_one = Rational(fraction_one)\n num_two = Rational(fraction_two)\n \n final_result = case operator\n when '/' then num_one / num_two\n when '*' then num_one * num_two\n when '+' then num_one + num_two\n when '-' then num_one - num_two\n end\n\n String(final_result)\n\n print String(final_result)\n\nend", "def test_Rational_InstanceMethods_round\n\t\tassert_equal(3, Rational(\"22/7\").round)\n\t\tassert_equal(-3, Rational(\"-22/7\").round)\n\tend", "def +(b)\n return self if b == 0\n return Int.new(@value + b) if b.is_a? Integer\n b = b.symdescfy\n case b\n when Infinity\n b\n when Ratio, BinaryOp\n b + self\n when Int\n Int.new(@value + b.value)\n else\n super\n end\n end", "def minimizar(a,b)\n mcd = gcd(a,b)\n aux = Fraccion.new(1,1)\n aux.num = a/mcd\n aux.denom = b/mcd\n return aux\n end", "def test_Rational_InstanceMethods_Comparison\n\t\tassert_equal(0, Rational(\"4/2\") <=> Rational(\"98/49\"))\n\t\tassert_equal(-1, Rational(\"3/4\") <=> 41)\n\t\tassert_equal(0, Rational(\"0\") <=> 0.0)\n\tend", "def to_foorth_r\r\n self.rationalize\r\n end", "def * other\n other = Fraction.new(other) if other.instance_of? Fixnum\n Fraction.new(@numer * other.numer, @denom * other.denom)\n end", "def test_Rational_InstanceMethods_numerator\n\t\tassert_equal(2, Rational(\"2/3\").numerator)\n\t\t# TODO, assert_equal(1978, Rational(\"1978/840\").numerator)\n\tend", "def new_from_graph(graph, objects = {}, pattern = nil)\n # Default to getting the first object in the graph with the same RDF type as this class\n pattern ||= [nil, RDF.type, resource_class.type]\n\n root_subject = graph.query(pattern).first_subject\n return unless root_subject\n\n # If the subject is an existing model, just retrieve it\n new_object = Ladder::Resource.from_uri(root_subject) if root_subject.is_a? RDF::URI\n new_object ||= new\n\n # Add object to stack for recursion\n objects[root_subject] = new_object\n\n subgraph = graph.query([root_subject])\n\n subgraph.each_statement do |statement|\n # Group statements for this predicate\n stmts = subgraph.query([root_subject, statement.predicate])\n\n if stmts.size > 1\n # We have already set this value in a prior pass\n next if new_object.read_attribute new_object.field_from_predicate statement.predicate\n\n # If there are multiple statements for this predicate, pass an array\n statement.object = RDF::Node.new\n new_object.send(:<<, statement) { stmts.objects.to_a } # TODO: implement #set_value instead\n\n elsif statement.object.is_a? RDF::Node\n next if objects[statement.object]\n\n # If the object is a BNode, dereference the relation\n objects[statement.object] = new_object.send(:<<, statement) do # TODO: implement #set_value instead\n klass = new_object.klass_from_predicate(statement.predicate)\n klass.new_from_graph(graph, objects, [statement.object]) if klass\n end\n\n else new_object << statement\n end\n end # end each_statement\n\n new_object\n end", "def operate(operator, other)\n if other.is_a?(Numeric)\n new(value.send(operator, other), unit)\n elsif other.respond_to?(:composition)\n if compatible_with?(other)\n converted = other.convert_to(unit)\n new(value.send(operator, converted.value),\n unit.send(operator, converted.unit))\n else\n new(value.send(operator, other.value),\n unit.send(operator, other.unit))\n end\n end\n end", "def test_rational_to_s\n assert_respond_to(@rat1, :to_s)\n assert_nothing_raised{ @rat1.to_s }\n assert_kind_of(String, @rat1.to_s)\n assert_equal(\"3/4\", @rat1.to_s)\n assert_equal(\"3/4\", @rat7.to_s)\n end", "def +(r)\n case r\n when Integer\n self + Fraction[r]\n when Fraction\n Fraction[ r.last*first + r.first*last, r.last*last ]\n else\n raise TypeError.new(\"Sorry, I can't add a Fraction and a #{r.class}. :(\")\n end\n end", "def %(other)\n\t\tRacional.new(num%denom, other.num%other.denom)\n\tend", "def test_NilClass_InstanceMethod_to_r\n\t\tassert_equal(Rational(0,1), nil.to_r)\n\tend", "def /(b)\n b = b.symdescfy\n case b\n when Number\n __div_number(b)\n when Infinity\n ZERO\n else\n super\n end\n end", "def transform_Object(o, scope)\n raise IllegalRelationshipOperandError.new(o)\n end", "def ==(b)\n case b\n when Rational, Ratio\n (@numerator == b.numerator) &&\n (@denominator == b.denominator)\n when Float\n self == b.symdescfy\n else\n false\n end\n end", "def /(n)\n return self.class.new(@val/n) if Numeric === n\n raise TypeError, \"Expected Numeric\"\n end", "def mediant(other)\n return SternBrocot::Fraction.new(self.numerator+other.numerator, self.denominator+other.denominator)\n end", "def +(obj)\n case obj\n when Numeric\n self.class.new(@val + obj)\n when self.class\n self.class.new(@val + obj.val)\n else\n raise TypeError, \"#{self.class} cannot be added to #{obj.class}\"\n end\n end", "def test_Rational_InstanceMethods_denominator\n\t\tassert_equal(3, Rational(\"2/3\").denominator)\n\t\tassert_equal(365, Rational(\"343434/365\").denominator)\n\tend", "def +(other)\n\t\tRacional.new(num*other.denom + other.num*denom, denom*other.denom)\n\tend", "def test_NilClass_InstanceMethod_rationalize\n\t\t# TODO, undefined method 'rationalize' under ruby 1.9.1p430 \n\t\t# assert_equal((0/1), nil.rationalize)\n\tend", "def rationalize=(rationalize)\n assert_unloaded\n @rationalize = rationalize\n end", "def mul\r\n node = unary()\r\n\r\n loop do\r\n if consume(\"*\")\r\n node = new_binary(ND_MUL, node, unary())\r\n elsif consume(\"/\")\r\n node = new_binary(ND_DIV, node, unary())\r\n else\r\n return node\r\n end\r\n end\r\nend", "def divide!(rhs)\n divide rhs, self\n end", "def to_b\n lft = self.left.to_b if self.left.is_a? Pow or !(self.left.is_a? BinaryOp)\n lft = \"(#{self.left.to_b})\" unless self.left.is_a? Pow or !(self.left.is_a? BinaryOp)\n rht = self.right.to_b if self.right.is_a? Pow or !(self.right.is_a? BinaryOp)\n rht = \"(#{self.right.to_b})\" unless self.right.is_a? Pow or !(self.right.is_a? BinaryOp)\n return \"#{lft}*#{rht}\"\n end", "def *(b)\n b = b.symdescfy\n case b\n when Number\n __prod_number(b)\n when Infinity\n b\n when Prod, Div\n b * self\n else\n self == 0 ? self : super\n end\n end", "def - other\n other = Fraction.new(other) if other.instance_of? Fixnum\n Fraction.new(@numer * other.denom - other.numer * @denom, @denom * other.denom)\n end", "def *(other)\n if self.class == Double || [Double, ::Float].include?(other.class)\n RDF::Literal::Double.new(to_f * other.to_f)\n elsif ((self.class == RDF::Literal::Float || other.class == RDF::Literal::Float) rescue false)\n RDF::Literal::Float.new(to_f * other.to_f)\n elsif self.class == Decimal || other.class == Decimal\n RDF::Literal::Decimal.new(to_d * (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n else\n RDF::Literal::Integer.new(to_i * other.to_i)\n end\n end", "def *(other)\n if self.class == Double || [Double, ::Float].include?(other.class)\n RDF::Literal::Double.new(to_f * other.to_f)\n elsif ((self.class == RDF::Literal::Float || other.class == RDF::Literal::Float) rescue false)\n RDF::Literal::Float.new(to_f * other.to_f)\n elsif self.class == Decimal || other.class == Decimal\n RDF::Literal::Decimal.new(to_d * (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n else\n RDF::Literal::Integer.new(to_i * other.to_i)\n end\n end", "def convert_object(value)\n value = value.object if value.kind_of? RDF::Literal\n value = make_node(value) if value.kind_of? RDF::Resource\n value\n end", "def divide(other)\n clone.divide! other\n end", "def to_r\n return Rational(numerator,denominator)\n end", "def new_object\n @object = scope.new params[object_name.to_sym]\n set_instance\n end", "def * r\n if r.is_a? Ratio\n # Default response. All elsifs should point toward this.\n Ratio.from_factors(self.factors + r.factors)\n elsif r.is_a? Numeric\n self * Ratio[r, 1]\n elsif r.is_a? NArray\n self * Ratio[*r].factors\n else\n raise ArgumentError.new(\"Supplied class #{r.class} to HD::Ratio.*\")\n end\n end", "def /(other)\n# self.class.new(self.x / num, self.y / num, self.z)\n if other.respond_to? :x and other.respond_to? :y and other.respond_to? :z\n self.class.new(self.x.to_f / other.x.to_f, self.y.to_f / other.y.to_f, self.z.to_f / other.z.to_f)\n elsif other.respond_to? :to_a\n self / self.class.from_array(other.to_a)\n else\n self.class.new(self.x.to_f / other.to_f, self.y.to_f / other.to_f, self.z.to_f / other.to_f)\n end\n end", "def *(other)\n RDF::Literal(to_d * (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n end", "def numerator\n\t\tan = @a.numerator\n\t\tbn = @b.numerator\n\t\tad = @a.denominator\n\t\tbd = @b.denominator\n\t\tabd = ad.lcm(bd)\n\t\t__new__(an * (abd / ad), bn * (abd / bd))\n\tend", "def to_ref(value)\n result = nil\n if uom_type == 'ref'\n result = value\n elsif uom_type == 'big'\n result = value * ratio\n elsif uom_type == 'small'\n result = value/ratio\n end\n result.to_f\n end", "def round!(target: COMMON_SCALE_FACTORS, direction: 0)\n # Scale can no longer be considered to be generated from string.\n @source_string = nil\n\n # If the scale factor is smaller than 1, round its inverse to an sensible\n # number. In 1:x, x should be the sensible value, not its inverse.\n downsize = @factor < 1\n @factor = 1 / @factor if downsize\n direction = -direction if downsize\n\n coefficient, exponent = split_number(@factor)\n coefficient = round_to_target(coefficient, target, direction)\n\n # Sometimes Rational is included and overrides Ruby core math functionality.\n # Ensure result is float to honor API contract and avoid unexpected\n # consequence elsewhere.\n @factor = (coefficient * 10**exponent).to_f\n\n @factor = 1 / @factor if downsize\n\n self\n end", "def reduce_mul_operator_1(_production, _range, _tokens, theChildren)\n return CalcDivideNode.new(theChildren[0].symbol)\n end", "def test_Complex_InstanceMethods_rationalize\n\t\tassert_equal(2.5, Complex(2.5, 0))\n\tend", "def _pack_object( obj ) \n klass = obj.class\n if klass == String\n obj\n elsif obj.respond_to?(:to_aqua) # Types requiring initialization\n obj.to_aqua( self )\n elsif obj.aquatic? && obj != self\n if obj._embed_me == true\n obj._pack\n else\n _build_stub( obj ) \n end \n else # other object without initializations\n _pack_vanilla( obj )\n end \n end", "def +(other)\n if other.class == Fraccion\n Fraccion.new(@num*other.denom + other.num*@denom , @denom*other.denom)\n else\n Fraccion.new(@num + other*@denom , @denom)\n end\n end", "def reciprocal\nFraccionario.new(@den, @num)\nend", "def /(other)\n\tself.num / other.num\nend", "def Fraction(*args)\n Fraction.new(*args)\nend", "def divide!(other)\n init_base_quantities(other.reciprocalize.to_hash)\n get_description\n return self\n end", "def multiplication\n expr = unary\n\n while match?(:slash, :star)\n operator = previous\n right = unary\n expr = Ringo::Binary.new(expr, operator, right)\n end\n\n return expr\n end", "def -(other)\n n=mcm(b, other.b)\n @a=(@a*n/@b)-(other.a*n/other.b)\n @b=n\n self.to_s #devuelve el resultado como cadena. la operacion modifica el valor del objeto.\n \n end", "def / number\n self.class[ self.with_values do |val|\n raise TErr, \"Compositions with rational exponents \" +\n \"not implemented!\" if val % number != 0\n val / number\n end ]\n end", "def test_Rational_InstanceMethods_ceil\n\t\tassert_equal(4, Rational(\"22/7\").ceil)\n\t\tassert_equal(-3, Rational(\"-22/7\").ceil)\n\tend", "def get_new_obj(obj, type='query')\n tmp_obj = self.new\n tmp_obj.send 'object'.to_sym, \"{#{obj['object'].to_s}}\"\n tmp_obj.send 'source_id'.to_sym, get_source_id\n tmp_obj.send 'update_type'.to_sym, type\n tmp_obj\n end", "def /(rvalue)\n values = coerce(rvalue)\n return ( values[1] / values[0])\n end", "def ** (other)\n if other == 0\n return Complex(1)\n end\n if other.kind_of?(Complex)\n r, theta = polar\n ore = other.real\n oim = other.image\n nr = Math.exp!(ore*Math.log!(r) - oim * theta)\n ntheta = theta*ore + oim*Math.log!(r)\n Complex.polar(nr, ntheta)\n elsif other.kind_of?(Integer)\n if other > 0\n\tx = self\n\tz = x\n\tn = other - 1\n\twhile n != 0\n\t while (div, mod = n.divmod(2)\n\t\t mod == 0)\n\t x = Complex(x.real*x.real - x.image*x.image, 2*x.real*x.image)\n\t n = div\n\t end\n\t z *= x\n\t n -= 1\n\tend\n\tz\n else\n\tif defined? Rational\n\t (Rational(1) / self) ** -other\n\telse\n\t self ** Float(other)\n\tend\n end\n elsif Complex.generic?(other)\n r, theta = polar\n Complex.polar(r**other, theta*other)\n else\n x, y = other.coerce(self)\n x**y\n end\n end", "def demongoize(object)\n new(value_of(object))\n end", "def test_Rational_InstanceMethods_Compare2\n\t\tassert_equal(true, Rational(\"2\") == Rational(\"2\"))\n\t\tassert_equal(false, Rational(\"1\") == Rational(\"2\"))\n\tend" ]
[ "0.5513748", "0.5395761", "0.5352221", "0.52719855", "0.5176099", "0.5094608", "0.5078279", "0.505973", "0.50355375", "0.49988765", "0.49968788", "0.4973092", "0.49586266", "0.4952022", "0.49476475", "0.493178", "0.49262136", "0.49208266", "0.49112248", "0.49032268", "0.48592547", "0.48440534", "0.4836613", "0.48280492", "0.4811144", "0.48049098", "0.48025346", "0.4782488", "0.47434404", "0.4720168", "0.4712511", "0.47063345", "0.46952266", "0.46911114", "0.4667517", "0.46639287", "0.46381122", "0.46084294", "0.46070042", "0.45903966", "0.45902655", "0.4587319", "0.45652264", "0.4564354", "0.4525045", "0.45246065", "0.4505946", "0.45038107", "0.4499973", "0.44831276", "0.44798934", "0.44779024", "0.4468932", "0.44681504", "0.4459312", "0.44576377", "0.4453811", "0.4448367", "0.44447947", "0.44407424", "0.44385466", "0.44381174", "0.4438014", "0.44369286", "0.44262305", "0.4421918", "0.44181794", "0.44166827", "0.4414981", "0.4410213", "0.44085342", "0.4404764", "0.4404764", "0.439647", "0.43808714", "0.43774477", "0.43721434", "0.4362361", "0.4361385", "0.4349942", "0.4345232", "0.434374", "0.43404853", "0.43378714", "0.43328625", "0.43289492", "0.43206993", "0.43199772", "0.43196833", "0.43161494", "0.4313132", "0.43063408", "0.43053475", "0.43050605", "0.43048313", "0.42986625", "0.42983246", "0.42638302", "0.42553407", "0.42445943" ]
0.55113226
1
:callseq: ratio == obj > true or false Returns true only if the `obj` is a SymDesc::Ratio or a Float or a Rational and it represents the same numeric value
def ==(b) case b when Rational, Ratio (@numerator == b.numerator) && (@denominator == b.denominator) when Float self == b.symdescfy else false end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def eql? r\n if r.is_a? Ratio\n return (self[0] == r[0] && self[1] == r[1])\n elsif r.is_a? Fixnum\n return (self.to_f == r)\n else\n raise TypeError.new(\"Tried to compare a #{r.class} to an HD::Ratio\")\n end\n end", "def ==(rational)\n end", "def =~(obj)\n return false unless self.left.is_a? Number\n if obj.is_a? Prod\n return false unless obj.left.is_a? Number\n return self.right == obj.right\n end \n return self.right == obj \n end", "def ==(obj)\n return false unless obj.kind_of? self.class\n\n value == obj.value\n end", "def similarTo?( otherObj )\n\t\t\treturn false unless otherObj.is_a?( self.class )\n\t\t\totherAry = otherObj.to_ary\n\t\t\trval = true\n\t\t\tself.to_ary.each_with_index {|elem,i|\n\t\t\t\tif (elem - otherAry[i]).abs > 1e-10\n\t\t\t\t\trval = false\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\t}\n\t\t\treturn rval\n\t\tend", "def eql?(obj_)\n if obj_.kind_of?(::String)\n obj_ = @_format.parse(obj_) rescue nil\n end\n return false unless obj_.kind_of?(Value)\n index_ = 0\n obj_.each_field_object do |field_, value_|\n return false if field_ != @_field_path[index_] || value_ != @_values[field_.name]\n index_ += 1\n end\n true\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n include_zero == o.include_zero &&\n max == o.max &&\n min == o.min &&\n scale == o.scale\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n denominator == o.denominator &&\n interval == o.interval &&\n message == o.message &&\n numerator == o.numerator &&\n query == o.query &&\n res_type == o.res_type &&\n resp_version == o.resp_version &&\n times == o.times\n end", "def =~(thing)\n if thing.is_a?(Money)\n self.to_f == thing.exchange_to(self.currency)\n elsif thing.respond_to?(:to_f)\n self.to_f == thing.to_f\n else\n false\n end\n end", "def ==(obj)\n self.class == obj.class and self.val == obj.val\n end", "def <= (object)\n if(self.to_float <= object.to_float)\n true\n end\n end", "def ===(thing)\n if thing.is_a?(Money)\n self.to_f == thing.to_f && self.currency == thing.currency && self.precision == thing.precision\n elsif thing.respond_to?(:to_f)\n self.to_f == thing.to_f\n else\n false\n end\n end", "def == (object)\n if(@numerador == object.numerador && @denominador == object.denominador)\n true\n end\n end", "def ==(obj_)\n (self <=> obj_) == 0\n end", "def >= (object)\n if(self.to_float >= object.to_float)\n true\n end\n end", "def eql?(obj)\n (obj.class == model) && (obj.values == @values)\n end", "def eql?(obj)\n (obj.class == model) && (obj.values == @values)\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n format == o.format &&\n resolution == o.resolution &&\n aspect_ratio == o.aspect_ratio &&\n size == o.size &&\n fps == o.fps &&\n scale_to == o.scale_to &&\n quality == o.quality &&\n repeat == o.repeat &&\n mute == o.mute &&\n range == o.range &&\n poster == o.poster &&\n thumbnail == o.thumbnail &&\n destinations == o.destinations\n end", "def ==(thing)\n if thing.is_a?(Money)\n self.to_f == thing.to_f && self.currency == thing.currency\n elsif thing.respond_to?(:to_f)\n self.to_f == thing.to_f\n else\n false\n end\n end", "def eql?(obj)\n self == obj\n end", "def > (object)\n if(self.to_float>object.to_float)\n true\n end\n end", "def amicable?\r\n a, b = self, self.sum_divisors\r\n a != b && b.sum_divisors == a\r\n end", "def === obj\n ! ! to_proc.call(obj)\n end", "def == (fraccion)\n @num == fraccion.num && @denom == fraccion.denom\n end", "def test_Complex_InstanceMethods_eql?\n\t\tassert_equal(true, Complex(1,0).eql?(Complex(1,0)))\n\t\tassert_equal(false, Complex(1,0).eql?(Complex(1.0,0)))\n\t\tassert_equal(false, Complex(1,0).eql?(1))\n\t\tassert_equal(true, Complex(1,0) == Complex(1,0))\n\t\tassert_equal(true, Complex(1,0) == Complex(1.0, 0))\n\t\tassert_equal(true, Complex(1,0) == 1)\n\tend", "def ==(other)\n\t\t# verifica que el segundo argumento sea de la clase racional\n\t\tif other.instance_of? Racional\n\t\t\t@num == other.num && @denom == other.denom\n\t\telse\n\t\t\tfalse\n\t\tend\n\tend", "def equal(obj)\n Matchy::Expectations::EqualExpectation.new(obj, self)\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class && value == o.value\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class && value == o.value\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n digits == o.digits &&\n refresh_interval == o.refresh_interval\n end", "def ===(obj)\n !test(obj).nil?\n end", "def ==(obj)\n (obj.class == model) && (obj.values == @values)\n end", "def equals?(obj)\n if obj.nil?\n false\n elsif !obj.instance_of?(self.class)\n false\n elsif equal?(obj)\n true\n else\n false\n end\n end", "def eql?(obj)\n build\n obj.build\n obj.all_info_matches?(@info)\n rescue StandardError\n false\n end", "def eql?(obj)\n return false unless obj.is_a?(self.class)\n fields.each do |tag, _|\n if value_for_tag?(tag)\n return false unless (obj.value_for_tag?(tag) && value_for_tag(tag).eql?(obj.value_for_tag(tag)))\n else\n return false if obj.value_for_tag?(tag)\n end\n end\n return true\n end", "def ==(obj)\n return true if obj.equal?(self)\n self.__getobj__ == obj\n end", "def ==(f)\n self.toFloat() == f.toFloat()\n end", "def ==(f)\n self.toFloat() == f.toFloat()\n end", "def eql?(obj)\n return true if obj.equal?(self)\n obj.eql?(__getobj__)\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n current_value == o.current_value &&\n incremental_change == o.incremental_change &&\n is_horizontal == o.is_horizontal &&\n max == o.max &&\n min == o.min &&\n page_change == o.page_change &&\n shadow == o.shadow &&\n name == o.name &&\n mso_drawing_type == o.mso_drawing_type &&\n auto_shape_type == o.auto_shape_type &&\n placement == o.placement &&\n upper_left_row == o.upper_left_row &&\n top == o.top &&\n upper_left_column == o.upper_left_column &&\n left == o.left &&\n lower_right_row == o.lower_right_row &&\n bottom == o.bottom &&\n lower_right_column == o.lower_right_column &&\n right == o.right &&\n width == o.width &&\n height == o.height &&\n x == o.x &&\n y == o.y &&\n rotation_angle == o.rotation_angle &&\n html_text == o.html_text &&\n text == o.text &&\n alternative_text == o.alternative_text &&\n text_horizontal_alignment == o.text_horizontal_alignment &&\n text_horizontal_overflow == o.text_horizontal_overflow &&\n text_orientation_type == o.text_orientation_type &&\n text_vertical_alignment == o.text_vertical_alignment &&\n text_vertical_overflow == o.text_vertical_overflow &&\n is_group == o.is_group &&\n is_hidden == o.is_hidden &&\n is_lock_aspect_ratio == o.is_lock_aspect_ratio &&\n is_locked == o.is_locked &&\n is_printable == o.is_printable &&\n is_text_wrapped == o.is_text_wrapped &&\n is_word_art == o.is_word_art &&\n linked_cell == o.linked_cell &&\n z_order_position == o.z_order_position &&\n font == o.font &&\n hyperlink == o.hyperlink &&\n link == o.link \n std_dev == o.std_dev\n end", "def equal?(p0) end", "def ==(obj)\n unless self.compatible? obj\n raise ArgumentError, \"first argument (#{self}) must be compatible with second argument (#{obj}) in order to compare them.\"\n end\n \n \n end", "def ==(obj)\n return false unless obj.is_a?(self.class)\n fields.each do |tag, _|\n if value_for_tag?(tag)\n return false unless (obj.value_for_tag?(tag) && value_for_tag(tag) == obj.value_for_tag(tag))\n else\n return false if obj.value_for_tag?(tag)\n end\n end\n return true\n end", "def eql?(comparison_object)\n self.class.equal?(comparison_object.class) &&\n @note == comparison_object.note &&\n @duration == comparison_object.duration\n end", "def eqv?(obj1, obj2)\n obj1 == obj2\n end", "def equal?(another_game_object); end", "def ==(obj)\n self.base == obj.base && self.range == obj.range && self.pointer == obj.pointer\n end", "def reminder?\n !(scalar % scalar.denominator).zero?\n end", "def !=(obj)\n return false if obj.equal?(self)\n __getobj__ != obj\n end", "def eql?(p0) end", "def eql?(p0) end", "def eql?(p0) end", "def eql?(p0) end", "def eql?(p0) end", "def eql?(p0) end", "def eql?(p0) end", "def ==(obj)\n self.base == obj.base && self.pointer == obj.pointer\n end", "def ==(comparison_object)\n comparison_object.equal?(self) ||\n (comparison_object.instance_of?(self.class) && \n @note == comparison_object.note &&\n @duration == comparison_object.duration)\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n max_cfvo == o.max_cfvo &&\n max_color == o.max_color &&\n mid_cfvo == o.mid_cfvo &&\n mid_color == o.mid_color &&\n min_cfvo == o.min_cfvo &&\n min_color == o.min_color \n std_dev == o.std_dev\n end", "def eq(_obj)\n raise NotImplementedError\n end", "def eql?(obj)\n super || (Spontaneous::PagePiece === obj && obj.target.eql?(self))\n end", "def eql?(other_money); end", "def fixed_ratio?\n fullsize_settings[:dimensions].all?(&:present?)\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n query == o.query &&\n sample_rate == o.sample_rate\n end", "def ==(money_live_convertor) \n arithmetic_op('==',self,money_live_convertor)\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n mean == o.mean &&\n median == o.median &&\n count == o.count &&\n high == o.high &&\n low == o.low &&\n std_dev == o.std_dev &&\n revisions_upward == o.revisions_upward &&\n revisions_downward == o.revisions_downward &&\n mean_7_days_ago == o.mean_7_days_ago &&\n mean_30_days_ago == o.mean_30_days_ago &&\n mean_60_days_ago == o.mean_60_days_ago &&\n mean_90_days_ago == o.mean_90_days_ago &&\n revisions_upward_last_7_days == o.revisions_upward_last_7_days &&\n revisions_downward_last_7_days == o.revisions_downward_last_7_days &&\n revisions_upward_last_30_days == o.revisions_upward_last_30_days &&\n revisions_downward_last_30_days == o.revisions_downward_last_30_days &&\n revisions_upward_last_60_days == o.revisions_upward_last_60_days &&\n revisions_downward_last_60_days == o.revisions_downward_last_60_days &&\n revisions_upward_last_90_days == o.revisions_upward_last_90_days &&\n revisions_downward_last_90_days == o.revisions_downward_last_90_days &&\n revisions_upward_last_120_days == o.revisions_upward_last_120_days &&\n revisions_downward_last_120_days == o.revisions_downward_last_120_days &&\n revisions_upward_last_150_days == o.revisions_upward_last_150_days &&\n revisions_downward_last_150_days == o.revisions_downward_last_150_days &&\n security == o.security\n end", "def >(frac)\n\t \n\t (@numerador.to_f / @denominador) > (frac.numerador.to_f / frac.denominador)\n\tend", "def >(frac)\n\t \n\t (@numerador.to_f / @denominador) > (frac.numerador.to_f / frac.denominador)\n\tend", "def numeric?(obj)\n obj.to_s.match(/\\A[+-]?\\d+?(\\.\\d+)?\\Z/).nil? ? false : true\n end", "def === obj\n return false unless obj.respond_to?(@shibboleth)\n return false unless @size == obj.size\n @matchers.each do |k, v|\n begin\n it = obj.fetch(k)\n rescue\n return false\n end\n next if v.nil?\n next if v == it\n next if v === it\n return false\n end\n return true\n end", "def test_Rational_InstanceMethods_Compare2\n\t\tassert_equal(true, Rational(\"2\") == Rational(\"2\"))\n\t\tassert_equal(false, Rational(\"1\") == Rational(\"2\"))\n\tend", "def numeric?(object)\n \t\ttrue if Float(object) rescue false\n\tend", "def match_percentage?(instance)\n percentage = percentage_flags.where(\"flaggable_type = ?\", instance.class.to_s).first.try(:percentage)\n instance.id % 10 < (percentage || 0) / 10\n end", "def == other_rating\n\t\t@star_value == other_rating.star_value && @percentage == other_rating.percentage\n\tend", "def test_Rational_InstanceMethods_Comparison\n\t\tassert_equal(0, Rational(\"4/2\") <=> Rational(\"98/49\"))\n\t\tassert_equal(-1, Rational(\"3/4\") <=> 41)\n\t\tassert_equal(0, Rational(\"0\") <=> 0.0)\n\tend", "def === obj\n #This is a stub, used for indexing\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n date == o.date &&\n intraperiod == o.intraperiod &&\n frequency == o.frequency &&\n open == o.open &&\n high == o.high &&\n low == o.low &&\n close == o.close &&\n volume == o.volume &&\n adj_open == o.adj_open &&\n adj_high == o.adj_high &&\n adj_low == o.adj_low &&\n adj_close == o.adj_close &&\n adj_volume == o.adj_volume &&\n factor == o.factor &&\n split_ratio == o.split_ratio &&\n dividend == o.dividend &&\n change == o.change &&\n percent_change == o.percent_change &&\n fifty_two_week_high == o.fifty_two_week_high &&\n fifty_two_week_low == o.fifty_two_week_low &&\n security == o.security\n end", "def is_equivalent_to?(other)\n return false if other.nil?\n return false unless self.factor == other.factor\n return false unless self.scaling == other.scaling\n return false unless self.dimensions == other.dimensions\n true\n end", "def matchers?(obj, pattern)\n (obj.respond_to?(:eql?) && obj.eql?(pattern)) ||\n (pattern.is_a?(Class) && obj.is_a?(pattern)) ||\n (pattern.is_a?(Regexp) && pattern.match(obj))\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n concatenated_path_down_count == o.concatenated_path_down_count &&\n administratively_down_count == o.administratively_down_count &&\n no_diagnostic_count == o.no_diagnostic_count &&\n path_down_count == o.path_down_count &&\n reverse_concatenated_path_down_count == o.reverse_concatenated_path_down_count &&\n neighbor_signaled_session_down_count == o.neighbor_signaled_session_down_count &&\n control_detection_time_expired_count == o.control_detection_time_expired_count &&\n echo_function_failed_count == o.echo_function_failed_count &&\n forwarding_plane_reset_count == o.forwarding_plane_reset_count\n end", "def float?(object)\n return true if Float(object)\n rescue \n return false\nend", "def ==(object)\n return true if object.equal?(self)\n if object.instance_of?(self.class)\n %w{antecedent num_antecedent_transactions \n support consequent confidence}.each do |key|\n return false unless object.send(key) == self.send(key)\n end\n return true\n else\n return false\n end\n end", "def matches?(value)\n value.kind_of?(primitive)\n end", "def eql?(other)\n\t if other.respond_to?(:units)\n\t\t(@units == other.units) and (@value == other.value)\n\t elsif other == 0\n\t\t@value == other\n\t else\n\t\t(@units == nil) and (@value == other)\n\t end\n\tend", "def ==(other)\n return @numerador == other.numerador && @denominador == other.denominador if other.instance_of? Fraccion \n false\n end", "def check_ratio_at_cap\n return if !@block_mode\n return if !@at_max_code\n\n if @checkpoint.nil?\n @checkpoint = @buf_pos + CHECKPOINT_BITS\n elsif @buf_pos > @checkpoint\n @ratio = @bytes_in / (@buf_pos / 8)\n @last_ratio = @ratio if @last_ratio.nil?\n\n if @ratio >= @last_ratio\n @last_ratio = @ratio\n @checkpoint = @buf_pos + CHECKPOINT_BITS\n elsif @ratio < @last_ratio\n # warn \"writing reset at #{@buf_pos} #{@buf_pos.divmod(8).join(',')}\"\n write_code(RESET_CODE)\n\n code_reset\n\n @checkpoint, @last_ratio = [nil, nil]\n end\n end\n end", "def eql?(*) end", "def equal?(obj)\n if obj.respond_to?(:is_poxreference?)\n _referenced_object.equal?(obj._referenced_object)\n else\n _referenced_object.equal?(obj)\n end\n end", "def numeric?(object)\n true if Float(object) rescue false\n end", "def >=(frac)\n\t \n\t (@numerador.to_f / @denominador) >= (frac.numerador.to_f / frac.denominador)\n\tend", "def >=(frac)\n\t \n\t (@numerador.to_f / @denominador) >= (frac.numerador.to_f / frac.denominador)\n\tend", "def ==(other)\n (other.base == self.base) && other.factor == self.factor\n end", "def ==(other_currency); end", "def nearly?(other); end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n type == o.type &&\n gap_width == o.gap_width &&\n gap_depth == o.gap_depth &&\n first_slice_angle == o.first_slice_angle &&\n is_color_varied == o.is_color_varied &&\n has_series_lines == o.has_series_lines &&\n overlap == o.overlap &&\n second_pie_size == o.second_pie_size &&\n pie_split_position == o.pie_split_position &&\n pie_split_by == o.pie_split_by &&\n doughnut_hole_size == o.doughnut_hole_size &&\n bubble_size_scale == o.bubble_size_scale &&\n hi_low_lines_format == o.hi_low_lines_format &&\n bubble_size_representation == o.bubble_size_representation\n end", "def object_equal(obj1, obj2)\n vars1 = obj1.instance_variables\n vars2 = obj2.instance_variables\n return false unless vars1.length == vars2.length\n # if they don't have exactly the same instance_variables names then return false\n return false unless vars1.map(&:to_s).sort.to_s == vars2.map(&:to_s).sort.to_s\n\n equal = true\n some(vars1, proc { |v|\n val1 = obj1.instance_variable_get(v)\n val2 = obj2.instance_variable_get(v)\n if val1 != val2\n equal = false\n true\n else\n false\n end\n })\n equal\nend", "def ==(obj)\n obj.grid == @grid\n end", "def real_close(r1,r2)\n (r1 - r2).abs < GeometryExpression::Epsilon\n end", "def ==(b)\n case b\n when Int\n @value == b.value\n when Numeric\n @value == b\n else\n false\n end\n end", "def real_close(r1,r2) \n (r1 - r2).abs < GeometryExpression::Epsilon\n end" ]
[ "0.6922043", "0.63706243", "0.6257363", "0.6167372", "0.6077013", "0.5956101", "0.58988214", "0.5849982", "0.582913", "0.5806711", "0.58051425", "0.5799605", "0.5765875", "0.57607144", "0.56601644", "0.565542", "0.565542", "0.56261075", "0.5595477", "0.55935556", "0.5589719", "0.55782217", "0.55724853", "0.5564014", "0.555739", "0.5528929", "0.5524271", "0.5512179", "0.5512179", "0.5499106", "0.5486952", "0.547182", "0.54712564", "0.54632515", "0.5437886", "0.5425615", "0.5417002", "0.5417002", "0.53914225", "0.5384598", "0.5378683", "0.5372667", "0.537177", "0.53684175", "0.53633344", "0.53412074", "0.53183544", "0.53158104", "0.53080493", "0.5300892", "0.5300892", "0.5300892", "0.53008705", "0.53008705", "0.53008705", "0.53008705", "0.5293758", "0.5288456", "0.52856094", "0.5276699", "0.52765834", "0.52759844", "0.52741545", "0.52732474", "0.5267731", "0.5267282", "0.5265634", "0.5265634", "0.52587146", "0.5256352", "0.52517796", "0.52428603", "0.52415097", "0.52137756", "0.5211883", "0.52061254", "0.52020025", "0.5193914", "0.51813036", "0.5173248", "0.515989", "0.5159524", "0.515262", "0.5150541", "0.5146462", "0.5146263", "0.51398385", "0.5131046", "0.5130628", "0.5125787", "0.5125787", "0.51194394", "0.5119311", "0.5111326", "0.5110159", "0.51095223", "0.5106356", "0.5105365", "0.5104354", "0.5094392" ]
0.6561627
1
:callseq: to_s > string to_s(str_io) > str_io If no argument is provided, it returns a string representation of the fraction. If a StringIO object is passed, the string representation is appended to the buffer and the buffer is returned.
def to_s(io = nil) if io __io_append(io, @numerator, DIV_ID, @denominator) else return "#{@numerator}/#{@denominator}" end io end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_rational_to_s\n assert_respond_to(@rat1, :to_s)\n assert_nothing_raised{ @rat1.to_s }\n assert_kind_of(String, @rat1.to_s)\n assert_equal(\"3/4\", @rat1.to_s)\n assert_equal(\"3/4\", @rat7.to_s)\n end", "def to_s\n return \"#{fraction.to_s}\"\n end", "def mixed_fraction(s)\n numerator, denominator = s.split('/').map(&:to_i)\n\n raise ZeroDivisionError if denominator.to_i.zero?\n \n if evenly_divides?(numerator, denominator)\n (numerator / denominator).to_s\n else\n simplify_fraction(numerator, denominator)\n end\nend", "def to_s\n @stringio.string\n end", "def to_s\n io = StringIO.new\n write io\n io.string\n end", "def to_s\n io = StringIO.new\n write(io)\n io.rewind\n io.read\n end", "def to_s(io = nil)\n return io ? (io << @value) : @value.to_s\n end", "def string\n if denominator.to_i == 0\n puts \"ERROR\"\n else\n puts numerator.to_s + \"/\" + denominator.to_s\n end\n end", "def to_io\n if @stream\n if @str.respond_to?(:rewind)\n @str.rewind\n end\n @str\n else\n StringIO.new(@str)\n end\n end", "def to_s(string)\n string.respond_to?(:to_str) ? string.to_str : string.try(:to_s)\n end", "def to_s(string)\n string.respond_to?(:to_str) ? string.to_str : string.try(:to_s)\n end", "def mixed_fraction(string)\n improper = Rational(*(string.split('/').map(&:to_i)))\n integer = improper.to_i\n fraction = improper - integer\n \n return \"#{integer}\" if (fraction).numerator == 0\n return \"#{fraction}\" if integer == 0\n \"#{integer} #{fraction.abs}\"\nend", "def to_s\n to_io.read(nil)\n end", "def string\n @io.string\n end", "def to_s_fraction(values)\n return \"#{values[1] - values[0]} / #{values[1]}\"\n end", "def to_s\n if @args[:data].is_a?(StringIO)\n return @args[:data].string\n else\n return File.read(@args[:data].path)\n end\n end", "def to_string\n io.string\n end", "def stringify(object)\n if object.nil?\n \"nil\"\n elsif object.is_a?(Float)\n text = object.to_s\n text.end_with?(\".0\") ? text[0...-2] : text\n else\n object.to_s\n end\n end", "def mixed_fraction(s)\n f = s\n fraction = f.split(\"/\").map { |x| x = x.to_i }\n p initial = Rational(fraction[0],fraction[1])\n p initial_split = initial.to_s.split(\"/\").map { |x| x = x.to_i }\n \n if initial_split[0] < 1\n initial_split[0] = initial_split[0] * -1\n initial_split[0]\n initial_split[2] = \"-\"\n initial_split[2]\n end\n if initial_split[1] == initial_split[0]\n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = initial_split[0]\n final_answer = final_answer.join\n elsif initial_split[0] == 0\n final_answer = \"0\"\n elsif (initial_split[0] / initial_split[1]) < 1\n final_answer = initial.to_s\n elsif (initial_split[0] / initial_split[1]) > 1\n if initial_split[0] % initial_split[1] == 0\n final_answer = \"#{initial_split[2]}#{initial_split[0]/initial_split[1]}\"\n elsif \n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = \"#{(initial_split[0]/initial_split[1])}\"\n final_answer[2] = \" #{initial_split[0] % initial_split[1]}/#{initial_split[1]}\"\n final_answer = final_answer.join\n end\n else \n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = \"#{(initial_split[0]/initial_split[1])}\"\n final_answer[2] = \" #{initial_split[0] % initial_split[1]}/#{initial_split[1]}\"\n final_answer = final_answer.join\n end\n p final_answer\nend", "def to_s\n @string || @object.to_s('F')\n end", "def to_s\n @string || @object.to_s('F')\n end", "def to_s(format = nil)\n\n # Go back to preferred units before printing.\n denormalize\n \n q = @quantity # use the de-normalized quantity\n\n # Split powers into numerator and denominator.\n num = powers.select{ |u,p| p > 0 }.to_a\n den = powers.select{ |u,p| p < 0 }.to_a\n den.map!{ |i| [i[0], i[1].abs] } # make all denominator powers positive\n\n # Convert num and den into strings.\n num = num.map{ |i| i[0].symbol.to_s + (i[1] > 1 ? \"^\" + i[1].to_s : \"\") }.join\n den = den.map{ |i| i[0].symbol.to_s + (i[1] > 1 ? \"^\" + i[1].to_s : \"\") }.join\n num = \"1\" if num.size == 0\n den = \"/\" + den if den.size > 0\n\n # Round the quantity to an integer if decimal portion is insignificant.\n q = q.to_i if q == q.to_i \n\n # Build and format the string.\n string = q.to_s + \" \" + num + den\n string.gsub!(/\\^(\\d+)/, '<sup>\\1</sup>') if format == :html\n \n # Return to normalized state.\n normalize\n\n # Return string.\n string\n end", "def sigfig_to_s(numero,digits) \n f = sprintf(\"%.#{digits - 1}e\", numero).to_f\n i = f.to_i\n (i == f ? i : f).to_s\n end", "def to_s\n if (@value)\n if (@value.to_i == @value)\n @value.to_i.to_s\n else\n\n float_digits = get_minimum_float\n\n rounded_value = \"%.#{float_digits}f\" % [@value.to_f]\n\n if Rational(rounded_value) != @value\n rounded_value += \"…\"\n end\n\n rounded_value\n end\n else\n raise CalculationError, 'Value of operand is not set'\n end\n end", "def puts(x)\n if x.is_a? Fraction #if Fraction\n s = \"#{x.getNum()}/#{x.getDenom()}\"\n super(s)\n elsif x.is_a? Mixed #if Mixed\n s = \"#{x.getWhole()} #{x.getNum()}/#{x.getDenom()}\"\n super(s)\n else\n super(x)\n end\nend", "def to_s(zero_string=nil)\n return zero_string if zero_string && free?\n seperated = \"#{sprintf(\"%.2f\",dollars)}\".to_s.split(\".\")\n if dollars >= 0\n seperated[0] = seperated[0].to_s.reverse.scan(/..?.?/).join(\",\").reverse\n \"$#{seperated.join(\".\")}\"\n else\n seperated[0] = seperated[0].to_s.delete(\"-\").reverse.scan(/..?.?/).join(\",\").reverse\n \"-$#{seperated.join(\".\")}\"\n end\n end", "def s_str(value=nil)\n if value.nil? or value.size == 0\n return s(:nil)\n else\n return s(:str, value.to_s)\n end\n end", "def string\n self.io unless @written\n return @io.string\n end", "def to_s\n if @real != 0\n if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1\n\tif @image >= 0\n\t @real.to_s+\"+(\"+@image.to_s+\")i\"\n\telse\n\t @real.to_s+\"-(\"+(-@image).to_s+\")i\"\n\tend\n else\n\tif @image >= 0\n\t @real.to_s+\"+\"+@image.to_s+\"i\"\n\telse\n\t @real.to_s+\"-\"+(-@image).to_s+\"i\"\n\tend\n end\n else\n if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1\n\t\"(\"+@image.to_s+\")i\"\n else\n\t@image.to_s+\"i\"\n end\n end\n end", "def str() stat(:str) end", "def export_as_string(format)\n sio = StringIO.new()\n export_to_io(sio, format)\n return sio.string\n end", "def frac_to_float(str)\n numerator, denominator = str.split(\"/\").map(&:to_f)\n denominator ||= 1\n numerator/denominator\n end", "def to_s \n return \"%s/%s\" % [@num.to_s, @den.to_s]\n end", "def wrap_io_or_string(io_or_str)\n return io_or_str if io_or_str.respond_to?(:read_one_char) # Bychar or R\n return R.new(io_or_str) if io_or_str.respond_to?(:read)\n R.new(StringIO.new(io_or_str))\n end", "def to_s_significant(decimals: 3)\n # NOTE: Similar to something like '\"%g\" % self' in pure ruby but arguably\n # easier to understand. Moreover, it's not an overhead since we have\n # Rails available anyway.\n # SOURCE: http://stackoverflow.com/a/18592312\n # DOC: http://api.rubyonrails.org/v5.2.1/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision\n number_with_precision(self,\n precision: decimals,\n significant: false,\n strip_insignificant_zeros: true)\n end", "def to_s\n self.__str__.rubify\n rescue PythonError, NoMethodError\n RubyPython::PyMain.str(self).rubify\n end", "def to_s\n string.to_s\n end", "def to_s\n StringIO.open do |buffer| # FIXME in RDF::Statement\n buffer << (subject.is_a?(Variable) ? subject.to_s : \"<#{subject}>\") << ' '\n buffer << (predicate.is_a?(Variable) ? predicate.to_s : \"<#{predicate}>\") << ' '\n buffer << (object.is_a?(Variable) ? object.to_s : \"<#{object}>\") << ' .'\n buffer.string\n end\n end", "def to_s (o)\n o ? o.to_s : nil\n end", "def string\n io.pos = start_index unless io.pos == start_index\n io.read(num_bytes)\n end", "def to_string\n s = ''\n reconstruir(s)\n s\n end", "def to_s\n\t\t\traise NotImplementedError, \"%s does not provide an implementation of #to_s\" %\n\t\t\t\t[ self.class.name ]\n\t\tend", "def to_s\r\n string = IOP.allocate_string(@size)\r\n @data.each {|x| string << x}\r\n string\r\n end", "def to_s\n str\n end", "def to_s\n s = for_string(@iterator, @first, @last, @step, @operator)\n return s\n end", "def to_s\n @str\n end", "def to(str, to_unit, ndigits=0)\n _to(str, to_unit, ndigits) rescue str\n end", "def to_s\n if self.class._equal?(String)\n self\n else\n String.new(self)\n end\n end", "def string(str); end", "def to_s\n if self.is_blank_interval\n #is blank interval --> <% 17>\n stimulusText='<% '+self.duration.to_s+'>'\n else\n #is not blank interval\n stimulusText='\"'+self.text+'\"'\n if self.stimulus_type==\"wav\"\n #is sound\n if self.synchronise_with_next==true\n stimulusText='<svp start> '+stimulusText\n end\n stimulusText='<'+self.stimulus_type+'> '+stimulusText\n \n else \n if self.stimulus_type==\"bmp\"||self.stimulus_type==\"jpg\"\n #is image\n stimulusText=' <'+self.stimulus_type+' '+self.top_possition.to_s+', '+self.left_possition.to_s+'> '+stimulusText \n else\n #is text\n #add line\n stimulusText=\"<Line \"+self.present_in_line.to_s+\"> \"+stimulusText\n end\n #add the duration of the stimulus (NOT FOR AUDIO STIMULUS?????)\n stimulusText=stimulusText+' <% '+self.duration.to_s+'>'\n end\n if self.not_erase_previous\n stimulusText=\"!\"+stimulusText\n end\n \n \n #add symbol \"/\" at the end of the stimulus or not\n if self.clear_screen\n stimulusText=stimulusText+\" /\"\n else\n stimulusText=stimulusText+\",\"\n end\n end\n stimulusText\n end", "def to_s\n @string || case\n when @object.nan? then 'NaN'\n when @object.infinite? then @object.to_s[0...-'inity'.length].upcase\n else @object.to_s\n end\n end", "def to_s\n to_buffer.to_s\n end", "def test_Rational_InstanceMethods_to_f\n\t\tassert_equal(9.25, Rational(\"37/4\").to_f)\n\tend", "def to_stringified_float(int)\n # your code goes here\n return (int.to_f).to_s\nend", "def str(str); end", "def str(str); end", "def to_s\n # Ideally, SymbolicValues shouldn't escape into trace world, and\n # we shouldn't require this if condition. However, they do escape.\n # This is because of the symbolic values being stored in concrete\n # hashes and arrays in SymbolicResult#each or SymbolicArray#map.\n if tracer.tracing?\n return self.ast.to_s\n end\n @to_s ||= begin\n to_s_var = TraceAST::Var.new(\"to_s\")\n var = tracer.new_var_for(TraceAST::Dot.new(self.ast,to_s_var))\n # Except for nil and empty string, to_s never\n # returns an empty string.\n SymbolicNonEmptyString.new var\n end\n end", "def to_s(x=10) end", "def to_s\n t = \"#{@numerator}/#{2**@denominator}\"\n m = @metronome_ticks.to_f / 24\n \"measure #{@measure_number} #{@start}-#{@end} #{t} #{m} qs metronome\"\n end", "def to_stringified_float(int)\r\n # your code goes here\r\n # use of methods\r\n\r\n int.to_f.to_s\r\nend", "def String(p0) end", "def string\n 1.0\n end", "def to_str() end", "def to_str() end", "def to_string(string)\n string.to_s\n end", "def to_s \n\tputs \"#{@num}/#{@denom}\"\n end", "def to_s\n if value < 0\n sprintf(\"%0*.*o\", size + 3, size + 3, value).slice(3..-1)\n else\n sprintf(\"%0*.*o\", size, size, value)\n end\n end", "def to_s(base=nil)\n base.nil? ? super() : super().to_i(Gibbler.default_base).to_s(base)\n end", "def to_s\n @string ||= Builder::ToString.new(self).string\n end", "def type\n :fractional\n end", "def as_string(x) \"#{x}\" end", "def to_s\n raise NotImplementedError.new(\"#{self.class}#to_s\")\n end", "def to_s(ast)\n @file = ''\n process(ast)\n @file\n end", "def to_io\n StringIO.new(self)\n end", "def extract_fraction ( string )\n match_fraction = /(\\d{1,})([\\/\\+])(\\d{1,})+/\n # m = string.match(match_fraction)[0]\n m = string.match(match_fraction)\n value = nil\n if m != nil\n value = Rational m[0]\n end\n return value\n end", "def to_string(value)\n # If we have a number that has a zero decimal (e.g. 10.0) we want to\n # get rid of that decimal. For this we'll first convert the number to\n # an integer.\n if value.is_a?(Float) and value.modulo(1).zero?\n value = value.to_i\n end\n\n return value.to_s\n end", "def to_s\n if currency.decimal_places == 0\n return \"-#{@unit}\" if exact_number.to_f < 0\n return @unit\n end\n subunit = ((\"0\" * currency.decimal_places) + @subunit.to_i.to_s)[(-1*currency.decimal_places)..-1]\n\n return \"-#{@unit}#{decimal_mark}#{subunit}\" if exact_number.to_f < 0\n \"#{@unit}#{decimal_mark}#{subunit}\"\n end", "def to_s\n @str\n end", "def to_s\n @str\n end", "def to_io() end", "def to_s\n string\n end", "def write(s)\n do_write(s)\n s.bytesize\n end", "def to_s(*) end", "def to_s(*) end", "def to_s(*) end", "def to_s\n @string.to_s\n end", "def to_s\n @string_value ||= calculate_roman_numeral\n end", "def to_s(arg0, arg1, *rest)\n end", "def reduce(frac)\n n, d = frac.split('/').map(&:to_i)\n unless (g = gcd(n, d)) == 1\n n /= g; d /= g\n end\n \"#{n}/#{d}\"\nend", "def to_str; end", "def to_str; end", "def to_str; end", "def to_str; end", "def to_str; end", "def to_str; end", "def to_str; end", "def to_str; end", "def to_str; end", "def to_stringified_float(int)\n x = int.to_f\n return puts x.to_s\n # your code goes here\nend", "def to_io\n io.to_io\n end" ]
[ "0.62411296", "0.6067417", "0.6048017", "0.56619906", "0.5567879", "0.5535255", "0.55082595", "0.5502486", "0.54220146", "0.533182", "0.533182", "0.522742", "0.5187833", "0.5176933", "0.5155773", "0.5132985", "0.51256114", "0.50557464", "0.5048989", "0.50249916", "0.50249916", "0.49755698", "0.49383032", "0.49241933", "0.4911021", "0.48664156", "0.48345923", "0.48161203", "0.47972798", "0.47819793", "0.47796434", "0.47692004", "0.47547567", "0.4742925", "0.47374368", "0.4700555", "0.46995467", "0.4686406", "0.4676284", "0.46715927", "0.46668297", "0.46556538", "0.46533853", "0.46309683", "0.46249783", "0.46010092", "0.4590327", "0.45902345", "0.457441", "0.45727637", "0.45724484", "0.45610318", "0.45586044", "0.4511015", "0.45094842", "0.45094842", "0.45047382", "0.45019063", "0.44882396", "0.44829482", "0.44802317", "0.4478286", "0.4475132", "0.4475132", "0.4470013", "0.44535366", "0.44491735", "0.44487032", "0.44378135", "0.44362074", "0.4434594", "0.44344637", "0.44293597", "0.44292575", "0.44238174", "0.44141287", "0.44071737", "0.4403699", "0.4403699", "0.43977726", "0.43963745", "0.43953884", "0.43938074", "0.43938074", "0.43938074", "0.43865362", "0.43783015", "0.43755695", "0.43718022", "0.4370609", "0.4370609", "0.4370609", "0.4370609", "0.4370609", "0.4370609", "0.4370609", "0.4370609", "0.4370609", "0.43699032", "0.43661565" ]
0.71509975
0
Get the normalized value for the key. If localization is in play the current locale will be appended to the key in MongoDB dot notation. FIXME (Did). This version DOES NOT USE ::I18n.locale directly. See the localized.rb file for more explanation.
def normalized_key(name, serializer) # serializer && serializer.localized? ? "#{name}.#{::I18n.locale}" : name serializer&.localized? ? "#{name}.#{::Mongoid::Fields::I18n.locale}" : name end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def normalized_key(name, serializer)\n serializer && serializer.localized? ? \"#{name}.#{::I18n.locale}\" : name\n end", "def lookup(locale, key, scope = [], separator = nil)\n return unless key\n keys = I18n.send(:normalize_translation_keys, locale, key, scope)\n @moneta[keys.join('.')]\n end", "def normalize(key)\n key.presence\n end", "def normalize_translation_keys(locale, key, scope, separator = nil)\n normalize_keys(locale, key, scope, separator)\n end", "def denormalize(key)\n @key_strings[normalize(key)] || key\n end", "def normalize_flat_keys(locale, key, scope, separator); end", "def normalize_flat_keys(locale, key, scope, separator); end", "def lookup(locale, key)\n cache_key = Translation.ck(locale, key)\n if @cache_store.exist?(cache_key) && value = @cache_store.read(cache_key)\n return value\n else\n translations = locale.translations.find_all_by_key(Translation.hk(key))\n case translations.size\n when 0\n value = nil\n when 1\n value = translations.first.value_or_default\n else\n value = translations.inject([]) do |values, t| \n values[t.pluralization_index] = t.value_or_default\n values\n end\n end\n\n @cache_store.write(cache_key, (value.nil? ? nil : value))\n return value\n end\n end", "def to_bson_normalized_key\n to_s\n end", "def normalized_key key\n key.downcase.parameterize.underscore.to_sym\n end", "def normalize_key(key)\n KEY_NORMALIZER.call(key)\n end", "def normalize_key(key)\n self.class.normalize_key(key)\n end", "def normalize_keys(locale, key, scope, separator = T.unsafe(nil)); end", "def localized(key, value = nil)\n self[key] = value if value\n\n case self[key]\n when NilClass then nil\n when Proc then instance_eval(&self[key])\n else _(self[key])\n end\n end", "def translate_property_value(key)\n return resource_translation_matrix.fetch(key) if resource_translation_matrix &&\n resource_translation_matrix.key?(key)\n\n key.to_s\n end", "def normalize(key)\n key.tr(\"-\", \"_\")\n end", "def normalize_keys(locale, key, scope, separator = nil)\n keys = [locale] + Array(scope) + Array(key)\n keys = keys.map {|k| I18n.translation_key_escaped?(k) ? I18n.unescape_translation_key(k) : k.to_s.split(separator || I18n.default_separator)}\n keys = (keys.flatten - ['']).reject {|k| !k}\n keys.map {|k| k.to_sym if k}\n end", "def translation\r\n translation_for(Mongoid::Globalize.locale)\r\n end", "def normalize_key(key, options = nil)\n str_key = expanded_key(key)\n raise(ArgumentError, \"key cannot be blank\") if !str_key || str_key.empty?\n\n namespace_key str_key, options\n end", "def translate_rails_key(key)\n key.to_s.camelize\n end", "def lookup(locale, key, scope = [], options = {})\n key = normalize_flat_keys(locale, key, scope, options[:separator])\n\n return if translations.missing?(locale, key)\n\n result = translations.lookup(locale, key, options)\n translations.missing(locale, key, options) if result.nil?\n\n result\n end", "def _(key,value=\"\")\n NSBundle.mainBundle.localizedStringForKey(key, value:value, table:nil)\n end", "def localize(key, options = {})\n I18n.localize(key, options.merge(:locale => self.locale))\n end", "def translate(locale, key, options = {})\n new_key = normalize_flat_keys(locale, key, options[:scope], options[:separator])\n content = super\n store_translations(locale, DynamicCopy.convert_to_hash(new_key, content), :escape => false) unless store[\"#{locale}.#{new_key}\"]\n content.respond_to?(:html_safe) ? content.html_safe : content\n end", "def normalize_key(key)\n case key\n when Numeric, nil\n # nils never happen here in Ruby >= 2.3 since nils\n # skip the normalizer.\n key\n else\n key.to_s.downcase.strip\n .gsub(/(?:\\s+|-)/, '_')\n .gsub(/[^a-zA-Z0-9_]+/, '')\n .squeeze('_')\n .gsub(/_$/, '')\n .to_sym\n end\n end", "def localize(key, error_msg='__localization_missing__', args={}, locale=nil)\n return if reserved_keys.include? key\n\n # Set a temporary Locale to support the localized_in method\n #\n unless locale.nil?\n @original_locale = Locale.code\n Locale.set_code(locale)\n end\n localized = localizations[key] || error_msg\n # Get translations from another country but in the same language if Globalite can't find a translation for my locale\n #\n if localized == error_msg\n locales.each do |t_locale|\n if t_locale.to_s.include?(\"#{current_language.to_s}-\") && t_locale != Locale.code\n localized = @@locales[t_locale][key] || error_msg\n end\n end\n end\n localized = interpolate_string(localized.dup, args.dup) if localized.class == String && localized != error_msg\n\n # let's handle pluralization if needed\n # the translation must include pluralize{count, singular string} to be translated\n # the translator can also pass the plural form if needed:\n # pluralize{3, goose, geese}\n localized = localized.gsub( /pluralize\\{(.*)\\}/){ |erb| pluralize(Regexp.last_match(1)) } if localized.is_a?(String) && (localized=~ /pluralize\\{(.*)\\}/)\n\n # Set the locale back to normal\n #\n unless locale.nil?\n Locale.code = @original_locale\n end\n\n return localized\n end", "def pluralize_key\n ActiveSupport::Inflector.pluralize(key)\n end", "def notes_normalized_key(part)\n part.to_s.tr(\" \", \"_\").to_sym\n end", "def convert_key(key)\n if regular_key?(key)\n key\n elsif (converted_key = __convert(key)) && regular_key?(converted_key)\n converted_key\n else\n key\n end\n end", "def fallback_localization(locale, key_without_locale)\n value = nil\n return nil unless fallbacks = ::Rails.application.config.i18n.fallbacks\n keys = fallbacks == true ? @locale_cache.keys : fallbacks\n keys.map(&:to_s).each do |lc|\n if lc != locale.locale && value.nil?\n nk = \"#{lc}.#{key_without_locale}\"\n v = localizations[nk]\n value = v if v.present? && value.nil?\n end\n end\n value\n end", "def normalize_key(k)\n k.to_s.gsub('-', '_').gsub(INVALID_PATTERN, '').to_sym\n end", "def load_entry(locale, key)\n locale, key = locale.to_s, key.to_s\n data = self.find_all_by_locale_and_key(locale, key)\n result = {}\n data.each do |row|\n #only return the simple translation if one is set\n return row.text if row.pluralization_index.blank?\n result[row.pluralization_index.to_sym] = row.text\n end\n return result\n end", "def normalize_locale\n return unless @locale\n alias_for = config.data.resolve_alias(locale)\n @locale = Locale.parse(alias_for) if alias_for and alias_for != locale\n \n normalized = {\n territory: territory.known? ? territory.code : nil,\n # todo: script etc\n }\n\n normalized.delete_if { |key, value| @locale[key] == value }\n reset_locale(@locale.with(**normalized)) if normalized.any?\n end", "def lookup(locale, key, scope = [], options = {})\n\n init_translations unless initialized?\n result = nil\n _locale = ::Locale.first(:code => locale)\n key = pluralizer(_locale, key, options[:count])\n value = _locale.translations.first(:code => key)\n result = value.value unless value.nil?\n result = options[:default] if !value.nil? && value.value == key && options[:default]\n return result unless value.nil? || value.value == key\n \n # check devise messages for remaining keys\n result = _locale.translations.first(:code => \"devise.sessions.#{key}\")\n return result.value unless result.nil?\n\n # fall back on yaml file if no object is found in db\n keys = I18n.normalize_keys(locale, key, scope, options[:separator])\n keys.inject(translations) do |result, _key|\n return nil unless result.is_a?(Hash) && result.has_key?(_key)\n result = result[_key]\n result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)\n result = options[:default] if options[:default] && result.nil?\n result\n end\n \n end", "def translate_property_key(value)\n return resource_translation_matrix.key(value) if resource_translation_matrix &&\n resource_translation_matrix.value?(value)\n\n value.to_s\n end", "def normalize_cache_key(key)\n if key.is_a?(Array)\n key.map { |part| normalize_cache_key(part) }.join('/')\n else\n key.to_s\n end\n end", "def mongoize\n @@value_map[value]\n end", "def mongoize(object)\n { ::I18n.locale.to_s => type.mongoize(object) }\n end", "def localize(field)\n if klass.fields[field.to_s].try(:localized?)\n field = \"#{field}.#{::I18n.locale}\".to_sym\n end\n field\n end", "def normalize_key(key)\n key_mapping[EnumType.comparable(key)] || key.to_sym\n end", "def localized_dynamic_attribute_value(field)\n if field.is_a?(String)\n field = self.content_type.find_field(field)\n end\n\n return nil if field.nil?\n\n value = (self.dynamic_attributes || {})[field.name.to_sym]\n\n # DEBUG puts \"[#{field.name.inspect}] #{value.inspect} / #{field.localized.inspect} / #{value.is_a?(Hash).inspect}\"\n\n if !field.is_relationship? && field.localized && value.is_a?(Hash)\n # get the localized value for the current locale\n _value = value[Locomotive::Mounter.locale]\n\n # no value for the current locale, give a try to the main one\n if _value.nil? && Locomotive::Mounter.locale != self.main_locale\n _value = value[self.main_locale]\n end\n\n value = _value\n end\n\n value # DEBUG .tap { |v| puts \"[#{field.name}] returning #{v.inspect}\" }\n end", "def normalized_hash\n normalize! unless @normalized\n hashify(:normalized)\n end", "def normalized(item)\n normalize! unless @normalized\n if values = @items[item]\n values[:normalized]\n end\n end", "def normalized_foreign_key\n @normalized_foreign_key ||= attribute.singularize\n end", "def translate(locale, key, options = {})\n @locale = locale_in_context(locale)\n\n options[:scope] = [options[:scope]] unless options[:scope].is_a?(Array) || options[:scope].blank?\n key = \"#{options[:scope].join('.')}.#{key}\".to_sym if options[:scope] && key.is_a?(Symbol)\n count = options[:count]\n # pull out values for interpolation\n values = options.reject { |name, value| [:scope, :default].include?(name) }\n\n entry = lookup(@locale, key)\n cache_lookup = true unless entry.nil?\n\n # if no entry exists for the current locale and the current locale is not the default locale then lookup translations for the default locale for this key\n unless entry || @locale.default_locale?\n entry = use_and_copy_default_locale_translations_if_they_exist(@locale, key)\n end\n\n # if we have no entry and some defaults ... start looking them up\n unless entry || key.is_a?(String) || options[:default].blank?\n default = options[:default].is_a?(Array) ? options[:default].shift : options.delete(:default)\n return translate(@locale.code, default, options.dup)\n end\n\n # this needs to be folded into the above at some point.\n # this handles the case where the default of the string key is a space\n if !entry && key.is_a?(String) && options[:default] == \" \"\n default = options[:default].is_a?(Array) ? options[:default].shift : options.delete(:default)\n return translate(@locale.code, default, options.dup)\n end\n\n # The requested key might not be a parent node in a hierarchy of keys instead of a regular 'leaf' node\n # that would simply result in a string return. If so, check the database for possible children \n # and return them in a nested hash if we find them.\n # We can safely ignore pluralization indeces here since they should never apply to a hash return\n if !entry && (key.is_a?(String) || key.is_a?(Symbol))\n #We need to escape % and \\. Rails will handle the rest.\n escaped_key = key.to_s.gsub('\\\\', '\\\\\\\\\\\\\\\\').gsub(/%/, '\\%')\n children = @locale.translations.find(:all, :conditions => [\"raw_key like ?\", \"#{escaped_key}.%\"]).select{|child| child.raw_key =~ /^#{key}/}\n if children.size > 0\n entry = hashify_record_array(key.to_s, children)\n @cache_store.write(Translation.ck(@locale, key), entry) unless cache_lookup == true\n return entry\n end\n end\n\n # we check the database before creating a translation as we can have translations with nil values\n # if we still have no blasted translation just go and create one for the current locale!\n unless entry \n pluralization_index = (options[:count].nil? || options[:count] == 1) ? 1 : 0\n translation = @locale.translations.find_by_key_and_pluralization_index(Translation.hk(key), pluralization_index) ||\n @locale.create_translation(key, key, pluralization_index)\n entry = translation.value_or_default\n end\n\n # write to cache unless we've already had a successful cache hit\n @cache_store.write(Translation.ck(@locale, key), entry) unless cache_lookup == true\n\n entry = pluralize(@locale, entry, count)\n entry = interpolate(@locale.code, entry, values)\n entry.is_a?(Array) ? entry.dup : entry # array's can get frozen with cache writes\n end", "def get_translate(locale, key)\r\n I18n.t!(key, :locale => locale)\r\n rescue\r\n nil\r\n end", "def translate_or_localize(key, options = {})\n [Date, DateTime, Time].include?(key.class) ? I18n.localize(key, options) : I18n.translate(key, options)\n end", "def singularize_key\n ActiveSupport::Inflector.singularize(key)\n end", "def export\n keys = {}\n reset\n db_localizations = {}\n Lit::Localization.find_each do |l|\n db_localizations[l.full_key] = l.get_value\n end\n db_localizations.sort.each do |(l_key, value)|\n current = keys\n yaml_keys = l_key.split('.')\n\n 0.upto(yaml_keys.size - 2) do |i|\n key = yaml_keys[i]\n # Overwrite en.key with en.sub.key\n unless current[key].class == Hash\n current[key] = {}\n end\n current = current[key]\n end\n current[yaml_keys.last] = value\n end\n keys.to_yaml\n end", "def normalize_abbreviation_key(key); end", "def normalize_key(key)\n keys = split_key(key)\n if (keys[0] =~ /HKLM|HKEY_LOCAL_MACHINE/)\n keys[0] = 'HKEY_LOCAL_MACHINE'\n elsif (keys[0] =~ /HKCU|HKEY_CURRENT_USER/)\n keys[0] = 'HKEY_CURRENT_USER'\n elsif (keys[0] =~ /HKU|HKEY_USERS/)\n keys[0] = 'HKEY_USERS'\n elsif (keys[0] =~ /HKCR|HKEY_CLASSES_ROOT/)\n keys[0] = 'HKEY_CLASSES_ROOT'\n elsif (keys[0] =~ /HKCC|HKEY_CURRENT_CONFIG/)\n keys[0] = 'HKEY_CURRENT_CONFIG'\n elsif (keys[0] =~ /HKPD|HKEY_PERFORMANCE_DATA/)\n keys[0] = 'HKEY_PERFORMANCE_DATA'\n elsif (keys[0] =~ /HKDD|HKEY_DYN_DATA/)\n keys[0] = 'HKEY_DYN_DATA'\n else\n raise ArgumentError, \"Cannot normalize unknown key: #{key}\"\n end\n print_status(\"Normalized #{key} to #{keys.join(\"\\\\\")}\") if $blab\n return keys.join(\"\\\\\")\n end", "def locale_name\n YAML.load(translation || \"{}\").with_indifferent_access[locale] || survey.default_locale_name\n end", "def normalize_language_keys(options)\n (LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES).each do |key|\n current = options[key]\n next unless current && current.kind_of?(Hash)\n\n current.keys.each do |language|\n current[language.to_s] = current.delete(language)\n end\n end\n\n options\n end", "def get_local_value(current_locale, value_hash)\n return value_hash[current_locale.to_sym] if value_hash[current_locale.to_sym].present?\n value_hash.values.select{|v| v.present?}.first\n end", "def normalize_language_keys(options)\n (LOCALISED_VERSION_VALUES.keys + LOCALISED_APP_VALUES.keys).each do |key|\n current = options[key]\n next unless current && current.kind_of?(Hash)\n\n current.keys.each do |language|\n current[language.to_s] = current.delete(language)\n end\n end\n\n options\n end", "def normalized\n @value\n end", "def normalize\n inject({}) do |hash, kv|\n k, v = kv\n v = v.is_a?(Array) ? v.join(',') : v.to_s\n hash[k.to_s.split('_').map {|w| w[0, 1] = w[0, 1].upcase; w }.join] = v\n hash\n end\n end", "def get_native_locale_attribute attribute, locale = Globalize.locale\n return self.send(attribute) unless translatable?\n\n if globalize.stash.contains?(locale, attribute)\n globalize.stash.read(locale, attribute)\n else\n translation_for(locale).send(attribute)\n end\n end", "def locale\n return nil if errors\n\n locale = YAML.safe_load(@text).keys.first\n locale.to_sym\n end", "def normalize_key(key, options)\n truncate_key super&.b\n end", "def translate(klass, key, value)\n if defined?(I18n)\n super\n else\n value ? value.to_s.humanize.downcase : 'nil'\n end\n end", "def parse_value(v, locale)\n new_value = nil\n case v\n when Symbol then\n lk = @localization_key_object_cache[v.to_s] || \\\n Lit::LocalizationKey.where(localization_key: v.to_s).first\n if lk\n loca = Lit::Localization.active.where(locale_id: locale.id).\n where(localization_key_id: lk.id).first\n new_value = loca.translation if loca && loca.translation.present?\n end\n when String then\n new_value = v\n when Hash then\n new_value = nil\n when Proc then\n new_value = nil # was v.call - requires more love\n else\n new_value = v.to_s\n end\n new_value\n end", "def to_bson_key\n value\n end", "def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength\n I18n.with_locale(locale) do\n # when an array has to be inserted with a default value, it needs to\n # be done like:\n # I18n.t('foo', default: [['bar', 'baz']])\n # because without the double array, array items are treated as fallback keys\n # - then, the last array element is the final fallback; so in this case we\n # don't specify fallback keys and only specify the final fallback, which\n # is the array\n val = value.is_a?(Array) ? [value] : value\n I18n.t(key, default: val)\n\n # this indicates that this translation already exists\n existing_translation =\n Lit::Localization.joins(:locale, :localization_key)\n .find_by('localization_key = ? and locale = ?', key, locale)\n\n return unless existing_translation\n\n if @raw\n existing_translation.update(default_value: value)\n else\n existing_translation.update(translated_value: value, is_changed: true)\n lkey = existing_translation.localization_key\n lkey.update(is_deleted: false) if lkey.is_deleted\n end\n end\n end", "def normalize_locale(locale)\n locale = locale.to_s\n\n locale.tr('-','_')\n end", "def locale\r\n read_attribute(:locale).to_sym\r\n end", "def value(key)\n if self[key].present?\n self[key].class != ActiveSupport::TimeWithZone ? self[key] : self[key].to_f\n elsif self[:parameters].present? && self[:parameters][key].present?\n return self[:parameters][key]\n elsif self[:extras].present? && self[:extras][key].present?\n return self[:extras][key]\n else\n return \"\"\n end\n end", "def translate_default(key, value)\n translated[key] = value\n end", "def localize\n helpers.localize\n end", "def [](key)\n key.to_s.split(\".\").inject(@values) { |v, k| v[k] if v }\n end", "def translation(locale=nil)\n return translation_for(:value, locale)\n end", "def normalize( value )\n value\n end", "def localized(value=nil, table=nil)\n @localized = NSBundle.mainBundle.localizedStringForKey(self, value:value, table:table)\n end", "def key_has_value?(key, locale = base_locale)\n t(locale_data(locale)[locale], key).present?\n end", "def translate key, opts = {}\n opts = { :locale => default_locale }.update(opts)\n\n I18n.translate(key, opts)\n end", "def extract_locale_from_subdomain\n @parsed_locale = request.subdomains.first\n if @parsed_locale.blank?\n @parsed_locale = 'en'\n end\n I18n.available_locales.include?(@parsed_locale.to_sym) ? @parsed_locale : 'en'\n end", "def convert_key(key)\n case key\n when '$'\n 'text'\n when 'D', 'Dm', 'F', 'FDm', 'FNm', 'G', 'Gm', 'Gn', 'H', 'Hm', 'Hn', 'Nm', 'P', 'Pp', 'PPd', 'PPn', 'S', 'T', 'U', 'V', 'W'\n key\n else\n key.to_s.strip.\n gsub('@', '').\n gsub(' ', '_').\n gsub(/([A-Z]+)([A-Z][a-z])/,'\\1_\\2').\n gsub(/([a-z\\d])([A-Z])/,'\\1_\\2').\n tr(\"-\", \"_\").\n squeeze(\"_\").\n downcase\n end\n end", "def locale\n @values.fetch('ai.device.locale') { \n @values['ai.device.locale'] = nil\n }\n end", "def read_attribute(name, options = {})\r\n options = {:translated => true, :locale => nil}.merge(options)\r\n if translated?(name) and options[:translated]\r\n globalize.fetch(options[:locale] || Mongoid::Globalize.locale, name)\r\n else\r\n super(name)\r\n end\r\n end", "def fetch(locale, name)\r\n Mongoid::Globalize.fallbacks(locale).each do |fallback|\r\n value = fetch_stash(fallback, name) || fetch_attribute(fallback, name)\r\n return value unless fallbacks_for?(value)\r\n end\r\n return nil\r\n end", "def key_format(field)\n @formatted_key[field] ||= JSONAPI.configuration\n .key_formatter\n .format(resource_key_for(field))\n .to_sym\n end", "def recursively_normalize_keys\n recursively_transform_keys { |key| key.downcase.to_sym rescue key }\n end", "def convert_key(key); end", "def convert_key(key); end", "def convert_key(key); end", "def translate(key)\n read(key.to_s)\n end", "def pluralize(locale, entry, count)\n\n # return the entry directly if it is a string\n return entry unless entry.is_a?(Hash)\n\n key = pluralizer(locale).call(count.nil? ? 1 : count)\n # fallback to other if :zero is not set\n key = :other if key == :zero && !entry.has_key?(:zero)\n\n # raise a pluralization error only if count is explicitely set and the entry is not available\n # else return the entry that may be a hash or the translated string\n if entry.has_key?(key)\n translation entry[key], :plural_key => key.to_s\n elsif count\n raise I18n::InvalidPluralizationData.new(entry, count)\n else\n translation entry, :plural_key => nil\n end\n end", "def translate(locale, key, options = {})\n options[:lit_default_copy] = options[:default].dup if can_dup_default(options)\n content = super(locale, key, options)\n\n if on_rails_6_1_or_higher?\n @untranslated_key = key if key.present? && options[:default].instance_of?(Object)\n\n if key.nil? && options[:lit_default_copy].present?\n update_default_localization(locale, options)\n end\n end\n\n if Lit.all_translations_are_html_safe && content.respond_to?(:html_safe)\n content.html_safe\n else\n content\n end\n end", "def transform_field_name(key, name)\n hash = ::CUSTOM_FIELD_NAMES\n class_name = self.class.name.demodulize.underscore.to_sym\n return name if hash.nil? || hash[class_name].nil? || hash[class_name][key.to_sym].nil?\n hash[class_name][key.to_sym]\n end", "def pluralize_empty_collection_node_key!\n self.key = transform_to_empty_key(pluralize_key)\n end", "def extract_locale_from_subdomain\n parsed_locale = request.subdomains.first\n \n end", "def [](key)\n # Return the value if it has already been converted\n if @converted.has_key?(key)\n @converted[key]\n else\n # Move the value from the original hash to the converted hash.\n # Support both symbol or string keys\n self.move_value(key)\n end\n end", "def add locale, key, value\n entry = self[key] ||= Entry.new\n entry[locale] = value\n end", "def create_pluralized_getter(key)\n define_singleton_method(BOOKWORM_KEYS[key]['plural'].to_sym) do\n self[key]\n end\n end", "def human_attribute_name(attribute_key_name, options = {})\n defaults = self_and_descendants_from_active_resource.map do |klass|\n :\"#{klass.name.underscore}.#{attribute_key_name}\"\n end\n defaults << options[:default] if options[:default]\n defaults.flatten!\n defaults << attribute_key_name.to_s.humanize\n options[:count] ||= 1\n I18n.translate(defaults.shift, options.merge(:default => defaults, :scope => [:activeresource, :attributes]))\n end", "def auth_domain_key(key)\n [AUTHDOMAIN, key].join('.')\n end", "def key_to_cast(val, key)\n return key if val.key?(key)\n return key.to_sym if val.key?(key.to_sym)\n return key if defaults.key?(key)\n end", "def prepare_key(val)\n val.nil? ? val : val.to_s.downcase\n end", "def translate(locale, key, options = T.unsafe(nil)); end", "def format_key(key)\n key.to_s.gsub(\"-\",\"_\")\n end" ]
[ "0.72772455", "0.65642506", "0.62767637", "0.6186129", "0.60458326", "0.6041448", "0.6041448", "0.6026203", "0.6001171", "0.5980327", "0.5969849", "0.59576917", "0.59545887", "0.58488494", "0.5821653", "0.58135754", "0.5752824", "0.57344896", "0.5678363", "0.5650589", "0.5646476", "0.5628828", "0.5615853", "0.5553842", "0.55390495", "0.5516525", "0.551172", "0.54973763", "0.5495832", "0.5486852", "0.54823816", "0.5472915", "0.54587173", "0.5450766", "0.5450759", "0.5405625", "0.5396085", "0.53869057", "0.53840035", "0.53778046", "0.53660893", "0.53641605", "0.5359278", "0.535872", "0.5353429", "0.5340488", "0.5324047", "0.5314003", "0.5310049", "0.52745736", "0.5273039", "0.52726275", "0.52523994", "0.52289295", "0.52232116", "0.52140397", "0.52012116", "0.5193779", "0.5178382", "0.5175705", "0.51401055", "0.5135713", "0.5129451", "0.51268387", "0.5113316", "0.51101434", "0.50943244", "0.50789106", "0.5031451", "0.50152004", "0.50082695", "0.50069195", "0.5002939", "0.4999496", "0.49963504", "0.49823985", "0.49714702", "0.49591517", "0.49456608", "0.49407187", "0.4932858", "0.49293986", "0.4925894", "0.4925894", "0.4925894", "0.4922132", "0.4917075", "0.49113247", "0.490858", "0.4907493", "0.4900941", "0.4898372", "0.48910162", "0.48884237", "0.48840314", "0.48715824", "0.48707238", "0.48542473", "0.4852765", "0.48314452" ]
0.7464962
0
COM interface method implementations
def Execute(*args) case args[0] when CmdAOT OnAOT(*args) when CmdItem1 OnItem1(*args) when CmdButton1 OnButton1(*args) end S_OK end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def interface; end", "def interface; end", "def invoke\r\n # TODO: rename to more appropriate one 2007/05/10 by shino\r\n raise 'must be implemented in subclasses'\r\n end", "def implementation; end", "def implementation; end", "def interface_methods; end", "def interface=(_arg0); end", "def method_missing(method_name, *args)\n @ole.send(method_name, *args)\n end", "def methods() end", "def extended_interfaces; end", "def interface; self.class.interface; end", "def methods; end", "def methods; end", "def methods; end", "def methods; end", "def commence\n raise NotImplementedError\n end", "def protocol; end", "def protocol; end", "def protocol; end", "def protocol; end", "def invoke\n raise NotImplementedError, \"Author of subclass forgot to implement #invoke\"\n end", "def protocol\n raise NotImplementedError\n end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def invoke; end", "def implemented_in; end", "def __getobj__\n __raise__ ::NotImplementedError, \"need to define `__getobj__'\"\n end", "def call\n raise NotImplementedError\n end", "def call\n raise NotImplementedError\n end", "def call(_rc)\n raise NotImplementedError\n end", "def respond(); end", "def method_missing(code, *args, &blk); end", "def method_missing(code, *args, &blk); end", "def service; raise NotImplementedError; end", "def method_missing(method_name, *args, &block)\n component.send(method_name,*args,&block)\n end", "def call\n raise NotImplementedError\n end", "def contract; end", "def contract; end", "def custom; end", "def custom; end", "def method_missing(method, *args)\n ole_method_name = method.to_s.sub(/=$/, '')\n if @designer.ole_respond_to?(ole_method_name)\n @designer.send(method, *args)\n else\n super\n end\n end", "def operation\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def dispatch(msg)\n case msg.message_type\n when Message::METHOD_CALL\n if not @intfs[msg.interface]\n raise InterfaceNotInObject, msg.interface\n end\n meth = @intfs[msg.interface].methods[msg.member.to_sym]\n raise MethodNotInInterface if not meth\n methname = Object.make_method_name(msg.interface, msg.member)\n retdata = method(methname).call(*msg.params)\n\n reply = Message.new.reply_to(msg)\n # I'm sure there is a ruby way to do that\n i = 0\n if meth.rets.size > 0 and not retdata.kind_of?(Array)\n raise InvalidReturnType\n end\n meth.rets.each do |rsig|\n reply.add_param(rsig[1], retdata[i])\n end\n @service.bus.send(reply.marshall)\n end\n end", "def method(p0) end", "def __getobj__\n raise \"Abstract class requires implementation\"\n end", "def call(*)\n raise NotImplementedError\n end", "def operation_method\n raise 'Not implemented!'\n end", "def call\n # implement in subclasses\n end", "def methods=(_arg0); end", "def required_operations1\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def dispatch\n raise NotImplementedError\n end", "def object\n raise NotImplementedError\n end", "def call(component)\n fail NotImplementedError\n end", "def protocol=(_arg0); end", "def get(_ref)\n raise NotImplementedError.new\n end", "def included_interfaces; end", "def internal; end", "def call\n raise NotImplementedError, 'Lotion::Command subclasses are expected to define #call'\n end", "def result\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def method_missing(method, *args, &blk); end", "def call( *args )\n raise NotImplementedError\n end", "def iterateinterfacestrategy(interface)\n\t\t@classname=\"#{$MarelliNamespace}_#{@interfacename}\"\n\t\t@methodList=\"\"\n\t\t@signalList=\"\"\n\t\t@privateSignalList=\"\"\n\n#Method\n\t\t@methodList=\"\"\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Method\"\n\t\tdef self.iteratemethodstrategy(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoIn\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"out\"\n\t\t\tdef self.argDo\n\t\t\t\targDoOut\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDo\n\t\t\t@argComplexTypeList += @argComplexTypeListSeparator+\"int32_t &progerror\"\n\t\t\t@argComplexTypeListSeparator = \", \"\n\t\t\t@argNameList += @argNameListSeparator+\"progerror\"\n\t\t\t@argNameListSeparator = \", \"\n\t\t\tend\n\t\t\titerateerror(method)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\n\n\t\t@methodList=\"\"\n\t\t#definisce l''azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.methodDo\n\t\t\t@argComplexTypeList = \"\"\n\t\t\t@argComplexTypeListSeparator = \"\"\n\t\t\t@argNameList = \"\"\n\t\t\t@argNameListSeparator = \"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.methodDoEnd\n\t\t\t@methodList += \"\\tint32_t #{@methodname}_imp(#{@argComplexTypeList})\\n\\t{\\n\\t\\treturn (#{@methodname}(#{@argNameList}));\\n\\t}\\n\\n\"\n\t\tend\n\t\t\n\t\t#quindi itera sui \"Method\"\n\t\titeratemethod(interface)\n\n\n#Signal\n\t\t@signalList=\"\"\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Signal\"\n\t\tdef self.iteratesignalstrategy(signal)\n\tdef argDoOut\n\t\tif @argdirection == \"out\" then\n\t\t\tcpptype=@argtype\n\t\t\tif @Primitive[cpptype].nil? then\n\t\t\t\tif $enum[cpptype].nil? then\n\t\t\t\t\tcpptype = \"#{$MarelliNamespace}_#{@servicename}_#{cpptype}\"\n\t\t\t\telse\n\t\t\t\t\tcpptype = \"uint32_t\"\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tcpptype = @Primitive[cpptype]\n\t\t\tend\n\t\t\tif cpptype == \"std::string\" then\n\t\t\t\tcpptype = \"CMMString\"\n\t\t\tend\n\t\t\t@argComplexTypeList += @argComplexTypeListSeparator+\"const #{cpptype} &p_#{@argname}\"\n\t\t\t@argComplexTypeListSeparator = \", \"\n\t\t\t@argNameList += @argNameListSeparator+\"p_\"+@argname\n\t\t\t@argNameListSeparator = \", \"\n\t\tend\n\tend\n\n\t\t\titeratearg(signal)\n\t\t\tdef self.errorDo\n\t\t\t\t@argComplexTypeList += @argComplexTypeListSeparator+\"int32_t &progerror\"\n\t\t\t\t@argComplexTypeListSeparator = \", \"\n\t\t\t\t@argNameList += @argNameListSeparator+\"progerror\"\n\t\t\t\t@argNameListSeparator = \", \"\n\t\t\tend\n\t\t\titerateerror(signal)\n\t\tend\n\n\t\t#definisce l'azione da compiere prima dell'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDo\n\t\t\t@argComplexTypeList=\"\"\n\t\t\t@argComplexTypeListSeparator=\"\"\n\t\t\t@argBaseTypeList=\"\"\n\t\t\t@argBaseTypeListSeparator=\"\"\n\t\t\t@argNameList=\"\"\n\t\t\t@argNameListSeparator=\"\"\n\t\t\t@conversionlist=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDoEnd\n\t\t\t@signalList += \"\\tvirtual void #{@signalname}_imp(#{@argComplexTypeList}) {}\\n\\n\"\n\t\tend\n\n\t\t#quindi itera sui \"Signal\"\n\t\titeratesignal(interface)\n\n#Signal\n\t\t@privateSignalList=\"\"\n\t\t@conversionList=\"\"\n\t\tdef self.iteratesignalstrategy(signal)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoSignal\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(signal)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDo\n\t\t\t\t@argBaseTypeList += @argBaseTypeListSeparator+\"int32_t &progerror\"\n\t\t\t\t@argBaseTypeListSeparator = \", \"\n\t\t\t\t@argNameList += @argNameListSeparator+\"progerror\"\n\t\t\t\t@argNameListSeparator = \", \"\n\t\t\tend\n\t\t\titerateerror(signal)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\t\t#definisce l''azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.signalDo\n\t\t\t@argComplexTypeList=\"\"\n\t\t\t@argComplexTypeListSeparator=\"\"\n\t\t\t@argBaseTypeList=\"\"\n\t\t\t@argBaseTypeListSeparator=\"\"\n\t\t\t@argNameList=\"\"\n\t\t\t@argNameListSeparator=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.signalDoEnd\n\t\t\t@privateSignalList += eval( '\"' + @privateSignalTemplate + '\"')\n\t\tend\n\n\t\titeratesignal(interface)\n\tend", "def verb\n raise NotImplementedError.new('Must override')\n end", "def method_missing(*rest) end", "def split\n raise NotImplementedError, \"#{__method__} has to be implemented in #{self.class}.\"\n end", "def method_missing(meth, *args); end", "def process\n raise NotImplemented.new\n end", "def iterateinterfacestrategy(interface)\n\t\t@classname=\"#{$MarelliNamespace}_#{@interfacename}\"\n\t\t@methodList=\"\"\n\t\t@signalList=\"\"\n\t\t@privatemethodList=\"\"\n\n#Method\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Method\"\n\t\tdef self.iteratemethodstrategy(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoIn\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"out\"\n\t\t\tdef self.argDo\n\t\t\t\targDoOut\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDo\n\t\t\t\t\t@arglist += @argseparator+\"int32_t &p_progerror\"\n\t\t\t\t\t@argseparator = \", \"\n\t\t\tend\n\t\t\titerateerror(method,true)\n\n\t\t\tdef self.errorDo\n\t\t\t\t\t@legalErrorList += \"//error return allowed: #{$errornamespace}#{@errorref} - Annotation: #{$error[@errorref][0]}\\n\"\n\t\t\tend\n\n\t\t\titerateerror(method,false)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\n\n\t\t@methodList=\"\"\n\t\t#definisce l'azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.methodDo\n\t\t\t@arglist=\"\"\n\t\t\t@argseparator=\"\"\n\t\t\t@legalErrorList=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.methodDoEnd\n\t\t\t@methodList += \"\\tvirtual int32_t #{@methodname}_imp(#{@arglist}) = 0;\\n\"\n\t\t\t$methodPrototypeList += \"\\tint32_t #{@methodname}_imp(#{@arglist});\\n\"\n\t\t\t$methodSkeletonList += \"\\n\\n#{@legalErrorList}int32_t #{$rootname}_SERVER::#{@methodname}_imp(#{@arglist})\\n{\\n\\tint32_t l_returnedValue=OK;\\n\\t/* TO BE DONE */\\n\\treturn (l_returnedValue);\\n}\\n\\n\"\n\t\tend\n\t\t\n\t\t#quindi itera sui \"Method\"\n\t\titeratemethod(interface)\n\n\n#Signal\n\t\t@signalList=\"\"\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Signal\"\n\t\tdef self.iteratesignalstrategy(signal)\n\t\t\tdef self.argDo\n\t\t\t\targDoSignal\n\t\t\tend\n\t\t\titeratearg(signal)\n\t\t\tdef self.errorDo\n\t\t\t\t\t@arglist += @argseparator+\"int32_t &progerror\"\n\t\t\t\t\t@argseparator = \", \"\n\t\t\t\t\t@imparglist += @impargseparator+\"progerror\"\n\t\t\t\t\t@impargseparator = \", \"\n\t\t\tend\n\t\t\titerateerror(signal)\n\t\tend\n\n\t\t#definisce l'azione da compiere prima dell'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDo\n\t\t\t@conversionlist=\"\"\n\t\t\t@dbusarglist=\"\"\n\t\t\t@dbusarglistseparator=\"\"\n\t\t\t@arglist=\"\"\n\t\t\t@argseparator=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDoEnd\n\t\t\tsignalcode = <<EOS\n\t\tvoid #{@signalname}_imp(#{@arglist})\n\t\t{\n#{@conversionlist}\n\t\t\t#{@signalname}(#{@dbusarglist});\n\t\t}\n\nEOS\n\n\t\t\t@signalList += signalcode\n\t\t\t$signalPrototypeList += \"\\tvoid #{@signalname}_imp(#{@arglist});\\n\"\n\t\t\t$signalSkeletonList += \"\\tvoid #{$rootname}_CLIENT::#{@signalname}_imp(#{@arglist})\\n{\\n\\t/* TO DO */\\n}\\n\"\n\t\t\t$signalConnectionList += \"\\tconnect_#{@signalname}();\\n\"\n\t\tend\n\n\t\t#quindi itera sui \"Signal\"\n\t\titeratesignal(interface)\n\n#Method\n\t\tdef interfaceDo\n\t\t\t@privatemethodList=\"\"\n\t\tend\n\t\tdef self.iteratemethodstrategy(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoInDBUS\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"out\"\n\t\t\tdef self.argDo\n\t\t\t\targDoOutDBUS\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDoDBUS\n\t\t\t\t\t@arglist += @argseparator+\"int32_t &progerror\"\n\t\t\t\t\t@argseparator = \", \"\n\t\t\t\t\t@imparglist += @impargseparator+\"progerror\"\n\t\t\t\t\t@impargseparator = \", \"\n\t\t\tend\n\t\t\titerateerror(method)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\t\t#definisce l'azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.methodDo\n\t\t\t@arglist=\"\"\n\t\t\t@argseparator=\"\"\n\t\t\t@imparglist=\"\"\n\t\t\t@impargseparator=\"\"\n\t\t\t@declarationList=\"\"\n\t\t\t@assignList=\"\"\n\t\t\t@tmpOutIndex=0\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.methodDoEnd\n\t\t\t@privatemethodList += eval( '\"' + @privatemethodtemplate + '\"')\n\t\tend\n\n\t\titeratemethod(interface)\n\tend", "def run(*)\n raise NotImplementedError, \"Expected #{self.class} to implement ##{__method__}\"\n end", "def delegating_method; end", "def *(obj)\n raise 'Not Implemented'\n end", "def notify\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def notify\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def private; end", "def process\n raise NotImplementedError(\"The instance method '#process' must be implemented for the operation\")\n end", "def command_code\n raise MovingsignApi::NotImplementedError, \"Needs to be implemented in subclass.\"\n end", "def overrides; end", "def operation; end", "def call\n raise NotImplementedError,\n \"Override #call and implement your application logic.\"\n end", "def interface_cache; end", "def abstract_method\n method_not_implemented\n end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end" ]
[ "0.68481", "0.68481", "0.65005314", "0.6432503", "0.6432503", "0.63621706", "0.6340731", "0.63237387", "0.6208223", "0.6166697", "0.6145106", "0.61411536", "0.61411536", "0.61411536", "0.61411536", "0.6103626", "0.61031777", "0.61031777", "0.61031777", "0.61031777", "0.6092361", "0.60383356", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5883267", "0.58810747", "0.5836227", "0.58292884", "0.58292884", "0.5805889", "0.5801132", "0.57804906", "0.57804906", "0.57379854", "0.5710254", "0.56966317", "0.5651965", "0.5651965", "0.56388897", "0.56388897", "0.56140053", "0.55954504", "0.5586469", "0.55820715", "0.55808604", "0.5574053", "0.55688953", "0.5560398", "0.55563885", "0.5548252", "0.5547241", "0.55237985", "0.5508525", "0.5504037", "0.54928714", "0.5486484", "0.5469197", "0.5465445", "0.54603547", "0.54266536", "0.54175895", "0.5417188", "0.54095435", "0.5399506", "0.53994495", "0.5398132", "0.5393031", "0.5390945", "0.53760093", "0.5367952", "0.5366796", "0.5365436", "0.5365436", "0.53643024", "0.5357983", "0.5357939", "0.5348952", "0.53459954", "0.534488", "0.5339498", "0.53394085", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855" ]
0.0
-1
COM interface method implementations
def OnCreateUICommand(*args) uich.QueryInterface(uich.class::IID, args[-1]) S_OK end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def interface; end", "def interface; end", "def invoke\r\n # TODO: rename to more appropriate one 2007/05/10 by shino\r\n raise 'must be implemented in subclasses'\r\n end", "def implementation; end", "def implementation; end", "def interface_methods; end", "def interface=(_arg0); end", "def method_missing(method_name, *args)\n @ole.send(method_name, *args)\n end", "def methods() end", "def extended_interfaces; end", "def interface; self.class.interface; end", "def methods; end", "def methods; end", "def methods; end", "def methods; end", "def commence\n raise NotImplementedError\n end", "def protocol; end", "def protocol; end", "def protocol; end", "def protocol; end", "def invoke\n raise NotImplementedError, \"Author of subclass forgot to implement #invoke\"\n end", "def protocol\n raise NotImplementedError\n end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def invoke; end", "def implemented_in; end", "def __getobj__\n __raise__ ::NotImplementedError, \"need to define `__getobj__'\"\n end", "def call\n raise NotImplementedError\n end", "def call\n raise NotImplementedError\n end", "def call(_rc)\n raise NotImplementedError\n end", "def respond(); end", "def method_missing(code, *args, &blk); end", "def method_missing(code, *args, &blk); end", "def service; raise NotImplementedError; end", "def method_missing(method_name, *args, &block)\n component.send(method_name,*args,&block)\n end", "def call\n raise NotImplementedError\n end", "def contract; end", "def contract; end", "def custom; end", "def custom; end", "def method_missing(method, *args)\n ole_method_name = method.to_s.sub(/=$/, '')\n if @designer.ole_respond_to?(ole_method_name)\n @designer.send(method, *args)\n else\n super\n end\n end", "def operation\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def dispatch(msg)\n case msg.message_type\n when Message::METHOD_CALL\n if not @intfs[msg.interface]\n raise InterfaceNotInObject, msg.interface\n end\n meth = @intfs[msg.interface].methods[msg.member.to_sym]\n raise MethodNotInInterface if not meth\n methname = Object.make_method_name(msg.interface, msg.member)\n retdata = method(methname).call(*msg.params)\n\n reply = Message.new.reply_to(msg)\n # I'm sure there is a ruby way to do that\n i = 0\n if meth.rets.size > 0 and not retdata.kind_of?(Array)\n raise InvalidReturnType\n end\n meth.rets.each do |rsig|\n reply.add_param(rsig[1], retdata[i])\n end\n @service.bus.send(reply.marshall)\n end\n end", "def method(p0) end", "def __getobj__\n raise \"Abstract class requires implementation\"\n end", "def call(*)\n raise NotImplementedError\n end", "def operation_method\n raise 'Not implemented!'\n end", "def call\n # implement in subclasses\n end", "def methods=(_arg0); end", "def required_operations1\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def dispatch\n raise NotImplementedError\n end", "def object\n raise NotImplementedError\n end", "def call(component)\n fail NotImplementedError\n end", "def protocol=(_arg0); end", "def get(_ref)\n raise NotImplementedError.new\n end", "def included_interfaces; end", "def internal; end", "def call\n raise NotImplementedError, 'Lotion::Command subclasses are expected to define #call'\n end", "def result\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def method_missing(method, *args, &blk); end", "def call( *args )\n raise NotImplementedError\n end", "def iterateinterfacestrategy(interface)\n\t\t@classname=\"#{$MarelliNamespace}_#{@interfacename}\"\n\t\t@methodList=\"\"\n\t\t@signalList=\"\"\n\t\t@privateSignalList=\"\"\n\n#Method\n\t\t@methodList=\"\"\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Method\"\n\t\tdef self.iteratemethodstrategy(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoIn\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"out\"\n\t\t\tdef self.argDo\n\t\t\t\targDoOut\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDo\n\t\t\t@argComplexTypeList += @argComplexTypeListSeparator+\"int32_t &progerror\"\n\t\t\t@argComplexTypeListSeparator = \", \"\n\t\t\t@argNameList += @argNameListSeparator+\"progerror\"\n\t\t\t@argNameListSeparator = \", \"\n\t\t\tend\n\t\t\titerateerror(method)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\n\n\t\t@methodList=\"\"\n\t\t#definisce l''azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.methodDo\n\t\t\t@argComplexTypeList = \"\"\n\t\t\t@argComplexTypeListSeparator = \"\"\n\t\t\t@argNameList = \"\"\n\t\t\t@argNameListSeparator = \"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.methodDoEnd\n\t\t\t@methodList += \"\\tint32_t #{@methodname}_imp(#{@argComplexTypeList})\\n\\t{\\n\\t\\treturn (#{@methodname}(#{@argNameList}));\\n\\t}\\n\\n\"\n\t\tend\n\t\t\n\t\t#quindi itera sui \"Method\"\n\t\titeratemethod(interface)\n\n\n#Signal\n\t\t@signalList=\"\"\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Signal\"\n\t\tdef self.iteratesignalstrategy(signal)\n\tdef argDoOut\n\t\tif @argdirection == \"out\" then\n\t\t\tcpptype=@argtype\n\t\t\tif @Primitive[cpptype].nil? then\n\t\t\t\tif $enum[cpptype].nil? then\n\t\t\t\t\tcpptype = \"#{$MarelliNamespace}_#{@servicename}_#{cpptype}\"\n\t\t\t\telse\n\t\t\t\t\tcpptype = \"uint32_t\"\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tcpptype = @Primitive[cpptype]\n\t\t\tend\n\t\t\tif cpptype == \"std::string\" then\n\t\t\t\tcpptype = \"CMMString\"\n\t\t\tend\n\t\t\t@argComplexTypeList += @argComplexTypeListSeparator+\"const #{cpptype} &p_#{@argname}\"\n\t\t\t@argComplexTypeListSeparator = \", \"\n\t\t\t@argNameList += @argNameListSeparator+\"p_\"+@argname\n\t\t\t@argNameListSeparator = \", \"\n\t\tend\n\tend\n\n\t\t\titeratearg(signal)\n\t\t\tdef self.errorDo\n\t\t\t\t@argComplexTypeList += @argComplexTypeListSeparator+\"int32_t &progerror\"\n\t\t\t\t@argComplexTypeListSeparator = \", \"\n\t\t\t\t@argNameList += @argNameListSeparator+\"progerror\"\n\t\t\t\t@argNameListSeparator = \", \"\n\t\t\tend\n\t\t\titerateerror(signal)\n\t\tend\n\n\t\t#definisce l'azione da compiere prima dell'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDo\n\t\t\t@argComplexTypeList=\"\"\n\t\t\t@argComplexTypeListSeparator=\"\"\n\t\t\t@argBaseTypeList=\"\"\n\t\t\t@argBaseTypeListSeparator=\"\"\n\t\t\t@argNameList=\"\"\n\t\t\t@argNameListSeparator=\"\"\n\t\t\t@conversionlist=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDoEnd\n\t\t\t@signalList += \"\\tvirtual void #{@signalname}_imp(#{@argComplexTypeList}) {}\\n\\n\"\n\t\tend\n\n\t\t#quindi itera sui \"Signal\"\n\t\titeratesignal(interface)\n\n#Signal\n\t\t@privateSignalList=\"\"\n\t\t@conversionList=\"\"\n\t\tdef self.iteratesignalstrategy(signal)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoSignal\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(signal)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDo\n\t\t\t\t@argBaseTypeList += @argBaseTypeListSeparator+\"int32_t &progerror\"\n\t\t\t\t@argBaseTypeListSeparator = \", \"\n\t\t\t\t@argNameList += @argNameListSeparator+\"progerror\"\n\t\t\t\t@argNameListSeparator = \", \"\n\t\t\tend\n\t\t\titerateerror(signal)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\t\t#definisce l''azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.signalDo\n\t\t\t@argComplexTypeList=\"\"\n\t\t\t@argComplexTypeListSeparator=\"\"\n\t\t\t@argBaseTypeList=\"\"\n\t\t\t@argBaseTypeListSeparator=\"\"\n\t\t\t@argNameList=\"\"\n\t\t\t@argNameListSeparator=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.signalDoEnd\n\t\t\t@privateSignalList += eval( '\"' + @privateSignalTemplate + '\"')\n\t\tend\n\n\t\titeratesignal(interface)\n\tend", "def verb\n raise NotImplementedError.new('Must override')\n end", "def method_missing(*rest) end", "def split\n raise NotImplementedError, \"#{__method__} has to be implemented in #{self.class}.\"\n end", "def method_missing(meth, *args); end", "def process\n raise NotImplemented.new\n end", "def iterateinterfacestrategy(interface)\n\t\t@classname=\"#{$MarelliNamespace}_#{@interfacename}\"\n\t\t@methodList=\"\"\n\t\t@signalList=\"\"\n\t\t@privatemethodList=\"\"\n\n#Method\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Method\"\n\t\tdef self.iteratemethodstrategy(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoIn\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"out\"\n\t\t\tdef self.argDo\n\t\t\t\targDoOut\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDo\n\t\t\t\t\t@arglist += @argseparator+\"int32_t &p_progerror\"\n\t\t\t\t\t@argseparator = \", \"\n\t\t\tend\n\t\t\titerateerror(method,true)\n\n\t\t\tdef self.errorDo\n\t\t\t\t\t@legalErrorList += \"//error return allowed: #{$errornamespace}#{@errorref} - Annotation: #{$error[@errorref][0]}\\n\"\n\t\t\tend\n\n\t\t\titerateerror(method,false)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\n\n\t\t@methodList=\"\"\n\t\t#definisce l'azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.methodDo\n\t\t\t@arglist=\"\"\n\t\t\t@argseparator=\"\"\n\t\t\t@legalErrorList=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.methodDoEnd\n\t\t\t@methodList += \"\\tvirtual int32_t #{@methodname}_imp(#{@arglist}) = 0;\\n\"\n\t\t\t$methodPrototypeList += \"\\tint32_t #{@methodname}_imp(#{@arglist});\\n\"\n\t\t\t$methodSkeletonList += \"\\n\\n#{@legalErrorList}int32_t #{$rootname}_SERVER::#{@methodname}_imp(#{@arglist})\\n{\\n\\tint32_t l_returnedValue=OK;\\n\\t/* TO BE DONE */\\n\\treturn (l_returnedValue);\\n}\\n\\n\"\n\t\tend\n\t\t\n\t\t#quindi itera sui \"Method\"\n\t\titeratemethod(interface)\n\n\n#Signal\n\t\t@signalList=\"\"\n\t\t#definisci la strategia di iterazione sugli elementi contenuti in \"Signal\"\n\t\tdef self.iteratesignalstrategy(signal)\n\t\t\tdef self.argDo\n\t\t\t\targDoSignal\n\t\t\tend\n\t\t\titeratearg(signal)\n\t\t\tdef self.errorDo\n\t\t\t\t\t@arglist += @argseparator+\"int32_t &progerror\"\n\t\t\t\t\t@argseparator = \", \"\n\t\t\t\t\t@imparglist += @impargseparator+\"progerror\"\n\t\t\t\t\t@impargseparator = \", \"\n\t\t\tend\n\t\t\titerateerror(signal)\n\t\tend\n\n\t\t#definisce l'azione da compiere prima dell'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDo\n\t\t\t@conversionlist=\"\"\n\t\t\t@dbusarglist=\"\"\n\t\t\t@dbusarglistseparator=\"\"\n\t\t\t@arglist=\"\"\n\t\t\t@argseparator=\"\"\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Signal\"\n\t\tdef self.signalDoEnd\n\t\t\tsignalcode = <<EOS\n\t\tvoid #{@signalname}_imp(#{@arglist})\n\t\t{\n#{@conversionlist}\n\t\t\t#{@signalname}(#{@dbusarglist});\n\t\t}\n\nEOS\n\n\t\t\t@signalList += signalcode\n\t\t\t$signalPrototypeList += \"\\tvoid #{@signalname}_imp(#{@arglist});\\n\"\n\t\t\t$signalSkeletonList += \"\\tvoid #{$rootname}_CLIENT::#{@signalname}_imp(#{@arglist})\\n{\\n\\t/* TO DO */\\n}\\n\"\n\t\t\t$signalConnectionList += \"\\tconnect_#{@signalname}();\\n\"\n\t\tend\n\n\t\t#quindi itera sui \"Signal\"\n\t\titeratesignal(interface)\n\n#Method\n\t\tdef interfaceDo\n\t\t\t@privatemethodList=\"\"\n\t\tend\n\t\tdef self.iteratemethodstrategy(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"in\"\n\t\t\tdef self.argDo\n\t\t\t\targDoInDBUS\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando si sono acquisiti i dati di un argomento\n\t\t\t#nello specifico caso si considerano solo gli argomenti con direzione \"out\"\n\t\t\tdef self.argDo\n\t\t\t\targDoOutDBUS\n\t\t\tend\n\t\t\t#quindi iterare sugli argomenti\n\t\t\titeratearg(method)\n\n\t\t\t#stabilisci quale azione eseguire quando è presente almeno un elemento\n\t\t\t#in \"ErrorSubset\"\n\t\t\t#nello specifico caso si aggiunge alla lista degli argomenti un argomento di errore\n\t\t\tdef self.errorDoDBUS\n\t\t\t\t\t@arglist += @argseparator+\"int32_t &progerror\"\n\t\t\t\t\t@argseparator = \", \"\n\t\t\t\t\t@imparglist += @impargseparator+\"progerror\"\n\t\t\t\t\t@impargseparator = \", \"\n\t\t\tend\n\t\t\titerateerror(method)\n\t\tend\n\t\t#end strategia di scansione di \"Method\"\n\t\t#definisce l'azione da compiere prima di attuare la strategia di iterazione su \"Method\"\n\t\tdef self.methodDo\n\t\t\t@arglist=\"\"\n\t\t\t@argseparator=\"\"\n\t\t\t@imparglist=\"\"\n\t\t\t@impargseparator=\"\"\n\t\t\t@declarationList=\"\"\n\t\t\t@assignList=\"\"\n\t\t\t@tmpOutIndex=0\n\t\tend\n\n\t\t#definisce l'azione da compiere dopo l'attuazione della strategia di iterazione su \"Method\"\n\t\tdef self.methodDoEnd\n\t\t\t@privatemethodList += eval( '\"' + @privatemethodtemplate + '\"')\n\t\tend\n\n\t\titeratemethod(interface)\n\tend", "def run(*)\n raise NotImplementedError, \"Expected #{self.class} to implement ##{__method__}\"\n end", "def delegating_method; end", "def *(obj)\n raise 'Not Implemented'\n end", "def notify\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def notify\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def private; end", "def process\n raise NotImplementedError(\"The instance method '#process' must be implemented for the operation\")\n end", "def command_code\n raise MovingsignApi::NotImplementedError, \"Needs to be implemented in subclass.\"\n end", "def overrides; end", "def operation; end", "def call\n raise NotImplementedError,\n \"Override #call and implement your application logic.\"\n end", "def interface_cache; end", "def abstract_method\n method_not_implemented\n end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end", "def object; end" ]
[ "0.68481", "0.68481", "0.65005314", "0.6432503", "0.6432503", "0.63621706", "0.6340731", "0.63237387", "0.6208223", "0.6166697", "0.6145106", "0.61411536", "0.61411536", "0.61411536", "0.61411536", "0.6103626", "0.61031777", "0.61031777", "0.61031777", "0.61031777", "0.6092361", "0.60383356", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5963534", "0.5883267", "0.58810747", "0.5836227", "0.58292884", "0.58292884", "0.5805889", "0.5801132", "0.57804906", "0.57804906", "0.57379854", "0.5710254", "0.56966317", "0.5651965", "0.5651965", "0.56388897", "0.56388897", "0.56140053", "0.55954504", "0.5586469", "0.55820715", "0.55808604", "0.5574053", "0.55688953", "0.5560398", "0.55563885", "0.5548252", "0.5547241", "0.55237985", "0.5508525", "0.5504037", "0.54928714", "0.5486484", "0.5469197", "0.5465445", "0.54603547", "0.54266536", "0.54175895", "0.5417188", "0.54095435", "0.5399506", "0.53994495", "0.5398132", "0.5393031", "0.5390945", "0.53760093", "0.5367952", "0.5366796", "0.5365436", "0.5365436", "0.53643024", "0.5357983", "0.5357939", "0.5348952", "0.53459954", "0.534488", "0.5339498", "0.53394085", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855", "0.53364855" ]
0.0
-1
General handler utility functions
def buildSubmissionVariables(data) data = data['submission'] data.keys.each do |key| # Build Up Submission Properties (non hash / arrays) if !data[key].is_a?(Hash) && !data[key].is_a?(Array) @variables['submission'][key] = data[key] end # Pass Form Object to the Build Form Variables Routine to Handle the Rest if key == "form" buildFormVariables({"form" => data[key]}) end # Build Submission Values Variables if key == "values" @variables['values'] = data[key] end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handler; end", "def handler; end", "def handlers; end", "def handlers; end", "def handlers; end", "def handler_method; end", "def handlers=(_arg0); end", "def handle; end", "def handle\n end", "def handler_base_class; end", "def errorhandling\n end", "def setup_handler\n end", "def handle_response(response); end", "def handle_response(response); end", "def exception_handler; end", "def middleware; end", "def start_handler\n\tend", "def helpers; end", "def helpers; end", "def helpers; end", "def main(context, event)\n return Response.new(event.method) unless event.method == 'POST'\n case event.body\n when 'return_userdata'\n context.user_data\n when 'return_string'\n 'a string'\n when 'return_bytes'\n ByteBuffer.new('bytes')\n when 'return_response'\n Response.new('response body', headers: {h1: :v1, h2: :v2}, content_type: 'text/plain', status_code: 201)\n when 'log'\n context.logger.debug('Debug message')\n context.logger.info('Info message')\n context.logger.warn('Warn message')\n context.logger.error('Error message')\n\n [201, 'returned logs']\n when 'log_with'\n context.logger.error('Error message', source: :rabbit, weight: 7)\n\n [201, 'returned logs with']\n when 'return_fields'\n event.fields.to_a.map { |field| field.join('=') }.sort.join(',')\n when 'return_path'\n event.path\n when 'return_error'\n raise 'some error'\n else\n raise \"Unknown return mode: #{event.body}\"\n end\nend", "def add_simple_handler(name,*args)\n add_handler(name) do |type,context|\n # need to clone because we modify and same array is used subsequently\n path=args.clone\n #Log.log.debug(\"path=#{path}\")\n # if last in path is boolean it tells if the error is only with http error code or always\n always=[true, false].include?(path.last) ? path.pop : false\n if context[:data].is_a?(Hash) and (!context[:response].code.start_with?('2') or always)\n msg_key=path.pop\n # dig and find sub entry corresponding to path in deep hash\n error_struct=path.inject(context[:data]) { |subhash, key| subhash.respond_to?(:keys) ? subhash[key] : nil }\n if error_struct.is_a?(Hash) and error_struct[msg_key].is_a?(String)\n RestErrorAnalyzer.add_error(context,type,error_struct[msg_key])\n error_struct.each do |k,v|\n next if k.eql?(msg_key)\n RestErrorAnalyzer.add_error(context,\"#{type}(sub)\",\"#{k}: #{v}\") if [String,Integer].include?(v.class)\n end\n end\n end\n end\n end", "def handle\n raise \"Not implemented yet!\"\n end", "def _handle_action_missing(*args); end", "def user_handle; end", "def handler_base_namespace; end", "def process(request); end", "def error_handler()\n @error_handler\n end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def scheme_handlers=(_arg0); end", "def start_handler\n end", "def handler_executed(handler)\n end", "def handle(_request)\n fail NotImplementedError\n end", "def pre_hook_send(handler); end", "def handle\n respond\n nil\n end", "def default_handler\n @default_handler\n end", "def middleware=(_arg0); end", "def add_handler(opts={})\n end", "def setup_default_handlers\n # Incoming events\n prepend_handler :incoming_msg, self.method(:r_msg)\n prepend_handler :incoming_act, self.method(:r_act)\n prepend_handler :incoming_notice, self.method(:r_notice)\n prepend_handler :incoming_ctcp, self.method(:r_ctcp)\n prepend_handler :incoming_ctcpreply, self.method(:r_ctcpreply)\n prepend_handler :incoming_mode, self.method(:r_mode)\n prepend_handler :incoming_join, self.method(:r_join)\n prepend_handler :incoming_part, self.method(:r_part)\n prepend_handler :incoming_kick, self.method(:r_kick)\n prepend_handler :incoming_quit, self.method(:r_quit)\n prepend_handler :incoming_nick, self.method(:r_nick)\n prepend_handler :incoming_miscellany, self.method(:r_miscellany)\n\n # Incoming numeric events here\n prepend_handler :incoming_welcome, self.method(:r_welcome)\n prepend_handler :incoming_bannedfromchan, self.method(:r_bannedfromchan)\n prepend_handler :incoming_badchannelkey, self.method(:r_badchannelkey)\n prepend_handler :incoming_nicknameinuse, self.method(:_nicknameinuse)\n prepend_handler :incoming_channelurl, self.method(:r_channelurl)\n prepend_handler :incoming_topic, self.method(:r_topic)\n prepend_handler :incoming_topicinfo, self.method(:r_topicinfo)\n prepend_handler :incoming_namreply, self.method(:_namreply)\n prepend_handler :incoming_endofnames, self.method(:r_endofnames)\n prepend_handler :incoming_motd, self.method(:r_motd)\n prepend_handler :incoming_motdstart, self.method(:r_motdstart)\n prepend_handler :incoming_endofmotd, self.method(:r_endofmotd)\n prepend_handler :incoming_invite, self.method(:r_invite)\n\n # Outgoing events\n prepend_handler :outgoing_begin_connection, self.method(:out_begin_connection)\n end", "def handle(status, user)\n end", "def cleanup_handler\n\tend", "def handle_messages(&handler)\n raise NotImplementedError\n end", "def process_uri(uri)\n # empty --> this is like an abstract class method\n end", "def handle(*types); end", "def scheme_handlers; end", "def scheme_handlers; end", "def handlers_idx; end", "def middleware(&block); end", "def raw_response; end", "def _catch_warden(&block); end", "def special_handler method, *args, &block\n ∀_word method, args, block\n end", "def action_wrapper\n begin\n yield\n rescue ::Rbt::Error::AuthError => e\n handle_auth_error(e)\n rescue ActiveRecord::RecordInvalid => e\n handle_validation_error(e)\n rescue => e\n handle_unknown_error(e)\n end\n end", "def start_handler\n # we're just pretending to be a handler\n end", "def call_handler(h)\n\t\t@handler[h].call if @handler[h]\n\tend", "def exception_handler(ex)\n \nend", "def cleanup_handler\n # we're just pretending to be a handler\n end", "def cleanup_handler\n end", "def weber; end", "def handle_request(socket, request_type, request_args)\n raise 'not implemented'\n end", "def file_handler_opts; end", "def handle( request ) # note: all 'handle's return 'ml_response' in a chain\n\n ml_response =\n case\n when request.get? then handle_get_muffin(request)\n when request.post? then handle_post(request)\n end\n end", "def handled!; @handled = true; end", "def dispatch(*_arg0); end", "def http; end", "def _handlers\n @handlers ||= {}\n end", "def call_ok_handler; call_handler(:ok); end", "def handle_request_intern(req)\n return handler_for_request(req).handle_request(req)\n end", "def lambda_handler(event:, context:)\n method = event['httpMethod']\n if method == 'GET'\n handle_get\n elsif method == 'POST'\n if event['body'] and store_score(event['body'])\n handle_post\n else\n handle_bad_request\n end\n else\n handle_bad_method(method)\n end\nend", "def middlewares; end", "def GET; end", "def handle_generic(tokens, options); end", "def handle_generic(tokens, options); end", "def _handle(filter, handler, *args)\n result = handler.call(*args)\n @processed += 1\n result\n rescue StandardError => err\n raise ::Webby::Error, \"#{filter} filter error: #{err.message.inspect}\"\n end", "def method_missing(name, *args)\n @handler.send(name, *args)\n end", "def response_parser; end", "def handle_requests(request)\r\n\tputs request\r\n\tdata = JSON.parse(request)\r\n\tif data['command'] == 'login'\r\n\t\treturn login(data)\r\n\telsif data['command'] == 'add_phone'\r\n\t\treturn add_phone(data)\r\n\telsif data['command'] == 'remove_phone'\r\n\t\treturn remove_phone(data)\t\t\t\r\n\telsif data['command'] == 'create_account'\r\n\t\treturn create_account(data)\r\n\telsif data['command'] == 'update_location'\r\n\t\treturn update_location(data)\r\n\telse\r\n\t\tputs \"Unknown command: #{data['command']}\"\r\n\t\treturn \"ERROR\"\r\n\tend\r\nend", "def handle_results(env, request = nil)\n # override me!\n end", "def middlewares=(_arg0); end", "def parse_page_handler_from_uri\n @page_handler = @uri.host.gsub(/\\./, '_') # get host, replace . with _\n # remove leading www_ if present\n @page_handler.capitalize! # convert to class name\n end", "def call(request); end", "def wrapper; end", "def initialize\n # list of handlers\n @error_handlers=[]\n @log_file=nil\n self.add_handler('Type Generic') do |type,context|\n if !context[:response].code.start_with?('2')\n # add generic information\n RestErrorAnalyzer.add_error(context,type,\"#{context[:request]['host']} #{context[:response].code} #{context[:response].message}\")\n end\n end\n end", "def egregious_exception_handler(exception)\n egregious_flash(exception)\n egregious_log(exception)\n egregious_respond_to(exception)\n end", "def handle_message(request, message)\n #\n end", "def handle(req)\n begin\n if req.is_a? DaemonListTorrentsRequest\n handleListTorrentsRequest req\n elsif req.is_a? DaemonAddTorrentRequest\n handleAddTorrentsRequest req\n elsif req.is_a? DaemonDelTorrentRequest\n handleDelTorrentsRequest req\n elsif req.is_a? DaemonGetTorrentRequest\n handleGetTorrentRequest req\n elsif req.is_a? DaemonTerminateRequest\n handleTerminateRequest req\n elsif req.is_a? DaemonLoginRequest\n handleLoginRequest req\n elsif req.is_a? DaemonAuthSessionRequest\n handleAuthSessionRequest req\n elsif req.is_a? DaemonLogoutRequest\n handleLogoutRequest req\n elsif req.is_a? DaemonPauseTorrentRequest\n handlePauseRequest req\n elsif req.is_a? DaemonGetAlertsRequest\n handleGetAlertsRequest req\n elsif req.is_a? DaemonFsInfoRequest\n handleFsInfoRequest req\n elsif req.is_a? DaemonGraphInfoRequest\n handleGraphInfoRequest req\n elsif req.is_a? DaemonListFilesRequest\n handleListFilesRequest req\n elsif req.is_a? DaemonDownloadFileRequest\n handleDownloadFileRequest req\n elsif req.is_a? DaemonDelFileRequest\n handleDelFileRequest req\n elsif req.is_a? DaemonGetTvShowSummaryRequest\n handleGetTvShowSummaryResponse req\n elsif req.is_a? DaemonGetMagnetRequest\n handleGetMagnetRequest req\n elsif req.is_a? DaemonGetUsageRequest\n handleGetUsageRequest req\n elsif req.is_a? DaemonGetAlarmsRequest\n handleGetAlarmsRequest req\n else\n $logger.warn \"Got an unknown request type #{req.class}\"\n nil\n end\n rescue\n $logger.error \"Got an exception when handling a request: #{$!}\"\n $logger.error \"#{$!.backtrace.join(\" \")}\"\n end\n end", "def processor; end", "def response=(_arg0); end", "def response=(_arg0); end", "def response=(_arg0); end", "def response=(_arg0); end", "def perform(request, response); end" ]
[ "0.78852904", "0.78852904", "0.7699488", "0.7699488", "0.7699488", "0.7279557", "0.70928675", "0.67347205", "0.63554645", "0.63363624", "0.6306352", "0.6291296", "0.6282299", "0.6282299", "0.6280245", "0.61602783", "0.61415493", "0.6130153", "0.6130153", "0.6130153", "0.61183655", "0.6108704", "0.60615426", "0.6056281", "0.6048928", "0.6040467", "0.60345054", "0.6027115", "0.590167", "0.590167", "0.590167", "0.590167", "0.590167", "0.590167", "0.590167", "0.590167", "0.590167", "0.590167", "0.590167", "0.5846112", "0.582659", "0.5802641", "0.5794451", "0.5784616", "0.57836473", "0.577902", "0.5777901", "0.5768361", "0.57482135", "0.573347", "0.5728068", "0.5718607", "0.57155544", "0.5711048", "0.57107383", "0.57107383", "0.5672754", "0.56714237", "0.5649864", "0.56398124", "0.56340146", "0.5629988", "0.56234866", "0.561201", "0.5611497", "0.5610859", "0.5609704", "0.5600243", "0.55821466", "0.5559274", "0.5557066", "0.55428797", "0.55357575", "0.5530873", "0.5525295", "0.5497972", "0.5488898", "0.5471363", "0.5467951", "0.54548764", "0.5454291", "0.5454291", "0.5451476", "0.54503256", "0.5448757", "0.5442681", "0.54410905", "0.5434414", "0.5429677", "0.54288685", "0.54234505", "0.54230356", "0.54083425", "0.540723", "0.5406064", "0.53992504", "0.5398644", "0.5398644", "0.5398644", "0.5398644", "0.5396243" ]
0.0
-1
This is a template method that is used to escape results values (returned in execute) that would cause the XML to be invalid. This method is not necessary if values do not contain character that have special meaning in XML (&, ", ), however it is a good practice to use it for all return variable results in case the value could include one of those characters in the future. This method can be copied and reused between handlers.
def escape(string) # Globally replace characters based on the ESCAPE_CHARACTERS constant string.to_s.gsub(/[&"><]/) { |special| ESCAPE_CHARACTERS[special] } if string end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def escape_xml(value)\n value.to_s.gsub(/[&<>\"']/) { |s| ESCAPE_TABLE[s] } # or /[&<>\"']/\n end", "def xml_escape(input); end", "def escape(val)\n return val\n end", "def escape(value)\n end", "def xml_escape(input)\n return input.to_s.to_xs\n end", "def test_output_escaping\n\t\ttext = '<bad-script>if (a &lt; b || b &gt; c) { return \"text\"; }<stop/>return \"&gt;&gt;&gt;snip&lt;&lt;&lt;\";</bad-script>'\n node = LibXML::XML::Parser.string(text).parse.root\n\t\tassert_equal text, node.to_s\n\n\t\ttext_noenc = '<bad-script>if (a < b || b > c) { return \"text\"; }<stop/>return \">>>snip<<<\";</bad-script>'\n\t\tnode.output_escaping = false\n\t\tassert_equal text_noenc, node.to_s\n\n\t\tnode.output_escaping = true\n\t\tassert_equal text, node.to_s\n\n\t\tnode.output_escaping = nil\n\t\tassert_equal text_noenc, node.to_s\n\n\t\tnode.output_escaping = true\n\t\tassert_equal text, node.to_s\n end", "def escape_xml(string) \n string.gsub(/[&<>\\'\\\"]/) do | match |\n case match\n when '&' then '&amp;'\n when '<' then '&lt;'\n when '>' then '&gt;'\n when '\"' then '&quot;'\n when \"'\" then '&apos;'\n end\n end \n end", "def clean_value\n if (type == :string || type == :text) && !Axlsx.trust_input\n Axlsx.sanitize(::CGI.escapeHTML(@value.to_s))\n else\n @value.to_s\n end\n end", "def escape_xml_data(xml_data)\n xml_data = xml_data.gsub(\"\\n\", \"\")\n xml_data = xml_data.gsub(\"\\n\", \"\")\n xml_data = xml_data.gsub(/[\\>]([ ])*[\\<]/, \"><\")\n return xml_data\n\n end", "def consume_escaped; end", "def test_output_escaping_sanity\n\t\ttext = '<bad-script>if (a &lt; b || b &gt; c) { return \"text\"; }<stop/>return \"&gt;&gt;&gt;snip&lt;&lt;&lt;\";</bad-script>'\n node = LibXML::XML::Parser.string(text).parse.root\n\t\taffected = node.find('//text()')\n\n\t\tcheck_escaping = lambda do |flag|\n\t\t\tassert_equal('bad-script', node.name)\n\t\t\tassert_equal(flag, node.output_escaping?)\n\t\t\taffected.each do |x|\n\t\t\t\tassert_equal(flag ? 'text' : 'textnoenc', x.name)\n\t\t\t\tassert_equal(flag, x.output_escaping?)\n\t\t\tend\n\t\tend\n\n\t\tnode.output_escaping = false\n\t\tcheck_escaping[false]\n\n\t\tnode.output_escaping = true\n\t\tcheck_escaping[true]\n\n\t\tnode.output_escaping = nil\n\t\tcheck_escaping[false]\n\n\t\tnode.output_escaping = true\n\t\tcheck_escaping[true]\n\n\t\taffected.first.output_escaping = true\n\t\taffected.last.output_escaping = false\n\t\tassert node.output_escaping?.nil?\n end", "def escape_xml(string)\n string.gsub!(\"&\", \"&amp;\")\n string.gsub!(\"<\", \"&lt;\")\n string.gsub!(\">\", \"&gt;\")\n string.gsub!(\"'\", \"&apos;\")\n string.gsub!(\"\\\"\", \"&quot;\")\n\n return string\n end", "def create_escape_value(value)\n if value.is_a?(String) || value.is_a?(Symbol)\n \"#{sanitize_escape_sequences(value.to_s)}\"\n else\n value\n end\n end", "def escape_xml(xml_in) \n return xml_in.gsub(/&/,'&amp;').gsub(/</,'&lt;')\n end", "def parse_escaped_chars; end", "def page_meta_escape_value(val)\n val.to_s.gsub(\"<\", \"&lt;\").gsub(\">\", \"&gt;\")\n end", "def parse_value_rexml(value, ns_strs, language)\n # Fixme\n end", "def xml_attr_escape\n replacements = {\"<\" => \"&lt;\", \">\" => \"&gt;\", \"&\" => \"&amp;\", \"\\\"\" => \"&quot;\", \"'\" => \"&apos;\"}\n gsub(/([<>&\\'\\\"])/) { replacements[$1] }\n end", "def escape(value)\n value.nil? ? nil : value.shellescape\n end", "def escape(value)\n _escape(value.to_s.to_str)\n rescue ArgumentError\n _escape(value.to_s.to_str.force_encoding(Encoding::UTF_8))\n end", "def escape_xml(text)\n text.encode(xml: :text)\n end", "def e(value)\n CGI.escape(value)\n end", "def xp str\n\t\treturn Mandar::Tools::Escape.xpath str\n\tend", "def _reduce_493(val, _values, result)\n result = \"&#{value(val[1])}\".to_sym\n \n result\nend", "def escape_value(connection, value)\n connection.quote(value)\n end", "def test_sql_escaped\n exc_handler = HumanParseExceptionHandler.new\n new_str = exc_handler.get_human_result_for_string(\"fo'ob\\\"ar\",\"ParseException\")\n assert_equal(false, new_str)\n end", "def escape(str); end", "def escape(string); end", "def uri_escape\n str = xml_escape.gsub(/\\+/, '&#43;')\n str = str.gsub(/\\s/, '+')\n end", "def escaped_value(item)\n result = item.is_a?(Symbol) ? item.to_s : item\n result = result.to_json unless result.is_a?(String)\n # noinspection RubyMismatchedArgumentType\n Rack::Utils.escape(result)\n end", "def to_soap_value\n CGI.escapeHTML self\n end", "def protectXML(content)\n content.gsub('&','&amp;').gsub('<','&lt;').gsub('>','&gt;')\n end", "def escape_quotes(unfiltered)\n unfiltered.to_s.gsub(/'/, \"''\")\n end", "def escape_content\n content.to_s.gsub(/&/, \"&amp;\").gsub(/\\\"/, \"&quot;\").gsub(/>/, \"&gt;\").gsub(/</, \"&lt;\") \n end", "def escape_value(value)\n value = value.to_s.dup\n value.gsub!(%r{\\\\([0nrt])}, '\\\\\\\\\\1')\n value.gsub!(%r{\\n}, '\\n')\n value.gsub!(%r{\\r}, '\\r')\n value.gsub!(%r{\\t}, '\\t')\n value.gsub!(%r{\\0}, '\\0')\n value\n end", "def add_expr_escaped(src, code)\n src << \" #{@bufvar} << _erubis_xml_helper.escape_xml((\" << code << '));'\n end", "def test_values_with_apostrophes\n doc = Document.new(%q#<tag h1=\"1'2'\" h2='1\"2'/>#)\n s = doc.to_s\n assert(s =~ /h1='1&apos;2&apos;'/)\n assert(s =~ /h2='1\"2'/)\n end", "def escape(value)\n value.to_s.strip.gsub(/\\s/, '')\n end", "def rdf_string_prep value\n return unless value.present?\n # the next two steps have been moved here from `export_rdf.rake`\n value.gsub!(\"\\r\\n\", '') # remove CrLf\n value.gsub!(\"\\\\\", '') # remove \"\\\" to avoid illegal control characters\n return value unless value =~ SINGLE_QUOTE_REGEXP\n value.strip!\n # replace initial or final \"'\" with \"\\'\"\n value.gsub(%r{^'|'$}, %q{\\\\\\'})\n end", "def force_correct_attribute_escaping!(node)\n return unless Nokogiri::VersionInfo.instance.libxml2?\n\n node.attribute_nodes.each do |attr_node|\n next unless LibxmlWorkarounds::BROKEN_ESCAPING_ATTRIBUTES.include?(attr_node.name)\n\n tag_name = LibxmlWorkarounds::BROKEN_ESCAPING_ATTRIBUTES_QUALIFYING_TAG[attr_node.name]\n next unless tag_name.nil? || tag_name == node.name\n\n #\n # this block is just like CGI.escape in Ruby 2.4, but\n # only encodes space and double-quote, to mimic\n # pre-2.9.2 behavior\n #\n encoding = attr_node.value.encoding\n attr_node.value = attr_node.value.gsub(/[ \"]/) do |m|\n \"%\" + m.unpack(\"H2\" * m.bytesize).join(\"%\").upcase\n end.force_encoding(encoding)\n end\n end", "def escape_value(value)\n CGI.escape(value.to_s).gsub('%20', '+')\n end", "def clean_param(leave_slashes: false)\n return unless @val\n\n val = @val.to_s.strip\n val.gsub!(/\\\\(.)/, \"\\\\1\") unless leave_slashes\n val\n end", "def xml_sanitize(str)\n str.gsub(/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]/, \"?\")\nend", "def xml_sanitize(str)\n str.gsub(/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]/, \"?\")\nend", "def esc(str)\n str = str.to_s.gsub(\"&\", \"&amp;\")\n str = str.gsub(\"\\\"\", \"&apos;\")\n str = str.gsub(\"\\\"\", \"&quot;\")\n str = str.gsub(\"<\", \"&lt;\")\n str.gsub(\">\", \"&gt;\")\nend", "def unescape_xml(text)\n CGI.unescape_html text\n end", "def _reduce_555(val, _values, result)\n result = \"&#{value(val[1])}\".to_sym\n \n result\nend", "def resolve_xml_entities(text)\r\n result=text\r\n result.gsub!(\"&lt;\", \"<\")\r\n result.gsub!(\"&gt;\", \">\")\r\n result.gsub!(\"&amp;\", \"&\")\r\n result\r\n end", "def ascii_quotes\n value = self.gsub(/'/, \"&#39;\").gsub(/\"/, \"&#34;\")\n return value\n end", "def my_html_escape(org_value)\n '' if org_value.nil?\n ERB::Util.html_escape(org_value). # Standard-Escape kann kein NewLine-><BR>\n gsub(/\\n/, '<br>'). # Alle vorkommenden NewLine ersetzen\n gsub(/\\r/, '') # Alle vorkommenden CR ersetzen, führt sonst bei Javascript zu Error String not closed\n end", "def escape_special_chars(data)\n data = data.dup\n data.gsub! /&/n , \"&amp;\"\n data.gsub! /\\\"/n , \"&quot;\"\n data.gsub! />/n , \"&gt;\"\n data.gsub! /</n , \"&lt;\"\n data.gsub! /'/ , \"&#039;\"\n return data\n end", "def smart_quote_entity(el); end", "def unicode_esc!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 9 )\n\n \n # - - - - main rule block - - - -\n # at line 309:9: '\\\\\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT\n match( 0x5c )\n match( 0x75 )\n hex_digit!\n hex_digit!\n hex_digit!\n hex_digit!\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 9 )\n\n end", "def escape(string)\n #This is a stub, used for indexing\n end", "def _reduce_583(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def html_escape(clean_me)\n clean_me.to_s.gsub(/[&\"<>]/) do |special|\n { '&' => '&amp;',\n '>' => '&gt;',\n '<' => '&lt;',\n '\"' => '&quot;' }[special]\n end\n end", "def prepare(value)\n value.to_s.gsub('\"', '\\\"')\n end", "def xpath_sanitize(text)\n # If there's nothing to escape, just wrap text in single-quotes\n if !text.include?(\"'\")\n return \"'#{text}'\"\n else\n result = text.gsub(/'/, %{', \"'\", '})\n return \"concat('#{result}')\"\n end\n end", "def to_s\n value = \"\"\n nodeValue.scan(/./um) do |c|\n code = c.unpack(\"U\")[0]\n if code == 9 || code == 10 || code == 13\n value << sprintf(\"&#x%X;\", code)\n elsif c == \"&\"\n value << \"&amp;\"\n elsif c == \"\\\"\"\n value << \"&quot;\"\n elsif c == \"<\"\n value << \"&lt;\"\n else\n value << c\n end\n end\n \"#{@name}=\\\"#{value}\\\"\"\n end", "def _reduce_582(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_582(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_582(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def /(val)\n data / Reg.clean_value(val)\n end", "def parse_smart_quotes; end", "def quote(value); end", "def escape_value(v) \n if v.nil?\n # Nulls (nil)\n return \"NULL\"\n elsif v.kind_of? Integer or v.kind_of? Float\n # Integers / Floats\n return v.to_s\n else\n # Everything Else\n return \"'#{@mysql.escape(v.to_s)}'\" \n end\n end", "def _reduce_511(val, _values, result)\n result = \"&#{value(val[1])}\".to_sym\n \n result\nend", "def _reduce_585(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_585(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_587(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def requote(value) return restore_ends(value, '\"') end", "def _reduce_580(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_580(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_580(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def html_safe_value\n sanitize(@values.join(' '), tags: %w[sub sup i em])\n end", "def escaped_content\n content.gsub(/&/, '&amp;').gsub(/</, '&lt;').strip\n end", "def normalizeAttributeValue(str)\n\t return nil if str.nil?\n\t val = str.dup\n\t result = ''\n\t until val.empty?\n\t\tpos = val =~ /[&\\s<]/m\n\t\tif pos.nil?\n\t\t result << val\n\t\t return result\n\t\tend\n\t\tresult << $`\n\t\tval = val[pos .. -1]\n\t\tif val =~ /\\A&#x([0-9a-f]*);/ni\n\t\t result << $1.hex.chr\n\t\t val = $'\n\t\telsif val =~ /\\A&#([0-9]*);/n\n\t\t result << $1.to_i.chr\n\t\t val = $'\n\t\telsif val =~ /\\A&([^&;]*);/n\n\t\t ref = $1\n\t\t case ref\n\t\t when 'amp'; result << '&'\n\t\t when 'lt'; result << '<'\n\t\t when 'gt'; result << '>'\n\t\t when 'quot'; result << '\"'\n\t\t when 'apos'; result << '\\''\n\t\t else\n\t\t\treplacement = @internalEntities[ref]\n\t\t\tif replacement.nil?\n\t\t\t str = \"entity reference '#{ref}' is undefined\"\n\t\t\t raise ParserError.new(str, self)\n\t\t\tend\n\t\t\tif !replacement.index('<').nil?\n\t\t\t str = \"attribute values may not contain '<'\"\n\t\t\t raise ParserError.new(str, self)\n\t\t\tend\n\t\t\tresult << normalizeAttributeValue(replacement)\n\t\t end\n\t\t val = $'\n\t\telsif val =~ /\\A\\s+/m\n\t\t result << ' '\n\t\t val = $'\n\t\telsif val[0] == ?<\n\t\t\tstr = \"attribute values may not contain '<'\"\n\t\t raise ParserError.new(str, self)\n\t\tend\n\t end\n\t return result\n\tend", "def _reduce_603(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n\n result\nend", "def _reduce_610(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n\n result\nend", "def escape_double_quotes\r\n return self.gsub('\"', '\\\"')\r\n end", "def escape_text(text)\n text\n end", "def escape(text)\n text.gsub('\"', '\\\"')\nend", "def _reduce_609(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n\n result\nend", "def quote_and_escape(value)\n case value\n when \"NULL\"\n value\n else\n value = value.gsub(/\\\\/, ARRAY_ESCAPE)\n value.gsub!(/\"/,\"\\\\\\\"\")\n \"\\\"#{value}\\\"\"\n end\n end", "def escape_html(value)\n CGI.escapeHTML(value)\n end", "def convert_escape_characters(*args, &block)\n maatsf_convert_escape_characters(super(*args, &block))\n end", "def escape_entities(str)\n CGI.escapeHTML(str).gsub(/[\\n\\r]/) {|c| '&#x' + c.unpack('h').first + ';'}\n end", "def clean_field(value)\n doc = Nokogiri::XML.fragment(value)\n doc.text.squish\n end", "def get_handler_xml_results(args = {})\r\n results = \"<results>\"\r\n args.each do |key,value|\r\n results << %|<result name=\"#{escape(key.to_s)}\">#{escape(value.to_s)}</result>|\r\n end\r\n results << \"</results>\"\r\n return results\r\n end", "def entity_gsub!(chars)\n mapping = {\n '&' => '&amp;',\n '<' => '&lt;',\n '>' => '&gt;',\n '\"' => '&quot;',\n \"'\" => '&apos;'\n }\n re = /&(?!amp;)|[<>'\"]/\n chars.gsub!(re, mapping)\n chars\n end", "def html_escape\n return to_s\n end", "def html_escape\n return to_s\n end", "def test_entity_replacement\n\tt = NQXML::Tokenizer.new('')\n\n\t# add a method that lets us set the internal entity hash\n\tclass << t\n\t def testSetInternalEntities(h); @internalEntities = h; end\n\tend\n\n\tt.testSetInternalEntities({ # as if we saw <!ENTITY...> tags\n\t 'a' => '&b;',\n\t 'b' => '&foo;',\n\t 'foo' => '&bar;',\n\t 'bar' => 'bletch',\n\t 'ugly' => 'An ampersand (&#38;) may be escaped' +\n\t\t\t' numerically (&#38;#38;) or with a general' +\n\t\t\t' entity (&amp;amp;).'\n\t})\n\n\tassert_equal('x <&> x', t.replaceAllRefsButParams('x &lt;&amp;&gt; x'))\n\tassert_equal('x \"\\' x', t.replaceAllRefsButParams('x &quot;&apos; x'))\n\tassert_equal('x A x', t.replaceAllRefsButParams('x &#65; x'))\n\tassert_equal('x A x', t.replaceAllRefsButParams('x &#x41; x'))\n\tassert_equal('&&', t.replaceAllRefsButParams('&amp;&#38;'))\n\n\tassert_equal('&amp', t.replaceAllRefsButParams('&amp'))\n\tassert_equal('&', t.replaceAllRefsButParams('&amp;'))\n\n\tassert_equal('bletch', t.replaceAllRefsButParams('&bar;'))\n\tassert_equal('bletch', t.replaceAllRefsButParams('&foo;'))\n\tassert_equal('bletch', t.replaceAllRefsButParams('&b;'))\n\tassert_equal('bletch', t.replaceAllRefsButParams('&a;'))\n\n\tassert_equal('An ampersand (&) may be escaped' +\n\t\t ' numerically (&#38;) or with a general' +\n\t\t ' entity (&amp;).', t.replaceAllRefsButParams('&ugly;'))\n\n\t# Make sure unknown entities raise an error\n\texpect_error('x &huh; x', /entity reference '&huh;' is undefined/)\n end", "def unescape_value(value)\n CGI.unescape(value)\n end", "def _reduce_584(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_584(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def _reduce_584(val, _values, result)\n identifier = val[1].to_sym\n\n self.env[identifier] = :lvar\n result = \"&#{identifier}\".to_sym\n \n result\nend", "def escape(value)\n $db.escape_identifier(value)\nend", "def test_entity_insertions\n assert_equal(\"&amp;\", REXML::Text.new(\"&amp;\", false, nil, true).to_s)\n #assert_equal(\"&\", REXML::Text.new(\"&amp;\", false, false).to_s)\n end", "def clean_value(value)\n # value.is_a?(String) ? value.strip.gsub(/\\A\"|\"\\Z/, '') : value\n value\n end", "def escape(input); input.to_s.gsub('\"', '\\\\\"'); end" ]
[ "0.6790408", "0.673146", "0.6600858", "0.63993174", "0.6328012", "0.62743497", "0.6160782", "0.6022911", "0.5983455", "0.5983152", "0.59736365", "0.58558583", "0.5832975", "0.58071023", "0.57079893", "0.57021266", "0.5694263", "0.5678588", "0.566588", "0.55844843", "0.5570339", "0.5568933", "0.55644643", "0.55602884", "0.5538957", "0.5495174", "0.54693955", "0.54633945", "0.54385096", "0.54254156", "0.5425332", "0.5423061", "0.5398056", "0.5395053", "0.53916293", "0.53754777", "0.5360073", "0.5353966", "0.535191", "0.53452134", "0.53442234", "0.5328826", "0.5319318", "0.5319318", "0.53047985", "0.52998763", "0.5281861", "0.5278198", "0.52627975", "0.5256091", "0.523172", "0.5229525", "0.52270895", "0.52254224", "0.52201957", "0.5197031", "0.5190631", "0.51861715", "0.5185378", "0.51714057", "0.51714057", "0.51714057", "0.51701295", "0.5164489", "0.51620644", "0.5160768", "0.5158432", "0.51530933", "0.51530933", "0.5148822", "0.5138133", "0.5131937", "0.5131937", "0.5131937", "0.511501", "0.51078707", "0.50981414", "0.5094785", "0.50875264", "0.5070453", "0.50674874", "0.50673825", "0.5066882", "0.505717", "0.5056679", "0.505407", "0.5049707", "0.504593", "0.504507", "0.50340056", "0.50318176", "0.50318176", "0.50308424", "0.5020447", "0.50166553", "0.50166553", "0.50166553", "0.5015463", "0.5013489", "0.5012277", "0.5011134" ]
0.0
-1
convert TeX into PDF
def tex_compile(file) print File.basename(Dir.pwd) + '/' + file `platex -kanji="sjis" #{file}.tex` print "." `#{$bibtex} #{file}` print "." # some system needs three times compiles. 3.times do `platex -kanji="sjis" #{file}.tex` print "." end `dvipdfmx #{file}.dvi > #{$dev_null} 2>&1` puts "." end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_pdf\n\t\trequire 'erb'\n\t\trequire 'fileutils'\n @self = self\n template = ERB.new(LatexTemplate.where(model: self.class.to_s).first.template)\n directory = \"#{Rails.root}/tmp/pdf/#{self.class.to_s}/\"\n\t\tif not File.directory? directory\n\t\t\tFileUtils.mkpath(directory)\n\t\tend\n\t\tfile = \"#{directory}/#{self.id}.tex\"\n\t\tFile.open(file, 'w') do |f|\n # TODO: this is a potential security hole. But as we trust the user anyways, we don't give too much of a sh***\n\t\t\tf.write(template.result(binding))\n\t\tend\n\t\tIO.popen(\"pdflatex -output-directory #{directory} #{file}\") do |handle|\n\t\t\tpdflatex_output = handle.read\n\t\tend\n\t\tif $? == 0\n\t\t\treturn File.read(\"#{directory}/#{self.id}.pdf\")\n\t\telse\n\t\t\tlogger.error(pdflatex_output)\n return nil\n\t\tend\n end", "def to_pdf_file\n to_tex_file do |tex_path|\n Dir.mktmpdir(ident) do |output_directory|\n system pdftex, *PDFTEX_OPTIONS, \"--output-directory=#{output_directory}\", tex_path\n pdf_path = File.join(output_directory, ident + '.pdf')\n raise PDFConversionFailed, self unless File.exist?(pdf_path)\n\n yield pdf_path\n File.unlink pdf_path\n end\n end\n end", "def to_pdf\n file = get_path()\n ext = File.extname(file)\n if ['.png', '.gif', '.jpg'].include?(ext.downcase)\n # image\n \"<center><p><img src='#{make_path(file)}'></p></center>\"\n else\n # other file\n source = escape_xml(File.read(File.join(@base, file)))\n \"<table width='100%' border='0' cellpadding='10'><tr>\"+\n \"<td bgcolor='#F0F0F0'><pre>#{source}</pre>\"+\n \"</td></tr></table><p></p>\"\n end\n end", "def latex(s)\n convert(s, mime: 'text/latex')\n end", "def to_pdf\n to_prawn.render\n end", "def to_pdf\n indent = @lines.first.match(/\\$\\s*/)[0].length\n source = @lines.map{|line| escape_xml(line[indent..-1])}.join(\"\\n\")\n \"<table width='100%' border='0' cellpadding='10'><tr>\"+\n \"<td bgcolor='#F0F0F0'><pre>#{source}</pre>\"+\n \"</td></tr></table><p></p>\"\n end", "def to_pdf\n template = ERB.new(PDF_TEMPLATE, 0, '%')\n Iconv.conv(PDF_ENCODING, @properties['encoding'],\n template.result(binding))\n end", "def pdf_to_text\n page.driver.instance_variable_set('@body', pdf_string_to_text_string(page.body) )\n end", "def render(options)\n @tex_out = template_instance.render options\n Latex.new(:preprocess => preprocess, :debug => debug).generate_pdf(tex_out)\n end", "def to_pdf\n to_html\n end", "def latex_template\n @latex_template ||= File.new(\n File.expand_path(\"../../../../../templates/latex_for_pdf.erb\", __FILE__),\n 'r'\n ).read\n end", "def generate_pdf(input)\n create_debug_output(input) if options[:debug]\n check_for_tex_presence!\n create_pdf(input)\n end", "def to_pdf(force_render = false)\n tex_path = File.join(OUTPUT_DIR, \"#{base_name}.tex\")\n out = 'error'\n\n if !force_render && File.size?(pdf_path) && File.mtime(pdf_path) > @r.edited_at\n return pdf_path, 'cached'\n end\n\n Dir.mkdir(OUTPUT_DIR) unless File.directory?(OUTPUT_DIR)\n FileUtils.cp_r(STYLE_DIR, OUTPUT_DIR)\n\n Dir.chdir OUTPUT_DIR do\n File.open(tex_path, 'w') do |file|\n file.write to_tex\n end\n\n File.unlink(pdf_path) if File.file?(pdf_path)\n\n cmd = \"pdflatex --halt-on-error #{tex_path}\"\n \n # Compile tex source twice (to sync AUX file and stuff)\n out = `#{cmd} && #{cmd}`\n\n return pdf_path, out if File.size?(pdf_path)\n end\n\n return nil, out\n end", "def make_pdf(options = {}, main_body)\n w = Wkhtmltopdf.new(WickedPdf.config, options[:wkhtmltopdf])\n @content = w.pdf_from_string(main_body, options)\n end", "def to_pdf\n begin \n fo = StringIO.new(to_fo).to_inputstream\n fopfac = FopFactory.newInstance\n fopfac.setBaseURL( File.join(ASUtils.find_base_directory, 'stylesheets') ) \n fop = fopfac.newFop(MimeConstants::MIME_PDF, @output.to_outputstream) \n transformer = TransformerFactory.newInstance.newTransformer()\n res = SAXResult.new(fop.getDefaultHandler)\n transformer.transform(StreamSource.new(fo), res)\n ensure\n @output.close\n end\n @output \n end", "def get_pdf(x)\n end", "def make_pdf(template_path, pdf_name, landscape=false)\n prince = Prince.new()\n # Sets style sheets on PDF renderer.\n prince.add_style_sheets(\n \"#{RAILS_ROOT}/public/stylesheets/main.css\",\n \"#{RAILS_ROOT}/public/stylesheets/bracket.css\",\n \"#{RAILS_ROOT}/public/stylesheets/bracket-print.css\",\n \"#{RAILS_ROOT}/public/stylesheets/prince.css\"\n )\n prince.add_style_sheets(\"#{RAILS_ROOT}/public/stylesheets/prince_landscape.css\") if landscape\n # Render the estimate to a big html string.\n # Set RAILS_ASSET_ID to blank string or rails appends some time after\n # to prevent file caching, fucking up local - disk requests.\n old_rails_asset_id = ENV[\"RAILS_ASSET_ID\"]\n begin\n ENV[\"RAILS_ASSET_ID\"] = ''\n html_string = render_to_string(:template => template_path, :layout => 'print.html')\n # Make all paths relative, on disk paths...\n html_string.gsub!(\"src=\\\"\", \"src=\\\"#{RAILS_ROOT}/public\")\n # Send the generated PDF file from our html string.\n return prince.pdf_from_string(html_string)\n ensure\n ENV[\"RAILS_ASSET_ID\"] = old_rails_asset_id\n end\n end", "def latex_environment(type, el, text); end", "def process_pdf_file(pdf_file)\n pdf_dir = Pathname.new(pdf_file)\n pdf_dir = pdf_dir.dirname.to_s\n file_name = File.basename(pdf_file,\".pdf\").chomp\n txt_file = pdf_dir+\"/\"+file_name+\".txt\"\n if !File.exist?(txt_file)\n puts \"Convering \"+pdf_file+\" to \"+txt_file\n %x[pdftotext #{pdf_file}]\n %x[dos2unix #{txt_file}]\n end\n return txt_file\nend", "def to_latex(*)\n opts = options.merge(:text=>html, :file=>refile(:latex), :type=>:latex)\n Latex.new(opts)\n end", "def convert_html_to_pdf\n cmd = convert_html_to_pdf_command\n Rails.logger.info(\"Converting HTML to PDF\")\n Rails.logger.info(cmd)\n `#{cmd}`\n Rails.logger.info(\"Converted HTML to PDF\")\n end", "def to_pdf_file\n Dir.mktmpdir(ident) do |output_directory|\n string = self.string\n pdf_path = File.join(output_directory, ident + '.pdf')\n Prawn::Document.generate(pdf_path) do\n font_families.update 'ComicSans' => {normal: Rails.root.join('vendor', 'assets', 'fonts', 'ComicSans.ttf').to_s}\n font('ComicSans') { text string }\n end\n yield pdf_path\n end\n end", "def to_tex\n ERB.new(IO.read(TEMPLATE_PATH)).result(binding)\n end", "def pdf(html)\n WickedPdf.new.pdf_from_string(html,\n margin: {:top => 0, :bottom => 0, :left => 0, :right => 0})\n end", "def latex!\n ToLatex::LatexString.new self\n end", "def convert()\n errors = \"\"\n output = \"\"\n \n if @user_pwd \n cmd = \"pdftohtml -stdout #{@format} -upw #{@user_pwd}\" + ' \"' + @path + '\"' \n elsif @owner_pwd \n cmd = \"pdftohtml -stdout #{@format} -opw #{@owner_pwd}\" + ' \"' + @path + '\"'\n else\n cmd = \"pdftohtml -enc 'UTF-8' -stdout\" + ' \"' + @path + '\" \"' + @target + '\"'\n end\n \n output = `#{cmd} 2>&1`\n\n if (output.include?(\"Error: May not be a PDF file\"))\n raise PDFToHTMLRError, \"Error: May not be a PDF file (continuing anyway)\"\n elsif (output.include?(\"Error:\"))\n raise PDFToHTMLRError, output.split(\"\\n\").first.to_s.chomp\n else\n return output\n end\n end", "def to_pdf_data; end", "def render_latex(profile, options)\n require 'tilt/erb'\n template = Tilt.new('templates/cv.erb')\n output = template.render(self, :profile => profile, :options => options)\n output\n end", "def create_pdf(width, height)\n doc = HexaPDF::Document.new\n page = doc.pages.add\n page[:MediaBox] = [0, 0, width, height]\n page.canvas.draw(self, x: width / 2.0, y: height / 2.0)\n doc\n end", "def render_pdf(output, output_filename)\n output_file = File.new(output_filename, 'w')\n output_file.write(output)\n output_file.close\n\n # Make sure this variable is escaped, clearly.....\n system(\"pdflatex -output-directory=/tmp/ #{output_filename}\")\n end", "def convert_to_pdf(file, outdir)\n case file[:type]\n when 'image'\n img_to_pdf(file, outdir)\n when 'code'\n code_to_pdf(file, outdir)\n when 'document'\n doc_to_pdf(file, outdir)\n when 'cover'\n cover_to_pdf(file, outdir)\n end\n end", "def code_to_pdf(file, outdir)\n # decide language syntax highlighting\n case file[:ext]\n when '.cpp', '.cs'\n lang = :cplusplus\n when '.c', '.h'\n lang = :c\n when '.java'\n lang = :java\n when '.pas'\n lang = :delphi\n else\n # should follow basic C syntax (if, else etc...)\n lang = :c\n end\n # code -> HTML\n html_body = CodeRay.scan_file(file[:actualfile], lang).html(:wrap => :div, :tab_width => 2, :css => :class, :line_numbers => :table, :line_number_anchors => false)\n\n # HTML -> PDF\n kit = PDFKit.new(html_body, :page_size => 'A4', :header_right => \"[page]/[toPage]\", :margin_top => \"10mm\", :margin_right => \"5mm\", :margin_bottom => \"5mm\", :margin_left => \"5mm\", :lowquality => true, :minimum_font_size => 8)\n kit.stylesheets << Rails.root.join(\"vendor/assets/stylesheets/coderay.css\")\n kit.to_file(outdir)\n end", "def TeX2htm(text,state=:normal,fname=\"\",sec=\"\")\n sp=proc{|s| $trads[$key.succ!]=s; \"\\\\#{$key} \"}\n mathdisplay=proc{|s|\n sp[TeX2htm(s,:math).h(\"I\").h(\"td\").h(\"tr\").h(\"table\").h(\"center\")]}\n text=text.gsub(/([^\\\\]|^)%.*/){m=$~;m[1]} # suppress tex comments\n unless state==:math\n text.gsub!(/\\\\$/,\"\\\\ \")\n vb=/\\|'\\\\\\|'\\|/ # a | in verbatim\n vb2=/\\|\\s*\\{\\s*\\\\tt\\s*\\\\\\|\\s*\\}\\s*\\|/ # another way for | in verbatim\n vbb=/(?:#{vb2}|#{vb})/o\n text.gsub!(/([^\\\\]|^|\\\\\\\\)\\|((?:[^|]|#{vbb})*)\\|/om){ m=$~\n if m[2]=~/\\n/\n m[1]+sp[m[2].gsub(vbb,\"|\").lines.map{|l| v=l.split(\"#\");\n\tv[0].gsub!(/&/,\"#\");v[0].gsub!(/</,\"&lt;\");\n\tif v[1] then v[1]=TeX2htm(v[1]); v.join(\"#\")\n\telse v[0]\n\tend}.join.h(\"pre\")]\n else m[1]+sp[m[2].gsub(vbb,\"|\").gsub(/&/,\"#\").gsub(/</,\"&lt;\").clean.h(\"code\")]\n end\n }\n text.gsub!(/\\$\\$(.*?)\\$\\$/m){m=$~; mathdisplay[m[1]]}\n text.gsub!(/\\\\\\[(.*?)\\\\\\]/m){m=$~; mathdisplay[m[1]]}\n text.gsub!(/([^\\\\]|^)\\$(.*?)\\$/m){m=$~\n m[1]+sp[TeX2htm(m[2],:math).h(\"I\")]}\n text.gsub!(/([^\\\\]|^)\\*([^*]*)([^\\\\])\\*/){m=$~;\n m[1]+sp[(m[2]+m[3]).h(\"strong\")]}\n end\n text.gsub!(/\\\\\\\\/){\"\\\\cr\"}\n text.gsub!(/([^\\\\])<([^>]*)>/m){m=$~;m[1]+sp[TeX2htm(m[2]).h(\"var\")]}\n text.gsub!(/([^\\\\]|^)'((?:[^']|\\\\')*)([^\\\\])'/m){m=$~;\n m[1]+sp[(m[2]+m[3]).clean.h(\"code\")]}\n text.gsub!(/([^\\\\]|^)\\\\([*{}|': <>;,#~-])/){m=$~;m[1]+sp[OneChar[m[2]]]}\n text.gsub!(/([^\\\\]|^)\\\\([*{}|': <>;,#~-])/){m=$~;m[1]+sp[OneChar[m[2]]]}\n unless state==:math\n text.gsub!(/^\\s*$/,\"\\\\par\")\n text.gsub!(/^\\s*\\\\vspace\\{[^}]*\\}\\s*$/,\"\\\\par\")\n text.gsub!(/^([^:\\n]*)([^\\\\]):(.*?)(?=\\\\par)/m){m=$~\n sp[\"<DL><DT>#{TeX2htm(m[1]+m[2])}:<DD>\"]+\"#{m[3]}\"+sp[\"</DL>\"]}\n text.gsub!(/\\\\cr/){sp[\"<BR>\"]}\n # characters that can appear in a cross reference\n text.gsub!(/([^\\\\]|^)\"([\\w\\s.$-]*)\"/m){m=$~;\n m[1]+sp[\"<a href=\\\"#{name2fn m[2]}\\\">#{m[2]}</a>\"]}\n text.gsub!(/\\\\\"/){sp['\"']}\n text.gsub!(/\\\\cite(?:\\[([^\\]\\[]*)\\])?\\s*\\{\\s*((?:\\w|,)+)\\s*\\}/m) { m=$~\n r=\"<A href=\\\"biblio.htm##{m[2].split(\",\")[0]}\\\">#{m[2].h(\"cite\")}</a>\"\n r<< \", \"+m[1] if m[1]\n sp[r] }\n text.gsub!(/\\\\accent\\s*([0-9]*)\\s*([a-zA-Z])/m){m=$~\n a=Accents[m[1]+m[2]]\n if a then a\n else $err.print \"** unhandled accent #{fname}:#{sec} #{m[0]}\\n\"\n end}\n text.gsub!(/\\\\psubsection\\s*\\{(.*?)\\}/m){m=$~; m[1].h(\"h3\")}\n text.gsub!(/\\\\psection\\s*\\{(.*?)\\}/m){m=$~;m[1].h(\"h1\").style(\"color:#ff0000\")}\n text.gsub!(/\\\\index\\s*\\{(.*?)\\}/m){m=$~\n $indexcount+=1 # emit an anchor and remember the index keys for later\n r=m[1].gsub(/\\\\([a-zA-Z]+) /){m=$~; $trads[m[1]] || \"\\\\#{m[1]} \"}\n $index[r]=$index[r].push([\"#{fname}#I#{$indexcount}\",\"#{sec.chapnum}.#{sec.secnum}\"])\n \"<A name = \\\"I#{$indexcount}\\\"></a>\\n\"\n }\n text.gsub!(/\\\\begin\\{([^}]*)\\}(.*?)\\\\end\\{\\1\\}/m){m=$~\n case m[1]\n when \"displaymath\",\"equation\" then mathdisplay[m[2]]\n when \"center\" then m[2].h(\"center\")\n when \"itemize\",\"enumerate\" then m[2]\n else \"{beg-\"+m[1]+\"}\".h(\"s\")+m[2]+\"{end-\"+m[1]+\"}\".h(\"s\")\n end}\n text.gsub!(/~/,\" \")\n end\n# nestedbraces=// # can define but not recognized inside another regexp\n# text.gsub!(/\\\\(\\s)/){m=$~;m[1]}\n text.gsub!(/\\{\\s*\\\\(?:sl|it)([^}]*)\\}/m){m=$~;\n sp[TeX2htm(m[1],state).h(\"I\")]}\n text.gsub!(/\\{\\s*\\\\cal([^}]*\\{[^}]*\\}[^}]*)\\}/m){sp[$~[1].style(\"font-family: cursive\")]}\n text.gsub!(/\\{\\s*\\\\cal([^}]*)\\}/m){sp[$~[1].style(\"font-family: cursive\")]}\n text.gsub!(/\\{\\s*\\\\tt([^}]*\\{[^}]*\\}[^}]*)\\}/m){m=$~;sp[m[1].h(\"code\")]}\n text.gsub!(/\\{\\s*\\\\tt([^}]*)\\}/m){m=$~;sp[m[1].h(\"code\")]}\n text.gsub!(/\\{\\s*\\\\bf([^}]*\\{[^}]*\\}[^}]*)\\}/m){m=$~;sp[m[1].h(\"strong\")]}\n text.gsub!(/\\{\\s*\\\\bf([^}]*)\\}/m){m=$~;sp[m[1].h(\"strong\")]}\n text.gsub!(/\\{\\s*\\\\em([^}]*\\{[^}]*\\}[^}]*)\\}/m){m=$~;sp[m[1].h(\"em\")]}\n text.gsub!(/\\{\\s*\\\\em([^}]*)\\}/m){m=$~;sp[m[1].h(\"em\")]}\n if state==:math\n text.gsub!(/</){sp[\"&lt;\"]}\n text.gsub!(/>/){sp[\"&gt;\"]}\n texarg=/([^{\\\\]|\\{(?:(?:[^{}]|\\{[^{}]*\\})*)\\}|\\\\[a-zA-Z]+)/\n text.gsub!(/\\^\\\\prime/om){sp[\"'\"]}\n text.gsub!(/\\^\\{\\\\prime\\\\prime\\}/om){sp[\"''\"]}\n text.gsub!(/\\\\not\\s*\\\\equiv/om){sp[\"&#8802;\"]}\n text.gsub!(/\\\\(?:text|mbox|hbox)\\{([^{}]*)\\}/){m=$~;\n sp[TeX2htm(m[1]).h(\"/i\")]}\n text.gsub!(/\\^\\s*#{texarg}/om){m=$~;sp[TeX2htm(m[1],:math).h(\"sup\")]}\n text.gsub!(/_\\s*#{texarg}/om){m=$~;sp[TeX2htm(m[1],:math).h(\"sub\")]}\n text.gsub!(/\\\\underline\\s*#{texarg}/om){m=$~;sp[TeX2htm(m[1],:math).h(\"u\")]}\n text.gsub!(/\\\\overline\\s*#{texarg}/om){m=$~;\n sp['<span style=\"text-decoration: overline\">'+\n TeX2htm(m[1],:math)+\"<\\/span>\"]}\n text.gsub!(/\\{\\s*\\\\rm([^}]*)\\}/m){m=$~;sp[m[1].h(\"I\")]}\n text.gsub!(/\\{\\s*\\\\mathcal([^}]*)\\}/m){m=$~;sp[m[1].h(\"u\")]}\n text.gsub!(/\\\\frac#{texarg}#{texarg}/om){m=$~;\n n=TeX2htm(m[1],'math'); d=TeX2htm(m[2],'math')\n n=\"(#{n})\" if n.length>1\n d=\"(#{d})\" if n.length>1\n \"#{n}/#{d}\"}\n text.gsub!(/\\\\not\\s*\\\\in/){sp[\"&notin;\"]}\n text.gsub!(/\\\\not\\s*=/){sp[\"&ne;\"]}\n text.gsub!(/\\\\([a-zA-Z]+)/){m=$~;\n if MathMacs[m[1]] then sp[MathMacs[m[1]]] else m[0] end}\n text.gsub!(/\\\\pmod\\s*#{texarg}/){m=$~;sp[\"(</i>mod<i> #{TeX2htm(m[1],:math)})\"]}\n text.gsub!(/\\\\begin\\{([^}]*)\\}(.*?)\\\\end\\{\\1\\}/m){m=$~\n case m[1]\n when \"array\",\"pmatrix\" then \n if m[1]==\"array\" then r=m[2].sub(/\\{[cl]*\\}/,\"\") else r=m[2] end\n r=r.split(\"\\\\cr\").map{|l| l.split(\"&\").map{|i| \n i.h(\"I\").h(\"td\")}.join(\"\").h(\"tr\")}.join.h('table style=\"display:inline-table;\"').h(\"td\").h(\"/td\")\n if m[1]==\"pmatrix\" then \"(\"+r+\")\" else r end\n else \"{beg-\"+m[1]+\"}\".h(\"s\")+m[2]+\"{end-\"+m[1]+\"}\".h(\"s\")\n end\n }\n end\n text.gsub!(/\\\\(?:text|mbox|hbox)\\{([^{}]*)\\}/){m=$~;\n sp[TeX2htm(m[1]).h(\"/i\")]}\n text.gsub!(/\\\\([a-zA-Z]+)/){m=$~;AlwaysMacs[m[1]] || m[0]}\n text.gsub!(/\\{([^{}]*)\\}/){m=$~; m[1]}\n text.gsub!(/\\\\([a-zA-Z]+) /){m=$~; $trads[m[1]] || \"\\\\#{m[1]} \"}\n text.gsub!(/\\\\([a-zA-Z]+) /){m=$~; $trads[m[1]] || \"\\\\#{m[1]} \"}\n text.gsub!(/\\\\([a-zA-Z]+)/){m=$~; $trads[m[1]] || \"\\\\#{m[1]}\"}\n text.scan(/\\\\([a-zA-Z]+)/){|m| $err.print \"!!!!! #{m.inspect} state=#{state}\\n\"}\n text\nend", "def convert_pdf_to_html file\n PDFToHTMLR::PdfFilePath.new(file).convert.force_encoding(\"UTF-8\")\n end", "def create_pdf\n File.open(@path, 'wb') do |file|\n file << rendered_pdf\n end\n end", "def to_pdf(file, options = {})\n drawing_block = Proc.new do |pdf|\n draw_crossword(pdf, :solved => false, :indexes => true)\n pdf.move_down PDF_CELL_SIZE\n if options[:include_solution]\n cursor = pdf.cursor\n draw_crossword(pdf, :solved => true, \n :at => [pdf.bounds.width - PDF_CELL_SIZE*(dimensions[:horizontal])/2, \n pdf.cursor + PDF_CELL_SIZE*(dimensions[:vertical])/2],\n :scale => 0.5,\n :inverted => true)\n \n pdf.move_cursor_to cursor #- PDF_CELL_SIZE\n end\n pdf.move_down PDF_CELL_SIZE\n draw_definitions(pdf)\n end\n if file.is_a?(Prawn::Document)\n drawing_block.call(file)\n else\n Prawn::Document.generate(file, &drawing_block)\n end\n end", "def convert_to_latex(node)\n latex_code = nil\n Open3.popen3(\"pandoc -f json -t latex --wrap=none\") {|stdin, stdout, stderr, wait_thr|\n stdin.write(node.to_json)\n stdin.close # stdin, stdout and stderr should be closed explicitly in this form.\n latex_code = stdout.read\n\n pid = wait_thr.pid # pid of the started process.\n exit_status = wait_thr.value # Process::Status object returned.\n }\n latex_code\n end", "def to_pdf(options={})\n self.to_pdf_writer(options).render\n end", "def show\n @exercice = Exercice.find(params[:id])\n content = render_to_string(:template => \"/exercices/show.pdf.erb\", :layout => true)\n puts content\n puts \"###################################################################\"\n target = \"/var/www/ludo/public/pdf/temp.pdf\"\n File.open(target, \"w+\") do |f|\n f.write(content)\n end\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @exercice }\n format.pdf { render pdf: @exercice }\n end\n end", "def make_pdf purchase, experience\n pdf = Prawn::Document.new :page_layout => :portrait\n\n # Para dibujar los ejes\n # pdf.fill_color \"363636\"\n # stroke_axis pdf\n\n # Header\n pdf.fill_color \"363636\"\n pdf.fill_rectangle [0, 720], 540, 40\n\n # Logo PuntosPoint\n pdf.image \"/#{Rails.root}/app/assets/images/logo_grande.png\", :at => [10, 670], width: 178, height: 70\n\n # Linea (como si fuera un hr)\n pdf.move_down 130\n pdf.stroke_horizontal_rule\n\n # Imagen de la experiencia\n p experience.image.url(:thumb)\n image = experience.image.url\n pdf.image open(image), :at => [10, 580], width: 184, height: 137\n\n y_coordinate = 0\n\n # Datos de la experiencia\n pdf.bounding_box([205, 580], :width => 320, :height => 330) do\n # Para dibujar contexto\n # pdf.stroke_bounds\n\n # Nombre Experiencia\n pdf.font_size 14\n pdf.font 'Helvetica', style: :bold\n pdf.text experience.name, :align => :justify\n\n # Enganche Experiencia\n pdf.font_size 10\n pdf.font 'Helvetica', style: :normal\n pdf.fill_color \"006699\"\n pdf.text experience.summary, :align => :justify\n\n # Detalles\n pdf.move_down 20\n pdf.fill_color \"363636\"\n pdf.text \"<b>#{Experience.human_attribute_name(:place)}:</b> #{experience.place}\", :inline_format => true, :leading => 5, :align => :justify\n # pdf.text \"<b>#{Experience.human_attribute_name(:comuna)}:</b> #{experience.comuna_name}\", :inline_format => true, :leading => 5, :align => :justify\n pdf.text \"<b>#{Experience.human_attribute_name(:validity_starting_at)}:</b> #{I18n.l experience.validity_starting_at, format: :long}\", :inline_format => true, :leading => 5, :align => :justify\n pdf.text \"<b>#{Experience.human_attribute_name(:validity_ending_at)}:</b> #{I18n.l experience.validity_ending_at, format: :long}\", :inline_format => true, :leading => 5, :align => :justify\n\n # 580 : Posicion Y del bounding_box\n # 330 : Alto máximo del bounding_box\n # pdf.cursor : Espacio del bounding_box no utilizado\n # 430 : Alto mínimo\n y_coordinate = [580 - 330 + pdf.cursor, 430].min\n end\n\n # Dejo el cursor en la ultima linea donde se escribio en el bounding_box anterior\n pdf.move_cursor_to y_coordinate\n\n # Agrando la fuente para los códigos\n pdf.font_size 12\n\n alto = 40\n ancho = 240\n\n # Código interno\n pdf.fill_color \"DDDDDD\"\n pdf.fill_rounded_rectangle [10, pdf.cursor], ancho, alto, 5\n pdf.fill_color \"363636\"\n pdf.bounding_box([20, pdf.cursor - (alto - pdf.font_size)/2], width: ancho, height: alto) do\n pdf.text \"Ticket de Compra: <b>#{@purchase.code}</b>\", :inline_format => true\n end\n\n # Códigos de validación\n pdf.fill_color \"DDDDDD\"\n pdf.fill_rounded_rectangle [10, pdf.cursor], ancho, alto + @purchase.reference_codes.count * (pdf.font_size + 2), 5\n pdf.fill_color \"363636\"\n\n pdf.bounding_box([20, pdf.cursor - (alto - pdf.font_size)/2], width: ancho - 20, height: pdf.font_size) do\n pdf.text \"#{Purchase.human_attribute_name(:reference_codes)}:\", :inline_format => true\n end\n\n pdf.bounding_box([20, pdf.cursor - (alto - pdf.font_size)/2 + pdf.font_size], width: ancho - 20, height: @purchase.reference_codes.count * (pdf.font_size + 2)) do\n @purchase.reference_codes.each_with_index do |rc, index|\n pdf.text \"<b>#{rc}</b>\", :inline_format => true, :align => :center\n end\n end\n\n # Forma de canje de la Experiencia\n pdf.font_size 10\n pdf.fill_color \"DDDDDD\"\n # NOTA: Para usar todo el alto disponible cambiar 150 => y_coordinate\n pdf.fill_rounded_rectangle [260, y_coordinate], 265, 150, 5\n pdf.fill_color \"363636\"\n # NOTA: Para usar todo el alto disponible usar height: y_coordinate - 20\n pdf.bounding_box([270, y_coordinate - 10], :width => 245, :height => 125) do\n # Para dibujar contexto\n # pdf.stroke_bounds\n\n # Título\n pdf.font_size 14\n pdf.text \"<b>#{Experience.human_attribute_name(:exchange_mechanism)}</b>\", :inline_format => true\n pdf.text \"\\n\"\n pdf.font_size 10\n\n # Mas información en: http://www.w3schools.com/tags/ref_entities.asp\n irregular_words = [\n [/&quot;/, '\"'],\n [/&apos;/, \"'\"],\n [/&amp;/, '&'],\n [/&lt;/, '<'],\n [/&gt;/, '>'],\n\n [/&nbsp;/, ' '],\n [/&iexcl;/, '¡'],\n [/&cent;/, '¢'],\n [/&pound;/, '£'],\n [/&curren;/, '¤'],\n [/&yen;/, '¥'],\n [/&brvbar;/, '¦'],\n [/&sect;/, '§'],\n [/&uml;/, '¨'],\n [/&copy;/, '©'],\n [/&ordf;/, 'ª'],\n [/&laquo;/, '«'],\n [/&not;/, '¬'],\n [/&shy;/, ''],\n [/&reg;/, '®'],\n [/&macr;/, '¯'],\n [/&deg;/, '°'],\n [/&plusmn;/, '±'],\n [/&sup3;/, '³'],\n [/&acute;/, '´'],\n [/&micro;/, 'µ'],\n [/&para;/, '¶'],\n [/&middot;/, '·'],\n [/&cedil;/, '¸'],\n [/&sup1;/, '¹'],\n [/&ordm;/, 'º'],\n [/&raquo;/, '»'],\n [/&frac14;/, '¼'],\n [/&frac12;/, '½'],\n [/&frac34;/, '¾'],\n [/&iquest;/, '¿'],\n [/&times;/, '×'],\n [/&divide;/, '÷'],\n\n [/&Agrave;/, 'À'],\n [/&Aacute;/, 'Á'],\n [/&Acirc;/, 'Â'],\n [/&Atilde;/, 'Ã'],\n [/&Auml;/, 'Ä'],\n [/&Aring;/, 'Å'],\n [/&AElig;/, 'Æ'],\n [/&AElig;/, 'Æ'],\n [/&Ccedil;/, 'Ç'],\n [/&Egrave;/, 'È'],\n [/&Eacute;/, 'É'],\n [/&Ecirc;/, 'Ê'],\n [/&Euml;/, 'Ë'],\n [/&Igrave;/, 'Ì'],\n [/&Iacute;/, 'Í'],\n [/&Icirc;/, 'Î'],\n [/&Iuml;/, 'Ï'],\n [/&ETH;/, 'Ð'],\n [/&Ntilde;/, 'Ñ'],\n [/&Ograve;/, 'Ò'],\n [/&Oacute;/, 'Ó'],\n [/&Ocirc;/, 'Ô'],\n [/&Otilde;/, 'Õ'],\n [/&Ouml;/, 'Ö'],\n [/&Oslash;/, 'Ø'],\n [/&Ugrave;/, 'Ù'],\n [/&Uacute;/, 'Ú'],\n [/&Ucirc;/, 'Û'],\n [/&Uuml;/, 'Ü'],\n [/&Yacute;/, 'Ý'],\n [/&THORN;/, 'Þ'],\n [/&szlig;/, 'ß'],\n\n [/&agrave;/, 'à'],\n [/&aacute;/, 'á'],\n [/&acirc;/, 'â'],\n [/&atilde;/, 'á'],\n [/&auml;/, 'ä'],\n [/&aring;/, 'å'],\n [/&aelig;/, 'æ'],\n [/&ccedil;/, 'ç'],\n [/&egrave;/, 'è'],\n [/&eacute;/, 'á'],\n [/&ecirc;/, 'ê'],\n [/&euml;/, 'ë'],\n [/&igrave;/, 'ì'],\n [/&iacute;/, 'í'],\n [/&icirc;/, 'î'],\n [/&iuml;/, 'ï'],\n [/&eth;/, 'ð'],\n [/&ntilde;/, 'ñ'],\n [/&ograve;/, 'ò'],\n [/&oacute;/, 'ó'],\n [/&ocirc;/, 'ô'],\n [/&otilde;/, 'õ'],\n [/&ouml;/, 'ö'],\n [/&oslash;/, 'ø'],\n [/&ugrave;/, 'ù'],\n [/&uacute;/, 'ú'],\n [/&ucirc;/, 'û'],\n [/&uuml;/, 'ü'],\n [/&yacute;/, 'ý'],\n [/&thorn;/, 'þ'],\n [/&yuml;/, 'ÿ'],\n\n [/&euro;/, '€'],\n [/&trade;/, '™']\n ]\n\n # Quito tags HTML que prawn no conoce\n exchange_mechanism = experience.exchange_mechanism.html_safe.gsub(/<\\/?[^>]+>/, '')\n irregular_words.each do |irregular_word|\n exchange_mechanism = exchange_mechanism.gsub(irregular_word[0], irregular_word[1])\n end\n\n # NOTA: Para usar todo el alto disponible\n # pdf.text_box exchange_mechanism, at: [0, pdf.cursor], :width => ancho, :height => y_coordinate - (y_coordinate - pdf.cursor), :overflow => :truncate, :align => :justify\n pdf.text_box exchange_mechanism, at: [0, pdf.cursor], :width => ancho, :height => 100, :overflow => :truncate, :align => :justify\n end\n\n return pdf\n end", "def to_tex_file\n check_security!\n\n Dir.mktmpdir(ident) do |output_directory|\n tex_path = File.join(output_directory, ident + '.tex')\n File.open(tex_path, 'w') { |f| f.puts wrapped_equation }\n yield tex_path\n File.unlink tex_path\n end\n end", "def output_pdf_data\n options = {\n delinearize: true,\n recompile: true,\n decrypt: false\n }\n\n pdf.delinearize! if pdf.linearized?\n pdf.send(:compile, options)\n pdf.send(:output, options)\n end", "def render\n @pdf.render\n end", "def render\n generate_content\n @pdf.render\n end", "def toPDF()\n doc = Prawn::Document.new(:compress => true, :page_size => [500, 280])\n doc.font 'Times-Roman'\n \n # Les images pour le background, le logo, la signature du tresorier\n doc.image \"public/images/recus/recu.png\", :at => [0, 200]\n doc.image \"public/images/recus/logo112x87.png\", :at => [370, 195], :fit => [56, 44]\n doc.image \"public/images/recus/signature_recu.png\", :at => [280, 80], :fit => [147,42]\n\n # Boite avec les informations principales du recu\n doc.bounding_box([5,180], :width => 500) do\n doc.text \"Date: \" + DateTime.now.strftime('%Y-%m-%d')\n \n doc.move_down 42\n annee = DateTime.now.strftime('%Y')\n doc.text \"Reçu pour abonnement à la piscine Dixie \" + annee, :style => :bold\n doc.text \"Receipt for Dixie pool registration \" + annee, :style => :bold\n \n doc.move_down 10\n doc.text \"Nom/Name: \" + nom\n doc.text \"Montant perçu/Amount paid: \" + sprintf('$%6.2f', @famille.paiementTotal)\n end\n \n # Boite avec les coordonnes de la piscine. En haut a droite avec le logo dedans\n doc.bounding_box([220, 195], :width => 210, :height => 45) do\n doc.stroke_bounds\n doc.bounding_box([2, 43], :width => 210) do\n doc.text \"Association Piscine Dixie Inc.\"\n doc.text \"CP 34045\"\n doc.text \"Lachine, Qc, H8S 4H4\"\n end\n end\n \n # Sous la signature\n doc.draw_text \"Trésorier / Treasurer\", :at => [300, 30]\n \n return doc\n end", "def convertToTeX(str)\n str.gsub(DEC) do |match|\n if DEC2TEX.has_key? match\n DEC2TEX[match]\n else\n match\n end\n end.gsub(HEX) do |match|\n key = match.downcase\n if HEX2TEX.has_key? key\n HEX2TEX[key]\n else\n match\n end\n end\nend", "def convert_to_pdf!\n if content_type == 'application/pdf'\n return stamp_pdf!\n else\n command = \"export LD_LIBRARY_PATH=/opt/openoffice.org2.4_sdk/linux/lib:/opt/openoffice.org2.4/program/; #{RAILS_ROOT}/lib/pdfconvert/convert.php #{self.versions[:original].path} \\\"\\\" #{self.versions[:pdf].path}\"\n RAILS_DEFAULT_LOGGER.info { \"--Converting file to pdf:\\n Command: #{command}\" }\n result = `#{command}`\n RAILS_DEFAULT_LOGGER.info { \"#{result}\" }\n RAILS_DEFAULT_LOGGER.info { \" --> Result: #{$?}\" }\n out = $?\n\n if result.to_s.include?(\"couldn't connect to socket\") || result.to_s.include?(\"error\") || !out.success?\n Thread.current['pdf_conversion_error'] = \"Could not convert document to PDF: #{result.to_s}\"\n else\n Thread.current['pdf_conversion_error'] = nil\n end\n \n stamp_pdf! if out.success?\n return out\n end\n end", "def in2pts(x)\n PDF::Writer.in2pts(x)\n end", "def to_latex(*args)\n @output_format = :latex\n @options += args\n convert\n end", "def generate_pdf(filename)\n @destination_path = \"#{Rails.root}/public/files/\"+filename.remove('pptx')+'pdf'\n Libreconv.convert( @files.to_s, @destination_path, nil, 'pdf:writer_pdf_Export')\n # Docsplit.extract_pdf(@files.to_s)\n\n # Creates the manipulated pptx file physically\n FileUtils.mv @files.to_s, \"#{Rails.root}/public/files/\"+filename\n @destination_path\n end", "def make_pdf(opts = {})\r\n @pdf = true\r\n @debug_pdf = params[:debug_pdf]\r\n params[:format] = 'html'\r\n html = render_to_string(:action => \"#{opts.delete(:action) || params[:action]}.html.erb\", :layout => (opts.delete(:layout) || 'pdf')) # layout not taken\r\n if !@debug_pdf\r\n html.gsub!(/\\/images\\//, Rails.root.join('public', 'images/').to_s)\r\n else\r\n render(:text => html, :layout => false) and return\r\n end\r\n kit = PDFKit.new(html, opts.merge(:encoding => 'UTF-8'))\r\n kit.stylesheets << Rails.root.join('public', 'stylesheets', 'pdf.css')\r\n return kit.to_pdf\r\n end", "def extractTextFromPDF(filename)\n\tif ENV['OS'] == \"Windows_NT\"\n\t\tpdftotextexec = File.expand_path(File.dirname(__FILE__)) + \"/pdftotext.exe\"\n\telse\n\t\tpdftotextexec = \"pdftotext\"\n\tend\n\ttext = `\"#{pdftotextexec}\" \"#{filename}\" -`\nend", "def to_tex(\n lang = I18n.locale,\n db_table = \"db_table_name\",\n title = \"Jasper ist doof 3\",\n lecturer_first = \"Oliver\",\n lecturer_last = \"Istdoof\",\n gender = :both,\n tutors = [\"Mustafa Mustermann\", \"Fred Nurk\", \"Ashok Kumar\",\n \"Juan Pérez\", \"Jakob Mierscheid\", \"Iwan Iwanowitsch\",\n \"Pierre Dupont\", \"John Smith\", \"Eddi Exzellenz\",\n \"Joe Bloggs\", \"John Doe\", \"Stefan ist doof\",\n \"Beccy ist doof\"],\n term = \"the same term as last year\",\n barcode = \"00000000\")\n\n # in case someone didn’t give us symbols\n lang, gender = lang.to_sym, gender.to_sym\n\n # set lang and load locales for default strings that are not part of\n # the form\n I18n.locale = lang\n I18n.load_path += Dir.glob(File.join(Rails.root, 'config/locales/*.yml'))\n I18n.load_path.uniq!\n\n tex = \"\"\n\n # form header and preamble\n tex << \"\\\\documentclass[#{I18n.t(:tex_babel_lang)}]{eval}\\n\"\n tex << \"\\\\lecturerFirst{#{lecturer_first.escape_for_tex}}\\n\"\n tex << \"\\\\lecturerLast{#{lecturer_last.escape_for_tex}}\\n\"\n tex << \"\\\\lecture{#{title.escape_for_tex}}\\n\"\n tex << \"\\\\dbtable{#{db_table}}\\n\"\n tex << \"\\\\term{#{term.escape_for_tex}}\\n\"\n tex << \"\\\\noAnswerText{#{I18n.t(:no_answer)}}\\n\"\n # note: these cannot be customized per tutor, as the tutor is not\n # known yet. They will be filled in result.pdf, so give placeholders\n # instead.\n tex << \"\\\\setTutor{#{I18n.t(:tutor)}}\\n\"\n tex << \"\\\\setMyTutor{#{I18n.t(:my_tutor)}}\\n\"\n\n # tutors\n tutors.collect! { |t| t.escape_for_tex }\n tex << \"\\\\tutors{\\n \"\n (0..(TUTOR_BOX_COUNT-2)).each do |i|\n tex << \"\\\\tutorbox[#{i+1}][#{tutors[i] || \"\\\\\\\\ \"}]\".ljust(35)\n tex << ((i%5 == 4) ? '\\\\\\\\'+\"\\n \" : ' & ')\n end\n tex << \"\\\\tutorbox[#{TUTOR_BOX_COUNT}][\\\\ #{I18n.t(:none)}] \\n\"\n tex << \"}\\n\\n\"\n\n tex << get_texhead(lang) + \"\\n\"\n tex << \"\\\\begin{document}\\n\"\n tex << tex_header(lang, gender, barcode) + \"\\n\\n\\n\"\n tex << tex_questions(lang, gender) + \"\\n\"\n tex << get_texfoot(lang) + \"\\n\"\n tex << \"\\\\end{document}\"\n\n tex\n end", "def pdf\n base = Estimate.get_base\n estimate = base.fetch_by_id(id)\n return base.pdf(estimate)\n end", "def render_pdf\n Payday::PdfRenderer.render(self)\n end", "def pdf\n #render layout: false\n Car.find(params[:id])\n Prawn::Document.generate(\"app/assets/pdf/#{@car.targa}.pdf\") do |f|\n f.text \"Hello Worldd!\"\n end\n end", "def t4\n annee = params[:annee].to_i\n copies = (params[:dest] == 'employe' ? 2 : 1)\n employeur = Employeur.find(params[:id])\n doc = Prawn::Document.new(:skip_page_creation => true, :margin => 0)\n T4.renderMultiple(doc, Employe.employesPayes(annee), employeur, annee, copies)\n send_data doc.render, :filename => 't4-' + annee.to_s + '.pdf', :type => 'application/pdf', :disposition => 'inline'\n end", "def latex?\n false\n end", "def compile_text(tmp)\n @prefilters.each do |f| \n tmp=f.run( tmp )\n end\n\n # compile to latex\n # puts tmp\n tmp=Kramdown::Document.new(tmp, @kramdown_opts).to_html\n\n # post filters\n @postfilters.each{ |f| tmp=f.run(tmp) }\n return tmp\n end", "def render_as_format(from, to, format)\n puts \"Hola, bon dia!!\"\n puts from\n puts to\n thefile = `iconv -f ISO8859-1 #{from}`\n dotfile = Tempfile.new('dot')\n begin\n model = T2Flow::Parser.new.parse(thefile)\n T2Flow::Dot.new.write_dot(dotfile, model)\n dotfile.close\n `dot -T#{format} -o\"#{to}\" #{dotfile.path}`\n ensure\n dotfile.unlink\n end\nend", "def convert_to_pdf(reportfile, pdfname)\n\n cmd = \"/usr/bin/unoconv -no #{pdfname} -f pdf #{reportfile}\"\n logger.debug \"Executing command \\'#{cmd}\\'\"\n output,returncode = Open3.capture2e(cmd) \n logger.debug \"Command output #{output} (returncode #{returncode})\"\n\t\treturncode\n end", "def render_pdf src, *opts\n render src, {render: {format: 'pdf'}}, *opts\n end", "def generate_html_and_make_pdf(folder, html_content, html_name, pdf_name, pdf_options)\n generate_html(folder, html_content, html_name)\n convert_html_to_pdf(folder, html_name, pdf_name, pdf_options)\n end", "def render_pdf_to_file(path)\n Payday::PdfRenderer.render_to_file(self, path)\n end", "def wiki_page_to_pdf(page, project)\n pdf = ITCPDF.new(current_language)\n pdf.SetTitle(\"#{project} - #{page.title}\")\n pdf.alias_nb_pages\n pdf.footer_date = format_date(Date.today)\n pdf.AddPage\n pdf.SetFontStyle('B',11)\n pdf.RDMMultiCell(190,5,\n \"#{project} - #{page.title} - # #{page.content.version}\")\n pdf.Ln\n # Set resize image scale\n pdf.SetImageScale(1.6)\n pdf.SetFontStyle('',9)\n write_wiki_page(pdf, page)\n pdf.Output\n end", "def pdf_template\n 'pro/subscriptions/invoices.pdf.haml'\n end", "def generate\n add_intro\n add_blood_pressure_intro\n add_blood_pressure_list\n add_blood_pressure_outro\n add_medications_intro\n add_medications_list\n add_about\n\n @pdf\n end", "def generate_pdf(report_data)\n Prawn::Document.new do\n text report_data\n end.render\n end", "def save_ctacte_pdf_to(filename,entity)\n require 'prawn'\n \n pdf = Prawn::Document.new(:left_margin => 35, :top_margin => 35,:page_size => \"LETTER\",\n :page_layout => :portrait)\n offset = 0\n\n pdf.repeat(:all, :dynamic => true) do\n pdf.draw_text (\"Cuenta corriente de \" + entity.first.try(:cliente).razonsocial + \" impreso el \" + Date.today.strftime(\"%d/%m/%Y\")) , :at => [5,745],:style => :bold, :size => 10\n pdf.draw_text \"Hoja Nro.: \" + pdf.page_number.to_s.rjust(4,\"0\"), :at => [300, 745],:style => :bold, :size => 8\n end\n data = [[\"Fecha\",\"Tipo Cp\",\"Numero\",\"Importe\",\"Fecha Vto\",\"impreso\"],[] ]\n saldo = 0\n entity.each do |r|\n data << [r.fecha.blank? ? '' : r.fecha.strftime(\"%d/%m/%Y\"),\n r.type,\n r.numero,\n r.total_comprobante,\n r.fechavto.blank? ? '' : r.fechavto.strftime(\"%d/%m/%Y\"),\n r.printed_at.blank? ? '' : r.printed_at.strftime(\"%d/%m/%Y\")]\n saldo += r.total_comprobante \n end\n data << [\"\" ,\"Totales\",\"\",saldo.to_s,\"\",\"\" ]\n\n pdf.table(data, :column_widths => [65, 100, 60, 65, 65, 65],\n :cell_style => { :font => \"Times-Roman\",\n :size => 10,:padding => [2,3,4,2],\n :align => :left,\n :valign => :center },\n :header => true ,\n :row_colors => [\"F0F0F0\", \"FFFFCC\"]\n ) do\n column(2...3).align = :right\n row(0).column(0..6).align = :center\n end\n pdf.render_file(filename)\nend", "def rendered_pdf\n WickedPdf.new.pdf_from_string(rendered_view, @pdf_options)\n end", "def create\n @statement = Statement.new(statement_params)\n @test = @statement.test.id\n\n path_to_file = \"#{Rails.root}/app/assets/images/cert#{@statement.id}.pdf\"\n\n pdf = CombinePDF.load \"#{@statement.test.certificate.path}\" \n\n if !pdf.pages.empty?\n\n #a = \"Привет\".encode(\"UTF-8\")\n\n # create a textbox and add it to the existing pdf on page 2 #{@statement.fio} #{@statement.position} \n pdf.pages[0].textbox @statement.position, height: 60, width: 450, y: 400, x: 82, :font => :time_new_roman, font_color: [0, 0.2, 0.26274509803], max_font_size: 16\n pdf.pages[0].textbox @statement.place, height: 60, width: 450, y: 380, x: 82, :font => :time_new_roman, font_color: [0, 0.2, 0.26274509803], max_font_size: 16\n #Суспеснкого районе г . Казани ниже\n pdf.pages[0].textbox @statement.phone, height: 60, width: 450, y: 360, x: 82, :font => :time_new_roman, font_color: [0, 0.2, 0.26274509803], max_font_size: 16\n pdf.pages[0].textbox @statement.name, height: 60, width: 450, y: 320, x: 82, :font => :time_new_roman, font_color: [0, 0.2, 0.26274509803], max_font_size: 35\n pdf.pages[0].textbox @statement.fio, height: 60, width: 450, y: 280, x: 82, :font => :time_new_roman, font_color: [0, 0.2, 0.26274509803], max_font_size: 35\n # output the new pdf which now contains your dynamic data\n pdf.save path_to_file\n File.open(path_to_file) do |f|\n @statement.certificate = f\n end\n File.delete(path_to_file) if File.exist?(path_to_file)\n end\n\n respond_to do |format|\n if @statement.save\n format.html { redirect_to root_path, notice: 'Statement was successfully created.' }\n else\n format.html { render :new}\n format.json { render json: @statement.errors, status: :unprocessable_entity }\n end\n end\n end", "def to_texfile(filename, params={}, &block)\n File.open(filename,'w') { |file| file << to_tex(params, &block) }\n end", "def pdf_to_html(url)\n\tend", "def to_pdf(path = nil)\n @outfile = File.expand_path(path) if path\n run\n @outfile\n end", "def generate_pdf(filename, pupil)\n Prawn::Document.generate(filename) do\n text \"CONTRATO DE PRESTAÇÃO DE SERVIÇOS EDUCACIONAIS EM DANÇA\"\n text \"Dados do Contratante\"\n text \"Aluno: #{pupil.first_name} #{pupil.last_name}\"\n text \"Contratante: #{pupil.first_name} #{pupil.last_name}\"\n text \"Endereço: #{pupil.user.try(:street)}, #{pupil.user.try(:district)}, \" +\\\n \"#{pupil.user.try(:city)}, #{pupil.user.try(:state)}, #{pupil.user.try(:zip_code)}\"\n text \"CPF: #{pupil.user.try(:cpf)} RG: #{pupil.user.try(:rg)}\"\n text \"Telefone(s): #{pupil.user.phone_numbers.collect { |p| p.number }}\"\n text \"E-mail: #{pupil.user.try(:email)}\"\n text \"Dados do Contratado\"\n text \"ESPAÇO DANÇAS MANÁ, localizado na Rua 58, Quadra 47, Casa 02, Vinhais, São Luís/MA,\" +\\\n \"inscrito no CNPJ nº 10.724.129/0001-04, representada por DYANNE MIRELLE BARBOSA SANTANA\" +\\\n \"portadora do CP F nº 074.016.854-18.\"\n text \"DO OBJETO E DAS CONDIÇÕES\"\n text \"Cláusula 1º: A Contratante firma com o Contratado a matrícula no(s) curso(s) de: BALLET CLÁSSICO (____); DANÇA CONTEMPORÂNEA (____); SAPATEADO (____); ALONGAMENTO (____); JAZZ (____); DANÇA DE SALÃO (____); DANÇA DE RUA (____); DANÇA DO VENTRE (____); DANÇA SENSUAL (____).\"\n text \"Cláusula 2ª: O presente contrato compreende apenas a prestação de serviços educacionais em dança, não estão incluídos no valor deste curso: taxa de exames; outros cursos extracurriculares; materiais; uniformes; figurinos; dentre outros materiais e serviços, que serão cobrados separadamente pelo Contratado.\"\n text \"Cláusula 3ª: Os cursos oferecidos pelo Contratado terão duração de ___ (______) meses, de ___________ à ___________ de 2013, assim como o presente contrato.\"\n text \"Cláusula 4ª: A formação e a continuidade das turmas dos cursos oferecidos pelo Contratado dependerá do número mínimo de alunos de _____ por turma, a serem preenchidos dentro do prazo máximo de 2 (dois) meses, contados a partir do início das atividades.\"\n text \"§1º: O não atingimento do número mínimo de alunos por turma implicará no remanejamento do aluno para outra turma compatível em nível, carga horária e preço, de acordo com o interesse do Contratante.\"\n text \"§2º: Caso não seja de interesse do Contratante fazer o remanejamento na hipótese do parágrafo anterior, este poderá requerer o cancelamento da sua matrícula sem o pagamento de qualquer multa contratual, desde que este requerimento ocorra antes da data de vencimento da mensalidade.\"\n text \"Cláusula 5ª: A Contratada se obriga a oferecer ao Contratante apenas as aulas especificadas na carga horária e nos horários definidos na tabela em anexo.\"\n text \"§1º: A reposição de aulas perdidas só será possível se houver vaga em outra turma em nível compatível aquele cursado pelo Contratante. Caso contrário o Contratante não terá direito a repor a aula.\"\n text \"§2º: Os alunos horistas poderão remarcar as aulas com até 5 (cinco) horas de antecedência do horário previamente marcado.\"\n text \"§3º: O aluno horista que não remarcar a aula no prazo estabelecido no parágrafo anterior perderá o direito de repor a aula previamente marcada.\"\n text \"Cláusula 6ª: O contrato de prestação de serviço é personalíssimo em relação ao aluno acima discriminado.\"\n text \"Cláusula 7ª: O curso contratado não possui diplomação.\"\n text \"Cláusula 8ª: O Contratante aceita os programas de ensino adotados, acatando o regimento interno do Contratado, normas disciplinares e o agrupamento dos alunos de acordo como o seu nível técnico.\"\n text \"DO PAGAMENTO DA COBRANÇA\"\n text \"Cláusula 9ª: O curso tem o custo total de R$ __________ (_______________________________________).Parágrafo Único: O valor curso pode ser pago em até ___ (_______) parcelas de __________(_________________________)\"\n text \"Cláusula 10ª: A cobrança tanto das parcelas quanto do valor total do curso será feita por meio de boleto bancário.\"\n text \"§1º: O(s) boleto(s) pode(m) ser pago(s) na própria sede da Contratada: em espécie e em cartão na modalidade débito. As modalidades aqui descritas não excluem as outras disponibilizadas pela instituição financeira que emite o boleto de cobrança.\"\n text \"§2º: O pagamento no cartão na modalidade crédito é apenas permitido para o pagamento integral do valor do curso.\"\n text \"§3°: O pagamento da mensalidade em espécie e dentro da data do vencimento confere ao aluno desconto de 4% na mesma.\"\n text \"§4°: O pagamento integral do valor do curso pago em espécie confere ao aluno desconto de 5%.\"\n text \"Cláusula 11ª: O Contratante deseja pagar o curso em (____) parcela(s) de R$ __________ (_______________________________) e estabelece como dia do vencimento da(s) parcela(s) o dia ____ do mês (de cada mês).\"\n text \"Cláusula 12ª: Os juros e multa diária pelo atraso no pagamento serão estabelecidos pela instituição financeira que realiza a emissão do(s) boleto(s) de pagamento.\"\n text \"Cláusula 13ª: O atraso no pagamento por prazo superior a 30 (trinta) dias implicará na suspensão do acesso as aulas e na inscrição do nome do inadimplente no cadastro de protesto, SPC e Serasa.\"\n text \"DA RECISÃO CONTRATUAL\"\n text \"Cláusula 14ª: A rescisão do contrato pode ser feita unilateralmente pelo Contratado, quando não houverem sido alcançadas as condições estabelecidas na Cláusula 4ª e no seu §1º, do presente contrato.\"\n text \"Parágrafo Único: O contrato também pode ser reincidido unilateralmente pelo Contratado quando o contratante não obedecer aos ditames da Cláusula 8ª.\"\n text \"Cláusula 15ª: A rescisão pode ser feita sem custas adicionais pelo Contratante, desde que seja requerida até a data do vencimento da parcela vincenda.\"\n text \"DISPOSIÇÕES GERAIS\"\n text \"Cláusula 16ª: O ingresso dos alunos nas turmas será precedido de avaliação física.\"\n text \"§1º: O Contratante poderá dispensar a avaliação física desde que ateste por escrito que encontra-se em condições de saúde para a prática de exercícios físicos.\"\n text \"§2º: É de inteira responsabilidade do Contratante informar aos professores eventuais doenças, lesões ou sequelas.\"\n text \"\"\n text \"\"\n text \"\"\n text \"\"\n text \"São Luís, _____ de ______________________ de 2013.\"\n text \"Contratante:________________________ Contratado: ________________________\"\n text \"Testemunha: ______________________ Testemunha: ______________________\"\n text \"CPF: CPF:\"\n text \"Quadro de Turmas da Matrícula\"\n end\n end", "def to_text(filename = nil,&block)\n self.class.send(:pdftotext,@filename,filename,&block)\n end", "def render_on(pdf_object)\n pdf_object.text @content.join(' ')\n end", "def latex(title, basedir = \"\")\n\t\t# Open the file to write\n\t\tbaseName = File.basename(@file.path, \".svg\")\n\t\tfile = File.new(baseName + \"#{@latex_file_count}\" + \".tex\", \"w\")\n\t\t\n\t\t# Print the \n\t\t(@latex_count..@count - 1).each do |i|\n\t\t\tfile.puts(\"\\\\begin{slide}{#{title}}\\n\" +\n\t\t\t\t\t \" \\\\centering\\n\" +\n \" \\\\includegraphics[]{\" + basedir + baseName + \"#{i}}\\n\" +\n \"\\\\end{slide}\\n\\n\")\n\t\tend\n\t\t\n\t\t# Finalize\n\t\t@latex_count = @count\n\t\t@latex_file_count += 1\n\t\tfile.close\n\tend", "def encode(temp_object, format, args = { })\n\n unless format == :pdf && self.class.valid_mime_type?(temp_object.meta[:mime_type])\n throw :unable_to_handle\n end\n\n if content = libreoffice(temp_object.path, :pdf)\n [ content, meta(temp_object, :pdf, 'application/pdf') ]\n else\n raise Heathen::NotConverted.new({\n temp_object: temp_object,\n action: 'office_to_pdf',\n command: executioner.last_command,\n original_error: executioner.last_messages\n })\n end\n end", "def text(input)\n command = \"pdftotext #{input.shellescape} -\"\n command_stdout(command)\n end", "def to_pdf\n\t\tunless id then raise ::ArgumentError,\n\t\t\t'Could not find id for this Invoice, are you trying '\\\n\t\t\t'to convert an invoice to PDF without creating it?'\n\t\tend\n\n\t\tencoded = NSConnector::Restlet.execute!(\n\t\t\t:action => 'invoice_pdf',\n\t\t\t:invoice_id => id\n\t\t).first\n\t\tBase64::decode64(encoded)\n\tend", "def pdfout(content, file: 'output.pdf', width: 7, height: 7)\n \"\"\"\n pdf('#{file}', width=#{width}, height=#{height})\n #{content}\n dev.off()\n \"\"\"\nend", "def compile_latex(options)\n latexFilePath = options[:file]\n unless latexFilePath\n Tempfile.open('latex', @tmpDir) do |f|\n latexFilePath = f.path\n f.puts options[:contents]\n end\n end\n\n # Always use absolute paths\n if FileTest.readable? latexFilePath\n require 'pathname'\n latexFilePath = Pathname.new(latexFilePath).realpath\n else\n latexFilePath = File.join(@tmpDir, latexFilePath)\n end\n FileTest.readable? latexFilePath or\n raise LatexCompilationError.new(\"Can't find #{latexFilePath}. Try passing a valid, readable absolute path to the :file option, or some LaTeX to the :contents options _and_ a writable tmpDir (it's currently '#{@tmpDir}') to the compiler constructor\")\n\n finalOptions = @pdflatexOptions\n finalOptions += options[:add_options] if options[:add_options]\n finalOptions = options[:replace_options] if options[:replace_options]\n\n command = \"cd #{@tmpDir} && #{@pdflatexBin} #{finalOptions} #{latexFilePath}\"\n output = `#{command}`\n $? == 0 or raise LatexCompilationError.new(\"pdflatex terminated with an error\", output, command, File.read(latexFilePath))\n output =~ /Output written on (.*\\.pdf)/\n $1 or raise LatexCompilationError.new(\"Can't find output file produced by pdflatex.\", output, command, File.read(File.join(@tmpDir, latexFilePath)))\n File.read(File.join(@tmpDir, $1))\n end", "def printout\n raise WedgieError, \"can't print #{content_type}\" unless content_type == 'text/x-clinical'\n pdf = FPDF.new('P','mm','A4')\n pdf.SetFont('Arial','',10)\n clinical_objects.each do |obj|\n pdf.AddPage\n obj.gen_pdf(pdf)\n end\n return pdf\n end", "def show_plain\n respond_to do |format|\n format.html\n format.pdf do\n render pdf: @document.name,\n template: \"documents/plain.pdf.erb\",\n locals: {:document => @document},\n layout: 'layouts/application.pdf.erb',\n :margin => { :bottom => 45, :top => 66, :left => 0 },\n header: {\n html: {\n template: 'documents/templates/header.pdf.erb',\n layout: 'plain.html.erb',\n locals: { :document => @document }\n }\n },\n show_as_html: params.key?('debug')\n end\n end\n end", "def pdftk; end", "def make_and_send_pdf(template_path, pdf_name, landscape=false)\n send_data(\n make_pdf(template_path, pdf_name, landscape),\n :filename => pdf_name,\n :type => 'application/pdf'\n ) \n end", "def to_png_file\n to_pdf_file do |pdf_path|\n Dir.mktmpdir(ident) do |output_directory|\n png_path = File.join(output_directory, ident + '.png')\n system convert, *CONVERT_OPTIONS, pdf_path, png_path\n raise PNGConversionFailed, self unless File.exist?(png_path)\n\n yield png_path\n File.unlink png_path\n end\n end\n end", "def to_png_file\n to_pdf_file do |pdf_path|\n Dir.mktmpdir(ident) do |output_directory|\n png_path = File.join(output_directory, ident + '.png')\n system convert, *CONVERT_OPTIONS, pdf_path, png_path\n raise PNGConversionFailed, self unless File.exist?(png_path)\n\n yield png_path\n File.unlink png_path\n end\n end\n end", "def generate_pdf \n pdf = ParkirPdf.new(@billing)\n pdf.render\n end", "def toPDF(doc, parent)\n if !parent\n raise \"Pas de parent pour le recu\"\n end\n \n doc.start_new_page\n doc.font 'Times-Roman'\n \n # On fait deux copies.\n [650, 400].each do |y|\n doc.bounding_box([0, y], :width => 500, :height => 200) do\n oneRecu(doc, parent)\n end\n end\n \n end", "def report\n\n @projecta = Project.find(params[:id])\n\n pdf = Prawn::Document.new\n pdf.text \"Universidad Nacional de Ingenieria\" , :size => 30, :style => :bold, :position => :center\n pdf.move_down(10) \n pdf.text \"Vicerectoria de Investigación y Desarrollo.\" , :size => 25, :style => :bold, :position => :center\n pdf.move_down(10)\n pdf.text \"Programa de acompañamiento a Proyectos\" , :size => 20, :style => :bold, :position => :center\n pdf.text \"Reporte Generado por el programa de Tecnología de la Informacion PROAP\" , :size => 15, :position => :center\n pdf.move_down(45) \n pdf.image \"#{Rails.root.join}/app/assets/images/uni.jpg\", :position => :center ,:at => [0, 600], :height => 100\n pdf.move_down(80)\n pdf.text \"Nombre del Proyecto:\", :size => 20, :style => :bold\n pdf.move_down(10) \n pdf.text \"#{@projecta.name}\", :size => 20\n pdf.move_down(10)\n pdf.text \"Objetivo del Proyecto: \" , :size => 13, :style => :bold\n pdf.move_down(10) \n pdf.text \"#{@projecta.objetive}\", :size => 13\n pdf.move_down(10) \n pdf.text \"Estado del Proyecto: #{@projecta.status}\", :size => 13\n pdf.move_down(20) \n pdf.text \"Fase del Proyecto: #{@projecta.fase}\", :size => 13\n pdf.move_down(10)\n pdf.text \" Los Reportes que pertenecen a #{@projecta.name} son :\", :size => 13, :style => :bold\n pdf.move_down(20)\n @projecta.reports.each do |pr|\n pdf.text \"Nombre del Reporte: #{pr.name}\", :style => :bold\n pdf.move_down(10)\n pdf.text \"Descripcion del Reporte: #{pr.desc}\"\n pdf.move_down(10)\n pdf.text \"Fecha y Hora local de creacion del reporte: #{pr.created_at}\"\n pdf.move_down(10)\n pdf.text \"Fecha y Hora local de acutalizacion del repote: #{pr.date}\"\n pdf.move_down(10)\n pdf.line [0,100], [500,100]\n end\n \n\n pdf.create_stamp(\"Proyecto Aprobado\") do\n pdf.rotate(30, :origin => [-5, -5]) do\n pdf.stroke_color \"FF3333\"\n pdf.stroke_ellipse [0, 0], 49, 15\n pdf.stroke_color \"000000\"\n pdf.fill_color \"993333\"\n pdf.font(\"Times-Roman\") do\n pdf.draw_text \"Proyecto Aprobado\", :at => [-23, -3]\n end\n pdf.fill_color \"000000\"\n end\n end\n pdf.stamp \"Proyecto Aprobado\"\n pdf.stamp_at \"Proyecto Aprobado\", [250, 200]\n send_data pdf.render, :filename => \"#{@projecta.name}\", :disposition => \"inline\"\n pdf.text_box \"Informe Generado por el Programa de acompañamiento a Proyectos\", :at => [220,200], :style => :bold\n end", "def render_document(input, outdir, outname, format, vars)\r\n \r\n \r\n #TODO: Clarify the following\r\n # on Windows, Tempdir contains a drive letter. But drive letter\r\n # seems not to work in pandoc -> pdf if the path separator ist forward\r\n # slash. There are two options to overcome this\r\n #\r\n # 1. set tempdir such that it does not contain a drive letter\r\n # 2. use Dir.mktempdir but ensure that all provided file names\r\n # use the platform specific SEPARATOR\r\n #\r\n # for whatever Reason, I decided for 2.\r\n \r\n tempfile = input\r\n tempfilePdf = \"#{@tempdir}/x.TeX.md\".to_osPath\r\n tempfileHtml = \"#{@tempdir}/x.html.md\".to_osPath\r\n outfilePdf = \"#{outdir}/#{outname}.pdf\".to_osPath\r\n outfileDocx = \"#{outdir}/#{outname}.docx\".to_osPath\r\n outfileHtml = \"#{outdir}/#{outname}.html\".to_osPath\r\n outfileRtf = \"#{outdir}/#{outname}.rtf\".to_osPath\r\n outfileLatex = \"#{outdir}/#{outname}.latex\".to_osPath\r\n outfileText = \"#{outdir}/#{outname}.txt\".to_osPath\r\n outfileSlide = \"#{outdir}/#{outname}.slide.html\".to_osPath \r\n \r\n #todo: handle latexStyleFile by configuration\r\n latexStyleFile = File.dirname(File.expand_path(__FILE__))+\"/../../ZSUPP_Styles/default.latex\"\r\n latexStyleFile = File.expand_path(latexStyleFile).to_osPath\r\n\r\n vars_string=vars.map.map{|key, value| \"-V #{key}=#{value.esc}\"}.join(\" \")\r\n \r\n @log.info(\"rendering #{outname} as [#{format.join(', ')}]\")\r\n \r\n if $?.success? then\r\n \r\n if format.include?(\"pdf\") then\r\n ReferenceTweaker.new(\"pdf\").prepareFile(tempfile, tempfilePdf)\r\n \r\n cmd=\"pandoc -S #{tempfilePdf.esc} --toc --standalone --latex-engine xelatex --number-sections #{vars_string}\" +\r\n \" --template #{latexStyleFile.esc} --ascii -o #{outfilePdf.esc}\"\r\n `#{cmd}`\r\n end\r\n \r\n if format.include?(\"latex\") then\r\n \r\n ReferenceTweaker.new(\"pdf\").prepareFile(tempfile, tempfilePdf)\r\n \r\n cmd=\"pandoc -S #{tempfilePdf.esc} --toc --standalone --latex-engine xelatex --number-sections #{vars_string}\" +\r\n \" --template #{latexStyleFile.esc} --ascii -o #{outfileLatex.esc}\"\r\n `#{cmd}`\r\n end\r\n \r\n if format.include?(\"html\") then\r\n \r\n ReferenceTweaker.new(\"html\").prepareFile(tempfile, tempfileHtml)\r\n \r\n cmd=\"pandoc -S #{tempfileHtml.esc} --toc --standalone --self-contained --ascii --number-sections #{vars_string}\" +\r\n \" -o #{outfileHtml.esc}\"\r\n \r\n `#{cmd}`\r\n end\r\n \r\n if format.include?(\"docx\") then\r\n \r\n ReferenceTweaker.new(\"html\").prepareFile(tempfile, tempfileHtml)\r\n \r\n cmd=\"pandoc -S #{tempfileHtml.esc} --toc --standalone --self-contained --ascii --number-sections #{vars_string}\" +\r\n \" -o #{outfileDocx.esc}\"\r\n `#{cmd}`\r\n end\r\n \r\n if format.include?(\"rtf\") then\r\n \r\n ReferenceTweaker.new(\"html\").prepareFile(tempfile, tempfileHtml)\r\n \r\n cmd=\"pandoc -S #{tempfileHtml.esc} --toc --standalone --self-contained --ascii --number-sections #{vars_string}\" +\r\n \" -o #{outfileRtf.esc}\"\r\n `#{cmd}`\r\n end\r\n \r\n if format.include?(\"txt\") then\r\n \r\n ReferenceTweaker.new(\"pdf\").prepareFile(tempfile, tempfileHtml)\r\n \r\n cmd=\"pandoc -S #{tempfileHtml.esc} --toc --standalone --self-contained --ascii --number-sections #{vars_string}\" +\r\n \" -t plain -o #{outfileText.esc}\"\r\n `#{cmd}`\r\n end\r\n \r\n if format.include?(\"slide\") then\r\n \r\n ReferenceTweaker.new(\"slide\").prepareFile(tempfile, tempfilePdf)\r\n \r\n cmd=\"pandoc -S #{tempfileHtml.esc} --toc --standalone --number #{vars_string}\" +\r\n \" --ascii -t dzslides --slide-level 2 -o #{outfileSlide.esc}\"\r\n `#{cmd}`\r\n end\r\n else\r\n \r\n @log.error \"failed to perform #{cmd}\"\r\n #TODO make a try catch block kere\r\n \r\n end\r\n \r\n end", "def makePDF( stylesheetPath, xml )\n pdfFile = Tempfile.new(\"pdf\");\n xmlFile = Tempfile.new(\"xml\");\n dmpFile = Tempfile.new(\"dump\" );\n RAILS_DEFAULT_LOGGER.debug( \" makePDF; xml is #{xml} \" ); \n xmlFile.write( xml );\n xmlFile.close();\n cmd = FOP_PATH+\" -xml #{xmlFile.path} -xsl #{stylesheetPath} -pdf #{pdfFile.path} &> #{dmpFile.path}\";\n RAILS_DEFAULT_LOGGER.debug( \" makePDF; command is #{cmd} \" );\n # see: file:/home/graham_s/ruby/docs/www.rubycentral.com/book/tut_threads.html\n IO.popen( cmd ) { \n |f| \n RAILS_DEFAULT_LOGGER.debug( \"command output is #{f.gets}\" ); \n }\n pdf = pdfFile.read();\n pdfFile.close();\n RAILS_DEFAULT_LOGGER.debug( \" output dump is \" + dmpFile.read() );\n dmpFile.close();\n return pdf\nend", "def show_text(string) # Tj\n raise PDF::Reader::MalformedPDFError, \"current font is invalid\" if current_font.nil?\n at = transform(Point.new(0,0))\n @content[at.y] ||= \"\"\n @content[at.y] << current_font.to_utf8(string)\n end", "def help # defines the helptext to be printed when option \"-h\" is used\nputs <<HELPTEXT\n\nNAME\n txt2pdf\n\nSYNOPSIS\n txt2pdf [-h] (filename)\n\nDESCRIPTION\n Reads a text file (if supplied as the first argument) and creates\n a pdf file with the same name but with .pdf as extension in the\n current directory via the program pdflatex (the only requirement\n besides ruby itself). If \"-h\" is the first argument, then the program\n displays the helptext and exits.\n\n The program can also read the input text from STDIN (STanDard IN) and\n create the pdf file in the user's home directory. When this method is\n used, no argument is given to the program and the text is simply piped\n directly into the program like this:\n\n $ echo \"Hello\" | txt2pdf\n\n This would create a pdf file with only \"Hello\" and the page number\n at the bottom of the resulting pdf page.\n\n With this, you could map a key binding in your window manager to\n create a pdf file from the text you selected in any program, be it the\n terminal, your browser or your text editor. In my wm of choice, i3,\n I have added the following to my i3 config:\n\n bindsym $mod+p exec xclip -o | txt2pdf\n \n This would create a pdf file from the text I have selected as I hit\n the \"Window button\" and \"p\".\n\nOPTIONS\n -h Show this help text\n\nCOPYRIGHT:\n By Geir Isene (https://isene.org) 2019. No rights reserved.\n\nHELPTEXT\nend", "def convert_html_to_pdf_command\n \"#{WebKitHTMLToPDF.binary} -O #{orientation} #{header_command} \" \\\n \"--disable-smart-shrinking \" \\\n \"-T 15mm -B 25mm -L 10mm -R 10mm \" \\\n \"#{Shellwords.escape(html_filename)} \" \\\n \"#{Shellwords.escape(filename)} 2>/dev/null\"\n end", "def pdf\n @resume = Resume.find(params[:id])\n html = RDiscount.new(@resume.content).to_html\n kit = PDFKit.new(html, :page_size => 'Letter')\n pdf = kit.to_pdf\n \n file_path = \"#{Rails.root.to_s}/tmp/#{@resume.id}.pdf\"\n file = kit.to_file(file_path)\n send_file file_path, :type => 'pdf', :disposition => 'inline'\n end", "def generate_event_pdf\n event = Event.find(params[:id])\n pdf = PDF::Writer.new()\n pdf.image \"public/images/about-neova.jpg\"\n pdf.select_font \"Courier\"\n pdf.margins_pt(36)\n pdf.text \"CERTIFICATE OF ATTENDANCE\", :font_size => 32,:justification => :center,:spacing => 2\n pdf.text \"This is to certify that\", :font_size => 15, :justification => :center,:spacing => 3\n pdf.text \"#{current_user.full_name}\", :font_size =>25,:justification => :center,:spacing => 2\n pdf.text \"attended the event\", :font_size =>15,:justification => :center,:spacing => 2\n pdf.text \"#{event.name}\", :font_size =>25,:justification => :center,:spacing => 2\n pdf.text \"held on #{event.starts_on}\",:font_size => 15,:justification => :center,:spacing => 2\n respond_to do |format|\n format.pdf do\n send_data pdf.render, :filename => 'event.pdf', :type => 'application/pdf', :disposition => 'attachment'\n end\n end\n #pdf.save_as(\"public/event_certificate_user#{current_user.id}_event#{event.id}.pdf\")\n #send_file \"public/event_certificate_user#{current_user.id}_event#{event.id}.pdf\", :type => 'application/pdf'\n end", "def clean_latex_document\n cache_literal(@polytex, :latex).tap do |doc|\n expand_input!(doc,\n Proc.new { |source| cache_literal(source, :latex) },\n 'tex')\n end\n end", "def create\n @comments = Comment.where.not(body: '')\n\n respond_to do |format|\n original_orientation = TextOnPdf.first.original_orientation\n\n format.pdf do\n pdf = render_to_string pdf: 'generated_pdf.pdf',\n template: 'text_on_pdfs/generated_pdf.pdf',\n encording: 'UTF-8',\n layout: 'pdf.html',\n orientation: original_orientation,\n show_as_html: true\n # show_as_html: params[:debug].present?\n send_data(pdf)\n end\n end\n end" ]
[ "0.7339175", "0.73134685", "0.6811696", "0.67833686", "0.67824274", "0.6647562", "0.6545204", "0.6417368", "0.64163077", "0.6391119", "0.63190246", "0.6300978", "0.6270027", "0.623456", "0.6213866", "0.62063766", "0.6203311", "0.6200837", "0.61946106", "0.61626494", "0.61520314", "0.61332405", "0.60449237", "0.6033787", "0.6016725", "0.6002281", "0.59941417", "0.5959328", "0.5921935", "0.59175754", "0.586521", "0.58650726", "0.58464265", "0.5845889", "0.584188", "0.58264923", "0.5824478", "0.5813078", "0.57781285", "0.5746147", "0.57381946", "0.57265675", "0.5724061", "0.57236964", "0.57139325", "0.57011074", "0.5700589", "0.56852347", "0.5682443", "0.56740797", "0.5673806", "0.56602824", "0.5651188", "0.5631216", "0.5624981", "0.5620629", "0.5602215", "0.55913335", "0.5590567", "0.55859625", "0.5577344", "0.55727285", "0.556766", "0.5566728", "0.55647516", "0.5561718", "0.5560729", "0.5560628", "0.55573964", "0.5556685", "0.55260295", "0.5522847", "0.5511931", "0.5511419", "0.5502984", "0.550153", "0.55006224", "0.5499465", "0.5490434", "0.5488971", "0.54844165", "0.5483659", "0.5474244", "0.5469632", "0.54540205", "0.545004", "0.5437001", "0.54330266", "0.54330266", "0.5430011", "0.54290736", "0.5421504", "0.5420583", "0.54204315", "0.5419693", "0.5411144", "0.5407355", "0.5397399", "0.53956664", "0.5394685", "0.5391719" ]
0.0
-1
compile all TeX files in dir
def compile(dir) savedir = Dir.pwd Dir.chdir(dir) # 中間ファイル削除 clean # 個別ファイルコンパイル Dir::glob("*.pdf").each do |file| next if "nzmath_doc" == file[0...-4] tex_compile(file[0...-4]) end header_footer = ["header_overview.tex", "header_basic_util.tex", "header_class.tex", "header_function.tex", "footer.tex"] header_footer.map!{|file| '../' + file} # リネーム header_footer.each do |file| File::rename(file, file + '_') end # 空ファイル作成 header_footer.each do |file| open(file, "w") {|f|} end begin # コンパイル tex_compile("nzmath_doc") ensure # リネーム header_footer.each do |file| File::rename(file + '_', file) end end ensure # 中間ファイル削除 clean Dir.chdir(savedir) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tex_compile(file)\r\n\tprint File.basename(Dir.pwd) + '/' + file\r\n\t`platex -kanji=\"sjis\" #{file}.tex`\r\n\tprint \".\"\r\n\t`#{$bibtex} #{file}`\r\n\tprint \".\"\r\n\r\n\t# some system needs three times compiles.\r\n\t3.times do\r\n\t\t`platex -kanji=\"sjis\" #{file}.tex`\r\n\t\tprint \".\"\r\n\tend\r\n\r\n\t`dvipdfmx #{file}.dvi > #{$dev_null} 2>&1`\r\n\tputs \".\"\r\nend", "def compile(path)\n files = getFilesInDirCompiler(path)\n filesWithLines = getFilesWithLinesCompiler(files)\n classNames = getClassNames(filesWithLines)\n functionInfo = getFunctionNameTypesFiles(filesWithLines)\n compilerInfo = [classNames, functionInfo]\n\n for i in 0..filesWithLines.size-1\n fSize = filesWithLines[i][0].size\n\n #renaming the\n compiledFileName = filesWithLines[i][0][0, fSize-5]+\".vm\"\n compiledFileXMLName = filesWithLines[i][0][0, fSize-5]+\"Out.xml\"\n tokensFileName = filesWithLines[i][0][0, fSize-5]+\"TOut.xml\"\n lines = filesWithLines[i][1]\n lines = getLines(lines)\n tokens = tokenize(lines)\n\n writeCompiledFile(tokens, compilerInfo, compiledFileName)\n writeCompiledXMLFile(tokens, classNames, compiledFileXMLName)\n writeTokensXMLFile(tokens, tokensFileName)\n puts filesWithLines[i][0] + \" was tokenized and compiled\" +\"\\n\"\n end\nend", "def compile\n Dir.chdir(build_path) do\n do_compile\n end\n end", "def compile_files(files)\n files.each do |base_path|\n # We do this second glob in case the path provided in the tayfile\n # references a compiled version\n Dir[@base_dir.join('src', base_path + '*')].each do |path|\n path = Pathname.new(path).relative_path_from(@base_dir.join('src'))\n file_in_path = @base_dir.join('src', path)\n file_out_path = asset_output_filename(@output_dir.join(path), @sprockets.engines.keys)\n\n if @sprockets.extensions.include?(path.extname)\n content = @sprockets[file_in_path].to_s\n else\n content = File.read(file_in_path)\n end\n\n FileUtils.mkdir_p(file_out_path.dirname)\n File.open(file_out_path, 'w') do |f|\n f.write content\n end\n end\n end\n end", "def compile_wiki_file(filename, wiki_dir, compile_dir)\n File.open(File.join(wiki_dir, filename)) do |file|\n wiki_file = file.read\n File.open(File.join(HTML_DIR, filename.sub(/\\.wiki$/, \"\").concat(\".html\")), 'w') do |out_file|\n content = WikiCreole.creole_parse(wiki_file)\n html_file = ''\n File.open(File.join('data', 'default.html')) {|file| html_file = file.read}\n \n erb = ERB.new(html_file)\n html_file = erb.result(binding)\n \n out_file.puts(html_file)\n end\n end\nend", "def run_all\n run_on_changes(Watcher.match_files(self, Dir.glob('**{,/*/**}/*.tex')))\n end", "def compile dir = nil\n if dir.nil?\n dir = @game_dir\n end\n\n valid_dir_entries(dir).each do |d|\n fullPath = File.join(dir, d)\n\n if File.directory?(fullPath)\n compile File.join(dir, d)\n elsif File.file?(fullPath)\n bits = fullPath[@game_dir.length+1..fullPath.length-1].split(File::SEPARATOR)\n if bits.include?('archetypes')\n compile_archetype(fullPath)\n elsif bits.include?('qualities')\n compile_mixin(fullPath)\n elsif bits.include?('verbs')\n compile_verb(fullPath)\n elsif bits.include?('adverbs')\n compile_adverb(fullPath)\n elsif bits[0] == 'domains' && bits.length == 3\n @pending << [ :compile_domain_data, [ fullPath, bits ]]\n end\n end\n end\n end", "def compile(files, file)\n\n # setup the output buffer with the base file\n output_buffer = File.read(File.path(file))\n\n # loop through import files and substitute imports\n files.each do |key, import_file|\n output_buffer = import(output_buffer, key, import_file)\n end\n\n File.open(output_filename(file), 'w') do |file|\n file.write(output_buffer)\n end\n end", "def compile_templates\n dir = File.join(Frank.root, Frank.dynamic_folder)\n\n Dir[File.join(dir, '**{,/*/**}/*')].each do |path|\n if File.file?(path) && !File.basename(path).match(/^(\\.|_)/)\n path = path[ (dir.size + 1)..-1 ]\n ext = File.extname(path)\n new_ext = ext_from_handler(ext)\n name = File.basename(path, ext)\n\n # No suitable handler found\n if not new_ext.is_a? String\n next\n end\n\n if Frank.production? && \"#{name}.#{new_ext}\" != 'index.html' && new_ext == 'html'\n new_file = File.join(Frank.export.path, path.sub(/(\\/?[\\w-]+)\\.[\\w-]+$/, \"\\\\1/index.#{new_ext}\"))\n else\n new_file = File.join(Frank.export.path, path.sub(/\\.[\\w-]+$/, \".#{new_ext}\"))\n end\n\n create_dirs(new_file)\n File.open(new_file, 'w') {|f| f.write render(path) }\n puts \" - \\033[32mCreating\\033[0m '#{new_file}'\" unless Frank.silent_export?\n end\n end\n end", "def compile\n tmpdir = Dir.mktmpdir\n Dir.chdir(tmpdir) do |source_dir, build_dir|\n yield source_dir, @build_dir\n end\n\n puts \"Packaging the following files/dirs:\"\n pipe \"ls #{@build_dir}\"\n ensure\n if ENV['DEBUG']\n puts \"Source dir: #{tmpdir}\"\n else\n FileUtils.rm_rf(tmpdir)\n end\n end", "def run(files)\n files = files.reject { |file| file.end_with? '.h' }\n filenames = files.map { |file| File.basename(file) }\n puts \"Compiling #{filenames * ' '}...\"\n Dir.mktmpdir('rucppy') do |dir|\n compile_command = \"g++ -std=c++11 #{files * ' '} -o #{dir}/a.out\"\n # puts compile_command\n `#{compile_command}`\n system(\"#{dir}/a.out\")\n end\nend", "def compile_exec()\n compile\n exec\n end", "def compile\n compile_body\n compile_head\n \n builder = ScriptBuilder.new @template\n builder.build_for_page @filename\n end", "def compile\n @tests.each do |test_hash|\n Liquid::Template.new.parse(test_hash[:liquid])\n Liquid::Template.new.parse(test_hash[:layout])\n end\n end", "def compile_file(ctx, source)\n compile_string(ctx, File.read(source))\n rescue StandardError => e\n puts \"Error compiling file: #{source}\"\n raise e\n end", "def compile\n File.chmod(0o755, start_script(root))\n augment_classpath_content\n end", "def compile(file)\n Liquid::Template.parse load(file)\n end", "def compile\n end", "def css\n puts 'Compiling LESS files to CSS...'\n `lessc ./less/main.less ../www/_res/css/uncompressed/main.css`\n puts 'Compressing CSS files...'\n `java -jar ./_scripts/yuicompressor-2.4.2.jar ../www/_res/css/uncompressed/main.css -o ../www/_res/css/main.css`\nend", "def compile\n Timer.new(:title => \"YMDP\").time do\n clean_tmp_dir do\n process_domains\n end\n end\n end", "def compile(file_or_dir, options = {})\n options = {\n check_for_changes: true,\n sub_template: false,\n collect_stats: true,\n ignore_blank_lines: true\n }.merge(options)\n @scope = options[:scope]\n # Doing here so the output_directory (requiring target load) doesn't get hit if\n # it is already defined\n options[:output_directory] ||= output_directory\n @check_for_changes = options[:check_for_changes]\n @options = options\n if options[:sub_template]\n block = options.delete(:block)\n if is_erb?(file_or_dir)\n run_erb(file_or_dir, options, &block)\n else\n f = File.open(file_or_dir)\n content = f.read\n f.close\n insert(content)\n end\n else\n Origen.file_handler.resolve_files(file_or_dir, ignore_with_prefix: '_', import: :template) do |file|\n compile_file(file, options)\n end\n end\n end", "def compile_from_command_line(args)\n compress = false\n if args.index(\"-c\") != nil or args.index(\"--compress\") != nil\n compress = true\n args = args.keep_if { |arg| [\"-c\", \"--compress\"].index(arg) == nil }\n end\n \n if args.index(\"-d\") != nil\n d_index = args.index(\"-d\")\n if args.length < d_index + 1\n raise Exception, \"The -d argument must be followed immediately by a directory path in which to compiler .wml files.\"\n end\n \n dir_path = args[d_index + 1]\n \n if !File.directory? dir_path\n raise Exception, \"Invalid directory path following -d argument.\"\n end\n \n Dir.chdir dir_path\n if args[\"-r\"] != nil\n Dir['**/*'].each { |f|\n if File.directory? f and ['.', '..'][f] == nil\n puts f\n compile_file_from_path(f, :strict => false, :compress => compress)\n end\n }\n else\n Dir['*'].each { |f|\n if File.directory? f and ['.', '..'][f] == nil\n puts f\n compile_file_from_path(f, :strict => false, :compress => compress)\n end\n }\n end\n \n else\n strict = true\n if args.index(\"-f\") != nil or args.index(\"--force\") != nil\n strict = false\n args = args.keep_if { |arg| [\"-f\", \"--force\"].index(arg) == nil }\n end\n \n args.each { |filepath|\n compile_file_from_path(filepath, :strict => strict, :compress => compress)\n }\n \n end\nend", "def compile(template_name, compiled_content)\n self.kramdown_source.compile(template_name, compiled_content)\n end", "def compiledo\n\n end", "def compile\n exe_file = File.join(@temp_dir, 'exe')\n result = TTY::Command.new(printer: :quiet).run!('gcc', '-o', exe_file, @src_file)\n [exe_file, result]\n end", "def compile()\n begin\n\n @config = FILE_IMPORTER.load(@config, true)\n\n Wavy::Parsers::Import.load(@config, @config_root)\n Wavy::Parsers::Import.extract\n\n if @view == false\n exports = Wavy::Models::Exports.get\n exports.each do |key, export|\n rendered = self.class.render(export.path)\n output(rendered['template'], rendered['full_path'], rendered['file_path'])\n end\n else\n rendered = self.class.render(@view)\n output(rendered['template'], rendered['full_path'], rendered['file_path'])\n end\n\n rescue Exception => e\n puts e.message\n end\n end", "def compile_templates(production)\n dir = File.join(@proj_dir, @dynamic_folder)\n \n Dir[File.join(dir, '**/*')].each do |path|\n if File.file?(path) && !File.basename(path).match(/^(\\.|_)/)\n path = path[ (dir.size + 1)..-1 ]\n ext = File.extname(path)\n new_ext = ext_from_handler(ext) \n name = File.basename(path, ext)\n \n if production == true && \"#{name}.#{new_ext}\" != 'index.html' && new_ext == 'html'\n new_file = File.join(@output_folder, path.sub(/(\\/?[\\w-]+)\\.[\\w-]+$/, \"\\\\1/index.#{new_ext}\"))\n else\n new_file = File.join(@output_folder, path.sub(/\\.[\\w-]+$/, \".#{new_ext}\")) \n end\n \n create_dirs(new_file)\n File.open(new_file, 'w') {|f| f.write render(path) }\n puts \" - \\033[32mCreating\\033[0m '#{new_file}'\"\n end\n end\n end", "def compile(css, include_paths, settings)\n\tcss\nend", "def templates_for(file); end", "def all\n Dir.chdir(content_dir) do\n files = Dir.glob(File.join(\"**\", \"*#{SOURCE_FILE_EXT}\")).delete_if {|p| p =~ Regexp.new(\"\\\\.[0-9]+\\\\#{SOURCE_FILE_EXT}$\")}\n files.collect {|f| Page.new(uri_from_path(f), File.open(f, 'r') {|b| b.read})}\n end\n end", "def compile_latex(options)\n latexFilePath = options[:file]\n unless latexFilePath\n Tempfile.open('latex', @tmpDir) do |f|\n latexFilePath = f.path\n f.puts options[:contents]\n end\n end\n\n # Always use absolute paths\n if FileTest.readable? latexFilePath\n require 'pathname'\n latexFilePath = Pathname.new(latexFilePath).realpath\n else\n latexFilePath = File.join(@tmpDir, latexFilePath)\n end\n FileTest.readable? latexFilePath or\n raise LatexCompilationError.new(\"Can't find #{latexFilePath}. Try passing a valid, readable absolute path to the :file option, or some LaTeX to the :contents options _and_ a writable tmpDir (it's currently '#{@tmpDir}') to the compiler constructor\")\n\n finalOptions = @pdflatexOptions\n finalOptions += options[:add_options] if options[:add_options]\n finalOptions = options[:replace_options] if options[:replace_options]\n\n command = \"cd #{@tmpDir} && #{@pdflatexBin} #{finalOptions} #{latexFilePath}\"\n output = `#{command}`\n $? == 0 or raise LatexCompilationError.new(\"pdflatex terminated with an error\", output, command, File.read(latexFilePath))\n output =~ /Output written on (.*\\.pdf)/\n $1 or raise LatexCompilationError.new(\"Can't find output file produced by pdflatex.\", output, command, File.read(File.join(@tmpDir, latexFilePath)))\n File.read(File.join(@tmpDir, $1))\n end", "def compile_text(tmp)\n @prefilters.each do |f| \n tmp=f.run( tmp )\n end\n\n # compile to latex\n # puts tmp\n tmp=Kramdown::Document.new(tmp, @kramdown_opts).to_html\n\n # post filters\n @postfilters.each{ |f| tmp=f.run(tmp) }\n return tmp\n end", "def compile\n Tipsy::Runners::Compiler.new(@args, @site)\n end", "def process_compiled_file\n doc = Nokogiri::XML(File.open(@source))\n records = doc.xpath('//*[local-name()=\"mods\"]')\n records.each do |record|\n # record\n druid = record.parent['objectId']\n doc_node = Nokogiri::XML(record.to_s)\n mods_file = MODSFile.new(doc_node, @template_xml, @namespace)\n process_mods_file(mods_file, druid)\n end\n write_output if @analysis_only == false\n report_data_loss\n end", "def compile_file_from_path(filepath, options={})\n defaults = {:strict => true, :compress => false}\n options = defaults.merge options\n \n ext = filepath.split('/')[-1].split('.')[-1]\n if ext != 'wml'\n puts ext\n if options[:strict]\n raise Exception, \"Invalid extension for (#{filepath}). Must be .wml.\"\n else\n return\n end\n end\n \n file = File.open(filepath, 'rb')\n data = file.read\n \n html = Compiler.new(:text => data, :compress => options[:compress]).output\n \n temp = filepath.split('/')\n temp.pop()\n filename = temp.join('/') << '/' << filepath.split('/')[-1].split('.')[0] << '.html'\n File.open(filename, 'wb') {|f| f.write(html) }\nend", "def run(content, params = {})\n # Add filename to load path\n Uglifier.new(params).compile(content)\n end", "def execute\n\n logger = Logger.new(\"/dev/null\")\n logger.level = Logger::WARN\n log_adapter = JerichoLoggerAdapter.new(logger)\n\n\n Dir.glob('./**/*.{jsp,jspf}').each do |path|\n content = File.read(path)\n source = Source.new(content)\n source.setLogger(log_adapter)\n out = OutputDocument.new(source)\n\n tags = source.getAllStartTags\n tags.each do |tag|\n if applicable?(tag)\n process_tag(source, out, tag, path)\n end\n end\n SpacewalkHtmlClean.generate_diff(content, out, path)\n end\n end", "def run\n return unless setup_compilable\n\n @collection.files.values.each do |pointer|\n compiled_file = File.join(@collection.compiled_path, pointer['id'])\n\n FileUtils.mkdir_p File.dirname(compiled_file)\n FileUtils.cp_r pointer['realpath'], compiled_file\n\n Ruhoh::Friend.say { green \" > #{pointer['id']}\" }\n end\n end", "def compile_all(mustCompile)\r\n return if !mustCompile\r\n FileLineData.clear\r\n echoln _INTL(\"*** Starting full compile ***\")\r\n echoln \"\"\r\n yield(_INTL(\"Compiling town map data\"))\r\n compile_town_map # No dependencies\r\n yield(_INTL(\"Compiling map connection data\"))\r\n compile_connections # No dependencies\r\n yield(_INTL(\"Compiling phone data\"))\r\n compile_phone # No dependencies\r\n yield(_INTL(\"Compiling type data\"))\r\n compile_types # No dependencies\r\n yield(_INTL(\"Compiling ability data\"))\r\n compile_abilities # No dependencies\r\n yield(_INTL(\"Compiling move data\"))\r\n compile_moves # Depends on Type\r\n yield(_INTL(\"Compiling item data\"))\r\n compile_items # Depends on Move\r\n yield(_INTL(\"Compiling berry plant data\"))\r\n compile_berry_plants # Depends on Item\r\n yield(_INTL(\"Compiling Pokémon data\"))\r\n compile_pokemon # Depends on Move, Item, Type, Ability\r\n yield(_INTL(\"Compiling Pokémon forms data\"))\r\n compile_pokemon_forms # Depends on Species, Move, Item, Type, Ability\r\n yield(_INTL(\"Compiling machine data\"))\r\n compile_move_compatibilities # Depends on Species, Move\r\n yield(_INTL(\"Compiling shadow moveset data\"))\r\n compile_shadow_movesets # Depends on Species, Move\r\n yield(_INTL(\"Compiling Regional Dexes\"))\r\n compile_regional_dexes # Depends on Species\r\n yield(_INTL(\"Compiling ribbon data\"))\r\n compile_ribbons # No dependencies\r\n yield(_INTL(\"Compiling encounter data\"))\r\n compile_encounters # Depends on Species\r\n yield(_INTL(\"Compiling Trainer type data\"))\r\n compile_trainer_types # No dependencies\r\n yield(_INTL(\"Compiling Trainer data\"))\r\n compile_trainers # Depends on Species, Item, Move\r\n yield(_INTL(\"Compiling battle Trainer data\"))\r\n compile_trainer_lists # Depends on TrainerType\r\n yield(_INTL(\"Compiling metadata\"))\r\n compile_metadata # Depends on TrainerType\r\n yield(_INTL(\"Compiling animations\"))\r\n compile_animations\r\n yield(_INTL(\"Converting events\"))\r\n compile_trainer_events(mustCompile)\r\n yield(_INTL(\"Saving messages\"))\r\n pbSetTextMessages\r\n MessageTypes.saveMessages\r\n MessageTypes.loadMessageFile(\"Data/messages.dat\") if safeExists?(\"Data/messages.dat\")\r\n System.reload_cache\r\n echoln \"\"\r\n echoln _INTL(\"*** Finished full compile ***\")\r\n echoln \"\"\r\n pbSetWindowText(nil)\r\n end", "def compile_all(options = {})\n # Each tasks\n @tasks.keys.map do |name|\n # Compile the task\n compile name, options\n end\n end", "def process_directory\n Dir.foreach(@source) do |f|\n next unless f.match(/[a-z]{2}[0-9]{3}[a-z]{2}[0-9]{4}\\.xml/)\n druid = get_druid_from_filename(f)\n mods_file = MODSFile.new(Nokogiri::XML(File.open(File.join(@source, f))), @template_xml, @namespace)\n process_mods_file(mods_file, druid)\n end\n write_output if @analysis_only == false\n report_data_loss\n end", "def transform_files!(files, type) \n files.each do |file|\n parsed = \"\"\n namespace = [DEFAULT_LANGUAGE, 'txt', type] + Base.get_namespace(file, type)\n puts \"Converting: \" + file + \" into namespace: \"\n puts namespace.map {|x| \"[\\\"#{x}\\\"]\"}.join(\"\")\n \n n = Namespace.new(namespace)\n \n contents = Base.get_file_as_string(file)\n parsed << GettextI18nConvertor.string_to_i18n(contents, n)\n \n #puts parsed\n # write the file\n \n File.open(file, 'w') { |file| file.write(parsed)}\n \n \n \n n.merge(@translations)\n end\n end", "def run(filename, css); end", "def execute\n\n logger = Logger.new(\"/dev/null\")\n logger.level = Logger::WARN\n log_adapter = JerichoLoggerAdapter.new(logger)\n\n perl_pages = File.join(top_git_directory, 'java/code/**/*.{jsp,jspf}')\n java_pages = File.join(top_git_directory, 'web//**/*.{pxt, pxi}')\n [perl_pages, java_pages].each do |pages|\n Dir.glob(pages).each do |path|\n content = File.read(path)\n on_file_start(content, path)\n source = Source.new(content)\n source.setLogger(log_adapter)\n out = OutputDocument.new(source)\n\n tags = source.getAllStartTags\n tags.each do |tag|\n if applicable?(tag)\n process_tag(source, out, tag, path)\n end\n end\n\n on_file_changed(content, out.toString, path)\n on_file_done(path)\n end\n end\n\n Dir.glob(File.join(top_git_directory, 'java/code/**/*.{java}')).each do |path|\n content = File.read(path)\n on_file_start(content, path)\n on_file_done(path)\n end\n\n Dir.glob(File.join(top_git_directory, 'web/**/*.{pm}')).each do |path|\n content = File.read(path)\n on_file_start(content, path)\n on_file_done(path)\n end\n\n on_done\n end", "def compile!\n puts \"Compiling website..\"\n puts %x[rm -rf output]\n puts %x[nanoc compile]\nend", "def compile!\n puts \"Compiling website..\"\n puts %x[rm -rf output]\n puts %x[nanoc compile]\nend", "def compile!\n puts \"Compiling website..\"\n puts %x[rm -rf output]\n puts %x[nanoc compile]\nend", "def run\n return unless setup_compilable\n\n @collection.files.values.each do |pointer|\n compiled_file = File.join(@collection.compiled_path, pointer['id'])\n FileUtils.mkdir_p File.dirname(compiled_file)\n FileUtils.cp_r pointer['realpath'], compiled_file\n Ruhoh::Friend.say { green \" > #{pointer['id']}\" }\n end\n end", "def compile(options={})\n defaults = {:text => nil, :compress => nil}\n options = defaults.merge options\n @text = options[:text] if options[:text] != nil\n @compress = !!options[:compress] if options[:compress] != nil\n \n while @text != \"\" do\n self.process_current_level\n self.close_lower_level_tags\n self.process_next_line\n end\n \n self.close_tag while @open_tags.length > 0\n \n @output\n end", "def compile_text(tmp)\n @prefilters.each do |f| \n tmp=f.run( tmp )\n end\n\n # compile to latex\n tmp=Kramdown::Document.new(tmp, @kramdown_opts).to_latex\n\n # post filters\n @postfilters.each{ |f| tmp=f.run(tmp) }\n return tmp\n end", "def run\n each_test do |liquid, layout, assigns, page_template, template_name|\n compile_and_render(liquid, layout, assigns, page_template, template_name)\n end\n end", "def compile(file, options = {})\n return unless write?\n # Any options passed in from an interface will be passed to the compiler and to\n # the templates being compiled\n options[:initial_options] = options\n Origen.file_handler.preserve_state do\n begin\n file = Origen.file_handler.clean_path_to_template(file)\n Origen.generator.compile_file_or_directory(file, options)\n rescue\n file = Origen.file_handler.clean_path_to(file)\n Origen.generator.compile_file_or_directory(file, options)\n end\n end\n end", "def compile_js_sources(base_dir, definitions)\n chdir(base_dir) do\n definitions.each do |definition|\n\n jscompressor = :uglifyjs\n\n sources = definition['inputs'].join(' ')\n\n sh %{cat #{sources} > #{definition['output']}.tmp}\n sh %{#{jscompressor} #{definition['output']}.tmp > #{definition['output']}}\n rm definition['output'] + '.tmp'\n end\n end\nend", "def transform_files!(files, type) \n files.each do |file|\n @file = file\n @type = type\n parsed = \"\"\n @dirnames = Base.get_namespace(file,type) # directories after the app/type/ directory\n \n namespaces = LANGUAGES.collect do |lang|\n if type == 'views'\n namespace = [lang] + @dirnames\n else\n namespace = [lang, type] + @dirnames\n end\n \n puts \"Converting: \" + file + \" into namespace: \"\n puts namespace.map {|x| \"[\\\"#{x}\\\"]\"}.join(\"\")\n \n Namespace.new(namespace,lang)\n end\n\n contents = Base.get_file_as_string(file)\n parsed << GettextI18nConvertor.string_to_i18n(contents, namespaces, type)\n \n # write the app/type/file with new i18n format instead of gettext\n File.open(file, 'w') { |file| file.write(parsed)}\n \n namespaces.each do |ns|\n new_file_handler(ns)\n end\n end\n end", "def refresh\n Dir.glob('haml/**/*.haml').each do |file|\n if file !~ /\\/_/\n file.gsub!(/^haml\\//, '')\n compile(file) unless File.exist?(output_file(file))\n end\n end\n end", "def create\n in_directory do\n # Create files\n build \"cv.tex\"\n File.rename(\"cv.tex\", \"main.tex\")\n build \"Makefile\"\n end\n end", "def run\n @files.each { |filename| load(filename) }\n end", "def importTcxFolder(folderpath)\n runs = []\n Dir.foreach(folderpath) do |filename|\n if( /.tcx/ =~ filename)\n currentRun = readTcxFile(File.join(folderpath,filename))\n runs.push(currentRun)\n end\n end\n return runs \nend", "def compile\n read_yml if File.exists?(@project)\n\n default_options = {}\n other_options = {}\n\n @compile_options.each do |k,v| \n if /default/.match(k)\n default_options[k] = v\n else\n other_options[k] = v\n end\n end\n\n command = \"#{@flex_sdk_bin}#{@compiler}\"\n other_options.each { |k,v| command += \" -#{k}=\\\"#{[v].flatten.join ','}\\\"\" }\n default_options.each { |k,v| command += \" -#{k}=\\\"#{[v].flatten.join ','}\\\"\" }\n command += \" #{@document_class}.as\"\n\n# puts command\n# TextMate.exit_show_html\n\n @command = command\n#TextMate.exit_show_html\n if process_output command\n# load_debugger\n display_web_player #unless ARGV[0] = \"--display\"\n# display_player\n end\nend", "def compileterm\n\n end", "def compile(tokens, options = T.unsafe(nil)); end", "def transform_pages(dir = '')\n base = File.join(self.source, dir)\n entries = Dir.entries(base)\n entries = entries.reject { |e| ['.', '_'].include?(e[0..0]) }\n \n entries.each do |f|\n if File.directory?(File.join(base, f))\n transform_pages(File.join(dir, f))\n else\n first3 = File.open(File.join(self.source, dir, f)) { |fd| fd.read(3) }\n \n if first3 == \"---\"\n page = Page.new(self.source, dir, f)\n page.add_layout(self.layouts, site_payload)\n page.write(self.dest)\n else\n FileUtils.mkdir_p(File.join(self.dest, dir))\n FileUtils.cp(File.join(self.source, dir, f), File.join(self.dest, dir, f))\n end\n end\n end\n end", "def compile(filename)\n # First pass - define labels\n elements.each do |codeline|\n codeline.register_labels\n @@position += codeline.size\n end\n\n # Second pass - write to binary file\n File.open(filename, 'wb') do |f|\n elements.each do |codeline|\n f.write codeline.to_bin\n end\n end\n end", "def build!\n test_git!\n\n file_list = Dir.glob(\"#{@source}*\").sort # Pull the file list before creating the target directory\n\n setup_target\n\n add_runner\n\n file_list.each do |infile_name|\n rewrite_animation_frame infile_name\n create_commit infile_name\n end\n end", "def compile(mod); end", "def recompile\n @compiled = nil\n compile\n end", "def compile(path)\n content = File.read(path)\n %{\n var template = Hogan.compile(#{content.to_json});\n module.exports = (function(data){ return template.render(data); });\n }\n end", "def create_core_files\n empty_directory(target_dir)\n\n create_template(\"CHANGELOG.md.erb\", \"CHANGELOG.md\")\n create_template(\"Gemfile.erb\", \"Gemfile\")\n create_template(\"Rakefile.erb\", \"Rakefile\")\n create_template(\"README.md.erb\", \"README.md\")\n create_template(\"gemspec.erb\", \"#{config[:gem_name]}.gemspec\")\n create_template(\"license_#{config[:license]}.erb\", license_filename)\n create_template(\"gitignore.erb\", \".gitignore\")\n create_template(\"tailor.erb\", \".tailor\")\n create_template(\"travis.yml.erb\", \".travis.yml\")\n create_file(File.join(target_dir, \".cane\"))\n end", "def run(options = {})\n paths.each do |path|\n Dir.chdir(path) do\n Dir[\"**/*.less\"].each do |less_sheet|\n directory = File.dirname(less_sheet)\n target_filename = File.basename(less_sheet, File.extname(less_sheet)) + \".css\"\n destination = \"#{directory}/#{target_filename}\"\n \n if !File.exists?(destination) || File.stat(less_sheet).mtime > File.stat(destination).mtime\n engine = File.open(less_sheet) {|f| Less::Engine.new(f) }\n css = engine.to_css\n css.delete(\"\\n\") if options[:compress]\n \n FileUtils.mkdir_p(directory)\n File.open(destination, \"w\") {|file|\n file.write HEADER % [path + \"/\" + less_sheet] if Rails.env == \"development\"\n file.write css\n }\n end\n end\n end # chdir\n end # each\n end", "def compileArr(arr)\n\tfor a in arr\n\t\tif isExecutable(a)\n\t\t\t$stderr.puts red(\"Error: \")+\"Couldn't link the source code.\"\n\t\t\texit 1\n\t\tend\n\tend\n\n\tarr.map! { |a|\n\t\tescapePath(a)\n\t}\n\n\treturn compile(arr.join(\" \"))\nend", "def generate_c_source( dir, filename = self.name + '.c' )\r\n # TODO\r\n puts \"generating \" + dir + '/' + filename\r\n end", "def compileTS ( file )\n puts \"Compiling #{file}\"\n result = TypeScript::Node.compile_file( file )\n fail result.stderr if result.exit_status != 0\n result.js\n end", "def setup_source_files\n project.sources.each do |src|\n # Figure out where stuff should come from and go to\n source_file = src\n object_file = objectsify src\n compile_task object_file, source_file\n end#project.sources.each\n end", "def create_compile_ext_tasks(source_root, dest_root, invoking_task)\n compiled_ext = \"#{source_root}/#{SPECIAL_BUNDLE_NAMES[File.basename(source_root)] || File.basename(source_root)}.bundle\"\n create_copy_file_tasks(FileList[compiled_ext], source_root, dest_root, invoking_task)\n file compiled_ext => FileList[\"#{source_root}/*.c\"] do\n cd source_root do\n `ruby extconf.rb; make >/dev/null 2>&1`\n end\n end\nend", "def lessc(file_info)\n compile_file(file_info[1], \"app\")\nend", "def compile\n return if changed_ruby_files.empty?\n\n errors = changed_ruby_files.each_with_object([]) do |file, es|\n output = `ruby -cw \"#{file}\" 2>&1`\n next if output == \"Syntax OK\\n\"\n\n es << output\n end\n heading('Ruby Warnings', errors.join) unless errors.empty?\n end", "def compile_eth(dir, to)\n Dir.chdir(dir) do\n sh 'make'\n sh \"cp build/bin/geth #{to}/geth\"\n end\nend", "def compile_less_styles(base_dir, definitions)\n\n chdir(base_dir) do\n definitions.each do |definition|\n\n lessc = 'lessc'\n flags = []\n\n if definition['include']\n flags << \"--include-path=\" + definition['include'].join(':')\n end\n\n sources = definition['inputs'].join(' ')\n\n sh %{#{lessc} #{flags.join(' ')} #{sources} #{definition['output']}}\n\n end\n end\nend", "def process(*files) # TODO: rename from process - should act as SexpProcessor\n files.each do |file|\n warn \"Processing #{file}\" if option[:verbose]\n\n ext = File.extname(file).sub(/^\\./, \"\")\n ext = \"rb\" if ext.nil? || ext.empty?\n msg = \"process_#{ext}\"\n\n unless respond_to? msg then\n warn \" Unknown file type: #{ext}, defaulting to ruby\"\n msg = \"process_rb\"\n end\n\n begin\n sexp = begin\n send msg, file\n rescue => e\n warn \" #{e.message.strip}\"\n warn \" skipping #{file}\"\n nil\n end\n\n next unless sexp\n\n process_sexp sexp\n rescue SyntaxError => e\n warn \" skipping #{file}: #{e.message}\"\n end\n end\n end", "def generate_file_files\n template_file = @template_dir + 'file-page.html.erb'\n debug_msg \"Generating file documentation\"\n @all_files.each do |file|\n debug_msg \" file #{file.path}\"\n outfile = @output_dir + file.path\n @file = file\n self.render_template(template_file, binding(), outfile)\n end\n end", "def compile_file(filename = @filename)\n\t\t\tcached = @controller.cached_tilts[filename]\n\t\t\treturn cached if @cache && cached\n\n\t\t\tcompiled = Tilt.new(filename, nil, @tilt_options)\n\t\t\t@controller.cached_tilts[filename] ||= compiled if @cache\n\t\t\tcompiled\n\t\tend", "def _inter source\n c = compile source\n cifrom c\nend", "def compile\n\n if all_files.join().match(/\\.coffee/) and !@has_coffee\n error \"Cannot compile coffeescript\".red\n error \"Add \".white + \"gem 'coffee-script'\".yellow + \" to your Gemfile.\"\n end\n\n if @options[:uglify] and !@uglifier\n error \"Cannot uglify javascript\".red\n error \"Add \".white + \"gem 'uglifier'\".yellow + \" to your Gemfile.\"\n end\n\n begin\n js = Stitch::Package.new(:dependencies => dependencies, :paths => @options[:paths]).compile\n js = @uglifier.compile(js) if @uglifier\n js\n rescue StandardError => e\n error \"Stitch failed to compile\".red\n error e\n false\n end\n end", "def run\n require 'find'\n\n # Get compiled files\n # FIXME: requires #build_reps to have been called\n all_raw_paths = site.compiler.reps.map(&:raw_path)\n compiled_files = all_raw_paths.flatten.compact.select { |f| File.file?(f) }\n\n # Get present files and dirs\n present_files = []\n present_dirs = []\n Find.find(site.config[:output_dir] + '/') do |f|\n present_files << f if File.file?(f)\n present_dirs << f if File.directory?(f)\n end\n\n # Remove stray files\n stray_files = (present_files - compiled_files)\n stray_files.each do |f|\n next if filename_excluded?(f)\n delete_file(f)\n end\n\n # Remove empty directories\n present_dirs.reverse_each do |dir|\n next if Dir.foreach(dir) { |n| break true if n !~ /\\A\\.\\.?\\z/ }\n next if filename_excluded?(dir)\n delete_dir(dir)\n end\n end", "def generate_all\n copy_template_dir('layouts', 'layouts')\n copy_template_dir('content/bootstrap', 'content/bootstrap')\n copy_template_dir('content/content', 'content/content')\n delete_target_file('lib/default.rb')\n copy_template_dir('lib', 'lib')\n delete_target_file('Rules')\n copy_template_file('Rules', 'Rules')\n copy_template_file('.gitignore', '.gitignore')\n copy_template_file('cg_config.rb', 'cg_config.rb')\n copy_template_file('cg_config.rb_sample', 'cg_config.rb_sample')\n delete_target_file('content/stylesheet.css')\n delete_target_file('content/index.html')\n delete_target_file('layouts/default.html')\n create_empty_dir('content/images')\n end", "def rebuild(options)\n puts \"rebuilding to #{options[:out]}\"\n puts options[:files].inspect\n File.open(options[:out], 'w') do |out|\n # out.write @pre if @pre\n\n options[:files].each do |file|\n out.write wrap_source file\n end\n\n if options[:main]\n main = options[:main].sub(/\\.rb$/, '')\n out.write \"opal.require('#{main}');\\n\"\n end\n\n # out.write @post if @post\n end\n end", "def compile_coffee_to_js\n files = ['level_core', 'path_core', 'deadlock_core']\n files.each do |file|\n if File.exist?(\"lib/assets/#{file}.js\")\n File.delete(\"lib/assets/#{file}.js\")\n end\n compile_file_coffee_to_js(\"app/assets/javascripts/game/models/#{file}.js.coffee\", \"lib/assets/#{file}.js\")\n end\nend", "def compile\n compile_libraries\n compile_ohai_plugins\n compile_compliance\n compile_attributes\n compile_lwrps\n compile_resource_definitions\n compile_recipes\n end", "def pre_compile(main_file, settings)\n\tFile.read(main_file)\nend", "def generate_from_templates\r\n %w{package.json _config.yml}.each do |file|\r\n template file\r\n end\r\n end", "def files_to_translate\n folders = [\n \"app\",\n \"lib\",\n \"config\",\n locale_path\n ].join(\",\")\n\n exts = [\n \"rb\",\n \"erb\",\n \"haml\",\n \"slim\",\n \"rhtml\",\n \"js\",\n \"jsx\",\n \"vue\",\n \"coffee\",\n \"handlebars\",\n \"hbs\",\n \"mustache\"\n ].join(\",\")\n\n Dir.glob(\n \"{#{folders}}/**/*.{#{exts}}\"\n )\n end", "def compile_templates\n puts \"Compiling Templates\"\n js = V8::Context.new\n js.eval \"window = {}\"\n js.load File.join(APP_ROOT, \"public\", \"javascripts\", \"jade.js\")\n js.load File.join(APP_ROOT, \"public\", \"javascripts\", \"formtacular.js\")\n js.eval \"var jade = require('jade')\"\n js.eval \"templates = {}\"\n Dir[File.join(APP_ROOT, \"app\", \"views\", \"**\", \"*.jade\")].each do |file|\n begin\n chunks = (file.sub(/^#{APP_ROOT}\\/app\\/views/, \"\")).split(\"/\").slice(1..-1)\n (chunks.length - 1).times do |i|\n scrpt = <<-EOS\n if (templates.#{chunks.slice(0..i).join(\".\")} == undefined) {\n templates.#{chunks.slice(0..i).join(\".\")} = {};\n };\n EOS\n js.eval scrpt\n end\n chunks[-1] = chunks[-1].sub(/\\.jade$/, \"\")\n js['template_text'] = File.read(file)\n js.eval \"templates.#{chunks.join(\".\")} = jade.compile(template_text)\"\n rescue\n raise \"ERROR IN TEMPLATE: #{file} (#{$!})\"\n end\n end\n File.open(File.join(APP_ROOT, \"public\", \"javascripts\", \"rocket_templates.js\"), \"w\") {|f| f.write recursive_object_dump(js[\"templates\"], \"templates\")}\n puts \"Finished compiling templates.\"\n end", "def run(content, params = {})\r\n ::TypeScript.compile(content)\r\n end", "def render_self!(files)\n files.each do |f|\n if File.exists?(f + @config['tpl_ext'])\n basename = f.sub(/^#{@app_root}\\//, '')\n carp \"From #{'self'.blue.bold} render #{basename.bold}\",\n render_file!(f + @config['tpl_ext'], f), 1\n end\n end\n end", "def compile(filename)\n check_cookie\n Native::magic_compile(@cookie, filename);\n end", "def start_watch_files\n coffee_files.each do |file|\n @notifier.watch(file, :modify) do\n CoffeeCompiler.compile_file(file, true, true)\n end\n end\n end", "def compile_jst(paths)\n compiled = paths.map do |path|\n template_name = File.basename(path, File.extname(path))\n contents = File.read(path).gsub(/\\n/, '').gsub(\"'\", '\\\\\\\\\\'')\n \"window.JST.#{template_name} = #{Jammit.template_function}('#{contents}');\"\n end\n compiler = Jammit.include_jst_script ? File.read(DEFAULT_JST_SCRIPT) : '';\n [JST_START, compiler, compiled, JST_END].flatten.join(\"\\n\")\n end", "def spin_wheels\n @files.each do |file|\n code = File.read(file)\n sexp = @parse_tree.parse_tree_for_string(code, file)\n # puts sexp.inspect\n handle_nodes(sexp)\n end\n end", "def tcompile source\n tc = VishCompiler.new\n tc.source = source\n tc.default_optimizers[:tail_call] = true\n tc.run\n tc\nend", "def process\n return @template if @template\n\n out = StringIO.new\n err = StringIO.new\n\n files = Dir.glob(File.join(@path, '*.{yml,yaml}'))\n cfoo = Cfoo::Factory.new(out, err).cfoo\n\n Dir.chdir('/') do\n cfoo.process(*files)\n end\n\n raise(TemplateYamlParseError, err.string) unless err.string.empty?\n\n @template = out.string\n @template\n end" ]
[ "0.6738461", "0.6415091", "0.6218515", "0.6178845", "0.6080331", "0.5979561", "0.5928755", "0.5855256", "0.5852079", "0.5778334", "0.57682055", "0.5739974", "0.56925184", "0.56823117", "0.5682132", "0.5673344", "0.5659808", "0.5652723", "0.56107134", "0.557006", "0.5547858", "0.5533055", "0.5533017", "0.55260503", "0.5503823", "0.54886097", "0.54295796", "0.54201645", "0.53944016", "0.5379482", "0.53730154", "0.53696257", "0.53661966", "0.5355051", "0.53429276", "0.5341457", "0.5323552", "0.53221184", "0.53135985", "0.5309307", "0.53080773", "0.5307794", "0.52999073", "0.52977514", "0.52901363", "0.52901363", "0.52901363", "0.5289523", "0.52894753", "0.5286646", "0.5280531", "0.5234646", "0.52140427", "0.5208582", "0.5205881", "0.519957", "0.5193804", "0.5184425", "0.5181489", "0.5178943", "0.5177294", "0.51709956", "0.51696545", "0.51694775", "0.5166493", "0.5163835", "0.5161927", "0.5161235", "0.5132747", "0.5123628", "0.5119914", "0.51166177", "0.511366", "0.51133215", "0.51118255", "0.50969005", "0.50855637", "0.5084661", "0.5081458", "0.5080188", "0.50643873", "0.5048754", "0.50468886", "0.50385946", "0.50376654", "0.5034631", "0.5031346", "0.50310814", "0.5019928", "0.5019888", "0.50163007", "0.5013707", "0.49791607", "0.497767", "0.49747223", "0.49727058", "0.4970557", "0.49616304", "0.49528512", "0.49484408" ]
0.7556378
0
Set the user of the gas simulation
def user self.full_simulation.user end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_User(value)\n set_input(\"User\", value)\n end", "def set_User(value)\n set_input(\"User\", value)\n end", "def set_User(value)\n set_input(\"User\", value)\n end", "def set_User(value)\n set_input(\"User\", value)\n end", "def set_User(value)\n set_input(\"User\", value)\n end", "def set_User(value)\n set_input(\"User\", value)\n end", "def set_User(value)\n set_input(\"User\", value)\n end", "def set_User(value)\n set_input(\"User\", value)\n end", "def set_user(user)\n agent&.set_user(user)\n end", "def set_user; end", "def user=(value)\n @user = value\n end", "def user=(value)\n @user = value\n end", "def user(user)\n @options[:user] = user\n end", "def set_user\n puts \"STAN THE MANNNNNNNNNNN\"\n @user = User.find(params[:id])\n end", "def user=(user)\n\t\tfname= \"#{self.class.name}.#{__method__}\"\n\t\tLOG.debug(fname) {\"user=user=#{user}\"}\n\t\t@user=user\n\t#def_user(user)\n\tend", "def set_user(user)\n @user = user\n end", "def set_user(user)\n @user = user\n end", "def cmd_twitt_set_user(*args)\n\t\t\t\tif args.length > 0\n\t\t\t\t\tprint_status(\"Setting the DM target user to #{args[0]}\")\n\t\t\t\t\t@user = args[0]\n\t\t\t\telse\n\t\t\t\t\tprint_error(\"Please provide a value\")\n\t\t\t\tend\n\t\t\tend", "def set_user\n @user = @current_user\n end", "def set_user\r\n @user = current_user\r\n end", "def set_user\n @user = current_user \n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n\t\t@active = \"user\"\n\t\t@user = current_user\n\tend", "def set_user\n @user = User.find(current_user[:id])\n end", "def set_user\n @user = User.find(current_user[:id])\n end", "def user=(the_user)\n authentication.user = the_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = current_user\n end", "def set_user\n @user = User.find(current_user.id)\n end", "def set_user\n @user = User.find(current_user.id)\n end", "def set_user\n @user = User.find(current_user.id)\n end", "def set_user\n @user = User.find(current_user.id)\n end", "def set_user\n @user = User.find(current_user.id)\n end", "def set_user\n UserInfo.current_user = session[:user]\n end", "def set_user\n @user = User.find_by(name: params[:name]) || current_user\n end", "def set_user\n @user = User.find(params[:user_name])\n end", "def set_user\n @cUser = current_user\n puts \"***#{@cUser}\"\n end", "def set_user\n @user = User.find(session[:user_id])\n end", "def set_user\n @user = User.find(session[:user_id])\n end", "def set_user\n @user = User.find(current_user)\n end", "def set_user\n @user = User.find(current_user)\n end", "def set_user\n @user = User.find(user_id)\n end", "def set_user\n @telemarketer = User.find(params[:id])\n end", "def set_user\n @user = User.find(current_user.id)\n end", "def set_user\n @user = User.find_by(name: params[:name])\n end", "def set_usuario\n \n end", "def set_user\n @user = @current_user.admin ? User.find(params['id']) : @current_user\n end", "def user=(user)\n check_user(user)\n set_user(user)\n # returns user\n end", "def set_user\n \t@user = User.new\n end", "def set_Salutation(value)\n set_input(\"Salutation\", value)\n end", "def set_user\n\t\t\t@user = User.find(params[:id])\n\t\t\tredirect_to(users_path) unless current_user.organization == @user.organization\n\t\tend", "def set_user\n @user = User.find(session[:user_id])\n end", "def user=(user)\n Thread.current[\"current_user\"] = user\n end", "def set_user\n assessment = Assessment.find(@submission.assessment_id)\n\t\t\t@user = User.find(assessment.user_id)\n end", "def set_user\n @client = current_client\n end", "def set_user\n @user = User.find(session[:user_id])\n end", "def set_user(v)\n set_userinfo(v, @password)\n v\n end", "def set_user\n if session[:user_id]\n @user = User.find(session[:user_id])\n end\n end", "def user=(value)\n conf['dashboard']['user'] = value\n end", "def site_user=(value)\n @site_user = value\n end", "def set_user\n @launch = Launch.find(params[:id])\n end", "def set_user\n @user\n # @user = User.find(params[:id])\n end", "def set_user\n @contractor = Contractor.find(params[:id])\n end", "def user=(value)\n conf['api']['user'] = value\n end", "def set_user\n @user = User.find(params[:user][:id])\n end", "def set_system_user\n @system_user = SystemUser.find(params[:id])\n end", "def set_user\n user_id = params['user_id']\n @user = user_id ? User.find(user_id) : User.find(1)\n end", "def set_user(user)\n reset_session\n if user && user.is_a?(Marty::User)\n Marty::User.current = user\n start_user_session(user)\n else\n Marty::User.current = nil\n end\n end", "def set_user\n @user = session[:current_user]\n unless @user\n redirect_to home_path\n end\n end", "def current_user=(user)\n master.current_user = user\n end", "def name=(user)\n\t\t@name=user\n\tend", "def user=(user)\n if self.user_id != user.id\n self.user_id = user.id\n @tax = user.get_tax.dup # this is nasty but could not figure out how to do it the right way\n @tax.save\n self.tax_id = @tax.id\n self.price_with_vat = calculate_price_with_vat\n end\n end" ]
[ "0.70538545", "0.70538545", "0.70538545", "0.70538545", "0.70538545", "0.70538545", "0.70538545", "0.7052837", "0.69139683", "0.68261945", "0.6655212", "0.6655212", "0.65319496", "0.65124714", "0.6509996", "0.64686495", "0.64686495", "0.6377614", "0.636727", "0.6352112", "0.6328246", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6308611", "0.6302161", "0.62394065", "0.62394065", "0.6232968", "0.62280035", "0.62280035", "0.62280035", "0.62280035", "0.62280035", "0.62280035", "0.62280035", "0.62280035", "0.62280035", "0.6194726", "0.6194726", "0.6194726", "0.6194726", "0.6194726", "0.6185792", "0.61577445", "0.61562216", "0.61332387", "0.61085254", "0.61085254", "0.6091123", "0.6091123", "0.60706407", "0.6067288", "0.6064613", "0.606027", "0.6060177", "0.6057439", "0.60473436", "0.6042815", "0.6025952", "0.6023358", "0.6018836", "0.60155195", "0.6012937", "0.6011173", "0.60097307", "0.6008295", "0.6005965", "0.6003582", "0.59999883", "0.59990084", "0.59958446", "0.59929675", "0.5988861", "0.59776586", "0.59753734", "0.5968503", "0.5967565", "0.59661484", "0.59642845", "0.5960703", "0.5952636" ]
0.6078279
69
This method can estimate the consumption depending on the params you give to it
def estimation(yearly_cost, yearly_consumption, floor_space, heat_type, water_cooking_type, nb_residents ) yearly_cost = yearly_cost.to_f yearly_consumption = yearly_consumption.to_i floor_space = floor_space.to_i nb_residents = nb_residents.to_i if verify_nilness_params(yearly_cost, yearly_consumption, floor_space, heat_type, water_cooking_type, nb_residents) first_factor = heat_type == 'Gaz' ? 1 : 0 second_factor = water_cooking_type == 'Gaz' ? 1 : 0 yearly_consumption = floor_space * 100 * first_factor + consumption_people(nb_residents) * second_factor if yearly_consumption.zero? [yearly_cost, yearly_consumption] else [false, -1] end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def effective_rate; end", "def capacity_to_demand_multiplier\n 1.0\n end", "def capacity_to_demand_multiplier\n 8760.0\n end", "def rate_scale; end", "def estimated_consumption(cr)\n total = 0\n # If real consumption equals zero, try to estimate\n if cr == 0\n # Only estimates if there is an incidence that requires estimating\n if ReadingIncidence.reading_should_be_estimated(self.id)\n # 1. Consumption invoiced in the same period of last year (reading_2)\n total = consumption_invoiced(reading_2)\n if total == 0\n # 2. Consumption invoiced in the last period (reading_1)\n total = consumption_invoiced(reading_1)\n if total == 0\n # 3. Average consumption of...\n invoice_date = billing_period.try(:prebilling_starting_date) || Date.today\n # 3.1. ...the last 36 months of reading\n from_date = invoice_date - 36.months\n total = consumption_previous_readings(from_date, invoice_date)\n if total == 0\n # 3.2. ...the last 12 months of reading\n from_date = invoice_date - 12.months\n total = consumption_previous_readings(from_date, invoice_date)\n if total == 0\n # 4. Nominal capacity of the meter x 15 hs x quantity of months\n nominal_flow = meter.caliber.nominal_flow rescue 1.5\n nominal_flow = 1.5 if nominal_flow.blank?\n total = (nominal_flow * 15) * billing_frequency.total_months\n end # 3.2\n end # 3.1\n end # 2\n end # 1\n end # ReadingIncidence.reading_should_be_estimated(self.id)\n else # If real consumption not equals zero, try to compensate\n total = estimated_consumption_with_cr(cr)\n end # cr == 0\n total || 0\n end", "def measure; end", "def consumption\n unless reading_index_1.nil? or reading_index.nil?\n if reading_index_1 <= reading_index\n reading_index - reading_index_1\n else\n # vuelta de contador\n (((10 ** meter.meter_model.digits)-1) - reading_index_1) + reading_index\n end\n else\n 0\n end\n rescue\n 0\n end", "def number_of_units\n return 0.0 if demand.zero?\n return super unless full_load_hours&.positive?\n\n if input_capacity&.positive?\n demand / (input_capacity * full_load_hours)\n elsif output_capacity&.positive?\n (demand - output_of_loss) / (output_capacity * full_load_hours)\n else\n super\n end\n end", "def compute\n \tself.start_time = DateTime.now\n\n #call API request methods to fetch products\n\t\tApiRequestLog.process(self, endpoint)\n\n\t\tproducts = if category.present?\n\t\t\tProduct.where(category: category)\n\t\telse\n\t\t\tProduct.all\n\t\tend\n\n #compute average cubic weight\n\t\tif products.count > 0\n\t\t\t_total_cubic_weight = products.inject(0) {|r, p| r += p.volume.to_f * conversion_factor} \n\t\t\tself.average_cubic_weight = _total_cubic_weight.to_f / products.count \n\t\tend\n\n #update tracking data\n\t\tself.finished = true\n\t\tself.end_time = DateTime.now\n\t\tself.duration = end_time - start_time\n\t\tself.save(validate: false)\n\n #broadcast to client side to notify with calcualted average cubic weight of a related category\n if category.present?\n ActionCable.server.broadcast \"api_request_notifications_channel\", weight: \"#{average_cubic_weight} kg\", category: category\n else\n ActionCable.server.broadcast \"api_request_notifications_channel\", weight: \"#{average_cubic_weight} kg\"\n end\n\trescue\n end", "def perfect_material_efficiency\n (0.02 * self.blueprint.waste_factor * quantity).ceil\n end", "def get_cost_for_duration(resource, duration) ; 1.0 end", "def foreign_demand(point)\n local_price = @local.price_curve.get(point)\n producers = foreign_producers(point, local_price)\n\n producers.reduce(0.0) do |sum, prod|\n amount = prod.load_curve.get(point) -\n Convergence.competitive_load(prod, point, local_price)\n\n sum + amount\n end\n end", "def load_factor\n max_pax / capacity.to_f\n end", "def electric_based_input_capacity\n fetch(:electric_based_input_capacity) do\n if electricity_output_conversion && electricity_output_conversion > 0\n electricity_output_capacity / electricity_output_conversion\n end\n end\n end", "def manufacturing_cost\n\tcost = 0.0\n\tself.item.materials.each do |mat|\n\t\tcost += ( (mat.quantity * waste_factor).round * mat.item.market_data.value )\n\tend\n\tself.manufacturing_requirements.each do |ram|\n\t\tnext if ram.item.skill?\n\t\tcost += ( ram.quantity * ram.damagePerJob * ram.item.market_data.value )\n\tend\n\tif self.tech_level == 2\n\t\tcost += self.invention_cost\n\tend\n\tcost /= self.item.portionSize\nend", "def estimate\n # (native code) \n end", "def measure() @measure ||= (nb_weight == 0.0 ? 0.0 : sum_weight / nb_weight) end", "def cooling_based_input_capacity\n fetch(:cooling_based_input_capacity) do\n if cooling_output_conversion && cooling_output_conversion > 0\n heat_output_capacity / cooling_output_conversion\n end\n end\n end", "def compute(object)\n @seller = self.calculable.seller if self.calculable && self.calculable.respond_to?(:seller)\n weight = object.weight(@seller)\n # find weight range\n arr = JSON.parse(preferred_interval)\n # sort by inerval from smalles to biggest\n arr = arr.to_enum.sort_by {|x| x['int']}\n arr.each do |h|\n if weight.to_f < h['int'].to_f\n cost = h['cost'].to_f\n break\n end\n end\n # if not find range - maximum cost\n cost = arr.map {|x| x['cost']}.max.to_f unless cost\n cost\n end", "def inject_demand!\n full_load_hours = participant.full_load_hours\n\n full_load_seconds =\n if !full_load_hours || full_load_hours.nan?\n full_load_hours = 0.0\n else\n full_load_hours * 3600\n end\n\n target_api[:full_load_hours] = full_load_hours\n target_api[:full_load_seconds] = full_load_seconds\n\n target_api.demand =\n (full_load_seconds / input_efficiency) *\n participant.input_capacity_per_unit *\n participant.number_of_units\n end", "def capacity_to_demand_multiplier\n 3600.0\n end", "def cost\n deductible * RATE\n end", "def storage_cost(storage_id)\n\t\t\n\tend", "def measure\n\t\t1\n\tend", "def actual_cost\n self.cost/1000.to_f\n end", "def benchmarkedcosts\n benchmark_rate = @benchmark_rates[@service_ref].to_f\n @benchmarkedcosts = benchmark_rate * @uom_vol\n end", "def consumption_total_period\n # @readings = Reading.where(billing_period_id: billing_period_id, subscriber_id: subscriber_ids).where('reading_type_id NOT IN (?)',[1,2,5,6]).group_by(&:reading_1_id)\n readings = subscriber.readings.where(billing_period_id: billing_period_id).where('reading_type_id IN (?)',[ReadingType::NORMAL,ReadingType::OCTAVILLA,ReadingType::RETIRADA,ReadingType::AUTO]).order(:reading_date).group_by(&:reading_1_id)\n total = 0\n ccm = 0\n readings.each do |reading|\n total += reading[1].last.consumption\n end\n if meter.is_master?\n # Billable Master Meter:\n # Consumption to bill must be the substraction between this consumption\n # and the sum of the child meters consumption\n ccm = consumption_child_meters\n total = ccm > total ? 0 : total - ccm\n end\n return total\n end", "def benefits\n self.ticket_price * self.spectators\n end", "def input_efficiency\n @input_efficiency ||=\n begin\n base_cop = @config.base_cop\n per_degree = @config.cop_per_degree\n\n temperature_curve.map do |val|\n cop = base_cop + per_degree * val\n\n # Coefficient of performance must not drop below 1.0 (where there\n # is no \"balanced_with\" energy, and only \"based_on\" energy is\n # used).\n cop < 1.0 ? 1.0 : cop\n end\n end\n end", "def rate; end", "def rate; end", "def variable_operation_and_maintenance_costs_per_typical_input\n fetch(:variable_operation_and_maintenance_costs_per_typical_input) do\n return 0.0 if input_capacity.zero?\n return 0.0 if variable_operation_and_maintenance_costs_per_full_load_hour.nil?\n return 0.0 if variable_operation_and_maintenance_costs_for_ccs_per_full_load_hour.nil?\n\n (variable_operation_and_maintenance_costs_per_full_load_hour +\n variable_operation_and_maintenance_costs_for_ccs_per_full_load_hour) / # highlighting\n (input_capacity * 3600.0)\n end\n end", "def max_consumption\n @max_consumption ||= begin\n augment = max_repeats == Float::INFINITY ? 10 : max_repeats\n self.next&.max_consumption.to_i + augment\n end\n end", "def cost\n start_value\n end", "def call_price(attrs)\n i_per_second_rate = attrs.fetch(:\"#{key}_initial_rate\").to_f / 60.0\n n_per_second_rate = attrs.fetch(:\"#{key}_next_rate\").to_f / 60.0\n # duration that will be on next calls monitoring run\n duration = attrs.fetch(:duration).to_i + MONITORING_INTERVAL # TODO: check if needed cast to int\n initial_interval = attrs.fetch(:\"#{key}_initial_interval\").to_i # TODO: check if needed cast to int\n next_interval = attrs.fetch(:\"#{key}_next_interval\").to_i # TODO: check if needed cast to int\n connect_fee = attrs.fetch(:\"#{key}_fee\").to_f\n vat = key == 'destination' ? attrs.fetch(:customer_acc_vat, 0).to_f : 0\n initial_interval_billing = connect_fee + initial_interval * i_per_second_rate\n next_interval_billing = (duration > initial_interval ? 1 : 0) * ((duration - initial_interval).to_f / next_interval).ceil * next_interval * n_per_second_rate\n (initial_interval_billing + next_interval_billing) * (1 + vat / 100.0)\n end", "def available_capacity(point)\n local_producers(point, @abroad.price_curve.get(point))\n .reduce(0.0) do |sum, prod|\n sum + (prod.max_load_at(point) - prod.load_curve.get(point))\n end\n end", "def weight; end", "def rate_scale=(_arg0); end", "def calculate_carrier_demand\n demand_curve.sum * 3600\n end", "def cost(meth)\n @costs[meth][\"cost_per_call\"] / 100.0 rescue 0.0\n end", "def rate=(_arg0); end", "def rate=(_arg0); end", "def estimated_consumption_with_cr(cr)\n total = 0\n # if real consumption greater than zero, must compensate estimation balance\n if cr > 0\n total = cr < current_estimation_balance ? cr * (-1) : current_estimation_balance * (-1)\n end # cr > 0\n total || 0\n end", "def max_available_electricity\n @max_available_electricity ||=\n @producer.demand * @producer.output(:electricity).conversion\n end", "def co2_emissions_costs_per_typical_input\n 0.0\n end", "def param_buff_rate(param_id)\r\n @buffs[param_id] * 0.25 + 1.0\r\n end", "def how_high\n energy * energy\nend", "def load_factor\n @item_count/ size\n end", "def typical_input\n fetch(:typical_input) { input_capacity * capacity_to_demand_multiplier * full_load_hours }\n end", "def calculate\n # Percentage of understanding is calculated by following\n self.progress_rate = ((sum_of_point.to_f / total_count.to_f) * 100.00).round(2)\n end", "def calculate_liability\n calculate_gross\n end", "def covered_strength; end", "def uomd\n @framework_rate = @framework_rates[@service_ref].to_f\n\n # benchmark rate set here\n @benchmark_rate = @benchmark_rates[@service_ref].to_f\n\n @uomd =\n if @supplier_name && @rate_card.data['Discounts'][@supplier_name][@service_ref]\n (1 - @rate_card.data['Discounts'][@supplier_name][@service_ref]['Disc %'].to_f) * @uom_vol * @rate_card.data['Prices'][@supplier_name][@service_ref][@building_data['fm-building-type']].to_f\n else\n @uom_vol * @framework_rate\n end\n rescue StandardError => e\n raise e\n end", "def cost\n # Todo pull this from the DB\n 1000\n end", "def capacity_costs\n fetch(:capacity_costs) do\n if fixed_costs_per_mw_input_capacity\n fixed_costs_per_mw_input_capacity * input_capacity\n else\n 0.0\n end\n end\n end", "def load_factor\n Float(@num_items) / size\n end", "def production_cost\n price = use_vendor_price? ? item.price : self.price\n price * quantity\n end", "def load_factor\n @items*1.0/size\n end", "def estimate()\n # (native code)\n end", "def estimate()\n # (native code)\n end", "def estimate()\n # (native code)\n end", "def fuel_efficiency\n ((mileage - predecessor.mileage) / liter).round(1) if predecessor\n end", "def load_factor\n @count.to_f / size.to_f\n end", "def estimate\n # (native code)\n end", "def estimate\n # (native code)\n end", "def estimate\n # (native code)\n end", "def total_demand_for_electricity\n final_demand_for_electricity +\n non_final_demand_for_electricity +\n electricity_losses_if_export_is_zero\n end", "def load_factor\n @item_count / size.to_f\n end", "def load_factor\n @item_count / size\n end", "def load_factor\n @item_count / size\n end", "def compute_total_value\n @value= @net_price * @count\n end", "def cost\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end", "def modeler_description\n return 'For each AirLoop in the model, reduce the fan pressure drop by the user-specified amount (default 10%). This default is a conservative estimate; further reductions may be achieved, but may not be practical based on size and cost constraints.'\n end", "def profitability\n # based on \n # @pools.map { |p| }.sum\n end", "def load_factor\n @items / self.get_size\n end", "def unlimited_carrier_curve\n demand_profile * max_carrier_production\n end", "def operating_costs\n fixed_om_costs + variable_costs\n end", "def gear_inches\n #... some complex code\n ratio * diameter\n #... some complex code\n end", "def real_budget\n # Continue only if is possible to read it attr\n if read_attribute(:value)\n # operator value to decimal (readable value)\n operator_in_decimal = read_attribute(:value).to_f/100\n\n # Return it real budget\n operator_in_decimal - (operator_in_decimal*0.25) # TODO call here the taxes implementation\n end\n end", "def measure=(_arg0); end", "def cost\r\n\t\treturn @extra_cost + @real_need.cost\r\n\tend", "def cost\n @cost = 0.89\n end", "def convert_to_measured\n converter = 1\n case self.cost_unit\n when \"tsp\"\n converter = 0.16667 # convert to us_fl_oz \n self.cost_unit = \"us_fl_oz\"\n when \"tbsp\"\n converter = 0.5 # convert to us_fl_oz \n self.cost_unit = \"us_fl_oz\"\n when \"cup\"\n converter = 8 # convert to us_fl_oz \n self.cost_unit = \"us_fl_oz\"\n end\n self.cost_size *= converter\n end", "def cost\n 0.89\n end", "def gain(new_total_cost,original_total_cost = @original_total_cost)\n ((original_total_cost - new_total_cost) / original_total_cost.to_f) * 100\nend", "def cu_desired\n if @queue.exists?\n # The additional number of compute units modifying this queue will\n # cost.\n (@desired - @queue.size) * @queue.cu_per_node\n else\n # The number of compute units creating this queue will cost.\n @desired * @queue.cu_per_node\n end\n end", "def calculate_gain(change_ratio, previous_gains, new_investment)\n return (previous_gains + new_investment) * change_ratio\nend", "def gear_inches\n #... some complex code\n foo = some_intermediate_result * ratio * wheel.diameter\n # ...some complex code\n end", "def load_factor\n puts \"load_factor: #{@values} / #{@size}\"\n (@values + 0.0) / @size\n end", "def goods_produced\n (0.2 * base_production + trade_goods_bonus).round(6)\n end", "def product_weight\n price_calculator.weight\n end", "def calculated; end", "def cost()\n unless @cost\n @cost = @description.inject(0) do |val, el|\n val + ((el.nil? || el.to_s.end_with?('?')) ? 1 : 0.1)\n end\n end\n @cost\n end", "def battery_weight; end", "def unitRecoilCoefficient _args\n \"unitRecoilCoefficient _args;\" \n end", "def how_high(energy)\n energy * energy\nend", "def calculate_price_in_micro_units\n 0\n end", "def cost_of_cable(length)\n\t\tmeter = length * 0.01\n\t\tdollar = [meter * 0.4079 + 0.5771, meter * 0.0919 + 7.2745].min * BANDWIDTH\n\t\t(dollar * 100).round.to_f / 100\n\tend", "def variance_at_completion\n budget_at_completion - estimate_at_completion_cost\n end", "def heat_based_input_capacity\n fetch(:heat_based_input_capacity) do\n if heat_output_conversion && heat_output_conversion > 0\n heat_output_capacity / heat_output_conversion\n end\n end\n end" ]
[ "0.6671547", "0.653203", "0.62655646", "0.625655", "0.6216866", "0.6146086", "0.604413", "0.60081655", "0.59809095", "0.5969978", "0.59527034", "0.59379196", "0.5934625", "0.5927867", "0.5905628", "0.58848727", "0.5879764", "0.58713216", "0.5864117", "0.5857021", "0.58331126", "0.57964116", "0.57898855", "0.5789382", "0.57769084", "0.57567555", "0.5734686", "0.57322663", "0.57298505", "0.57157034", "0.57157034", "0.5708669", "0.5699982", "0.5699438", "0.5697257", "0.56949687", "0.56941575", "0.5684448", "0.56622297", "0.5661313", "0.56467855", "0.56467855", "0.5645898", "0.5645084", "0.56444854", "0.56388086", "0.56306535", "0.56266725", "0.5626423", "0.5607065", "0.56035376", "0.5603258", "0.55849886", "0.5580636", "0.5561089", "0.55585337", "0.55583733", "0.5555003", "0.55542606", "0.55542606", "0.55542606", "0.55520743", "0.5539729", "0.5537551", "0.5537551", "0.5537551", "0.5536891", "0.55341804", "0.55299604", "0.55299604", "0.5529802", "0.5527299", "0.5520885", "0.5520832", "0.551561", "0.55155396", "0.55019325", "0.55014175", "0.54995227", "0.5497201", "0.54971355", "0.549536", "0.5484808", "0.5483633", "0.54816103", "0.5475103", "0.5472789", "0.5472615", "0.54654986", "0.5455821", "0.5451326", "0.5442117", "0.5439824", "0.54386014", "0.54333085", "0.5430972", "0.5428884", "0.5424049", "0.54229367", "0.54222196" ]
0.55513304
62
This method execute the comparison between what is entered by the client and the contracts
def comparison(yearly_cost, yearly_consumption) first_filter = GasContract.all.select { |contract| yearly_consumption.between?(contract.low_kw_consumption_per_year * 1000, contract.high_kw_consumption_per_year * 1000) } second_filter = first_filter.select{ |contract| yearly_cost > (contract.kwh_price_base * yearly_consumption + contract.subscription_base_price_month * 12) } max_save = 0 all_savings = [] second_filter.each do |contract| savings = yearly_cost - (contract.kwh_price_base * yearly_consumption + contract.subscription_base_price_month * 12) if savings > max_save max_save = savings end all_savings << savings end [max_save.round(2), second_filter, all_savings] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def contract; end", "def contract; end", "def compare_contractor_data(contractor)\n message_good = \"Each attribute value is equal to the corresponding attributes of a freelancer #{contractor[:name]} on a profile page:\\n#{contractor}\"\n message_bad = \"Freelancer attribute values ​​not equal to the corresponding attributes in the shared page. Expected:\\n#{contractor}\\nGot:\\n#{@hash_contractor}\"\n #hash_contractor = @hash_contractor\n (contractor == @hash_contractor) ? (puts message_good) : (puts message_bad)\n end", "def update_contract\n case status.to_sym\n when :started then lock_contract\n when :successful then complete_contract\n when :failed then release_contract unless contract.flights.in_progress.any?\n else lock_contract\n end\n true\n end", "def configure_contracts_for_tests\n # configure accounts for eosdactokens\n run? %(cleos system newaccount --stake-cpu \"10.0000 EOS\" --stake-net \"20.0000 EOS\" --transfer --buy-ram-kbytes 2024 eosio dacowner #{CONTRACT_PUBLIC_KEY} #{CONTRACT_PUBLIC_KEY})\n run? %(cleos system newaccount --stake-cpu \"10.0000 EOS\" --stake-net \"10.0000 EOS\" --transfer --buy-ram-kbytes 2024 eosio otherowner #{CONTRACT_PUBLIC_KEY} #{CONTRACT_PUBLIC_KEY})\n\n run %(cleos push action dacdirectory regdac '{\"owner\": \"dacowner\", \"dac_name\": \"eosdac\", \"dac_symbol\": \"4,EOSDAC\", \"title\": \"Custodian Test DAC\", \"refs\": [[1,\"some_ref\"]], \"accounts\": [[2,\"daccustodian\"], [5,\"dacocoiogmbh\"], [7,\"dacescrow\"], [0, \"dacowner\"], [4, \"eosdactokens\"], [1, \"eosdacthedac\"]], \"scopes\": [] }' -p dacowner)\n\n run %(cleos push action daccustodian updateconfige '{\"newconfig\": { \"lockupasset\": \"10.0000 EOSDAC\", \"maxvotes\": 5, \"periodlength\": 604800 , \"numelected\": 12, \"should_pay_via_service_provider\": 1, \"auththresh\": 3, \"initial_vote_quorum_percent\": 15, \"vote_quorum_percent\": 10, \"auth_threshold_high\": 11, \"auth_threshold_mid\": 7, \"auth_threshold_low\": 3, \"lockup_release_time_delay\": 10, \"requested_pay_max\": \"450.0000 EOS\"}, \"dac_id\": \"eosdac\"}' -p dacowner)\n # run %(cleos push action daccustodian updateconfige '{\"newconfig\": { \"lockupasset\": \"10.0000 EOSDAC\", \"maxvotes\": 5, \"periodlength\": 604800 , \"numelected\": 12, \"should_pay_via_service_provider\": 1, \"auththresh\": 3, \"initial_vote_quorum_percent\": 15, \"vote_quorum_percent\": 10, \"auth_threshold_high\": 11, \"auth_threshold_mid\": 7, \"auth_threshold_low\": 3, \"lockup_release_time_delay\": 10, \"requested_pay_max\": \"450.0000 EOS\"}, \"dac_id\": \"otherdac\"}' -p otherowner -p dacowner)\n\n # run %(cleos push action eosdactokens create '{ \"issuer\": \"dacowner\", \"maximum_supply\": \"100000.0000 EOSDAC\", \"transfer_locked\": false}' -p dacowner)\n # run %(cleos push action eosdactokens create '{ \"issuer\": \"otherowner\", \"maximum_supply\": \"100000.0000 OTRDAC\", \"transfer_locked\": false}' -p otherowner)\n\n # run %(cleos push action eosdactokens issue '{ \"to\": \"eosdactokens\", \"quantity\": \"77337.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p dacowner)\n # run %(cleos push action eosdactokens issue '{ \"to\": \"eosdactokens\", \"quantity\": \"77337.0000 OTRDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p otherowner)\n # run %(cleos push action eosio.token issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"100000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\n # run %(cleos push action eosdactokens issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"1000.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p dacowner)\n # run %(cleos push action eosdactokens issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"1000.0000 OTRDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p otherowner)\n\n\n # run %(cleos push action eosdactokens newmemtermse '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\", \"dac_id\": \"custtestdac\"}' -p dacowner)\n # run %(cleos push action eosdactokens newmemtermse '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\", \"dac_id\": \"otherdac\"}' -p otherowner -p dacowner)\n\n #create users \n # seed_dac_account(\"testreguser1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n # seed_dac_account(\"testreguser1\", issue: \"100.0000 OTRDAC\", memberreg: \"New Latest terms\", dac_id: \"otherdac\", dac_owner: \"otherowner\") # run again for the same user in a different dac should just do the DAC stuff.\n # seed_dac_account(\"testreguser2\", issue: \"100.0000 EOSDAC\")\n # seed_dac_account(\"testreguser3\", issue: \"100.0000 EOSDAC\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n # seed_dac_account(\"testreguser4\", issue: \"100.0000 EOSDAC\", memberreg: \"old terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n # seed_dac_account(\"testreguser5\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n # seed_dac_account(\"testregusera\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n\n # This is required to allow the newperiode to run and set the account permissions from within the action.\n run %(cleos set account permission dacowner owner '{\"threshold\": 1,\"keys\": [{\"key\": \"#{CONTRACT_PUBLIC_KEY}\",\"weight\": 1}],\"accounts\": [{\"permission\":{\"actor\":\"daccustodian\",\"permission\":\"eosio.code\"},\"weight\":1}]}' '' -p dacowner@owner)\n # Configure accounts permissions hierarchy\n run %(cleos set account permission dacowner high #{CONTRACT_PUBLIC_KEY} active -p dacowner)\n run %(cleos set account permission dacowner med #{CONTRACT_PUBLIC_KEY} high -p dacowner)\n run %(cleos set account permission dacowner low #{CONTRACT_PUBLIC_KEY} med -p dacowner)\n run %(cleos set account permission dacowner one #{CONTRACT_PUBLIC_KEY} low -p dacowner)\n\nend", "def configure_contracts_for_tests\n # configure accounts for eosdactokens\n run %(cleos system newaccount --stake-cpu \"10.0000 EOS\" --stake-net \"10.0000 EOS\" --transfer --buy-ram-kbytes 2024 eosio dacowner #{CONTRACT_PUBLIC_KEY} #{CONTRACT_PUBLIC_KEY})\n run %(cleos system newaccount --stake-cpu \"10.0000 EOS\" --stake-net \"10.0000 EOS\" --transfer --buy-ram-kbytes 2024 eosio otherowner #{CONTRACT_PUBLIC_KEY} #{CONTRACT_PUBLIC_KEY})\n run %(cleos push action dacdirectory regdac '{\"owner\": \"dacowner\", \"dac_id\": \"custtestdac\", \"dac_symbol\": {\"symbol\": \"4,EOSDAC\", \"contract\": \"eosdactokens\"}, \"title\": \"Custodian Test DAC\", \"refs\": [[1,\"some_ref\"]], \"accounts\": [[2,\"daccustodian\"], [5,\"dacocoiogmbh\"], [7,\"dacescrow\"], [0, \"dacowner\"], [4, \"eosdactokens\"], [1, \"eosdacthedac\"]], \"scopes\": [] }' -p dacowner -p eosdacthedac@owner)\n run %(cleos push action dacdirectory regdac '{\"owner\": \"otherowner\", \"dac_id\": \"otherdac\", \"dac_symbol\": {\"symbol\": \"4,OTRDAC\", \"contract\": \"eosdactokens\"}, \"title\": \"Other Test DAC\", \"refs\": [[1,\"some_ref\"]], \"accounts\": [[2,\"daccustodian\"], [5,\"dacocoiogmbh\"], [7,\"dacescrow\"], [0, \"otherowner\"], [4, \"eosdactokens\"], [1, \"eosdacthedac\"]], \"scopes\": [] }' -p otherowner -p eosdacthedac@owner)\n\n run %(cleos push action daccustodian updateconfige '{\"newconfig\": { \"lockupasset\": {\"quantity\": \"10.0000 EOSDAC\", \"contract\": \"eosdactokens\"}, \"maxvotes\": 5, \"periodlength\": 604800 , \"numelected\": 12, \"should_pay_via_service_provider\": 1, \"auththresh\": 3, \"initial_vote_quorum_percent\": 15, \"vote_quorum_percent\": 10, \"auth_threshold_high\": 11, \"auth_threshold_mid\": 7, \"auth_threshold_low\": 3, \"lockup_release_time_delay\": 10, \"requested_pay_max\": { \"contract\": \"eosio.token\",\"quantity\": \"450.0000 EOS\"}}, \"dac_id\": \"custtestdac\"}' -p dacowner)\n run %(cleos push action daccustodian updateconfige '{\"newconfig\": { \"lockupasset\": {\"quantity\": \"10.0000 EOSDAC\", \"contract\": \"eosdactokens\"}, \"maxvotes\": 5, \"periodlength\": 604800 , \"numelected\": 12, \"should_pay_via_service_provider\": 1, \"auththresh\": 3, \"initial_vote_quorum_percent\": 15, \"vote_quorum_percent\": 10, \"auth_threshold_high\": 11, \"auth_threshold_mid\": 7, \"auth_threshold_low\": 3, \"lockup_release_time_delay\": 10, \"requested_pay_max\": { \"contract\": \"eosio.token\",\"quantity\": \"450.0000 EOS\"}}, \"dac_id\": \"otherdac\"}' -p otherowner -p dacowner)\n\n run %(cleos push action eosdactokens create '{ \"issuer\": \"dacowner\", \"maximum_supply\": \"100000.0000 EOSDAC\", \"transfer_locked\": false}' -p dacowner)\n run %(cleos push action eosdactokens create '{ \"issuer\": \"otherowner\", \"maximum_supply\": \"100000.0000 OTRDAC\", \"transfer_locked\": false}' -p otherowner)\n\n run %(cleos push action eosdactokens issue '{ \"to\": \"eosdactokens\", \"quantity\": \"77337.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p dacowner)\n run %(cleos push action eosdactokens issue '{ \"to\": \"eosdactokens\", \"quantity\": \"77337.0000 OTRDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p otherowner)\n run %(cleos push action eosio.token issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"100000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\n run %(cleos push action eosdactokens issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"1000.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p dacowner)\n run %(cleos push action eosdactokens issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"1000.0000 OTRDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p otherowner)\n\n\n run %(cleos push action eosdactokens newmemtermse '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\", \"dac_id\": \"custtestdac\"}' -p dacowner)\n run %(cleos push action eosdactokens newmemtermse '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\", \"dac_id\": \"otherdac\"}' -p otherowner -p dacowner)\n\n #create users \n seed_dac_account(\"testreguser1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"testreguser1\", issue: \"100.0000 OTRDAC\", memberreg: \"New Latest terms\", dac_id: \"otherdac\", dac_owner: \"otherowner\") # run again for the same user in a different dac should just do the DAC stuff.\n seed_dac_account(\"testreguser2\", issue: \"100.0000 EOSDAC\")\n seed_dac_account(\"testreguser3\", issue: \"100.0000 EOSDAC\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"testreguser4\", issue: \"100.0000 EOSDAC\", memberreg: \"old terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"testreguser5\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"testregusera\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"custtestdac\", dac_owner: \"dacowner\")\n\n # This is required to allow the newperiode to run and set the account permissions from within the action.\n run %(cleos set account permission dacowner owner '{\"threshold\": 1,\"keys\": [{\"key\": \"#{CONTRACT_PUBLIC_KEY}\",\"weight\": 1}],\"accounts\": [{\"permission\":{\"actor\":\"daccustodian\",\"permission\":\"eosio.code\"},\"weight\":1}]}' '' -p dacowner@owner)\n # Configure accounts permissions hierarchy\n run %(cleos set account permission dacowner high #{CONTRACT_PUBLIC_KEY} active -p dacowner)\n run %(cleos set account permission dacowner med #{CONTRACT_PUBLIC_KEY} high -p dacowner)\n run %(cleos set account permission dacowner low #{CONTRACT_PUBLIC_KEY} med -p dacowner)\n run %(cleos set account permission dacowner one #{CONTRACT_PUBLIC_KEY} low -p dacowner)\nend", "def precondition(_op)\n # gain access to operation instance methods \n op = Operation.find(_op.id)\n \n # get params\n response_request = op.input(\"Response Request Message\").val\n response_regex = op.input(\"Response Regex Format\").val\n response_tag = op.input(\"Response Tag\").val\n response_status_tag = \"Response Block status\"\n response_level = op.input(\"Response Level\").val\n \n case response_level\n when \"Plan\"\n obj = _op.plan\n response_tag += \" [#{_op.id}]\"\n response_status_tag += \" [#{_op.id}]\"\n when \"Operation\"\n obj = _op\n when \"Item\"\n obj = _op.input(\"Sample\").item\n end\n \n # library method from ControlBlock (Could this interface be improved?)\n user_response = get_user_response(op, response_request_message: response_request, response_regex: response_regex)\n \n # if the user hasn't responded yet, fail and keep downstream operations in waiting\n return false if user_response.nil?\n \n # Response recieved!\n \n # associate response to the item being passed through\n obj.associate(response_tag, user_response)\n \n # associate note on operation to indicate that you cant retroactively change response\n op.associate \"Response Block status\", \"Your response was successfully recorded as \\\"#{user_response}\\\"\"\n \n # pass input, allowing downstream operations to begin\n op.pass(\"Sample\", \"Sample\")\n\n # set status to done, so this block will not be evaluated again\n op.status = \"done\"\n op.save\n \n return true\nend", "def configure_contracts_for_tests\n\n run %(cleos system newaccount --stake-cpu \"10.0000 EOS\" --stake-net \"10.0000 EOS\" --transfer --buy-ram-kbytes 2024 eosio dacowner #{CONTRACT_PUBLIC_KEY} #{CONTRACT_PUBLIC_KEY})\n\n run %(cleos push action dacdirectory regdac '{\"owner\": \"dacowner\", \"dac_name\": \"escrowdac\", \"dac_symbol\": \"4,EOSDAC\", \"title\": \"Dac Title\", \"refs\": [], \"accounts\": [[2,\"daccustodian\"], [5,\"dacescrow\"], [7,\"dacescrow\"], [0, \"dacowner\"], [4, \"eosdactokens\"], [1, \"eosdacthedac\"] ]}' -p dacowner)\n run %(cleos push action eosdactokens create '{ \"issuer\": \"dacowner\", \"maximum_supply\": \"100000.0000 EOSDAC\", \"transfer_locked\": false}' -p dacowner)\n\n run %(cleos push action eosdactokens issue '{ \"to\": \"dacowner\", \"quantity\": \"78337.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p dacowner)\n run %(cleos push action eosio.token issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"100000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\n\n run %(cleos push action daccustodian updateconfig '{\"newconfig\": { \"lockupasset\": \"10.0000 EOSDAC\", \"maxvotes\": 5, \"periodlength\": 604800 , \"numelected\": 12, \"should_pay_via_service_provider\": 1, \"auththresh\": 3, \"initial_vote_quorum_percent\": 15, \"vote_quorum_percent\": 10, \"auth_threshold_high\": 11, \"auth_threshold_mid\": 7, \"auth_threshold_low\": 3, \"lockup_release_time_delay\": 10, \"requested_pay_max\": \"450.0000 EOS\"}, \"dac_scope\": \"escrowdac\"}' -p dacowner)\n\n run %(cleos set account permission dacescrow active '{\"threshold\": 1,\"keys\": [{\"key\": \"#{CONTRACT_PUBLIC_KEY}\",\"weight\": 1}],\"accounts\": [{\"permission\":{\"actor\":\"dacescrow\",\"permission\":\"eosio.code\"},\"weight\":1}]}' owner -p dacescrow)\n\n # Ensure terms are registered in the token contract\n run %(cleos push action eosdactokens newmemtermse '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\", \"dac_id\": \"escrowdac\"}' -p dacowner)\n\n #create users\n\n seed_dac_account(\"sender1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_scope: \"escrowdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"sender2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_scope: \"escrowdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"sender3\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_scope: \"escrowdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"sender4\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_scope: \"escrowdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"receiver1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_scope: \"escrowdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"arb1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_scope: \"escrowdac\", dac_owner: \"dacowner\")\n seed_dac_account(\"arb2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_scope: \"escrowdac\", dac_owner: \"dacowner\")\n\n run %(cleos push action eosio.token issue '{ \"to\": \"sender1\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\n run %(cleos push action eosio.token issue '{ \"to\": \"sender2\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\n run %(cleos push action eosio.token issue '{ \"to\": \"sender3\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\n run %(cleos push action eosio.token issue '{ \"to\": \"sender4\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\nend", "def contracts\n @user=current_user\n\n if @user.provider == true\n @contracts=Contract.where(:service_id => current_user.services.ids, :provider_id => nil)\n @contracts_acepted=Contract.where(:provider_id => current_user.id, :score => nil)\n render :dashboard\n else \n @contracts=Contract.where(:client_id => current_user.id)\n @contracts_provider=Contract.where.not(:provider_id => nil, :finished_contract => true)\n render :my_contracts\n end\n end", "def exchange\n\t\t# se os usuários não entiverem infectados e os pontos dos items serem iguais, executa o escambo entre os usuários\n\t\tdata_origin, data_destiny = origin_params, destiny_params\n\n\t\tunless (User.healthy?(data_origin[:user_id]) && User.healthy?(data_destiny[:user_id]))\n \t\trender json: { error: \"Denied access. User is contaminated!\" }, status: 403 and return\n\t\tend\n\n\t\tunless Inventory.equality(data_origin, data_destiny)\n\t\t\trender json: { error: \"The items points aren't equal!\" }, status: 400 and return\n\t\tend\n\n\t\tif Inventory.exchange(data_origin, data_destiny)\n\t\t\trender json: :success, status: 200\n\t\telse\n\t\t\trender json: :error, status: 400\n\t\tend\n\tend", "def contract; Contract.get(self.contract_id); end", "def execute_transaction\n if self.sender.balance > self.amount && self.status == \"pending\" && self.valid?\n self.receiver.deposit(self.amount)\n self.sender.deposit(-self.amount) \n self.status = \"complete\"\n else\n self.status = \"rejected\" \n \"Transaction rejected. Please check your account balance.\"\n end\n end", "def execute_transaction\n if self.valid? == true && @sender.balance > amount && @status == 'pending'\n @sender.balance -= amount\n @receiver.balance += amount\n @status = 'complete'\n else\n @status = 'rejected'\n \"Transaction rejected. Please check your account balance.\"\n end\n end", "def execute_transaction\n if self.status == \"pending\" && self.sender.balance > self.amount && self.valid?\n self.sender.balance -= self.amount\n self.receiver.balance += self.amount\n self.status = \"complete\"\n else\n self.status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\"\n end\n end", "def index\n @contracts = Contrato.all\n\n # geth attach ipc:\\\\.\\pipe\\geth.ipc\n client = Ethereum::IpcClient.new(\"\\\\\\\\.\\\\pipe\\\\geth.ipc\", false)\n client2 = Ethereum::HttpClient.new('http://localhost:8545')\n @balance = client2.eth_get_balance \"0xCf3cC4A1211920fff9716b0343bFe978DbbAb8B1\"\n @gas_price = client2.eth_gas_price\n puts @gas_price\n\n end", "def execute()\n\t\n\t\t# Retrieve a single entry from CHG:Infrastructure Change based on Remedy Login ID\n\t\tentry = @@remedy_forms['CHG:Infrastructure Change'].find_entries(\n\t\t :single,\n\t\t :conditions => [%|'#{@search_by_field}' = \"#{@parameters['search_value']}\"|],\n\t\t :fields => :all\n\t\t)\n\t\tif entry.nil?\n\t\t raise(%|Could not find entry on CHG:Infrastructure Change with '#{@search_by_field}'=\"#{@parameters['search_value']}\"|)\n\t\tend\n\t\t\n\n\t\t#For backwards compability with ArsModels prior to v2 as prior versions do not have a .to_s method for the EnumFieldValue class.\n\t\t#Only Enum & non-remedy types are included in the temp hash of field values.\n\t\thash_entry = {}\n\t\tentry.to_h.each do |key, value|\n\t\t\tif value.is_a? ArsModels::FieldValues::EnumFieldValue\n\t\t\t\thash_entry[key] = value.value\n\t\t\telsif !entry[key].is_a? ArsModels::FieldValues\n\t\t\t\thash_entry[key] = value\n\t\t\tend\n\t\tend\n\n\t\t# Build the results to be returned by this handler\n\t\tresults = <<-RESULTS\n\t\t<results>\n\t\t\t<result name=\"Actual Start Date\">#{escape(hash_entry['Actual Start Date'])}</result>\n\t\t\t<result name=\"Actual End Date\">#{escape(hash_entry['Actual End Date'])}</result>\n\t\t\t<result name=\"Change Timing\">#{escape(hash_entry['Change Timing'])}</result>\n\t\t\t<result name=\"Change Type\">#{escape(hash_entry['Change Type'])}</result>\n\t\t\t<result name=\"Company\">#{escape(hash_entry['Company'])}</result>\n\t\t\t<result name=\"Company3\">#{escape(hash_entry['Company3'])}</result>\n\t\t\t<result name=\"Completed Date\">#{escape(hash_entry['Completed Date'])}</result>\n\t\t\t<result name=\"Description\">#{escape(hash_entry['Description'])}</result>\n\t\t\t<result name=\"Detailed Description\">#{escape(hash_entry['Detailed Description'])}</result>\n\t\t\t<result name=\"Earliest Start Date\">#{escape(hash_entry['Earliest Start Date'])}</result>\n\t\t\t<result name=\"First Name\">#{escape(hash_entry['First Name'])}</result>\n\t\t\t<result name=\"Impact\">#{escape(hash_entry['Impact'])}</result>\n\t\t\t<result name=\"Last Name\">#{escape(hash_entry['Last Name'])}</result>\n\t\t\t<result name=\"Location Company\">#{escape(hash_entry['Location Company'])}</result>\n\t\t\t<result name=\"Risk Level\">#{escape(hash_entry['Risk Level'])}</result>\n\t\t\t<result name=\"Scheduled End Date\">#{escape(hash_entry['Scheduled End Date'])}</result>\n\t\t\t<result name=\"Scheduled Start Date\">#{escape(hash_entry['Scheduled Start Date'])}</result>\n\t\t\t<result name=\"Status\">#{escape(hash_entry['Change Request Status'])}</result>\n\t\t\t<result name=\"SRID\">#{escape(hash_entry['SRID'])}</result>\n\t\t\t<result name=\"SRInstanceID\">#{escape(hash_entry['SRInstanceID'])}</result>\n\t\t\t<result name=\"SRMSAOIGuid\">#{escape(hash_entry['SRMSAOIGuid'])}</result>\n\t\t\t<result name=\"Submitter\">#{escape(hash_entry['Submitter'])}</result>\n\t\t\t<result name=\"Support Group Name\">#{escape(hash_entry['Support Group Name'])}</result>\n\t\t\t<result name=\"Support Organization\">#{escape(hash_entry['Support Organization'])}</result>\n\t\t\t<result name=\"Urgency\">#{escape(hash_entry['Urgency'])}</result>\n\t\t</results>\n\t\tRESULTS\n\t\tputs(results) if @debug_logging_enabled\t\n\n\t\t# Return the results String\n\t\treturn results\n\tend", "def run remote = false,day_wise = true\n\t\t@remote = remote\n\t\t@day_wise = day_wise\n\t\t@companies.each do |company|\n\t\t\tconsumable = get_consumables(company)\n\t\t\t# print consumable.to_json\n\t\t\t# throw Exception.new(\"woh\")\n\t\t\tperforming_quote = consumable['performing_quote']\n\t\t\tday_quote\t\t = consumable['day_quote']\n\t\t\t# if ony both are found\n\t\t\tif (performing_quote != nil && day_quote != nil) then\n\t\t\t\t# price has appreciated over open\n\t\t\t\tset_performing_till_interval(performing_quote,day_quote,company)\n\t\t\t\t# stock is best performing\n\t\t\t\t\n\t\t\tend # if ony both are found\n\t\tend # end company loop\n\t\tif @day_wise\n\t\t\tset_performing(@quote_to_invest,@number_to_invest,@stock_till_interval)\n\t\tend\n\t\tself\n\tend", "def execute_transaction\n#each transfer can only happen once\n if valid? && sender.balance > amount && self.status == \"pending\"\n receiver.balance += amount\n sender.balance -= amount\n self.status = \"complete\"\n else\n#rejects a transfer if the sender doesn't have a valid account\n reject_transfer\n end\n end", "def execute_transaction\n if @counter != 0\n @status = 'rejected'\n false\n elsif !@sender.valid? || @sender.balance <= @amount\n @status = 'rejected'\n \"Transaction rejected. Please check your account balance.\"\n else\n @sender.balance = @sender.balance - @amount\n @receiver.balance = @receiver.balance + @amount\n @counter += 1\n @status = 'complete'\n end\n end", "def execute_transaction\n if valid? && @sender.balance > amount && @status == \"pending\"\n @sender.balance -= amount\n @receiver.balance += amount\n @status = \"complete\"\n else\n reject\n end\n end", "def create\n param! :comparison, Hash do |c|\n c.param! :name, String, required: true\n c.param! :description, String, default: \"\"\n c.param! :comparison_app, String\n c.param! :inputs, Hash, required: true\n end\n\n comp_params = unsafe_params[:comparison]\n inputs = comp_params[:inputs]\n app_dxid = CGI.unescape(comp_params[:comparison_app])\n\n app = if app_dxid == DEFAULT_COMPARISON_APP\n inputs = remap_inputs(inputs)\n DefaultComparatorApp\n else\n Comparisons::ComparatorProvider.call(app_dxid)\n end\n\n if app.blank?\n render_errors([I18n.t(\"invalid_comparator\")])\n return\n end\n\n project = User.find(@context.user_id).private_comparisons_project\n input_spec_preparer = InputSpecPreparer.new(@context)\n spec_inputs = input_spec_preparer.run(app, inputs)\n\n unless input_spec_preparer.valid?\n render_errors(input_spec_preparer.errors)\n return\n end\n\n api = DIContainer.resolve(\"api.user\")\n\n files_errors = []\n spec_inputs.files.each do |file|\n next if file.state == UserFile::STATE_CLOSED\n\n files_errors << I18n.t(\"comparison_file_not_closed\", file: file.name)\n end\n\n if files_errors.present?\n render_errors(files_errors)\n return\n end\n\n files = {}\n\n spec_inputs.run_inputs.each do |input_name, value|\n spec_inputs.files.each do |file|\n next unless file.uid == value\n\n files[input_name] = file\n end\n end\n\n run_input = {\n name: comp_params[:name],\n project: project,\n input: spec_inputs.dx_run_input,\n }\n\n begin\n job_id = api.app_run(app.dxid, nil, run_input)[\"id\"]\n rescue StandardError => e\n json_error = e.message.scan(/({\"error\".*)/).flatten.first\n\n raise e if json_error.blank?\n\n render_errors([JSON.parse(json_error).dig(\"error\", \"message\")])\n return\n end\n\n opts = {\n name: comp_params[:name],\n description: comp_params[:description],\n user_id: @context.user_id,\n scope: Comparison::SCOPE_PRIVATE,\n state: Comparison::STATE_PENDING,\n dxjobid: job_id,\n project: project,\n meta: {},\n app_dxid: app.dxid,\n run_input: spec_inputs.dx_run_input.reject do |input_name, _|\n files.keys.include?(input_name)\n end,\n }\n\n Comparison.transaction do\n comparison = Comparison.create!(opts)\n\n files.each do |input_name, file|\n comparison.inputs.create!(user_file_id: file.id, role: input_name)\n end\n end\n\n render json: { url: comparisons_path }\n end", "def execute_transaction\n if valid? && sender.balance > amount && self.status == \"pending\"\n sender.balance -= amount\n receiver.balance += amount\n self.status = \"complete\"\n else \n self.status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\" \n end\n end", "def validate\n\n return error_with_data(\n 'fcb_3',\n 'missing @client_id',\n 'Something Went Wrong.',\n GlobalConstant::ErrorAction.default,\n {}\n ) if @client_id.blank?\n\n @balances_to_fetch.each do |chain_type, data|\n\n case chain_type\n\n when GlobalConstant::CriticalChainInteractions.utility_chain_type\n\n return error_with_data(\n 'fcb_4',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:address_uuid].blank?\n\n return error_with_data(\n 'fcb_5',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:balance_types].blank?\n\n when GlobalConstant::CriticalChainInteractions.value_chain_type\n\n return error_with_data(\n 'fcb_6',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:address].blank?\n\n return error_with_data(\n 'fcb_7',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:balance_types].blank?\n\n else\n return error_with_data(\n 'fcb_7',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n )\n end\n\n end\n\n success\n\n end", "def create_contract(context: self.execution_context)\n caller_address = context.instruction.sender\n value = context.instruction.value\n account = find_account(caller_address)\n\n # return contract address 0 represent execution failed\n return 0 unless account.balance >= value || depth > max_depth\n snapshot = state.snapshot\n\n # generate contract_address\n material = RLP.encode_simple([caller_address.to_s, account.nonce - 1])\n contract_address = Utils.keccak(material)[-20..-1]\n\n transact(sender: caller_address, value: value, to: contract_address)\n\n # initialize contract account\n contract_account = find_account(contract_address)\n context.instruction.address = contract_address\n with_context(context) do\n if contract_account.has_code? || contract_account.nonce > 0\n err = ContractCollisionError.new(\"address #{contract_address.to_hex} collision\")\n debug(err.message)\n set_exception(err)\n else\n execute\n end\n\n deposit_code_gas = fork_schema.calculate_deposit_code_gas(output)\n gas_is_not_enough = deposit_code_gas > remain_gas\n deposit_code_reach_limit = output.size > fork_schema.contract_code_size_limit\n\n # check deposit_code_gas\n if gas_is_not_enough || deposit_code_reach_limit\n contract_address = 0\n if fork_schema.exception_on_deposit_code_gas_not_enough\n if deposit_code_reach_limit\n set_exception GasNotEnoughError.new(\"deposit_code size reach limit, code size: #{output.size}, limit size: #{fork_schema.contract_code_size_limit}\")\n else\n set_exception GasNotEnoughError.new(\"deposit_code_gas not enough, deposit_code_gas: #{deposit_code_gas}, remain_gas: #{remain_gas}\")\n end\n else\n set_output ''.b\n end\n elsif exception\n contract_address = 0\n else\n # set contract code\n set_account_code(contract_address, output)\n if fork_schema.contract_init_nonce != 0\n state.set_nonce(contract_address, fork_schema.contract_init_nonce)\n end\n # minus deposit_code_fee\n consume_gas deposit_code_gas\n end\n\n finalize_message(snapshot)\n [contract_address, exception]\n end\n end", "def accept_contract\n @contract=Contract.find(params[:id])\n @contract.provider_id=current_user.id\n @contract.save\n end", "def others_transfer_same_bank(client, client1, amount)\n puts \"Seleccione la cuenta origen de la cual trasladara los fondos (opciones ahorro o corriente):\"\n origin = gets.chomp.to_s.downcase\n puts \"Seleccione a que cuenta desea trasladar los fondos:\"\n puts \"Ahorro #{client1.saving_account} opcion 1\"\n puts \"Corriente #{client1.check_account} opcion 2\"\n destination = gets.chomp.to_i\n\n if origin == \"ahorro\" && destination == 1\n if client.saving_amount >= amount\n client.saving_amount -= amount\n client1.saving_amount += amount\n success_transfer\n else\n no_money\n end\n elsif origin == \"ahorro\" && destination == 2\n if client.check_amount >= amount\n client.saving_amount -= amount\n client1.check_amount += amount\n success_transfer\n else\n no_money\n end\n elsif origin == \"corriente\" && destination == 1\n if client.check_amount >= amount\n client.check_amount -= amount\n client1.saving_amount += amount\n success_transfer\n else\n no_money\n end\n elsif origin == \"corriente\" && destination == 2\n if client.saving_amount >= amount\n client.check_amount -= amount\n client1.check_amount += amount\n success_transfer\n else\n no_money\n end\n else \n return \"Las opciones validas son ahorro y corriente\"\n end \n end", "def do \n validate\n ZipMoney.api.checkout(self.params)\n end", "def execute_transaction\n if valid? && sender.balance > amount && self.status == \"pending\"\n sender.balance -= amount\n receiver.balance += amount\n self.status = \"complete\"\n else\n reject_transfer\n end\n\n end", "def contract_saved contract\n\t\t@contract = contract\n\t\t@semesters = @contract.semesters\n\t\t# Prices\n\t\t@application_fee = Prices::application_fee\n\t\t@deposit = Prices::deposit(@semesters)\n\t\t@early_bird = Prices::early_bird(@semesters, Date.today)\n\t\t@rent = Prices::rent(@semesters)\n\t\t@parking = Prices::parking_price(@contract.parking_type, @semesters)\n\t\t@multiple_semesters = Prices::multiple_semester_discounts @semesters\n\n\t\t# Calculations\n\t\t@parking_price = 0\n\t\t@parking.each do |park|\n\t\t\t@parking_price += park\n\t\tend\n\t\t@early_bird_sum = 0\n\t\t@early_bird.each do |early|\n\t\t\t@early_bird_sum += early\n\t\tend\n\t\t@multiple_semesters_sum = 0\n\t\t@multiple_semesters.each do |discount|\n\t\t\t@multiple_semesters_sum += discount\n\t\tend\n\n\t\t@euro = 0\n\t\t@euro = 50 unless @contract.euro.empty?\n\t\t@discounts_total = @early_bird_sum + @multiple_semesters_sum + @euro\n\n\t\t@rent_sum = 0\n\t\t@rent.each do |rent|\n\t\t\t@rent_sum += rent\n\t\tend\n\t\t@total = @application_fee + @deposit + @rent_sum + @parking_price - @discounts_total\n\n\t\tmail to: ['managers@windsormanor.net', @contract.email],\n\t\t\tsubject: 'Your Receipt for Windsor Manor'\n\tend", "def validate_step\n\n r = fetch_eth_ost_balance(true)\n return r unless r.success?\n\n r = super\n return r unless r.success?\n\n if is_client_step_one_complete? && is_client_step_two_complete?\n\n success\n\n elsif is_client_step_one_complete?\n error_with_go_to(\n 'e_tss_sth_1',\n 'token_setup_not_complete',\n GlobalConstant::GoTo.economy_planner_step_two\n )\n else\n error_with_go_to(\n 'e_tss_sth_2',\n 'token_setup_not_complete',\n GlobalConstant::GoTo.economy_planner_step_one\n )\n end\n\n end", "def run\n super\n \n require_enrichment\n \n # check our fingerprints for a version\n our_version = nil\n fp = _get_entity_detail(\"fingerprint\")\n fp.each do |f|\n if f[\"vendor\"] == \"SolarWinds\" && f[\"version\"] != \"\" && f[\"version\"] != nil\n our_version = f[\"version\"]\n break\n end\n end\n \n if our_version\n _log \"Got version: #{our_version}\"\n else\n _log_error \"Unable to get version, failing\"\n return\n end\n \n # affected versions are 2019.4 through 2020.2.1 HF1\n if compare_versions_by_operator(our_version, \"2019.4\", \">=\") && compare_versions_by_operator(our_version, \"2020.2.1 HF1\", \"<=\")\n _log_good \"Vulnerable!\"\n _create_linked_issue(\"solarwinds_orion_code_compromise\", {\n proof: {\n detected_version: our_version\n }\n })\n return\n else\n _log \"Version does not appear to be vulnerable\"\n end\n \n end", "def call\n bank_request = context.bank_request\n change_amount = context.provided_amount.to_i.positive? ? context.provided_amount.to_i : bank_request.requested_amount\n bank_cell = BankCell.find_by(bank: bank_request.bank, game_item: bank_request.game_item)\n context.fail!(message: 'Bank cell does not exist') if bank_cell.nil?\n context.fail!(message: 'Too many items') if bank_cell.amount < change_amount\n ActiveRecord::Base.transaction do\n bank_request.update!(status: 2)\n bank_cell.update!(amount: bank_cell.amount - change_amount)\n end\n context.bank_cell = bank_cell\n rescue StandardError\n context.fail!(message: 'Bank request can not be updated')\n end", "def execute_transaction\n if self.valid?\n @sender.balance -= @amount\n @receiver.balance += @amount\n @amount -= @amount\n @status = \"complete\"\n else\n @status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\"\nend\nend", "def test_guest_pay_for_entry\n @room1.guest_pay_for_entry(@guest2)\n assert_equal(115, @guest2.guest_wallet.room_price)\n end", "def compare\r\n invoice = params[:invoice]\r\n imported = Invoice.find(invoice[:Imported_id])\r\n generated = Invoice.find(invoice[:Generated_id])\r\n @result = Invoice.compareInvoices(imported, generated)\r\n if @result\r\n respond_to do |format|\r\n # compare.html.erb\r\n format.html\r\n end\r\n end\r\n end", "def test_test_place_order_with_minimum_criteria()\r\n # Parameters for the API call\r\n body = CreateOrderRequestModel.from_hash(JSON.parse(\r\n '{\"accountIdentifier\":\"sdkautotest5\",\"amount\":1.00,\"customerIdentifier\":\"sdk'\\\r\n 'autotest4\",\"sendEmail\":false,\"utid\":\"U561593\"}'\r\n ))\r\n\r\n # Perform the API call through the SDK function\r\n result = self.class.controller.create_order(body)\r\n\r\n # Test response code\r\n assert_equal(@response_catcher.response.status_code, 201)\r\n\r\n # Test whether the captured response is as we expected\r\n assert_not_nil(result)\r\n expected_body = JSON.parse(\r\n '{\"referenceOrderID\":\"RA180426-1401-64\",\"customerIdentifier\":\"sdkautotest4\",'\\\r\n '\"accountIdentifier\":\"sdkautotest5\",\"accountNumber\":\"A32386768\",\"amountCharg'\\\r\n 'ed\":{\"value\":1,\"currencyCode\":\"USD\",\"total\":1},\"marginShare\":{\"value\":0,\"cu'\\\r\n 'rrencyCode\":\"USD\"},\"denomination\":{\"value\":1,\"currencyCode\":\"USD\"},\"utid\":\"'\\\r\n 'U561593\",\"rewardName\":\"Reward Link\",\"sender\":{\"firstName\":\"\",\"lastName\":\"\",'\\\r\n '\"email\":\"\"},\"recipient\":{\"email\":\"\",\"firstName\":\"\",\"lastName\":\"\"},\"sendEmai'\\\r\n 'l\":false,\"status\":\"COMPLETE\",\"createdAt\":\"2018-04-26T20:08:59.624Z\",\"reward'\\\r\n '\":{\"credentials\":{\"Redemption URL\":\"https://sandbox.rewardlink.io/r/1/ed0Ht'\\\r\n 'zSblNV6oFddNnnlf68eXzGQoREvcxwxu_Vi5Wk\"},\"credentialList\":[{\"label\":\"Redemp'\\\r\n 'tion URL\",\"value\":\"https://sandbox.rewardlink.io/r/1/ed0HtzSblNV6oFddNnnlf6'\\\r\n '8eXzGQoREvcxwxu_Vi5Wk\",\"type\":\"url\"}],\"redemptionInstructions\":\"<p>&bull; C'\\\r\n 'lick on the redemption link above to activate your Reward Link.<br />\\\\r\\\\n'\\\r\n '&bull; Next, you will be able to spend your balance on retail gift cards.</'\\\r\n 'p>\\\\r\\\\n\\\\r\\\\n<p>If you don&#39;t want to spend your entire Reward Link val'\\\r\n 'ue right away, save the email or URL and return via the redemption link - y'\\\r\n 'our value will be waiting to be spent. This allows you to store the balance'\\\r\n ' to redeem at another time.</p>\\\\r\\\\n\"}}'\r\n )\r\n received_body = JSON.parse(@response_catcher.response.raw_body)\r\n assert(TestHelper.match_body(expected_body, received_body))\r\n end", "def contracts\n #if isAuth(@userhouselink.house) # only house owner or admin can delete\n id = params[:id]\n print \"contracts id=\" + id.to_s\n #houseId_userId_roleNumber\n houseId,userId,role = id.to_s.split(\"_\")\n print \"houseId=\" + houseId.to_s + \", userId=\" + userId.to_s + \", role=\" + role.to_s\n if(houseId && userId && role)\n @user_house_contracts = UserHouseContract.where(:house_id => houseId, :user_id => userId, :role => role)\n else\n @errMsg = \"Invalid input format.\"\n print @errMsg \n render 'error', :status => :unprocessable_entity \n end\n #\n #end\n end", "def other_transfer_diferent_bank\n puts \"Seleccione la cuenta origen de la cual trasladara los fondos (opciones ahorro o corriente):\"\n origin = gets.chomp.to_s.downcase\n puts \"Escriba la cuenta a la que desea trasladar el dinero\"\n destination = gets.chomp.to_i\n case origin\n when \"ahorro\"\n if client.saving_amount >= amount\n client.saving_amount -= amount\n success_transfer\n else\n no_money\n end\n when \"corriente\"\n if client.check_amount >= amount\n client.check_amount -= amount\n success_transfer\n else\n no_money\n end\n else \n return \"Las opciones validas son ahorro y corriente\"\n end \n\n\n\n end", "def authorize_net_valid(options)\n transaction = AuthorizeNet::AIM::Transaction.new($api_login, $api_key, :gateway => $gateway.to_s.to_sym,\n :encapsulation_character => \"|\",\n :allow_split => true)\n\n # Find a state\n if params[:state].blank?\n state = \"--\"\n else\n state = State.find_by_state(options[:state]).state_abbr\n end \n\n # Add address to request\n address = AuthorizeNet::Address.new(:first_name => options[:first_name],\n :last_name => options[:last_name],\n :street_address => options[:address],\n :city => options[:city],\n :state => state,\n :zip => options[:zip],\n :country => options[:country])\n transaction.set_address(address)\n\n # Convert a date expired\n expired_date = params[:expires_date_months].[](0..1).strip.concat(params[:expires_date_years].[](2..3))\n if expired_date.length == 3\n expired_date = \"0\".concat(expired_date)\n end\n\n # Add credit card to request\n credit_card = AuthorizeNet::CreditCard.new(options[:cc_number], expired_date, :card_code => options[:cvv])\n # Execute a request\n response = transaction.authorize(0.0, credit_card)\n\n # Get a result of request\n @authorize_transaction_id = response.transaction_id\n #@authorize_gateway = transaction.gateway\n @authorize_gateway = response.raw.body\n @authorize_code = response.authorization_code\n @response_code = response.response_code\n @response_reason_code = response.response_reason_code\n\n # Generate user message\n if @response_code.to_i == 1 && @response_reason_code.to_i == 1\n user_message = \"Billing information changed\"\n else\n user_message = get_user_message(@response_code, @response_reason_code)\n end\n\n unless response.success?\n # Card is invalid(authorize.net)\n flash[:error_card] = 'Can\\'t authorize credit card'\n\n # Block in session\n block_ip_in_session\n\n # Add transaction\n add_transaction(:i_account => @account.i_account, \n :type => \"payment_refund\",\n :transaction_id => @authorize_transaction_id,\n :gw_string => @authorize_gateway,\n :user_message => user_message,\n :ip => request.remote_ip.to_s,\n :authorization_code => @authorize_code)\n \n false\n else\n true\n end\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n returned_balances == o.returned_balances &&\n tags == o.tags &&\n transaction_type == o.transaction_type &&\n token == o.token &&\n ref_transaction == o.ref_transaction &&\n node == o.node &&\n network == o.network &&\n sub_network == o.sub_network &&\n mid == o.mid &&\n tid == o.tid &&\n stan == o.stan &&\n ca_name == o.ca_name &&\n ca_street == o.ca_street &&\n ca_zip == o.ca_zip &&\n ca_city == o.ca_city &&\n ca_region == o.ca_region &&\n ca_country == o.ca_country &&\n function_code == o.function_code &&\n reason_code == o.reason_code &&\n response_code == o.response_code &&\n approval_number == o.approval_number &&\n display_message == o.display_message &&\n date == o.date &&\n transmission_date == o.transmission_date &&\n local_transaction_date == o.local_transaction_date &&\n capture_date == o.capture_date &&\n settlement_date == o.settlement_date &&\n itc == o.itc &&\n irc == o.irc &&\n currency_code == o.currency_code &&\n amount == o.amount &&\n additional_amount == o.additional_amount &&\n acquirer_fee == o.acquirer_fee &&\n issuer_fee == o.issuer_fee &&\n rc == o.rc &&\n extrc == o.extrc &&\n duration == o.duration &&\n cardholder == o.cardholder &&\n acting_cardholder == o.acting_cardholder &&\n card == o.card &&\n account == o.account &&\n account2 == o.account2 &&\n mcc == o.mcc &&\n network_reference_id == o.network_reference_id &&\n acquirer_reference_id == o.acquirer_reference_id &&\n retrieval_reference_number == o.retrieval_reference_number &&\n forwarding_inst_id == o.forwarding_inst_id &&\n network_mid == o.network_mid &&\n request_amount == o.request_amount &&\n transaction_state == o.transaction_state &&\n remote_host == o.remote_host &&\n response_amount == o.response_amount &&\n expiration_time == o.expiration_time &&\n incoming_network_request_itc == o.incoming_network_request_itc &&\n digital_wallet_token == o.digital_wallet_token &&\n tranlog_attributes == o.tranlog_attributes &&\n payload == o.payload &&\n layer == o.layer &&\n transaction_name == o.transaction_name &&\n originator == o.originator &&\n acquirer == o.acquirer &&\n gpaorder == o.gpaorder &&\n gateway_log == o.gateway_log\n end", "def self_transfer(client, amount)\n puts \"Seleccione la cuenta origen de la cual trasladara los fondos (opciones ahorro o corriente):\"\n origin = gets.chomp.to_s.downcase\n case origin\n when \"ahorro\"\n if client.saving_amount >= amount\n client.saving_amount -= amount\n client.check_amount += amount\n success_transfer\n else\n no_money\n end\n when \"corriente\"\n if client.check_amount >= amount\n client.check_amount -= amount\n client.saving_amount += amount\n success_transfer\n else\n no_money\n end\n else \n return \"Las opciones validas son ahorro y corriente\"\n end \n end", "def get_contract\n if self.complete? and not self.passed_out?\n bid = self.get_current_call(Bid)\n double = self.get_current_call(Double)\n redouble = self.get_current_call(Redouble)\n declarer_bid = nil\n # Determine partnership.\n caller = self.who_called?(bid)\n partnership = [caller, Direction[(caller + 2) % 4]]\n # Determine declarer.\n self.calls.each do |call|\n if call.is_a?(Bid) and call.strain == bid.strain and partnership.include?(self.who_called?(call))\n declarer_bid = call\n break\n end\n end\n \n {\n :bid => bid,\n :declarer => declarer_bid.nil? ? nil : self.who_called?(declarer_bid),\n :double_by => double.nil? ? nil : self.who_called?(double),\n :redouble_by => redouble.nil? ? nil : self.who_called?(redouble) \n }\n else\n nil # Bidding passed out or not complete, no contract.\n end\n end", "def verifyIdeaResponseContract\n return verifyResponseContract(@idea_response_structure)\n end", "def validate_new_contract(data)\n errors = []\n\n #fields\n errors.push INVALID_CONTRACT_NAME unless GeneralValidator.validate_string data[:name]\n errors.push INVALID_CONTRACT_DESCRIPTION unless GeneralValidator.validate_string data[:description]\n errors.push INVALID_CONTRACT_EXPIRY unless GeneralValidator.validate_unix_datetime data[:expires]\n\n #arrays\n conditions_result = validate_new_conditions data[:conditions], data[:participants]\n transactions_result = validate_transactions data[:transactions]\n participants_result = validate_participants data[:participants]\n signatures_result = validate_new_contract_signatures data[:signatures]\n\n errors.concat conditions_result\n errors.concat transactions_result\n errors.concat participants_result\n errors.concat signatures_result\n\n raise ValidationError, {:valid => false, :errors => errors}.to_json if errors.count > 0\n end", "def checks\n return if @server.info[:server_version].nil? && @server.info[:app_server_version].nil? \n\n cve_data = update_cve_files(@server.info[:server_name])\n\n if cve_data.nil?\n @result.warned(\"CVE Data not available for #{@server.info[:server_name].capitalize}.\")\n return\n end\n\n server_version = @server.info[:server_version] \n\n short_name = \"#{@server.info[:server_name]}/#{@server.info[:server_version]}\"\n\n cve_data[\"cves\"].each do |cve|\n from_v = Version.new cve['from']\n to_v = cve['to'].nil? ? nil : Version.new(cve['to']) \n prior_v = cve['prior'].nil? ? nil : Version.new(cve['prior']) \n\n # If the server version is \n if server_version >= from_v \n \n # if there are no to_ / prior_v or to_v is present and we're in the range or prior is present and we're in the range, then...\n if ( to_v.nil? && prior_v.nil? ) || ( !to_v.nil? && server_version <= to_v ) || ( !prior_v.nil? && server < prior_v )\n @result.failed(\"CVE: #{short_name} CVE-#{cve['cve']}: #{cve['title']}: #{cve['url']}\")\n end\n end\n\n end\n\n end", "def test_checkin\n req = c.checkin(\"abc123\", 123, &blk)\n\n assert_sent(req.tag, :verb => V::CHECKIN, :path => \"abc123\", :cas => 123)\n assert_recv(reply(req.tag, :cas => 123))\n end", "def execute_transaction\n if valid? && sender.balance > amount && status == \"pending\"\n receiver.balance += amount\n sender.balance -= amount\n self.status = \"complete\"\n else \n reject_transfer\n end\n end", "def check_cells(cells, remote_asset, fee_required, changes, stx_info)\n @logger.info(\"#{@key.pubkey} check cells: amount begin.\")\n\n for change in changes\n change_actual = change[:output].capacity\n change_min = change[:output].calculate_min_capacity(change[:output_data])\n return \"error_change_container_insufficient\", change_actual - change_min if change_actual < change_min\n end\n\n stx_actual = stx_info[:outputs][0].capacity\n stx_min = stx_info[:outputs][0].calculate_min_capacity(stx_info[:outputs_data][0])\n return \"error_settle_container_insufficient\", stx_actual - stx_min if stx_actual < stx_min\n\n change = assemble_change(changes)\n\n capacity_gathered = get_total_capacity(cells)\n return \"error_cell_dead\", true if !capacity_gathered\n # check stx is enough.\n for current_type_script_hash in remote_asset.keys()\n current_type = find_type(current_type_script_hash)\n current_decoder = current_type[:decoder]\n # I only import one stx, so the index is 0.\n check_output_result = check_output(remote_asset[current_type_script_hash], stx_info[:outputs][0], stx_info[:outputs_data][0], current_decoder)\n # check the amount he invests is right as he claims.\n return \"error_amount_invest_inconsistent\", check_output_result if check_output_result != 0\n # check change + settelement refund is equal to amount_total\n if current_type_script_hash != \"\"\n amount_required = remote_asset[current_type_script_hash]\n amount_gathered = get_total_amount(cells, current_type_script_hash, current_decoder)\n refund_amount = current_decoder.call(stx_info[:outputs_data][0]) + current_decoder.call(change[:output_data])\n return \"error_amount_refund_inconsistent\", amount_gathered - refund_amount if amount_gathered != refund_amount\n end\n end\n\n refund_capacity = change[:output].capacity + stx_info[:outputs][0].capacity\n\n return \"error_capacity_inconsistent\", capacity_gathered - (fee_required + refund_capacity) if capacity_gathered != fee_required + refund_capacity\n\n @logger.info(\"#{@key.pubkey} check cells: capacity end.\")\n return \"success\", \"0\"\nend", "def test_pair_sync\n return_value = YAML::load_file(File.join(__dir__, 'txt/result.txt'))\n\n Pairdata::Client.stub :post, return_value do\n #verify default options fail, require app number\n assert_raises Pairdata::BadQuery do\n @client.pair_sync\n end\n\n res = @client.pair_sync(searchText: 'random_app_num')\n\n assert_kind_of Pairdata::Result, res\n assert_equal 'Pil Sang Yoo , Gyeonggi-do (KR)', res.primaryInventor\n end\n end", "def validate\n\n @critical_chain_interaction_log = CriticalChainInteractionLog.where(\n parent_id: @parent_id,\n activity_type: GlobalConstant::CriticalChainInteractions.deploy_airdrop_activity_type\n ).first\n\n return error_with_data(\n 'j_s_gasj_1',\n 'something_went_wrong',\n GlobalConstant::ErrorAction.default\n ) if @critical_chain_interaction_log.blank?\n\n @client_id = @critical_chain_interaction_log.client_id\n\n success\n\n end", "def configure_contracts\n # configure accounts for eosdactokens\n\n run %(cleos push action eosdactokens create '{ \"issuer\": \"dacdirectory\", \"maximum_supply\": \"100000.0000 EOSDAC\", \"transfer_locked\": false}' -p dacdirectory)\n\n run %(cleos push action dacdirectory regdac '{\"owner\": \"dacdirectory\", \"dac_name\": \"dacproposals\", \"dac_symbol\": \"4,MYSYM\", \"title\": \"Dac Title\", \"refs\": [], \"accounts\": [[2,\"daccustmock\"], [5,\"\"], [7,\"dacescrow\"], [0, \"dacauthority\"], [4, \"eosdactokens\"], [1, \"eosdacthedac\"] ], \"scopes\": []}' -p dacdirectory)\n run %(cleos push action dacdirectory regdac '{\"owner\": \"dacdirectory\", \"dac_name\": \"mydacname2\", \"dac_symbol\": \"4,EOSDAC\", \"title\": \"Dac Title\", \"refs\": [], \"accounts\": [[1,\"account1\"]], \"scopes\": []}' -p dacdirectory)\n\n run %(cleos push action eosdactokens issue '{ \"to\": \"eosdactokens\", \"quantity\": \"78337.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p dacdirectory)\n run %(cleos push action eosio.token issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"100000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio)\n\n # Ensure terms are registered in the token contract\n run %(cleos push action eosdactokens newmemtermse '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\", \"dac_id\": \"dacproposals\"}' -p dacauthority)\n\n #create users\n seed_dac_account(\"proposeracc1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"proposeracc2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"proposeracc3\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"arbitrator11\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n\n seed_dac_account(\"custodian1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian3\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian4\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian5\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian11\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian12\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian13\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n seed_dac_account(\"custodian14\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\", dac_id: \"dacproposals\", dac_owner: \"dacdirectory\")\n\n run %(cleos push action daccustmock updatecust '{\"custodians\": [\"custodian1\", \"custodian2\", \"custodian3\", \"custodian4\", \"custodian5\", \"custodian11\", \"custodian12\", \"custodian13\", \"custodian14\"], \"dac_id\": \"dacproposals\"}' -p proposeracc1)\n\n run %(cleos set account permission dacauthority one '{\"threshold\": 1,\"keys\": [],\"accounts\": [{\"permission\":{\"actor\":\"custodian1\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian11\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian12\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian13\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian2\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian3\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian4\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian5\",\"permission\":\"active\"},\"weight\":1}]}' low -p dacauthority@low)\nend", "def testExactMatch\n initTestCase do\n $Context[:SlaveActions] = [\n [ 'DummyTool', 'DummyAction', [] ]\n ]\n executeMaster( [ '--process', 'DummyProcess', '--user', 'DummyUser' ],\n :Repository => 'Dummy/MasterServerInstalledWithDummySenderFilterDummyTool',\n :AddRegressionProcesses => true,\n :AddRegressionSenders => true\n ) do |iError|\n assert_equal( [\n [ 'sendMessage', [ 'DummyUser', {\n 'DummyTool' => {\n 'DummyAction' => [\n []\n ]\n }\n } ]\n ]\n ],\n $Variables[:DummySenderCalls]\n )\n assert_equal([], getSlaveClientQueue)\n end\n end\n end", "def put_contract(q)\n$LOG.info('put_contract');\n@USER=q[\"USER\"];\n@CONTRACT=q[\"CONTRACT\"];\n@CID=@USER[\"CID\"];\n\n@user=$CACHE.get(\"USER\",@CID)\n$LOG.info(@USER.to_s()+' - '+@CONTRACT.to_s());\n\nif (@user == nil) \n @user=$STORAGE.get(\"USER\",@CID)\n if (@user == nil) \n $STORAGE.put(\"USER\",@CID,@USER)\n @user=$STORAGE.get(\"USER\",@CID)\n end\n if (@user != nil)\n @user=$CACHE.put(\"USER\",@CID,@user) ## new user added\n end \nend\n\n## add new contract with vendor\n\nif (@CONTRACT!=nil)\n@VID=@CONTRACT[\"VID\"];\n@vendor=get_vendor(@VID)\nif (@vendor != nil)\n## vendor exists - OK!!!\n@contracts=get_contracts_by_vendor(@VID);\n\n$LOG.info(@VID.to_s()+' get_contracts_by_vendor '+@contracts.to_s());\n\n\n@contract=@contracts[@CID]\n\n$LOG.info(@CID.to_s()+' get_contract '+@contract.to_s());\n\nif (@contract!=nil)\nclear_price_for_contract(@contract)\nend\nput_contract_for_vendor(@USER, @CONTRACT)\nend \nend\n\nend", "def dataVerification(accounts)\r\n @insuredName = (account[\"accountName\"] + \"_\" + $accountID)\r\n \r\n accounts.each do |account| \r\n if account[\"accountName\"] != \"\" \r\n \r\n #run tests for individual tables, in this case, just the AccountInfo table\r\n accountInfo(account)\r\n\r\n puts \"\"\r\n puts \"Data Compare tests complete for account: \" + @insuredName + \".\"\r\n puts \"\"\r\n end\r\n end\r\nend", "def index\n if params[:commit] == '검색'\n if !params[:search].blank?\n @admin_contracts = Contract.search_by_user_type(params[:search], params[:category])\n elsif !(params[:start_date].blank? && params[:end_date].blank?)\n @admin_contracts = Contract.where('manage_start_at > ? AND manage_start_at <= ?', params[:start_date], params[:end_date])\n elsif !params[:step].blank?\n case params[:step]\n when \"1\"\n @admin_contracts = Contract.with_hospital\n when \"2\"\n @admin_contracts = Contract.with_studio\n end\n\n else\n @admin_contracts = Contract.all\n end\n\n else\n @admin_contracts = Contract.all\n end\n\n end", "def call\n transaction do\n @failures = {}\n update_contents_and_resort_opinions(form)\n end\n\n if @failures.any?\n broadcast(:invalid, @failures)\n else\n broadcast(:ok)\n end\n end", "def initialize(this_transaction)\n\n # Prepare for some sanity check errors\n required_hash = {\n :operation=>\":operation . The code of requested operation to be done\", \n :amount=>\":amount . The amount of the transaction\", \n :user_id=>\"user_id . The id of your user in your own Database\", \n :card_nbr=>\":card_nbr . The crypted partial card number in your Database\", \n :expire=>\":expire . The expiration date of the card\",\n :cvv2=>\":cvv2 . The CVV2 parameter you should have stored in your DB\",\n :numtrans=>\":numtrans . The previous transaction number\" \n }\n\n # WARNING :numtrans parameter IS REQUIRED only for operations 00002, 00005, 00013, 00017, 00052, 00055 \n numtrans_required_array = ['00002', '00005', '000013', '00017', '00052', '00055']\n\n # Let's check if we've got everything (only numtrans is optionnal here)\n required_hash.each do |parameter, name|\n if !this_transaction.has_key?(parameter)\n if(parameter == :numtrans && numtrans_required_array.include?(this_transaction[:operation]))\n raise \"Paybox line 61 => Parameter #{name} is required for operation code #{this_transaction[:operation]} !\"\n elsif(parameter != :numtrans)\n # Required parameter missing\n raise \"Paybox line 64 => Parameter #{name} is missing !\"\n end\n end\n end\n\n ##### List of all available operations ###########\n # One-shot operations for customers\n # ------------------------------------------------\n # 00001 = Autorisation, \n # 00002 = Débit, \n # 00003 = Autorisation + Débit,\n # 00004 = Crédit, \n # 00005 = Annulation, \n # 00011 = Vérification de l’existence d’une transaction, \n # 00012 = Transaction sans demande d’autorisation, \n # 00013 = Modification du montant d’une transaction, \n # 00014 = Remboursement, \n # 00017 = Consultation\n \n # Recurring Operations on suscriber accounts\n # -----------------------------------------------\n # 00051 = Autorisation seule sur un abonné, \n # 00052 = Débit sur un abonné, \n # 00053 = Autorisation + Débit sur un abonné, \n # 00054 = Crédit sur un abonné, \n # 00055 = Annulation d’une opération sur un abonné, \n # 00056 = Inscription nouvel abonné, \n # 00057 = Modification abonné existant, \n # 00058 = Suppression abonné \n # 00061 = Transaction sans demande d’autorisation (forçage).\n\n # You can use these three card numbers for tests\n # with any cvv2 3 digits number and any expiration date > this month\n # 1111222233334444\n # 4975660000000004\n # 4970100000025102\n \n ######## Place YOUR own production parameters here\n # These are actually the test plateform/account parameters\n # You can use them safely while you test your app\n url = URI.parse(\"https://preprod-ppps.paybox.com\")\n site = '1999888'\n rang = '99'\n cle = \"1999888I\"\n \n # These params shouldn't change...\n http = Net::HTTP.new(url.host, 443)\n http.use_ssl = true\n #http.verify_mode = OpenSSL::SSL::VERIFY_NONE \n path = '/PPPS.php'\n ##############\n \n # Collect datas in a big hash \n this_date = Time.now\n\n datas = {\n :DATEQ=>this_date.strftime('%d%m%Y%H%M%S'),\n :TYPE=>this_transaction[:operation],\n :NUMQUESTION=>this_date.to_i,\n :MONTANT=>this_transaction[:amount],\n :SITE=>site,\n :RANG=>rang,\n :REFERENCE=>\"test\",\n :REFABONNE=>this_transaction[:user_id],\n :VERSION=>'00104',\n :CLE=>cle,\n :IDENTIFIANT=>'',\n :DEVISE=>\"978\",\n :PORTEUR=>this_transaction[:card_nbr],\n :DATEVAL=>this_transaction[:expire],\n :CVV=>this_transaction[:cvv2],\n :ACTIVITE=>\"024\",\n :ARCHIVAGE=>\"Simplissime\",\n :DIFFERE=>\"000\", \n :NUMAPPEL=>\"\",\n :NUMTRANS=>this_transaction[:numtrans],\n :AUTORISATION=>\"\" \n #:PAYS=>\"FR\"\n }\n\n # Format request\n headers = {'Content-Type' => 'application/x-www-form-urlencoded'}\n \n formated_datas = ''\n datas.each do |key,value|\n formated_datas == '' ? true : formated_datas << \"&\"\n formated_datas << \"#{key}=#{CGI::escape(value.to_s)}\"\n end\n\n # POST request via Net:HTTP over ssl\n begin\n response, data = http.post(path, formated_datas, headers)\n rescue\n # Third party server or transfert error \n return nil\n end\n \n # Now we've got a response, let's parse it \n response.body.split('&').each do |parameter|\n key = parameter.split('=').first\n value = Iconv.conv('utf-8', 'ISO-8859-1', parameter.split('=').last)\n \n case key\n ###############################################\n # All Paybox response parameters available\n when 'NUMTRANS'\n #Numéro de la transaction créée (int (10))\n @numtrans = value \n \n when 'NUMAPPEL'\n # Numéro de la requête gérée sur Paybox (int (10))\n @numappel = value \n \n when 'NUMQUESTION'\n # Identifiant unique et sequentiel (un timestamp sur 10 chiffres )\n @numquestion = value \n \n when 'SITE'\n # Numéro d'adhérent fourni par la banque (int (7))\n @site = value \n \n when 'RANG'\n # Numéro de rang fourni par la banque du commerçant (int (2))\n @rang = value \n \n when 'IDENTIFIANT'\n # Champ vide (int (10))\n @identifiant = value \n \n when 'AUTORISATION'\n # Numéro d'autorisation délivré par le centre d'autorisation de la banque du commerçant si le paiement est accepté (varchar (10))\n @autorisation = value \n \n when 'CODEREPONSE'\n # Code réponse concernant l'état de la réponse traité, opération acceptée ou refusée (varchar (10))\n @codereponse = value \n \n when 'REFABONNE'\n # Numéro d'abonné (user) contenu dans la trame question (varchar (250))\n @refabonne = value \n \n when 'PORTEUR'\n # Numéro porteur partiel (n° carte crypté), Identique à la trame question (varchar (19))\n @porteur = value \n \n when 'COMMENTAIRE'\n # Messages divers pour information (varchar(100))\n @commentaire = value \n \n when 'PAYS'\n # Code Pays du porteur de la carte (format ISO 3166)\n @pays = value \n \n when 'TYPECARTE'\n # Type de carte utilisé (varchar(10))\n @typecart = value \n \n when 'SHA-1'\n # Empreinte SHA-1 de la carte utilisée\n @sha1 = value \n \n when 'STATUS'\n # Etat de la transaction, retourné uniquement avec une question type 17 (=consultation) (varchar (16)) \n @status = value \n \n when 'REMISE'\n # Identifiant Paybox de la remise collectée (uniquement en consultation type 17), (int (9))\n @remise = value \n end\n end\n\n end", "def fetch_and_validate_models\n @client = Client.get_from_memcache(@client_id)\n\n @user_kyc_comparison_detail = UserKycComparisonDetail.using_client_shard(client: @client).\n where(user_extended_detail_id: @user_extended_detail_id).first\n\n if @user_kyc_comparison_detail.blank?\n ApplicationMailer.notify(\n body: 'user kyc comparison details not available',\n data: {user_extended_detail_id: @user_extended_detail_id},\n subject: 'user_kyc_comparison_details issue'\n ).deliver\n return false\n end\n\n return false if @user_kyc_comparison_detail.image_processing_status !=\n GlobalConstant::ImageProcessing.processed_image_process_status\n\n @user_kyc_detail = UserKycDetail.using_client_shard(client: @client).\n where(client_id: @user_kyc_comparison_detail.client_id,\n user_extended_detail_id: @user_kyc_comparison_detail.user_extended_detail_id,\n status: GlobalConstant::UserKycDetail.active_status).first\n\n return false if @user_kyc_detail.blank? || @user_kyc_detail.has_been_auto_approved?\n\n @client_kyc_pass_setting = ClientKycPassSetting.get_active_setting_from_memcache(@user_kyc_detail.client_id)\n\n @client_token_sale_detail = ClientTokenSaleDetail.get_from_memcache(@user_kyc_detail.client_id)\n @user_extended_detail = UserExtendedDetail.using_client_shard(client: @client).where(id: @user_extended_detail_id).first\n\n true\n end", "def verify_exchange( stock_ticker_symbol_1, shares_1, stock_ticker_symbol_2, shares_2 )\n\tresult = false\n\t#BEGIN_STUDENT\n\tif shares_1.to_i <= 0 || shares_2.to_i <= 0\n\t\treturn result\n\tend\n\tif !STOCKS.has_key?(stock_ticker_symbol_1) && !STOCKS.has_key?(stock_ticker_symbol_2)\n\t\treturn false\n end\n\tif market_value(stock_ticker_symbol_1, shares_1) < market_value(stock_ticker_symbol_2,shares_2)\n\t\tresult = false\n else\n\t\tresult = true\n end\n\n\n\t#END_STUDENT\n\n\treturn result\nend", "def ver_ledger()\n get_chain()\n Verify.chain($blockchain)\nend", "def run\n SoopaStore.checkout.cashier = @cashier\n @cashier.checkout = SoopaStore.checkout\n SoopaStore.cashiers.add @cashier\n puts \"Time #{SoopaStore.current_time} : Cashier #{@cashier.eid} arrives & starts work\"\n end", "def execute_transaction\n if valid?\n self.sender.balance -= self.amount\n self.receiver.balance += self.amount\n self.status = 'complete'\n elsif !valid?\n self.status = 'rejected'\n return \"Transaction rejected. Please check your account balance.\"\n end\n end", "def perform\n\n r = validate\n return r unless r.success?\n\n fetch_balances\n\n end", "def get_contract(*params); raise('Stub or mock required.') end", "def check_update_forclient(nomeprog, ver_prog)\n @log.debug(\"Controller: check_update_forclient\")\n net_prot_ver = [SUPP_SERV_VER_MAJ, SUPP_SERV_VER_MIN ]\n info_client = [nomeprog, ver_prog, net_prot_ver ]\n msg_details = YAML.dump(info_client)\n @log.debug \"update_req: #{info_client}\"\n cmd_to_send = build_cmd(:update_req, msg_details)\n send_data_to_server(cmd_to_send)\n @cup_gui.log_sometext(\"UPDATE: controlla se esiste una nuova versione\\n\")\n end", "def compare(a, b)\n #YOUR WORK HERE\n end", "def exec_orders(lower, higher)\n\n # get the target price\n\n target = get_target\n\n unless target\n return \"program exited\"\n end\n\n #set the order hash\n order = {\n \"account\" => @account,\n \"venue\" => @venue,\n \"symbol\" => @stock,\n \"price\" => target,\n \"direction\" => \"buy\",\n \"orderType\" => \"limit\"\n }\n\n\n # place orders until the target quantity is reached\n while (quantity ||= 1) < 100000\n\n # generate a random quantity for the order\n order[\"qty\"] = rand(lower..higher)\n\n #execute the order\n response = HTTParty.post(\"#{@@base_url}/venues/#{@venue}/stocks/#{@stock}/orders\",\n :body => JSON.dump(order),\n :headers => {\"X-Starfighter-Authorization\" => @apikey}\n )\n\n # check that the order has been submited correctly\n case response.code\n\n # order has been placed\n when 200\n\n\n # get the status of the order\n id = response.parsed_response[\"id\"]\n\n response = HTTParty.get(\"#{@@base_url}/venues/#{@venue}/stocks/#{@stock}/orders/#{id}\",\n :headers => {\"X-Starfighter-Authorization\" => @apikey})\n\n status = response.parsed_response[\"open\"]\n\n # check the status of the order 3 times, if it's still open after 3 times\n # close the order and accept the partial fill\n while status\n\n count ||= 0\n\n response = HTTParty.get(\"#{@@base_url}/venues/#{@venue}/stocks/#{@stock}/orders/#{id}\",\n :headers => {\"X-Starfighter-Authorization\" => @apikey})\n\n status = response.parsed_response[\"open\"]\n\n puts \"The order #{id} is still open\"\n\n count += 1\n #order has been checked 3 times\n if count.equal?(3)\n # close the order\n response = HTTParty.delete(\"#{@@base_url}/venues/#{@venue}/stocks/#{@stock}/orders/#{id}\",\n :headers => {\"X-Starfighter-Authorization\" => @apikey})\n\n count = 0\n\n break\n\n end\n\n end\n\n puts \"The order #{id} is closed\"\n\n #update the quantity\n quantity += response.parsed_response[\"totalFilled\"].to_i\n\n puts \"Total quantity: #{quantity}\"\n\n\n\n\n # Order has not been placed\n else\n\n puts response\n\n end\n\n end\n\n puts \"#{quantity} stocks has been ordered\"\n\n end", "def execute_transaction\n if self.valid? == true && status != \"complete\"\n self.receiver.balance += self.amount\n self.sender.balance -= self.amount\n self.status = \"complete\"\n else\n self.status = \"rejected\"\n return \"Transaction rejected. Please check your account balance.\"\n end\n end", "def compare_to_approach(*args)\n\n end", "def configure_contracts\n # configure accounts for eosdactokens\n\nend", "def check\n \n end", "def check\n \n end", "def verifyIdeasResponseContract\n return verifyResponseContract(@ideas_response_structure)\n end", "def testExactDifference\n initTestCase do\n $Context[:SlaveActions] = [\n [ 'DummyTool2', 'DummyAction', [] ]\n ]\n executeMaster( [ '--process', 'DummyProcess', '--user', 'DummyUser' ],\n :Repository => 'Dummy/MasterServerInstalledWithDummySenderFilterDummyTool',\n :AddRegressionProcesses => true,\n :AddRegressionSenders => true\n ) do |iError|\n assert_equal(nil, $Variables[:DummySenderCalls])\n assert_equal([], getSlaveClientQueue)\n end\n end\n end", "def acerto_cli\n \n #é obrigátorio informar o cliente\n if params[:client].blank? || params[:date1].blank? || params[:date2].blank?\n flash[:warning] = 'Você precisa selecionar o Cliente, informar o periodo e consultar para poder efetivar a baixa em seguida!'\n redirect_to receipts_path and return\n end\n \n #verifica se foi selecionado contas já RECEBIDAS, se sim, não faz o acerto pra não mexer em baixas já feitas\n if params[:tipo_consulta] == 'RECEBIDA' || params[:tipo_consulta].blank?\n flash[:warning] = 'Você não pode fazer acerto de cliente sem marcar a opção CONTAS Á RECEBER, verifique os dados!'\n redirect_to receipts_path and return\n end\n \n check_receipt = Invoice.where(client_id: params[:client]).where(status: 'Á RECEBER').where('created_at::Date Between ? and ?', params[:date1],params[:date2]).count\n if check_receipt >= 1\n #atualizo para RECEBIDA todas as entradas com base no periodo informado\n Invoice.where(client_id: params[:client]).where(status: 'Á RECEBER').where('created_at::Date Between ? and ?', params[:date1],params[:date2]).update_all(status: 'RECEBIDA') \n #atualizando todas as contas a receber do cliente informado e no periodo informado\n Receipt.where(client_id: params[:client]).where(status: 'Á RECEBER').where('created_at::Date Between ? and ?', params[:date1],params[:date2]).update_all(status: 'RECEBIDA', receipt_date: Date.today) \n \n flash[:success] = 'Acerto realizado com sucesso!'\n redirect_to receipts_path and return\n else\n flash[:warning] = 'Não existem dados para serem baixados!'\n redirect_to receipts_path and return \n end \n \n end", "def perform\n\n r = validate_and_sanitize\n return r unless r.success?\n\n r = update_in_mysql\n return r unless r.success?\n\n r = update_in_saas\n return r unless r.success?\n\n success_with_data(\n client_token: @client_token,\n client_token_planner: @client_token_planner\n )\n\n end", "def agreed_to_contract?\n if current_user.class.to_s.eql? \"AssetUser\"\n stage = Stage.find(params[:id])\n stage_user = StageUser.find(:first, :conditions => [\"stage_id = ? AND asset_user_id = ?\", stage.id, current_user.id])\n if stage_user.has_agreed_to_contract == false\n if stage.contract\n redirect_to contract_asset_manager_stage_path(stage)\n end\n end\n end\n end", "def perform(params)\n init_params(params)\n\n r = fetch_ethereum_address\n if !r.success?\n notify_errors(\"Ethereum address is invalid.\", r)\n update_edit_kyc_request(GlobalConstant::EditKycRequest.failed_status, r.to_json)\n return\n end\n\n r = validate_whitelisting_process\n if !r.success?\n notify_errors(r.error_display_text)\n update_edit_kyc_request(GlobalConstant::EditKycRequest.failed_status, r.to_json)\n return\n end\n\n r = send_unwhitelist_request\n if !r.success?\n notify_errors(\"Failed while sending unwhitelist request.\", r)\n update_edit_kyc_request(GlobalConstant::EditKycRequest.failed_status, r.to_json)\n return\n end\n\n # Mark Edit Kyc Request as unWhitelist in process\n update_edit_kyc_request(GlobalConstant::EditKycRequest.unwhitelist_in_process_status)\n\n end", "def perform_changes\n Token.where(stake_currency_id: @pax_stake_currency_id).find_in_batches(batch_size: 100) do |token_batches|\n @client_ids_array = []\n token_batches.each do |token|\n unless token['client_id'].present?\n fail 'invalid client id'\n end\n current_client_id = token['client_id']\n @client_ids_array.push(current_client_id)\n debug_data = {\"disassociation_reason\": \"Removing all economies whose stake currency is PAX\"}\n Token.where(client_id: current_client_id).update_all(client_id_was: current_client_id, client_id: nil, debug: debug_data.to_json)\n Workflow.where(client_id: current_client_id, kind: GlobalConstant::Workflow.token_deploy).update_all(unique_hash: nil)\n end\n\n change_client_related_flags\n KitSaasSharedCacheManagement::TokenDetails.new(@client_ids_array).clear\n CacheManagement::WorkflowByClient.new(@client_ids_array).clear\n end\n end", "def perform\n centry_ids_prices.each do |product|\n if product[0].present? && product[1].present?\n resp = centry.put(\"/conexion/v1/products/#{product[0]}.json\", {}, {\"price_compare\": product[1]})\n if (resp.code == \"200\")\n centry_product_info = JSON.parse(resp.body)\n ::Product.where(id_product_centry: centry_product_info[\"_id\"]).each do |local_product|\n local_product[:last_price_reported_centry] = centry_product_info[\"price_compare\"]\n local_product.save!\n end\n end\n end\n end\n end", "def transactions\n\n @response = CompanyApi::Request::Economy.new(\n CompanyApi::Response::Formatter::Economy,\n request.cookies,\n {\"User-Agent\" => http_user_agent}\n ).fetch_transaction_kinds_details\n\n # Check if error present or not?\n unless @response.success?\n render_error_response(@response)\n return\n end\n\n @presenter_obj = ::WebPresenter::Economy::TransactionKind.new(@response, params)\n unless @presenter_obj.client_token.step_three_done?\n redirect_to :planner, status: GlobalConstant::ErrorCode.temporary_redirect\n return\n end\n\n end", "def process entity\n return entity unless contract?\n\n success, errors = contract.match(entity)\n\n result.errors[entity_name] = errors unless success\n\n entity\n end", "def testExactDifference2Actions\n initTestCase do\n $Context[:SlaveActions] = [\n [ 'DummyTool2', 'DummyAction', [] ],\n [ 'DummyTool2', 'DummyAction2', [] ]\n ]\n executeMaster( [ '--process', 'DummyProcess', '--user', 'DummyUser' ],\n :Repository => 'Dummy/MasterServerInstalledWithDummySenderFilterDummyTool',\n :AddRegressionProcesses => true,\n :AddRegressionSenders => true\n ) do |iError|\n assert_equal(nil, $Variables[:DummySenderCalls])\n assert_equal([], getSlaveClientQueue)\n end\n end\n end", "def act_on_ok\n if body['message'] == 'Approval successful.'\n output(\n event: 'success',\n message: message_text,\n uuid: body['uuid'],\n accession: payloads.first[:output][:accession]\n )\n else\n Rails.logger.error(\"Approve transfer Job failed with: #{message_text}\")\n output(event: 'failed', message: message_text)\n fail!\n end\n end", "def confirm_acceptance\n return render(:template => 'shared/access_denied', :status => :unauthorized) unless current_user?(@user)\n @short_listed_winner = current_user.short_listed_winnings.find(params[:id])\n if @short_listed_winner.pending?\n if request.get?\n @dispatch = Dispatch.new(current_user.attributes().delete_if{|k,v| ![:address_line_1, :address_line_2, :city, :state, :country, :pin_code, :mobile_number, :phone_number].include?(k.to_sym)})\n @dispatch.prize = @short_listed_winner.prize\n else\n begin\n Dispatch.transaction do |transaction|\n @dispatch = Dispatch.new(params[:dispatch])\n @dispatch.user_id = current_user.id\n @dispatch.country = current_user.country\n @dispatch.prize_id = @short_listed_winner.prize.id\n @dispatch.short_listed_winner_id = params[:id]\n if !@dispatch.prize.needs_dd?\n @dispatch.status = Dispatch::STATUSES[:pending_shipment]\n @dispatch.payment_type = 'N/A'\n end \n @dispatch.save!\n\n @short_listed_winner.accepted = true\n @short_listed_winner.confirmed_on = Time.now\n @short_listed_winner.save!\n \n if @dispatch.prize.needs_dd?\n flash[:notice] = 'Your prize will be dispatched within 30 working days after we receive your DD.'\n else\n flash[:notice] = 'Your prize will be dispatched within 30 working days.'\n end \n PrizeMailer.deliver_prize_confirmed_notification(@dispatch, self)\n return redirect_to(:action => :pending_prizes)\n end\n\t rescue Exception => err\n #logger.error(err.to_s)\n end #begin\n end #get?\n else\n case @short_listed_winner.status\n when 'Accepted' then flash.now[:notice] = 'You have already accepted this prize.'\n when 'Rejected' then flash.now[:notice] = 'You have rejected this prize.'\n when 'Expired' then flash.now[:notice] = 'Oops! Looks like you’re a little late. The confirmation period for your prize claim has expired. But you can still play more contests to WIN more amazing prizes.'\n end\n end # pending?\n render :layout => 'users'\n end", "def verifyPostIdeaResponseContract\n return verifyResponseContract(@postIdea_response_structure)\n end", "def test_purchase_and_credit_for_check_with_differing_amounts\n assert purchase = @gateway.purchase(10000, @check, @options)\n assert_success purchase\n assert_approved purchase\n \n assert void = @gateway.credit(500, purchase.authorization, @options)\n assert_success void\n assert_not_equal 'Approved', void.message\n end", "def check_for_duplicate_ethereum\n # Check for duplicate Ethereum address\n hashed_db_ethereurm_address = Md5UserExtendedDetail.using_client_shard(client: @client).\n get_hashed_value(@new_ethereum_address)\n\n # check if same ethereum address\n return error_with_data(\n 'am_k_uea_cfde_1',\n \"This Ethereum address already exists for the case.Please provide a different ethereum address\",\n \"This Ethereum address already exists for the case.Please provide a different ethereum address\",\n GlobalConstant::ErrorAction.default,\n {}\n ) if md5_user_extended_detail.ethereum_address == hashed_db_ethereurm_address\n\n user_extended_detail_ids = Md5UserExtendedDetail.using_client_shard(client: @client).\n where(ethereum_address: hashed_db_ethereurm_address).pluck(:user_extended_detail_id)\n\n # Ethereum address is already present\n if user_extended_detail_ids.present?\n # Check whether duplicate address kyc is already approved\n already_approved_cases = []\n UserKycDetail.using_client_shard(client: @client).\n active_kyc.where(client_id: @client_id, user_extended_detail_id: user_extended_detail_ids).each do |ukd|\n if GlobalConstant::UserKycDetail.admin_approved_statuses.include?(ukd.admin_status)\n already_approved_cases << ukd.id if (ukd.id != @user_kyc_detail.id)\n end\n end\n return error_with_data(\n 'am_k_uea_5',\n \"Duplicate Ethereum address cases has already been approved, Case Ids #{already_approved_cases}\",\n \"Duplicate Ethereum address cases has already been approved, Case Ids #{already_approved_cases}\",\n GlobalConstant::ErrorAction.default,\n {}\n ) if already_approved_cases.present?\n end\n\n success\n\n end", "def run\n success = false\n\n scan_class = TableScanHelper.scan_class(session)\n scan = scan_class.new(session, left_table, right_table)\n scan.progress_printer = progress_printer\n\n self.helper = SyncHelper.new(self)\n syncer = Syncers.configured_syncer(sync_options).new(helper)\n \n execute_sync_hook :before_table_sync\n self.helper.log_table_sync_started(left_table)\n\n scan.run do |type, row|\n yield type, row if block_given? # To enable progress reporting\n unless event_filtered?(type, row)\n syncer.sync_difference type, row\n end\n end\n\n self.helper.log_table_sync_complete(left_table)\n execute_sync_hook :after_table_sync\n\n success = true # considered to be successful if we get till here\n ensure\n helper.finalize success if helper\n end", "def test_guest_pays_entry_charge\n @guest1.spent_money(@room1)\n assert_equal(95, @guest1.wallet)\n end", "def execute\n if activemerchant_credit_card.nil?\n # Client created by admin\n create_subscription\n user.update_attribute :card_access, User.card_access.find_value(:forbidden).value\n subscription.update_attribute :start_at, Date.today if subscription.present?\n UserMailer.welcome(user.id).deliver_later\n else\n # Subscription by Client.\n process_payment_workflow\n return false unless subscription.present? && user.persisted?\n finalize_user_subscription\n end\n end", "def configure_contracts\n # configure accounts for eosdactokens\n `cleos push action eosdactokens updateconfig '[\"daccustodian\"]' -p eosdactokens`\n `cleos push action eosdactokens create '{ \"issuer\": \"eosdactokens\", \"maximum_supply\": \"100000.0000 EOSDAC\", \"transfer_locked\": false}' -p eosdactokens`\n `cleos push action eosdactokens issue '{ \"to\": \"eosdactokens\", \"quantity\": \"78337.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p eosdactokens`\n `cleos push action eosio.token issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"100000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio`\n\n #create users\n # Ensure terms are registered in the token contract\n `cleos push action eosdactokens newmemterms '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\"}' -p eosdactokens`\n\n #create users\n seed_dac_account(\"sender1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"sender2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"sender3\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"sender4\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"receiver1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"arb1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"arb2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n\n `cleos push action eosio.token issue '{ \"to\": \"sender1\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio`\n `cleos push action eosio.token issue '{ \"to\": \"sender2\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio`\n `cleos push action eosio.token issue '{ \"to\": \"sender3\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio`\n `cleos push action eosio.token issue '{ \"to\": \"sender4\", \"quantity\": \"1000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio`\nend", "def compute(object)\n # eSedex presume contract\n raise 'eSedex MUST have a contract configured' unless has_contract?\n super(object)\n end", "def configure_contracts\n # configure accounts for eosdactokens\n `cleos push action eosdactokens updateconfig '[\"daccustodian\"]' -p eosdactokens`\n `cleos push action eosdactokens create '{ \"issuer\": \"eosdactokens\", \"maximum_supply\": \"100000.0000 EOSDAC\", \"transfer_locked\": false}' -p eosdactokens`\n `cleos push action eosdactokens issue '{ \"to\": \"eosdactokens\", \"quantity\": \"78337.0000 EOSDAC\", \"memo\": \"Initial amount of tokens for you.\"}' -p eosdactokens`\n `cleos push action eosio.token issue '{ \"to\": \"eosdacthedac\", \"quantity\": \"100000.0000 EOS\", \"memo\": \"Initial EOS amount.\"}' -p eosio.token`\n `cleos push action dacdirectory regdac '{\"owner\": \"dacdirectory\", \"dac_name\": \"dacproposals\", \"dac_symbol\": \"4,MYSYM\", \"title\": \"Dac Title\", \"refs\": [[1,\"some_ref\"]], \"accounts\": [[2,\"daccustodian\"], [5,\"dacescrow\"], [7,\"dacescrow\"], [0, \"dacauthority\"], [4, \"eosdactokens\"], [1, \"eosdacthedac\"] ], \"scopes\": [[2,\"daccustodian\"], [4, \"eosdactokens\"]]}' -p dacdirectory`\n \n #create users\n # Ensure terms are registered in the token contract\n `cleos push action eosdactokens newmemterms '{ \"terms\": \"normallegalterms\", \"hash\": \"New Latest terms\"}' -p eosdactokens`\n\n #create users\n seed_dac_account(\"proposeracc1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"proposeracc2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"arbitrator11\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n\n seed_dac_account(\"custodian1\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian2\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian3\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian4\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian5\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian11\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian12\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian13\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n seed_dac_account(\"custodian14\", issue: \"100.0000 EOSDAC\", memberreg: \"New Latest terms\")\n\n `cleos push action daccustodian updatecust '[[\"custodian1\", \"custodian2\", \"custodian3\", \"custodian4\", \"custodian5\", \"custodian11\", \"custodian12\", \"custodian13\", \"custodian14\"]]' -p proposeracc1`\n\n `cleos set account permission dacauthority one '{\"threshold\": 1,\"keys\": [],\"accounts\": [{\"permission\":{\"actor\":\"custodian1\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian11\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian12\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian13\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian2\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian3\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian4\",\"permission\":\"active\"},\"weight\":1}, {\"permission\":{\"actor\":\"custodian5\",\"permission\":\"active\"},\"weight\":1}]}' low -p dacauthority@low`\nend", "def update\n if @transaction.update(transaction_params)\n\n # implement all admin approved transactions here.\n if @transaction.kind == 'withdraw' and @transaction.status == 'approved' and @transaction.processed == false\n account = Account.find(@transaction.account_id)\n if account.balance > @transaction.amount\n account.balance -= @transaction.amount\n account.save\n @transaction.eff_date = Time.current\n @transaction.processed = true\n @transaction.save\n user_to_mail = User.find(Account.find(@transaction.account_id).user_id)\n UserMailer.transaction_email(user_to_mail, @transaction).deliver_later\n end\n elsif @transaction.kind == 'deposit' and @transaction.status == 'approved' and @transaction.processed == false\n account = Account.find(@transaction.account_id)\n account.balance += @transaction.amount\n account.save\n @transaction.eff_date = Time.current\n @transaction.processed = true\n @transaction.save\n user_to_mail = User.find(Account.find(@transaction.account_id).user_id)\n UserMailer.transaction_email(user_to_mail, @transaction).deliver_later\n elsif @transaction.kind == 'borrow' and @transaction.status == 'approved' and @transaction.processed == false\n account1 = Account.find(@transaction.from)\n account2 = Account.find(@transaction.to)\n if account1.balance > @transaction.amount\n account1.balance -= @transaction.amount\n account2.balance += @transaction.amount\n account1.save\n account2.save\n @transaction.start_date = Time.current\n @transaction.eff_date = Time.current\n @transaction.status = 'approved'\n @transaction.processed = true\n @transaction.account_id = account1.id\n @transaction.save\n sender = User.find(Account.find(@transaction.from).user_id)\n recipient = User.find(Account.find(@transaction.to).user_id)\n UserMailer.transaction_email(sender, @transaction).deliver_later\n UserMailer.transaction_email(recipient, @transaction).deliver_later\n end\n end\n\n redirect_to @transaction, notice: 'Transaction was successfully updated.', id: @transaction.id\n else\n render :edit\n end\n end", "def capture_and_cash\n if self.active? && self.pending_purchase_order && self.accepted_receiver\n\n # start transaction\n ActiveRecord::Base.transaction do\n capture = self.pending_purchase_order.capture\n if capture.success?\n \n sales_order = self.accepted_receiver.sell_to(self.sender, self.accepted_receiver.cart.cart_line_item(self))\n cash = sales_order.cash(self.accepted_receiver.piggy_bank)\n \n if cash.success?\n self.pending_purchase_order.update_origin_address_from(self.accepted_receiver)\n \n service_fee_product = Product.service_fee(:country_code => self.accepted_receiver.default_country)\n \n if service_fee_product\n reward_item = self.accepted_receiver.cart.add(self)\n service_fee_item = self.accepted_receiver.cart.add(service_fee_product, 1, :dependent => reward_item)\n \n purchase_order = self.accepted_receiver.purchase(service_fee_item,\n :seller => Organization.probono)\n charge = purchase_order.pay(self.accepted_receiver.piggy_bank)\n \n if charge.success?\n probono = Organization.probono\n\n if probono\n\n probono_sales_order = probono.sell_to(self.accepted_receiver, service_fee_item)\n probono_cash = probono_sales_order.cash(probono.piggy_bank)\n\n if probono_cash.success?\n # congrats, we are done!\n return true\n else\n logger.error \"Error cashing service fee sales order {#{probono_sales_order.id}} \" +\n \"for reward {#{self.id}} kase {#{self.kase.id}}\\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n \n else\n logger.error \"Error probono organization not found for reward {#{self.id}} kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n\n else\n logger.error \"Error when charging service fee to partner on order \" + \n \"##{purchase_order.number} for kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n else\n logger.error \"Error could not find service fee for accepted_receiver {#{self.accepted_receiver.id}}, \" + \n \"country code \\\"#{self.accepted_receiver.default_country}\\\" for kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n \n else\n logger.error \"Error when cashing sales order {#{sales_order.id}} #{sales_order.number} for kase {#{self.kase.id}}\\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n \n else\n logger.error \"Error when capturing pending order {#{self.pending_purchase_order.id}} #{self.pending_purchase_order.number} for kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n end\n end\n false\n end", "def execute\n @checkup = {}\n\n case @publisher\n when 'sql'\n begin\n @d = I2X::SQLDetector.new(self)\n rescue Exception => e\n @response = {:status => 400, :error => e}\n I2X::Config.log.error(self.class.name) {\"#{e}\"}\n end\n when 'csv'\n begin\n @d = I2X::CSVDetector.new(self)\n rescue Exception => e\n @response = {:status => 400, :error => e}\n I2X::Config.log.error(self.class.name) {\"#{e}\"}\n end\n when 'xml'\n begin\n @d = I2X::XMLDetector.new(self)\n rescue Exception => e\n @response = {:status => 400, :error => e}\n I2X::Config.log.error(self.class.name) {\"#{e}\"}\n end\n when 'json'\n begin\n @d = I2X::JSONDetector.new(self)\n rescue Exception => e\n @response = {:status => 400, :error => e}\n I2X::Config.log.error(self.class.name) {\"#{e}\"}\n end\n end\n\n\n # Start checkup\n begin\n unless content.nil? then\n @d.content = content\n end\n @checkup = @d.checkup\n rescue Exception => e\n I2X::Config.log.error(self.class.name) {\"Checkup error: #{e}\"}\n end\n\n # Start detection\n begin\n @d.objects.each do |object|\n @d.detect object\n end\n\n @checkup[:templates] = @d.templates.uniq\n rescue Exception => e\n I2X::Config.log.error(self.class.name) {\"Detection error: #{e}\"}\n end\n\n begin\n if @checkup[:status] == 100 then\n process @checkup\n end\n rescue Exception => e\n I2X::Config.log.error(self.class.name) {\"Process error: #{e}\"}\n end\n response = {:status => @checkup[:status], :message => \"[i2x][Checkup][execute] All OK.\"} \n end", "def set_contract\n @contract = Contract.find_by(resource_id: contract_params[:resource_id])\n # @contract = Contract.find(params[:id])\n end", "def check_for_franchise\n if self.is_franchised\n player = Player.find(self.player_id)\n length = self.contract_length\n position = player.position\n averaged_player_salary = 0\n final_salary = 0\n this_salary = 0\n contracted_team_id = self.subcontracts.last.team_id\n top_5_players_of_position = Player.where(\"position = ?\", player.position).sort_by { |player| player.auction_value }.reverse.first(5)\n\n top_5_players_of_position.each do |top_player|\n if top_player.is_contracted?\n this_salary = top_player.this_year.salary_amount\n else\n this_salary = top_player.auction_value\n end\n averaged_player_salary += this_salary\n end\n averaged_player_salary /= 5\n\n salary_progression = SalaryProgression.find_by_auction_value(player.auction_value).attributes.to_a\n\n\n if player.this_year.contract.is_extended\n salary = salary_progression[(length + 2)][1]\n else\n salary = salary_progression[(length + 1)][1] \n end \n if averaged_player_salary >= salary\n final_salary = averaged_player_salary\n else\n final_salary = salary\n end \n\n # create the Subcontract\n sub = Subcontract.new\n if self.is_extended\n sub.contract_year = contract_start_year + length + 1\n else\n sub.contract_year = contract_start_year + length\n end\n sub.salary_amount = final_salary\n sub.contract_id = self.id\n sub.team_id = contracted_team_id\n sub.this_is_a_franchise_tag = true\n sub.save! \n\n # update GM's annual actions to not allow more franchise tags\n actions = AnnualGmAction.find_by_team_id_and_year(contracted_team_id, current_year)\n actions.has_franchised = true\n actions.franchised_player_id = self.player.id\n actions.save!\n end\n end", "def propogate_change(action, params)\n return unless @calendar_network.remote_nodes\n @calendar_network.remote_nodes.each do |remote_node|\n print \"Excuting the change(s) in (#{remote_node.address}, #{remote_node.port})... \"\n remote_server = xml_rpc_client(remote_node.address, @calendar_network.config[\"path\"], remote_node.port)\n if remote_server.call(\"appointment.#{action}\", params)\n puts \" done!\"\n else\n puts \" could not be done!\"\n end\n end\n true\n end", "def testExactMatch1Of2\n initTestCase do\n $Context[:SlaveActions] = [\n [ 'DummyTool', 'DummyAction', [] ],\n [ 'DummyTool2', 'DummyAction2', [] ]\n ]\n executeMaster( [ '--process', 'DummyProcess', '--user', 'DummyUser' ],\n :Repository => 'Dummy/MasterServerInstalledWithDummySenderFilterDummyTool',\n :AddRegressionProcesses => true,\n :AddRegressionSenders => true\n ) do |iError|\n assert_equal( [\n [ 'sendMessage', [ 'DummyUser', {\n 'DummyTool' => {\n 'DummyAction' => [\n []\n ]\n }\n } ]\n ]\n ],\n $Variables[:DummySenderCalls]\n )\n assert_equal([], getSlaveClientQueue)\n end\n end\n end" ]
[ "0.5922322", "0.5922322", "0.58432645", "0.56738245", "0.5638366", "0.5567748", "0.55164385", "0.5511663", "0.5450405", "0.5410191", "0.5304728", "0.52622634", "0.5238766", "0.5228185", "0.51697916", "0.51577604", "0.51554716", "0.5134517", "0.5097427", "0.50964075", "0.5093484", "0.5083534", "0.5083104", "0.5072784", "0.5061572", "0.5060496", "0.50559133", "0.50483286", "0.5029153", "0.5010809", "0.4994054", "0.49729735", "0.49727842", "0.4970612", "0.49700806", "0.49612555", "0.4956859", "0.49536797", "0.49501386", "0.4950039", "0.49452198", "0.49430427", "0.49415308", "0.49389067", "0.49388486", "0.49336144", "0.49333888", "0.4921902", "0.49056906", "0.4894992", "0.4894005", "0.48807576", "0.48795056", "0.48776653", "0.48766172", "0.4875592", "0.4873812", "0.48706856", "0.48675123", "0.48657507", "0.48573175", "0.48526278", "0.4852545", "0.48521042", "0.48440656", "0.48422262", "0.48386595", "0.48375076", "0.48346516", "0.48275736", "0.48233533", "0.48233533", "0.48165205", "0.48142707", "0.48087987", "0.48071176", "0.47958347", "0.4793368", "0.4787601", "0.4785967", "0.47834837", "0.47804177", "0.47775748", "0.4768124", "0.47666258", "0.47625148", "0.47619194", "0.47614425", "0.47603667", "0.4760164", "0.47569227", "0.47564924", "0.47556067", "0.4753089", "0.47525036", "0.47470576", "0.47415766", "0.473434", "0.47324342", "0.47297025", "0.47275072" ]
0.0
-1
This method create all the join table given by the filter and the saving associated with each
def create_join_table_gas(filter, all_savings) filter.each_with_index do |contract, index| JoinTableGasSimulationContract.create(gas_simulation: self, gas_contract: contract, savings: all_savings[index]) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_table_joins(klass)\n if join_tables = klass.ann(:self, :join_tables)\n for info in join_tables\n begin\n # UGGLY hack!\n key_type = klass.ann(:oid, :sql).split(\" \").first\n create_join_table_sql(info, key_type).each do |sql|\n exec(sql, false)\n end\n debug \"Created join table '#{info[:table]}'.\" if $DBG\n rescue Object => ex\n if table_already_exists_exception? ex\n debug \"Join table already exists\" if $DBG\n else\n raise\n end\n end\n end\n end\n end", "def create_join_table_ele(filter, all_savings)\n filter.each_with_index do |contract, index|\n JoinTableEleSimulationContract.create(ele_simulation: self, ele_contract: contract, savings: all_savings[index])\n end\n end", "def join_writer\n \"@join_table.create(@source.id,@destination.id)\"\n end", "def create_join_excluded_tbl(preserve_null_pk = true)\n if @excluded_join_tbl.nil?\n join_list =join_list()\n cross_join_from = ''\n full_join_from = ''\n satisfied_tbl = create_satisfied_tbl()\n 0.upto(join_list.count-1) do |i|\n join = join_list.find{|j| j['id'] ==i }\n l_rel_list = join['l_rel_list']\n quals = join['quals']\n q = ReverseParseTree.whereClauseConst(quals)\n has_quals = (not join['quals'].nil?)\n join_type = ReverseParseTree.joinTypeConvert(join['jointype'].to_s, has_quals)\n\n r_rel = join['r_rel_list'][0]\n l_arg = (i==0 ? \"#{l_rel_list[0].relname} #{l_rel_list[0].relalias}\" : \"\")\n # for efficiency only change the last join to cross join\n if i == join_list.count-1\n cross_join_from = cross_join_from + \"#{l_arg} CROSS JOIN #{r_rel.relname} #{r_rel.relalias} \"\n else\n cross_join_from = cross_join_from + \"#{l_arg} #{join_type} #{r_rel.relname} #{r_rel.relalias} on #{q} \"\n end\n # full_join_from = full_join_from + \"#{l_arg} CROSS JOIN #{r_rel.relname} #{r_rel.relalias} on #{q}\"\n end\n @excluded_join_tbl = \"#{@table}_join_excluded\"\n # renamed_pk_col = @pk_full_list.map { |pk| \"#{pk['col']} as #{pk['alias']}_pk\" }.join(', ')\n \n if preserve_null_pk\n renamed_pk_col = @pk_full_list.map { |pk| \"#{pk['col']} as #{pk['alias']}_pk\" }.join(', ')\n else\n renamed_pk_col = @pk_full_list.map do |pk|\n pkcol = @all_cols.find{|col| col.colname == pk['colname'] and col.relname==pk['relname']}\n \"COALESCE(#{pkcol.select_name},#{pkcol.null_replacement}) as #{pkcol.colalias}_pk\"\n end.join(',')\n end\n targetListReplacement = \"#{renamed_pk_col},#{@all_cols_select}\"\n query = ReverseParseTree.reverseAndreplace(@parseTree, targetListReplacement, '')\n old_from = from_query()\n # cross join\n all_cols_renamed()\n cross_join_query = query.gsub(/#{old_from}/i,cross_join_from)\n # pk_join_satisfied_tbl = @pk_full_list.map { |pk| \"t.#{pk['alias']}_pk = s.#{pk['alias']}_pk\" }.join(' AND ')\n # pk_not_in_satisfied_tbl = @pk_full_list.map { |pk| \"s.#{pk['alias']}_pk is null\" }.join(' OR ')\n\n create_tbl_query = \"select * from #{satisfied_tbl} where 1=2\"\n create_tbl_query = QueryBuilder.create_tbl(@excluded_join_tbl, '', create_tbl_query)\n DBConn.exec(create_tbl_query)\n # limit to 1000 rows due to resource limitation\n cross_join_query = \"with cross_join as (#{cross_join_query} limit 1000) INSERT INTO #{@excluded_join_tbl} select * from (select t.* from cross_join as t except select * from #{satisfied_tbl}) as tmp\"\n puts cross_join_query\n DBConn.exec(cross_join_query)\n\n # unless preserve_null_pk\n # pk = @pk_full_list.map { |pk| \"#{pk['alias']}_pk\" }.join(',')\n # DBConn.update_null_columns(@excluded_join_tbl,pk)\n # end\n # # full join\n # full_join_query = query.gsub(old_from,full_join_from)\n # full_join_query = \"(#{full_join_query} except select #{@all_cols_renamed} from #{satisfied_tbl})\"\n # full_join_query = \"INSERT INTO #{@excluded_tbl} #{full_join_query}\"\n # DBConn.exec(query)\n end\n return @excluded_join_tbl\n end", "def build_tables\n @db.exec(%q[\n CREATE TABLE IF NOT EXISTS breeds(\n id serial NOT NULL PRIMARY KEY,\n breed varchar(30),\n price integer\n )])\n\n @db.exec(%q[\n CREATE TABLE IF NOT EXISTS puppies(\n id serial NOT NULL PRIMARY KEY,\n breed varchar(30),\n name varchar(30),\n age integer,\n created_at timestamp NOT NULL DEFAULT current_timestamp\n )])\n\n @db.exec(%q[\n CREATE TABLE IF NOT EXISTS requests(\n id serial NOT NULL PRIMARY KEY,\n breed text,\n status text,\n created_at timestamp NOT NULL DEFAULT current_timestamp\n )])\n end", "def index\n @create_join_table_movie_countries = CreateJoinTableMovieCountry.all\n end", "def add_join_table( id_left, table_left, id_right, table_right, name = nil, &block )\n name ||= [ table_left, table_right ].sort.join( '_' )\n add_table name do\n foreign_key id_left, table_left\n foreign_key id_right, table_right\n primary_key [ id_left, id_right ]\n unique [ id_right, id_left ]\n instance_eval &block if block\n end\n end", "def create_many table\n table.map do |row|\n create_record row\n end\n end", "def habtm_to_fixture\n joins = self.reflect_on_all_associations.select do |j|\n j.macro == :has_and_belongs_to_many\n end\n joins.each do |join|\n hsh = {}\n connection.select_all(\"SELECT * FROM #{join.options[:join_table]}\").each_with_index do |record, i|\n hsh[\"join_#{'%05i' % i}\"] = record\n end\n write_file(File.expand_path(\"test/fixtures/#{join.options[:join_table]}.yml\", Rails.root), hsh.to_yaml(SortKeys: true))\n end\n end", "def createTables \n createUserTable\n createTaskTable\n createProjectTable\n end", "def join_builder table, fta_asset_class_id=nil\n case table\n when :track, :guideway, :power_signal, :capital_equipment, :service_vehicle\n klass = table.to_s.camelize.constantize\n when :bus, :rail_car, :ferry, :other_passenger_vehicle\n klass = RevenueVehicle\n when :passenger_facility, :maintenance_facility, :admin_facility, :parking_facility\n klass = Facility\n end\n\n # Special cases\n case table\n when :service_vehicle\n klass = klass.non_revenue\n when :capital_equipment\n # For some reason the asset_events join causes it to forget that it's transam_assetible so explicitly add\n klass = klass.joins(\"left outer join transam_assets on transam_assets.transam_assetible_id = transit_assets.id and transam_assets.transam_assetible_type = 'TransitAsset'\")\n end \n\n # Common to all assets\n disposition_event_type_id = ServiceStatusType.where(name: 'Disposed').limit(1).pluck(:id).first\n\n query = klass.joins('left join organizations on transam_assets.organization_id = organizations.id')\n .joins('left join asset_subtypes on transam_assets.asset_subtype_id = asset_subtypes.id')\n .joins(\"left join asset_events all_events on all_events.id = (select id from asset_events where asset_events.base_transam_asset_id = transam_assets.id order by event_date desc, updated_at desc, id desc limit 1)\")\n .joins('left join asset_event_types on all_events.asset_event_type_id = asset_event_types.id')\n .joins(\"left join asset_events condition_events on condition_events.id = (select max(id) from asset_events asset_events where asset_events.transam_asset_id = transam_assets.id and asset_events.transam_asset_type = 'TransamAsset' and asset_events.asset_event_type_id = #{ConditionUpdateEvent.asset_event_type.id})\")\n .joins('left join condition_types on condition_events.condition_type_id = condition_types.id')\n .joins(\"left join asset_events service_status_events on service_status_events.id = (select max(id) from asset_events asset_events where asset_events.base_transam_asset_id = transam_assets.id and asset_events.transam_asset_type = 'TransamAsset' and asset_events.asset_event_type_id = #{ServiceStatusUpdateEvent.asset_event_type.id})\")\n .joins(\"left join service_status_types on service_status_types.id = (case when transam_assets.disposition_date is not null then #{disposition_event_type_id} else service_status_events.service_status_type_id end)\")\n .joins(\"left join asset_events rebuild_rehab_events on rebuild_rehab_events.id = (select max(id) from asset_events asset_events where asset_events.base_transam_asset_id = transam_assets.id and asset_events.transam_asset_type = 'TransamAsset' and asset_events.asset_event_type_id = #{RehabilitationUpdateEvent.asset_event_type.id})\")\n\n \n # Major asset groups\n case table\n when :track, :guideway, :power_signal\n query = query.joins('left join fta_asset_classes on fta_asset_class_id = fta_asset_classes.id')\n .joins('left join infrastructure_divisions on infrastructure_division_id = infrastructure_divisions.id')\n .joins('left join infrastructure_subdivisions on infrastructure_subdivision_id = infrastructure_subdivisions.id')\n .joins('left join infrastructure_segment_types on infrastructure_segment_type_id = infrastructure_segment_types.id')\n when :service_vehicle, :bus, :rail_car, :ferry, :other_passenger_vehicle\n query = query.joins('left join fta_asset_classes on fta_asset_class_id = fta_asset_classes.id')\n .joins('left join manufacturers on transam_assets.manufacturer_id = manufacturers.id')\n .joins('left join manufacturer_models on transam_assets.manufacturer_model_id = manufacturer_models.id')\n .joins('left join fta_vehicle_types on fta_type_id = fta_vehicle_types.id')\n .joins('left join chasses on chassis_id = chasses.id')\n .joins('left join fuel_types on fuel_type_id = fuel_types.id')\n .joins('left join organizations as operators on operator_id = operators.id')\n .joins(\"left join asset_events mileage_events on mileage_events.id = (select max(id) from asset_events where asset_events.base_transam_asset_id = transam_assets.id and asset_events.transam_asset_type = 'ServiceVehicle' and asset_events.asset_event_type_id = #{MileageUpdateEvent.asset_event_type.id})\")\n .joins('left join transam_assets_model_names on transam_assets.transam_assetible_id=transam_assets_model_names.transam_asset_id')\n when :passenger_facility, :maintenance_facility, :admin_facility, :parking_facility\n query = query.joins('left join fta_equipment_types on fta_type_id = fta_equipment_types.id')\n\n end\n\n # Specific cases\n case table\n when :track\n query = query.joins('left join fta_track_types on fta_type_id = fta_track_types.id')\n .joins('left join infrastructure_tracks on infrastructure_track_id = infrastructure_tracks.id')\n when :guideway\n query = query.joins('left join fta_guideway_types on fta_type_id = fta_guideway_types.id')\n when :power_signal\n query = query.joins('left join fta_power_signal_types on fta_type_id = fta_power_signal_types.id')\n .joins('left join infrastructure_tracks on infrastructure_track_id = infrastructure_tracks.id')\n when :capital_equipment\n query = query.joins('left join fta_asset_classes on fta_asset_class_id = fta_asset_classes.id')\n .joins('left join manufacturers on transam_assets.manufacturer_id = manufacturers.id')\n .joins('left join manufacturer_models on transam_assets.manufacturer_model_id = manufacturer_models.id')\n .joins('left join fta_equipment_types on fta_type_id = fta_equipment_types.id')\n .joins('left join transam_assets_model_names on transam_assets.transam_assetible_id=transam_assets_model_names.transam_asset_id')\n .where(transam_assetible_type: 'TransitAsset')\n when :bus, :rail_car, :ferry, :other_passenger_vehicle\n query = query.joins('left join esl_categories on esl_category_id = esl_categories.id')\n .joins('left join fta_funding_types on fta_funding_type_id = fta_funding_types.id')\n .joins('left join fta_ownership_types on fta_ownership_type_id = fta_ownership_types.id')\n .where(fta_asset_class_id: fta_asset_class_id)\n when :passenger_facility, :maintenance_facility, :admin_facility, :parking_facility\n query = query.joins('left join fta_equipment_types on fta_type_id = fta_equipment_types.id')\n .where(fta_asset_class_id: fta_asset_class_id)\n .where(transam_assetible_type: 'TransitAsset')\n end\n\n query.where(organization_id: @organization_list)\n end", "def create_all(name, table)\n table.hashes.map do |attributes|\n Utils.model(name).new(attributes).tap do |document|\n document.save\n end\n end\n end", "def fat_record_joins\n joins = \" LEFT JOIN active_sources AS obj_sources ON semantic_relations.object_id = obj_sources.id AND semantic_relations.object_type = 'TaliaCore::ActiveSource'\"\n joins << \" LEFT JOIN semantic_properties AS obj_props ON semantic_relations.object_id = obj_props.id AND semantic_relations.object_type = 'TaliaCore::SemanticProperty'\"\n joins << \" LEFT JOIN active_sources AS subject_sources ON semantic_relations.subject_id = subject_sources.id\"\n joins\n end", "def set_create_join_table_movie_country\n @create_join_table_movie_country = CreateJoinTableMovieCountry.find(params[:id])\n end", "def build_report\n klass = model_class.constantize\n @cols = klass.columns.map { |c| c.name.to_sym }\n @assocs = klass.reflect_on_all_associations\n\n through = @assocs.each_with_object({}) { |x, hsh| hsh[x.options[:through]] = 1 }\n # through={} ; @assocs.each { |x| through[x.options[:through]] = 1 }\n @assocs = @assocs.select { |x| !through[x.name] }\n @tire_saved = klass.tire.mapping.keys\n end", "def create_join_table!(hash, options=OPTS)\n drop_table?(join_table_name(hash, options))\n create_join_table(hash, options)\n end", "def create\n @db.create_table?(:authors) do\n primary_key :id\n String :username, unique: true\n String :password, fixed: true, size: 60\n String :email, unique: true\n String :display_name, null: true\n String :bio, text: true\n String :role\n TrueClass :active, default: false\n DateTime :created_at\n end\n\n @db.create_table?(:posts) do\n primary_key :id\n String :title\n String :content, text: true\n String :slug, unique: true\n String :status\n foreign_key :author_id, :authors\n DateTime :published_on\n DateTime :last_updated\n end\n\n @db.create_table? :categories do\n primary_key :id\n String :name, unique: true\n end\n\n @db.create_join_table(post_id: :posts, category_id: :categories)\n\n @db.create_table?(:pages) do\n primary_key :id\n String :title\n String :content, text: true\n String :slug, unique: true\n end\n\n # @db.create_table?(:subscribers) do\n # primary_key :id\n # String :status\n # # TODO: Finish this one\n # end\n\n # @db.create_table?(:subscriptions) do\n # primary_key :id\n # TrueClass :active, default: false\n # String :host, unique: true\n # String :label\n # end\n end", "def _join_table_dataset(opts)\n ds = model.db.from(opts.join_table_source)\n opts[:join_table_block] ? opts[:join_table_block].call(ds) : ds\n end", "def prepare_job_and_associations\r\n temp_job = @temp_job\r\n payer_group = '--'\r\n @original_job = Job.includes(:images_for_jobs).find(temp_job.job_id)\r\n @micr_record, payer_group = get_micr_and_payer_group if @original_job.micr_applicable?\r\n\r\n job = prepare_job\r\n job.payer_group = payer_group\r\n job.is_correspondence = @original_job.is_correspondence\r\n\r\n check_information = prepare_check\r\n job.check_informations << check_information\r\n check_information.micr_line_information = @micr_record if @micr_record\r\n\r\n Batch.where(:id => @original_job.batch_id).update_all(:associated_entity_updated_at => Time.now)\r\n job\r\n end", "def create_tables\n create_mirrors\n create_users\n create_user_tokens\n create_products\n create_users_products\n create_versions\n create_dependencies\n create_access_keys\n end", "def add_joins!(sql, options, scope = :auto)\r\n scope = scope(:find) if :auto == scope\r\n join = (scope && scope[:joins]) || options[:joins]\r\n return if join.blank?\r\n extend_sql_avoiding_table_naming_clashes!(sql, scope && scope[:joins])\r\n extend_sql_avoiding_table_naming_clashes!(sql, options[:joins])\r\n end", "def build_inheritances_joins(arel, types)\n columns = Hash.new{ |h, k| h[k] = [] }\n base_on_key = model.arel_table[primary_key]\n base_attributes = model.attribute_names\n\n # Iterate over each casted dependent calculating the columns\n types.each.with_index do |model, idx|\n join_table = model.arel_table.alias(\"\\\"i_#{idx}\\\"\")\n arel.outer_join(join_table).on(base_on_key.eq(join_table[primary_key]))\n (model.attribute_names - base_attributes).each do |column|\n columns[column] << join_table\n end\n end\n\n # Return the list of needed columns\n columns.default_proc = nil\n columns\n end", "def link!\n base = ::ActiveRecord::Associations::ClassMethods::JoinDependency.new(\n @model, [], nil\n )\n \n @fields.each { |field|\n field.model ||= @model\n field.columns.each { |col|\n field.associations[col] = associations(col.__stack.clone)\n field.associations[col].each { |assoc| assoc.join_to(base) }\n }\n }\n \n @attributes.each { |attribute|\n attribute.model ||= @model\n attribute.columns.each { |col|\n attribute.associations[col] = associations(col.__stack.clone)\n attribute.associations[col].each { |assoc| assoc.join_to(base) }\n }\n }\n end", "def create_users_products\n @db.create_join_table(:user_id => :users, :product_id => :products) do\n end\n end", "def create_tables\n DB.create_table? :event_templates do\n primary_key :id, :type => :uuid\n String :title, :unique=>true\n String :duration\n String :description\n String :status\n end\n\n DB.create_table? :events do\n primary_key :id, :type => :uuid\n foreign_key :event_template_id, :type => :uuid\n String :title\n String :duration\n String :description\n String :date\n String :start_time\n String :timezone\n String :cohort\n Integer :cohort_id\n String :income_amount\n String :income_currency\n String :utc_time\n\n end\n\n DB.create_table? :coaches do\n primary_key :id\n String :name\n String :email\n String :image\n String :status\n end\n\n DB.create_table? :assigned_coaches do\n primary_key :id\n foreign_key :event_id, :type => :uuid\n foreign_key :coach_id\n end\n\n DB.create_table? :coach_fees do\n primary_key :id\n foreign_key :event_template_id, :type => :uuid\n foreign_key :event_id, :type => :uuid\n String :currency\n String :amount\n end\n\n DB.create_table? :timezones do\n primary_key :id\n String :name\n end\n\n DB.create_table? :cohorts do\n primary_key :id\n String :name\n String :status\n end\n\nend", "def clean_join_table\n # these 2 lines run pretty much the same sql, self.parses adds a where in clause\n self.parsers = []\n # OR\n # ActiveRecord::Base.connection.execute(\"DELETE FROM parsers_transformations WHERE transformation_id = #{id}\")\n end", "def export_to_db!(filter_boxes)\n return unless @contradiction_count.zero?\n create_new_chapters!\n @chapters.each do |c|\n create_new_sections!(c)\n c['mampf_chapter'] = c['mampf_chapter'].reload\n end\n create_or_update_chapter_items!\n create_or_update_section_items!\n create_or_update_content_items!(filter_boxes)\n update_tags!(filter_boxes)\n end", "def save\n unless @added.empty? && @deleted.empty?\n # We cannot reuse the allocated space, since the data\n # that is copied would be destroyed.\n if polymorphic?\n offset = @database.allocate_polymorphic_join_elements(@size)\n else\n offset = @database.allocate_join_elements(@size)\n end\n pairs =\n @size.times.map do |index|\n rod_id = id_for(index)\n if rod_id.is_a?(Model)\n object = rod_id\n if object.new?\n if polymorphic?\n object.reference_updaters <<\n ReferenceUpdater.for_plural(self,index,@database)\n else\n object.reference_updaters <<\n ReferenceUpdater.for_plural(self,index,@database)\n end\n next\n else\n rod_id = object.rod_id\n end\n end\n [rod_id,index]\n end.compact\n if polymorphic?\n pairs.each do |rod_id,index|\n class_id = (rod_id == 0 ? 0 : class_for(index).name_hash)\n @database.set_polymorphic_join_element_id(offset,index,rod_id,class_id)\n end\n else\n pairs.each do |rod_id,index|\n @database.set_join_element_id(offset,index,rod_id)\n end\n end\n @offset = offset\n @added.clear\n @deleted.clear\n @map.clear\n @original_size = @size\n end\n @offset\n end", "def tables_and_joins\n sql = \"#{fact_class.table_name}\"\n cube_class.dimensions_hierarchies.each do |dimension_name, hierarchy_name|\n dimension_table_name = fact_class.dimension_class(dimension_name).table_name\n sql += \" LEFT JOIN #{dimension_table_name} as #{dimension_name}\"\n sql += \" ON #{fact_class.table_name}.\"\n sql += \"#{fact_class.dimension_relationships[dimension_name].foreign_key}\"\n sql += \" = #{dimension_name}.id\\n\"\n end\n sql\n end", "def table_list(our_join = join, our_tables = tables)\n flatten_joins([model.table_name] + our_join + our_tables, false).uniq\n end", "def needs_join_table(table_name1, type, table_name2, clause, join_name = nil)\n join_name ||= \"#{table_name1}=#{type}=#{table_name2}\"\n @needed_join_tables[join_name] ||= {}\n @needed_join_tables[join_name][table] ||= begin\n # define join for this part ('table' = unique for each part)\n\n # don't add to list of tables, just get unique alias name\n second_table = get_alias(table_name2)\n\n # create join\n first_table = table(table_name1)\n\n @join_tables[first_table] ||= []\n @join_tables[first_table] << \"#{type} JOIN #{second_table} ON #{clause.gsub('TABLE1',first_table).gsub('TABLE2',second_table)}\"\n second_table\n end\n end", "def copy_and_clear_table(params)\n table_name = params[:table]\n game = params[:game]\n team_table = params[:team_table]\n result_filter = params[:result_filter] # for Log only\n main_class = table_name.constantize\n archive_class = (\"Archive#{table_name}\").constantize\n\n main_class.where(game_id: game.id).each do |row|\n\n condition = result_filter.blank? || result_filter.include?(row.result_code) # check the result_filter\n condition &&= archive_class.find_by_id(row.id).blank? # check if this record is already archived\n if condition\n archive_instance = archive_class.new\n main_class.column_names.each do |column|\n if column == 'team_id'\n # if this team is not in game requests\n unless team_table[row.team_id]\n team = Team.find(row.team_id)\n archive_team = ArchiveTeam.create(name: team.name, alternative_name: team.alternative_name,\n image_url: team.image_url, team_id: team.id, game_id: game.id)\n team_table.merge!({team.id => archive_team.id})\n end\n\n archive_instance.send( \"#{column}=\", team_table[row.team_id] )\n else\n archive_instance.send(\"#{column}=\", row.send(column))\n end\n end\n archive_instance.save\n end\n end\n main_class.where(game_id: game.id).map(&:delete)\n end", "def auto_assoc(opts = {})\n except = opts[:except] || []\n\n assocs = db.schema_parse_associations(table_name)\n relations = process_join_tables(assocs)\n\n relations.each do |row|\n src_tbl = row[:src_tbl]\n src_col = row[:src_col]\n if src_tbl == table_name && ! (src_col & except).empty?\n # TODO enable except for *_to_many\n next\n end\n src_uniq = row[:src_uniq]\n src_cardinality = cardinality(src_uniq)\n\n join_tbl = row[:join_tbl]\n\n dst_tbl = row[:dst_tbl]\n dst_col = row[:dst_col]\n dst_uniq = row[:dst_uniq]\n dst_cardinality = cardinality(dst_uniq)\n\n TABLE_MODELS.wait_all(src_tbl, dst_tbl) do |src_cls, dst_cls|\n self_ref = src_cls == dst_cls\n\n src = self_ref ? :child : underscore(src_cls.name).to_sym\n src = src_uniq ? singularize(src).to_sym : pluralize(src).to_sym\n\n dst = self_ref ? :parent : underscore(dst_cls.name).to_sym\n dst = dst_uniq ? singularize(dst).to_sym : pluralize(dst).to_sym\n\n if join_tbl\n left_col = row[:left_col]\n right_col = row[:right_col]\n send :many_to_many, src, :class => src_cls, :join_table => join_tbl,\n :left_key => left_col, :left_primary_key => dst_col,\n :right_key => right_col, :right_primary_key => src_col\n else\n # TODO name overrides\n\n if self == dst_cls\n # dst holds the foreign key -> one_to_*\n meth = dst_cardinality + '_to_' + src_cardinality\n send meth, src, :class => src_cls, :key => src_col, :primary_key => dst_col\n end\n\n if self == src_cls\n # src holds the foreign key -> *_to_one\n meth = src_cardinality + '_to_' + dst_cardinality\n\n # one_to_one requires to swap pk and fk\n src_col, dst_col = dst_col, src_col if src_uniq\n send meth, dst, :class => dst_cls, :key => src_col, :primary_key => dst_col\n end\n end\n\n end\n end\n end", "def create_prejoined_fact_table(options={})\r\n connection.transaction {\r\n drop_prejoin_fact_table\r\n\r\n connection.create_table(prejoined_table_name, :id => false) do |t|\r\n # get all columns except the foreign_key columns for prejoined dimensions\r\n columns.each do |c|\r\n t.column(c.name, c.type) unless excluded_foreign_key_names.include?(c.name)\r\n end\r\n #prejoined_columns\r\n prejoined_fields.each_pair do |key, value|\r\n dclass = dimension_class(key)\r\n dclass.columns.each do |c|\r\n t.column(c.name, c.type) if value.include?(c.name.to_sym) \r\n end\r\n end\r\n end\r\n }\r\n end", "def join_table\n\t\traise \"No player yet!\" unless @player_id\n\t\tjoin_specific_table(ask_to_choose_table)\n\tend", "def join_table\n\t\traise \"No player yet!\" unless @player_id\n\t\tjoin_specific_table(ask_to_choose_table)\n\tend", "def _create(other_id, attrs, force)\n raise 'Cannot call create! on a non-join model' unless @find_method\n join = force ? nil : find(other_id)\n return join if (join && attrs.empty?)\n\n # create! short circuits if a join record already exists, and no\n # attrs are provided. otherwise a new or existing join model is\n # updated with attrs before being saved\n join ||= @target.new\n join.assign_attributes(attrs.merge!({\n \"#{@class_name}_id\" => @id,\n \"#{@other_name}_id\" => other_id\n }))\n join\n end", "def writers_join_table\n self.class.writers_join_table\n end", "def joins\n joins_hash = {}\n @rules.each do |rule|\n merge_joins(joins_hash, rule.associations_hash)\n end\n clean_joins(joins_hash) unless joins_hash.empty?\n end", "def tnTableCreation(tableName)\n pk_list = @pkList.join(',')\n pk_list = \"#{pk_list},branch_name,node_name\"\n q = QueryBuilder.create_tbl(tableName, pk_list, \"select #{@pkSelect}, 0 as test_id,''::varchar(30) as node_name, ''::varchar(30) as branch_name, ''::varchar(5) as type from #{@fTable} f where 1 = 0\")\n # pp q\n DBConn.exec(q)\n\n # q=\"ALTER TABLE #{tableName} add column test_id int, add column node_name varchar(30), add column branch_name varchar(30), add column type varchar(5);\"\n # DBConn.exec(q)\n # pk=@pkList.join(',')\n # # add index\n # q=\"create index ix_#{tableName}t on #{tableName} (#{pk},branch_name);\"\n # pp q\n # DBConn.exec(q)\n end", "def construct_join_attributes(*records)\n if @reflection.source_reflection.macro != :belongs_to\n raise HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(@owner, @reflection)\n end\n\n join_attributes = {\n @reflection.source_reflection.foreign_key =>\n records.map { |record|\n record.send(@reflection.source_reflection.association_primary_key)\n }\n }\n\n if @reflection.options[:source_type]\n join_attributes[@reflection.source_reflection.foreign_type] =\n records.map { |record| record.class.base_class.name }\n end\n\n if records.count == 1\n Hash[join_attributes.map { |k, v| [k, v.first] }]\n else\n join_attributes\n end\n end", "def create_join_associations_for_codegen!(schema, options={})\n create_join_associations!(schema, options)\n end", "def populate_nonprofit_table(org_eins)\n org_eins.each do |ein|\n Nonprofit.create(charityName: charityname(ein), city: city(ein), url: url(ein), ein: ein(ein) , zipcode: zipcode(ein), cause: cause(ein))\n end\nend", "def create_join_table?(hash, options=OPTS)\n if supports_create_table_if_not_exists? && options[:no_index]\n create_join_table(hash, options.merge(:if_not_exists=>true))\n elsif !table_exists?(join_table_name(hash, options))\n create_join_table(hash, options)\n end\n end", "def rebuild(table); end", "def joins\n joins_hash = {}\n @rules.each do |rule|\n associations_hash = rule.custom_where_conditions ? rule.conditions : rule.associations_hash\n merge_joins(joins_hash, associations_hash)\n end\n if joins_hash.empty?\n [joins_hash, []]\n else\n clean_joins(joins_hash)\n end\n end", "def join_tables(db)\n db.execute(\"SELECT users.user_name, platform.platform_name, music.artist, music.song, music.explicit_lyrics FROM music JOIN users ON music.user_id = users.id JOIN platform ON music.platform_id = platform.id\")\nend", "def relation\n # base query relation for asset\n base_rel = TransamAsset.where(\"transam_assets.organization_id\": organization_list || [])\n\n join_tables = {}\n where_sqls = {}\n field_pairs = {}\n query_filters.each do |filter|\n query_field = filter.query_field\n # exclude organization_id as its handled above\n next unless query_field || query_field.name == 'organization_id'\n unless query_field.pairs_with.blank?\n field_pairs[query_field.name] = query_field.pairs_with\n end\n\n where_sqls_for_one_filter = []\n query_field.query_asset_classes.each do |asset_class|\n asset_table_name = asset_class.table_name\n unless join_tables.keys.include?(asset_table_name) || asset_class.transam_assets_join.blank?\n join_tables[asset_table_name] = asset_class.transam_assets_join\n end\n\n query_field_name = \"#{asset_table_name}.#{query_field.name}\"\n query_filter_type = query_field.filter_type\n\n filter_value = filter.value\n # wrap values\n if filter.op == 'like'\n filter_value = \"'%#{filter.value}%'\"\n elsif ['date', 'text'].include?(query_filter_type) and filter.op != 'in' # if coming from a list expect quotes to already be added\n filter_value = \"'#{filter.value}'\"\n end\n\n filter_op = filter.op\n if filter_op == 'in' \n if filter_value.blank?\n filter_op = 'is'\n filter_value = 'NULL'\n else\n filter_value = \"(#{filter_value})\"\n end\n end\n\n #if query_filter_type == 'text'\n #query_field_name = \"lower(#{query_field_name})\"\n #filter_value = \"lower(#{filter_value})\"\n #end\n\n where_clause_str = \"#{query_field_name} #{filter_op} #{filter_value}\"\n unless query_field.column_filter.blank? || query_field.column_filter_value.blank?\n where_clause_str = \"(#{query_field_name} #{filter_op} #{filter_value} AND #{query_field.column_filter} = '#{query_field.column_filter_value}')\"\n end\n where_sqls_for_one_filter << where_clause_str\n end\n\n where_sqls[query_field.name] = where_sqls_for_one_filter.join(\" OR \")\n end\n\n # deal with field_pairs: if both the main field and pairs_with field are filters, then they should be a OR sql relation\n # e.g., manufacturer_id in (1,2) OR other_manufacturer in ('A', 'B')\n field_pairs.each do |main_field, pairs_with|\n main_field_sql = where_sqls[main_field]\n pairs_with_sql = where_sqls[pairs_with]\n next if main_field_sql.blank? || pairs_with_sql.blank? \n where_sqls[main_field] = \"(#{main_field_sql}) OR (#{pairs_with_sql})\"\n where_sqls.delete(pairs_with) # delete pairs_with sql\n end\n\n select_sqls = []\n column_filters = {}\n query_fields.each do |field|\n unless field.column_filter.blank? || field.column_filter_value.blank?\n if column_filters[field.column_filter]\n column_filters[field.column_filter] << field.column_filter_value unless column_filters[field.column_filter].include?(field.column_filter_value)\n else\n column_filters[field.column_filter] = [field.column_filter_value]\n end\n end\n\n query_field_name = field.name\n field_association = field.query_association_class\n if field_association\n association_table_name = field_association.table_name\n association_id_field_name = field_association.id_field_name\n association_display_field_name = field_association.display_field_name\n use_field_name = field_association.use_field_name\n end\n\n field.query_asset_classes.each do |qac|\n asset_table_name = qac.table_name\n table_join = qac.transam_assets_join\n\n unless join_tables.keys.include?(asset_table_name) || table_join.blank?\n join_tables[asset_table_name] = table_join\n end\n\n unless association_table_name.blank?\n as_table_name = \"#{asset_table_name}_#{association_table_name}\"\n as_table_name += \"_#{query_field_name}\" if use_field_name\n # select value from association table\n unless join_tables.keys.include?(as_table_name)\n join_tables[as_table_name] = \"left join #{association_table_name} as #{as_table_name} on #{as_table_name}.#{association_id_field_name} = #{asset_table_name}.#{query_field_name}\"\n end\n\n unless field.column_filter.blank? || field.column_filter_value.blank?\n select_sqls << \"IF(#{field.column_filter} = '#{field.column_filter_value}',#{as_table_name}.#{association_display_field_name}, '') as #{asset_table_name}_#{query_field_name}\"\n else\n select_sqls << \"#{as_table_name}.#{association_display_field_name} as #{asset_table_name}_#{query_field_name}\"\n end\n else\n # select value directly from asset_table\n\n output_field_name = field.display_field.blank? ? \"#{asset_table_name}.#{query_field_name}\" : \"#{asset_table_name}.#{field.display_field}\"\n\n unless field.column_filter.blank? || field.column_filter_value.blank?\n select_sqls << \"IF(#{field.column_filter} = '#{field.column_filter_value}',#{output_field_name}, '') as #{asset_table_name}_#{query_field_name}\"\n else\n select_sqls << \"#{output_field_name} as #{asset_table_name}_#{query_field_name}\"\n end\n\n end\n end\n end \n\n # joins\n join_tables.each do |table_name, join_sql|\n base_rel = base_rel.joins(join_sql)\n end\n\n # wheres\n if where_sqls.any?\n base_rel = base_rel.where(where_sqls.map{ |field_name, field_sql| \"(\" + field_sql + \")\" }.join(\" AND \"))\n end\n\n # apply column filters\n if column_filters.any?\n base_rel = base_rel.where(column_filters.map{ |column_filter, column_filter_values| \"#{column_filter} in (\" + column_filter_values.map{|v| \"'#{v}'\"}.join(',') + \")\" }.join(\" OR \"))\n end\n\n # selects\n if select_sqls.any?\n base_rel = base_rel.select(\"transam_assets.id\", select_sqls.join(\", \"))\n end\n\n # return base query relation\n puts base_rel.to_sql\n base_rel\n end", "def joins_on\n # join(relations).on(conditions)\n condition = deals.join(clients)\n .on(deals[:advertiser_id].eq(clients[:id]))\n workflow_criterions.each do |wc|\n case wc.field\n when 'currencies'\n condition = condition\n .join(currencies)\n .on(deals[:curr_cd].eq(currencies[:curr_cd]))\n when 'deal_type'\n condition = condition\n .join(values)\n .on(deals[:id].eq(values[:subject_id]))\n .join(options)\n .on(values[:option_id].eq(options[:id]))\n when 'deal_initiative'\n condition = condition\n .join(initiatives)\n .on(deals[:initiative_id].eq(initiatives[:id]))\n when 'teams'\n condition = condition\n .join(deal_members)\n .on(deal_members[:deal_id].eq(deals[:id]))\n .join(users)\n .on(users[:id].eq(deal_members[:user_id]))\n .join(teams)\n .on(teams[:id].eq(users[:team_id]).or(teams[:leader_id].eq(users[:id])))\n when 'client_segments'\n condition = condition\n .join(client_segments)\n .on(clients[:client_segment_id].eq(client_segments[:id]))\n when 'client_regions'\n condition = condition\n .join(client_regions)\n .on(clients[:client_region_id].eq(client_regions[:id]))\n when 'client_categories'\n condition = condition\n .join(client_categories)\n .on(clients[:client_category_id].eq(client_categories[:id]))\n when 'client_subcategories'\n condition = condition\n .join(client_subcategories)\n .on(clients[:client_subcategory_id].eq(client_subcategories[:id]))\n when 'share'\n condition = condition\n .join(deal_members)\n .on(deal_members[:deal_id].eq(deals[:id]))\n end\n case wc.base_object\n when 'Account Custom Fields'\n unless condition.to_sql.include?(\"INNER JOIN \\\"account_cfs\\\"\")\n condition = condition\n .join(account_cfs)\n .on(clients[:id].eq(account_cfs[:client_id]))\n end\n when 'Deal Custom Fields'\n unless condition.to_sql.include?(\"INNER JOIN \\\"deal_custom_fields\\\"\")\n condition = condition\n .join(deal_custom_fields)\n .on(deals[:id].eq(deal_custom_fields[:deal_id]))\n end\n when 'Deal Members'\n condition = condition\n .join(deal_members)\n .on(deal_members[:deal_id].eq(deals[:id]))\n .join(values)\n .on(values[:subject_id].eq(deal_members[:id]))\n .join(fields)\n .on(values[:field_id].eq(fields[:id]))\n .join(member_roles)\n .on(fields[:id].eq(member_roles[:field_id])) if wc.field.eql?('role')\n end\n end\n condition\n end", "def construct_nested_join_attributes( reflection = @reflection, \n association_class = reflection.klass,\n table_ids = {association_class.table_name => 1})\n if reflection.through_reflection\n construct_has_many_through_attributes(reflection, table_ids)\n else\n construct_has_many_or_belongs_to_attributes(reflection, association_class, table_ids)\n end\n end", "def setup_target_table\n self.target_table = source_table if target_table.blank?\n end", "def create\n begin\n puts \"Creating...\"\n ActiveRecord::Schema.define do\n #create_table :test_relations do |table|\n # table.column :test_case_id, :integer\n # table.column :test_collection_id, :integer\n #end\n create_table :defaults do |table|\n table.column :configuration_id, :integer\n end\n\n\n # Project configuration\n create_table :configurations do |table|\n table.column :name, :string\n table.column :server, :string\n table.column :devkey, :string\n table.column :smtp_host, :string\n table.column :smtp_recipient, :string\n table.column :project, :string # aka prefix\n table.column :vm_user, :string\n table.column :vm_password, :string\n table.column :ssh_key_path, :string\n table.column :ssh_key_pw, :string\n table.column :base_path, :string\n table.column :output_path, :string\n table.column :public_options, :string\n end\n\n\n # A test collection is a collection of test, defined by project, testplan and build\n create_table :test_collections do |table|\n table.column :project, :string\n table.column :project_id, :string\n table.column :plan, :string\n table.column :plan_id, :string\n #table.column :build, :string\n #table.column :testrun_id, :string\n #table.column :test_cases, :string\n end\n\n create_table :test_cases do |table|\n table.column :urgency, :string\n table.column :name, :string\n table.column :file, :string\n table.column :external_id, :string\n table.column :platform_id, :string\n table.column :test_collection_id, :string\n\n end\n\n end\n\n rescue ActiveRecord::StatementInvalid\n # Table already created\n puts \"Setup already done. Destroy tables first before creating\"\n end\n\n\n end", "def join_from_sql(type, sql)\n if(from = @opts[:from][1..-1]).empty?\n raise(Error, 'Need multiple FROM tables if updating/deleting a dataset with JOINs') if @opts[:join]\n else\n sql << SPACE << type.to_s << SPACE\n source_list_append(sql, from)\n select_join_sql(sql)\n end\n end", "def to_sql\n sql = @primary_table.to_sql\n for join in @joins\n sql << \" \" << join.to_sql\n end\n sql\n end", "def create_relationships(invitation)\n @invitor = Person.where(\"email = ? AND status = 'active mobile'\", invitation.invitor_email).first\n @invitee = Person.where(\"email = ? AND status = 'active mobile'\", invitation.invitee_email).first\n logger.debug(\"debug point alpha\")\n @invitor.person_connections.build(:person_a_id => @invitor.id, :person_b_id => @invitee.id,\n :category => invitation.category, :invitation_id => invitation.id, :status => 'active')\n logger.debug(\"debug point beta\")\n\n # create the second (reverse) person_connection \n @invitee.person_connections.build(:person_a_id => @invitee.id, :person_b_id => @invitor.id,\n :category => @invitation.category, :invitation_id => @invitation.id, :status => 'active')\n logger.debug(\"debug point gamma\")\n\n # add caretaker row for each pet owned by the invitor\n @invitor.caretakers.each do |ct|\n if ct.primary_role.eql?('Owner')\n if @invitation.category.eql?('Spouse-Partner')\n p_role = 'Owner'\n else\n p_role = @invitation.category\n end\n @invitee.caretakers.build(:pet_id => ct.pet_id, :primary_role => p_role, :status => 'active', :started_at => Time.now)\n end\n logger.debug(\"debug point delta\")\n end\n @invitor.save && @invitee.save\n \n end", "def join(*args)\n\t\tif args.count > 1\n\t\t\tjoins = args.map { |arg| \"INNER JOIN #{arg} ON #{arg}.#{table}_id = #{table}.id\"}.join(\" \")\n\t\t\trows = connection.execute <<-SQL \n\t\t\t\tSELECT * FROM #{table} #{joins};\n\t\t\tSQL\n\t\telse\n\t\t\tcase args.first\n\t\t\twhen String\n\t\t\t\trows = connection.execute <<-SQL\n\t\t\t\t\tSELECT * FROM #{table} #{BlocRecord::Utility.sql_strings(args.first)};\n\t\t\t\tSQL\n\t\t\twhen Symbol\n\t\t\t\trows = connection.execute <<-SQL \n\t\t\t\t\tSELECT * FROM #{table}\n\t\t\t\t\tINNER JOIN #{args.first} ON #{arg.first}.#{table}_id = #{table}.id;\n\t\t\t\tSQL\n\t\t\twhen Hash \n\t\t\t\t#extract the options from the hash\n\t\t\t\tsecond_table = args[0].keys.first \n\t\t\t\tthird_table = args[0].keys.first\n\t\t\t\trows = connection.execute <<-SQL \n\t\t\t\t\tSELECT * FROM #{table}\n\t\t\t\t\tINNER JOIN #{second_table} ON #{second_table}.#{table}_id = #{table}.id\n\t\t\t\t\tINNER JOIN #{third_table} ON #{third_table}.#{second_table}_id = #{second_table}.id;\n\t\t\t\tSQL\n\n\t\t\tend \n\t\tend\n\t\trows_to_array(rows)\n\tend", "def create_full_rst_tbl(preserve_null_pk = true)\n unless defined? @full_rst_tbl\n self.all_cols_select\n self.pk_full_list\n if preserve_null_pk\n renamed_pk_col = @pk_full_list.map { |pk| \"#{pk['col']} as #{pk['alias']}_pk\" }.join(', ')\n else\n renamed_pk_col = @pk_full_list.map do |pk|\n pkcol = @all_cols.find{|col| col.colname == pk['colname'] and col.relname==pk['relname']}\n \"COALESCE(#{pk['col']},#{pkcol.null_replacement}) as #{pk['alias']}_pk\"\n end.join(',')\n end\n targetListReplacement = \"#{renamed_pk_col},#{@all_cols_select}\"\n query = ReverseParseTree.reverseAndreplace(@parseTree, targetListReplacement, '')\n @full_rst_tbl = \"#{@table}_full_rst\"\n pk = @pk_full_list.map { |pk| \"#{pk['alias']}_pk\" }.join(', ')\n # binding.pry\n DBConn.tblCreation(@full_rst_tbl, pk, query)\n\n # unless preserve_null_pk\n # DBConn.update_null_columns(@full_rst_tbl,pk)\n # end\n # if is_plain_query()\n # query = QueryBuilder.create_tbl(@full_rst_tbl, pk, query)\n # DBConn.exec(query)\n # else\n # query = QueryBuilder.create_tbl(@full_rst_tbl, '', query)\n # DBConn.exec(query)\n\n # # not_null_query = pk_list.flat.map{|pk| \"#{pk} is not null\"}.join(' AND ')\n # # add index on not null columns\n # pk_not_null = @pk_full_list.map { |pk| \"#{pk['alias']}_pk is not null\"}.join(' OR ')\n # create_indx = \"CREATE UNIQUE INDEX idx_#{@full_rst_tbl} on #{@full_rst_tbl} (#{pk}) where #{pk_not_null}\"\n # pp create_indx\n # DBConn.exec(create_indx)\n\n # end\n end\n return @full_rst_tbl\n end", "def populate_prejoined_fact_table(options={})\r\n fact_columns_string = columns.collect {|c|\r\n \"#{table_name}.\" + c.name unless excluded_foreign_key_names.include?(c.name)\r\n }.compact.join(\",\\n\") \r\n \r\n prejoined_columns = []\r\n \r\n tables_and_joins = \"#{table_name}\"\r\n \r\n prejoined_fields.each_pair do |key, value|\r\n dimension = dimension_class(key)\r\n tables_and_joins += \"\\nJOIN #{dimension.table_name} as #{key}\"\r\n tables_and_joins += \"\\n ON #{table_name}.#{dimension_relationships[key].foreign_key} = \"\r\n tables_and_joins += \"#{key}.#{dimension.primary_key}\"\r\n prejoined_columns << value.collect {|v| \"#{key}.\" + v.to_s}\r\n end\r\n\r\n if connection.support_select_into_table?\r\n drop_prejoin_fact_table\r\n sql = <<-SQL\r\n SELECT #{fact_columns_string}, \r\n #{prejoined_columns.join(\",\\n\")}\r\n FROM #{tables_and_joins}\r\n SQL\r\n sql = connection.add_select_into_table(prejoined_table_name, sql)\r\n else\r\n create_prejoined_fact_table(options)\r\n sql = <<-SQL\r\n INSERT INTO #{prejoined_table_name}\r\n SELECT #{fact_columns_string}, \r\n #{prejoined_columns.join(\",\\n\")}\r\n FROM #{tables_and_joins}\r\n SQL\r\n end\r\n connection.transaction { connection.execute(sql) } \r\n end", "def join_table(type, table, *args, &block)\n if table.is_a?(Class) && table < Sequel::Model\n Sequel::Deprecation.deprecate(\"Passing Sequel::Model class to a dataset join method\", \"Pass the model's table name or dataset as the first argument instead\")\n if table.dataset.simple_select_all?\n super(type, table.table_name, *args, &block)\n else\n super(type, table.dataset, *args, &block)\n end\n else\n super\n end\n end", "def join_from_sql(type, sql)\n if(from = @opts[:from][1..-1]).empty?\n raise(Error, 'Need multiple FROM tables if updating/deleting a dataset with JOINs') if @opts[:join]\n else\n sql << ' ' << type.to_s << ' '\n source_list_append(sql, from)\n select_join_sql(sql)\n end\n end", "def print_join\r\n if get_tables.size < 2\r\n puts \"you do not have enough tables to join\"\r\n return nil\r\n end\r\n to_join = []\r\n puts \"choose 2 of these tables to join\"\r\n print_table_names\r\n until to_join.length == 2\r\n puts \"what is your first table you would like to join?\" if to_join.length == 0\r\n puts \"what is your second table you would like to join?\" if to_join.length == 1\r\n answer = gets.chomp\r\n to_join << answer if table_exists?(answer)\r\n end\r\n if references(to_join[1]).include?(to_join[0])\r\n execute = @db.execute(\"SELECT * FROM #{to_join[0]} JOIN #{to_join[1]}\r\n ON #{to_join[0]}.#{to_join[1]}_id = #{to_join[1]}.id ;\")\r\n print_execute_titles(execute)\r\n print_execute(execute)\r\n elsif references(to_join[0]).include?(to_join[1])\r\n execute = @db.execute(\"SELECT * FROM #{to_join[1]} JOIN #{to_join[0]}\r\n ON #{to_join[1]}.#{to_join[0]}_id = #{to_join[0]}.id ;\")\r\n print_execute_titles(execute)\r\n print_execute(execute)\r\n else\r\n puts \"Those two tables are incompatible and cannot be joined\"\r\n end\r\n end", "def join_query\n prefixes = Survey.all.map &:prefix\n query = [\"select * from export_journal_infos ji, \"] << prefixes.map {|prefix| \"export_variables_#{prefix}_answers\" }\n prefixes.each do |prefix|\n query << \"where export_variables_#{prefix}_answers. #{prefix} on #{prefix}.journal_id = ji.journal_id \"\n # query << \"inner join export_variables_#{prefix}_answers #{prefix} on #{prefix}.journal_id = ji.journal_id \"\n end\n query\n end", "def spawn_tables\n\t# pseudo-migration / schema\n\tif !FeedEntry.table_exists?\n\t\tprint \"Creating feed entry table...\\n\"\n\t\tActiveRecord::Base.connection.create_table(:feed_entries) do |t|\n\t\t\tt.column :name, :string\n\t\t\tt.column :content, :string\n\t\t\tt.column :url, :string\n\t\t\tt.column :guid, :string\n\t\t\tt.column :published_at, :datetime\n\t\t\tt.column :feed_id, :integer\n\t\tend\n\tend\n\tif !Feed.table_exists?\n\t\tprint \"Creating feed table...\\n\"\n\t\tActiveRecord::Base.connection.create_table(:feeds) do |t|\n\t\t\tt.column :url, :string\n\t\tend\n\tend\n\tif !Blacklist.table_exists?\n\t\tprint \"Creating blacklist table...\\n\"\n\t\tActiveRecord::Base.connection.create_table(:blacklists) do |t|\n\t\t\tt.column :word, :string\n\t\tend\n\tend\nend", "def write_sql model_name, model_attributes,output\n model_attributes.each do|key,query|\n sql= ActiveRecord::Base.connection();\n (sql.select_all query).each do |row|\n make_triples(row,model_name,\"\")\n end\n end\n end", "def create_add_partner_table(options_table2)\n options_table2.raw.each do |row|\n case row[0].downcase\n when 'first name'\n first_name.set row[1]\n when 'last name'\n last_name.set row[1]\n when 'email'\n sleep 1\n email.set row[1]\n when 'date of birth'\n sleep 3\n dob.click\n dob.set row[1]\n sleep 1\n when 'gender'\n gender_dropdown.click\n sleep 2\n gender_select.each do |gen|\n gen.click if gen.text == row[1]\n end\n when 'partner info'\n sleep 2\n partner_information_dropdown.click\n partiner_info_select.each do |pi|\n pi.click if pi.text == row[1]\n end\n end\n end\n end", "def habtm_to_fixture(path)\n joins = self.reflect_on_all_associations.select { |j|\n j.macro == :has_and_belongs_to_many\n }\n joins.each do |join|\n hsh = {}\n connection.select_all(\"SELECT * FROM #{join.options[:join_table]}\").each_with_index { |record, i|\n hsh[\"join_#{'%05i' % i}\"] = record\n }\n write_file(File.expand_path(\"#{path}/#{join.options[:join_table]}.yml\", RAILS_ROOT), hsh.to_yaml(:SortKeys => true))\n end\n end", "def habtm_to_fixture(path)\n joins = self.reflect_on_all_associations.select { |j|\n j.macro == :has_and_belongs_to_many\n }\n joins.each do |join|\n hsh = {}\n connection.select_all(\"SELECT * FROM #{join.options[:join_table]}\").each_with_index { |record, i|\n hsh[\"join_#{'%05i' % i}\"] = record\n }\n write_file(File.expand_path(\"#{path}/#{join.options[:join_table]}.yml\", RAILS_ROOT), hsh.to_yaml(:SortKeys => true))\n end\n end", "def join(table, field1, field2, join_type = 'INNER JOIN')\n @join = \" #{join_type} #{table} ON #{@from}.#{field1}=#{table}.#{field2}\"\n\n self\n end", "def create_excluded_tbl\n unless defined? @excluded_tbl\n self.all_cols_select\n self.pk_full_list\n renamed_pk_col = @pk_full_list.map { |pk| \"#{pk['col']} as #{pk['alias']}_pk\" }.join(', ')\n targetListReplacement = \"#{renamed_pk_col},#{@all_cols_select}\"\n @excluded_tbl = \"#{@table}_excluded\"\n excluded_predicate = get_excluded_query\n # pp excluded_predicate\n query = ReverseParseTree.reverseAndreplace(@parseTree, targetListReplacement, excluded_predicate)\n query = QueryBuilder.create_tbl(@excluded_tbl, @pk_full_list.map { |pk| \"#{pk['alias']}_pk\" }.join(', '), query)\n DBConn.exec(query)\n\n check_excluded_tup_orig\n end\n return @excluded_tbl\n end", "def init\n ActiveRecord::Schema.define do\n create_table :students, force: true do |t|\n t.string :name\n t.belongs_to :organization\n end\n\n create_table :organizations, force: true do |t|\n t.string :name\n end\n\n create_table :projects, force: true do |t|\n t.string :title\n t.string :subcategory\n t.belongs_to :organization\n t.belongs_to :student\n end\n\n create_table :tags, force: true do |t|\n t.string :name\n t.string :tag_type\n t.belongs_to :project\n end\n end\nend", "def setup\n current_user = options[:currentuser]\n all_flag = options[:allflag]\n if current_user.percentcompleteenabled\n table = Table([:description, :goaltype_label, :datecompleted, :created_date, :last_updated_date, :percentcomplete]) do |t|\n if all_flag\n current_user.goals.find(:all).each {|g| t << g.report_record()}\n else\n current_user.goals.find(:all).each {|u| t << u.report_record unless u.datecompleted != nil}\n end\n end\n \n table.rename_columns(:description => \"Description\",\n :goaltype_label => \"Goal Type\",\n :datecompleted => \"Date Completed\",\n :created_date => \"Date Created\",\n :last_updated_date => \"Date Last Updated\",\n :percentcomplete => \"Percent Complete\")\n\n else\n table = Table([:description, :goaltype_label, :datecompleted, :created_date, :last_updated_date]) do |t|\n if all_flag\n current_user.goals.find(:all).each {|g| t << g.report_record()}\n else\n current_user.goals.find(:all).each {|u| t << u.report_record unless u.datecompleted != nil}\n end\n end\n\n table.rename_columns(:description => \"Description\",\n :goaltype_label => \"Goal Type\",\n :datecompleted => \"Date Completed\",\n :created_date => \"Date Created\",\n :last_updated_date => \"Date Last Updated\")\n\n \n end\n\n self.data = table\n end", "def prepare_hgt_com_trsf_prkgrs_old()\n \n @conn.execute \\\n \"truncate table hgt_com_trsf_prkgrs\"\n \n puts \"hgt_com_trsf_prkgrs table truncated...\"\n \n #\n sql = \"select id,\n gene_id,\n TXSRC_ID,\n TXDST_ID,\n WEIGHT_TR_TX\n from HGT_COM_TRSF_TAXONS\"\n \n #puts \"sql: #{sql}\"\n \n \n tr_taxons = HgtComTrsfTaxon.find_by_sql(sql)\n \n tr_taxons.each {|tr|\n \n\n #debugging\n #next unless tr.gene_id == 111 and tr.txsrc_id == 768679 and tr.txdst_id == 374847\n \n #puts \"tr: #{tr.inspect}\"\n #puts \"tr.id: #{tr.id}, #{tr.gene_id}\"\n \n #for each chiteria\n (0..1).each {|crit|\n \n #for each criteria and\n #for each source and destination prok groups\n sql = \"select tg.PROK_GROUP_ID,\n tg.WEIGHT_PG\n from TAXON_GROUPS tg \n join PROK_GROUPS pg on pg.id = tg.PROK_GROUP_ID\n where tg.TAXON_ID = #{tr.txsrc_id} and\n pg.GROUP_CRITER_ID = #{crit}\"\n #puts \"sql: \\n #{sql}\"\n \n pg_src = TaxonGroup.find_by_sql(sql)\n \n \n sql = \"select tg.PROK_GROUP_ID,\n tg.WEIGHT_PG\n from TAXON_GROUPS tg \n join PROK_GROUPS pg on pg.id = tg.PROK_GROUP_ID\n where tg.TAXON_ID = #{tr.txdst_id} and\n pg.GROUP_CRITER_ID = #{crit}\"\n #puts \"sql: \\n #{sql}\"\n \n pg_dst = TaxonGroup.find_by_sql(sql)\n \n pg_src.each {|src|\n pg_dst.each {|dst|\n \n #puts \"src: #{src.inspect}\"\n #puts \"dst: #{dst.inspect}\"\n \n #insert alternative\n prkg = HgtComTrsfPrkgr.new \n prkg.gene_id = tr.gene_id\n prkg.hgt_com_trsf_taxon_id = tr.id\n prkg.pgsrc_id = src.prok_group_id\n prkg.pgdst_id = dst.prok_group_id\n prkg.weight_tr_pg = tr.weight_tr_tx * src.weight_pg * dst.weight_pg\n prkg.save\n \n #prkg.gene_id = tr.gene_id \n #prkg.save\n \n \n }\n }\n \n \n \n \n \n } \n }\n \n \n end", "def default_join_table\n [self[:class_name], self[:model].name].map{|i| underscore(pluralize(demodulize(i)))}.sort.join('_').to_sym\n end", "def create!\n destroy!\n tables.each(&:create)\n end", "def generate_query\n unless databases.nil?\n databases.each do |db|\n create_query[db] = [\"create table #{tablename} (\"]\n end\n csv_column_datatypes.each do |header, datatype|\n append_to_query = build_query_for_datatype(header, datatype)\n append_to_query.each do |key, value|\n create_query[key].push(value)\n end\n end\n prepare_sql_statements\n prepare_import_csv\n # Pass the prepared statements to options varaible.\n # Which gets passed on to print_metadata_analysis\n options[:create_query] = create_query\n options[:import_query] = import_query\n end\n print_metadata_analysis\n end", "def save_predicates_attributes\n each_predicate do |namespace, name, objects|\n objects.each { |object| object.save if object.is_a?(Source) && object.new_record? }\n self.predicate_replace(namespace, name, objects.to_s) if changed?(namespace, name, objects)\n end\n end", "def create_fund_table\n Bsf::Scraper.db.create_fund_table\n end", "def make_table(table, *args, others)\n unless others.is_a? Hash\n args << others\n others = {}\n end\n table = table.to_s # probably already was\n table_sym = table.to_sym\n @fields[table_sym] = args + others.keys\n @xform[table_sym] = {:inspect => [], :yaml => []}\n xform, fields = @xform, @fields # because of change in 'self'\n @db.create_table table_sym do\n primary_key table+\"_id\"\n args.each do |field| \n if field.to_s =~ /_id$/\n Integer field \n else\n String field\n end\n end\n others.each_pair do |field, klass|\n case klass.to_s.to_sym\n when :Integer; Integer field\n when :String; String field\n when :Float; Float field\n when :DateTime; DateTime field\n when :Array, :Hash, :Symbol\n String field\n xform[table_sym][:inspect] << field\n when :Yaml\n String field\n xform[table_sym][:yaml] << field\n end\n end\n end\n # Now save metadata...\n args_hash = {}\n args.each {|arg| args_hash.update(arg => :String) }\n args_hash.update(others)\n args_hash.each_pair {|k, v| args_hash[k] = v.to_s.to_sym }\n @db[:metadata].insert(:table => table, :transform => xform[table_sym].to_yaml, \n :fields => fields[table_sym].to_yaml)\n end", "def create_target_table(context, &block)\n with_logging(:debug, \"Creating target table #{target} (from #{source})\") do\n context.execute \"CREATE TABLE #{target} LIKE #{source}\"\n yield if block_given?\n end\n end", "def save_predicates_attributes # :nodoc:\n each_predicate do |namespace, name, objects|\n objects.each { |object| object.save if object.is_a?(Source) && object.new_record? }\n self.predicate_replace(namespace, name, objects.to_s) if predicate_changed?(namespace, name, objects)\n end\n end", "def insert_records(items)\n\t\titems.each do |item|\n\t\t\t#Titles, years, publishers, codecs, comments & covers tables.\n\t\t\talbum_title_id = insert_if_not_exists(TITLES_TABLE,\n\t\t\t\tTITLE_COLUMN, item[:album_title])\n\t\t\ttrack_title_id = insert_if_not_exists(TITLES_TABLE,\n\t\t\t\tTITLE_COLUMN, item[:track_title])\n\t\t\tyear_id = insert_if_not_exists(YEARS_TABLE,\n\t\t\t\tYEAR_COLUMN, item[:year])\n\t\t\tpublisher_id = insert_if_not_exists(PUBLISHERS_TABLE,\n\t\t\t\tPUBLISHER_COLUMN, item[:publisher])\n\t\t\tcodec_id = insert_if_not_exists(CODECS_TABLE,\n\t\t\t\tCODEC_COLUMN, item[:codec])\n\t\t\tcomment_id = insert_if_not_exists(COMMENTS_TABLE,\n\t\t\t\tCOMMENT_COLUMN, item[:comment])\n\t\t\tcover_id = insert_if_not_exists(COVERS_TABLE,\n\t\t\t\tCOVER_COLUMN, item[:cover])\n\n\t\t\t#Styles table.\n\t\t\tstyles = item[:style].split(\", \")\n\t\t\tstyle_ids = []\n\t\t\tstyles.each do |style|\n\t\t\t\tstyle_ids << insert_if_not_exists(STYLES_TABLE,\n\t\t\t\t\tSTYLE_COLUMN, style)\n\t\t\tend\n\n\t\t\t#Composers table.\n\t\t\tcomposers = item[:composer].split(\", \")\n\t\t\tcomposer_ids = []\n\t\t\tcomposers.each do |composer|\n\t\t\t\tcomposer_ids << insert_if_not_exists(COMPOSERS_TABLE,\n\t\t\t\t\tCOMPOSER_COLUMN, composer)\n\t\t\tend\n\n\t\t\t#Artists table.\n\t\t\t#Album_artist.\n\t\t\talbum_artists = item[:album_artist].split(\", \")\n\t\t\talbum_artist_ids = []\n\t\t\talbum_artists.each do |album_artist|\n\t\t\t\talbum_artist_ids << insert_if_not_exists(ARTISTS_TABLE,\n\t\t\t\t\tARTIST_COLUMN, album_artist)\n\t\t\tend\n\n\t\t\t#Track_artist.\n\t\t\tif item[:track_artist] == item[:album_artist]\n\t\t\t\ttrack_artist_ids = album_artist_ids\n\t\t\telse\n\t\t\t\ttrack_artists = item[:track_artist].split(\", \")\n\t\t\t\ttrack_artist_ids = []\n\t\t\t\ttrack_artists.each do |track_artist|\n\t\t\t\t\ttrack_artist_ids << insert_if_not_exists(ARTISTS_TABLE,\n\t\t\t\t\t\tARTIST_COLUMN, track_artist)\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t#Albums table.\n\t\t\tcheck_columns = [TITLE_ID_COLUMN]\n\t\t\tcheck_items = [album_title_id]\n\t\t\tinsert_items = [album_title_id, year_id, publisher_id,\n\t\t\t\tcodec_id, comment_id, cover_id]\n\t\t\talbum_id = insert_if_not_exists(ALBUMS_TABLE, check_columns,\n\t\t\t\tcheck_items, insert_items)\n\n\t\t\t#Tracks table.\n\t\t\tcheck_columns = [TRACK_NUMBER_COLUMN, DISC_NUMBER_COLUMN,\n\t\t\t\tALBUM_ID_COLUMN]\n\t\t\tcheck_items = [item[:track_number], item[:disc_number], album_id]\n\t\t\tinsert_items = [track_title_id, item[:track_number],\n\t\t\t\titem[:disc_number], album_id]\n\t\t\ttrack_id = insert_if_not_exists(TRACKS_TABLE, check_columns,\n\t\t\t\tcheck_items, insert_items)\n\t\t\t#puts \"Album: #{album_id}\\tDisc: #{disc_id}\\tTrack: #{track_id}\"\n\n\t\t\t#Albums_Artists table.\n\t\t\tcheck_columns = [ALBUM_ID_COLUMN, ARTIST_ID_COLUMN]\n\t\t\talbum_artist_ids.each_with_index do |album_artist_id, i|\n\t\t\t\tcheck_items = [album_id, album_artist_id]\n\t\t\t\tinsert_items = [album_id, album_artist_id, i.to_s]\n\t\t\t\tinsert_if_not_exists(ALBUMS_ARTISTS_TABLE, check_columns,\n\t\t\t\t\tcheck_items, insert_items)\n\t\t\tend\n\n\t\t\t#Albums_Styles table.\n\t\t\tcheck_columns = [ALBUM_ID_COLUMN, STYLE_ID_COLUMN]\n\t\t\tstyle_ids.each_with_index do |style_id, i|\n\t\t\t\tcheck_items = [album_id, style_id]\n\t\t\t\tinsert_items = [album_id, style_id, i.to_s]\n\t\t\t\tinsert_if_not_exists(ALBUMS_STYLES_TABLE, check_columns,\n\t\t\t\t\tcheck_items, insert_items)\n\t\t\tend\n\n\t\t\t#Tracks_Artists table.\n\t\t\tcheck_columns = [TRACK_ID_COLUMN, ARTIST_ID_COLUMN]\n\t\t\ttrack_artist_ids.each_with_index do |track_artist_id, i|\n\t\t\t\tcheck_items = [track_id, track_artist_id]\n\t\t\t\tinsert_items = [track_id, track_artist_id, i.to_s]\n\t\t\t\tinsert_if_not_exists(TRACKS_ARTISTS_TABLE, check_columns,\n\t\t\t\t\tcheck_items, insert_items)\n\t\t\tend\n\n\t\t\t#Tracks_Composers table.\n\t\t\tcheck_columns = [TRACK_ID_COLUMN, COMPOSER_ID_COLUMN]\n\t\t\tcomposer_ids.each_with_index do |composer_id, i|\n\t\t\t\tcheck_items = [track_id, composer_id]\n\t\t\t\tinsert_items = [track_id, composer_id, i.to_s]\n\t\t\t\tinsert_if_not_exists(TRACKS_COMPOSERS_TABLE, check_columns,\n\t\t\t\t\tcheck_items, insert_items)\n\t\t\tend\n\t\tend\n\tend", "def save_timetable_classtimings_on_split(current_timetable)\n batches = Batch.active.all(:conditions=>[\"batches.start_date <= ? and batches.end_date >= ?\", self.end_date,self.start_date]).collect(&:id)\n current_time_table_class_timings=current_timetable.time_table_class_timings\n current_time_table_class_timings.each do |class_timings|\n current_timetable_class_timing_sets=class_timings.time_table_class_timing_sets\n if batches.include? class_timings.batch_id\n ttct=self.time_table_class_timings.build(:batch_id => class_timings.batch_id)\n current_timetable_class_timing_sets.each do |ttcts|\n ttct.time_table_class_timing_sets.build(:batch_id=>class_timings.batch_id,:class_timing_set_id=>ttcts.class_timing_set_id,:weekday_id=>ttcts.weekday_id)\n end\n end\n end\n end", "def build_query_parts\n # Always include the following columns:\n select_clause = ['DISTINCT(Person.' + _(:id, :person) + ') as person_id'] # person id\n select_clause += ['Person.' + _(:first_name, :person) + ' as First_Name'] # first name\n select_clause += ['Person.' + _(:last_name, :person) + ' as Last_Name'] # last name\n \n # Always include the person table\n tables = ['Person']\n tables_clause = Person.table_name + ' as Person'\n # Always include the campus involvements table\n tables << 'CampusInvolvement'\n tables_clause += \" LEFT JOIN #{CampusInvolvement.table_name} as CampusInvolvement on Person.#{_(:id, :person)} = CampusInvolvement.#{_(:person_id, :campus_involvement)} AND CampusInvolvement.end_date IS NULL\"\n # Always include the ministry involvements table\n tables << 'MinistryInvolvement'\n tables_clause += \" LEFT JOIN #{MinistryInvolvement.table_name} as MinistryInvolvement on Person.#{_(:id, :person)} = MinistryInvolvement.#{_(:person_id, :ministry_involvement)} AND MinistryInvolvement.end_date IS NULL\"\n # Always include the current address\n tables << 'CurrentAddress'\n tables_clause += \" LEFT JOIN #{CurrentAddress.table_name} as CurrentAddress on Person.#{_(:id, :person)} = CurrentAddress.#{_(:person_id, :address)} AND #{_(:address_type, :address)} = 'current'\"\n # Hooks to support different schemas\n tables += build_query_parts_custom_tables if self.respond_to?(:build_query_parts_custom_tables)\n tables_clause += build_query_parts_custom_tables_clause if self.respond_to?(:build_query_parts_custom_tables_clause)\n\n columns.each do |column|\n raise inspect if column.nil? # If something goes wrong, we want good information\n # Add table to table clause\n table_name = column.from_clause.constantize.table_name if column.from_clause.present?\n unless !column.from_clause.present? || tables.include?(column.from_clause)\n tables << column.from_clause\n source_model = (column.source_model.to_s.empty? ? 'Person' : column.source_model).constantize\n source_column = column.source_column.to_s.empty? ? 'id' : column.source_column\n foreign_key = column.foreign_key.to_s.empty? ? 'person_id' : column.foreign_key\n source_table_name = source_model.table_name\n join_on_left = \"#{source_model}.#{_(source_column.to_sym, source_model.name.downcase.to_sym)}\"\n join_on_right = \"#{column.from_clause}.#{_(foreign_key.to_sym, column.from_clause.underscore.to_sym)}\"\n tables_clause += \" LEFT JOIN #{table_name} as #{column.from_clause} on #{join_on_left} = #{join_on_right}\"\n tables_clause += \" AND \" + column.join_clause unless column.join_clause.blank?\n end\n \n # Don't add id, first name or last name here because we added them earlier\n unless ['id','first_name','last_name'].include?(column.select_clause)\n # Add column to select clause\n unless column.select_clause.first == '('\n select_clause << \"#{column.from_clause}.#{_(column.select_clause, column.from_clause.underscore)} as #{column.safe_name}\"\n else\n select_clause << \"#{column.select_clause} as #{column.safe_name}\"\n end\n end\n end\n self.select_clause = select_clause.join(', ')\n self.tables_clause = tables_clause\n return tables\n end", "def joins\n joins_hash = {}\n @can_definitions.each do |can_definition|\n merge_joins(joins_hash, can_definition.associations_hash)\n end\n clean_joins(joins_hash) unless joins_hash.empty?\n end", "def build_auxiliary_statements(arel)\n return unless auxiliary_statements_values.present?\n auxiliary_statements_values.map do |klass|\n klass.build(self).tap { arel.join_sources.concat(klass.join_sources) }\n end\n end", "def create_queries\n gen_rulename\n [\"\n -- FN for sync updates \n CREATE FUNCTION fn_#{suffix}()\n RETURNS TRIGGER\n LANGUAGE plpgsql\n AS $function$\n BEGIN\n UPDATE #{dest_table}\n SET #{ cols.map{|src, dest| \"\\\"#{dest}\\\" = NEW.\\\"#{src}\\\"\" }.join(', ') }\n WHERE \\\"#{map_dest}\\\" = NEW.\\\"#{map_src}\\\";\n RETURN NULL;\n END;\n $function$;\",\n \"\n -- TR for sync updates\n CREATE TRIGGER tr_#{suffix}\n AFTER INSERT OR UPDATE ON #{src_table} \n FOR EACH ROW EXECUTE PROCEDURE fn_#{suffix}();\",\n \"\n -- FN for cleaner\n CREATE FUNCTION fn_#{suffix}_cleaner()\n RETURNS TRIGGER\n LANGUAGE plpgsql\n AS $function$\n BEGIN\n IF OLD.sid = #{sid_src} OR OLD.sid = #{sid_dest} THEN\n #{delete_queries.join(' ')}\n END IF;\n RETURN NULL;\n END;\n $function$;\",\n \"\n -- TR for cleaner\n CREATE TRIGGER tr_#{suffix}_cleaner\n AFTER DELETE ON #{surveys_table}\n FOR EACH ROW EXECUTE PROCEDURE fn_#{suffix}_cleaner();\n \"]\n end", "def reflection_merge(reflection, from, to)\n foreign_key = reflection.options[:foreign_key] || table_name.classify.foreign_key\n sql = case reflection.macro\n when :has_one, :has_many\n \"UPDATE #{reflection.klass.table_name} SET #{foreign_key} = #{to} WHERE #{foreign_key} = #{from}\\n\" \n when :has_and_belongs_to_many\n join_table = reflection.options[:join_table] || ( table_name < reflection.klass.table_name ? '#{table_name}_#{reflection.klass.table_name}' : '#{reflection.klass.table_name}_#{table_name}')\n \"UPDATE #{join_table} SET #{foreign_key} = #{to} WHERE #{foreign_key} = #{from}\\n\" \n else return\n end\n connection.update(sql)\n end", "def create_tables_mysql()\n\n\t\tdbrows = @database.query <<-SQL\n\t\tCREATE TABLE IF NOT EXISTS invoices (\n\t\t\torganization VARCHAR(255),\n\t\t\tupdated DATE,\n\t\t\tamount FLOAT,\n\t\t\tamount_outstanding FLOAT,\n\t\t\tdiscount FLOAT,\n\t\t\tinvoice_id VARCHAR(255),\n\t\t\tnumber VARCHAR(255) UNIQUE PRIMARY KEY,\n\t\t\tmatter VARCHAR(255),\n\t\t\tstatus VARCHAR(255),\n\t\t\tdate DATE\n\t\t\t);\n\t\t\tSQL\n\n\t\t\tdbrows = @database.query <<-SQL\n\t\t\tCREATE TABLE IF NOT EXISTS invoice_lines (\n\t\t\t\tline_id INTEGER,\n\t\t\t\t_order INTEGER,\n\t\t\t\tnumber VARCHAR(255),\n\t\t\t\tinvoice_id VARCHAR(255),\n\t\t\t\tdescription TEXT,\n\t\t\t\tamount FLOAT,\n\t\t\t\tfirst_expense_id INTEGER,\n\t\t\t first_time_entry_id TEXT,\n\t\t\t\tline_item_date VARCHAR(255),\n\t\t\t\tperson VARCHAR(512),\n\t\t\t\tname VARCHAR(255),\n\t\t\t\tunit_cost FLOAT,\n\t\t\t\tquantity FLOAT,\n\t\t\t\ttype VARCHAR(255),\n\t\t\t\tmatter VARCHAR(255),\n\t\t\t\tupdated DATE\n\t\t\t\t);\n\t\t\t\tSQL\n\t\t## Add code here if you end up making additional tables\n\n\t\tdbrows = @database.query <<-SQL\n\t\tCREATE TABLE IF NOT EXISTS projects (\n\t\t\tmatter VARCHAR(255) UNIQUE,\n\t\t\tname VARCHAR(255),\n\t\t\tproject_id VARCHAR(255),\n\t\t\thour_budget FLOAT\n\t\t\t);\n\t\t\tSQL\n\t\tdbrows = @database.query('DELETE FROM projects;')\n\n\t\tdbrows = @database.query <<-SQL\n\t\tCREATE TABLE IF NOT EXISTS time_entries (\n\t\t\ttime_entry_id INTEGER UNIQUE,\n\t\t\tstaff_id INTEGER,\n\t\t\tproject_id VARCHAR(255),\n\t\t\ttask_id INTEGER,\n\t\t\thours FLOAT,\n\t\t\tdate DATE,\n\t\t\tnotes TEXT,\n\t\t\tbilled INTEGER\n\t\t);\n\t\tSQL\n\t\tdbrows = @database.query('DELETE FROM time_entries;')\n\n\t\tdbrows = @database.query <<-SQL\n\t\tCREATE TABLE IF NOT EXISTS staff (\n\t\t\tperson VARCHAR(512),\n\t\t\tfirst_name VARCHAR(255),\n\t\t\tlast_name VARCHAR(255),\n\t\t\tstaff_id INTEGER,\n\t\t\trate FLOAT\n\t\t);\n\t\tSQL\n\t\tdbrows = @database.query('DELETE FROM staff;')\n\n\t\tdbrows = @database.query <<-SQL\n\t\tCREATE TABLE IF NOT EXISTS contractor (\n\t\t\tname VARCHAR(255),\n\t\t\tcontractor_id INTEGER,\n\t\t\trate FLOAT\n\t\t);\n\t\tSQL\n\t\tdbrows = @database.query('DELETE FROM contractor;')\n\n\t\tdbrows = @database.query <<-SQL\n\t\t\t-- estimates from Contractors\n\t\t\tCREATE OR REPLACE VIEW unbilled_contractor_time AS\n\t\t\t\tSELECT projects.matter, contractor.name as person, SUM(time_entries.hours * contractor.rate) as estimated\n\t\t\t\tFROM time_entries\n\t\t\t\tINNER JOIN projects ON projects.project_id = time_entries.project_id\n\t\t\t\tINNER JOIN contractor ON contractor.contractor_id = time_entries.staff_id\n\t\t\t\tWHERE projects.matter <> '' AND time_entries.billed = 0\n\t\t\t\tGROUP BY projects.matter, person\n\t\t\t;\n\t\t\tSQL\n\n\t\t\t#UNBILLED STAFF TIME view\n\t\tdbrows = @database.query <<-SQL\n\t\t-- Estimates from Staff\n\t\t\tCREATE OR REPLACE VIEW unbilled_staff_time AS\n\t\t\t\t\tSELECT projects.matter, staff.person, SUM(time_entries.hours * staff.rate) as estimated\n\t\t\t\t\tFROM time_entries\n\t\t\t\t\tINNER JOIN projects ON projects.project_id = time_entries.project_id\n\t\t\t\t\tINNER JOIN staff ON staff.staff_id = time_entries.staff_id\n\t\t\t\t\tWHERE projects.matter <> '' AND time_entries.billed = 0\n\t\t\t\t\tGROUP BY projects.matter, staff.person\n\t\t\t\t\tORDER BY projects.matter, staff.person\n\t\t\t\t\t;\n\n\t\t\tSQL\n\n\t\t#UNBILLED ALL TIME TEMP view\n\t\tdbrows = @database.query <<-SQL\n\t\t\tCREATE OR REPLACE VIEW unbilled_all_time_temp AS\n\t\t\t\t\tSELECT * FROM unbilled_staff_time\n\t\t\t\t\tUNION\n\t\t\t\t\tSELECT * FROM unbilled_contractor_time;\n\t\t\tSQL\n\n\t\t#UNBILLED ALL TIME view\n\t\tdbrows = @database.query <<-SQL\n\t\t\t-- All unbilled time\n\t\t\t\tCREATE OR REPLACE VIEW unbilled_all_time AS\n\t\t\t\t\tSELECT *\n\t\t\t\t\tFROM unbilled_all_time_temp\n\t\t\t\t\tGROUP BY unbilled_all_time_temp.matter, unbilled_all_time_temp.person\n\t\t\t\t;\n\t\t\t\tSQL\n\n\t\t#mysql version\n\t\t#INVOICES GROUP view\n\t\tdbrows = @database.query <<-SQL\n\t\t\tCREATE OR REPLACE VIEW invoices_grouped AS\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tinvoices.organization\n\t\t\t\t\t\t, invoices.matter\n\t\t\t\t\t\t, SUM((CASE WHEN status <> 'draft' THEN invoices.amount ELSE 0 END)) AS lifetime_billed\n\t\t\t\t\t\t, SUM((CASE WHEN YEAR(invoices.date) = YEAR(NOW()) THEN\n\t\t\t\t\t\t\t(CASE WHEN status <> 'draft' THEN invoices.amount ELSE 0 END)\n\t\t\t\t\t\t\tELSE 0 END)) as ytd_billed\n\t\t\t\t\t\t, SUM((CASE WHEN status = 'draft' THEN invoices.amount ELSE 0 END)) as draft_invoices\n\t\t\t\t\t\t, SUM((CASE WHEN status <> 'draft' THEN invoices.amount_outstanding ELSE 0 END)) as outstanding\n\t\t\t\t\tFROM invoices\n\t\t\t\t\tGROUP BY invoices.organization, invoices.matter;\n\t\t\tSQL\n\n\t\t#ORGNAMES view\n\t\tdbrows = @database.query <<-SQL\n\t\t\tCREATE OR REPLACE VIEW orgnames AS\n\t\t\t\tSELECT DISTINCT invoices_grouped.organization, unbilled_all_time.matter\n\t\t\t\tFROM unbilled_all_time\n\t\t\t\tLEFT OUTER JOIN invoices_grouped ON SUBSTR(invoices_grouped.matter,1,4) = SUBSTR(unbilled_all_time.matter,1,4);\n\t\t\tSQL\n\n\t\tdbrows = @database.query <<-SQL\n\t\t\t-- Build a deconstructed invoice from the line items\n\t\t\tCREATE OR REPLACE VIEW apportioned_invoices AS\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tinvoices.organization\n\t\t\t\t\t\t\t, invoices.updated\n\t\t\t\t\t\t\t, (invoice_lines.amount - (invoice_lines.amount * invoices.discount/100)) as amount\n\t\t\t\t\t\t\t, (invoices.amount_outstanding/invoices.amount) * (invoice_lines.amount - (invoice_lines.amount * invoices.discount/100)) as amount_outstanding\n\t\t\t\t\t\t\t, invoices.discount\n\t\t\t\t\t\t\t, invoices.invoice_id\n\t\t\t\t\t\t\t, invoices.number\n\t\t\t\t\t\t\t, invoices.matter\n\t\t\t\t\t\t\t, invoices.status\n\t\t\t\t\t\t\t, invoices.date\n\t\t\t\t\t\t\t, (CASE WHEN invoice_lines.person = '' OR invoice_lines.person IS NULL THEN 'no name found' ELSE invoice_lines.person END) as person\n\t\t\t\t\t\t\t, invoice_lines.type\n\t\t\t\t\t\tFROM invoice_lines\n\t\t\t\t\t\tLEFT OUTER JOIN invoices ON invoices.invoice_id = invoice_lines.invoice_id\n\t\t\t\t\t\t;\n\t\t\tSQL\n\n\t\tdbrows = @database.query <<-SQL\n\t\t\tCREATE OR REPLACE VIEW apportioned_invoices_grouped AS\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tapportioned_invoices.organization\n\t\t\t\t\t\t, apportioned_invoices.matter\n\t\t\t\t\t\t, apportioned_invoices.person\n\t\t\t\t\t\t, SUM((CASE WHEN apportioned_invoices.status <> 'draft' THEN apportioned_invoices.amount ELSE 0 END)) AS lifetime_billed\n\t\t\t\t\t\t, SUM((CASE WHEN YEAR(apportioned_invoices.date) = YEAR(NOW()) THEN\n\t\t\t\t\t\t\t(CASE WHEN apportioned_invoices.status <> 'draft' THEN apportioned_invoices.amount ELSE 0 END)\n\t\t\t\t\t\t\tELSE 0 END)) as ytd_billed\n\t\t\t\t\t\t, SUM((CASE WHEN apportioned_invoices.status = 'draft' THEN apportioned_invoices.amount ELSE 0 END)) as draft_invoices\n\t\t\t\t\t\t, SUM(unbilled_all_time.estimated) AS estimated\n\t\t\t\t\t\t, SUM((CASE WHEN apportioned_invoices.status <> 'draft' THEN apportioned_invoices.amount_outstanding ELSE 0 END)) as outstanding\n\t\t\t\t\tFROM apportioned_invoices\n\t\t\t\t\tLEFT OUTER JOIN unbilled_all_time ON apportioned_invoices.matter = unbilled_all_time.matter AND apportioned_invoices.person = unbilled_all_time.person\n\t\t\t\t\tGROUP BY apportioned_invoices.organization, apportioned_invoices.matter, apportioned_invoices.person;\n\t\t\t\t\t;\n\t\t\t\tSQL\n\n\t\t#UNBILLED ALL TIME WITH ORGS view\n\t\tdbrows = @database.query <<-SQL\n\t\t\t-- need to fix up matters\n\t\t\tCREATE OR REPLACE VIEW unbilled_all_time_with_orgs AS\n\t\t\t\t\tSELECT (CASE WHEN orgnames.organization <> '' THEN orgnames.organization ELSE 'unknown organization' END) as organization, unbilled_all_time.person, unbilled_all_time.matter, unbilled_all_time.estimated\n\t\t\t\t\tFROM unbilled_all_time\n\t\t\t\t\tLEFT OUTER JOIN orgnames ON orgnames.matter = unbilled_all_time.matter\n\t\t\t\t;\n\t\t\tSQL\n\n\t\tdbrows = @database.query <<-SQL\n\t\t\tCREATE OR REPLACE VIEW dashboard_detailed AS\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tapportioned_invoices_grouped.organization\n\t\t\t\t\t\t, apportioned_invoices_grouped.matter\n\t\t\t\t\t\t, apportioned_invoices_grouped.person\n\t\t\t\t\t\t, apportioned_invoices_grouped.lifetime_billed\n\t\t\t\t\t\t, apportioned_invoices_grouped.ytd_billed\n\t\t\t\t\t\t, apportioned_invoices_grouped.outstanding\n\t\t\t\t\t\t, apportioned_invoices_grouped.draft_invoices\n\t\t\t\t\t\t, (CASE WHEN unbilled_all_time_with_orgs.estimated IS NULL THEN 0 ELSE unbilled_all_time_with_orgs.estimated END) as estimated\n\t\t\t\t\t\t, (apportioned_invoices_grouped.lifetime_billed + apportioned_invoices_grouped.draft_invoices + (CASE WHEN unbilled_all_time_with_orgs.estimated IS NULL THEN 0 ELSE unbilled_all_time_with_orgs.estimated END)) as all_spend\n\t\t\t\t\tFROM apportioned_invoices_grouped\n\t\t\t\t\tLEFT OUTER JOIN unbilled_all_time_with_orgs ON unbilled_all_time_with_orgs.matter = apportioned_invoices_grouped.matter AND unbilled_all_time_with_orgs.person = apportioned_invoices_grouped.person\n\t\t\t\t\tUNION\n\t\t\t\t\t-- Find the other half of the FULL OUTER JOIN\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tunbilled_all_time_with_orgs.organization\n\t\t\t\t\t\t, unbilled_all_time_with_orgs.matter\n\t\t\t\t\t\t, unbilled_all_time_with_orgs.person\n\t\t\t\t\t\t, 0 as lifetime_billed\n\t\t\t\t\t\t, 0 as ytd_billed\n\t\t\t\t\t\t, 0 as outstanding\n\t\t\t\t\t\t, 0 as draft_invoices\n\t\t\t\t\t\t, unbilled_all_time_with_orgs.estimated\n\t\t\t\t\t\t, unbilled_all_time_with_orgs.estimated as all_spend\n\t\t\t\t\tFROM unbilled_all_time_with_orgs\n\t\t\t\t\tLEFT OUTER JOIN apportioned_invoices_grouped ON apportioned_invoices_grouped.matter = unbilled_all_time_with_orgs.matter AND apportioned_invoices_grouped.person = unbilled_all_time_with_orgs.person\n\t\t\t\t\tWHERE apportioned_invoices_grouped.matter IS NULL;\n\t\t\t\t;\n\t\t\tSQL\n\n\n\n\t\t\t#DASHBOARD view\n\t\t\tdbrows = @database.query <<-SQL\n\t\t\t\tCREATE OR REPLACE VIEW dashboard AS\n\t\t\t\t\tSELECT\n\t\t\t\t\t \torganization\n\t\t\t\t\t , matter\n\t\t\t\t\t , SUM(lifetime_billed) as lifetime_billed\n\t\t\t\t\t , SUM(ytd_billed) as ytd_billed\n\t\t\t\t\t , SUM(outstanding) as outstanding\n\t\t\t\t\t , SUM(draft_invoices) as draft_invoices\n\t\t\t\t\t , SUM(estimated) as estimated\n\t\t\t\t\t , SUM(all_spend) as all_spend\n\t\t\t\t\tFROM dashboard_detailed\n\t\t\t\t\tGROUP BY matter\n\t\t\t\t;\n\t\t\tSQL\n\tend", "def add_join(join)\n @clause[:final_join] = join.implicit_joins\n end", "def def_many_to_many(opts)\n super\n def_association_pks_getter(opts) do\n _join_table_dataset(opts).filter(opts[:left_key]=>send(opts[:left_primary_key])).select_map(opts[:right_key])\n end\n def_association_pks_setter(opts) do |pks|\n checked_transaction do\n ds = _join_table_dataset(opts).filter(opts[:left_key]=>send(opts[:left_primary_key]))\n ds.exclude(opts[:right_key]=>pks).delete\n pks -= ds.select_map(opts[:right_key])\n pks.each{|pk| ds.insert(opts[:left_key]=>send(opts[:left_primary_key]), opts[:right_key]=>pk)}\n end\n end\n end", "def fk_join_arr\n result = []\n groups.each_with_index do |group, idx|\n group_alias = \"#{group.parent_table}_#{idx}\"\n group_query = group_query_builder(group)\n result.push \"JOIN (\\n#{group_query}\\n\\t) AS #{group_alias}_fk\"\n result.push \"ON #{group_alias}_fk.#{FKEYS[group.parent_table]}=#{group.parent_table}.#{group.parent_table_pk}\"\n if idx > 0\n groups.each_with_index do |x_group, x_idx|\n #next if x_idx < idx\n x_group_alias = \"#{x_group.parent_table}_#{x_idx}\"\n result.push \"\\tAND #{x_group_alias}_fk.year = #{group_alias}_fk.year\"\n break\n end\n end\n end\n return result\n end", "def create\n if @db.table_info(METADATA_TABLE_NAME).empty?\n stmt = \"CREATE TABLE #{METADATA_TABLE_NAME} (key VARCHAR(1024), val VARCHAR(8192), env VARCHAR(255))\"\n @db.execute(stmt)\n end\n\n if @db.table_info(RUN_HISTORY_TABLE_NAME).empty?\n stmt = \"CREATE TABLE #{RUN_HISTORY_TABLE_NAME} (name VARCHAR(1024), outcome VARCHAR(16), env VARCHAR(255), time DATETIME)\"\n @db.execute(stmt)\n\n index_stmt = \"CREATE INDEX index_run_history ON #{RUN_HISTORY_TABLE_NAME} (time DESC)\"\n @db.execute(index_stmt)\n end\n\n if @db.table_info(DISABLED_MONITOR_TABLE_NAME).empty?\n stmt = \"CREATE TABLE #{DISABLED_MONITOR_TABLE_NAME} (name VARCHAR(1024), env VARCHAR(255))\"\n @db.execute(stmt)\n end\n\n if @db.table_info(MONITOR_INFO_TABLE_NAME).empty?\n stmt = \"CREATE TABLE #{MONITOR_INFO_TABLE_NAME} (name VARCHAR(1024), description VARCHAR(8192))\"\n @db.execute(stmt)\n end\n end", "def creatables(include_references: nil); end", "def prepare\n super\n\n # open the database.\n if File.exist?(@options['DATABASE'])\n @db = ::SQLite3::Database.open(@options['DATABASE'])\n else\n @db = ::SQLite3::Database.new(@options['DATABASE'])\n end\n @db.results_as_hash = true\n\n tables = @db.execute('SELECT name FROM sqlite_master WHERE type=\"table\" AND name=\"tblMessages\" ORDER BY name')\n if tables.length == 0\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblMessages (\n mID integer primary key,\n mStatus char(5),\n mTime datetime,\n mText varchar(255))\n )\n\n @db.execute( tbl_def )\n end\n\n tables = @db.execute('SELECT name FROM sqlite_master WHERE type=\"table\" AND name=\"tblOptions\" ORDER BY name')\n if tables.length == 0\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblOptions (\n oID integer primary key,\n oType varchar(255),\n oInstance varchar(255),\n oOption varchar(255),\n oValue TEXT)\n )\n\n @db.execute( tbl_def )\n end\n\n tables = @db.execute('SELECT name FROM sqlite_master WHERE type=\"table\" AND name=\"tblProcedures\" ORDER BY name')\n if tables.length == 0\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblProcedures (\n pID integer primary key,\n pTime datetime,\n pProc varchar(255))\n )\n\n @db.execute( tbl_def )\n\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblSteps (\n sID integer primary key,\n pID integer,\n sLabel varchar(255),\n sCommand TEXT,\n sFinal TEXT)\n )\n\n @db.execute( tbl_def )\n\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblParameters (\n pID integer primary key,\n sID integer,\n pLabel varchar(255),\n pValue varchar(255),\n pConstraint varchar(255))\n )\n\n @db.execute( tbl_def )\n\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblComparisons (\n cID integer primary key,\n pID integer,\n sID1 integer,\n sID2 integer,\n cRelationship varchar(255))\n )\n\n @db.execute( tbl_def )\n end\n\n tables = @db.execute('SELECT name FROM sqlite_master WHERE type=\"table\" AND name=\"tblResults\" ORDER BY name')\n if tables.length == 0\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblResults (\n rID integer primary key,\n rTime datetime,\n rTestId integer,\n rProc varchar(255),\n rProcId integer,\n rApp varchar(255))\n )\n\n @db.execute( tbl_def )\n\n tbl_def = %q( CREATE TABLE IF NOT EXISTS tblResultData (\n dID integer primary key,\n rID integer,\n dStep varchar(255),\n dStepId integer,\n dStatus varchar(255),\n dType varchar(255),\n dData TEXT)\n )\n\n @db.execute( tbl_def )\n end\n\n tables = @db.execute('SELECT name FROM sqlite_master WHERE type=\"view\" AND name=\"qryResults\" ORDER BY name')\n if tables.length == 0\n tbl_def = %q( CREATE VIEW IF NOT EXISTS qryResults AS\n SELECT R.rTestId As qTestId, R.rProc As qProc, R.rProcId As qProcId, R.rApp As qApp,\n D.dStep As qStep, D.dStepId As qStepId, D.dStatus As qStatus, D.dType As qType, D.dData As qData\n FROM tblResults As R, tblResultData As D\n WHERE D.rID = R.rID\n )\n\n @db.execute( tbl_def )\n\n tbl_def = %q( CREATE VIEW IF NOT EXISTS qryComparisons AS\n SELECT R.rTestId As qTestId, R.rProc As qProc, R.rProcId As qProcId, C.cRelationship As qRelationship,\n D1.dStep As qStep1, D1.dStepId As qStepId1, D1.dStatus As qStatus1, D1.dType As qType1, D1.dData As qData1,\n D2.dStep As qStep2, D2.dStepId As qStepId2, D2.dStatus As qStatus2, D2.dType As qType2, D2.dData As qData2\n FROM tblComparisons As C, tblResults As R, tblResultData As D1, tblResultData As D2\n WHERE C.pID = R.rProcID AND C.sID1 = D1.dStepId AND C.sID2 = D2.dStepId\n )\n\n @db.execute( tbl_def )\n end\n end", "def fetch_and_import!(opts={})\n eve_table = opts[:eve_table]\n dest_table = opts[:dest_table]\n mapping = opts[:mapping]\n dbh = opts[:conn] || @dbh\n comment_label = opts[:label]\n \n # Fetch Data from crpActivities Table\n results = dbh.query(\"SELECT * FROM \"+eve_table)\n # Clear Destination Table to eliminate Redundancy\n dest_table.camelize.constantize.delete_all\n # Do some Meta programming FU magic\n results.each do |row|\n insert_map = {}\n mapping.each do |key,value|\n insert_map[key.to_sym] = row[value]\n end \n dest_table.camelize.constantize.create!(insert_map)\n # Just so you see something when running this script..\n p \"Creating Record for #{dest_table} : \" + row[comment_label].to_s\n end\nend", "def CreateTables()\n\n #Products/Items .. Description of products\n @@db.execute \"CREATE TABLE IF NOT EXISTS Product(item_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL, desciption TEXT);\"\n\n #Inventory - to keep track of products currently in the store,\n @@db.execute \"CREATE TABLE IF NOT EXISTS Inventory(item_id INTEGER NOT NULL PRIMARY KEY,price NUMERIC NOT NULL,quantity INTEGER ,extraNotes TEXT);\"\n\n # customer's shopping cart... items that customer chose\n @@db.execute \"CREATE TABLE IF NOT EXISTS Basket(item_id INTEGER NOT NULL PRIMARY KEY, quantity INTEGER);\"\n end", "def create_lookuptable(id)\n\n params = Hash.new\n @basecase = Basecase.find(id) \n\n params[:lookup] = {\n \n name: @basecase.lookup_table(id),\n basecase_id: id\n }\n \n if @basecase.lookups.count < 1 \n\n @lookup = @basecase.lookups.build(params[:lookup]) \n if @lookup.save \n # this is just a dummy variable to do something in the loop\n a = 1\n end \n end\n\n end", "def add_piggy_back_sql_data!(reflection_name, prefix, table_alias, attributes, select, joins, conditions, join_type)\n ktn = table_name\n kpkey = primary_key\n reflection = reflections[reflection_name]\n atn = reflection.table_name\n attributes.each do |attr|\n if table_alias\n select << \", #{table_alias}.#{attr} AS #{prefix}_#{attr}\"\n else\n select << \", #{atn}.#{attr} AS #{prefix}_#{attr}\"\n end\n end\n fkey = reflection.primary_key_name\n fpkey = reflection.klass.primary_key\n\n case reflection.macro\n when :belongs_to\n if table_alias\n joins << \" #{join_type} JOIN #{atn} #{table_alias} ON #{table_alias}.#{fpkey}=#{ktn}.#{fkey} \"\n else\n joins << \" #{join_type} JOIN #{atn} ON #{atn}.#{fpkey}=#{ktn}.#{fkey} \"\n end\n when :has_one\n if table_alias\n joins << \" #{join_type} JOIN #{atn} #{table_alias} ON #{table_alias}.#{fkey}=#{ktn}.#{kpkey} \"\n else\n joins << \" #{join_type} JOIN #{atn} ON #{atn}.#{fkey}=#{ktn}.#{kpkey} \"\n end\n when :has_many\n raise \"piggy_back: aliasing not implemented for has_many\" if table_alias\n if reflection.options[:through]\n ttn = reflection.through_reflection.klass.table_name\n tkfkey = reflection.through_reflection.primary_key_name\n tafkey = reflection.source_reflection.primary_key_name\n\n through_conditions = reflection.options[:conditions] ?\n \" AND \" + reflection.options[:conditions] : \"\"\n source_conditions = reflection.through_reflection.options[:conditions] ?\n \" AND \" + reflection.through_reflection.options[:conditions] : \"\"\n\n joins << \" LEFT JOIN #{ttn} ON (#{ttn}.#{tkfkey}=#{ktn}.#{kpkey}#{through_conditions})\"\n joins << \" LEFT JOIN #{atn} ON (#{ttn}.#{tafkey}=#{atn}.#{fpkey}#{source_conditions}) \"\n else\n reflection_conditions = reflection.options[:conditions] ?\n \" AND \" + reflection.options[:conditions] : \"\"\n\n joins << \" LEFT JOIN #{atn} ON (#{atn}.#{fkey}=#{ktn}.#{kpkey}#{reflection_conditions}) \"\n end\n else\n raise \"can't piggy back #{reflection.macro} on class #{klass}\"\n end\n end", "def scaffold_reflection_merge(reflection, from, to)\n if reflection.class == DataMapper::Associations::OneToMany::Relationship\n foreign_key = get_key_array_safe(reflection.target_key).name\n table = reflection.target_model\n elsif reflection.class == DataMapper::Associations::ManyToMany::Relationship\n foreign_key = get_key_array_safe(reflection.through.child_key).name\n table = reflection.send(:through_model)\n else\n return\n end\n table.all(foreign_key => from).update(foreign_key => to)\n end", "def create_table_structure(columns_to_include)\n if @table_created\n @columns.each do |column|\n begin\n ActiveRecord::Schema.add_column(@new_table_name, column[:name], column[:type]) if (columns_to_include.blank? or columns_to_include.include? column[:name])\n rescue\n puts \"Couldnt add field #{column[:name].downcase}\"\n end\n end\n ActiveRecord::Schema.add_column(@new_table_name,\"the_geom\", :geometry,:null => false)\n ActiveRecord::Schema.add_index(@new_table_name,\"the_geom\",:spatial => true)\n end\n end" ]
[ "0.6556048", "0.6534441", "0.6457511", "0.6235183", "0.6114938", "0.6044283", "0.5942229", "0.5807729", "0.58055997", "0.5781895", "0.57558334", "0.5721014", "0.571776", "0.5715381", "0.5669762", "0.566083", "0.5571541", "0.55399054", "0.55355793", "0.55269796", "0.5503767", "0.5503427", "0.5499425", "0.5497307", "0.54875416", "0.54850745", "0.54570514", "0.54482573", "0.5439006", "0.5435462", "0.5424884", "0.5410058", "0.5399184", "0.5398745", "0.5396694", "0.5396694", "0.53735423", "0.5373384", "0.53671265", "0.5356454", "0.534565", "0.5309047", "0.53033775", "0.5299208", "0.5296577", "0.52680856", "0.5247265", "0.5247016", "0.52454", "0.52391547", "0.52356154", "0.52294374", "0.52254915", "0.52183956", "0.521809", "0.52169186", "0.52100015", "0.520642", "0.5198386", "0.5194699", "0.51852673", "0.51664925", "0.51650983", "0.5156504", "0.5156455", "0.51436573", "0.51436573", "0.5135014", "0.513185", "0.51181275", "0.5116296", "0.5113166", "0.51071256", "0.50941694", "0.50913596", "0.5084443", "0.5074645", "0.506969", "0.5064095", "0.50585824", "0.5058359", "0.50572133", "0.5051695", "0.50471675", "0.5040002", "0.5032345", "0.50292206", "0.50286925", "0.50274724", "0.502403", "0.50200474", "0.50187016", "0.5008199", "0.50020653", "0.50000155", "0.49988413", "0.49982584", "0.49975544", "0.4995127", "0.49945498" ]
0.65796465
0
This method can show the top best contracts depending on the number we want to show
def sort_contracts(how_many) return_array = [] contracts_sorted = join_table_gas_simulation_contracts.sort_by(&:savings).reverse how_many.times do |i| return_array << GasContract.find(contracts_sorted[i].gas_contract_id) rescue return_array end return_array end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def money_top(driver_sum)\n arr_money = driver_sum.map { |driver| driver[:total_money]}\n money_max = arr_money.max\n money_name = \"\"\n\n driver_sum.each do |item|\n if item[:total_money] == money_max\n money_name << item[:id] << \" \"\n end\n end\n\n money_result = [money_max, money_name]\n return money_result\nend", "def display_top(n: 3)\n draw \"Top #{n} sections:\"\n draw \"Top #{n} HTTP status:\"\n draw \"Top #{n} IPs:\"\n draw_eol\n clear_line\n\n sections = @queue.top_sections.first(n)\n statuses = @queue.top_status.first(n)\n ips = @queue.top_ips.first(n)\n\n n.times do |index|\n clear_line\n\n section, section_hits = sections[index]\n status, status_hits = statuses[index]\n ip, ip_hits = ips[index]\n\n draw \" %-19s %-10s\" % [section.to_s.empty? ? '/' : section, section_hits]\n status.nil? ? (draw '') : (draw \" #{status} #{status_hits}\" % [status, status_hits])\n ip.nil? ? (draw '') : (draw \" %-16s %s\" % [ip, ip_hits])\n\n draw_eol\n end\n end", "def top_ten\n reverse_sort = self.sort.reverse\n return reverse_sort[0, 10]\n end", "def list_top_coins\n # here doc - http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html\n puts <<-DOC.colorize(:cyan)\n ____ ____ ____ _________ ____ ____ ____ ____ ____ ____ _________ ____ ____ ____ ____ ____ ____\n ||T |||h |||e ||| |||C |||r |||y |||p |||t |||o ||| |||U |||p |||d |||a |||t |||e ||\n ||__|||__|||__|||_______|||__|||__|||__|||__|||__|||__|||_______|||__|||__|||__|||__|||__|||__||\n |/__\\|/__\\|/__\\|/_______\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/_______\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\||\n\n DOC\n\n puts \"Top 100 Cryptocurrencies By Market Capitalization\"\n puts \"\"\n puts \"Todays crypto update:\"\n puts \"-----------------\"\n puts \"| Coin (Symbol) |\"\n puts \"-----------------\"\n\n @coins = TheCryptoUpdate::Coin.all[0..99]\n\n @coins.each.with_index(1) do |coin, i|\n # puts \"#{i}. #{coin.name} (#{coin.symbol}) | $#{coin.volume_1d} | #{coin.volume_7d}% | #{coin.volume_30d}% |\"\n puts \"#{i}. #{coin.name} (#{coin.symbol})\"\n end\n\n end", "def top_ten\n Rails.cache.fetch('top_ten_resp', expires_in: 1.minutes) do\n conn = Faraday.new(url: @base_url) do |faraday|\n faraday.adapter(Faraday.default_adapter)\n end\n\n resp = conn.get do |req|\n req.url '/v1/cryptocurrency/listings/latest'\n req.headers['X-CMC_PRO_API_KEY'] = @api_key\n req.params['start'] = 1\n req.params['limit'] = 10\n req.params['convert'] = 'USD'\n req.params['sort'] = 'market_cap'\n req.params['sort_dir'] = 'desc'\n end\n\n raise 'Cannot parse response body' unless resp.body\n\n resp.body\n end\n end", "def show_most_popular\n @card_sets = CardSet.order(\"impressions_count DESC\")[0..19]\n end", "def output_driver_with_most_money(earned_per_each_driver)\n max_earned = earned_per_each_driver.max_by do |current_driver|\n current_driver[:driver_earned]\n end\n\n puts \"\\nDriver #{max_earned[:driver_id]} earned the most money $#{max_earned[:driver_earned]}.\"\nend", "def top(num = nil)\n temp = @user.scores.group(:sentence).sum(:val).sort_by{|_,v| -v}\n filter_by_num(temp, num)\n end", "def rate_top(driver_sum)\n arr_rate = driver_sum.map { |driver| driver[:aver_rate]}\n rate_max = arr_rate.max\n rate_name = \"\"\n\n driver_sum.each do |item|\n if item[:aver_rate] == rate_max\n rate_name << item[:id] << \" \"\n end\n end\n\n rate_result = [rate_max, rate_name]\n return rate_result\nend", "def rank_top_teams # DO NOT USE THIS METHOD, outdated, slow\n @top_teams = {}\n @top_teams = Score.in_challenge(self.id).teams_in_all_divisions.limit(5).\n order(\"sum_points DESC, MAX(#{Score.table_name}.\n earned_at) DESC\").sum(:points) \n return @top_teams\n end", "def getTop10AwesomePeeps\n @persons.sort!\n return @persons[-10..-1]\n end", "def personal_best\n personal_top_three.first\n end", "def return_cards_from_top(count)\n if cards and count > 0\n cards.where(\"card_order > ?\", (get_top_order-count) )\n end\n end", "def by_make_top(make, number)\n by_make(make).take(number)\n end", "def this_teams_top_players(number_of_players)\n \tnfl_players.order(:points).last(number_of_players)\n end", "def top_three_recipes\n recipe_cards.max_by(3) {|recipe_cards| recipe_cards.rating}\n end", "def get_top_order\n cards.maximum('card_order') || 0\n end", "def best_ask\n @asks.min_by { |x| x.fetch(:price) }\n end", "def best_fans\n @teams.max_by { |team| team.home_minus_away_percentage }.team_name\n end", "def top_ten\n sorted = @person_array.sort { |a, b| a.awesomeness <=> b.awesomeness }\n sorted.reverse!\n return sorted[0..9] if sorted.size >= 10\n return sorted\n end", "def top_5\n count = @sentence.blips.group(:body).distinct.count\n percent = count.each {|k, v| count[k] = v / @sentence.blips_count.to_f }\n statistics = percent.sort_by { |k, v| v }.reverse[0..4].flatten.each { |k, v| puts \"#{k}: #{v}\" }\n end", "def franchise_with_highest_profit\n company = get_company\n no_franchises(company)\n big_earner = company.franchises.max_by { |franchise| franchise.profit }\n puts \"Franchise #{big_earner.id} has the highest profit, having earned $#{big_earner.profit}.\"\n menu\n end", "def most_money(rideshare)\n highest_earned = 0.0\n high_earner = \"\"\n # call method from #2\n money_made(rideshare).map do |driver, cost|\n if cost > highest_earned\n highest_earned = cost\n high_earner = driver\n end\n end\n return high_earner\nend", "def biggest_investment\n self.funding_rounds.max_by do |round|\n round.startup.uniq \n end\n end", "def worst_clients(top: 5, timeframe: default_timeframe)\n clients_with_revenue_impact(timeframe: timeframe).order('revenue_impact asc').limit(top)\n end", "def top_bid\n bids(:bid_amount).max\n end", "def top_three_recipes\n self.find_user_recipe_cards.sort_by{|rcard| rcard.rating}.reverse![0..2]\n end", "def best(n)\n @score.sort{|a,b| b[1][0] <=> a[1][0]}[0..n-1]\n end", "def personal_top_three\n scores.max([scores.length, 3].min)\n end", "def top_5_teams\n team_names = []\n teams = UserTeam.all.collect{|team| team.team_id}\n most_common_value = teams.uniq.sort_by{ |i| teams.count( i ) }.reverse[0..4]\n most_common_value.each do |team|\n team_names << get_team_name_by_id(Team.find(team).api_team_id)\n end\n team_names\nend", "def show_top_beers\n voted_beers = Beer.where(state_id: params[:stateId])\n ordered_ten = voted_beers.sort_by { |b| b['votes'] }.reverse.slice(0, 10)\n top_arr = []\n ordered_ten.each do |b|\n top_arr << BreweryDb::ShowVotes.new(b.beer_id, b.votes).results\n end\n render json: top_arr\n end", "def top(number)\n 1.upto(number) { |count| puts ('*' * count).center(number) if count.odd? }\nend", "def topn_by_downloads (keyinfo, n)\n topn_by_downloads = keyinfo.sort_by{ |x| x[:total_downloads] }.reverse.slice(0 .. n-1)\n top_table topn_by_downloads\nend", "def best\n @best = User.find_paginated_best_bands_and_deejays :page => params[:page], :per_page => 3\n render :partial => 'best'\n end", "def top_books\n if orders.empty?\n puts \"There are not orders...\"\n else\n @orders.group_by(&:book).values.max_by(&:size).first.book\n end\n end", "def top_vuln_graph(limit=10)\n\t\t\t\t\tg = Gruff::Bar.new(GRAPH_WIDTH)\n\t\t\t\t\tg.title = sprintf \"Top 10 Hosts with Notable Findings Count\"\n\t\t\t\t\tg.sort = false\n\t\t\t\t\tg.marker_count = 1\n\t\t\t\t\tg.theme = {\n\t\t\t\t\t\t:colors => Risu::GRAPH_COLORS,\n\t\t\t\t\t\t:background_colors => %w(white white)\n\t\t\t\t\t}\n\n\t\t\t\t\tItem.risks_by_host(limit).to_a.each do |item|\n\t\t\t\t\t\tip = Host.find_by_id(item.host_id).name\n\t\t\t\t\t\tcount = Item.where(:host_id => item.host_id).where(:severity => 4).size\n\n\t\t\t\t\t\tif count > 0\n\t\t\t\t\t\t\tg.data(ip, count)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\tStringIO.new(g.to_blob)\n\t\t\t\tend", "def best_customers\n Invoice.where(merchant_id: self.id)\n .joins(:transactions, :customer)\n .select('customers.*, count(transactions) as most_success')\n .where('transactions.result = ?', 0)\n .group('customers.id')\n .order('most_success desc')\n .limit(5)\n end", "def top_5\n company_impressions = Impression.where(\n \"created_at > ? AND created_at < ? AND action_name = ? AND controller_name = ?\",\n 1.weeks.ago.to_date.at_beginning_of_day,\n Date.today.tomorrow.at_beginning_of_day,\n 'stat_show',\n 'companies'\n )\n\n company_ids = company_impressions.map{ |si| si.impressionable_id }\n company_id_counts = Hash.new(0)\n company_ids.each{|si| company_id_counts[si] += 1}\n company_id_counts.sort_by {|key, value| value}\n\n # Order company_id_counts by count\n sortable = company_id_counts.map{|k, v| [v, k]}\n sortable.sort!.reverse!\n\n companies = sortable.map{ |count, id| Company.find(id) }\n\n ok_companies = []\n companies.each do |s|\n if s.all_departments.map(&:id).include? current_user.department_id\n ok_companies.push(s)\n end\n end\n\n ok_companies.each { |s| s.stat_count = company_id_counts[s.id] }\n\n respond_with ok_companies[0..4]\n end", "def bestCand(voterOpinion, candList)\r\n\ttopCands = Array.new # []\r\n\ttopScore = nil\r\n\t\r\n\t# for each element in the candList array, calling the current element cand.\r\n\t#\tthe {/} are the same as the do/end shown in the Main section. \r\n\t#\tIncluded here to show the availabailty for different style choices\r\n\tcandList.each { |cand| \r\n\t\t\t\t\tcurrScore = getCandScore(voterOpinion,cand.drop(1))\r\n\t\t\t\t\tif topScore.nil? then\r\n\t\t\t\t\t\ttopScore = currScore\r\n\t\t\t\t\tend\r\n\t\t\t\t\tunless currScore < topScore # essentially if !(currScore < topScore)\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif currScore == topScore\r\n\t\t\t\t\t\t\ttopCands.push(cand[0])\r\n\t\t\t\t\t\telse # must be greater\r\n\t\t\t\t\t\t\ttopScore = currScore\r\n\t\t\t\t\t\t\ttopCands = [cand[0]]\r\n\t\t\t\t\t\tend\r\n\t\t\t\t\tend\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\treturn topCands\r\nend", "def top_10_table(output)\n\t\t\t\t\theaders = [\"Description\", \"Count\"]\n\t\t\t\t\theader_widths = {0 => (output.bounds.width - 50), 1 => 50}\n\n\t\t\t\t\tdata = top_10_sorted\n\n\t\t\t\t\toutput.table([headers] + data[0..9], :header => true, :column_widths => header_widths, :width => output.bounds.width) do\n\t\t\t\t\t\trow(0).style(:font_style => :bold, :background_color => 'cccccc')\n\t\t\t\t\t\tcells.borders = [:top, :bottom, :left, :right]\n\t\t\t\t\tend\n\t\t\t\tend", "def stockRankings(stat)\n stock_count = {} #Hash to store Product Name and Stock Units\n @@products.each { |p| stock_count [p.units] = p.name } \n\n if stat == \"max\"\n pnames = []\n stock_count.keys.sort!.last(3).each { |count| pnames << stock_count[count] }\n\n puts \"\\n Please find below Product Details for Top-3 Products with maximum units in Stock : \"\n pnames.reverse.each { |pname| getProdbyName(pname) }\n elsif stat == \"min\"\n pnames = [] \n stock_count.keys.sort!.first(3).each { |count| pnames << stock_count[count] }\n\n puts \"\\n Please find below Product Details for Top-3 Products with minimum units in Stock : \"\n pnames.each { |pname| getProdbyName(pname) }\n end\n end", "def top_10_sorted\n\t\t\t\t\traw = notable_order_by_cvss_raw\n\t\t\t\t\tdata = Array.new\n\n\t\t\t\t\traw.each do |vuln|\n\t\t\t\t\t\trow = Array.new\n\t\t\t\t\t\tplugin_id = vuln[0]\n\t\t\t\t\t\tcount = vuln[1]\n\n\t\t\t\t\t\tname = scrub_plugin_name(Plugin.find_by_id(plugin_id).plugin_name)\n\n\t\t\t\t\t\trow.push(name)\n\t\t\t\t\t\trow.push(count)\n\t\t\t\t\t\tdata.push(row)\n\t\t\t\t\tend\n\n\t\t\t\t\tdata = data.sort do |a, b|\n\t\t\t\t\t\tb[1] <=> a[1]\n\t\t\t\t\tend\n\n\t\t\t\t\treturn data\n\t\t\t\tend", "def index\n @items = Item.all\n @items = @items.select {|item| item.owner_id != current_user.id}\n @top = @items.max(3) {|item1, item2| item1.purchased <=> item2.purchased}\n @sale = @items.select {|item| item.on_sale }\n\n end", "def biggest_investment()\n funding_rounds = self.funding_rounds.select {|funding| funding.amount}\n amount = 0\n\n funding_rounds.select do |funding|\n\n if funding.amount >= amount\n amount = funding.amount\n funding\n end\n \n end\n end", "def top_10_fans\n users_array = UserTeam.all.collect{|user| user.user_id}\n most_common_value = users_array.uniq.sort_by{ |i| users_array.count( i ) }.reverse\n biggest_fans = most_common_value.map {|user| User.find(user).name}[0..9]\n users_teams_count = most_common_value.map {|user| User.find(user).teams.count}[0..9]\n counter = 0\n return_hash = {}\n until counter == biggest_fans.length do\n return_hash[biggest_fans[counter].to_s] = users_teams_count[counter].to_s\n counter += 1\n end\n return_hash\nend", "def best_coin(default_list=[])\r\n\r\n list = if default_list.empty? then\r\n self.coin_names(limit: 5)\r\n else\r\n default_list\r\n end\r\n \r\n a2 = list.map {|x| [x, btc_gain(x)]}\r\n a2.max_by {|x| x[1].last} \r\n end", "def top(num)\n @top = num\n self\n end", "def best_offense\n @teams.max_by { |team| team.average_goals_scored }.team_name\n end", "def most_expensive_player_on_team \n\n the_club = choose_club #user chooses club they want to see most expensive player for\n my_club = Club.find_by(name: the_club) #use class instance find_by to find the instance of club with the name provided by user (the_club)\n club_players = my_club.players.sort_by do |player| #loops through instance of club and sorts the players by their market value (remember to change market_value from string to integer)\n player.market_value.to_i\n end\n\n most_expensive_player = club_players.last #in ascending order the last item of the sorted array is the player with the highest market value\n puts \"#{the_club}'s most expensive player is #{most_expensive_player.name}. He is worth £#{most_expensive_player.market_value}M\"\n #the_club --> user choice of club name\n #most_expensive_player.name --> use the_club name to find the specific instance of Club class. \n #Use \".players\" method to find all player instances of that specifc club (the instances of players that \n #belong to that instance of club). Use \".name\" method to retrieve attribute \"name\" of player instance. \n #Use \".market_value\" to retrieve attribute \"market_value\" of the player instance. \n\nend", "def top_three_recipes\n recipes_sorted_by_rating.reverse[0..2]\n end", "def top_students(grade_hash, number_of_students)\n scores = averages(grade_hash)\n shortlist = scores.sort_by{|k,v| v}.reverse.take(number_of_students)\n names = shortlist.map{|k,v| k}\nend", "def top_three_recipes\n my_recipes = self.recipe_cards\n my_recipes.sort{|a, b| b.rating <=> a.rating }.slice(0,3)\n end", "def top\n cards.first\n end", "def top_three_recipes\n top_three = RecipeCard.all.select {|atr| atr.user == self}\n top_three.sort_by {|atr| atr.rating}.reverse\n top_three[0..2]\n end", "def top_readers\n hash = @orders.inject(Hash.new(0)) do |count, order|\n count[order.reader.name] += 1\n count\n end\n top = hash.max_by { |key, value| value }.first\n puts \"Active reader is: #{top}\"\n end", "def top_three_recipes\n top_three_cards = recipe_cards.sort_by { |card| card.rating}.reverse.slice(0, 3)\n top_three_cards.map { |c| c.recipe }\n end", "def top10(url)\n\t\tlista=recorre(url)\n\t\tfor i in 1..10\n\t\t\tdatos(lista[i][0])\n\t\tend\n\tend", "def top_three_recipes \n a = recipes.sort_by do |i| \n i.rating \n end \n a[-3..-1]\n end", "def top_ten_list(category)\n # Select all of category from work instances\n work_by_category = Work.all.select { |work| work.category.downcase == \"#{category}\" }\n # Return max by vote count for top 10\n return work_by_category.max_by(10) { |work| work.votes.length }\n end", "def show\n\n tempList = Array.new\n @course.knowledges.each do|k|\n tempList = tempList << k.id \n end\n \n @best_list = Array.new\n len = tempList.size\n for i in 0..len-1\n max = tempList[0];\n tempLen = tempList.size\n for j in 0..tempLen-1\n if Knowledge.find((tempList[j])).good > Knowledge.find(max).good\n max = tempList[j]\n end\n end\n @best_list = @best_list << Knowledge.find(max)\n tempList.delete(max)\n end\n\n end", "def driver_with_highest_income(all_rides)\n all_income = total_income_per_driver(all_rides)\n highest_income = all_income.values.max\n driver = all_income.key(highest_income)\n puts \"#{driver} made the most money, earning $#{'%.2f' % highest_income}\"\nend", "def visible_scrapers(heights)\n max = 0\n r = 0\n heights.each do |item|\n if item > max\n r += 1\n max = item\n end\n end\n r\nend", "def visible_scrapers(heights)\n max = 0\n r = 0\n heights.each do |item|\n if item > max\n r += 1\n max = item\n end\n end\n r\nend", "def top_largest_houses\n# user selects how many houses they want to see\n# method outputs top x number of houses (by size)\n start_and_end_of_output\n prompt = TTY::Prompt.new\n puts \" How many houses do you want to see?\"\n puts \" \"\n input = prompt.ask(\" Input a number between 1 and 50:\").to_i\n\n ordered_houses = House.all.sort_by do |house|\n split_string_array(house.swornMembers).count\n end.reverse\n\n start_and_end_of_output\n puts \" Top #{input} Largest Houses:\"\n puts \" \"\n i = 1\n ordered_houses[0..input-1].map do |house|\n puts \" #{i}. #{house.name} - #{split_string_array(house.swornMembers).count} members\"\n i += 1\n end\n start_and_end_of_output\n\n input = see_more_house_details?\n if input.include?(\"Y\")\n find_info_of_house\n elsif input.include?(\"N\")\n\n input = return_menu?\n if input.include?(\"1\")\n top_largest_houses\n elsif input.include?(\"2\")\n character_menu_select\n elsif input.include?(\"3\")\n house_menu_select\n end\n\n end\nend", "def least_popular_venue\n venues = @games.group_by { |game| game.venue}\n venues.min_by { |venue, games| games.count }.first\n end", "def top_10 (matches)\n matches.sort_by! { |match| match['score'] }.reverse[:10]\nend", "def biggest_investment\n big_investment = 0\n big_round = {}\n self.funding_rounds.each do |funding_round|\n if funding_round.investment > big_investment\n big_investment = funding_round.investment\n big_round = funding_round\n end\n end\n big_round\n end", "def top_three_recipes\n sorted_recipe_cards = self.recipe_cards.sort do |recipe_card|\n recipe_card.rating end\n if sorted_recipe_cards.length < 3\n sorted_recipe_cards\n else\n sorted_recipe_cards[-3,3]\n end\n end", "def how_orders_of_three_most_popular_books\n books_count.each {|title, times| puts \"The most popular books, '#{title}', ordered #{times}\" if times == books_count.values.max }\n end", "def top_three_recipes\n self.recipes.sort_by {|info| info.rating}.pop(3)\n end", "def highest_possibility_price( possibilities )\n highest_price_index = 0\n highest_total = Money.new(0)\n\n initial = Money.new(0)\n possibilities.each_with_index do |possibility, index|\n\n total = possibility.inject(initial) { |sum, n| sum + n.price }\n if total > highest_total\n highest_total = total\n highest_price_index = index\n end\n\n end\n return highest_total, possibilities[ highest_price_index ]\n end", "def best_invoice_by_revenue\n @engine.invoices.all.max_by do |invoice|\n inv_items = find_inv_items_from_paid_in_full_invoices([invoice])\n find_total_revenue_for_inv_items(inv_items)\n end\n end", "def find_top\n @result_sets.each do |set|\n check set.results.first\n end\n end", "def top_numbers?\n true\n end", "def top_10_requests\n \"|| Volume || Count || Request ||\\n\" +\n top(:request).map { |bytes, count, request|\n \"| #{'%.1f' % (bytes / 1024.0 / 1024.0)} MB \" +\n \"| #{count} | #{request} |\\n\"\n }.join\n end", "def top_three\n @top_3 = User.order('win_percentage DESC').limit(3)\n render json: { data: @top_3 }.to_json\n end", "def best_leaveit_card(leave_it)\r\n @log.debug(\"calculate best_leaveit_card\") \r\n w_cards = []\r\n leave_it.each do |card_lbl|\r\n card_s = card_lbl.to_s # something like '_Ab'\r\n segno = card_s[2,1] \r\n\r\n curr_w = 0\r\n curr_w += 200 if card_s[2] == @briscola.to_s[2]\r\n curr_w += 500 if card_s[1] == \"A\"[0]\r\n curr_w += 400 if card_s[1] == \"3\"[0] \r\n curr_w += 300 if card_s[1] == \"R\"[0] \r\n curr_w += 280 if card_s[1] == \"C\"[0] \r\n curr_w += @deck_info.get_card_info(card_lbl)[:rank]\r\n\r\n w_cards << [card_lbl, curr_w ]\r\n end\r\n min_list = w_cards.min{|a,b| a[1]<=>b[1]}\r\n @log.debug(\"Best card to play on leave it cards is #{min_list[0]}, w_cards = #{w_cards.to_s}\")\r\n return min_list[0]\r\n end", "def top(num)\n @mut.synchronize{@array.sort!.reverse.take(num)}\n end", "def best_bid\n @bids.max_by { |x| x.fetch(:price) }\n end", "def percent_high_ranking\n high = 0.0\n low = 0.0\n cards.each do |card|\n if card.rank >= 11\n high += 1\n else\n low += 1\n end\n end\n (high * 100 / (high + low)).ceil(2)\n end", "def get_top_news(start=0,count=TopNewsPerPage)\n numitems = $r.zcard(\"news.top\")\n news_ids = $r.zrevrange(\"news.top\",start,start+(count-1))\n result = get_news_by_id(news_ids,:update_rank => true)\n # Sort by rank before returning, since we adjusted ranks during iteration.\n return result.sort_by(&:rank), numitems\nend", "def top_three_recipes\n\t\trecipes.select { |recipe| recipe.rating }.sort_by { |recipe| recipe.rating }.last(3)\n\tend", "def top_students(grade_hash, number_of_students)\n averages(grade_hash).sort_by { |k, v| v}.reverse.map{ |k, v| k }.take(number_of_students)\nend", "def most_points_scored\n max = nil\n name = nil \n game_hash.each do |team, team_values|\n team_values[:players].each do |player|\n if max == nil || player[:points] > max\n max = player[:points]\n name = player[:player_name]\n end\n end\n end\n name\nend", "def top_id\r\n (index - (index < @switch_max ? 0 : @switch_max)) * 10 + 1\r\n end", "def top_matches(preferences, person, limit = 5)\n scores = preferences.map {|pref| [sim_pearson(preferences, person, pref[0]), pref[0]] unless pref[0] == person}.compact\n scores.sort! {|a,b| b[0] <=> a[0]}\n return scores[0...limit]\nend", "def top_students(grade_hash, number_of_students)\n averages = averages(grade_hash)\n\n result = averages.sort_by do |key, value|\n value\n end\n\n students = result.map do |key, value|\n key\n end\n\n non_reversed = students.last(number_of_students)\n\n reversed = non_reversed.reverse\nend", "def index\n @morts = Mort.all_with_total\n # render plain: Mort.top5_oldest\n end", "def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end", "def biggest_investment\n biggest_amount = 0\n funding_instance = 0\n\n funding_rounds.map do |funding| \n if funding.investment > biggest_amount\n biggest_amount = funding.investment\n funding_instance = funding\n end\n end\n\n funding_instance\n end", "def highest_priced_options\n possibilities = possibilites_matrix\n ( highest_total, highest_possibilities ) = highest_possibility_price( possibilities )\n end", "def print_most_common_nationalities\n self.most_common_nationalities_list.map do |nationality|\n if nationality[1] > 1\n puts \"#{nationality[1]} players from #{nationality[0]}\"\n else\n puts \"#{nationality[1]} player from #{nationality[0]}\"\n end\n end\n \"These are the most common nationalities for #{self.home_team_name} v #{self.away_team_name}.\"\n end", "def top\n @game_records = GameRecord.all\n @game_scores = Array.new()\n game_score = Array.new()\n for record in @game_records\n game_score = [record.name, record.get_total_score]\n @game_scores << game_score\n end\n @game_scores = @game_scores.sort_by{|s| s[1]}\n @game_scores = @game_scores.reverse\n @game_scores = @game_scores[0, 10]\n respond_to do |format|\n format.js\n end\n end", "def percent_high_ranking\n\n count_high = 0\n\n cards.each do |card|\n\n if card.rank >= 11\n count_high += 1\n end\n\n end\n\n\n count_high_f = count_high.to_f\n count_total = cards.length\n count_total_f = count_total.to_f\n\n (100 * (count_high_f/count_total_f)).round(2)\n\n end", "def biggest_bust(seasonasstring)\n #get all teams in data\n #find all games played by team in season - given by arg\n #get subset of 95 where p is in season marker\n #count games won in subset on 95 / total games in subset on 95\n #get subset of 85 where r is in season marker\n #count games won in subset on 98 / total games in subset on 98\n #result of line 97 - line 99\n #find highest number\n #return team name of result of line 101\n end", "def find_best_score(total_per_player)\n best_score = 0\n winner = ''\n total_per_player.each do |player_name,total|\n\n if total > best_score\n best_score = total\n winner = player_name\n end\n end\n return winner\n end", "def biggest_investment\n funding_rounds.max_by {|funding_round| funding_round.investment}\n end", "def list_top_players\n if @highscore_list.empty?\n puts \"No available data.\"\n else\n table = TTY::Table.new header: ['Name', 'Score']\n @highscore_list.each do |player|\n table << [player.name, player.score]\n end\n\n finalTable = table.render :unicode do |renderer|\n renderer.alignments = [:left, :center]\n renderer.border.separator = :each_row\n end\n\n puts \"Sets Current Highscore\"\n puts finalTable\n end\n \n end", "def biggest_investment\n investment_arr = self.funding_rounds.collect do |f|\n f.investment\n end\n investment_arr.max_by do |i|\n i\n end\n end", "def show\n @clitems = Clitem.order(\"number ASC\").page(params[:page]).per_page(1)\n\n\n end" ]
[ "0.6581193", "0.6335129", "0.6146729", "0.6145433", "0.61236113", "0.6091667", "0.606354", "0.6054245", "0.60077995", "0.5996436", "0.59670955", "0.5957648", "0.5940633", "0.5919165", "0.5895838", "0.5876413", "0.5863333", "0.5850707", "0.5848036", "0.58316904", "0.5827998", "0.5812127", "0.58070034", "0.5806797", "0.5798982", "0.5788784", "0.577806", "0.5769342", "0.57650155", "0.5758486", "0.57234734", "0.57162005", "0.57125616", "0.57056785", "0.5700527", "0.569996", "0.56936544", "0.5686096", "0.56753737", "0.5673645", "0.5666701", "0.5663188", "0.56545067", "0.5653936", "0.5633432", "0.5631085", "0.5630408", "0.56186837", "0.56151825", "0.56007504", "0.5600244", "0.5586875", "0.5576179", "0.5574462", "0.5566697", "0.5564785", "0.5552527", "0.55492985", "0.5546335", "0.5530603", "0.5520493", "0.55124986", "0.55124986", "0.5509838", "0.5509152", "0.55037487", "0.5502461", "0.5481944", "0.5477835", "0.5476415", "0.5473695", "0.5461702", "0.54592586", "0.5431994", "0.5425963", "0.5423091", "0.54133654", "0.5411723", "0.5411531", "0.5406042", "0.5403207", "0.5395019", "0.53900117", "0.5380845", "0.5375218", "0.5373642", "0.5372623", "0.53691655", "0.53678715", "0.53673375", "0.5367176", "0.5363372", "0.5361747", "0.5357531", "0.5357097", "0.5356993", "0.5351558", "0.5351198", "0.53510636", "0.5348332" ]
0.5441949
73
Estimate the consumption per habitant
def consumption_people(nb_residents) hash = { 1 => 1630, 2 => 2945, 3 => 4265, 4 => 5320, 5 => 6360 } if hash[nb_residents].nil? hash[5] + (nb_residents - 5) * 1000 else hash[nb_residents] end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fuel_consumption(tank)\n return self.mass_flow_rate / tank.fuel_density\n end", "def fuel_efficiency\n ((mileage - predecessor.mileage) / liter).round(1) if predecessor\n end", "def profit_calculation\r\n @total_profit = @cocktail_profit + @beer_profit + @water_profit\r\n end", "def profit_per_mwh_electricity\n production_mwh = production(:mwh)\n return nil if production_mwh.zero?\n\n profit / production_mwh\n end", "def energyEfficiency()\n\t\t\t\t\"Carbs \" + carbsPercent().round(2).to_s + \"%,\\nProteins \" + proteinsPercent().round(2).to_s + \"%\\nLipids \" + lipidsPercent().round(2).to_s + \"%\\n\"\n\t\t\tend", "def perfect_material_efficiency\n (0.02 * self.blueprint.waste_factor * quantity).ceil\n end", "def tot_current_benefit\n if self != nil && self.current_package != nil && self.current_package.calc_hourly_benefit != nil\n (self.calc_tot_hours * self.current_package.calc_hourly_benefit * 100.0).round / 100.0\n else\n 0.00\n end\n # check ?\n # ( @employee_benefit[\"deposit\"] -\n # ( @employee_benefit[\"monthly_benefit\"] - @employee_benefit[\"tot_deposits_made\"] )\n # ) > 0.005\n end", "def estimated_consumption(cr)\n total = 0\n # If real consumption equals zero, try to estimate\n if cr == 0\n # Only estimates if there is an incidence that requires estimating\n if ReadingIncidence.reading_should_be_estimated(self.id)\n # 1. Consumption invoiced in the same period of last year (reading_2)\n total = consumption_invoiced(reading_2)\n if total == 0\n # 2. Consumption invoiced in the last period (reading_1)\n total = consumption_invoiced(reading_1)\n if total == 0\n # 3. Average consumption of...\n invoice_date = billing_period.try(:prebilling_starting_date) || Date.today\n # 3.1. ...the last 36 months of reading\n from_date = invoice_date - 36.months\n total = consumption_previous_readings(from_date, invoice_date)\n if total == 0\n # 3.2. ...the last 12 months of reading\n from_date = invoice_date - 12.months\n total = consumption_previous_readings(from_date, invoice_date)\n if total == 0\n # 4. Nominal capacity of the meter x 15 hs x quantity of months\n nominal_flow = meter.caliber.nominal_flow rescue 1.5\n nominal_flow = 1.5 if nominal_flow.blank?\n total = (nominal_flow * 15) * billing_frequency.total_months\n end # 3.2\n end # 3.1\n end # 2\n end # 1\n end # ReadingIncidence.reading_should_be_estimated(self.id)\n else # If real consumption not equals zero, try to compensate\n total = estimated_consumption_with_cr(cr)\n end # cr == 0\n total || 0\n end", "def compute_actual\n line[1] = @ho_form.line['sqft']\n line[2] = @ho_form.line['total_sqft']\n line[3] = (line[1] * 100.0 / line[2]).round(2)\n\n line['4/gross_inc'] = gross_income\n\n # We make a simplifying assumption that (1) every Home Office Expense\n # applies to every Home Office form, and (2) all expenses are indirect.\n categorize_records('Home Office Expense')\n #\n # We assume that the home office using the actual method is being rented and\n # thus there are no mortgage payments or such on it.\n #\n #fill_for_categories(self, '5b', 'Casualty_Losses')\n #fill_for_categories(self, '6b', 'Mortgage_Interest')\n #fill_for_categories(self, '7b', 'Real_Estate_Taxes')\n\n line['8b'] = sum_lines('5b', '6b', '7b')\n line[9] = (line['8b'] * line[3] / 100.0).round\n line[10] = line[9]\n\n line[11] = other_business_expenses\n\n line[12] = sum_lines(10, 11)\n line['13/ho_max_ded'] = line[4] - line[12]\n\n fill_for_categories(self, '16b', 'Insurance')\n fill_for_categories(self, '17b', 'Rent')\n fill_for_categories(self, '18b', 'Repairs')\n fill_for_categories(self, '19b', 'Utilities')\n fill_other_categories(\n self, '20b', continuation: 'Other Home Office Expenses'\n )\n line['21b'] = sum_lines(*%w(14b 15b 16b 17b 18b 19b 20b))\n line[22] = (line['21b'] * line[3] / 100.0).round\n\n # Assume no carryover for line 23\n line['24/ho_ded'] = sum_lines('21a', 22, 23)\n line[25] = [ line[13], line[24] ].min\n line[26] = line[13] - line[25]\n\n # Assume no casualty losses or depreciation for lines 27-29 and 33\n line[30] = sum_lines(27, 28, 29)\n line[31] = [ line[26], line[30] ].min\n line[32] = sum_lines(10, 25, 31)\n\n line[33] = BlankZero\n line['34/ho_expenses'] = line[32] - line[33]\n\n end", "def estimate_fiat_profit\n open_positions.sum(:amount) - positions_balance_amount\n end", "def fuel_per_hour\n 10\n end", "def calc_spirit_defense\n features_sum(:spirit_defense)\n end", "def estimate_fiat_profit\n positions_balance_amount - open_positions.sum(:amount)\n end", "def defense\n total_for(:defense)\n end", "def cost\n @beverage.cost\n end", "def estimated_profit\n day_rate = avg_rate_card_amount_cents.round(2)\n mins_tracked = Timing.minute_duration_submitted_for_client(id)\n days_tracked = (mins_tracked.to_s.to_d / account.account_setting.working_day_duration_minutes).round(2)\n\n task_estimate_mins = Task.total_estimated_minutes_for_client(id)\n task_estimate_days = (task_estimate_mins.to_s.to_d / account.account_setting.working_day_duration_minutes).round(2)\n\n ((task_estimate_days * day_rate.to_s.to_d) - (days_tracked * day_rate.to_s.to_d)).round(2)\n end", "def profit\n revenue - total_costs\n end", "def total_demand_for_electricity\n final_demand_for_electricity +\n non_final_demand_for_electricity +\n electricity_losses_if_export_is_zero\n end", "def calories_per_liter\n 672\n end", "def benefits\n self.ticket_price * self.spectators\n end", "def calc_calorie\n self.ingredients.map {|x| x.calories * x.qty }.sum\n end", "def energy_balance\n dataset.energy_balance\n end", "def cost\n @beverage.cost + 0.15\n end", "def value\n (\n 0.7 * (annual_income / average_income) +\n 0.3 * (base_manpower / avearge_manpower)\n ).round(6)\n end", "def cost\n @beverage.cost + 0.20\n end", "def vac_fuel_consumption(tank)\n return self.vac_mass_flow_rate / tank.fuel_density\n end", "def tot_deposits_made\n Rails.logger.debug(\"*** tot_deposits_made\")\n # note cannot use database sum because big_deposit is not native to database\n dep_result = 0.0\n EmployeeBenefit.where(\n \"employee_id = ? and eff_month = ? and eff_year = ? and deposited_at IS NOT NULL\",\n self.employee_id.to_s,\n self.eff_month.to_s,\n self.eff_year.to_s\n ).each do |eb|\n dep_result += round_money(eb.deposit)\n end\n Rails.logger.debug(\"*** dep_result: #{dep_result.inspect}\")\n return dep_result\n end", "def estimate_crypto_profit\n close_positions.sum(:quantity) - quantity\n end", "def profitability\n # based on \n # @pools.map { |p| }.sum\n end", "def cost\n @beverage.cost + 0.10\n end", "def cost\n @beverage.cost + 0.10\n end", "def estimate_crypto_profit\n quantity - close_positions.sum(:quantity)\n end", "def fuel_efficiency(attrs = {})\n d = estimate(:distance, attrs)\n f = estimate(:fuel_use, attrs)\n d / f\n end", "def totalCaloricValue()\n\t\t\t\tplato = @alimentsList.head\n\t\t\t\tgrams = @gramsList.head\n\t\t\t\ttotal = 0.0\n\n\t\t\t\twhile plato != nil\n\t\t\t\t\ttotal += (plato.value.get_energia() * grams.value) / 100\n\t\t\t\t\tplato = plato.next\n\t\t\t\t\tgrams = grams.next\n\t\t\t\tend\n\n\t\t\t\treturn total\n\t\t\tend", "def CPI\n if self.spent_hours>0 and self.estimated_hours>0\n earned_value= (self.completed_percent * self.estimated_hours)/100\n actual_cost=self.spent_hours\n return (earned_value/actual_cost)\n else\n return 0\n end\n\n rescue\n return 0\n end", "def value\n property.net_operating_income / property.cap_rate\n end", "def actual_travel\n actual_travel = travel_expenses.reduce(0) {|sum, expense| sum += expense.amount }\n end", "def input_efficiency\n @input_efficiency ||=\n begin\n base_cop = @config.base_cop\n per_degree = @config.cop_per_degree\n\n temperature_curve.map do |val|\n cop = base_cop + per_degree * val\n\n # Coefficient of performance must not drop below 1.0 (where there\n # is no \"balanced_with\" energy, and only \"based_on\" energy is\n # used).\n cop < 1.0 ? 1.0 : cop\n end\n end\n end", "def profit\n total_before_tax - total_cost\n end", "def profit\n total_before_tax - total_cost\n end", "def profit()\n profit = margin() * @quantity\n return profit\n end", "def average_calories\n total = 0\n self.desserts.each do |dessert|\n total + dessert.calories / dessert.ingreidents.length\n end\n total\n end", "def energy_row(bg)\n energy_profile = bg.group_energy_profiles.where(age_group: \"all\").first\n total_energy = Calculators::Conversion.to_kWh(energy_profile.imported_electricity_consumption.to_i || 0, energy_profile.imported_electricity_consumption_unit) +\n Calculators::Conversion.to_kWh(energy_profile.generated_electricity_consumption.to_i || 0, energy_profile.generated_electricity_consumption_unit) -\n Calculators::Conversion.to_kWh(energy_profile.exported_electricity.to_i || 0, energy_profile.exported_electricity_unit) +\n Calculators::Conversion.to_kWh(energy_profile.fossil_1_consumption.to_i || 0, energy_profile.fossil_1_consumption_unit) +\n Calculators::Conversion.to_kWh(energy_profile.fossil_2_consumption.to_i || 0, energy_profile.fossil_2_consumption_unit)\n total_emission = Calculators::Conversion.kgCO2_from_kWh(\"imported electricity consumption\", \n Calculators::Conversion.to_kWh(energy_profile.imported_electricity_consumption.to_i || 0, energy_profile.imported_electricity_consumption_unit)) +\n Calculators::Conversion.kgCO2_from_kWh(energy_profile.fossil_1_consumption_type,\n Calculators::Conversion.to_kWh(energy_profile.fossil_1_consumption.to_i || 0, energy_profile.fossil_1_consumption_unit)) +\n Calculators::Conversion.kgCO2_from_kWh(energy_profile.fossil_2_consumption_type,\n Calculators::Conversion.to_kWh(energy_profile.fossil_2_consumption.to_i || 0, energy_profile.fossil_2_consumption_unit))\n\n data = calculate(total_energy, total_emission, bg.total_area, bg.total_occupancy)\n data.merge({name: bg.name + \" \" + bg.category, year: bg.year})\n end", "def manufacturing_cost\n\tcost = 0.0\n\tself.item.materials.each do |mat|\n\t\tcost += ( (mat.quantity * waste_factor).round * mat.item.market_data.value )\n\tend\n\tself.manufacturing_requirements.each do |ram|\n\t\tnext if ram.item.skill?\n\t\tcost += ( ram.quantity * ram.damagePerJob * ram.item.market_data.value )\n\tend\n\tif self.tech_level == 2\n\t\tcost += self.invention_cost\n\tend\n\tcost /= self.item.portionSize\nend", "def number_of_kcal_per_meal\n kcal_per_recipe = recipe_ingredients.each.sum do |recipe_ingredient|\n calories_per_gram = recipe_ingredient.ingredient.calories / 100 \n kilograms_of_ingredient = recipe_ingredient.calculated_weight_in_grams / 1000\n (calories_per_gram * kilograms_of_ingredient) #kcal\n end\n kcal_per_recipe / num_people\n end", "def total_benefits_value\n benefits.map{|b| b.total_value_cents}.reduce(:+).to_i\n end", "def expense_total\n self.expenses.sum(:amount).to_f\n end", "def speed_of_spread #in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n case @population_density\n when 0..50 then 2.5\n when 51..100 then 2\n when 101..150 then 1.5\n when 151..200 then 1\n else 0.5\n end\n\n end", "def food_consumption\n return residents.length * 2\n end", "def avarage_calories_burned\n total_workout_calories / set_sport_by_user.count\n rescue\n 0\n end", "def speed_of_spread #in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n case @population_density\n when 0..50 then 2.5\n when 51..100 then 2\n when 101..150 then 1.5\n when 151..200 then 1\n else 0.5\n end\n end", "def profit\n (self.price - self.product.cost) * self.quantity\n end", "def estimated_supply\n values = {}\n\n # Pi\n values[:absorbed_nitrogen_at_opening] = estimate_absorbed_nitrogen_at_opening\n\n # Ri\n values[:mineral_nitrogen_at_opening] = estimate_mineral_nitrogen_at_opening\n\n # Mh\n values[:humus_mineralization] = estimate_humus_mineralization\n\n # Mhp\n values[:meadow_humus_mineralization] = estimate_meadow_humus_mineralization\n\n # Mr\n values[:previous_cultivation_residue_mineralization] = estimate_previous_cultivation_residue_mineralization\n\n # Mrci\n values[:intermediate_cultivation_residue_mineralization] = estimate_intermediate_cultivation_residue_mineralization\n\n # Nirr\n values[:irrigation_water_nitrogen] = estimate_irrigation_water_nitrogen\n\n # Xa\n values[:organic_fertilizer_mineral_fraction] = estimate_organic_fertilizer_mineral_fraction\n\n # Rf\n values[:nitrogen_at_closing] = estimate_nitrogen_at_closing\n\n # Po\n values[:soil_production] = estimate_soil_production\n\n # Xmax\n values[:maximum_nitrogen_input] = estimate_maximum_nitrogen_input\n\n values\n end", "def total_value_cents\n total_benefits_value\n end", "def calcElectCost( calcType )\n balancekWh = 0\n # Subtract old electricity cost from total before recalculating electricity cost\n $gResults[$outputHCode][\"avgFuelCostsTotal$\"] -= $gResults[$outputHCode][\"avgFuelCostsElec$\"]\n if ( calcType == \"annualMin\" )\n $gElecRate[\"avgFuelCostsElec$\"] = $gElecRate[\"ElecMthMinCharge$\"] * 12\n else\n if ( $gResults[$outputHCode][\"avgFueluseEleckWh\"] > $gElecRate[\"ElecBlck1Units\"] )\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] = $gElecRate[\"ElecBlck1Units\"] * $gElecRate[\"ElecBlck1CostPerUnit\"]\n balancekWh = $gResults[$outputHCode][\"avgFueluseEleckWh\"] - $gElecRate[\"ElecBlck1Units\"]\n if ( balancekWh > $gElecRate[\"ElecBlck2Units\"] )\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += $gElecRate[\"ElecBlck2Units\"] * $gElecRate[\"ElecBlck2CostPerUnit\"]\n balancekWh -= $gElecRate[\"ElecBlck2Units\"]\n if ( balancekWh > $gElecRate[\"ElecBlck3Units\"] )\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += $gElecRate[\"ElecBlck3Units\"] * $gElecRate[\"ElecBlck3CostPerUnit\"]\n balancekWh -= $gElecRate[\"ElecBlck3Units\"]\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += balancekWh * $gElecRate[\"ElecBlck4CostPerUnit\"]\n else\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += balancekWh * $gElecRate[\"ElecBlck3CostPerUnit\"]\n end\n else\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += balancekWh * $gElecRate[\"ElecBlck2CostPerUnit\"]\n end\n else\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] = $gResults[$outputHCode][\"avgFueluseEleckWh\"] * $gElecRate[\"ElecBlck1CostPerUnit\"]\n end\n end\n # Update total fuel cost variable\n $gResults[$outputHCode][\"avgFuelCostsTotal$\"] += $gResults[$outputHCode][\"avgFuelCostsElec$\"]\nend", "def effective_rate; end", "def speed_of_spread #in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n\n case @population_density\n when (0..49)\n 2.5\n when (50..99)\n 2\n when (100..149)\n 1.5\n when (150..199)\n 1\n else #(200+)\n 0.5\n end\n end", "def billable_utilization(date=Date.today)\n(resource_assignments.in_date_range(date,date).to_a.sum(&:billable_allocation)/target_utilization)*100\n end", "def calc_carbon_savings_from_chp_elec(val1= chp_salable_elec, val2= 2.7, val3= 0.643)\n\t\t(val1 * val2 * val3).round 2\n\tend", "def fitness\n return @fitness if @fitness\n\n consumption_per_cluster = {}\n @data.each_with_index do |v, i|\n consumption_per_cluster[v] ||= 0\n # puts @prosumers[i].id, @real_consumption\n consumption_per_cluster[v] += (@real_consumption[@prosumers[i].id] || 0)\n end\n\n total_penalties_before = @initial_imballance.map do |imballance|\n penalty(imballance)\n end\n\n total_penalties_after = 0\n res = 0;\n\n consumption_per_cluster.each do |cluster, consumption |\n # puts \"DEBUG: #{cluster}, #{consumption}\"\n p = penalty((consumption || 0) - (@targets_per_cluster[cluster] || 0))\n res += 100 * (total_penalties_before[cluster] - p) / total_penalties_before[cluster] if total_penalties_before[cluster] > 0\n end\n\n\n\n\n @fitness = res\n\n end", "def carbsPercent()\n\t\t\t\tplato = @alimentsList.head\n\t\t\t\tgrams = @gramsList.head\n\t\t\t\ttotalEnergy = 0.0\n\t\t\t\ttotalCarbsEnergy = 0.0\n\n\t\t\t\twhile plato != nil\n\t\t\t\t\ttotalEnergy += (plato.value.get_energia * grams.value) / 100\n\t\t\t\t\ttotalCarbsEnergy += (plato.value.get_energia_carbs * grams.value) / 100\n\n\t\t\t\t\tplato = plato.next\n\t\t\t\t\tgrams = grams.next\n\t\t\t\tend\n\n\t\t\t\treturn (totalCarbsEnergy * 100) / totalEnergy\n\t\t\tend", "def estimate\n e = 0\n @@mappings.each do |k,v|\n counts = eval v.pluralize\n counts.each do |obj|\n if obj.respond_to? 'population_estimate'\n e = e + obj.population_estimate\n elsif obj.respond_to? 'population_estimate_min'\n # handles the Other case which just has a range\n e = e + obj.population_estimate_min\n else\n strata = eval \"obj.#{v}_strata\"\n strata.each do |stratum|\n e = e + stratum.population_estimate\n end\n end\n end\n end\n e\n end", "def estimation(yearly_cost, yearly_consumption, floor_space, heat_type, water_cooking_type, nb_residents )\n yearly_cost = yearly_cost.to_f\n yearly_consumption = yearly_consumption.to_i\n floor_space = floor_space.to_i\n nb_residents = nb_residents.to_i\n if verify_nilness_params(yearly_cost, yearly_consumption, floor_space, heat_type, water_cooking_type, nb_residents)\n first_factor = heat_type == 'Gaz' ? 1 : 0\n second_factor = water_cooking_type == 'Gaz' ? 1 : 0\n yearly_consumption = floor_space * 100 * first_factor + consumption_people(nb_residents) * second_factor if yearly_consumption.zero?\n [yearly_cost, yearly_consumption]\n else\n [false, -1]\n end\n end", "def total_calcium\n food.calcium * quantity\n end", "def defense_bonus(lv)\n (80 * 3 * lv.to_f / 2 + 250) / 100 + 5\n end", "def indicator_energia()\n\t\t\t\te = totalCaloricValue() / @alimentsList.length\n\n\t\t\t\tif e < 670\n\t\t\t\t\treturn 1.0\n\t\t\t\telsif e <= 830\n\t\t\t\t\treturn 2.0\n\t\t\t\telse\n\t\t\t\t\treturn 3.0\n\t\t\t\tend\n\t\t\tend", "def calorie_count\n @sugar_amount * CALORIES_PER_SUGAR_GRAM +\n @flour_amount * CALORIES_PER_FLOUR_GRAM\n end", "def food_eaten\n max_vegetation = 1300 # max size of vegetation jungle 13\n max_food = max_health / 3.0\n\n field.vegetation.size * max_food / max_vegetation\n end", "def how_high\n energy * energy\nend", "def SPI\n\n #byebug\n if self.estimated_hours>0 and !self.start_date.nil? and !self.due_date.nil?\n hoxe_dias=(Date.parse(Time.now.to_s) - self.start_date).to_f\n total_dias=(self.due_date-self.start_date).to_f\n earned_value= (completed_percent * estimated_hours)/100 # Podria ser tambien las spent_hours\n planned_value=(hoxe_dias/total_dias)*estimated_hours\n return (earned_value/planned_value)\n else\n return 0\n end\n\n rescue\n return 0\n\n end", "def calculate_profit(amount)\n @value * amount\n end", "def percentage\n \tamount / expense.cost\n end", "def goods_produced\n (0.2 * base_production + trade_goods_bonus).round(6)\n end", "def production_cost\n reagent_reference.production_cost * quantity\n end", "def estimate\n # (native code) \n end", "def average_calories\n tot_calories = self.ingredients.sum {ingredient| ingredient.calories}\n tot_calories/self.desserts_count\n end", "def coefficient_by_inhabitants(tariff, fee_type)\n # Should be used to add to block limits\n if should_bill_by_inhabitants?(tariff, fee_type) && subscriber.inhabitants > tariff.inhabitants_from\n (subscriber.inhabitants - tariff.inhabitants_from) * tariff.inhabitants_increment rescue 0\n else\n 0\n end\n end", "def reagent_cost\n reagents.map do |reagent|\n reagent.reagent.production_cost\n end.sum\n end", "def speed_of_spread #in months\r\n # We are still perfecting our formula here. The speed is also affected\r\n # by additional factors we haven't added into this functionality.\r\n speed = 0.0\r\n\r\n if @population_density >= 200\r\n speed += 0.5\r\n elsif @population_density >= 150\r\n speed += 1\r\n elsif @population_density >= 100\r\n speed += 1.5\r\n elsif @population_density >= 50\r\n speed += 2\r\n else\r\n speed += 2.5\r\n end\r\n puts \"#{@state} will lose #{@number_of_deaths} people in this outbreak and will spread across the state in #{speed} months.\\n\\n\"\r\n end", "def variance_at_completion\n budget_at_completion - estimate_at_completion_cost\n end", "def calculate_liability\n calculate_gross\n end", "def consumption\n unless reading_index_1.nil? or reading_index.nil?\n if reading_index_1 <= reading_index\n reading_index - reading_index_1\n else\n # vuelta de contador\n (((10 ** meter.meter_model.digits)-1) - reading_index_1) + reading_index\n end\n else\n 0\n end\n rescue\n 0\n end", "def current_life\n 0.01 * total_life * current_life_percent\n end", "def profit\n return 0.0 unless self.deliverables.size > 0\n \n # Covers fixed and percentage profit though the +profit+ method being overloaded on the Deliverable types\n return self.deliverables.collect(&:profit).delete_if { |d| d.blank?}.inject { |sum, n| sum + n } || 0.0\n end", "def huella_ambiental\r\n energia = 0.0\r\n carbono = 0.0\r\n huella = 0.0\r\n if vct < 670 then\r\n energia = 1.0\r\n elsif vct <= 830 then\r\n energia = 2.0\r\n else\r\n energia = 3.0\r\n end\r\n if gei < 800 then\r\n carbono = 1.0\r\n elsif terrenos <= 1200 then\r\n carbono = 2.0\r\n else\r\n carbono = 3.0\r\n end\r\n huella = (energia + carbono)/2\r\n return huella\r\n \r\n end", "def consumption_total_period\n # @readings = Reading.where(billing_period_id: billing_period_id, subscriber_id: subscriber_ids).where('reading_type_id NOT IN (?)',[1,2,5,6]).group_by(&:reading_1_id)\n readings = subscriber.readings.where(billing_period_id: billing_period_id).where('reading_type_id IN (?)',[ReadingType::NORMAL,ReadingType::OCTAVILLA,ReadingType::RETIRADA,ReadingType::AUTO]).order(:reading_date).group_by(&:reading_1_id)\n total = 0\n ccm = 0\n readings.each do |reading|\n total += reading[1].last.consumption\n end\n if meter.is_master?\n # Billable Master Meter:\n # Consumption to bill must be the substraction between this consumption\n # and the sum of the child meters consumption\n ccm = consumption_child_meters\n total = ccm > total ? 0 : total - ccm\n end\n return total\n end", "def get_expense_details\n @total_expenses = 0.0\n @billed_expenses = 0.0\n @expense_entries = {}\n @expense_entries = @saved_expense_entries\n for time_entry in @saved_time_entries\n @expense_entries += time_entry.tne_invoice_expense_entries\n end\n unless @expense_entries.empty?\n @total_expenses = @expense_entries.map(&:expense_amount).inject(0) do |total,amount|\n total + amount\n end\n @billed_expenses = @expense_entries.map(&:final_expense_amount).inject(0) do |total,amount|\n total + amount\n end\n @billed_expenses = @billed_expenses.to_f.roundf2(2)\n end\n end", "def usd_profit\n break_even(:usd).abs\n end", "def cost\n total = 0.0\n not_covered.each do |n|\n total += n.cost\n end\n total\n end", "def speed_of_spread #in months\r\n # We are still perfecting our formula here. The speed is also affected\r\n # by additional factors we haven't added into this functionality.\r\n speed = 0.0\r\n\r\n if @population_density >= 200\r\n speed += 0.5\r\n elsif @population_density >= 150\r\n speed += 1\r\n elsif @population_density >= 100\r\n speed += 1.5\r\n elsif @population_density >= 50\r\n speed += 2\r\n else\r\n speed += 2.5\r\n end\r\n\r\n \r\n\r\n end", "def speed_of_spread(this) #in months\r\n # We are still perfecting our formula here. The speed is also affected\r\n # by additional factors we haven't added into this functionality.\r\n speed = 0.0\r\n case @population_density\r\n when 200..\r\n speed += 0.5\r\n when 150..200\r\n speed += 1\r\n when 100..150\r\n speed += 1.5\r\n when 50..100\r\n speed += 2\r\n when 0..50\r\n speed += 2.5\r\n end\r\n puts \" and will spread across the state in #{speed} months.\\n\\n\"\r\n end", "def speed_of_spread #in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n \n if @population_density >= 200\n 0.5\n elsif @population_density >= 150\n 1\n elsif @population_density >= 100\n 1.5\n elsif @population_density >= 50\n 2\n else\n 2.5\n end\n end", "def speed_of_spread #in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n \n if @population_density >= 200\n 0.5\n elsif @population_density >= 150\n 1\n elsif @population_density >= 100\n 1.5\n elsif @population_density >= 50\n 2\n else\n 2.5\n end\n\n end", "def speed_of_spread #in months\r\n # We are still perfecting our formula here. The speed is also affected\r\n # by additional factors we haven't added into this functionality.\r\n speed = 0.0\r\n inf = 1.0/0\r\n case @population_density\r\n when 200..inf\r\n speed += 0.5\r\n when 150...200\r\n speed += 1\r\n when 100...150\r\n speed += 1.5\r\n when 50...100\r\n speed += 2\r\n else\r\n speed += 2.5\r\n end\r\n\r\n puts \" and will spread across the state in #{speed} months.\\n\\n\"\r\n\r\n end", "def quota()\n (@quota) + (@experience / 2)\nend", "def energy\n return @data.inject(0.0){|sum,x| sum + (x * x)}\n end", "def speed_of_spread #in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n\n if @population_density >= 200\n 0.5\n elsif @population_density >= 150\n 1\n elsif @population_density >= 100\n 1.5\n elsif @population_density >= 50\n 2\n else\n 2.5\n end\n\n end", "def speed_of_spread #in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n speed = 0.0\n\n if @population_density >= 200\n speed += 0.5\n elsif @population_density >= 150\n speed += 1\n elsif @population_density >= 100\n speed += 1.5\n elsif @population_density >= 50\n speed += 2\n else\n speed += 2.5\n end\n\n end", "def estimated_velocity_per_day\n estimated_velocity / 7.0\n end", "def estimate\n # (native code)\n end", "def estimate\n # (native code)\n end" ]
[ "0.64738995", "0.6460504", "0.64576095", "0.6407664", "0.6324953", "0.6310428", "0.6309668", "0.63042414", "0.6296991", "0.62953824", "0.62562126", "0.6215982", "0.6200238", "0.61958694", "0.6178777", "0.61774266", "0.6176287", "0.6160859", "0.6142263", "0.6128977", "0.61065", "0.6088958", "0.60832435", "0.605301", "0.6037474", "0.6033229", "0.60143256", "0.60021913", "0.59991086", "0.5988264", "0.5988264", "0.59694993", "0.59673834", "0.59673804", "0.5965409", "0.5961015", "0.5955783", "0.59402144", "0.59396607", "0.59396607", "0.59316444", "0.5913641", "0.59102273", "0.58981204", "0.5875352", "0.58736604", "0.58717585", "0.5870714", "0.58638173", "0.5857348", "0.5849924", "0.5836959", "0.5829481", "0.58103096", "0.5809799", "0.58041644", "0.58026093", "0.5796547", "0.5795167", "0.5792715", "0.57866275", "0.5775655", "0.57725203", "0.57705534", "0.5758303", "0.57534677", "0.5752772", "0.57509005", "0.5750345", "0.57500327", "0.57430786", "0.57409364", "0.5739612", "0.57310426", "0.57269835", "0.57215506", "0.57204556", "0.5720113", "0.5716539", "0.57158685", "0.5714527", "0.5707689", "0.5697217", "0.5689903", "0.5689152", "0.5686923", "0.5686832", "0.5682493", "0.5679275", "0.5678046", "0.56755584", "0.5673632", "0.567192", "0.5670549", "0.56671834", "0.5667137", "0.56667525", "0.56611454", "0.566009", "0.56590194", "0.56590194" ]
0.0
-1
This method is part of the estimation process It verifies the entries of the client
def verify_nilness_params(yearly_cost, yearly_consumption, floor_space, heat_type, water_cooking_type, nb_residents) if yearly_cost.zero? # if he forgot the yearly cost false else if yearly_consumption.zero? # if the consumption is not entered, all the other field must be present if [floor_space, nb_residents].include?(0) || [heat_type, water_cooking_type].include?('') false else true end else true end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def verify\n end", "def verify\n # nothing to do here, so just return\n end", "def verify\n create_order\n start_challenge\n wait_verify_status\n check_verify_status\n rescue Acme::Client::Error => e\n retry_on_verify_error(e)\n end", "def fetch_and_validate_models\n @client = Client.get_from_memcache(@client_id)\n\n @user_kyc_comparison_detail = UserKycComparisonDetail.using_client_shard(client: @client).\n where(user_extended_detail_id: @user_extended_detail_id).first\n\n if @user_kyc_comparison_detail.blank?\n ApplicationMailer.notify(\n body: 'user kyc comparison details not available',\n data: {user_extended_detail_id: @user_extended_detail_id},\n subject: 'user_kyc_comparison_details issue'\n ).deliver\n return false\n end\n\n return false if @user_kyc_comparison_detail.image_processing_status !=\n GlobalConstant::ImageProcessing.processed_image_process_status\n\n @user_kyc_detail = UserKycDetail.using_client_shard(client: @client).\n where(client_id: @user_kyc_comparison_detail.client_id,\n user_extended_detail_id: @user_kyc_comparison_detail.user_extended_detail_id,\n status: GlobalConstant::UserKycDetail.active_status).first\n\n return false if @user_kyc_detail.blank? || @user_kyc_detail.has_been_auto_approved?\n\n @client_kyc_pass_setting = ClientKycPassSetting.get_active_setting_from_memcache(@user_kyc_detail.client_id)\n\n @client_token_sale_detail = ClientTokenSaleDetail.get_from_memcache(@user_kyc_detail.client_id)\n @user_extended_detail = UserExtendedDetail.using_client_shard(client: @client).where(id: @user_extended_detail_id).first\n\n true\n end", "def verify()\n # TODO\n end", "def credential_check\n %w(partner req_id service v).all? { |k|\n # AlipayWap.logger.debug \"#{k}: #{@protocol_fields[k]}<->#{@request.protocol_fields[k]}\"\n @protocol_fields[k] == @request.protocol_fields[k].to_s\n } || raise(\"Response is not for this request\")\n end", "def verify\n end", "def verify\n\n end", "def validate\n\n return error_with_data(\n 'fcb_3',\n 'missing @client_id',\n 'Something Went Wrong.',\n GlobalConstant::ErrorAction.default,\n {}\n ) if @client_id.blank?\n\n @balances_to_fetch.each do |chain_type, data|\n\n case chain_type\n\n when GlobalConstant::CriticalChainInteractions.utility_chain_type\n\n return error_with_data(\n 'fcb_4',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:address_uuid].blank?\n\n return error_with_data(\n 'fcb_5',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:balance_types].blank?\n\n when GlobalConstant::CriticalChainInteractions.value_chain_type\n\n return error_with_data(\n 'fcb_6',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:address].blank?\n\n return error_with_data(\n 'fcb_7',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if data[:balance_types].blank?\n\n else\n return error_with_data(\n 'fcb_7',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n )\n end\n\n end\n\n success\n\n end", "def test_37\n customer_hash = {\n 'orderId' => '37',\n 'amount' => '3001',\n 'orderSource'=>'telephone',\n 'billToAddress'=>{\n 'firstName' => 'Tom',\n 'lastName' => 'Black'},\n \n 'echeck'=>{\n 'accNum' =>'10@BC99999',\n 'accType' => 'Checking',\n 'routingNum' => '053100300'}\n }\n hash = customer_hash.merge(@@merchant_hash)\n echeck_response = CnpOnlineRequest.new.echeck_verification(hash)\n assert_equal('301', echeck_response.echeckVerificationResponse.response)\n assert_equal('Invalid Account Number', echeck_response.echeckVerificationResponse.message)\n end", "def test_verify\n # Start out unavailabl\n assert_raise(Puppet::Network::InvalidClientRequest) do\n @obj.verify(@request)\n end\n class << @obj\n def available?(req)\n true\n end\n end\n assert_raise(Puppet::Network::InvalidClientRequest) do\n @obj.verify(@request)\n end\n class << @obj\n def authorized?(req)\n true\n end\n end\n assert_nothing_raised do\n @obj.verify(@request)\n end\n end", "def client_verified?\n @client = client_class.find_by_consumer_key(request.consumer_key)\n request.verify_signature(@client)\n end", "def check\n \n end", "def check\n \n end", "def check_update_forclient(nomeprog, ver_prog)\n @log.debug(\"Controller: check_update_forclient\")\n net_prot_ver = [SUPP_SERV_VER_MAJ, SUPP_SERV_VER_MIN ]\n info_client = [nomeprog, ver_prog, net_prot_ver ]\n msg_details = YAML.dump(info_client)\n @log.debug \"update_req: #{info_client}\"\n cmd_to_send = build_cmd(:update_req, msg_details)\n send_data_to_server(cmd_to_send)\n @cup_gui.log_sometext(\"UPDATE: controlla se esiste una nuova versione\\n\")\n end", "def verify#todo\n #if its a fault, then its a no for sure\n #otherwise make sure all the fields are the right type, and are initialized etc\n true\n end", "def validate_inventory()\n validated = true\n line_item_total = 0\n line_item_hash = Hash.new \n self.line_items.each do |line_item|\n line_item_hash[line_item.variant_id] = line_item.quantity\n line_item_total += line_item.quantity\n end\n \n \n inventory_total = 0\n inventory_hash = Hash.new \n self.inventory_units.each do |unit|\n inventory_total += 1\n if inventory_hash.has_key?(unit.variant_id)\n inventory_hash[unit.variant_id] += 1\n else\n inventory_hash[unit.variant_id] = 1\n end \n end\n \n validated = false if (inventory_total != line_item_total)\n self.line_items.each do |line_item|\n validated = false if line_item_hash[line_item.variant_id] != inventory_hash[line_item.variant_id]\n break if !validated \n end\n \n raise \"inventory_units not matched with line item: \" + self.number if !validated\n\n\n shipping_events_total = 0\n shipping_events_hash = Hash.new\n self.shipments.first.shipping_events.each do |se|\n se.inventory_units.each do |unit|\n # puts se.id.to_s + \"#\" + unit.id.to_s\n # puts se.shipped_at\n # puts unit.state \n shipping_events_total += 1\n if se.is_shipped?\n validated = false if unit.state != 'returned' && unit.state != 'shipped' \n else\n validated = false if unit.state == 'shipped'\n end\n \n \n break if !validated \n end\n end\n \n \n raise \"inventory_units state not matched with shipping events: \" + self.number if !validated\n \n validated = false if (inventory_total != shipping_events_total)\n # puts inventory_total\n # puts shipping_events_total\n raise \"inventory_units total not matched with shipping events: \" + self.number if !validated\n \n return validated \n \n end", "def check\n @response = nil\n verified?\n end", "def verified_request?; end", "def example_verify_challenge_tx_threshold\n # 1. The wallet makes a GET request to /auth,\n # 2. The server receives the request, and returns the challenge xdr.\n envelope_xdr = Stellar::SEP10.build_challenge_tx(\n server: $server_kp,\n client: $client_master_kp,\n anchor_name: \"SDF\",\n timeout: 600\n )\n # 3. The wallet recieves the challenge xdr and collects enough signatures from\n # the accounts signers to reach the medium threshold on the account.\n # `envelope.signatures` already contains the server's signature, so the wallet\n # adds to the list.\n envelope = Stellar::TransactionEnvelope.from_xdr(envelope_xdr, \"base64\")\n envelope.signatures += [\n envelope.tx.sign_decorated($client_master_kp),\n envelope.tx.sign_decorated($client_signer_kp1),\n envelope.tx.sign_decorated($client_signer_kp2)\n ]\n envelope_xdr = envelope.to_xdr(:base64)\n\n # 4. The wallet makes a POST request to /auth containing the signed challenge\n # 5. The server verifies the challenge transaction\n envelope, client_master_address = Stellar::SEP10.read_challenge_tx(\n challenge_xdr: envelope_xdr,\n server: $server_kp\n )\n account = Stellar::Account.from_address(client_master_address)\n begin\n # Get all signers and thresholds for account\n info = $client.account_info(account)\n rescue Faraday::ResourceNotFound\n # The account doesn't exist yet.\n # In this situation, all the server can do is verify that the client master\n # keypair has signed the transaction.\n begin\n Stellar::SEP10.verify_challenge_tx(\n challenge_xdr: envelope_xdr, server: $server_kp\n )\n rescue Stellar::InvalidSep10ChallengeError => e\n puts \"You should handle possible exceptions:\"\n puts e\n else\n puts \"Challenge verified by client master key signature\"\n end\n else\n # The account exists, so the server should check if the signatures reach the\n # medium threshold on the account\n begin\n signers_found = Stellar::SEP10.verify_challenge_tx_threshold(\n challenge_xdr: envelope_xdr,\n server: $server_kp,\n threshold: info.thresholds[\"med_threshold\"],\n signers: Set.new(info.signers)\n )\n rescue Stellar::InvalidSep10ChallengeError => e\n puts \"You should handle possible exceptions:\"\n puts e\n else\n puts \"Challenge signatures and threshold verified!\"\n total_weight = 0\n signers_found.each do |signer|\n total_weight += signer[\"weight\"]\n puts \"signer: #{signer[\"key\"]}, weight: #{signer[\"weight\"]}\"\n end\n puts \"Account medium threshold: #{info.thresholds[\"med_threshold\"]}, total signature(s) weight: #{total_weight}\"\n end\n end\nend", "def test_valid\n assoc = Association.new('handle', 'secret', Time.now, 10000, 'HMAC-SHA1')\n\n assert_log_matches() {\n assert_equal(call_negotiate([assoc]), assoc)\n }\n end", "def verify_key; end", "def verify_key; end", "def validate_records\n have_enough_items_to_trade?\n end", "def verifyPostIdeaResponseContract\n return verifyResponseContract(@postIdea_response_structure)\n end", "def verify!(block)\n self.instance_eval(&block)\n expected = Set.new(expected_entries)\n provided = Set.new(provided_entries)\n missing_entries = expected - provided\n extra_entries = provided - expected\n missing_entries_found(missing_entries) if missing_entries.any?\n extra_entries_found(extra_entries) if extra_entries.any?\n end", "def verify\r\n self.verified = true\r\n end", "def all_expected_fields_received?\n @signature_fields ||= %w(idterminal idcomercio idtransaccion importe moneda coderror codautorizacion firma).map{|value| value = value.to_sym}\n !@fields.empty? && @fields.areset?(@signature_fields)\n end", "def verify()\n if has_order_items?\n order_template = order_object\n order_template = yield order_object if block_given?\n @virtual_server.softlayer_client[:Product_Order].verifyOrder(order_template)\n end\n end", "def verify\n new_rb_id_list = @rb_bmet.redbox_ids - @ds_bmet.redbox_ids\n update_rb_id_list = @rb_bmet.redbox_ids - new_rb_id_list\n if DEBUG\n puts\n puts \"@ds_bmet.redbox_ids=#{@ds_bmet.redbox_ids.inspect}\"\n puts \"@rb_bmet.redbox_ids=#{@rb_bmet.redbox_ids.inspect}\"\n puts\n puts \"new_rb_id_list=#{new_rb_id_list.inspect}\"\n puts \"update_rb_id_list=#{update_rb_id_list.inspect}\"\n puts\n end\n end", "def verify_iss; end", "def verify_iss; end", "def check!()\n # Check to see if the ticket is expired\n if self.expired?\n return { :success => false, :message => \"Ticket Expired\", :resultcode => 0, :date => Time.now.strftime(\"%Y-%m-%d\"), :eventid => self.event_id }\n # Check to see if the available entries have been exhausted\n elsif self.used?\n return { :success => false, :message => \"No Entries Available\", :resultcode => 0, :date => Time.now.strftime(\"%Y-%m-%d\"), :eventid => self.event_id }\n # Otherwise, grant access\n else\n # Decrement available entries\n self.update_attributes({:entries_used => self.entries_used + 1, :entries_available => self.entries_available - 1})\n # Log an entry under the ticket\n Entry.log(self)\n # Return success!\n return { :success => true, :message => \"Access Granted\", :resultcode => 1, :date => Time.now.strftime(\"%Y-%m-%d\"), :eventid => self.event_id }\n end\n end", "def validate_transaction_line_item tranx_number,line_type,home_value , line_item_gla_name, expected_dim1, expected_dim2, expected_dim3, expected_dim4,search_by_gla=false\n\tpage.has_text?(tranx_number)\n\tTRANX.click_more\n\tif search_by_gla == true\n\t\tTRANX.click_more\n\t\tTRANX.open_transaction_line_item_by_gla line_item_gla_name\n\telse\n\t\tTRANX.open_transaction_line_item_by_home_value home_value\n\tend\n\tSF.wait_for_search_button\n\tgen_compare line_item_gla_name , TRANX.get_line_item_gla_name ,\"Expected GLA value to be #{line_item_gla_name}.\"\n\tgen_compare expected_dim1 , TRANX.get_line_item_dimension1_value ,\"Expected Dimension 1 value to be #{expected_dim1}.\"\n\tgen_compare expected_dim2 , TRANX.get_line_item_dimension2_value ,\"Expected Dimension 2 value to be #{expected_dim2}.\"\n\tgen_compare expected_dim3 , TRANX.get_line_item_dimension3_value ,\"Expected Dimension 3 value to be #{expected_dim3}.\"\n\tgen_compare expected_dim4 , TRANX.get_line_item_dimension4_value ,\"Expected Dimension 4 value to be #{expected_dim4}.\"\n\tgen_compare line_type ,\tTRANX.get_line_item_line_type_value ,\"Expected line type value to be #{line_type}.\"\n\tSF.click_link tranx_number\n\tpage.has_text?(tranx_number)\nend", "def well_formated_response?\n all_expected_fields_received? && validate_bank_response_signature\n end", "def vadidate_journal_line_items line_number, expected_gla_name, expected_amount , expected_dim1, expected_dim2, expected_dim3, expected_dim4\n\tgen_compare expected_gla_name,(JNL.line_get_journal_gla line_number),\"expected_gla_name at No. #{line_number} is #{expected_gla_name}\"\n\tgen_compare expected_amount,(JNL.line_get_journal_line_value line_number),\"expected_amount at No. #{line_number} is #{expected_amount}\"\n\tgen_compare expected_dim1,(JNL.line_get_journal_dimension1 line_number),\"expected_dim1 at No. #{line_number} is #{expected_dim1}\"\n\tgen_compare expected_dim2,(JNL.line_get_journal_dimension2 line_number),\"expected_dim2 at No. #{line_number} is #{expected_dim2}\"\n\tgen_compare expected_dim3,(JNL.line_get_journal_dimension3 line_number),\"expected_dim3 at No. #{line_number} is #{expected_dim3}\"\n\tgen_compare expected_dim4,(JNL.line_get_journal_dimension4 line_number),\"expected_dim4 at No. #{line_number} is #{expected_dim4}\"\nend", "def verify_hash_action_notify( file )\n hash = @hasher.generate_hash( file )\n res = @dbase.search_hashes( file ) \n\n unless hash.to_s.eql?( res[\"hash\"] ) \n \n puts \"Host:\\t\\t#{res[\"host\"]}\"\n puts \"File:\\t\\t#{file}\"\n puts \"Database date:\\t#{res[\"date\"]}\"\n puts \"Current date:\\t#{Time.now}\"\n puts \"Old hash:\\t#{res[\"algo\"]},\\t#{res[\"hash\"]}\"\n puts \"New hash:\\t#{@hasher.algo},\\t#{hash.to_s}\"\n puts \"\"\n \n end\nend", "def negotiate_lines_added\n @estimate.line_items.each do |line_item|\n unless line_item.negotiate_lines.empty?\n return true if line_item.negotiate_lines.last.line_item_id_changed?\n end\n # return true\n #end\n end\n end", "def verify_signature\n #puts \"sing in params: #{@params[\"sign\"]}\" unless @params[\"sign\"] == Alipay.generate_signature(@params, @key)\n #puts Alipay.generate_signature(@params, @key)\n @params[\"sign\"] == Alipay.generate_signature(@params, @key)\n end", "def validate_client_details\n\n return error_with_data(\n 'um_su_3',\n 'Client is not active',\n 'Client is not active',\n GlobalConstant::ErrorAction.default,\n {}\n ) if !@client.is_web_host_setup_done?\n\n return error_with_data(\n 'um_su_4',\n 'Registration has ended, it is no longer possible to signup now',\n 'Registration has ended, it is no longer possible to signup now',\n GlobalConstant::ErrorAction.default,\n {},\n {}\n ) if @client_token_sale_details.has_registration_ended?\n\n success\n end", "def verify\n @bathroom.verify\n end", "def connection_valid?\n begin\n result = client.call(:fe_dummy).body[:fe_dummy_response][:fe_dummy_result]\n @observations << \"app_server: #{result[:app_server]}, db_server: #{result[:db_server]}, auth_server: #{result[:auth_server]}\"\n result[:app_server] == \"OK\" and result[:db_server] == \"OK\" and result[:auth_server] == \"OK\"\n rescue => e\n @errors << e.message\n @backtrace = e.backtrace\n false\n end\n end", "def check\n req = GData::HTTP::Request.new(@base_uri + '/' + @model)\n sign_and_request(req)\n end", "def verify\n response = @client.call :payment_verification, message: {\n 'MerchantID' => Zarinpal.configuration.merchant_id,\n 'Authority' => @authority,\n 'Amount' => @amount,\n }\n\n @response.validate(response.body)\n end", "def verify_signature\n #puts \"sing in params: #{@params[\"sign\"]}\" unless @params[\"sign\"] == Alipay.generate_signature(@params, @key)\n #puts Alipay.generate_signature(@params, @key)\n @params[\"sign\"] == Tenpay.generate_signature(@params, @key) #.tap{|sig| puts \"Generated sig #{sig}\"}\n end", "def verify_object_info_data(data_set)\n logger.debug \"Checking object number #{data_set[CoreObjectData::OBJECT_NUM.name]}\"\n object_data_errors = []\n text_values_match?(data_set[CoreObjectData::OBJECT_NUM.name], element_value(object_num_input), object_data_errors)\n\n other_nums = data_set[CoreObjectData::OTHER_NUM.name]\n other_nums && other_nums.each do |num|\n index = other_nums.index num\n text_values_match?(num[CoreObjectData::NUM_VALUE.name], element_value(other_num_num_input index), object_data_errors)\n text_values_match?(num[CoreObjectData::NUM_TYPE.name], element_value(other_num_type_input index), object_data_errors)\n end\n\n num_objects = data_set[CoreObjectData::NUM_OBJECTS.name]\n num_objects && text_values_match?(num_objects.to_s, element_value(num_objects_input), object_data_errors)\n\n collection = data_set[CoreObjectData::COLLECTION.name]\n collection && text_values_match?(collection, element_value(collection_input), object_data_errors)\n\n resp_depts = data_set[CoreObjectData::RESPONSIBLE_DEPTS.name]\n resp_depts && resp_depts.each { |dept| text_values_match?(dept[CoreObjectData::RESPONSIBLE_DEPT.name], element_value(resp_dept_input resp_depts.index(dept)), object_data_errors) }\n\n pub_to_list = data_set[CoreObjectData::PUBLISH_TO_LIST.name]\n pub_to_list && pub_to_list.each { |pub| text_values_match?(pub[CoreObjectData::PUBLISH_TO.name], element_value(publish_to_input pub_to_list.index(pub)), object_data_errors) }\n\n status = data_set[CoreObjectData::RECORD_STATUS.name]\n status && text_values_match?(status, element_value(record_status_input), object_data_errors)\n\n inv_statuses = data_set[CoreObjectData::INVENTORY_STATUS_LIST.name]\n inv_statuses && inv_statuses.each { |stat| text_values_match?(stat[CoreObjectData::INVENTORY_STATUS.name], element_value(inventory_status_input inv_statuses.index(stat)), object_data_errors) }\n\n brief_descrips = data_set[CoreObjectData::BRIEF_DESCRIPS.name]\n brief_descrips && brief_descrips.each { |descrip| text_values_match?(descrip[CoreObjectData::BRIEF_DESCRIP.name], element_value(brief_desc_text_area brief_descrips.index(descrip)), object_data_errors) }\n\n dist_feat = data_set[CoreObjectData::DISTINGUISHING_FEATURES.name]\n dist_feat && text_values_match?(dist_feat, element_value(dist_features_text_area), object_data_errors)\n\n comments = data_set[CoreObjectData::COMMENTS.name]\n comments && comments.each { |comment| text_values_match?(comment[CoreObjectData::COMMENT.name], element_value(comment_text_area comments.index(comment)), object_data_errors) }\n\n titles = data_set[CoreObjectData::TITLE_GRP.name]\n titles && titles.each do |title|\n index = titles.index title\n text_values_match?(title[CoreObjectData::TITLE.name], element_value(title_input index), object_data_errors)\n text_values_match?(title[CoreObjectData::TITLE_TYPE.name], element_value(title_type_input index), object_data_errors)\n text_values_match?(title[CoreObjectData::TITLE_LANG.name], element_value(title_lang_input index), object_data_errors)\n\n translations = title[CoreObjectData::TITLE_TRANSLATION_SUB_GRP.name]\n translations && translations.each do |trans|\n sub_index = translations.index trans\n text_values_match?(trans[CoreObjectData::TITLE_TRANSLATION.name], element_value(title_translation_input [index, sub_index]), object_data_errors)\n text_values_match?(trans[CoreObjectData::TITLE_TRANSLATION_LANG.name], element_value(title_translation_lang_input [index, sub_index]), object_data_errors)\n end\n end\n\n obj_names = data_set[CoreObjectData::OBJ_NAME_GRP.name]\n obj_names && obj_names.each do |name|\n index = obj_names.index name\n text_values_match?(name[CoreObjectData::OBJ_NAME_NAME.name], element_value(object_name_input index), object_data_errors)\n text_values_match?(name[CoreObjectData::OBJ_NAME_CURRENCY.name], element_value(object_name_currency_input index), object_data_errors)\n text_values_match?(name[CoreObjectData::OBJ_NAME_LEVEL.name], element_value(object_name_level_input index), object_data_errors)\n text_values_match?(name[CoreObjectData::OBJ_NAME_SYSTEM.name], element_value(object_name_system_input index), object_data_errors)\n text_values_match?(name[CoreObjectData::OBJ_NAME_TYPE.name], element_value(object_name_type_input index), object_data_errors)\n text_values_match?(name[CoreObjectData::OBJ_NAME_LANG.name], element_value(object_name_lang_input index), object_data_errors)\n text_values_match?(name[CoreObjectData::OBJ_NAME_NOTE.name], element_value(object_name_note_input index), object_data_errors)\n end\n\n object_data_errors\n end", "def _verify\n unless (@_headers['x-allopass-response-signature'] || []).include?(@_signature)\n raise Allorails::ApiFalseResponseSignatureError\n end\n end", "def check_key_data(record, ref_data, resp_data,\n exclude = nil, # exclude from db check.\n allow = nil, augment = true, # extra GET /keys items\n disallow = nil, line = nil)\n # XXX validate internally-generated db fields.\n must_exclude = [:time_constraints, :admin]\n exclude = exclude ? exclude + must_exclude : must_exclude\n # Allow skipping check_data.\n if (record && ref_data)\n check_data(record, ref_data, exclude, nil, disallow, line)\n end\n # Allow skipping reply check.\n if !resp_data\n return\n end\n\n non_db = [ \"bluetooth_address\",\n \"first_name\", \"last_name\", \"email\",\n \"user_display_name\", \"time_constraints\", \"lock_time_zone\" ]\n server_time = augment ? [:server_time] : []\n # reply splits into two sub-hashes.\n key_data = resp_data[\"key_data\"]\n key_info = resp_data[\"key_info\"]\n assert_not_nil key_data, \"key_data present\"\n assert_not_nil key_info, \"key_info present\"\n check_reply(json: key_data, model: record,\n elsewhere: non_db, allow: @@key_data_fields,\n exclude: [\"seq_no\"], augment: nil)\n # id present due to global rule in key_info, but not required\n check_reply(json: key_info, model: record,\n elsewhere: non_db, exclude: @@key_data_fields,\n augment: server_time)\n assert_equal record.lock.bluetooth_address, key_info[\"bluetooth_address\"], \"bluetooth_address\"\n assert_equal record.lock.name, key_info[\"name\"], \"name\"\n assert date_match(record.last_access, key_info[\"last_access\"]), \"last_access\"\n assert_equal record.user.account.first_name, key_info[\"first_name\"], \"first_name\"\n assert_equal record.user.account.last_name, key_info[\"last_name\"], \"last_name\"\n assert_equal record.user.account.email, key_info[\"email\"], \"email\"\n assert_equal record.user.display_name, key_info[\"user_display_name\"], \"user_display_name\"\n assert_equal record.lock.time_zone, key_info[\"lock_time_zone\"], \"time_zone\"\n # XXX admin\n\n check_key_time_constraints(record, key_data, key_info)\n\n #/locks doesn't include the same fields as /keys, so ignore these checks for GET /locks\n if (!ref_data && augment)\n # get /keys has extra fields\n admin = key_info['admin']\n auto_generated = key_info['auto_generated']\n lock_owner_key = key_info['lock_owner_key']\n assert_boolean_equal admin || lock_owner_key, auto_generated, \"auto_generated equals admin || lock_owner_key\"\n assert_boolean_equal record.lock.user_id == record.user_id, lock_owner_key, \"lock_owner_key equals record.lock.user_id == record.user_id\"\n lu = LocksUser.where(:lock_id => record.lock.id,\n :user_id => record.user_id)\n assert_boolean_equal (lu.count > 0) && lu.first.admin, admin, \"admin matches LocksUser\"\n # XXX lock_owner_display_name, sharer_display_name\n end\n end", "def result_of_checking; end", "def verifyIdeasResponseContract\n return verifyResponseContract(@ideas_response_structure)\n end", "def verifyIdeaResponseContract\n return verifyResponseContract(@idea_response_structure)\n end", "def check_values\n check_numericity\n check_zip_code\n end", "def verify(request, times = exactly(1))\n logger.debug('Sending query for verify to mockserver')\n results = retrieve(request)\n\n # Reusing the times model here so interpreting values here\n times = Times.new(symbolize_keys(times))\n num_times = times.remaining_times\n is_exact = !times.unlimited\n\n fulfilled = is_exact ? (num_times == results.size) : (num_times <= results.size)\n fail \"Expected request to be present: [#{num_times}] (#{is_exact ? 'exactly' : 'at least'}). But found: [#{results.size}]\" unless fulfilled\n results\n end", "def validate(response)\n # Invalid if the zuora timestamp is more than 300 seconds ago\n timestamp = from_zuora_time(response[\"timestamp\"].to_i)\n return false if timestamp < Time.now - 300\n # Match the signature with the signature from zuora\n create(response[\"id\"], response[\"timestamp\"], response[\"token\"]).signature == response[\"responseSignature\"]\n end", "def check\n megamgw_health\n #megamceph_health\n overall\n end", "def valid?\n @hydra.queue(request('verify'))\n end", "def verify_signatures?; end", "def is_checksum_valid?(received_params)\n paytmparams = Hash.new\n\n keys = received_params.keys\n keys.each do |k|\n paytmparams[k] = received_params[k]\n end\n\n checksum_hash = paytmparams[\"CHECKSUMHASH\"]\n paytmparams.delete(\"CHECKSUMHASH\")\n\n Rails.logger.debug \"HERE\"\n Rails.logger.debug \"paytmparams #{paytmparams}\"\n Rails.logger.debug \"checksum_hash #{checksum_hash}\"\n Rails.logger.debug \"PAYTM_MERCHANT_KEY #{ENV[\"PAYTM_MERCHANT_KEY\"]}\" \n \n return new_pg_verify_checksum(paytmparams, checksum_hash, ENV[\"PAYTM_MERCHANT_KEY\"])\n end", "def verify\n\t\t#puts \"INSIDE DEF: vERIFY IN ORDER CONCERN.\"\n\t\tself.reports.each do |report|\n\t\t\treport.a_test_was_verified = false\n\t\t\tif report.consider_for_processing?(self.history_tags)\n\t\t\t#puts \"checking report: #{report.name}\"\n\t\t\t#puts \"report verify all is: #{report.verify_all},,, #{Diagnostics::Report::VERIFY_ALL}\"\n\t\t\t\tif report.verify_all == Diagnostics::Report::VERIFY_ALL\n\t\t\t\t\t#puts \"reprot verify all is true\"\n\t\t\t\t\tif report.impression.blank?\n\t\t\t\t\t\t#puts \"impression is balnk\"\n\t\t\t\t\t\treport.tests.each do |test|\n\t\t\t\t\t\t\t#puts \"Calling verify if normal on test: #{test.name}\"\n\t\t\t\t\t\t\tunless test.verify_if_normal(self.current_user).blank?\n\t\t\t\t\t\t\t\treport.a_test_was_verified = true\n\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\treport.tests.each do |test|\n\t\t\t\t\t\t\tunless test.verify.blank?\n\t\t\t\t\t\t\t\treport.a_test_was_verified = true\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def test_line_items_auth \n c = customers(:bob)\n assert_equal(line_items(:bob_line_item), c.find_line_item(1))\n assert_nil(c.find_line_item(2))\n assert_nil(c.find_line_item(100000))\n end", "def check_ins\n check_in_responses\n end", "def verify &block\n\t\t\tif @verified\n\t\t\t\tyield true\n\t\t\t\treturn true\n\t\t\tend\n\n\t\t\t@request_queue.get '/description.xml', :info, 4 do |result|\n\t\t\t\tputs \"Description result: #{result.inspect}\" # XXX\n\t\t\t\tif result.is_a?(Hash) && result[:status] == 200\n\t\t\t\t\t@desc = REXML::Document.new result[:content]\n\t\t\t\t\t@desc.write($stdout, 4, true) # XXX\n\t\t\t\t\t@desc.elements.each('friendlyName') do |el|\n\t\t\t\t\t\tputs \"Friendly name: #{@name}\" # XXX\n\t\t\t\t\t\tset_name el.text\n\t\t\t\t\tend\n\t\t\t\t\t@desc.elements.each('serialNumber') do |el|\n\t\t\t\t\t\tputs \"Serial number: #{@serial}\" # XXX\n\t\t\t\t\t\t@serial = el.text.downcase\n\t\t\t\t\tend\n\t\t\t\t\t@desc.elements.each('modelName') do |el|\n\t\t\t\t\t\tputs \"modelName: #{el.text}\" # XXX\n\t\t\t\t\t\tif el.text.include? 'Philips hue'\n\t\t\t\t\t\t\t@verified = true\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\t# FIXME: Delete this line when converted to em-http-request; this\n\t\t\t\t\t# works around the empty :content returned by EM::HttpClient\n\t\t\t\t\t#\n\t\t\t\t\t# See commits:\n\t\t\t\t\t# 34110773fc45bfdd56c32972650f9d947d8fac78\n\t\t\t\t\t# 6d8d7a0566e3c51c3ab15eb2358dde3e518594d3\n\t\t\t\t\t@verified = true\n\t\t\t\tend\n\n\t\t\t\tbegin\n\t\t\t\t\tyield @verified\n\t\t\t\trescue => e\n\t\t\t\t\tlog_e e, \"Error notifying block after verification\"\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def validate_client\n\n @client = CacheManagement::Client.new([@client_id]).fetch[@client_id]\n\n return validation_error(\n 'e_sam_4',\n 'invalid_api_params',\n ['invalid_client_id'],\n GlobalConstant::ErrorAction.default\n ) if @client.blank? || @client[:status] != GlobalConstant::Client.active_status\n\n r = fetch_client_eth_address\n return r unless r.success?\n\n success\n\n end", "def check_record; end", "def evaluate_request\n\t\tprincipal_amt = principal_amount\n\t minimum = loan_type.minimum\n\t maximum = loan_type.maximum\n\n\t required_documents = loan_type.loan_docs.sort\n\t submitted_documents = loan_docs.sort unless loan_docs.nil?\n\n\t errors = []\n\n\t if principal_amt < minimum\n\t \terrors << \"Principal is below minimum\"\n\t end\n\n\t if principal_amt > maximum\n\t \terrors << \"Principal is greater than maximum\"\n\t end\n\n\t if required_documents != submitted_documents\n\t \terrors << \"Incomplete submitted documents\"\n\t end\n\n\t errors\n\t \n\t #(principal_amt >= minimum && principal_amt <= maximum) && required_documents == submitted_documents\n\tend", "def verify\n\t\tself.verified = true\n\t\tself.save\n\tend", "def verify_connection\n @client.find :first, {\n search_type: 'Property',\n class: '1', # 1 Residential\n query: '(246=|A),(61=|BROWARD)', # 246 ListingStatus\n # A Active-Available\n # 61 County\n limit: 1\n }\n end", "def verify\n head :ok\n end", "def check_modifiche\n # if self.changed?\n # self.stato_metadata = 'modificato'\n # #chiamo api per cancellare cache metadati\n # #creo jwe\n # priv_key = OpenSSL::PKey::RSA.new(File.read(Settings.path_key_jwe))\n # payload = { 'client' => self.client }.to_json\n # encrypted = JWE.encrypt(payload, priv_key, zip: 'DEF')\n # response = HTTParty.get(File.join(Settings.app_auth_url,\"spid/aggiorna_cache_metadata\"),\n # :headers => { 'Authorization' => \"Bearer #{encrypted}\" },\n # :body => {},\n # :follow_redirects => false,\n # :timeout => 500 )\n # unless response.blank?\n # if response['esito'] == 'ok'\n # logger.error \"Cache aggiornata con successo!\"\n # else\n # #TO-DO: schedulare su una coda l'aggiornamento della cache\n # logger.error \"Cache non aggiornata!\"\n # end \n # else\n # #TO-DO: schedulare su una coda l'aggiornamento della cache\n # logger.error \"Cache non aggiornata! Response vuota!\"\n # end\n #end\n end", "def fetch_and_validate_client\n @client = Client.get_from_memcache(@client_id)\n\n return error_with_identifier('invalid_client_id','sb_2') if\n @client.blank? || @client.status != GlobalConstant::Client.active_status\n\n success\n end", "def test_annuity_credit_results\n @annuity_credit_Value.each { |key, value| assert_in_delta @calc_annuity[@row_number][key], value, 0.03 }\n check_count @calc_annuity\n end", "def test_numericality_of_internal_tat\n client = Client.new(:name => \"MVG\", :partener_bank_group_code => 'HJ',\n :tat => 89, :group_code => 'LP', :max_jobs_per_user_payer_wise => 5,\n :max_jobs_per_user_client_wise => 5, :max_eobs_per_job => 5, :internal_tat => \"hj\")\n assert_equal(false, client.save, \"Internal TAT can't be blank!\")\n end", "def validate_client\n\n return invalid_credentials_response('a_ar_b_vc_1') unless @client.present?\n\n return invalid_credentials_response('a_ar_b_vc_2') if\n @client.status != GlobalConstant::Client.active_status\n\n r = decrypt_api_secret\n\n return error_with_identifier('internal_server_error', 'a_ar_b_vc_4') unless r.success?\n\n # Note: internal code for this error is same for client not present\n return invalid_credentials_response('a_ar_b_vc_1') unless generate_signature == @signature\n\n success\n end", "def contains_response_and_soln?() true ; end", "def verify_callback; end", "def verify_callback; end", "def verify_server_key(key); end", "def acknowledge\n verify? params, KEY\n end", "def acknowledge\n verify? params, KEY\n end", "def validate_client_manager\n\n @client_manager = CacheManagement::ClientManager.new([@manager_id], {client_id: @manager[:current_client_id]}).fetch[@manager_id]\n return client_manager_not_associated_response('am_vc_11') if @client_manager.blank?\n\n privileges = @client_manager[:privileges]\n\n is_client_manager_active = Util::CommonValidator.is_active_admin?(privileges)\n\n return client_manager_not_associated_response('am_vc_12') unless is_client_manager_active\n\n success\n\n end", "def test_getClientUnitsUsage\n info_srv = @adwords.get_service(13, 'Info')\n start_day = Date.new(Date.today.year, 1, 1)\n end_day = Date.today\n usage_map, doubles = info_srv.getClientUnitsUsage(start_day, end_day)\n\n # Did we get back a hash and an array?\n assert_instance_of(Hash, usage_map,\n \"Unexpected object type returned: #{usage_map.class}\")\n assert_instance_of(Array, doubles,\n \"Unexpected object type returned: #{doubles.class}\")\n\n email = @adwords.credentials.credentials['email']\n\n # There should be 6 items in there, one for the main MCC and one for each\n # of the 5 client accounts\n assert_not_nil(usage_map[email],\n 'Root MCC account was not present in usage map')\n 1.upto(5) do |index|\n assert_not_nil(usage_map[\"client_#{index}+#{email}\"],\n \"Client account #{index} was not present in usage map\")\n end\n assert_equal(usage_map.size, 6, 'Unexpected number of entries returned')\n end", "def checks; end", "def verify_orders\n photos = params.select { |key, val| key =~ /^[a-f0-9]{24}/ }\n\n invalid_photo_order_numbers = []\n\n photos.each_pair do |key, val|\n val.strip!\n if val.empty? || !(val =~ /^\\d{8}$/ )\n invalid_photo_order_numbers << key\n next\n end\n photo = Photo.find(key)\n next if photo.order_number == val\n photo.set order_number: val\n end\n\n if invalid_photo_order_numbers.any?\n @entries = contestant_unverified_photos\n @errors = invalid_photo_order_numbers\n render :verify and return\n end\n\n flash[:notice] = 'Order Numbers successfully verified. Thank you.'\n redirect_to share_photos_path\n end", "def verify!\n return true if verified?\n http = Net::HTTP.new('rest.akismet.com', 80)\n resp, data = http.post('/1.1/verify-key', \"key=#{@key}&blog=#{@blog}\", @headers)\n @verified = (data == \"valid\")\n end", "def show\n # Public method\n if @order.secure_hash != params[:secure_hash]\n respond_to do |format|\n format.html { redirect_to items_path }\n end\n return\n end\n\n @email_is_registered = User.exists?(email: @order.email)\n \n client = DogecoinClient.new\n\n if client.valid?\n @doges_deposited = client.get_received_by_address(@order.doge_address, 0)\n @doges_pending = @order.total_doges - @doges_deposited\n @doges_pending = 0 if @doges_pending < 0\n @is_payed = @doges_pending == 0\n else\n @doges_deposited = \"Error, no address generated. Please contact support.\"\n @doges_pending = 0\n @is_payed = false\n end\n \n end", "def consistency_checks\n unless certificate_serial_number == voucher_serial_number\n error_report << \"serial number mismatch certificate '#{certificate_serial_number}' vs '#{voucher_serial_number}'\"\n return false\n end\n # other tests here.\n return true\n end", "def validate_peer_data!(data)\n\t\t\t[:uuid,:host,:port].each{|k|\n\t\t\t\tdata[k] || fail(\"Peer data does not meet requirements. #{k} is a required field. See Hive documentation.\")\n\t\t\t}\n\t\t\tkeys = peer_fields.keys\n\t\t\tdata.keys.each{|k|\n\t\t\t\tkeys.include?(k) || warn(\"Provided key #{k} will not be stored with peer data\")\n\t\t\t}\n\t\t\ttrue\n\t\tend", "def test_19_createofflinedonations_verifythermometer()\n\t\t\n\t\tputs \"---------------------- START OF SCENARIO 19 ----------------------\"\n\t\tcreateOfflineDonation($offline_donorname, $offline_donoremail, $offline_donoramount)\n\t\tlogout()\n\t\tputs \"---------------------- END OF SCENARIO 19 ----------------------\"\n\t\n\tend", "def partner_info_verify(partner)\n h3_section.text.eql?(partner.company_info.name).present?\n expand(account_details_icon)\n pooled_resources_table.visible?\n end", "def verify_process!\n updated_attribute(:verified, true)\n end", "def control_infos\n @log.info 'Info control started!'\n return false unless @infos.class == Hash\n\n props = [YEAR, PROP, LESSON, STUDENT, EXAM]\n return false unless props.sort == @infos.keys.sort\n @log.info 'Info control succesful!'\n true\n end", "def test_verify_data_positions\n result = verify_data_positions(@warehouse_data)\n assert_equal(true,result)\nend", "def valid?\n result = IO.popen(\"#{Ledger.bin} -f - stats 2>&1\", 'r+') do |f|\n f.write to_ledger\n f.close_write\n f.readlines\n end\n\n $?.success? && !result.empty?\n end", "def assert_valid\n check_api_key\n check_application_id\n check_index_name\n\n Algolia.init(\n application_id: application_id,\n api_key: api_key\n )\n\n nil\n end", "def test_26\n customer_hash = {\n 'orderId' => '26',\n 'amount' => '18698',\n 'orderSource'=>'ecommerce',\n 'card'=>{\n 'number' =>'5194560012341234',\n 'expDate' => '1212',\n 'type' => 'MC'},\n 'allowPartialAuth' => 'true',\n 'healthcareIIAS' => {\n 'healthcareAmounts' => {\n 'totalHealthcareAmount' =>'20000'\n },\n 'IIASFlag' => 'Y'\n }\n }\n hash = customer_hash.merge(@@merchant_hash)\n auth_response = CnpOnlineRequest.new.authorization(hash)\n assert_equal('341', auth_response.authorizationResponse.response)\n assert_equal('Invalid healthcare amounts', auth_response.authorizationResponse.message)\n end", "def perform\n validate_data_from_requests\n end", "def verify\n @_buffer.shift(fbe_offset)\n fbe_result = verify_fields\n @_buffer.unshift(fbe_offset)\n fbe_result\n end", "def verify\n @_buffer.shift(fbe_offset)\n fbe_result = verify_fields\n @_buffer.unshift(fbe_offset)\n fbe_result\n end", "def verify\n @_buffer.shift(fbe_offset)\n fbe_result = verify_fields\n @_buffer.unshift(fbe_offset)\n fbe_result\n end", "def verify\n @_buffer.shift(fbe_offset)\n fbe_result = verify_fields\n @_buffer.unshift(fbe_offset)\n fbe_result\n end", "def validate_and_sanitize\n r = validate\n return r unless r.success?\n\n # Default Client is not allowed to open case\n return error_with_data(\n 'am_k_uea_1',\n 'Update ethereum not allowed for Token Sale Client.',\n 'Update ethereum not allowed for Token Sale Client.',\n GlobalConstant::ErrorAction.default,\n {}\n ) if @client.is_st_token_sale_client?\n\n r = fetch_and_validate_admin\n return r unless r.success?\n\n return error_with_data(\n 'am_k_uea_2',\n 'Admin does not have rights to perform this action.',\n 'Admin does not have rights to perform this action.',\n GlobalConstant::ErrorAction.default,\n {}\n ) if @admin.default_client_id != @client.id\n\n @client_kyc_config_detail = @client.client_kyc_config_detail\n\n return error_with_data(\n 'am_k_uea_3',\n 'Invalid Request',\n 'Invalid Request. Ethereum address not supported for client',\n GlobalConstant::ErrorAction.default,\n {}\n ) if @client_kyc_config_detail.kyc_fields_array.exclude?(GlobalConstant::ClientKycConfigDetail.ethereum_address_kyc_field)\n\n @user_kyc_detail = UserKycDetail.using_client_shard(client: @client).\n where(client_id: @client_id, id: @case_id).first\n return error_with_data(\n 'am_k_uea_5',\n 'Kyc Details not found or its closed.',\n 'Kyc Details not found or its closed.',\n GlobalConstant::ErrorAction.default,\n {}\n ) if @user_kyc_detail.blank? || @user_kyc_detail.inactive_status? || @user_kyc_detail.case_closed?\n\n r = validate_ethereum_address\n return r unless r.success?\n\n # Check for pending edit kyc requests\n edit_kyc_request = EditKycRequest.using_client_shard(client: @client).under_process.where(case_id: @case_id).first\n\n return error_with_data(\n 'am_k_uea_4',\n 'Edit request is in process for this case.',\n 'Edit request is in process for this case.',\n GlobalConstant::ErrorAction.default,\n {}\n ) if edit_kyc_request.present?\n\n @user_extended_details = UserExtendedDetail.using_client_shard(client: @client).\n where(id: @user_kyc_detail.user_extended_detail_id).first\n\n success\n end" ]
[ "0.6227038", "0.6166866", "0.6136668", "0.6095083", "0.60388434", "0.5999311", "0.58063453", "0.58043236", "0.57649106", "0.5720362", "0.56577307", "0.5614118", "0.55964535", "0.55964535", "0.5582783", "0.55827284", "0.55825675", "0.556687", "0.5527957", "0.5522332", "0.5509549", "0.55089533", "0.55089533", "0.5500843", "0.54996765", "0.5499517", "0.5479891", "0.5456139", "0.5454795", "0.5441722", "0.5441406", "0.5441406", "0.5427751", "0.54239374", "0.5414234", "0.5393411", "0.5392526", "0.5385698", "0.5371034", "0.53651243", "0.5362438", "0.5354944", "0.53483367", "0.5327967", "0.5325443", "0.5321396", "0.5317485", "0.5315123", "0.5315114", "0.5313619", "0.5303359", "0.529506", "0.52843446", "0.5282592", "0.52820903", "0.527868", "0.52738225", "0.52730775", "0.52705884", "0.52685034", "0.52654976", "0.52637094", "0.52635425", "0.5260012", "0.5250705", "0.523809", "0.523717", "0.52346784", "0.52271783", "0.5221798", "0.5212664", "0.52099216", "0.52091455", "0.520834", "0.52041346", "0.52041346", "0.5201127", "0.51963234", "0.51963234", "0.5187914", "0.5186544", "0.5180482", "0.51802295", "0.51794213", "0.51791364", "0.51683044", "0.51678807", "0.51673573", "0.51609725", "0.5160574", "0.5159588", "0.51590043", "0.5154611", "0.5149693", "0.51434666", "0.5143423", "0.514084", "0.514084", "0.514084", "0.514084", "0.5134493" ]
0.0
-1
Return the URL to the user's profile banner image
def profile_banner_uri(size=:web) ::URI.parse(insecure_uri([@attrs[:profile_banner_url], size].join('/'))) if @attrs[:profile_banner_url] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def profile_url\n if self.profile and self.profile != \"\"\n return self.profile\n end\n return \"/blank.png\"\n end", "def get_image_url( account_profile ) \n account_profile['profile_image_url']\n end", "def user_profile_img(user)\n if user.avatar?\n return image_tag(user.avatar, alt: user.name, size: \"60x60\")\n else\n img_url = 'no_image.png'\n end\n image_tag(img_url, alt: user.name, size: \"60x60\")\n end", "def profile_banner_url(size=:web)\n insecure_url([@attrs[:profile_banner_url], size].join('/')) if profile_banner_url?\n end", "def image_url\n url_for(object.profile_pic)\n end", "def display_profile_image\n if self.picture.present? && self.picture.url(:small).present?\n self.picture.url(:small)\n else\n ActionController::Base.helpers.asset_path('user.png')\n end\n end", "def linked_in_avatar(user)\n image_tag(user.user_info[\"linked_in\"][\"image\"])\n end", "def get_current_user_profile_image\n if ProfileImage.find_by(user_id: get_current_user.id).image_base64 != \"\"\n return ProfileImage.find_by(user_id: get_current_user.id)\n else\n return \"/img/logo/small-logo.png\"\n end\n end", "def user_pic user\n \"<a href='#{site(user)}' title='#{user.city} #{user.jobs} #{user.maxim} #{user.memo}' target='_blank'><img width='48' height='48' src='#{user.avatar.thumb.url}' width='#{USER_THUMB_SIZE}' height='#{USER_THUMB_SIZE}'></a>\"\n end", "def banner_for(user, height=100)\n image_tag(url_for(user.set_banner(height)))\n end", "def avatar_url\n if !self.fb_id.blank?\n return 'https://graph.facebook.com/%s/picture?width=90&height=90' % self.fb_id\n elsif !self.gpp_id.blank?\n return 'http://profiles.google.com/s2/photos/profile/%s?sz=90' % self.gpp_id\n else\n return ''\n end\n end", "def show\n if @user_profile.image.attachment \n @profile_image = @user_profile.image\n else\n @profile_image = \"https://api.adorable.io/avatars/200/#{current_user.username}\" \n end\n end", "def user_avatar_url(user = nil, variant:)\n if user.nil? || Rails.application.show_dummy_image?\n UsersHelper.no_avatar_path\n else\n user.avatar_image_location(variant: variant) || UsersHelper.no_avatar_path\n end.to_s\n end", "def profile_image(profile)\n url = Gravatar.new(profile.display_email || '@').image_url size: 40,\n secure: true, default: :mm\n image_tag url, alt: \"gravatar for #{profile.name}\",\n style: 'width: 40px; height: 40px;'\n end", "def profile_url(size: 'w300')\n if profile_path.present?\n \"#{h.configuration.base_url}#{size}#{object[\"profile_path\"]}\"\n else\n \"http://dummyimage.com/300x450/d9d9d9/000000.png&text=N/A\"\n end\n end", "def image_path\n uri_path = URI(profile_image_url).path\n extension = File.extname(uri_path)\n \"#{@base_path}/#{screen_name}#{extension}\"\n end", "def profile_image_url(size=:normal)\n insecure_url(profile_image_url_https(size)) if profile_image_url?\n end", "def get_profile_picture_url\n\t\tidentity = self.identities.find_by_provider_id(ApplicationController.fb_app[:id])\n\t\treturn ApplicationController.fb_app[:graph][:query_root_url] + identity.uid + \"/\" + ApplicationController.fb_app[:graph][:query_mypic_suffix]\t\t\n\tend", "def avatar_url(user)\n default_url = \"#{root_url}images/guest.jpg\"\n # BUG: Don't use gravatar as you can get someone else's gravatar with your name.\n # eg. Try signing up with name \"test meme\" ... it's some dude's distorted face\n # if user.profile\n # if user.profile.avatar_url.present?\n # user.profile.avatar_url\n # else\n # gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n # \"http://gravatar.com/avatar/#{gravatar_id}?s=200&d=#{CGI.escape(default_url)}\"\n # end\n # else\n # default_url\n # end\n end", "def twitter_profile_image\n @profile_image ||= begin\n require 'open-uri'\n require 'json'\n buffer = open(\"http://twitter.com/users/show/#{self.twitter_screen_name}.json\").read\n result = JSON.parse(buffer)\n result['profile_image_url']\n end\n end", "def avatar_url\n\t\t\"http://zombitar.com/#{id}.jpg\"\n\tend", "def user_img_URL\n self.user.image_url\n end", "def profile_pic_url\n result_hash['pic']\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def facebookProfilePicURL\n # https://www.facebook.com/user_name\n if facebook_url\n return \"https://graph.facebook.com/[PROFILE_ID]/picture\"\n else\n None\n end\n end", "def blank_profile_pic_url(format = 'tiny')\n \"/images/profile_pictures/profile_blank_#{format}.png\"\n end", "def avatar_url(user_id, avatar_id)\n \"#{api_base}/users/#{user_id}/avatars/#{avatar_id}.jpg\"\n end", "def avatar_url(user)\n url = \"http://www.gravatar.com/avatar/#{Digest::MD5::hexdigest(user.email)}?d=mm\"\n image_tag(url, :alt => 'Avatar', :class => 'avatar')\n end", "def profile_picture\n if facebook_authentication && facebook_authentication.profile_picture\n return facebook_authentication.profile_picture\n end\n return '/images/unknown_user.png'\n end", "def avatar_url\n \"http://robohash.org/#{email}?gravatar=yes\"\n end", "def avatar_url(avatar_size=\"small\")\n if self.has_shelby_avatar\n return self.shelby_avatar_url(avatar_size)\n else\n return self.user_image_original || self.user_image || \"#{Settings::ShelbyAPI.web_root}/images/assets/avatar.png\"\n end\n end", "def avatar_url\r\n return @user.avatar_url\r\n end", "def profile_pic_url\n json[\"entry_data\"][\"ProfilePage\"].first[\"graphql\"][\"user\"][\"profile_pic_url\"]\n end", "def avatar_url(user)\n default_url = \"#{root_url}images/user-img.gif\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end", "def get_profile_photo_url(photo)\n if photo != nil\n return photo.image.url(:thumb)\n else\n return 'user.png'\n end\n end", "def profile_img(uid, type=\"normal\")\n \"http://graph.facebook.com/#{uid}/picture?type=#{type}\"\n end", "def avatar_url\n avatar_uri(object)\n end", "def user_avatar_url\n @raw['user']['avatar_url']\n end", "def profile_picture_url\n hash = Digest::MD5.hexdigest(email)\n \"https://www.gravatar.com/avatar/#{hash}?d=mm\"\n end", "def get_avatar_url(user_id)\n u = User.find_by_id( user_id)\n avatar = u.avatar.url(:thumb)\n unless u.avatar_file_size?\n avatar = false\n end\n return avatar || Settings.avatar_image \n end", "def profile_picture\n profile_picture_file_name\n end", "def profile_photo\n photos = self.profile_photos\n photos.empty? ? 'http://ragatzi.s3.amazonaws.com/uploads/profile_default_1.png' : photos.last.photo.url\n end", "def profile_picture_for(user)\n if user.picture?\n image_tag(user.picture.url, alt: user.name, class: \"profile_picture\")\n else\n image_tag(random_default_image, alt: user.name, class: \"profile_picture\")\n end\n end", "def picture_url\n if avatar\n image_path(\"speakers/#{avatar}\")\n else\n image_path(\"default-avatar.png\")\n end\n end", "def author_picture_url\n @author_picture_url ||= begin\n if self.author_screenname\n \"http://twitter.com/api/users/profile_image/#{self.author_screenname}\"\n else\n image_path(\"default-avatar.png\")\n end\n end\n end", "def image_uri\n return \"/image_store/#{id}.#{profile_image}\"\n end", "def image\n if File.exist?(\"public/images/profile_images/#{self.username}.jpg\")\n img_path = \"/images/profile_images/#{self.username}.jpg\"\n else\n img_path = \"/images/default.jpg\"\n end\n return img_path\n end", "def user_image_url # return the user image\n ((self.user_image.present?)?(self.user_image.url.to_s):nil) || self.photo_url || \"/assets/no-image.png\"\n end", "def author_avatar\n anonymous? ? Avatar.default.url : user.profile.avatar.url\n end", "def profile_banner_url_https(size=:web)\n [@attrs[:profile_banner_url], size].join('/') if profile_banner_url?\n end", "def set_profile_picture_url(user)\n case user.provider\n when 'facebook'\n x = open(\"http://graph.facebook.com/v2.6/#{user.uid}/picture?redirect=false\", &:read)\n user.profile_pic = eval(x)[:data][:url]\n else # 'twitter', 'google', 'linkedin'\n user.profile_pic = open(user.image_url)\n end\n user.profile_pic.url\n end", "def author_avatar\n is_anonymous ? Avatar.default.url : user.profile.avatar.url\n end", "def header_nav_avatar\n if current_user.role? :superadmin\n avatar = current_user.institution.institution_logo.url(:thumb)\n else\n avatar = current_user.user_avatar.url(:thumb)\n end\n\n image_tag(avatar, class: 'img-squared', id: 'nav-user-avatar')\n end", "def avatar_url\n return image_url if image_url\n return DEFAULT_AVATAR if email.nil?\n\n gravatar_url\n end", "def profile_photo_url(version)\n if self.photos.profile_photo.blank? \n \"#{version.to_s}_avtar.jpg\"\n else \n self.photos.profile_photo.first.name_url(version)\n end \n end", "def profile_picture\n\t\tFbGraph::User.me(self.oauth_token).fetch.picture(width: 150, height: 200)\n\tend", "def profile_url\n @data[:profile_url]\n end", "def get_userpic(user_page)\n\t\t\tuserpic_xpath = '(//div[@id=\"profile-hero-panel\"]/div/img/@src)[1]'\n\t\t\tpic_img = user_page.parser.xpath(userpic_xpath)\n\n\t\t\tpic_img.text\n\tend", "def profile_image hash = {}\n image_name = hash.delete(:image_name) ||\n @controller.instance_variable_get(:@profile_user).feed.name.titlecase.\n gsub(/[\\/\\\\\\!\\@\\#\\$\\%\\^\\*\\&\\-\\.\\,\\?]+/, ' ').gsub(' ', '').underscore\n hash.update :action => 'profile_image', :id =>\n image_name, :format => (hash[:format] || 'jpeg'), :trailing_slash => false\n home(hash)\n end", "def social_image_for(user, options = { size: 80 })\n image_urls = user.social_profiles.pluck(:image_url)\n border = 4\n unless image_urls.empty?\n image_tag(image_urls.sample, size: options[:size] + border,\n alt: user.email, class: \"gravatar\")\n end\n end", "def social_image_for(user, options = { size: 80 })\n image_urls = user.social_profiles.pluck(:image_url)\n border = 4\n unless image_urls.empty?\n image_tag(image_urls.sample, size: options[:size] + border,\n alt: user.email, class: \"gravatar\")\n end\n end", "def profile_url\n nil\n end", "def og_image\n if @user && @user.image?\n @user.image.url\n elsif @person && @person.image?\n @person.image\n else\n root_url.chomp('/') + image_path('logo.png')\n end\n end", "def logo_url\n logo? ? logo.url : profile_img\n end", "def avatar_url (size)\n if avatar.present?\n return avatar.url(size)\n # elsif provider == \"facebook\" and external_uid\n # return \"https://graph.facebook.com/#{external_uid}/picture\"\n else\n return \"http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(email.downcase)}\"\n end\n end", "def avatar_img\n \"https://cdn.discordapp.com/avatars/#{id}/#{avatar}.webp?size=1024\"\n end", "def avatar_img\n \"https://cdn.discordapp.com/avatars/#{id}/#{avatar}.webp?size=1024\"\n end", "def avatar_url(style = :small)\n if avatar_file_name\n avatar.url(style)\n else\n url = avatar.url(style)\n providers.each do |e|\n next unless e.image_url\n\n url = e.image_url\n end\n url\n end\n end", "def fb_image_url(type='square')\n \"http://graph.facebook.com/#{fb_user_id}/picture?type=#{type}\" \n end", "def user_avatar(user)\n user.avatar ? user.avatar.photo.url(:thumb) : \"default-avatar.jpg\"\n end", "def get_user_image(user,size)\n if img=user.image\n img.photo.url(size)\n else\n '/images/default-user-image-'+size.to_s+'.jpg'\n end\n end", "def gravatar_url\n hash = Digest::MD5.hexdigest(self.email)\n\n image_src = \"//www.gravatar.com/avatar/#{hash}?d=identicon\"\n end", "def get_user_image(user_id)\n @user = User.find(:first,:select=>\"profile_image_url\",:conditions=>[\"id=#{user_id}\"])\n return @user.profile_image_url\n end", "def image_url \n if fb_id\n \"http://graph.facebook.com/#{fb_id}/picture?height=200\"\n end\n end", "def get_image_profile_pic\n last_pic = images.where(\"kind = ?\", \"profile_pic\").last\n\n if last_pic.nil?\n return \"/assets/octacat-resized.png\"\n else\n last_pic.url\n end\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def avatar_url(user, size)\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}\"\n end", "def picture\n if self.avatar?\n self.avatar.url\n elsif self.image_url != nil\n self.image_url\n else\n 'generic_avatar'\n end\n end", "def avatar_url\n root = Rails.application.routes.url_helpers.url_for(:root)\n uri = URI(root)\n uri.path = avatar_path\n uri.to_s\n end", "def avatar_url(type = :small)\n \"#{authentications.first.avatar_url}?type=#{type}\"\n end", "def fb_avatar(user, options = {})\n if user.class.name == 'User'\n if user.provider == \"facebook\"\n image_tag(\"https://graph.facebook.com/#{user.external_user_id}/picture?type=square\", { :alt => user_name(user), :class => 'fb-avatar' }.merge(options))\n else\n image_tag(\"no_avatar.jpg\", :size => '50x50')\n end\n else\n image_tag(\"no_avatar.jpg\", :size => '50x50')\n end\n # the code below turns the facebook avatar into a link, which we don't want.\n # link_to(image_tag(\"http://graph.facebook.com/#{user.external_user_id}/picture?type=square\", { :alt => user_name(user), :class => 'fb-avatar' }.merge(options)), \"http://www.facebook.com/profile.php?id=#{user.external_user_id}\", { :target => '_blank' })\n end", "def social_profile_image(profile, options = { size: 80 })\n return nil if profile.nil?\n image_tag(profile.image_url, size: options[:size], alt: profile.identity.email)\n end", "def avatar\n \"https://cdn.discordapp.com/avatars/#{@obj['id']}/#{@obj['avatar']}.webp?size=1024\"\n end", "def profile_url\n @json['user']['links']['self']\n end", "def gravatar_img_src\n # Não usa facebook\n if self.uid.nil?\n # include MD5 gem, should be part of standard ruby install\n require 'digest/md5'\n # create the md5 hash\n hash = Digest::MD5.hexdigest(self.email.downcase)\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n self.image = \"http://www.gravatar.com/avatar/#{hash}\"\n end\n end", "def user_image_link(user = nil, variant:)\n white_theme_user_image_link(user, variant: variant)\n end", "def banner_url\n object.banner_url.url\n end", "def avatar_url(format = nil)\n return API::User.default_avatar(@discriminator) unless @avatar_id\n\n API::User.avatar_url(@id, @avatar_id, format)\n end", "def profile_picture\n\t\timage_tag(\"ruby.svg.png\", alt: \"Profile Picture\")\n\tend", "def image_url\n \"https://graph.facebook.com/#{id}/picture\"\n end", "def user_image(user, options={})\n # get the email from URL-parameters or what have you and make lowercase\n email_address = user.email.downcase\n \n # create the md5 hash\n hash = Digest::MD5.hexdigest(email_address)\n\n query_string = hash_to_query_string(options.reverse_merge({\n :size => 100,\n :default => 'identicon'\n }))\n\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n \"http://www.gravatar.com/avatar/#{hash}#{query_string}\"\n end", "def fb_profile_url\n \"http://www.facebook.com/profile.php?id=#{fb_user_id}\"\n end", "def profile_image_miniature\n image_path = profile_user_image.present? ? profile_user_image.image.url(:miniature) :\n DEFAULT_USER_PROFILE_IMAGE_NAME\n\n h.image_tag image_path, class: 'img-thumbnail', alt: full_name\n end", "def get_pic_url\n\t if !self.pic_url\n\t\t twit_u = User.get_twitter_user_from_name(self.screen_name)\n\t\t\tputs twit_u\n\t\t\tself.pic_url = twit_u[\"profile_image_url\"]\n\t\t\tself.save!\n\t\tend\n\tend", "def profile_urls\n Enceladus::Configuration::Image.instance.url_for(\"profile\", profile_path)\n end", "def show\n banner = Banner.where(area: Banner.areas[:MemberShow]).first\n if banner\n @banner_image = banner.desktop_image.url\n @banner_url = banner.desktop_url\n end\n end", "def user_logo(user)\n image_tag(user.avatar_url)\n end", "def tw_image_url(type)\n \"http://api.twitter.com/1/users/profile_image?user_id=#{tw_user_id}&size=#{type}\"\n end" ]
[ "0.8004414", "0.7848266", "0.773669", "0.763777", "0.7636071", "0.7571114", "0.74976575", "0.7484197", "0.7441429", "0.7433081", "0.74250734", "0.739835", "0.7378658", "0.73764014", "0.7341379", "0.733608", "0.7283216", "0.725527", "0.7251441", "0.72503185", "0.7247855", "0.7244932", "0.7244322", "0.71945935", "0.7194274", "0.71654886", "0.7164779", "0.7157731", "0.7149973", "0.71368027", "0.7133063", "0.712968", "0.7113171", "0.7110909", "0.70844585", "0.70494086", "0.70394284", "0.70322096", "0.702121", "0.6992691", "0.69791216", "0.6977039", "0.6953901", "0.6952224", "0.6948303", "0.6938046", "0.6930576", "0.6924139", "0.6907792", "0.69055927", "0.69042486", "0.686559", "0.68582463", "0.6854244", "0.68542403", "0.68525326", "0.6847288", "0.6835733", "0.68357164", "0.68272865", "0.68105876", "0.68105876", "0.67993146", "0.6790183", "0.6789314", "0.6788832", "0.67842966", "0.67841244", "0.6777354", "0.67754984", "0.67738616", "0.677074", "0.676594", "0.6761616", "0.6754231", "0.6752932", "0.6752523", "0.6752523", "0.67470306", "0.6734584", "0.67306083", "0.67010367", "0.6698567", "0.6697757", "0.66953814", "0.6692602", "0.66851854", "0.6684479", "0.6677983", "0.667666", "0.6674385", "0.6673212", "0.6669059", "0.6666727", "0.6661461", "0.6656958", "0.6655342", "0.66420585", "0.6636215", "0.6634683" ]
0.7316583
16
Return the secure URL to the user's profile banner image
def profile_banner_uri_https(size=:web) ::URI.parse([@attrs[:profile_banner_url], size].join('/')) if @attrs[:profile_banner_url] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def profile_banner_url(size=:web)\n insecure_url([@attrs[:profile_banner_url], size].join('/')) if profile_banner_url?\n end", "def profile_url\n if self.profile and self.profile != \"\"\n return self.profile\n end\n return \"/blank.png\"\n end", "def profile_image_url(size=:normal)\n insecure_url(profile_image_url_https(size)) if profile_image_url?\n end", "def get_image_url( account_profile ) \n account_profile['profile_image_url']\n end", "def profile_banner_uri(size=:web)\n ::URI.parse(insecure_uri([@attrs[:profile_banner_url], size].join('/'))) if @attrs[:profile_banner_url]\n end", "def image_url\n url_for(object.profile_pic)\n end", "def display_profile_image\n if self.picture.present? && self.picture.url(:small).present?\n self.picture.url(:small)\n else\n ActionController::Base.helpers.asset_path('user.png')\n end\n end", "def profile_banner_url_https(size=:web)\n [@attrs[:profile_banner_url], size].join('/') if profile_banner_url?\n end", "def profile_url(size: 'w300')\n if profile_path.present?\n \"#{h.configuration.base_url}#{size}#{object[\"profile_path\"]}\"\n else\n \"http://dummyimage.com/300x450/d9d9d9/000000.png&text=N/A\"\n end\n end", "def get_current_user_profile_image\n if ProfileImage.find_by(user_id: get_current_user.id).image_base64 != \"\"\n return ProfileImage.find_by(user_id: get_current_user.id)\n else\n return \"/img/logo/small-logo.png\"\n end\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def user_profile_img(user)\n if user.avatar?\n return image_tag(user.avatar, alt: user.name, size: \"60x60\")\n else\n img_url = 'no_image.png'\n end\n image_tag(img_url, alt: user.name, size: \"60x60\")\n end", "def avatar_url(avatar_size=\"small\")\n if self.has_shelby_avatar\n return self.shelby_avatar_url(avatar_size)\n else\n return self.user_image_original || self.user_image || \"#{Settings::ShelbyAPI.web_root}/images/assets/avatar.png\"\n end\n end", "def user_avatar_url(user = nil, variant:)\n if user.nil? || Rails.application.show_dummy_image?\n UsersHelper.no_avatar_path\n else\n user.avatar_image_location(variant: variant) || UsersHelper.no_avatar_path\n end.to_s\n end", "def image_path\n uri_path = URI(profile_image_url).path\n extension = File.extname(uri_path)\n \"#{@base_path}/#{screen_name}#{extension}\"\n end", "def user_pic user\n \"<a href='#{site(user)}' title='#{user.city} #{user.jobs} #{user.maxim} #{user.memo}' target='_blank'><img width='48' height='48' src='#{user.avatar.thumb.url}' width='#{USER_THUMB_SIZE}' height='#{USER_THUMB_SIZE}'></a>\"\n end", "def user_img_URL\n self.user.image_url\n end", "def profile_image(profile)\n url = Gravatar.new(profile.display_email || '@').image_url size: 40,\n secure: true, default: :mm\n image_tag url, alt: \"gravatar for #{profile.name}\",\n style: 'width: 40px; height: 40px;'\n end", "def get_profile_picture_url\n\t\tidentity = self.identities.find_by_provider_id(ApplicationController.fb_app[:id])\n\t\treturn ApplicationController.fb_app[:graph][:query_root_url] + identity.uid + \"/\" + ApplicationController.fb_app[:graph][:query_mypic_suffix]\t\t\n\tend", "def blank_profile_pic_url(format = 'tiny')\n \"/images/profile_pictures/profile_blank_#{format}.png\"\n end", "def avatar_url(user)\n default_url = \"#{root_url}images/guest.jpg\"\n # BUG: Don't use gravatar as you can get someone else's gravatar with your name.\n # eg. Try signing up with name \"test meme\" ... it's some dude's distorted face\n # if user.profile\n # if user.profile.avatar_url.present?\n # user.profile.avatar_url\n # else\n # gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n # \"http://gravatar.com/avatar/#{gravatar_id}?s=200&d=#{CGI.escape(default_url)}\"\n # end\n # else\n # default_url\n # end\n end", "def linked_in_avatar(user)\n image_tag(user.user_info[\"linked_in\"][\"image\"])\n end", "def avatar_url\n if !self.fb_id.blank?\n return 'https://graph.facebook.com/%s/picture?width=90&height=90' % self.fb_id\n elsif !self.gpp_id.blank?\n return 'http://profiles.google.com/s2/photos/profile/%s?sz=90' % self.gpp_id\n else\n return ''\n end\n end", "def avatar_url\n \"http://robohash.org/#{email}?gravatar=yes\"\n end", "def profile_image_uri(size=:normal)\n ::URI.parse(insecure_uri(profile_image_uri_https(size))) if @attrs[:profile_image_url_https]\n end", "def show\n if @user_profile.image.attachment \n @profile_image = @user_profile.image\n else\n @profile_image = \"https://api.adorable.io/avatars/200/#{current_user.username}\" \n end\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def banner_for(user, height=100)\n image_tag(url_for(user.set_banner(height)))\n end", "def avatar_url\n\t\t\"http://zombitar.com/#{id}.jpg\"\n\tend", "def profile_picture\n if facebook_authentication && facebook_authentication.profile_picture\n return facebook_authentication.profile_picture\n end\n return '/images/unknown_user.png'\n end", "def profile_pic_url\n result_hash['pic']\n end", "def profile_picture_url\n hash = Digest::MD5.hexdigest(email)\n \"https://www.gravatar.com/avatar/#{hash}?d=mm\"\n end", "def facebookProfilePicURL\n # https://www.facebook.com/user_name\n if facebook_url\n return \"https://graph.facebook.com/[PROFILE_ID]/picture\"\n else\n None\n end\n end", "def image_uri\n return \"/image_store/#{id}.#{profile_image}\"\n end", "def avatar_url(user)\n default_url = \"#{root_url}images/user-img.gif\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end", "def avatar_url\r\n return @user.avatar_url\r\n end", "def avatar_url(user_id, avatar_id)\n \"#{api_base}/users/#{user_id}/avatars/#{avatar_id}.jpg\"\n end", "def get_profile_photo_url(photo)\n if photo != nil\n return photo.image.url(:thumb)\n else\n return 'user.png'\n end\n end", "def image\n if File.exist?(\"public/images/profile_images/#{self.username}.jpg\")\n img_path = \"/images/profile_images/#{self.username}.jpg\"\n else\n img_path = \"/images/default.jpg\"\n end\n return img_path\n end", "def avatar_url(user)\n url = \"http://www.gravatar.com/avatar/#{Digest::MD5::hexdigest(user.email)}?d=mm\"\n image_tag(url, :alt => 'Avatar', :class => 'avatar')\n end", "def gravatar_url\n hash = Digest::MD5.hexdigest(self.email)\n\n image_src = \"//www.gravatar.com/avatar/#{hash}?d=identicon\"\n end", "def get_profile_url_linkedin\n profile_url = self[:info][:urls][:public_profile] if self[:info] and self[:info][:urls]\n profile_url.gsub!(/^http:/, 'https:') if profile_url # protect cookies\n profile_url\n end", "def profile_picture\n profile_picture_file_name\n end", "def profile_image_url_https(size=:normal)\n # The profile image URL comes in looking like like this:\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_normal.png\n # It can be converted to any of the following sizes:\n # https://a0.twimg.com/profile_images/1759857427/image1326743606.png\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_mini.png\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_bigger.png\n resize_profile_image_url(@attrs[:profile_image_url_https], size) if profile_image_url?\n end", "def profile_url\n nil\n end", "def twitter_profile_image\n @profile_image ||= begin\n require 'open-uri'\n require 'json'\n buffer = open(\"http://twitter.com/users/show/#{self.twitter_screen_name}.json\").read\n result = JSON.parse(buffer)\n result['profile_image_url']\n end\n end", "def avatar_url (size)\n if avatar.present?\n return avatar.url(size)\n # elsif provider == \"facebook\" and external_uid\n # return \"https://graph.facebook.com/#{external_uid}/picture\"\n else\n return \"http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(email.downcase)}\"\n end\n end", "def get_avatar_url(user_id)\n u = User.find_by_id( user_id)\n avatar = u.avatar.url(:thumb)\n unless u.avatar_file_size?\n avatar = false\n end\n return avatar || Settings.avatar_image \n end", "def user_image_url # return the user image\n ((self.user_image.present?)?(self.user_image.url.to_s):nil) || self.photo_url || \"/assets/no-image.png\"\n end", "def profile_img(uid, type=\"normal\")\n \"http://graph.facebook.com/#{uid}/picture?type=#{type}\"\n end", "def user_avatar_url\n @raw['user']['avatar_url']\n end", "def avatar_url\n return image_url if image_url\n return DEFAULT_AVATAR if email.nil?\n\n gravatar_url\n end", "def avatar_url\n avatar_uri(object)\n end", "def fb_image_url(type='square')\n \"http://graph.facebook.com/#{fb_user_id}/picture?type=#{type}\" \n end", "def api_profile_url\n return nil unless (temp_api_profile_url = read_attribute(:api_profile_url))\n # logger.debug2 \"temp_api_profile_url = #{temp_api_profile_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_url, 'api_profile_url', 39)\n end", "def api_profile_url\n return nil unless (temp_api_profile_url = read_attribute(:api_profile_url))\n # logger.debug2 \"temp_api_profile_url = #{temp_api_profile_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_url, 'api_profile_url', 39)\n end", "def profile_pic_url\n json[\"entry_data\"][\"ProfilePage\"].first[\"graphql\"][\"user\"][\"profile_pic_url\"]\n end", "def seller_url\r\n ['http:', user.user_url].join('//') rescue nil\r\n end", "def avatar_url(type = :small)\n \"#{authentications.first.avatar_url}?type=#{type}\"\n end", "def gravatar_api_url(hash, ssl=false)\n if ssl\n \"https://secure.gravatar.com/avatar/#{hash}\"\n else\n \"http://www.gravatar.com/avatar/#{hash}\"\n end\n end", "def profile_url\n @data[:profile_url]\n end", "def user_image(user, options={})\n # get the email from URL-parameters or what have you and make lowercase\n email_address = user.email.downcase\n \n # create the md5 hash\n hash = Digest::MD5.hexdigest(email_address)\n\n query_string = hash_to_query_string(options.reverse_merge({\n :size => 100,\n :default => 'identicon'\n }))\n\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n \"http://www.gravatar.com/avatar/#{hash}#{query_string}\"\n end", "def picture_url\n if avatar\n image_path(\"speakers/#{avatar}\")\n else\n image_path(\"default-avatar.png\")\n end\n end", "def set_profile_picture_url(user)\n case user.provider\n when 'facebook'\n x = open(\"http://graph.facebook.com/v2.6/#{user.uid}/picture?redirect=false\", &:read)\n user.profile_pic = eval(x)[:data][:url]\n else # 'twitter', 'google', 'linkedin'\n user.profile_pic = open(user.image_url)\n end\n user.profile_pic.url\n end", "def avatar_img\n \"https://cdn.discordapp.com/avatars/#{id}/#{avatar}.webp?size=1024\"\n end", "def avatar_img\n \"https://cdn.discordapp.com/avatars/#{id}/#{avatar}.webp?size=1024\"\n end", "def avatar_url(user, size)\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}\"\n end", "def avatar_url\n root = Rails.application.routes.url_helpers.url_for(:root)\n uri = URI(root)\n uri.path = avatar_path\n uri.to_s\n end", "def author_picture_url\n @author_picture_url ||= begin\n if self.author_screenname\n \"http://twitter.com/api/users/profile_image/#{self.author_screenname}\"\n else\n image_path(\"default-avatar.png\")\n end\n end\n end", "def author_avatar\n anonymous? ? Avatar.default.url : user.profile.avatar.url\n end", "def profile_image_uri_https(size=:normal)\n # The profile image URL comes in looking like like this:\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_normal.png\n # It can be converted to any of the following sizes:\n # https://a0.twimg.com/profile_images/1759857427/image1326743606.png\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_mini.png\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_bigger.png\n ::URI.parse(@attrs[:profile_image_url_https].sub(PROFILE_IMAGE_SUFFIX_REGEX, profile_image_suffix(size))) if @attrs[:profile_image_url_https]\n end", "def get_banner_image_url(banner_image_id)\n banner_image = BannerImage.where(:id => banner_image_id, :active => true).first\n if banner_image\n return \"#{Brevidy::Application::S3_BASE_URL}/#{banner_image.path}/#{banner_image.filename}\"\n else\n # The banner image is either inactive or could not be found so return the default one\n return \"#{Brevidy::Application::S3_BASE_URL}/#{BannerImage.find_by_filename('banner-1.jpg').path}/#{BannerImage.find_by_filename('banner-1.jpg').filename}\"\n end\n end", "def image_url\n \"http://graph.facebook.com/#{third_party_id}/picture?type=square\"\n end", "def smol_avatar_url\n # Gravatar uses MD5 hashes of people's email addresses, so it works well here.\n hash = Digest::MD5.hexdigest(email)\n \"http://www.gravatar.com/avatar/#{hash}?size=50px\"\n end", "def gravatar_img_src\n # Não usa facebook\n if self.uid.nil?\n # include MD5 gem, should be part of standard ruby install\n require 'digest/md5'\n # create the md5 hash\n hash = Digest::MD5.hexdigest(self.email.downcase)\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n self.image = \"http://www.gravatar.com/avatar/#{hash}\"\n end\n end", "def avatar_url(style = :small)\n if avatar_file_name\n avatar.url(style)\n else\n url = avatar.url(style)\n providers.each do |e|\n next unless e.image_url\n\n url = e.image_url\n end\n url\n end\n end", "def photo_url\n gravatar_id = Digest::MD5.hexdigest(email.downcase)\n \"https://gravatar.com/avatar/#{gravatar_id}.png\"\n end", "def get_user_image(user,size)\n if img=user.image\n img.photo.url(size)\n else\n '/images/default-user-image-'+size.to_s+'.jpg'\n end\n end", "def user_image_link(user = nil, variant:)\n white_theme_user_image_link(user, variant: variant)\n end", "def image_url(style='original')\n ENV[\"domain\"] + self.picture.image.url(:original) if self.picture.present?\n end", "def profile_photo_url(version)\n if self.photos.profile_photo.blank? \n \"#{version.to_s}_avtar.jpg\"\n else \n self.photos.profile_photo.first.name_url(version)\n end \n end", "def display_picture_url\n\t\tdisplay_picture.url(:original)\n\tend", "def banner_url\n object.banner_url.url\n end", "def image_url\n image.presence or (email.present? and gravatar_url) or Guest::IMAGE_URL\n end", "def social_profile_image(profile, options = { size: 80 })\n return nil if profile.nil?\n image_tag(profile.image_url, size: options[:size], alt: profile.identity.email)\n end", "def logo_url\n logo? ? logo.url : profile_img\n end", "def profile_urls\n Enceladus::Configuration::Image.instance.url_for(\"profile\", profile_path)\n end", "def default_url\n Settings.image.default_avatar\n end", "def default_url\n Settings.image.default_avatar\n end", "def default_url\n Settings.image.default_avatar\n end", "def fb_profile_url\n \"http://www.facebook.com/profile.php?id=#{fb_user_id}\"\n end", "def square_image_url\n fb_connected? ? fb_image_url('square') : tw_image_url('bigger')\n end", "def user_gravatar_url\n self.user.gravatar_url\n end", "def og_image\n if @user && @user.image?\n @user.image.url\n elsif @person && @person.image?\n @person.image\n else\n root_url.chomp('/') + image_path('logo.png')\n end\n end", "def default_url\n \"/images/user/avatar/\" + [version_name, \"default.png\"].compact.join('_')\n end", "def author_avatar\n is_anonymous ? Avatar.default.url : user.profile.avatar.url\n end", "def social_image_for(user, options = { size: 80 })\n image_urls = user.social_profiles.pluck(:image_url)\n border = 4\n unless image_urls.empty?\n image_tag(image_urls.sample, size: options[:size] + border,\n alt: user.email, class: \"gravatar\")\n end\n end", "def social_image_for(user, options = { size: 80 })\n image_urls = user.social_profiles.pluck(:image_url)\n border = 4\n unless image_urls.empty?\n image_tag(image_urls.sample, size: options[:size] + border,\n alt: user.email, class: \"gravatar\")\n end\n end" ]
[ "0.78130656", "0.76481104", "0.75924057", "0.73992205", "0.73567855", "0.7302048", "0.7253386", "0.72063124", "0.7148167", "0.7110586", "0.710684", "0.710684", "0.70610666", "0.69632035", "0.6952374", "0.6947484", "0.6927653", "0.6922039", "0.69173527", "0.6890155", "0.6875653", "0.6852923", "0.6831424", "0.68307143", "0.68114513", "0.6810901", "0.68019384", "0.67973775", "0.67969054", "0.6784674", "0.6772884", "0.6770751", "0.6761112", "0.6727464", "0.6722038", "0.6679082", "0.6668412", "0.66382784", "0.6632502", "0.66027886", "0.65919447", "0.658924", "0.657271", "0.6572649", "0.65705353", "0.6563051", "0.65612096", "0.6558329", "0.6540665", "0.65046847", "0.650122", "0.64884555", "0.6478389", "0.64740145", "0.6468344", "0.6464543", "0.64608574", "0.64608574", "0.64595574", "0.6455132", "0.64546937", "0.6452114", "0.6450224", "0.6448982", "0.6448214", "0.6439317", "0.643919", "0.6438857", "0.6433303", "0.64302284", "0.6423209", "0.641429", "0.64102", "0.640701", "0.6401741", "0.64008296", "0.639995", "0.63959515", "0.6395393", "0.6390549", "0.6378046", "0.636759", "0.6361631", "0.63466865", "0.63381106", "0.633532", "0.63314867", "0.63311255", "0.63300574", "0.6318663", "0.6318663", "0.6318663", "0.631794", "0.6313688", "0.63113016", "0.6310533", "0.6306785", "0.6306021", "0.6305296", "0.6305296" ]
0.685851
21
Return the URL to the user's profile image
def profile_image_uri(size=:normal) ::URI.parse(insecure_uri(profile_image_uri_https(size))) if @attrs[:profile_image_url_https] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def profile_url\n if self.profile and self.profile != \"\"\n return self.profile\n end\n return \"/blank.png\"\n end", "def image_url\n url_for(object.profile_pic)\n end", "def get_image_url( account_profile ) \n account_profile['profile_image_url']\n end", "def user_profile_img(user)\n if user.avatar?\n return image_tag(user.avatar, alt: user.name, size: \"60x60\")\n else\n img_url = 'no_image.png'\n end\n image_tag(img_url, alt: user.name, size: \"60x60\")\n end", "def display_profile_image\n if self.picture.present? && self.picture.url(:small).present?\n self.picture.url(:small)\n else\n ActionController::Base.helpers.asset_path('user.png')\n end\n end", "def user_img_URL\n self.user.image_url\n end", "def image_path\n uri_path = URI(profile_image_url).path\n extension = File.extname(uri_path)\n \"#{@base_path}/#{screen_name}#{extension}\"\n end", "def profile_picture_url\n hash = Digest::MD5.hexdigest(email)\n \"https://www.gravatar.com/avatar/#{hash}?d=mm\"\n end", "def avatar_url\r\n return @user.avatar_url\r\n end", "def profile_pic_url\n result_hash['pic']\n end", "def profile_image_url(size=:normal)\n insecure_url(profile_image_url_https(size)) if profile_image_url?\n end", "def profile_picture\n if facebook_authentication && facebook_authentication.profile_picture\n return facebook_authentication.profile_picture\n end\n return '/images/unknown_user.png'\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def avatar_url\n if !self.fb_id.blank?\n return 'https://graph.facebook.com/%s/picture?width=90&height=90' % self.fb_id\n elsif !self.gpp_id.blank?\n return 'http://profiles.google.com/s2/photos/profile/%s?sz=90' % self.gpp_id\n else\n return ''\n end\n end", "def user_avatar_url(user = nil, variant:)\n if user.nil? || Rails.application.show_dummy_image?\n UsersHelper.no_avatar_path\n else\n user.avatar_image_location(variant: variant) || UsersHelper.no_avatar_path\n end.to_s\n end", "def twitter_profile_image\n @profile_image ||= begin\n require 'open-uri'\n require 'json'\n buffer = open(\"http://twitter.com/users/show/#{self.twitter_screen_name}.json\").read\n result = JSON.parse(buffer)\n result['profile_image_url']\n end\n end", "def get_profile_photo_url(photo)\n if photo != nil\n return photo.image.url(:thumb)\n else\n return 'user.png'\n end\n end", "def get_current_user_profile_image\n if ProfileImage.find_by(user_id: get_current_user.id).image_base64 != \"\"\n return ProfileImage.find_by(user_id: get_current_user.id)\n else\n return \"/img/logo/small-logo.png\"\n end\n end", "def get_profile_picture_url\n\t\tidentity = self.identities.find_by_provider_id(ApplicationController.fb_app[:id])\n\t\treturn ApplicationController.fb_app[:graph][:query_root_url] + identity.uid + \"/\" + ApplicationController.fb_app[:graph][:query_mypic_suffix]\t\t\n\tend", "def profile_image(profile)\n url = Gravatar.new(profile.display_email || '@').image_url size: 40,\n secure: true, default: :mm\n image_tag url, alt: \"gravatar for #{profile.name}\",\n style: 'width: 40px; height: 40px;'\n end", "def image\n if File.exist?(\"public/images/profile_images/#{self.username}.jpg\")\n img_path = \"/images/profile_images/#{self.username}.jpg\"\n else\n img_path = \"/images/default.jpg\"\n end\n return img_path\n end", "def profile_img(uid, type=\"normal\")\n \"http://graph.facebook.com/#{uid}/picture?type=#{type}\"\n end", "def user_pic user\n \"<a href='#{site(user)}' title='#{user.city} #{user.jobs} #{user.maxim} #{user.memo}' target='_blank'><img width='48' height='48' src='#{user.avatar.thumb.url}' width='#{USER_THUMB_SIZE}' height='#{USER_THUMB_SIZE}'></a>\"\n end", "def profile_pic_url\n json[\"entry_data\"][\"ProfilePage\"].first[\"graphql\"][\"user\"][\"profile_pic_url\"]\n end", "def avatar_url(user)\n default_url = \"#{root_url}images/guest.jpg\"\n # BUG: Don't use gravatar as you can get someone else's gravatar with your name.\n # eg. Try signing up with name \"test meme\" ... it's some dude's distorted face\n # if user.profile\n # if user.profile.avatar_url.present?\n # user.profile.avatar_url\n # else\n # gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n # \"http://gravatar.com/avatar/#{gravatar_id}?s=200&d=#{CGI.escape(default_url)}\"\n # end\n # else\n # default_url\n # end\n end", "def user_avatar_url\n @raw['user']['avatar_url']\n end", "def avatar_url\n \"http://robohash.org/#{email}?gravatar=yes\"\n end", "def avatar_url(avatar_size=\"small\")\n if self.has_shelby_avatar\n return self.shelby_avatar_url(avatar_size)\n else\n return self.user_image_original || self.user_image || \"#{Settings::ShelbyAPI.web_root}/images/assets/avatar.png\"\n end\n end", "def set_profile_picture_url(user)\n case user.provider\n when 'facebook'\n x = open(\"http://graph.facebook.com/v2.6/#{user.uid}/picture?redirect=false\", &:read)\n user.profile_pic = eval(x)[:data][:url]\n else # 'twitter', 'google', 'linkedin'\n user.profile_pic = open(user.image_url)\n end\n user.profile_pic.url\n end", "def picture_url\n if avatar\n image_path(\"speakers/#{avatar}\")\n else\n image_path(\"default-avatar.png\")\n end\n end", "def facebookProfilePicURL\n # https://www.facebook.com/user_name\n if facebook_url\n return \"https://graph.facebook.com/[PROFILE_ID]/picture\"\n else\n None\n end\n end", "def avatar_url\n avatar_uri(object)\n end", "def avatar_url(user)\n url = \"http://www.gravatar.com/avatar/#{Digest::MD5::hexdigest(user.email)}?d=mm\"\n image_tag(url, :alt => 'Avatar', :class => 'avatar')\n end", "def avatar_url(user)\n default_url = \"#{root_url}images/user-img.gif\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end", "def show\n if @user_profile.image.attachment \n @profile_image = @user_profile.image\n else\n @profile_image = \"https://api.adorable.io/avatars/200/#{current_user.username}\" \n end\n end", "def profile_picture\n profile_picture_file_name\n end", "def avatar_url(type = :small)\n \"#{authentications.first.avatar_url}?type=#{type}\"\n end", "def profile_url(size: 'w300')\n if profile_path.present?\n \"#{h.configuration.base_url}#{size}#{object[\"profile_path\"]}\"\n else\n \"http://dummyimage.com/300x450/d9d9d9/000000.png&text=N/A\"\n end\n end", "def author_picture_url\n @author_picture_url ||= begin\n if self.author_screenname\n \"http://twitter.com/api/users/profile_image/#{self.author_screenname}\"\n else\n image_path(\"default-avatar.png\")\n end\n end\n end", "def profile_picture_for(user)\n if user.picture?\n image_tag(user.picture.url, alt: user.name, class: \"profile_picture\")\n else\n image_tag(random_default_image, alt: user.name, class: \"profile_picture\")\n end\n end", "def profile_photo\n photos = self.profile_photos\n photos.empty? ? 'http://ragatzi.s3.amazonaws.com/uploads/profile_default_1.png' : photos.last.photo.url\n end", "def linked_in_avatar(user)\n image_tag(user.user_info[\"linked_in\"][\"image\"])\n end", "def avatar_url (size)\n if avatar.present?\n return avatar.url(size)\n # elsif provider == \"facebook\" and external_uid\n # return \"https://graph.facebook.com/#{external_uid}/picture\"\n else\n return \"http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(email.downcase)}\"\n end\n end", "def avatar_url(user_id, avatar_id)\n \"#{api_base}/users/#{user_id}/avatars/#{avatar_id}.jpg\"\n end", "def user_image_url # return the user image\n ((self.user_image.present?)?(self.user_image.url.to_s):nil) || self.photo_url || \"/assets/no-image.png\"\n end", "def profile_picture\n\t\tFbGraph::User.me(self.oauth_token).fetch.picture(width: 150, height: 200)\n\tend", "def blank_profile_pic_url(format = 'tiny')\n \"/images/profile_pictures/profile_blank_#{format}.png\"\n end", "def get_user_image(user,size)\n if img=user.image\n img.photo.url(size)\n else\n '/images/default-user-image-'+size.to_s+'.jpg'\n end\n end", "def avatar_url(user, size)\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}\"\n end", "def avatar_url(format = nil)\n return API::User.default_avatar(@discriminator) unless @avatar_id\n\n API::User.avatar_url(@id, @avatar_id, format)\n end", "def get_user_image(user_id)\n @user = User.find(:first,:select=>\"profile_image_url\",:conditions=>[\"id=#{user_id}\"])\n return @user.profile_image_url\n end", "def photo_url\n gravatar_id = Digest::MD5.hexdigest(email.downcase)\n \"https://gravatar.com/avatar/#{gravatar_id}.png\"\n end", "def gravatar_url\n hash = Digest::MD5.hexdigest(self.email)\n\n image_src = \"//www.gravatar.com/avatar/#{hash}?d=identicon\"\n end", "def user_avatar(user)\n user.avatar ? user.avatar.photo.url(:thumb) : \"default-avatar.jpg\"\n end", "def picture\n if self.avatar?\n self.avatar.url\n elsif self.image_url != nil\n self.image_url\n else\n 'generic_avatar'\n end\n end", "def profile_url\n @data[:profile_url]\n end", "def avatar_url\n\t\t\"http://zombitar.com/#{id}.jpg\"\n\tend", "def get_pic_url\n\t if !self.pic_url\n\t\t twit_u = User.get_twitter_user_from_name(self.screen_name)\n\t\t\tputs twit_u\n\t\t\tself.pic_url = twit_u[\"profile_image_url\"]\n\t\t\tself.save!\n\t\tend\n\tend", "def avatar_url(style = :small)\n if avatar_file_name\n avatar.url(style)\n else\n url = avatar.url(style)\n providers.each do |e|\n next unless e.image_url\n\n url = e.image_url\n end\n url\n end\n end", "def get_avatar_url(user_id)\n u = User.find_by_id( user_id)\n avatar = u.avatar.url(:thumb)\n unless u.avatar_file_size?\n avatar = false\n end\n return avatar || Settings.avatar_image \n end", "def avatar_url(options = {})\n options = {\n rating: 'pg',\n default: 'retro'\n }.merge(options)\n hash = Digest::MD5.hexdigest(object.email)\n\n uri = URI.parse(\"https://secure.gravatar.com/avatar/#{hash}\")\n uri.query = URI.encode_www_form(options)\n\n uri.normalize.to_s\n end", "def avatar_url\n return image_url if image_url\n return DEFAULT_AVATAR if email.nil?\n\n gravatar_url\n end", "def image_uri\n return \"/image_store/#{id}.#{profile_image}\"\n end", "def image_avatar_path(person, options={})\n options = {:name => :thumb, :anonymous => false}.merge(options).symbolize_keys\n source = options.delete(:source)\n return source if source \n name = options.delete(:name)\n anonymous = options.delete(:anonymous)\n\n if person && !anonymous && person.avatar.file?\n source = person.avatar.url(name)\n end\n if source.blank?\n if :profile == name.to_sym\n source = person && person.is_female? ? image_path('icons/avatars/female_large_turquoise.png') : image_path('icons/avatars/male_large_turquoise.png')\n else\n if person && person.partner?\n source = person.is_male? ? image_path('icons/avatars/male_green.png') : image_path('icons/avatars/female_green.png')\n else\n source = person && person.is_female? ? image_path('icons/avatars/female_blue.png') : image_path('icons/avatars/male_blue.png')\n end\n end\n end\n source\n end", "def avatar_url\n root = Rails.application.routes.url_helpers.url_for(:root)\n uri = URI(root)\n uri.path = avatar_path\n uri.to_s\n end", "def get_avatar\n u = User.find_by_id(self.id)\n if u.role == 'user'\n return u.avatar.url unless u.avatar.nil?\n else\n info = Info.find_by_email(self.email)\n return info.info_avatar.image.url unless info.nil?\n end\n return nil\n end", "def profile_image hash = {}\n image_name = hash.delete(:image_name) ||\n @controller.instance_variable_get(:@profile_user).feed.name.titlecase.\n gsub(/[\\/\\\\\\!\\@\\#\\$\\%\\^\\*\\&\\-\\.\\,\\?]+/, ' ').gsub(' ', '').underscore\n hash.update :action => 'profile_image', :id =>\n image_name, :format => (hash[:format] || 'jpeg'), :trailing_slash => false\n home(hash)\n end", "def author_avatar\n is_anonymous ? Avatar.default.url : user.profile.avatar.url\n end", "def user_image(user, options={})\n # get the email from URL-parameters or what have you and make lowercase\n email_address = user.email.downcase\n \n # create the md5 hash\n hash = Digest::MD5.hexdigest(email_address)\n\n query_string = hash_to_query_string(options.reverse_merge({\n :size => 100,\n :default => 'identicon'\n }))\n\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n \"http://www.gravatar.com/avatar/#{hash}#{query_string}\"\n end", "def tw_image_url(type)\n \"http://api.twitter.com/1/users/profile_image?user_id=#{tw_user_id}&size=#{type}\"\n end", "def author_avatar\n anonymous? ? Avatar.default.url : user.profile.avatar.url\n end", "def user_gravatar_url\n self.user.gravatar_url\n end", "def get_image_profile_pic\n last_pic = images.where(\"kind = ?\", \"profile_pic\").last\n\n if last_pic.nil?\n return \"/assets/octacat-resized.png\"\n else\n last_pic.url\n end\n end", "def avatar_url\n hash = Digest::MD5.hexdigest(email)\n \"http://www.gravatar.com/avatar/#{hash}\"\n end", "def avatar_url\n \"https://avatars.githubusercontent.com/u/#{uid}?v=2\"\n end", "def raster_profile_picture(user)\n if user.authentications.where(:provider == \"Facebook\").any?\n fb_picture(user)\n elsif user.authentications.where(:provider == \"Twitter\").any?\n twitter_picture(user, type: \"normal\") \n else\n image_tag user.avatar.url(:raster), class: \"img-circle small_profile_picture\"\n end\n end", "def getPicturePath\n\t\t#return User.find(self.user_id)\n @profile = Profile.find(:first, :conditions => {:user_id => self.user_id})\n if @profile.avatar != '' and @profile.avatar!=nil\n return @profile.avatar\n else\n return @profile.picture_path\n end\n\t\t#return Profile.find(:first, :conditions => {:user_id => self.user_id}).picture_path\n\tend", "def profile_urls\n Enceladus::Configuration::Image.instance.url_for(\"profile\", profile_path)\n end", "def profile_url\n nil\n end", "def smol_avatar_url\n # Gravatar uses MD5 hashes of people's email addresses, so it works well here.\n hash = Digest::MD5.hexdigest(email)\n \"http://www.gravatar.com/avatar/#{hash}?size=50px\"\n end", "def image\n require 'digest/md5'\n \"http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(author_email.downcase)}\"\n end", "def profile_photo_url(version)\n if self.photos.profile_photo.blank? \n \"#{version.to_s}_avtar.jpg\"\n else \n self.photos.profile_photo.first.name_url(version)\n end \n end", "def fb_image_url(type='square')\n \"http://graph.facebook.com/#{fb_user_id}/picture?type=#{type}\" \n end", "def avatar_url_for(person, options = {})\n return nil if person.nil?\n options = parse_options(person, options)\n field = options[:twitter_field]\n return nil if field.nil?\n twitter_name = person.send(field)\n return nil if twitter_name.nil?\n Twitter.profile_image(twitter_name, :size => options[:size])\n end", "def avatar\n \t\t# get the email from URL-parameters or what have you and make lowercase\n\t\temail_address = self.email.downcase\n\t\t \n\t\t# create the md5 hash\n\t\thash = Digest::MD5.hexdigest(email_address)\n\t\t \n\t\t# compile URL which can be used in <img src=\"RIGHT_HERE\"...\n\t\timage_src = \"http://www.gravatar.com/avatar/#{hash}\"\n \tend", "def social_profile_image(profile, options = { size: 80 })\n return nil if profile.nil?\n image_tag(profile.image_url, size: options[:size], alt: profile.identity.email)\n end", "def avatar_url\n @attributes[:avatar_url]\n end", "def avatar_url\n @attributes[:avatar_url]\n end", "def avatar_url\n @data['avatarUrl']\n end", "def avatar_url(options = {})\n base_url = if options[:ssl]\n \"https://secure.gravatar.com/avatar/\"\n else\n \"http://www.gravatar.com/avatar/\"\n end\n email_digest = Digest::MD5.hexdigest(email)\n \"#{base_url}#{email_digest}\"\n end", "def url\n URI.join(request.url, @picture.image.url)\n end", "def gravatar_img_src\n # Não usa facebook\n if self.uid.nil?\n # include MD5 gem, should be part of standard ruby install\n require 'digest/md5'\n # create the md5 hash\n hash = Digest::MD5.hexdigest(self.email.downcase)\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n self.image = \"http://www.gravatar.com/avatar/#{hash}\"\n end\n end", "def profile_url\n @json['user']['links']['self']\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def avatar\n config = Rails::Configuration.new\n\n Dir.glob(config.root_path + '/public/assets/users/user_' + self.id.to_s + '*').each do |entry|\n return '/assets/users/' + File.basename(entry)\n end\n\n '/images/users/user_default.png'\n end", "def direct_avatar(profile_url, http)\n resp = http.head('/pavatar.png')\n profile_url + (profile_url =~ /\\/$/ ? '' : '/') + 'pavatar.png' if resp.kind_of?(Net::HTTPSuccess)\n end", "def image_url\n \"https://graph.facebook.com/#{id}/picture\"\n end", "def avatar_url_for(person, options = {})\n person.nil? ? nil : url\n end" ]
[ "0.83991086", "0.8366859", "0.8138298", "0.8138133", "0.80715215", "0.8066858", "0.8061989", "0.8019302", "0.8017834", "0.7945696", "0.794209", "0.7894318", "0.7863307", "0.78624856", "0.78569233", "0.7840354", "0.78331876", "0.78296447", "0.78228533", "0.7821407", "0.78047466", "0.7786666", "0.7781785", "0.77691", "0.7768584", "0.7763518", "0.7727229", "0.77116704", "0.77104485", "0.77072036", "0.7699606", "0.76423764", "0.7641098", "0.7640406", "0.76376945", "0.7631561", "0.7627224", "0.76175666", "0.76025206", "0.7577736", "0.7576817", "0.7556689", "0.75505215", "0.75402814", "0.75397927", "0.753374", "0.7504973", "0.7501263", "0.74823606", "0.74784285", "0.74754155", "0.7465704", "0.7457549", "0.74537677", "0.7446568", "0.7435542", "0.74339205", "0.741815", "0.74117285", "0.74026835", "0.74000347", "0.7396803", "0.73822683", "0.73688775", "0.7367544", "0.7354499", "0.73541653", "0.73504585", "0.7344506", "0.7337117", "0.73340285", "0.73205477", "0.7311804", "0.7278448", "0.72780377", "0.72717774", "0.72424245", "0.7236789", "0.7218567", "0.72031254", "0.71973705", "0.71914214", "0.7190803", "0.7188421", "0.7158289", "0.7155507", "0.7149914", "0.71493006", "0.71493006", "0.7148123", "0.7141191", "0.7108987", "0.70978093", "0.70884776", "0.7087528", "0.7087528", "0.7085878", "0.70853704", "0.7084158", "0.70800334" ]
0.7244905
76
Return the secure URL to the user's profile image
def profile_image_uri_https(size=:normal) # The profile image URL comes in looking like like this: # https://a0.twimg.com/profile_images/1759857427/image1326743606_normal.png # It can be converted to any of the following sizes: # https://a0.twimg.com/profile_images/1759857427/image1326743606.png # https://a0.twimg.com/profile_images/1759857427/image1326743606_mini.png # https://a0.twimg.com/profile_images/1759857427/image1326743606_bigger.png ::URI.parse(@attrs[:profile_image_url_https].sub(PROFILE_IMAGE_SUFFIX_REGEX, profile_image_suffix(size))) if @attrs[:profile_image_url_https] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def profile_image_url(size=:normal)\n insecure_url(profile_image_url_https(size)) if profile_image_url?\n end", "def profile_url\n if self.profile and self.profile != \"\"\n return self.profile\n end\n return \"/blank.png\"\n end", "def image_url\n url_for(object.profile_pic)\n end", "def display_profile_image\n if self.picture.present? && self.picture.url(:small).present?\n self.picture.url(:small)\n else\n ActionController::Base.helpers.asset_path('user.png')\n end\n end", "def get_image_url( account_profile ) \n account_profile['profile_image_url']\n end", "def profile_picture_url\n hash = Digest::MD5.hexdigest(email)\n \"https://www.gravatar.com/avatar/#{hash}?d=mm\"\n end", "def user_img_URL\n self.user.image_url\n end", "def image_path\n uri_path = URI(profile_image_url).path\n extension = File.extname(uri_path)\n \"#{@base_path}/#{screen_name}#{extension}\"\n end", "def avatar_url(avatar_size=\"small\")\n if self.has_shelby_avatar\n return self.shelby_avatar_url(avatar_size)\n else\n return self.user_image_original || self.user_image || \"#{Settings::ShelbyAPI.web_root}/images/assets/avatar.png\"\n end\n end", "def profile_picture\n if facebook_authentication && facebook_authentication.profile_picture\n return facebook_authentication.profile_picture\n end\n return '/images/unknown_user.png'\n end", "def get_current_user_profile_image\n if ProfileImage.find_by(user_id: get_current_user.id).image_base64 != \"\"\n return ProfileImage.find_by(user_id: get_current_user.id)\n else\n return \"/img/logo/small-logo.png\"\n end\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def api_profile_picture_url\n return nil unless (temp_api_profile_picture_url = read_attribute(:api_profile_picture_url))\n # logger.debug2 \"temp_api_profile_picture_url = #{temp_api_profile_picture_url}\"\n encrypt_remove_pre_and_postfix(temp_api_profile_picture_url, 'api_profile_picture_url', 40)\n end", "def avatar_url\r\n return @user.avatar_url\r\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def avatar_url(user)\n if user.avatar_url.present?\n user.avatar_url\n else\n default_url = \"#{root_url}images/guest.png\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end\n end", "def user_profile_img(user)\n if user.avatar?\n return image_tag(user.avatar, alt: user.name, size: \"60x60\")\n else\n img_url = 'no_image.png'\n end\n image_tag(img_url, alt: user.name, size: \"60x60\")\n end", "def image\n if File.exist?(\"public/images/profile_images/#{self.username}.jpg\")\n img_path = \"/images/profile_images/#{self.username}.jpg\"\n else\n img_path = \"/images/default.jpg\"\n end\n return img_path\n end", "def profile_image_uri(size=:normal)\n ::URI.parse(insecure_uri(profile_image_uri_https(size))) if @attrs[:profile_image_url_https]\n end", "def profile_url(size: 'w300')\n if profile_path.present?\n \"#{h.configuration.base_url}#{size}#{object[\"profile_path\"]}\"\n else\n \"http://dummyimage.com/300x450/d9d9d9/000000.png&text=N/A\"\n end\n end", "def user_avatar_url(user = nil, variant:)\n if user.nil? || Rails.application.show_dummy_image?\n UsersHelper.no_avatar_path\n else\n user.avatar_image_location(variant: variant) || UsersHelper.no_avatar_path\n end.to_s\n end", "def get_profile_picture_url\n\t\tidentity = self.identities.find_by_provider_id(ApplicationController.fb_app[:id])\n\t\treturn ApplicationController.fb_app[:graph][:query_root_url] + identity.uid + \"/\" + ApplicationController.fb_app[:graph][:query_mypic_suffix]\t\t\n\tend", "def profile_pic_url\n result_hash['pic']\n end", "def avatar_url\n \"http://robohash.org/#{email}?gravatar=yes\"\n end", "def avatar_url(user)\n default_url = \"#{root_url}images/guest.jpg\"\n # BUG: Don't use gravatar as you can get someone else's gravatar with your name.\n # eg. Try signing up with name \"test meme\" ... it's some dude's distorted face\n # if user.profile\n # if user.profile.avatar_url.present?\n # user.profile.avatar_url\n # else\n # gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n # \"http://gravatar.com/avatar/#{gravatar_id}?s=200&d=#{CGI.escape(default_url)}\"\n # end\n # else\n # default_url\n # end\n end", "def get_profile_photo_url(photo)\n if photo != nil\n return photo.image.url(:thumb)\n else\n return 'user.png'\n end\n end", "def avatar_url(type = :small)\n \"#{authentications.first.avatar_url}?type=#{type}\"\n end", "def profile_image(profile)\n url = Gravatar.new(profile.display_email || '@').image_url size: 40,\n secure: true, default: :mm\n image_tag url, alt: \"gravatar for #{profile.name}\",\n style: 'width: 40px; height: 40px;'\n end", "def user_pic user\n \"<a href='#{site(user)}' title='#{user.city} #{user.jobs} #{user.maxim} #{user.memo}' target='_blank'><img width='48' height='48' src='#{user.avatar.thumb.url}' width='#{USER_THUMB_SIZE}' height='#{USER_THUMB_SIZE}'></a>\"\n end", "def blank_profile_pic_url(format = 'tiny')\n \"/images/profile_pictures/profile_blank_#{format}.png\"\n end", "def avatar_url\n if !self.fb_id.blank?\n return 'https://graph.facebook.com/%s/picture?width=90&height=90' % self.fb_id\n elsif !self.gpp_id.blank?\n return 'http://profiles.google.com/s2/photos/profile/%s?sz=90' % self.gpp_id\n else\n return ''\n end\n end", "def profile_picture\n profile_picture_file_name\n end", "def avatar_url(user)\n default_url = \"#{root_url}images/user-img.gif\"\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}\"\n end", "def avatar_url (size)\n if avatar.present?\n return avatar.url(size)\n # elsif provider == \"facebook\" and external_uid\n # return \"https://graph.facebook.com/#{external_uid}/picture\"\n else\n return \"http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(email.downcase)}\"\n end\n end", "def set_profile_picture_url(user)\n case user.provider\n when 'facebook'\n x = open(\"http://graph.facebook.com/v2.6/#{user.uid}/picture?redirect=false\", &:read)\n user.profile_pic = eval(x)[:data][:url]\n else # 'twitter', 'google', 'linkedin'\n user.profile_pic = open(user.image_url)\n end\n user.profile_pic.url\n end", "def user_avatar_url\n @raw['user']['avatar_url']\n end", "def facebookProfilePicURL\n # https://www.facebook.com/user_name\n if facebook_url\n return \"https://graph.facebook.com/[PROFILE_ID]/picture\"\n else\n None\n end\n end", "def gravatar_url\n hash = Digest::MD5.hexdigest(self.email)\n\n image_src = \"//www.gravatar.com/avatar/#{hash}?d=identicon\"\n end", "def photo_url\n gravatar_id = Digest::MD5.hexdigest(email.downcase)\n \"https://gravatar.com/avatar/#{gravatar_id}.png\"\n end", "def smol_avatar_url\n # Gravatar uses MD5 hashes of people's email addresses, so it works well here.\n hash = Digest::MD5.hexdigest(email)\n \"http://www.gravatar.com/avatar/#{hash}?size=50px\"\n end", "def gravatar_api_url(hash, ssl=false)\n if ssl\n \"https://secure.gravatar.com/avatar/#{hash}\"\n else\n \"http://www.gravatar.com/avatar/#{hash}\"\n end\n end", "def profile_img(uid, type=\"normal\")\n \"http://graph.facebook.com/#{uid}/picture?type=#{type}\"\n end", "def picture_url\n if avatar\n image_path(\"speakers/#{avatar}\")\n else\n image_path(\"default-avatar.png\")\n end\n end", "def profile_image_url_https(size=:normal)\n # The profile image URL comes in looking like like this:\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_normal.png\n # It can be converted to any of the following sizes:\n # https://a0.twimg.com/profile_images/1759857427/image1326743606.png\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_mini.png\n # https://a0.twimg.com/profile_images/1759857427/image1326743606_bigger.png\n resize_profile_image_url(@attrs[:profile_image_url_https], size) if profile_image_url?\n end", "def avatar_url(user, size)\n gravatar_id = Digest::MD5.hexdigest(user.email.downcase)\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}\"\n end", "def image_uri\n return \"/image_store/#{id}.#{profile_image}\"\n end", "def avatar_url(options = {})\n base_url = if options[:ssl]\n \"https://secure.gravatar.com/avatar/\"\n else\n \"http://www.gravatar.com/avatar/\"\n end\n email_digest = Digest::MD5.hexdigest(email)\n \"#{base_url}#{email_digest}\"\n end", "def avatar_url(options = {})\n options = {\n rating: 'pg',\n default: 'retro'\n }.merge(options)\n hash = Digest::MD5.hexdigest(object.email)\n\n uri = URI.parse(\"https://secure.gravatar.com/avatar/#{hash}\")\n uri.query = URI.encode_www_form(options)\n\n uri.normalize.to_s\n end", "def twitter_profile_image\n @profile_image ||= begin\n require 'open-uri'\n require 'json'\n buffer = open(\"http://twitter.com/users/show/#{self.twitter_screen_name}.json\").read\n result = JSON.parse(buffer)\n result['profile_image_url']\n end\n end", "def user_image(user, options={})\n # get the email from URL-parameters or what have you and make lowercase\n email_address = user.email.downcase\n \n # create the md5 hash\n hash = Digest::MD5.hexdigest(email_address)\n\n query_string = hash_to_query_string(options.reverse_merge({\n :size => 100,\n :default => 'identicon'\n }))\n\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n \"http://www.gravatar.com/avatar/#{hash}#{query_string}\"\n end", "def get_user_image(user,size)\n if img=user.image\n img.photo.url(size)\n else\n '/images/default-user-image-'+size.to_s+'.jpg'\n end\n end", "def user_image_url # return the user image\n ((self.user_image.present?)?(self.user_image.url.to_s):nil) || self.photo_url || \"/assets/no-image.png\"\n end", "def avatar_url\n root = Rails.application.routes.url_helpers.url_for(:root)\n uri = URI(root)\n uri.path = avatar_path\n uri.to_s\n end", "def profile_pic_url\n json[\"entry_data\"][\"ProfilePage\"].first[\"graphql\"][\"user\"][\"profile_pic_url\"]\n end", "def avatar_url(user_id, avatar_id)\n \"#{api_base}/users/#{user_id}/avatars/#{avatar_id}.jpg\"\n end", "def avatar_url(user)\n url = \"http://www.gravatar.com/avatar/#{Digest::MD5::hexdigest(user.email)}?d=mm\"\n image_tag(url, :alt => 'Avatar', :class => 'avatar')\n end", "def avatar_url\n hash = Digest::MD5.hexdigest(email)\n \"http://www.gravatar.com/avatar/#{hash}\"\n end", "def show\n if @user_profile.image.attachment \n @profile_image = @user_profile.image\n else\n @profile_image = \"https://api.adorable.io/avatars/200/#{current_user.username}\" \n end\n end", "def avatar_url\n avatar_uri(object)\n end", "def profile_url\n @data[:profile_url]\n end", "def avatar_url\n return image_url if image_url\n return DEFAULT_AVATAR if email.nil?\n\n gravatar_url\n end", "def author_picture_url\n @author_picture_url ||= begin\n if self.author_screenname\n \"http://twitter.com/api/users/profile_image/#{self.author_screenname}\"\n else\n image_path(\"default-avatar.png\")\n end\n end\n end", "def avatar_url(style = :small)\n if avatar_file_name\n avatar.url(style)\n else\n url = avatar.url(style)\n providers.each do |e|\n next unless e.image_url\n\n url = e.image_url\n end\n url\n end\n end", "def get_avatar_url(user_id)\n u = User.find_by_id( user_id)\n avatar = u.avatar.url(:thumb)\n unless u.avatar_file_size?\n avatar = false\n end\n return avatar || Settings.avatar_image \n end", "def user_gravatar_url\n self.user.gravatar_url\n end", "def avatar_url\n\t\t\"http://zombitar.com/#{id}.jpg\"\n\tend", "def profile_url\n nil\n end", "def url\n URI.join(request.url, @picture.image.url)\n end", "def linked_in_avatar(user)\n image_tag(user.user_info[\"linked_in\"][\"image\"])\n end", "def gravatar_url\n stripped_email = email.strip\n downcased_email = stripped_email.downcase\n hash = Digest::MD5.hexdigest(downcased_email)\n \n \"http://gravatar.com/avatar/#{hash}\"\n end", "def get_pic_url\n\t if !self.pic_url\n\t\t twit_u = User.get_twitter_user_from_name(self.screen_name)\n\t\t\tputs twit_u\n\t\t\tself.pic_url = twit_u[\"profile_image_url\"]\n\t\t\tself.save!\n\t\tend\n\tend", "def picture\n if self.avatar?\n self.avatar.url\n elsif self.image_url != nil\n self.image_url\n else\n 'generic_avatar'\n end\n end", "def profile_urls\n Enceladus::Configuration::Image.instance.url_for(\"profile\", profile_path)\n end", "def get_user_image(user_id)\n @user = User.find(:first,:select=>\"profile_image_url\",:conditions=>[\"id=#{user_id}\"])\n return @user.profile_image_url\n end", "def profile_picture_for(user)\n if user.picture?\n image_tag(user.picture.url, alt: user.name, class: \"profile_picture\")\n else\n image_tag(random_default_image, alt: user.name, class: \"profile_picture\")\n end\n end", "def image_avatar_path(person, options={})\n options = {:name => :thumb, :anonymous => false}.merge(options).symbolize_keys\n source = options.delete(:source)\n return source if source \n name = options.delete(:name)\n anonymous = options.delete(:anonymous)\n\n if person && !anonymous && person.avatar.file?\n source = person.avatar.url(name)\n end\n if source.blank?\n if :profile == name.to_sym\n source = person && person.is_female? ? image_path('icons/avatars/female_large_turquoise.png') : image_path('icons/avatars/male_large_turquoise.png')\n else\n if person && person.partner?\n source = person.is_male? ? image_path('icons/avatars/male_green.png') : image_path('icons/avatars/female_green.png')\n else\n source = person && person.is_female? ? image_path('icons/avatars/female_blue.png') : image_path('icons/avatars/male_blue.png')\n end\n end\n end\n source\n end", "def author_avatar\n anonymous? ? Avatar.default.url : user.profile.avatar.url\n end", "def gravatar_url\n # to remove white spaces from email\n stripped_email = email.strip\n downcased_email = stripped_email.downcase\n hash = Digest::MD5.hexdigest(downcased_email)\n \"http://gravatar.com/avatar/#{hash}\"\n end", "def fb_image_url(type='square')\n \"http://graph.facebook.com/#{fb_user_id}/picture?type=#{type}\" \n end", "def avatar_url\n \"https://avatars.githubusercontent.com/u/#{uid}?v=2\"\n end", "def tw_image_url(type)\n \"http://api.twitter.com/1/users/profile_image?user_id=#{tw_user_id}&size=#{type}\"\n end", "def big_avatar_url\n # Gravatar uses MD5 hashes of people's email addresses, so it works well here.\n hash = Digest::MD5.hexdigest(email)\n \"http://www.gravatar.com/avatar/#{hash}?size=800px\"\n end", "def profile_photo\n photos = self.profile_photos\n photos.empty? ? 'http://ragatzi.s3.amazonaws.com/uploads/profile_default_1.png' : photos.last.photo.url\n end", "def gravatar_image_url(size_in_pixels=32)\n email_hash = Digest::MD5.hexdigest(email.strip.downcase)\n \"https://secure.gravatar.com/avatar/#{ email_hash }?s=#{ size_in_pixels.to_i }&d=retro\"\n end", "def avatar_url(size)\n gravatar_id = Digest::MD5::hexdigest(self.email).downcase\n \"http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}\"\n end", "def get_avatar\n u = User.find_by_id(self.id)\n if u.role == 'user'\n return u.avatar.url unless u.avatar.nil?\n else\n info = Info.find_by_email(self.email)\n return info.info_avatar.image.url unless info.nil?\n end\n return nil\n end", "def author_avatar\n is_anonymous ? Avatar.default.url : user.profile.avatar.url\n end", "def profile_image hash = {}\n image_name = hash.delete(:image_name) ||\n @controller.instance_variable_get(:@profile_user).feed.name.titlecase.\n gsub(/[\\/\\\\\\!\\@\\#\\$\\%\\^\\*\\&\\-\\.\\,\\?]+/, ' ').gsub(' ', '').underscore\n hash.update :action => 'profile_image', :id =>\n image_name, :format => (hash[:format] || 'jpeg'), :trailing_slash => false\n home(hash)\n end", "def gravatar_img_src\n # Não usa facebook\n if self.uid.nil?\n # include MD5 gem, should be part of standard ruby install\n require 'digest/md5'\n # create the md5 hash\n hash = Digest::MD5.hexdigest(self.email.downcase)\n # compile URL which can be used in <img src=\"RIGHT_HERE\"...\n self.image = \"http://www.gravatar.com/avatar/#{hash}\"\n end\n end", "def gravatar_image_url(email = nil, size = nil)\n url = '//www.gravatar.com/avatar/'\n url += if email\n Digest::MD5.hexdigest(email)\n else\n '0' * 32\n end\n size ? \"#{url}?size=#{size}\" : url\n end", "def getPicturePath\n\t\t#return User.find(self.user_id)\n @profile = Profile.find(:first, :conditions => {:user_id => self.user_id})\n if @profile.avatar != '' and @profile.avatar!=nil\n return @profile.avatar\n else\n return @profile.picture_path\n end\n\t\t#return Profile.find(:first, :conditions => {:user_id => self.user_id}).picture_path\n\tend", "def avatar_url(format = nil)\n return API::User.default_avatar(@discriminator) unless @avatar_id\n\n API::User.avatar_url(@id, @avatar_id, format)\n end", "def user_url\n @raw['user']['url']\n end", "def raster_profile_picture(user)\n if user.authentications.where(:provider == \"Facebook\").any?\n fb_picture(user)\n elsif user.authentications.where(:provider == \"Twitter\").any?\n twitter_picture(user, type: \"normal\") \n else\n image_tag user.avatar.url(:raster), class: \"img-circle small_profile_picture\"\n end\n end", "def profile_picture\n\t\tFbGraph::User.me(self.oauth_token).fetch.picture(width: 150, height: 200)\n\tend", "def profile_banner_url(size=:web)\n insecure_url([@attrs[:profile_banner_url], size].join('/')) if profile_banner_url?\n end", "def gravatar_path\n \"/avatar/#{Digest::MD5.hexdigest(email)}?s=48&r=r&d=#{ENCODED_DEFAULT_AVATAR}\"\n end", "def user_avatar(user)\n user.avatar ? user.avatar.photo.url(:thumb) : \"default-avatar.jpg\"\n end", "def image_url\n image.presence or (email.present? and gravatar_url) or Guest::IMAGE_URL\n end", "def image_url(style='original')\n ENV[\"domain\"] + self.picture.image.url(:original) if self.picture.present?\n end" ]
[ "0.81058383", "0.7958155", "0.78643423", "0.7643549", "0.75786215", "0.7572952", "0.75723356", "0.75454056", "0.74461323", "0.74282527", "0.74064827", "0.74060076", "0.74060076", "0.7391989", "0.73644364", "0.7363571", "0.7362", "0.73546225", "0.7346148", "0.7340833", "0.7338404", "0.73365664", "0.73154235", "0.72925085", "0.7290027", "0.7226402", "0.7211453", "0.72055095", "0.7154527", "0.71481955", "0.7146787", "0.71421415", "0.7135948", "0.71307015", "0.7121002", "0.7092573", "0.70889467", "0.7084503", "0.70729184", "0.7068036", "0.7058363", "0.7054859", "0.7050256", "0.7026219", "0.702616", "0.7004217", "0.7002639", "0.6998174", "0.6993709", "0.69804925", "0.697433", "0.6972867", "0.69684786", "0.696397", "0.69607645", "0.6954325", "0.6947742", "0.69471705", "0.69358456", "0.69235086", "0.6902307", "0.6896441", "0.68826073", "0.6876606", "0.68745756", "0.6869808", "0.6861588", "0.68403274", "0.6828034", "0.68263793", "0.68220323", "0.6815695", "0.6801729", "0.6785128", "0.6784222", "0.67679125", "0.67606825", "0.6741704", "0.6740417", "0.6719406", "0.67170495", "0.6716548", "0.67146254", "0.67139155", "0.6706717", "0.670633", "0.6702937", "0.6698104", "0.66951174", "0.66943264", "0.6693975", "0.6684142", "0.6683709", "0.6674329", "0.6669512", "0.6666897", "0.66647315", "0.6663006", "0.6658844", "0.6653067" ]
0.6887495
62
Determines whether the NFA accepts a given string.
def accepts?(input) resp = feed(input) resp[:accept] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def isNFA?\n if isValid? then \n if @alphabet.include? \"\" then\n return true\n else\n combo = []\n @transition_rules.each do |transition|\n combo.push([transition.current_state, transition.input_char])\n if combo.count != combo.uniq.count then\n return true \n end\n end\n end\n end\n return false\n end", "def decide string\n @current_state = @start_state\n string.each_char do |c|\n if !@alphabet.include? c then\n return false\n end\n transition = false\n @transition_rules.each do |rule|\n if rule.input_char === c && rule.current_state === @current_state then\n transition = rule\n break\n end\n end\n if !transition then \n return false\n else\n @current_state = transition.end_state\n end\n end\n\n if @accept_states.include? @current_state then\n return true\n else\n return false\n end\n end", "def include?(str)\n fa.accepts?(str)\n end", "def apply?(str)\n !!(regexp.match(str))\n end", "def verify_choice_ok (choice)\r\n if \"adehlnq+?\".include? (choice)\r\n return true\r\n else\r\n return false\r\n end\r\nend", "def is? str\n !!match(str)\n end", "def check_string( str )\r\n result = false\r\n return result unless validate_string(str)\r\n\r\n if str.include?( self.pattern )\r\n result = true\r\n end\r\n return result\r\n end", "def prad_valid? str\n return false unless str\n !!parse(str)\n end", "def attempt?(string)\n string = string.strip.downcase\n if answer_is_integer?\n return string == answer || string == HumaneInteger.new(answer.to_i).to_english\n else\n return string == answer.downcase\n end\n end", "def yours?(str)\n str[0..1] == 'BA'\n end", "def username_arg_ok? username\n return false if username.nil?\n return false unless (1..16) === username.length\n return false unless username.match /\\A[0-9a-zA-Z]*\\z/\n \n # oh? okay, all good.\n true\n end", "def match? str, name\n rule = rule(name)\n raise \"no such rule: #{name.inspect}\" unless rule\n rest = rule.match? str\n return false unless rest && rest.empty?\n true\n end", "def validate_string( str )\r\n if str.kind_of?(String)\r\n return true\r\n else\r\n puts \"#{self.class}:check_string: Error: Input must be a string.\"\r\n return false\r\n end\r\n end", "def check_string(s)\r\n\t\treturn s.length == @m*@n\r\n\tend", "def panagram?(string)\nend", "def correct?(string)\n \"#{string}\".downcase == self.string.downcase\n end", "def check_string(string)\n\tzombie_apocalypse_supplies = [\"hatchet\", \"rations\", \"water jug\", \"binoculars\",\n \"shotgun\", \"compass\", \"CB radio\", \"batteries\"]\n\tzombie_apocalypse_supplies.each do |item|\n\t\tif string.downcase == item.downcase\n\t\t\treturn true\n\t\tend\n\tend\n false\nend", "def can_encode?(str)\n str.nil? || !(GSM_REGEX =~ str).nil?\n end", "def valid_case_string?()\n LuckyCase.case(self) != nil\n end", "def valid_substring?(string)\n !!@pointer.node_at(string)\n end", "def valid?(string)\n r = Regexp.new(@matcher)\n \n !(string =~ r).nil?\n end", "def validity_check\n\n if strand == '+'\n\n codon = ref_seq[0..2].map(&:last).join\n return true if codon.include?('N')\n codon == 'ATG'\n\n elsif strand == '-'\n\n codon = ref_seq[-3..-1].map(&:last).join\n return true if codon.include?('N')\n codon == 'CAT'\n\n end\n\n end", "def valid_play?(string)\n unless (\"a\"..\"z\").to_a.include?(string)\n return false\n end\n\n newFragment = @fragment + string\n\n # if @dictionary.empty?\n # dictionary\n # end\n\n wordIncludeFragment = dictionary.any? do |word|\n # debugger\n # puts '#{word}'\n word.start_with?(newFragment)\n end\n\n if wordIncludeFragment\n return true\n end\n\n false\n end", "def valid_name?(nm)\n\t\treturn false unless (nm =~ VALID_NAME)\n\t\ttrue\n\tend", "def accept?(str)\n raise(\"no final state\") if @final.nil?\n cursor = @initial\n str.each_char { |chr|\n transition = self.follow(cursor, chr)\n return false unless transition\n cursor = transition\n }\n cursor == @final\n end", "def match?(string)\n bigrams = get_bigrams(string)\n while bigrams.length > 1\n pair = bigrams.shift\n return true if bigrams[1..-1].include?(pair)\n end\nend", "def anagram?(string)\n length_matches(string) && character_count_matches(string)\n end", "def valid_string?(string)\n if string.class == String\n string\n else\n false\n end\nend", "def filters?(str); end", "def filters?(str); end", "def has_sin?(string)\n return !(string.match(/(\\b)(\\w{3})-(\\w{3})-(\\w{3})/).nil?)\nend", "def string?(string, &block)\n string !~ /\\0/ && runner( String, string, &block )\n end", "def can_encode?(str, charset: BASIC_CHARSET)\n !str || !!(regex(charset) =~ str)\n end", "def is_valid_name(str)\n\tnames_arr = str.split(\" \")\n if names_arr.length < 2\n return false\n end\n\n \tnames_arr.each do |name|\n if check_case(name)\n return true\n \n else\n return false\n end\n end \nend", "def carefull_name?(name)\n not !! (name =~ /\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}/)\nend", "def match?(name, literal) true end", "def matched?(str)\r\n # puts \">>> #{self.matcher.source}\"\r\n # puts \">>> #{str}\"\r\n return false if (!self.implicit && str[0] != \"!\")\r\n if (self.matcher =~ str) != nil\r\n $bot.last_match = $~\r\n $log.info(\"/#{self.matcher.source}/ matched #{str}\")\r\n return true\r\n end\r\n false\r\n end", "def is_var(str)\n\t(\"a\"..\"z\").to_a.include?(str)\nend", "def is_isogram(string)\n return false if string.class != String\n string = string.downcase\n used_letters = []\n string.split(\"\").each do |e|\n if used_letters.include?(e)\n return false\n else\n used_letters << e\n end\n end\n return true\nend", "def match_name?(gotten_name, requested_name)\n gotten_name.text.strip.downcase == requested_name.downcase\n end", "def ion(input)\n\t(/^[a-zA-Z]{1}([a-zA-Z]{2})*(ion)$/ =~ input)? \"true\" : \"false\"\nend", "def reserved_word?(str)\n RESERVED_WORDS.include?(str.downcase)\n end", "def valid?(text)\n Gman.new(text).valid?\n end", "def accept? text\r\n !text.match(@regexp).nil?\r\n end", "def letter?(s)\n\ts =~ /[A-Za-z]/\nend", "def ABCheck(str)\n\n return \"true\" if str=~(/a...b/) or str=~(/b...a/)\n return \"false\"\n \nend", "def valid_name?(name)\n !!(name =~ NAME_REGEX)\n end", "def is_strname?(); @type == GRT_STRNAME; end", "def panagram2?(string)\n ('a'..'z').all? { |letter| string.downcase.include?(letter) }\nend", "def term_valid?(term)\n term.is_a?(String)\n end", "def valid_string?(field, param)\n true\n end", "def name(input)\n\t(/[a-zA-Z]+(\\,|\\s)(\\s)?[a-zA-Z]+(\\,|\\s)(\\s)?[a-zA-Z]+(\\.)?/i =~ input)? \"true\" : \"false\"\nend", "def string_validator(string, parameter)\n \n\tif string.length <= $MIN_LENGTH\n puts \"The #{parameter} requires at least #{$MIN_LENGTH} letters\"\n\t\treturn false\n\telsif string != string.gsub(/[^0-9a-z]/i, '')\n puts \"The #{parameter} can only contain alpha numeric characters \"\\\n\t\t \"(no spaces or special characters)\"\n\t\treturn false\n\telsif string !~ /[A-Z]/\n\t puts \"The #{parameter} requires an uppercase character\"\n\t\treturn false\n elsif string !~ /[a-z]/\n\t puts \"The #{parameter} requires an lowercase character\"\n\t\treturn false\n elsif string !~ /\\d/\n\t puts \"The #{parameter} requires numeric character\"\n\t\treturn false\n end\n\n\treturn true\nend", "def valid_answer?( answer_string )\n @validate.nil? or\n (@validate.is_a?(Regexp) and answer_string =~ @validate) or\n (@validate.is_a?(Proc) and @validate[answer_string])\n end", "def match?(str)\n !!(str =~ @regex)\n end", "def match?(str)\n !!(str =~ @regex)\n end", "def nick?(str)\n str.match(nick_regex) != nil\n end", "def is_valid_name(str)\n parts = str.split(\" \")\n isTrue = true\n parts.each do |part|\n if part[0] == part[0].downcase\n isTrue = false\n end\n part[1..-1].each_char do |chr|\n if chr == chr.upcase\n isTrue = false\n end\n end\n end \n return isTrue && parts.length > 1\nend", "def user_verify(answer)\n answer.downcase!\n if answer.start_with?('y')\n return true\n else\n return false\n end\nend", "def matches?(input_string)\n @word_list.include? input_string\n end", "def name?(name)\n name = name&.strip\n !(name.blank? || name.match?(%r{(N[/\\\\]+A|UNKNOWN)}i))\n end", "def validate_string(string)\n !string.match(/\\A[-a-zA-Z0-9]*\\z/).nil?\n end", "def starts_with_consonant?(s)\n # YOUR CODE HERE\n /^[b-df-hj-np-tv-z]/i.match(s) != nil\nend", "def match?(name); end", "def nmap_validate_arg(str)\n # Check for existence\n if str.nil? || str.empty?\n print_error \"Missing nmap argument\"\n return false\n end\n # Check for quote balance\n if !(str.scan(/'/).size % 2).zero? or !(str.scan(/\"/).size % 2).zero?\n print_error \"Unbalanced quotes in nmap argument: #{str}\"\n return false\n end\n # Check for characters that enable badness\n disallowed_characters = /([\\x00-\\x19\\x21\\x23-\\x26\\x28\\x29\\x3b\\x3e\\x60\\x7b\\x7c\\x7d\\x7e-\\xff])/n\n badchar = str[disallowed_characters]\n if badchar\n print_error \"Malformed nmap arguments (contains '#{badchar}'): #{str}\"\n return false\n end\n # Check for commas outside of quoted arguments\n quoted_22 = /\\x22[^\\x22]*\\x22/n\n requoted_str = str.tr('\\'','\"')\n if requoted_str.split(quoted_22).join[/,/]\n print_error \"Malformed nmap arguments (unquoted comma): #{str}\"\n return false\n end\n return true\nend", "def letter(input)\n\t(/[a-zA-Z]{2,}(\\,)\\s?[A-Z]{2}(\\s)([0-9]{5}|[0-9]{5}(\\-)?[0-9]{4}|[a-zA-Z]{1}[0-9]{1}[a-zA-Z]{1}(\\s|\\-)?[0-9]{1}[a-zA-Z]{1}[0-9]{1})}/i =~ input)? \"true\" : \"false\"\nend", "def can_show? str\n \treturn not(str.nil? || str === \"\")\n end", "def include?(str)\n @name.index(str) >= 0\n end", "def in_both?(string)\n\t\t[\"elsif\",\"else\",\"when\",\"rescue\",\"ensure\"].each{|x|\n\t\treturn true if string.lstrip.slice(/^#{x}/)\n\t\t}\n\t\tfalse\n\tend", "def is_string?(); @type == GRT_STRING; end", "def starts_with_consonant?(s)\n !!(s =~ /^[A-Z&&[^AEIOU]]/i)\nend", "def match?(given_names); end", "def supports_inflection(str)\n str.is_a?(String) &&\n (str.production? || true)\n rescue\n false\n end", "def is_valid_name?(name)\n return name.class == String && name.match(/[a-zA-Z]+?/)\n end", "def starts_with_consonant?(s)\n s.downcase!\n if (s =~ /\\A[b-df-hj-np-tv-z]/) == 0 \n return true\n else\n return false\n end\nend", "def ismatch(string)\n (string =~ @pattern) ? true : false\n end", "def has_special_ch?(str)\n (str =~ @@regex)?true:false\n end", "def isIdentifier(str)\n digitsOfAlphabet = getAlphabet[0] # if its a digit\n charsOfAlphabet = getAlphabet[1] # if a letter\n\n # first character in name cannot be digit\n if digitsOfAlphabet.include?(str[0])\n return false\n end\n\n # if keyword includes str\n if getKeywords.include?(str)\n return false\n end\n\n # check is in the alphabet\n for i in 1..str.size-1\n character = str[i]\n\n unless digitsOfAlphabet.include?(character) or charsOfAlphabet.include?(character)\n return false\n end\n end\n\n return true\nend", "def letter?(string)\n string =~ /[A-Za-z]/\n end", "def string_check(elem)\n (('a'..'z').to_a + ('A'..'Z').to_a).each { |k| return true if elem.include?(k) }\n false\n end", "def correct?(str)\n str = str.is_a?(String) ? str : str.to_s\n str == (@answer.is_a?(String) ? @answer : @answer.to_s) # don't change @answer type\n end", "def accept?(s, current = @start)\n if s == \"\"\n is_final?(current)\n else\n dest = get_transition(current,s[0,1])\n if dest == nil\n false\n else\n accept?(s[1..-1], dest)\n end\n end\n end", "def is_valid_name(str)\n\twords = str.split(\" \")\n \tif words.length >= 2\n \twords.each do |word|\n temp = word[0].upcase + word[1..-1].downcase\n if temp != word\n return false\n end\n end\n return true\n end\n return false\nend", "def validate_alpha_accent str\n\t\t\t(ActiveSupport::Inflector.transliterate(str) =~ /^[a-zA-Z\\'\\-\\s]*$/ ) == nil ? false : true\n\t\tend", "def is_valid_name(str)\n\tnames = str.split(\" \")\n \tif names.length < 2\n return false\n end\n \n \tnames.each do | name |\n if(name[0] != name[0].upcase || name[1..-1] != name[1..-1].downcase)\n return false\n end\n end\n return true\nend", "def is_valid_name(name)\n return false if name.split.length < 2\n name == format_name(name)\nend", "def complete_expression?(str); end", "def accept?(s, current = @start)\n if s == \"\"\n is_final?(current)\n else\n dest = get_transition(current, s[0,1])\n if dest == nil\n false\n else\n accept?(s[1..-1], dest)\n end\n end\n end", "def valid?\n invalid_strings = %w[ab cd pq xy]\n invalid_strings.each do |x|\n return false if include?(x)\n end\n\n true\n end", "def valid_acn?\n return false unless @acn.is_a?(String)\n return false if (@acn =~ /^[0-9]{9}$/).nil?\n weighting = [8,7,6,5,4,3,2,1]\n chksum = 0\n (0..7).each do |d|\n chksum += @acn[d].to_i * weighting[d]\n end\n return (10 - chksum % 10) % 10 == @acn[8].to_i\n rescue => e\n puts \"Error: #{e.class}\\n#{e.backtrace.join(\"\\n\")}\"\n return false\n end", "def host_label?(str)\n str =~ /^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)$/\n end", "def check_str(str,s)\n if str.include?s\n puts \"true\"\n else\n puts \"false\"\n end\nend", "def abCheck(str)\n\treturn false if(str.include?('a') == false || str.include?('b') == false || str.rindex('b') < str.rindex('a'))\n\treturn str.rindex('b') - str.rindex('a') == 4\n\t\nend", "def name_valid?(name)\n name.nil? || /^[A-Za-z]{2,}$/.match?(name)\n end", "def name_matches?(pattern)\n name.match(pattern)\n end", "def name_is_valid?(user, name)\n\t\t\tuser.respond_to? \"#{name}s_participating\" and [\"event\",\"class\",\"game\", \"offering_session\", \"personal_trainer\", \"group_training\"].include? name.underscore\n\t\tend", "def string?(input)\n input.class == String\nend", "def base_term?\n return @is_a_str.count==0\n end", "def validate(noun)\n return false if noun.is_proper?\n\n s = noun.to_s\n return false if s.nil?\n return false if s.length <= 1\n\n @@patterns.each do |pattern|\n return false if s =~ pattern\n end\n\n return true\n end", "def has_a_b?(string)\n\tif /b/.match(string)\n\t\tputs \"We have a match!\"\n\telse\n\t\tputs \"No match here.\"\n\tend\nend", "def ssn(input)\n\t(/(\\d){3}(-?)(\\d){2}(-?)(\\d){4}/ =~ input)? \"true\" : \"false\"\nend" ]
[ "0.6675932", "0.6577142", "0.6505087", "0.64102805", "0.63964826", "0.6392033", "0.63919264", "0.62675434", "0.6210856", "0.6210753", "0.615116", "0.6150965", "0.6089369", "0.6027092", "0.60260725", "0.6019783", "0.60065895", "0.60019", "0.6001774", "0.5995471", "0.59788066", "0.5971263", "0.59685856", "0.5967712", "0.59640855", "0.59279704", "0.5924723", "0.592439", "0.5911696", "0.5911696", "0.59068036", "0.58954483", "0.5894705", "0.5885202", "0.58767474", "0.5876715", "0.58730847", "0.58661866", "0.5850014", "0.5845221", "0.5844398", "0.5836146", "0.5831134", "0.5826773", "0.582544", "0.5823626", "0.5812247", "0.58100843", "0.5803479", "0.58032423", "0.579736", "0.5795849", "0.5793845", "0.57915485", "0.5787973", "0.5787973", "0.5784983", "0.5783654", "0.5780925", "0.57801706", "0.57753456", "0.57623875", "0.5754182", "0.57503265", "0.5749405", "0.57465214", "0.5745381", "0.57393247", "0.57306445", "0.5729472", "0.57285523", "0.57170784", "0.5710465", "0.5708974", "0.5707819", "0.57051325", "0.5703416", "0.5698446", "0.56975913", "0.5689382", "0.56862926", "0.5684605", "0.5680851", "0.56733656", "0.5672987", "0.5671253", "0.5667263", "0.5664003", "0.565738", "0.5654635", "0.56546247", "0.56462216", "0.5645227", "0.56425583", "0.5639501", "0.5633557", "0.56226814", "0.56187266", "0.5616221", "0.56141335", "0.5608595" ]
0.0
-1
Determines whether or not any transition states exist given a beginning state and input symbol pair.
def has_transition?(state, symbol) return false unless @transitions.include? state @transitions[state].has_key? symbol end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accepts_zero_characters(start_state, end_state)\n marked_states = Set.new\n state_stack = [start_state]\n while !state_stack.empty?\n state = state_stack.pop\n next if marked_states.include? state.id\n marked_states.add(state.id)\n return true if state.id == end_state.id\n state.edges.each do |label, dest_state|\n next unless label.contains? EPSILON\n state_stack << dest_state\n end\n end\n false\n end", "def valid?\n valid_symbol? && valid_states?\n end", "def checkExist(state)\n\ti=0\n\tuntil i==$transition_array.length\n\t\tif $transition_array[i][0] == state\n\t\t\treturn true\n\t\tend\n\t\ti = i+1\n\tend\n\treturn false\nend", "def has_state?\n !@states.empty?\n end", "def isInTransition()\n\t\t\treturn @_state == nil\n\t\tend", "def has_state(name)\n !@_possible_states[name].nil?\n end", "def aasm_states_to_check\n started? || aasm_event == 'start' || ignore_states\n end", "def reaches_state(start_state, target_state, states)\n if ((start_state).equal?(target_state))\n states.add(target_state)\n # System.out.println(\"found target DFA state \"+targetState.getStateNumber());\n @state_reachable.put(start_state.attr_state_number, REACHABLE_YES)\n return true\n end\n s = start_state\n # avoid infinite loops\n @state_reachable.put(s.attr_state_number, REACHABLE_BUSY)\n # look for a path to targetState among transitions for this state\n # stop when you find the first one; I'm pretty sure there is\n # at most one path to any DFA state with conflicting predictions\n i = 0\n while i < s.get_number_of_transitions\n t = s.transition(i)\n edge_target = t.attr_target\n target_status = @state_reachable.get(edge_target.attr_state_number)\n if ((target_status).equal?(REACHABLE_BUSY))\n # avoid cycles; they say nothing\n i += 1\n next\n end\n if ((target_status).equal?(REACHABLE_YES))\n # return success!\n @state_reachable.put(s.attr_state_number, REACHABLE_YES)\n return true\n end\n if ((target_status).equal?(REACHABLE_NO))\n # try another transition\n i += 1\n next\n end\n # if null, target must be REACHABLE_UNKNOWN (i.e., unvisited)\n if (reaches_state(edge_target, target_state, states))\n states.add(s)\n @state_reachable.put(s.attr_state_number, REACHABLE_YES)\n return true\n end\n i += 1\n end\n @state_reachable.put(s.attr_state_number, REACHABLE_NO)\n return false # no path to targetState found.\n end", "def error_state?(sym); @error_states.include?(sym) end", "def valid_from_state?(from_state)\n find_match(from_state, @options[:from], @options[:except_from])\n end", "def isNFA?\n if isValid? then \n if @alphabet.include? \"\" then\n return true\n else\n combo = []\n @transition_rules.each do |transition|\n combo.push([transition.current_state, transition.input_char])\n if combo.count != combo.uniq.count then\n return true \n end\n end\n end\n end\n return false\n end", "def final_state?(curr_state = nil, **)\n next_state(curr_state).blank?\n end", "def valid_transition?(new_state)\n VALID_TRANSITIONS[@state][:valid].include?(new_state)\n end", "def state?(name)\n @states.include?(name.to_sym)\n end", "def runtime_state?(sym); @runtime_states.include?(sym) end", "def fatal_error_state?(sym); @fatal_states.include?(sym) end", "def has_state?(v)\n @state[v]\n end", "def has_state?(v)\n @state[v]\n end", "def same?(state)\n map[state] == state || (map[ANY_STATE] == state && from_state == state)\n end", "def has_state?(v)\n@state[v]\nend", "def is_state?(name)\n @state.include?(name)\n end", "def done?(state)\n legal_moves(state).empty?\n end", "def isStateStackEmpty()\n\t\t\treturn @_state_stack.empty?\n\t\tend", "def from_place_to_transition?\n net.places.any? {|p| p.id == source_id} and net.transitions.any? {|t| t.id == target_id}\n end", "def state?(state)\n @states.key?(state)\n end", "def exception_state?(sym); @exception_states.include?(sym) end", "def compute_unreachable_states\n queue = [starting_state].to_set\n transitions = self.each_transition.to_a.dup\n\n done_something = true\n while done_something\n done_something = false\n transitions.delete_if do |from, _, to|\n if queue.include?(from)\n queue << to\n done_something = true\n end\n end\n end\n\n transitions.map(&:first).to_set\n end", "def check_win(symbol)\n WIN_CASES.each do |i|\n diff = i - scan_symbol_positions(symbol)\n return true if diff.empty?\n end\n false\n end", "def transition_choice?\n matching = machine.transitions[name]\n [matching[from_state], matching[ANY_STATE]].any? do |match|\n match.is_a?(Array)\n end\n end", "def can_fire?(current_state)\n if from.is_a?(Array)\n from.include?(current_state.to_sym)\n elsif from == :__statum_any_state\n true\n else\n from == current_state.to_sym\n end\n end", "def done?(state)\n state[:position][0][0] == 0\n end", "def start_state?\n @state_type == :start\n end", "def from?( state )\n origin_names.include?( state.to_sym ) || target_for_origin(state)\n end", "def perform_initial_transition?\n !current_state\n end", "def valid?\n arcs.each do |arc|\n source_transition = find_transition(arc.source_id)\n source_place = find_place(arc.source_id)\n target_transition = find_transition(arc.target_id)\n target_place = find_place(arc.target_id)\n\n # arc from transition to place\n cond1 = not(source_transition.nil?) && not(target_place.nil?)\n\n # arc from place to transition\n cond2 = not(source_place.nil?) && not(target_transition.nil?)\n\n unless cond1 or cond2\n return false\n end\n end\n\n return true\n end", "def is_deterministic\n if ((@dangling_states.size).equal?(0) && (@states_with_syntactically_ambiguous_alts_set.size).equal?(0) && (@dfa.get_unreachable_alts.size).equal?(0))\n return true\n end\n if (@states_with_syntactically_ambiguous_alts_set.size > 0)\n it = @states_with_syntactically_ambiguous_alts_set.iterator\n while (it.has_next)\n d = it.next_\n if (!@states_resolved_with_semantic_predicates_set.contains(d))\n return false\n end\n end\n # no syntactically ambig alts were left unresolved by predicates\n return true\n end\n return false\n end", "def final?\n @transitions.empty?\n end", "def test_state_names_2\n simple_dfa = Automaton.new(false) do |fa|\n fa.add_state(:initial => true)\n end\n assert_raise ArgumentError do\n simple_dfa.get_state('') # non-existing state\n end\n end", "def has_state?\n !!current_state\n end", "def can_fire?(current_state)\n if from.is_a?(Array)\n from.include?(current_state.to_sym)\n elsif from == Statum::ANY_STATE_NAME\n true\n else\n from == current_state.to_sym\n end\n end", "def aasm_states_to_check\n created? ||\n (planned? && !aasm_state_changed? ) || # exclude validation on transition from created to planned\n started? ||\n ignore_states\n end", "def been_to?(matrix)\n previous_states.each do |state|\n return true if matrix[0] == state[0] &&\n matrix[1] == state[1] &&\n matrix[2] == state[2]\n end\n\n false\n end", "def compute_symbol(symbol)\r\n transition_matrices[symbols_list.index(symbol)][current_state].index {|val| val == 1}\r\n end", "def initialized?\n defined?(@state) && @state\n end", "def has_next_state?\n return @operation != :nop\n end", "def reachable_states\n visited_states = Set.new()\n unvisited_states = Set[@start_state]\n begin\n outbound_transitions = @transitions.select { |t| unvisited_states.include?(t.from) }\n destination_states = outbound_transitions.map(&:to).to_set\n visited_states.merge(unvisited_states) # add the unvisited states to the visited_states\n unvisited_states = destination_states - visited_states\n end until unvisited_states.empty?\n visited_states\n end", "def from_transition_to_place?\n net.transitions.any? {|t| t.id == source_id} and net.places.any? {|p| p.id == target_id}\n end", "def has_predicate\n return @state_to_alt_set_with_semantic_predicates_map.size > 0\n end", "def test_state_names_1\n s0,s1,s2 = nil,nil,nil\n simple_dfa = Automaton.new(false) do |fa|\n s0 = fa.add_state(:initial => true, :name => 'A')\n s1 = fa.add_state(:accepting => true, :name => 'B')\n s2 = fa.add_state(:name => 'C')\n fa.connect(s0, s1, 'a')\n fa.connect(s1, s1, 'b')\n fa.connect(s1, s2, 'c')\n end\n assert_raise ArgumentError do\n simple_dfa.get_state(56) # wrong type\n end\n assert_raise ArgumentError do\n simple_dfa.get_state('T') # non-existing name\n end\n\n assert_raise ArgumentError do\n simple_dfa.get_state('') # non-existing state\n end\n\n assert_raise ArgumentError do\n simple_dfa.get_state(nil) # nil name\n end\n assert_equal s0,simple_dfa.get_state('A')\n assert_equal s1,simple_dfa.get_state('B')\n assert_equal s2,simple_dfa.get_state('C')\n end", "def transition_exist?(filename)\n test_file_existence(filename, Transitions_Path, @transition_data)\n end", "def in_progress?\n transitive_states.include? status\n end", "def final_state?\n current_state == final_state\n end", "def transitions_loaded?(state_class)\n state_loaded?(state_class) && @transitions.key?(state_class)\n end", "def is_full\n count(@state.flatten, '-') == 0\n end", "def done?\n not state.blank?\n end", "def valid?()\n (@invalid_reason.nil? && !(@hops.find { |h| h.is_a?(Symbol) or h.is_a?(String) }))\n end", "def path_exists?(edges, start, finish) \n nodes = edges[start].keys\n touchedNodes = nodes + [start]\n newNodes = nodes\n\n until newNodes.length == 0\n return true if touchedNodes.include?(finish)\n newNodes = []\n nodes.each do |node|\n newNodes += edges[node].keys - touchedNodes\n end\n touchedNodes += newNodes\n nodes = newNodes\n end\n false\n end", "def in_state?(path)\n self.find_states(current_state.path).include? find_state(path)\n end", "def to?( state )\n target_names.include?( state.to_sym )\n end", "def current_state?(state)\n state == current_state.to_sym\n end", "def full?\n !@state.include?(nil)\n end", "def validate_not_to_initial_state(to)\n unless to.nil? || successors.values.flatten.include?(to)\n raise InvalidTransitionError,\n \"Cannot transition to initial state '#{to}'\"\n end\n end", "def in_or_before_state?(test_state)\n return false if test_state.nil? || self.state.nil?\n test_state = test_state.to_sym\n my_state = self.state.to_sym\n\n # Get all the states that are in or before the state we want to check (test_state),\n # and then see if the vehicle's current state is in that list (well, technically in a lazy enumerable).\n Vehicle.aasm.states.reverse.lazy.drop_while { |state| state != test_state }.include?(my_state)\n end", "def decide string\n @current_state = @start_state\n string.each_char do |c|\n if !@alphabet.include? c then\n return false\n end\n transition = false\n @transition_rules.each do |rule|\n if rule.input_char === c && rule.current_state === @current_state then\n transition = rule\n break\n end\n end\n if !transition then \n return false\n else\n @current_state = transition.end_state\n end\n end\n\n if @accept_states.include? @current_state then\n return true\n else\n return false\n end\n end", "def is_valid_state(state)\n temp_state = @state\n @state = temp_state\n\n if all_valid\n @state = temp_state\n return true\n else\n @state = temp_state\n return false\n end\n end", "def valid_states\n aasm.states.map(&:name).map(&:to_s)\n end", "def validate_from_and_to_state(from, to)\n unless successors.fetch(from, []).include?(to)\n raise InvalidTransitionError,\n \"Cannot transition from '#{from}' to '#{to}'\"\n end\n end", "def state?(state)\n @state == state\n end", "def empty?() @symbols.empty? end", "def transition?\n not @transition.nil? || @transition.finished?\n end", "def is_transition_for?(event_name, subject_state)\n is_same_event?(event_name) && is_same_from?(subject_state)\n end", "def invalid?\n !@state\n end", "def final?\n @finals.include? @state\n end", "def valid_prev_states(state)\n normalized_state = normalize_state(state)\n prev = STATES.select do |_, v|\n normalize_state(v) < normalized_state && v < ERROR_STATE_THRESHOLD\n end\n\n prev.keys\n end", "def known_states; end", "def known_states; end", "def known_states; end", "def terminal_state?\n self.class.terminal_states.include?(@state)\n end", "def finished?\n symbols_count = PLAYER_SYMBOLS.map{|s| board_state.count(s)}.inject(&:+)\n symbols_count == 9 || !winner.nil?\n end", "def state_meets_requirements?\n @needs.each do |requirement|\n valid, reason = state.meets_requirement?(requirement)\n\n unless valid\n logger.debug(\"State does not meet the requirements %s: %s\" % [self, reason])\n return false\n end\n end\n\n true\n end", "def find_all_transitions(transition)\n transition = infer_transition(transition)\n return [] unless transition\n\n pattern = {}\n transition.each_pair do |k, v|\n pattern[k.to_sym] = v if v\n end\n return [] if pattern.empty?\n \n self.transitions.find_all do |t|\n (pattern[:name] ? t.name == pattern[:name] : true) and \n (pattern[:from_state] ? t.from_state == pattern[:from_state] : true) and \n (pattern[:to_state] ? t.to_state == pattern[:to_state] : true) and \n (pattern[:probability] ? t.probability == pattern[:probability] : true) and \n (pattern[:reward] ? t.reward == pattern[:reward] : true)\n end\n end", "def accept_state_of(closure)\r\n closure.each do |set|\r\n if @accept_states.include?(set)\r\n return @accept_states[set] # change this to \"true\" if reverting to crappy system\r\n end\r\n end\r\n return false\r\n end", "def final?(vertex)\n final_states = (0..last).select { |i| @vertices[i].nil? }\n final_states.include?(vertex)\n end", "def available_transitions_from(state)\n find_all_transitions(:from_state => state)\n end", "def is_move_valid(current_state, proposed_change)\n proposed_floor = current_state[:elevator] + proposed_change[:elevator]\n return false if proposed_change.length < 2 || proposed_change.length > 3\n return false if proposed_floor < 0 || proposed_floor > 3\n\n proposed_state = get_new_state(current_state, proposed_change)\n generators = []\n chips = []\n proposed_state[:floors][proposed_floor].each do |item|\n binding.pry if item == nil\n if item[0] == :gen\n generators << item[1]\n else\n chips << item[1]\n end\n end\n if generators.length > 0\n chips.each do |chip_type|\n return false if !generators.include?(chip_type)\n end\n end\n\n return false if @visited_states.include? proposed_state.to_s\n @visited_states << proposed_state.to_s\n # binding.pry\n proposed_state\nend", "def current_state?(state) \n\t return state == current_state.to_sym\n\tend", "def state?(state)\n @_state == state\n end", "def sync_state_exists?\n session.left.tables.include? \"#{options[:rep_prefix]}_sync_state\"\n end", "def matches_state_attrs?\n @expected_attrs == state_attrs\n end", "def transitive_states\n states.select do |state|\n state.end_with? 'IN_PROGRESS'\n end\n end", "def transitions_from(station)\n stations.select do |destination| \n has_edge?(station.to_sym, destination)\n end\n end", "def validity?\n solve_until_complete unless @solved\n return :ambiguous if !@truth_table.values.grep(nil).empty?\n @program.left.each do |clause|\n return false if clause.type == :statement && !eval_stmt(clause.left)\n return :ambiguous if clause.type == :statement && eval_stmt(clause.left).nil?\n end\n true\n end", "def valid_symbol?(symbol)\n return false if [].include?(symbol)\n true\n end", "def in_or_after_state?(test_state)\n return false if test_state.nil? || self.state.nil?\n test_state = test_state.to_sym\n my_state = self.state.to_sym\n\n # Get all the states that are in and after the state we want to check (test_state),\n # and then see if the vehicle's current state is in that list (well, technically in a lazy enumerable).\n Vehicle.aasm.states.lazy.drop_while { |state| state != test_state }.include?(my_state)\n end", "def define_state_predicate; end", "def state?(type, name)\n @state.key?(make_key(type, name))\n end", "def is_valid?(s)\n stack = []\n mapping = { \n '}' => '{',\n ']' => '[',\n ')' => '('\n }\n s.chars.each do |c|\n if mapping.has_key?(c) && !stack.empty? && stack.last == mapping[c]\n stack.pop\n else\n stack.push(c)\n end\n end\n return stack.empty?\nend", "def state_funding_complete?\n draft_budgets.where(default: true).each do |budget|\n if budget.funding_source_type.try(:name).in? [\"State\"]\n return false\n end\n end\n return true \n end", "def transition_symbols_for(state)\n trans = {}\n return trans if @transitions[state].nil?\n @transitions[state].each do |k,v|\n tmp = v.is_a?(Array) ? v : [v]\n tmp.each do |i|\n k.is_a?(Symbol) ? @cats[k].each {|s| trans.push_at(s, v)} : trans.push_at(k, i)\n end\n end\n trans\n end", "def in_workflow_state?(test_states = [])\n return false unless state && !test_states.blank?\n\n test_state_regex = test_states.join('|').gsub(/\\s+/, '.+')\n !/#{test_state_regex}/.match(state).nil?\n end" ]
[ "0.6617021", "0.65058094", "0.6217322", "0.62026346", "0.60841686", "0.60547996", "0.59882087", "0.5873334", "0.58653444", "0.58478713", "0.5809739", "0.57889265", "0.5787568", "0.5771664", "0.5749269", "0.5711251", "0.56665385", "0.56665385", "0.5664258", "0.5635463", "0.56216455", "0.56041294", "0.56014585", "0.55432236", "0.55424803", "0.5542305", "0.55026305", "0.5439152", "0.54385275", "0.5422216", "0.54124993", "0.54111797", "0.541065", "0.53672665", "0.5352057", "0.53506243", "0.53285253", "0.5318318", "0.5292447", "0.52780414", "0.52768385", "0.5276183", "0.52694297", "0.5267948", "0.52609086", "0.5239358", "0.5234152", "0.5230053", "0.52188873", "0.52152586", "0.52032804", "0.5196914", "0.5195304", "0.5183037", "0.518049", "0.51707906", "0.51556873", "0.51554215", "0.5149514", "0.5139788", "0.5138645", "0.5137977", "0.512502", "0.5113782", "0.50946677", "0.50850224", "0.5079489", "0.5074511", "0.50590324", "0.50570834", "0.50502515", "0.50481015", "0.50400037", "0.5031031", "0.5028022", "0.5028022", "0.5028022", "0.5027999", "0.50143135", "0.5007351", "0.4996373", "0.49787557", "0.4978237", "0.49710262", "0.49655068", "0.49495536", "0.49446708", "0.4931563", "0.49262682", "0.49209434", "0.49208257", "0.4909305", "0.49087265", "0.49060783", "0.48974964", "0.48948246", "0.48917082", "0.4890505", "0.4887355", "0.48823565" ]
0.7356532
0
Determines if a given state is an accept state.
def accept_state?(state) @accept.include? state end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_accept_state?(state)\n @accept.include? state.to_s\n end", "def accepted?\n state == 'accepted'\n end", "def can_accept?\n !accepted? && !rejected? && !withdrawn?\n end", "def accepting?\n\treturn self.type == \"Accepting\"\n end", "def accepted?\n return (self.status == STATUS_ACCEPTED)\n end", "def accepted?\n self.status == ACCEPTED\n end", "def accept_state_of(closure)\r\n closure.each do |set|\r\n if @accept_states.include?(set)\r\n return @accept_states[set] # change this to \"true\" if reverting to crappy system\r\n end\r\n end\r\n return false\r\n end", "def accept!\n self.state = :accepted\n end", "def state?(state)\n @state == state\n end", "def add_accept_state(state, type)\r\n @accept_states[state] = type\r\n end", "def rejected?\n state == 'rejected'\n end", "def accepts?(input)\n resp = feed(input)\n resp[:accept]\n end", "def accepts?(input)\n resp = feed(input)\n resp[:accept]\n end", "def find_accepting_states(nodes) \n\t nodes.sub.any? { |state| \n\t\treturn \"Accepting\" if state.any? { |result| \n\t\t result.accepting? \n\t\t} \n\t }\n\t return \"\"\n end", "def state?(state)\n @_state == state\n end", "def can_reject?\n !accepted? && !rejected? && !withdrawn?\n end", "def confirmed?\n state == 'confirmed'\n end", "def approved?\n !([STATE_UNKNOWN, STATE_BLOCK_REQUESTED, STATE_BLOCKED, STATE_APPROVAL_REQUESTED, STATE_UNAVAILABLE, STATE_CANCELLED, STATE_EXPIRED, STATE_AVAILABLE_EXPIRED].include?(self.state))\n end", "def accept?(s, current = @start)\n if s == \"\"\n is_final?(current)\n else\n dest = get_transition(current, s[0,1])\n if dest == nil\n false\n else\n accept?(s[1..-1], dest)\n end\n end\n end", "def accepted?\n !!self.accepted_at\n end", "def accepted?\n false\n end", "def accept?(s, current = @start)\n if s == \"\"\n is_final?(current)\n else\n dest = get_transition(current,s[0,1])\n if dest == nil\n false\n else\n accept?(s[1..-1], dest)\n end\n end\n end", "def transition_choice?\n matching = machine.transitions[name]\n [matching[from_state], matching[ANY_STATE]].any? do |match|\n match.is_a?(Array)\n end\n end", "def is_state?(name)\n @state.include?(name)\n end", "def decided?\n return (self.status == STATUS_DENIED or self.status == STATUS_ACCEPTED)\n end", "def can_be_accepted_by?(acceptor)\n self.can_accept? && self.kase.person == acceptor &&\n (self.kase.offers_reward? ? self.kase.owner_only_offers_reward? : true)\n end", "def can_receive?\n if (self.state == 'C' or self.state == 'F')\n return true\n end\n return false\n end", "def rejected?\n state == :rejected\n end", "def valid_transition?(new_state)\n VALID_TRANSITIONS[@state][:valid].include?(new_state)\n end", "def __accepted__\n defined?(accepted) ? accepted : false\n end", "def has_accepted_attestation_terms?\n SUBMITTED_STATUS.include?(aasm_state)\n end", "def already_accepted?(story_id)\n response = Net::HTTP.start(uri.host, uri.port) do |http|\n http.get(uri.path, data)\n end\n Nokogiri::XML(response.body).at_css('current_state').content == \"accepted\"\n end", "def pending?\n state == 'pending'\n end", "def verify_accept\n raise WebSocket::Error::Handshake::InvalidAuthentication unless @handshake.headers['sec-websocket-accept'] == accept\n true\n end", "def state?(state)\n @states.key?(state)\n end", "def valid_state?(state_class)\n state_class.is_a?(Class) && state_class < State\n end", "def _accept?(wi)\n Ruote.participant_send(self, :accept?, 'workitem' => wi)\n end", "def isInTransition()\n\t\t\treturn @_state == nil\n\t\tend", "def can_reattempt_connect_for_state?(state)\n case state\n when :disconnected\n time_spent_attempting_state(:disconnected, ignore_states: [:connecting]) < connection.connection_state_ttl\n when :suspended\n true # suspended state remains indefinitely\n else\n raise ArgumentError, \"Connections in state '#{state}' cannot be reattempted\"\n end\n end", "def pending?\n\t\tself.accepted_at == nil\n\tend", "def approved?\n state == 'approved'\n end", "def accepted?\n return true if exclusive?\n\n accepted_by?(host_lead_member) && accepted_by?(guest_lead_member)\n end", "def accepted?\n if (app = applications.find_by(status: :accepted))\n app.accepted?\n end\n end", "def state?(name)\n @states.include?(name.to_sym)\n end", "def examine_block\n if accepted?\n worker && worker.report_accepted_block(self)\n end\n true\n end", "def valid?\n state_validator = EnumAttributeValidator.new('String', ['WAITING', 'RUNNING', 'FINISHED'])\n return false unless state_validator.valid?(@state)\n true\n end", "def is_transition_for?(event_name, subject_state)\n is_same_event?(event_name) && is_same_from?(subject_state)\n end", "def pending?\n return false if state.nil?\n \"pending\".casecmp(state).zero?\n end", "def current_state?(state)\n state == current_state.to_sym\n end", "def accepted?\n verdict && verdict.accepted?\n end", "def event?(state)\n @events.key?(state)\n end", "def pending_answer?\r\n\t\t\treturn (@type == 'answer' && @state == 're')\r\n\t\tend", "def friend_request_accepted?\n friend_request_exists? && friend.accepted?\n end", "def accept?(s, current = @start)\n false\n end", "def has_accepted_response?\n self.responses.accepted.any? {|response| response.accepted?}\n end", "def accept!\n accepted!\n end", "def has_state?(v)\n @state[v]\n end", "def has_state?(v)\n @state[v]\n end", "def valid_from_state?(from_state)\n find_match(from_state, @options[:from], @options[:except_from])\n end", "def concluded?\n state == :answered || state == :canceled\n end", "def self_organized_and_accepted_or_confirmed?\n self_organized? && (accepted? || confirmed?)\n end", "def pending?\n\t\t\tstate == 'pending'\n\t\tend", "def to?( state )\n target_names.include?( state.to_sym )\n end", "def prescriptively_ok?\n acceptance & PRESCRIPTIVE == PRESCRIPTIVE\n end", "def desired_state?\n return true unless options.key?(:desired_state)\n\n options[:desired_state]\n end", "def in_transit?\n status.sent?\n end", "def can_fire?(current_state)\n if from.is_a?(Array)\n from.include?(current_state.to_sym)\n elsif from == Statum::ANY_STATE_NAME\n true\n else\n from == current_state.to_sym\n end\n end", "def state_active?(state)\n @states[state][1]\n end", "def accept?(s, current)\nif s == \"\"\nis_final?(current)\nelse\ndest = get_transition(current,s[0,1])\nif dest == nil || dest.size > 1\nfalse\nelse\naccept?(s[1..-1], dest[0])\nend\nend\nend", "def if_state(*expected_states) # :nodoc:\n mutex.lock\n raise ArgumentError.new('no block given') unless block_given?\n\n if expected_states.include? @state\n yield\n else\n false\n end\n ensure\n mutex.unlock\n end", "def descriptively_ok?\n acceptance & DESCRIPTIVE == DESCRIPTIVE\n end", "def from?( state )\n origin_names.include?( state.to_sym ) || target_for_origin(state)\n end", "def same?(state)\n map[state] == state || (map[ANY_STATE] == state && from_state == state)\n end", "def transition_allowed?(event)\n allowed = case event\n when :charge\n [ :pending, :failed, :unpaid ].include?(self.state.to_sym)\n when :generate_pdf\n true\n else\n state_events.include?(event)\n end\n end", "def state?\n usa?\n end", "def on_bees?\n state == 'bees'\n end", "def waiting_in_queue_state?(state)\n [:wait_in_queue, :wait_queue_pos].include? state\nend", "def confirmed?\n [:confirmed, :in_progress, :done].include?(self.status)\n end", "def terminal_state?\n self.class.terminal_states.include?(@state)\n end", "def can_fire?(current_state)\n if from.is_a?(Array)\n from.include?(current_state.to_sym)\n elsif from == :__statum_any_state\n true\n else\n from == current_state.to_sym\n end\n end", "def grant_access_state?\n workflow_class.public_read_states.include? Array.wrap(state).first.underscore\n end", "def acceptable_by?(acceptor)\n self.can_accept? &&\n !!acceptor && !!self.person && !!self.kase.person && acceptor == self.kase.person &&\n (self.kase.offers_reward? ? acceptor != self.kase.person : true)\n end", "def aasm_state_changed_to_canceled_or_paid?\n aasm_state_changed? && %w(canceled paid).include?(aasm_state_change.last.to_s)\n end", "def has_state(name)\n !@_possible_states[name].nil?\n end", "def approval_requested?\n !([STATE_UNKNOWN, STATE_BLOCK_REQUESTED, STATE_BLOCKED, STATE_UNAVAILABLE, STATE_CANCELLED, STATE_EXPIRED, STATE_AVAILABLE_EXPIRED].include?(self.state))\n end", "def pending?\n state == :pending\n end", "def pending?\n state == :pending\n end", "def state_reached?(state)\n states = states_events.map { |se| se[0] }\n if states.index(current_state) && states.index(state)\n states.index(current_state) >= states.index(state)\n end\n end", "def in_progress?\n if current_state =~ /\\A(started|finished|delivered)\\Z/\n true\n else\n false\n end\n end", "def accepted?\n return listing.accepted_proposal_id == id\n end", "def state?(type, name)\n @state.key?(make_key(type, name))\n end", "def challenge_open?\n self.state == \"open\"\n end", "def payment_success?\n @fields['decision'] == 'ACCEPT'\n end", "def current_state?(state) \n\t return state == current_state.to_sym\n\tend", "def accepts_outcome_status_of_result?\n accepted_outcome_types.member?('statusofResult')\n end", "def has_accepted_submission_terms?\n SUBMITTED_STATUS.include?(aasm_state)\n end", "def waiting_state?(state)\n [:wait_in_queue, :wait_queue_pos, :wait_stable_build].include? state\nend", "def can_capture?(payment)\n ['pending'].include?(payment.state)\n end", "def state_changed?\n peek_state\n !@state_queue.empty?\n end", "def closed?\n state_name == \"closed\"\n end" ]
[ "0.88380766", "0.79399586", "0.68606234", "0.67599756", "0.65416485", "0.64303", "0.63275045", "0.6324492", "0.63241726", "0.6242839", "0.6232949", "0.621452", "0.621452", "0.6202336", "0.61447644", "0.60632914", "0.60215425", "0.5997094", "0.5952792", "0.59490377", "0.5939479", "0.592307", "0.59115756", "0.58794117", "0.5865071", "0.58641493", "0.58533347", "0.5840707", "0.58136004", "0.57614905", "0.5753586", "0.5727036", "0.5725114", "0.57116467", "0.57031053", "0.5691324", "0.56864023", "0.56799716", "0.5663946", "0.56562245", "0.5647971", "0.56336385", "0.5630095", "0.5601501", "0.5595369", "0.5589162", "0.5584064", "0.55767965", "0.55660075", "0.55657744", "0.55592954", "0.55558664", "0.5539331", "0.55351484", "0.55283767", "0.5518125", "0.5510677", "0.5510677", "0.5505471", "0.55007523", "0.546445", "0.54614186", "0.54598576", "0.545658", "0.54518807", "0.54496145", "0.543488", "0.542143", "0.53894633", "0.53859216", "0.5371539", "0.5367126", "0.5364306", "0.53600264", "0.53532004", "0.53520364", "0.53467894", "0.5341495", "0.534029", "0.53359914", "0.53321064", "0.5327902", "0.5323387", "0.53232086", "0.5321779", "0.53189003", "0.53189003", "0.53140646", "0.53031176", "0.5300783", "0.5294166", "0.5282794", "0.5276945", "0.5276443", "0.52720344", "0.5258121", "0.52581054", "0.5252499", "0.5250458", "0.52253455" ]
0.87743056
1
override with a better message
def apply_summary file = @file ? File.basename(@file) : 'SIMP server <host>.yaml' "Disabling of duplicate OS & SIMP YUM repos in #{file} #{@applied_status}" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def msg; end", "def msg; end", "def msg; end", "def msg=(_); end", "def msg=(_); end", "def message\n @message || super\n end", "def default_messages=(_arg0); end", "def message; end", "def message; end", "def message; end", "def message; end", "def message; end", "def message; end", "def error_message; end", "def miss_reason; end", "def message=(_); end", "def warn message\n super message if @verbosity > 1\n end", "def failure_message_preface=(_arg0); end", "def reason; end", "def reason; end", "def display_error_message(ex)\n $stderr.puts self.to_s()\n super(ex) \n end", "def message() end", "def message\n \"#{super}:\\n#{errors_message}\"\n end", "def message\n raise \"Override #message in the service class\"\n end", "def message(message) end", "def warnings; end", "def warnings; end", "def warnings; end", "def warnings; end", "def warnings; end", "def warnings; end", "def warnings; end", "def warnings; end", "def error_messages; end", "def warn(msg)\n #This is a stub, used for indexing\n end", "def msg(message)\n end", "def notice; end", "def original_error; end", "def original_error; end", "def message( message )\n\tend", "def tag; raise 'Override this method'; end", "def errback &block\n super\n end", "def errback &block\n super\n end", "def warned; end", "def reason(*) end", "def foorth_message\r\n \"#{self.foorth_code} #{self.message}\"\r\n end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def miss_reason=(_arg0); end", "def show_err_msg(message)\n responds_to_parent do\n render :update do |page|\n page.call 'change_basic_form'\n page.call \"flash_writter\", \"#{message}\"\n page << \"activate_click('#{params[:form_txt]}_onclick')\"\n #page.call \"load_completer\"\n end\n end\n end", "def warning_state\n super\n end", "def inactive_message \n if !approved? \n :not_approved \n else \n super # Use whatever other message \n end \n end", "def diagnostic; end", "def messages; end", "def messages; end", "def messages; end", "def error_messages=(_arg0); end", "def message\n end", "def not_found\n super(t('messages.list_item.errors.find'))\n end", "def warning?; end", "def warning?; end", "def warning?; end", "def inspect; message; end", "def verbose_message(msg)\n\t\t\t\tUI.message(msg) if (@verbose)\n\t\t\tend", "def failure_message_when_negated; end", "def failure_message_when_negated; end", "def failure_message_when_negated; end", "def error; end", "def error; end", "def error; end", "def error; end", "def error; end", "def error; end", "def error; end", "def post_fail_message; end", "def overrides; end", "def message\n @cause.nil? ? super : \"#{super} (cause: #{@cause.message})\"\n end", "def initialize(msg, original=$!)\n super(msg)\n @original = original;\n end", "def not_valid_message; nil; end", "def not_valid_message; nil; end", "def inactive_message \n if !is_approved? \n :not_approved \n else \n super # Use whatever other message \n end \n end", "def show_error\n raise NotImplementedError\n end", "def notice=(message); end", "def notice=(message); end", "def initialize(message)\n\t\t$stderr.puts \"#{@name}: initialize not overridden!\"\n\tend", "def ammend(message)\n\t\t$stderr.puts \"#{@name}: ammend not overridden!\"\n\tend", "def message( *args )\n raise NotImplementedError, \"You must implement #message in your driver.\"\n end", "def bold_error(*args); end", "def set_error_message(msg)\n if self[:error_message]\n self[:error_message] += \"\\n\" + msg\n else\n self[:error_message] = msg\n end\n end", "def say(*par)\n return unless self[:verbose]\n\n super(*par)\n end", "def description\n super + \", Soy\"\n end", "def sonido()\n return super << \" miaaauuu\"\n end", "def not_found\n super(t('messages.employee.errors.find'))\n end", "def inactive_message \n approved? ? super : :not_approved\n end", "def inactive_message; end", "def inactive_message; end" ]
[ "0.7049173", "0.7049173", "0.7049173", "0.7004298", "0.7004298", "0.6855491", "0.67363703", "0.66996366", "0.66996366", "0.66996366", "0.66996366", "0.66996366", "0.66996366", "0.66343576", "0.65666604", "0.6540973", "0.65294886", "0.6514811", "0.65086156", "0.65086156", "0.6502227", "0.6498696", "0.6448084", "0.6447496", "0.63649374", "0.6288527", "0.6288527", "0.6288527", "0.6288527", "0.6288527", "0.6288527", "0.6288527", "0.6288527", "0.62836885", "0.626941", "0.6268613", "0.62597007", "0.6253057", "0.6253057", "0.6252728", "0.6251949", "0.6227315", "0.6227315", "0.6227079", "0.6221703", "0.6210239", "0.62063545", "0.62063545", "0.62063545", "0.62063545", "0.62063545", "0.62063545", "0.62063545", "0.61683494", "0.61648035", "0.6123267", "0.61067945", "0.6102075", "0.6092078", "0.6092078", "0.6092078", "0.6091098", "0.60881114", "0.6083594", "0.6080094", "0.6080094", "0.6080094", "0.60750026", "0.6069385", "0.60660046", "0.60660046", "0.60660046", "0.6063934", "0.6063934", "0.6063934", "0.6063934", "0.6063934", "0.6063934", "0.6063934", "0.60429376", "0.6021888", "0.6017425", "0.60100204", "0.6000615", "0.6000615", "0.59867555", "0.59801525", "0.5974694", "0.5974694", "0.5953683", "0.59536254", "0.5949391", "0.59483284", "0.593158", "0.5927559", "0.59266365", "0.5915402", "0.59151524", "0.5914314", "0.5906319", "0.5906319" ]
0.0
-1
Pass on certain authorize_params to the Slack authorization GET request. See
def authorize_params super.tap do |params| %w(scope team redirect_uri).each do |v| if !request.params[v].to_s.empty? params[v.to_sym] = request.params[v] end end log(:debug, "Authorize_params #{params.to_h}") end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def authorize_request\n if basic_auth.values.all?\n [:basic_auth, @username, @password]\n else\n [:desk_oauth, oauth]\n end\n end", "def authorize\n params[:access_token] ||= params[:oauth_token]\n super\n end", "def authorize_params\n super.tap do |params|\n %w[display scope auth_type].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n end\n end\n end\n end", "def authorize(params = {})\n open_url authorize_url(params)\n end", "def authorize_params\n\n # Trick shamelessly borrowed from the omniauth-facebook gem!\n super.tap do |params|\n %w[scope].each { |v| params[v.to_sym] = request.params[v] if request.params[v] }\n params[:scope] ||= DEFAULT_SCOPE # ensure that we're always request *some* default scope\n end\n end", "def authorize_params\n super.tap do |params|\n %w[display scope auth_type].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n end\n end\n\n params[:scope] ||= DEFAULT_SCOPE\n params[:approval_prompt] ||= 'force'\n end\n end", "def authorize_params\n super.tap do |params|\n %w[auth_type display revoke scope state].each do |v|\n next unless request.params[v]\n params[v.to_sym] = request.params[v]\n\n session[\"omniauth.state\"] = params[:state] if v == \"state\"\n # to support omniauth-oauth2’s auto csrf protection\n end\n\n params[:scope] ||= DEFAULT_SCOPE\n end\n end", "def authorize\n end", "def authorize\n end", "def authorize_params\n super.tap do |params|\n options[:authorize_options].each do |k|\n params[k] = request.params[k.to_s] unless [nil, ''].include?(request.params[k.to_s])\n end\n end\n end", "def send_auth_request \n request = AuthorizeRequest.new(:get, action_to_call) do |req|\n req.request_params = params\n end\n request.send_request(Config.url)\n end", "def authorize_params\n # Only set state if it hasn't already been set\n options.authorize_params[:state] ||= SecureRandom.hex(24)\n params = options.authorize_params.merge(options_for(\"authorize\"))\n if OmniAuth.config.test_mode\n @env ||= {}\n @env[\"rack.session\"] ||= {}\n end\n params\n end", "def call_authorization_api(params)\n return call_api(\"/api/auth/authorization\", {\n \"parameters\" => URI.encode_www_form(params)\n })\nend", "def authorize_params\n super.tap do |params|\n %w[ state ].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n\n # to support omniauth-oauth2's auto csrf protection\n session['omniauth.state'] = params[:state] if v == 'state'\n end\n end\n end\n end", "def authorize_params\n super.tap do |params|\n provider = session['omniauth.params'].delete('provider') rescue nil\n params[:provider] = provider if provider\n\n service = session['omniauth.params'].delete('service') rescue nil\n params[:service] = service if service\n\n context = session['omniauth.params'].delete('context') rescue nil\n params[:context] = context if context\n end\n end", "def authorize_params\n options.authorize_params[:state] = SecureRandom.hex(24) + '|' + Base64.strict_encode64(request.params.to_param)\n params = options.authorize_params.merge(options_for(\"authorize\"))\n if OmniAuth.config.test_mode\n @env ||= {}\n @env[\"rack.session\"] ||= {}\n end\n session[\"omniauth.state\"] = params[:state]\n params\n end", "def authorize\n\n # redirect to kpass for authorization (and authentication if they're not\n # signed in.)\n # \n \n\n authorize_url = \"#{ENV['KPASS_ENDPOINT']}/oauth/authorize?app_id=#{ENV['KPASS_APP_ID']}\"\n redirect_to authorize_url\n end", "def authorize_scopes\n @authorize_scopes ||= (env['omniauth.params']['scope'] || authorize_params['scope']).split(' ')\n end", "def authorize_resource(*args); end", "def authorization_params\n params.require(:authorization).permit(:user_id, :authorizer_id, :room_id, :date_register, :date_expiration)\n end", "def raw_params(auth); end", "def authorization_params\n params.require(:authorization).permit(:provider, :token)\n end", "def authorize(verb); send_or_default(\"authorize_#{verb}\",true) ; end", "def authorize_url(params = {})\n super\n .tap { |result| __ext_debug(\"--> #{result.inspect}\") }\n end", "def authorize_request\n authenticate_with_http_token do |token, option|\n User.find_by(token: token)\n end\n end", "def authorization_params\n {\n :jsonrpc => \"2.0\",\n :id => request_id,\n :method => \"user.login\",\n :params => {\n :user => username,\n :password => password\n }\n }\n end", "def oauth_header_params\n @oauth_header_params ||= OAuthenticator.parse_authorization(authorization)\n end", "def authorize\n if params[:redirect_path].present?\n session[:redirect_path] = params[:redirect_path]\n end\n\n # Certain providers require options to be selected\n if !params[:perform] && app_instance.app && PROVIDERS_WITH_OPTIONS.include?(app_instance.app.nid.to_s)\n render \"mno_enterprise/webhook/o_auth/providers/#{app_instance.app.nid}\"\n return\n end\n\n @redirect_to = MnoEnterprise.router.authorize_oauth_url(params[:id], extra_params.merge(wtk: wtk))\n end", "def authorize(username, password)\n resp = call_api_method(\"pnet.api.authorize\", :username => username, :passwd => password)\n\n if resp['success'] == 1 && resp.has_key?('authkey')\n DEFAULT_PARAMS.merge!(:username => username, :authkey => resp['authkey'])\n end\n end", "def authorize(token)\n url_encoded_connection.authorization :Bearer, token\n json_encoded_connection.authorization :Bearer, token\n end", "def authorize_params\n params = super\n params = params.merge(request_params) unless OmniAuth.config.test_mode\n redirect_params.merge(params)\n end", "def authorize_request\n authenticate_with_http_token do |token, options|\n User.find_by(token: token)\n end\n end", "def authorize\n\n @token = ::RequestToken.find_by_token params[:oauth_token]\n\n unless @token\n render :action=>\"authorize_failure\"\n return\n end\n\n unless @token.invalidated?\n if request.post?\n if params[:authorize] == '1'\n @token.authorize!(current_person)\n if @token.oauth10?\n @redirect_url = params[:oauth_callback] || @token.client_application.callback_url\n else\n @redirect_url = @token.oob? ? @token.client_application.callback_url : @token.callback_url\n end\n\n if @redirect_url\n if @token.oauth10?\n redirect_to \"#{@redirect_url}?oauth_token=#{@token.token}\"\n else\n redirect_to \"#{@redirect_url}?oauth_token=#{@token.token}&oauth_verifier=#{@token.verifier}\"\n end\n else\n render :action => \"authorize_success\"\n end\n elsif params[:authorize] == \"0\"\n @token.invalidate!\n render :action => \"authorize_failure\"\n end\n end\n else\n render :action => \"authorize_failure\"\n end\n end", "def authorize_request\n\t\tauthenticate_with_http_token do |token, options|\n\t\t\tUser.find_by(token: token)\n\t\tend\n\tend", "def authorize\n if session[:dc_access_token].nil? or session[:dc_address_for_token] != session[:dc_address] then\n session[:dc_address_for_token] = session[:dc_address]\n redirect \"#{settings.FQDN}/oauth/authorize?client_id=#{settings.api_key}&scope=DC&redirect_uri=#{settings.redirect_url}\"\n else\n redirect '/getDeviceCapabilities'\n end\nend", "def authorize_with(&blk)\n @authorize_with = blk if blk\n @authorize_with\n end", "def authorize_request\n @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]\n @exp = (AuthorizeApiRequest.new(request.headers).call)[:exp]\n end", "def authorize_params\n if !OmniAuth.config.test_mode\n options.authorize_params[:state] = generate_jwt_state(request.params)\n # Remove querystring params as only `state` is allowed.\n request.params.clear\n end\n params = options.authorize_params.merge(options_for(\"authorize\"))\n if OmniAuth.config.test_mode\n @env ||= {}\n @env[\"rack.session\"] ||= {}\n end\n session[\"omniauth.state\"] = params[:state]\n redirect_params.merge(params)\n end", "def authorize!\n response = till_response { send_raw_request(authorization_params) }\n raise AuthenticationError.new(\"Could not authenticate with Zabbix API at #{uri}: #{response.error_message}\") if response.error?\n raise AuthenticationError.new(\"Malformed response from Zabbix API: #{response.body}\") unless response.string?\n @auth = response.result\n end", "def authorization\r\n@env['HTTP_AUTHORIZATION'] ||\r\n@env['X-HTTP_AUTHORIZATION'] ||\r\n@env['X_HTTP_AUTHORIZATION'] ||\r\n@env['REDIRECT_X_HTTP_AUTHORIZATION']\r\nend", "def request_authorized_query query_string\n query query_string\nend", "def authorize_url(attribs={})\n self.class.authorize_url id, attribs.reverse_merge(credentials: api_creds)\n end", "def authorize_request\n if request.path_info.include?('clients')\n @current_user = AuthorizeClientApiRequest.new(request.parameters[:client_uuid], request.headers).call[:user]\n elsif request.path_info.include?('apps')\n @current_device = AuthorizeDeviceApiRequest.new(request.parameters[:device_uuid], request.headers).call[:device]\n @current_user = @current_device.user unless @current_device.nil?\n else\n raise(ExceptionHandler::AuthenticationError, Message.unauthorized)\n end\n end", "def authorize_request\n authenticate_with_http_token do |token, options|\n User.find_by(token: token)\n end\n end", "def authorize\n \t\t#teste http://localhost:3000/products/2/who_bought.atom\n \t\t#ou curl --silent --user dave:secret http://localhost:3000/products/2/who_bought.atom \n \t\treturn if User.count.zero?\n\n \t\tif request.format == Mime[:html]\n \t\t\tuser = User.find_by(id: session[:user_id])\n \t\telse\n \t\t\tuser = authenticate_or_request_with_http_basic do |u,p|\n \t\t\t\tUser.find_by_name(u).try(:authenticate, p)\n \t\t\tend\n \t\tend\n\n \t\tredirect_to login_url, notice: \"Please log in\" unless user\n \t\t\n \tend", "def authorize\n if params[:response_type].nil?\n params[:response_type] = \"code\"\n end\n @authorizer = OAuth::Provider::Authorizer.new current_user, true, params\n client_application = ClientApplication.find_by_key(params[:client_id])\n statsd = StatsManager.new\n statsd.feedAuthorizeMetric(current_user, client_application)\n #If this is an auto authentication transparent for end user\n redirect_to @authorizer.redirect_uri\n end", "def get(*args)\n require_authentication\n arguments(args, required: [:authorization_id])\n\n get_request(\"/authorizations/#{authorization_id}\", arguments.params)\n end", "def authorize!\n api_key = ApiKey.find_by_access_token(params[:access_token])\n head :unauthorized unless api_key\n return false\n end", "def params_auth_hash\n params[scope]\n end", "def params_auth_hash\n params[scope]\n end", "def authorize_url(params=nil)\n connection.build_url(options[:authorize_url], params).to_s\n end", "def authorize_request\n @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]\n render json: { error: 'Not Authorized' }, status: 401 unless @current_user\n end", "def authorize\n if @api_user\n authorize_user\n else\n authorize_unauthenticated_user\n end\n end", "def authorize\n resp = { authorized: StreamToken.validate_token(params[:token]) }\n if params[:name] and not resp[:authorized].any? { |valid| params[:name].index(valid).present? }\n return head :forbidden\n end\n\n respond_to do |format|\n format.urlencoded do\n resp[:authorized] = resp[:authorized].join(';')\n render plain: resp.to_query, content_type: :urlencoded, status: :accepted\n end\n format.text do\n render plain: resp[:authorized].join(\"\\n\"), status: :accepted\n end\n format.xml do\n render xml: resp, root: :response, status: :accepted\n end\n format.json do\n render json: resp, status: :accepted\n end\n end\n rescue StreamToken::Unauthorized\n return head :forbidden\n end", "def auth_param; end", "def authorize(user,pass)\n @uri.path += 'auth'\n @uri.query = \"user=\" + user + \"&pass=\" + pass\n response = @caller.request_get(@uri)\n raise RestApiCallerError::AuthorizationError unless response.code == '200'\n @token = JSON.parse(response.body)[\"token\"]\n raise RestApiCallerError::AuthorizationError unless @token\n end", "def authorizations(params = {})\n scope 'default'\n post('authorizations/', params)\n end", "def authorize_request(req)\n req.headers['Authorization'] = \"ApiKey #{@user}:#{@apikey}\"\n end", "def params_auth_hash; end", "def auth\n if session[:authorize_token]\n response = Pusher[params[:channel_name]].authenticate(params[:socket_id], {\n :user_id => session[:authorize_token], # => required\n :user_info => {}\n })\n render :json => response\n else\n render :text => \"Forbidden\", :status => '403'\n end\n end", "def call_introspection_api(token, scopes, subject)\n return call_api(\"/api/auth/introspection\", {\n \"token\" => token,\n \"scopes\" => scopes,\n \"subject\" => subject\n })\nend", "def authorize_request\n # Hacky... I know...\n if request.headers['X-GitHub-Delivery'].present?\n request.headers['Authorization'] = request.query_parameters[:token]\n end\n @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]\n end", "def authorize_url\n # Fix: replace default oauth2 options, specially to prevent the Faraday gem which\n # concatenates with \"/\", removing the Facebook api version\n options = {\n site: File.join(@site, api_version.to_s),\n authorize_url: File.join(@auth_site, api_version.to_s, auth_path),\n token_url: token_url\n }\n\n @scope = access_permissions.present? ? access_permissions.join(',') : scope\n super(options)\n end", "def get_access\n path = '/v3/oauth/authorize'\n data = \"consumer_key=#{Consumer_key}&code=#{Token}\"\n return pocket_api(path,data)\nend", "def authorize_user\n unless @api_user.permit? params[:controller], params[:action]\n head :unauthorized and return\n end\n end", "def authorize_with(&blk)\n @authorize_with = blk if blk\n @authorize_with\n end", "def authentication_url(params={})\n @request_token.authorize_url params\n end", "def authorize_request\n unless request.headers['Authorization'].present?\n render json: {message: 'Missing Token'}, status: :unauthorized\n end\n end", "def authorize_request\n @current_user = AuthorizeApiRequest.new(request.headers).call[:user]\n\n # Check if the user record is ban and cancel all actions\n json_response({ error: 'Bannis' }, :unauthorized_request) if @current_user.isBan\n\n # Check achievements in all queries by the user, three times out of ten\n @current_user.check_achievements if rand(10) >= 7\n end", "def api_authorize\n api_authenticate\n\n unless api_user.api_secret && api_user.api_secret == params[:api_secret]\n render :json => {:error => \"API secret mismatch\"}, :status => :unauthorized\n end\n end", "def params_auth_hash\n if params[scope].kind_of?(Hash) && params[scope].has_key?(authentication_keys.first)\n params[scope]\n else\n params\n end\n end", "def authorize\n puts \"********** current user app controller *****************\"\n puts @current_user\n puts current_user\n puts '*********************************************************'\n # NOTE: to self: current_user method is called, it then decodes the JSON WEB Token,\n # grabs the user_id, and uses that id to make a query to find the user that matches that id and returns it. Then on that returned user we do a .id to get the id and compare it to the parameter :id\n\n render json: {status: 401, message: \"unauthorized\"} unless current_user.id == params[:id].to_i\n end", "def authorize_request\n @current_user = ( AuthorizeApiRequest.new( request.headers ).call )[ :user ]\n end", "def authorization(*args, &block); end", "def authorize\n\t\t\n\t\tcsrf_token = SecureRandom.base64(18).tr('+/','-_').gsub(/=*$/, '')\n\t\tsession[:csrf] = csrf_token\n\t\t\n\t\toauthUrl = Dropbox.build_uri(__method__) + \"/oauth2/authorize\" #build the proper url\n\t\t\n\t\t#\tPrepare and send the authorization request\n\t\tparams = {\n\t\t :client_id => ENV['DROPBOX_KEY'],\n\t\t :response_type => :code,\n\t\t :redirect_uri => \"http://localhost:3000/dropbox/get_token\",\n\t\t :state => csrf_token\n\t\t}\n\t\tquery = params.map{|k,v| \"#{k.to_s}=#{URI.escape(v.to_s)}\"}.join '&'\n\t\tredirect_to \"#{oauthUrl}?#{query}\"\n\t\t\n\t end", "def auth_request(method, body = {})\n body[:in0] = { \"aut:name\" => Application.name, \"aut:token\" => Application.token }\n body[:order!] = body.keys.sort_by { |key| key.to_s }\n request method, body\n end", "def authorize_request\n puts \"Authorize request\"\n @current_user = nil\n @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]\n end", "def pre_authorize_cb; end", "def authorize\n authorization_check(params[:controller], params[:action], request.request_method.downcase, self) || unauthorized\n end", "def authorize_request\n # request.headers[\"Authorization\"] = JsonWebToken.encode(user_id: 1)\n @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]\n end", "def authorize\n unless params[:token] == Rails.configuration.api_token\n return render(plain: \"Unauthorized API token\\n\", status: :unauthorized)\n end\n end", "def authorize_callback\n @request_token = OAuth::RequestToken.new(@oauth,\n session[:request_token], \n session[:request_token_secret])\n\n @access_token = @request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])\n session[:access_token] = @access_token.token\n session[:secret_token] = @access_token.secret\n session[:user_id] = @access_token.params[\"user_id\"] rescue \"\"\n session[:screen_name] = @access_token.params[\"screen_name\"] rescue \"\"\n session[:authorized] = true\n @log.info \"authorized, user [#{session[:screen_name]}]\"\n \n if session[:redirect_to]\n url = session[:redirect_to]\n session[:redirect_to] = nil \n redirect url\n else\n redirect '/'\n end\n\n end", "def oauth_url_authorize\n return \"#{$SETTINGS[:oauth_server_url_authorize]}?response_type=code&client_id=#{$SETTINGS[:oauth_client_id]}&scope=ALL&redirect_uri=#{oauth_redirect_uri}\" \n end", "def request_authorization\n create_ticket\n verify_resource_owner or return\n render_authorize_form\n end", "def authorize(*args)\n permissions, _opts = _perform_authorization(*args)\n permissions\n end", "def oauth_params\n @oauth_params ||= request.env[\"omniauth.auth\"]\n end", "def oauth_authentication; end", "def authorize_url\n request_token.authorize_url\n end", "def authorize\n oauth_verifier = params[:oauth_verifier]\n request_token = session[:request_token]\n access_token = request_token.get_access_token(:oauth_verifier => oauth_verifier)\n \n user = User.login(access_token)\n session[:user] = user.id unless user.nil?\n redirect_to :controller => :home\n end", "def pre_authorize_cb=(_arg0); end", "def authorize_request\n puts \"request --------> #{request}\"\n @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]\n end", "def authorize\n if not params[:oauth_token] then\n dbsession = DropboxSession.new(APP_KEY, APP_SECRET)\n\n session[:dropbox_session] = dbsession.serialize #serialize and save this DropboxSession\n\n #pass to get_authorize_url a callback url that will return the user here\n redirect_to dbsession.get_authorize_url url_for(:action => 'authorize')\n else\n # the user has returned from Dropbox\n dbsession = DropboxSession.deserialize(session[:dropbox_session])\n # This will fail if the user didn't visit the above URL and hit 'Allow'\n dbsession.get_access_token #we've been authorized, so now request an access_token\n session[:dropbox_session] = dbsession.serialize\n \n redirect_to drop_all_files_path\n\t\tend\n\tend", "def run_filters\n set_user\n authorize\n end", "def credentials(authorization, request); end", "def authorize_request(request)\n user = Rails.application.secrets.service_login\n pw = Rails.application.secrets.service_password\n request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)\n end", "def authorize(attribs={})\n params = parse_request_params(attribs)\n parsed, creds = request(:post, resource_path+'/authorize', params)\n factory(parsed, creds)\n end", "def authorize_url(auth_provider_id, attribs={})\n params = parse_request_params(attribs)\n parsed, creds = request(:get, resource_path+\"/#{CGI.escape auth_provider_id}/authorize\", params)\n raise QueryError, parsed[:errors] if parsed[:errors].any?\n factory(parsed, creds)\n end", "def authorize_url\n polymorphic_url([ @workspace, :twitter_account ], :action => 'authorize')\n end", "def authorize_url\n @connection.authorize_url\n end", "def authorize_achievement!\n authorize!(:award, @achievement) if achievement_params.include?(:course_user_ids)\n end" ]
[ "0.7459845", "0.71612453", "0.71542764", "0.715173", "0.70455563", "0.6966972", "0.680541", "0.67030513", "0.67030513", "0.6687164", "0.6647343", "0.656474", "0.64518327", "0.6423493", "0.64209443", "0.6316849", "0.6271404", "0.6212525", "0.62081057", "0.61979944", "0.6179658", "0.61790466", "0.61782885", "0.6176831", "0.61763585", "0.6163909", "0.6159992", "0.61592466", "0.6149369", "0.612497", "0.6123543", "0.6092401", "0.60876817", "0.60871494", "0.6083818", "0.60753125", "0.6064516", "0.6062968", "0.60542226", "0.6030624", "0.6028002", "0.6016158", "0.6007663", "0.6002116", "0.59852886", "0.59512436", "0.59498286", "0.59460074", "0.5938746", "0.5938746", "0.5922372", "0.59076613", "0.5906082", "0.5905352", "0.59040225", "0.59007704", "0.5899215", "0.58979875", "0.58968586", "0.58920413", "0.58811074", "0.5880676", "0.58702844", "0.58686316", "0.58585805", "0.5855362", "0.5854752", "0.58543044", "0.58401245", "0.5834639", "0.5826456", "0.58257324", "0.58000016", "0.5790452", "0.57779986", "0.57730436", "0.57715803", "0.5769422", "0.5768671", "0.576654", "0.575891", "0.5753367", "0.57489634", "0.57458085", "0.57394606", "0.5738866", "0.5737756", "0.5735688", "0.57347697", "0.57265306", "0.5720675", "0.5717098", "0.57091767", "0.57033277", "0.5702849", "0.5701577", "0.5698879", "0.5685843", "0.56680906", "0.566096" ]
0.7246134
1
Get a new OAuth2::Client and define custom behavior. overrides previous omniauthstrategiesoauth2 :client definition. Log API requests with OmniAuth.logger
def client new_client = super team_domain = request.params['team_domain'] || options[:team_domain] if !team_domain.to_s.empty? site_uri = URI.parse(options[:client_options]['site']) site_uri.host = "#{team_domain}.slack.com" new_client.site = site_uri.to_s log(:debug, "Oauth site uri with custom team_domain #{site_uri}") end st_raw_info = raw_info new_client.define_singleton_method(:request) do |*args| OmniAuth.logger.send(:debug, "(slack) API request #{args[0..1]}; in thread #{Thread.current.object_id}.") request_output = super(*args) uri = args[1].to_s.gsub(/^.*\/([^\/]+)/, '\1') # use single-quote or double-back-slash for replacement. st_raw_info[uri.to_s]= request_output request_output end new_client end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def client\n # Merge in authorize url if supplied\n options.authorize_params[:clientId] = options.client_id\n options.authorize_params[:redirect] = callback_url\n options.client_options[:authorize_url] = options.authorize_url if options.authorize_url.present?\n options.client_options[:site] = options.site if options.site.present?\n\n ::OAuth2::Client.new(\n options.client_id,\n options.client_secret,\n deep_symbolize(options.client_options)\n )\n end", "def oauth2_client(token, params = {})\n @oauth2_client = RubyLokaliseApi::OAuth2Client.new token, params\n end", "def client\n @client ||= OAuth2::Client.new(\n client_id,\n client_secret,\n :site => site,\n :authorize_url => authorize_url,\n :token_url => token_url\n )\n end", "def client\n ::OAuth2::Client.new(\n options.client_id,\n options.client_secret,\n deep_symbolize(options.client_options).merge(site: site)\n )\n end", "def special_client\n @special_client ||= Twitter::REST::Client.new do |c|\n c.consumer_key = configure[:consumer_key]\n c.consumer_secret = configure[:consumer_secret]\n c.access_token = configure[:access_token]\n c.access_token_secret = configure[:access_token_secret]\n end\n end", "def client\n @client ||= ::OAuth2::Client.new(\n @consumer_token,\n @consumer_secret,\n :site => 'https://api-ssl.bitly.com',\n :token_url => '/oauth/access_token'\n )\n end", "def oauth_client\n if @oauth_client\n @oauth_client\n else\n conn ||= Faraday::Connection.new \\\n :url => \"https://api.gowalla.com\",\n :headers => default_headers\n\n oauth= OAuth2::Client.new(api_key, api_secret, oauth_options = {\n :site => 'https://api.gowalla.com',\n :authorize_url => 'https://gowalla.com/api/oauth/new',\n :access_token_url => 'https://gowalla.com/api/oauth/token'\n })\n oauth.connection = conn\n oauth\n end\n end", "def oauth_client\n @oauth_client ||= OAuth2::Client.new @app_key, @app_secret, site: @workxp_site do |stack|\n stack.request :multipart\n stack.request :url_encoded\n stack.adapter :net_http\n end\n end", "def new_client_application\n OAuth2::Client.new(caller_service.client_id, caller_service.client_secret, :site => authorizator_service.site, :raise_errors => false)\n end", "def auth_client(client_id, client_secret, params = {})\n RubyLokaliseApi::OAuth2::Auth.new client_id, client_secret, params\n end", "def client\n @client ||= OAuth2::Client.new(caller_service.client_id,\n caller_service.client_secret,\n :site => called_service.site,\n :raise_errors => false)\n end", "def client\n ::DelegatedAuthentication.new(options[:app_id], options[:app_secret], nil, nil, options[:privacy_url], callback_url)\n end", "def client\n @client ||= OAuth2::Client.new(@apikey, @apisecret, :site => @graph_api_url)\n end", "def oauth_client(options = {})\n @@linkedin_config ||= LinkedinBackup.load_config\n \n @key = @@linkedin_config['consumer_key']\n @secret = @@linkedin_config['consumer_secret']\n \n @client = Linkedin2::Consumer.new(@key, @secret,options )\n end", "def get_client(uri, http_type, method)\n final_url = @base_url + URI.escape(uri)\n params = {\n :site => @base_url,\n :http_method => method,\n :request_token_path => \"\",\n :authorize_path => \"\",\n :access_token_path => \"\"}\n #params[:ca_file] = self.ca_cert_file unless self.ca_cert_file.nil?\n\n consumer = OAuth::Consumer.new(@oauth_consumer_key,\n @oauth_consumer_secret, params)\n request = http_type.new(final_url)\n consumer.sign!(request)\n headers = {\n 'Authorization' => request['Authorization'],\n 'accept_language' => @lang,\n 'cp-user' => 'admin'\n }\n\n # Creating a new client for every request:\n client = RestClient::Resource.new(@base_url,\n :headers => headers)\n return client\n end", "def client\n @client ||= OAuth2::Client.new( get_config('SMARTCAR_CLIENT_ID'),\n get_config('SMARTCAR_SECRET'),\n :site => OAUTH_PATH\n )\n end", "def initialize(options = {})\n client_id = options[:client_id]\n\n @oauth2_client = TwitchOAuth2::Client.new(\n client_id: client_id, **options.slice(:client_secret, :redirect_uri, :scopes)\n )\n\n @token_type = options.fetch(:token_type, :application)\n\n @tokens = @oauth2_client.check_tokens(\n **options.slice(:access_token, :refresh_token), token_type: @token_type\n )\n\n CONNECTION.headers['Client-ID'] = client_id\n\n renew_authorization_header if access_token\n end", "def client\n @client ||= OpenIDConnect::Client.new(\n identifier: @client_id,\n secret: @secret,\n redirect_uri: @redirect_url,\n realm: 'esdl-mapeditor',\n audience: @audience,\n authorization_endpoint: discovery.authorization_endpoint,\n token_endpoint: discovery.token_endpoint,\n userinfo_endpoint: discovery.userinfo_endpoint\n )\n end", "def set_client\n p \"Fetching twitter client #{@client}\"\n @client ||= Twitter::REST::Client.new do |config|\n config.consumer_key = Rails.application.secrets.twitter_key\n config.consumer_secret = Rails.application.secrets.twitter_secret\n config.access_token = self.twitter_oauth_token\n config.access_token_secret = self.twitter_oauth_token_secret\n end\n end", "def create_client(oauth)\n\t\t@client = Twitter::REST::Client.new(\n\t\t\tconsumer_key: oauth[\"consumer_key\"],\n\t\t\tconsumer_secret: oauth[\"consumer_secret\"],\n\t\t\taccess_token: oauth[\"access_token\"],\n\t\t\taccess_token_secret: oauth[\"access_token_secret\"]\n\t\t\t)\n\tend", "def client\n @_client ||= Twitter::REST::Client.new do |config|\n config.consumer_key = CONSUMER_KEY\n config.consumer_secret = CONSUMER_SECRET\n config.access_token = ACCESS_TOKEN\n config.access_token_secret = ACCESS_TOKEN_SECRET\n end\n end", "def initialize(client_id, client_secret, version='v4', base='https://platform.pokitdok.com')\n @client_id = client_id\n @client_secret = client_secret\n @version = version\n\n @api_url = \"#{base}/api/#{version}\"\n @client = OAuth2::Client.new(@client_id, @client_secret,\n site: @api_url, token_url: '/oauth2/token')\n\n\n @scopes = {}\n @scopes['default'] = { scope: refresh_token }\n scope 'default'\n end", "def client\n @client ||= EvernoteOAuth::Client.new token: auth_token\n end", "def initialize\n self.http_client = HTTPClient.new(:base_url => Rdioid::BASE_URL, :force_basic_auth => true)\n\n http_client.set_auth(Rdioid::OAUTH_TOKEN_ENDPOINT, Rdioid.config.client_id, Rdioid.config.client_secret)\n end", "def client\n @client ||= Twitter::REST::Client.new(client_params)\n end", "def get_client(uri, http_type, method)\n return @client\n end", "def client\n @client ||= Client.new(config[:credentials], config[:end_point])\n end", "def get_oauth_clients_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: OAuthApi.get_oauth_clients ...\"\n end\n \n # resource path\n local_var_path = \"/api/v2/oauth/clients\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n local_header_accept = ['application/json']\n local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result\n\n # HTTP header 'Content-Type'\n local_header_content_type = ['application/json']\n header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n \n auth_names = ['PureCloud OAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'OAuthClientEntityListing')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: OAuthApi#get_oauth_clients\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def two_factor_auth_client\r\n @two_factor_auth_client ||= TwoFactorAuth::Client.new(config: config)\r\n end", "def client\n @client ||= Twitter::Client.new(client_config)\n end", "def get_client\n config.client.new(self)\n end", "def init\n\t\tuser_credentials = {\n\t\t\t:access_token => access_token,\n\t\t\t:refresh_token => refresh_token,\n\t\t\t:expires_at => Time.now + expires_in\n\t\t}\n\n client_id = '694fc2f618facf30b3b41726ee6d0ac04c650669ca3d114cb0bae4223cecade3'\n client_secret = '3e7cfd07d829211ac50dd6486fe677ca76e965f25ad7d68e67e845e0d4a213e7'\n\t\tCoinbase::OAuthClient.new(client_id, client_secret, user_credentials)\n\tend", "def auth_client\n raise NOT_IMPLEMENTED_ERROR\n end", "def client\n OAuth2::Client.new(\n API_KEY,\n API_SECRET,\n :authorize_url => \"/uas/oauth2/authorization?response_type=code\", #LinkedIn's authorization path\n :token_url => \"/uas/oauth2/accessToken\", #LinkedIn's access token path\n :site => \"https://www.linkedin.com\"\n )\n end", "def client #:nodoc:\n Thread.current[:twitter_client] ||= Twitter::Client.new(\n :consumer_key => oauth[\"consumer_key\"],\n :consumer_secret => oauth[\"consumer_secret\"],\n :oauth_token => oauth[\"oauth_token\"],\n :oauth_secret => oauth[\"oauth_secret\"]\n )\n end", "def create_http_client\n c = DefaultHttpClient.new( @connection_manager, @cparams )\n c.http_request_retry_handler = @retry_handler if @retry_handler\n c\n end", "def adwords_client\n if @adwords_client\n # Ensure token hasn't expired\n @adwords_client.authorize\n update authentication: @adwords_client.get_auth_handler.get_token\n\n return @adwords_client\n end\n \n authentication_hash = AppConfig.adwords.deep_dup\n authentication_hash[:oauth2_token].merge!(self.authentication)\n\n @adwords_client = AdwordsApi::Api.new({\n :authentication => authentication_hash,\n :service => {\n :environment => 'PRODUCTION'\n },\n :connection => {\n :enable_gzip => 'TRUE'\n },\n :library => {\n :log_level => 'INFO', # or DEBUG\n }\n })\n\n # Try and get a new access token if it's expired.\n token = @adwords_client.authorize\n\n # AdwordsApi does nothing if issued_at is nil (for example, if we've never\n # requested an access token before for this client channel), but for us\n # that means we definitely want to get a new one!\n @adwords_client.get_auth_handler.refresh_token! if !token[:issued_at]\n\n update authentication: @adwords_client.get_auth_handler.get_token\n \n adwords_client.config.set(\"authentication.client_customer_id\", self.uid)\n adwords_client.skip_report_header = true\n adwords_client.skip_report_summary = true\n\n return @adwords_client\n end", "def client\n OAuth2::Client.new(\n API_KEY, \n API_SECRET, \n :authorize_url => \"/uas/oauth2/authorization?response_type=code\", #LinkedIn's authorization path\n :token_url => \"/uas/oauth2/accessToken\", #LinkedIn's access token path\n :site => \"https://www.linkedin.com\"\n )\n end", "def client\n OAuth2::Client.new(\n API_KEY, \n API_SECRET, \n :authorize_url => \"/uas/oauth2/authorization?response_type=code\", #LinkedIn's authorization path\n :token_url => \"/uas/oauth2/accessToken\", #LinkedIn's access token path\n :site => \"https://www.linkedin.com\"\n )\n end", "def initialize(klass = nil)\n @klass = klass\n if @klass.present?\n @client = OAuth2::AccessToken.from_hash consumer, JSON.load(@klass.oauth2_token)\n end\n end", "def initialize(api, opts)\n # Initialize client. max_redirect is required as oauth2 will otherwise redirect to location from header (localhost)\n # https://github.com/intridea/oauth2/blob/master/lib/oauth2/client.rb#L100\n # Our code is encoded in the URL and has to be parsed from there.\n client = OAuth2::Client.new(\n api.client_id,\n api.client_secret,\n site: api.oauth_site,\n token_url: '/oauth/token',\n max_redirects: 0,\n raise_errors: true,\n connection_opts: { headers: { user_agent: api.user_agent } }\n )\n\n # Verify opts. Prefered authorization methis is auth_code. If no auth_code is present a login from\n # \"Resource Owner Password Credentials Grant\" flow.\n # @token is a Oauth2::AccessToken object. Accesstoken is @token.token\n @token =\n if opts.key?(:auth_code) && !opts[:auth_code].empty?\n # Exchange code for a token\n exchange_code_for_token(api, client, opts[:auth_code])\n else\n #\n login_with_resource_owner_password_credentials(\n client,\n opts[:username],\n opts[:password],\n )\n end\n\n # Override OAuth2::AccessToken#refresh! to update self instead of returnign a new object\n # Inspired by https://github.com/intridea/oauth2/issues/116#issuecomment-8097675\n #\n # @param [Hash] opts Refresh opts passed to original refresh! method\n #\n # @return [OAuth2::AccessToken] Updated access token object\n #\n def @token.refresh!(opts = {})\n new_token = super\n (new_token.instance_variables - %w[@refresh_token]).each do |name|\n instance_variable_set(name, new_token.instance_variable_get(name))\n end\n self\n end\n\n # Override OAuth2::AccessToken#request to refresh token when less then 60 seconds left\n #\n # @param [Symbol] verb the HTTP request method\n # @param [String] path the HTTP URL path of the request\n # @param [Hash] opts the options to make the request with\n #\n def @token.request(verb, path, opts = {}, &block)\n refresh! if refresh_token && (expires_at < Time.now.to_i + 60)\n super\n end\n end", "def initialize(app, name, client_id=nil, client_secret=nil, client_options={}, options={}, &block)\n self.client_id = client_id\n self.client_secret = client_secret\n self.client_options = client_options\n super\n end", "def oauth(options = {})\n @oauth ||= ApiFactory.new 'Authorizations', options\n end", "def client\n @client ||= Twitter::REST::Client.new do |config|\n config.consumer_key = ENV['TWITTER_API_KEY']\n config.consumer_secret = ENV['TWITTER_API_SECRET']\n config.access_token = session['token']\n config.access_token_secret = session['secret']\n end\n end", "def create_client(oauth)\n\t\t@client = Twitter::Client.new(\n\t\t\t consumer_key: oauth[\"consumer_key\"],\n\t\t\t consumer_secret: oauth[\"consumer_secret\"],\n\t\t\t oauth_token: oauth[\"oauth_token\"],\n\t\t\t oauth_token_secret: oauth[\"oauth_token_secret\"]\n\t\t)\n\tend", "def client config = {}\n client_config = self.config.merge(config)\n if config.empty? or @config_hash.nil? or (client_config.hash == @config_hash)\n @config_hash = client_config.hash\n url = client_config[:url]\n client_config.delete_if { |k,v| not VALID_CLIENT_OPTIONS.include?(k) }\n client_config[:open_timeout] ||= client_config[:timeout]\n @client ||= RestClient::Resource.new(url, client_config)\n else\n raise ArgumentError, \"Attemping to re-initialize #{self.class}#client with different configuration parameters\"\n end\n end", "def api_client\n @client ||= (begin\n client = Google::APIClient.new\n\n client.authorization.client_id = settings.credentials.client_id\n client.authorization.client_secret = settings.credentials.client_secret\n client.authorization.redirect_uri = settings.credentials.redirect_uris.first\n client.authorization.scope = SCOPES\n client\n end)\n end", "def create_client_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: AuthClientsApi.create_client ...\"\n end\n # resource path\n local_var_path = \"/auth/clients\"\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(opts[:'client_resource'])\n auth_names = ['oauth2_client_credentials_grant', 'oauth2_password_grant']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'ClientResource')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: AuthClientsApi#create_client\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def set_oauth2_auth(client, secret, authorize_path, token_path, site = nil)\n FHIR.logger.info 'Configuring the client to use OpenID Connect OAuth2 authentication.'\n @use_oauth2_auth = true\n @use_basic_auth = false\n @security_headers = {}\n options = {\n site: site || @base_service_url,\n authorize_url: authorize_path,\n token_url: token_path,\n raise_errors: true\n }\n client = OAuth2::Client.new(client, secret, options)\n client.connection.proxy(proxy) unless proxy.nil?\n @client = client.client_credentials.get_token\n end", "def client\n Twitter::Client.new(\n oauth_token: token,\n oauth_token_secret: token_secret\n )\n end", "def client\n Twitter::REST::Client.new(consumer_key: Settings.consumer.key,\n consumer_secret: Settings.consumer.secret,\n access_token: oauth_token,\n access_token_secret: oauth_token_secret)\n end", "def twitter_client\n @twitter_client ||= Twitter::REST::Client.new do |config|\n config.consumer_key = twitter_config(:consumer_key)\n config.consumer_secret = twitter_config(:consumer_secret)\n config.access_token = twitter_config(:access_token)\n config.access_token_secret = twitter_config(:access_token_secret)\n end\n end", "def init_client; end", "def initialize(options)\n @client_options = options.merge(client: self)\n end", "def initialize(config)\n $LOG.i('initializing client')\n @config = config\n @epoint = Upwork::Api::DEFAULT_EPOINT\n\t@url_auth, @url_rtoken, @url_atoken = URI_AUTH, URI_RTOKEN, URI_ATOKEN\n @tenant_id = nil\n\n\t@oauth2_client = OAuth2::Client.new(\n @config.client_id,\n @config.client_secret,\n\t :site => Upwork::Api::BASE_HOST,\n\t :authorize_url => @url_auth,\n\t :token_url => @url_atoken,\n\t :connection_opts => { :headers => {'User-Agent' => 'Github Upwork API Ruby Client' }}\n\t)\n end", "def twitter_client\n @twitter_client ||= begin\n if provider = self.omni_auth_providers.where(name: \"twitter\").first\n Twitter::REST::Client.new do |config|\n config.consumer_key = ENV[\"TWITTER_CLIENT_ID\"]\n config.consumer_secret = ENV[\"TWITTER_CLIENT_SECRET\"]\n config.access_token = provider.auth_data[\"credentials\"][\"token\"]\n config.access_token_secret = provider.auth_data[\"credentials\"][\"secret\"]\n end\n end\n end\n end", "def initialize(options={})\n # Client auth configuration\n @flow = options[:flow] || options.keys.first.to_s || 'web'\n fdata = options[@flow.to_sym] || options[@flow]\n @client_id = fdata[:client_id] || fdata[\"client_id\"]\n @client_secret = fdata[:client_secret] || fdata[\"client_secret\"]\n @redirect_uris = fdata[:redirect_uris] || fdata[\"redirect_uris\"]\n @redirect_uris ||= [fdata[:redirect_uri] || fdata[\"redirect_uri\"]].compact\n @javascript_origins = (\n fdata[:javascript_origins] ||\n fdata[\"javascript_origins\"]\n )\n @javascript_origins ||= [fdata[:javascript_origin] || fdata[\"javascript_origin\"]].compact\n @authorization_uri = fdata[:auth_uri] || fdata[\"auth_uri\"]\n @authorization_uri ||= fdata[:authorization_uri]\n @token_credential_uri = fdata[:token_uri] || fdata[\"token_uri\"]\n @token_credential_uri ||= fdata[:token_credential_uri]\n\n # Associated token info\n @access_token = fdata[:access_token] || fdata[\"access_token\"]\n @refresh_token = fdata[:refresh_token] || fdata[\"refresh_token\"]\n @id_token = fdata[:id_token] || fdata[\"id_token\"]\n @expires_in = fdata[:expires_in] || fdata[\"expires_in\"]\n @expires_at = fdata[:expires_at] || fdata[\"expires_at\"]\n @issued_at = fdata[:issued_at] || fdata[\"issued_at\"]\n end", "def initialize(klass = nil)\n @klass = klass\n if @klass.present?\n @client = OAuth::AccessToken.new(consumer, @klass.access_token, @klass.access_secret)\n end\n end", "def oauth_authentication; end", "def client\r\n @client ||= Twitter::REST::Client.new do |config|\r\n config.consumer_key = \"6Qp2jNoS9qOVZMpVNjpBNw\"\r\n config.consumer_secret = \"fm7Xplz3ndNsLgMrBRwHaT6oiaBE78wYO8K013dN8\"\r\n config.access_token = \"1256486036-PoyKFmiz3VtVchgbip875A57HZ5AA3cMxbgWfOk\"\r\n config.access_token_secret = \"N4MehECNc3x658xZb674Ev8TnD5doh5v8sFGYdL0t5J94\"\r\n end\r\nend", "def initialize\n # Create the configuration object\n @config = Configuration.new Client.configure\n\n # Yield the configuration if needed\n yield @config if block_given?\n\n # Create credentials\n credentials = @config.credentials\n # Use self-signed JWT if the endpoint is unchanged from default,\n # but only if the default endpoint does not have a region prefix.\n enable_self_signed_jwt = @config.endpoint == Configuration::DEFAULT_ENDPOINT &&\n !@config.endpoint.split(\".\").first.include?(\"-\")\n credentials ||= Credentials.default scope: @config.scope,\n enable_self_signed_jwt: enable_self_signed_jwt\n if credentials.is_a?(::String) || credentials.is_a?(::Hash)\n credentials = Credentials.new credentials, scope: @config.scope\n end\n\n @quota_project_id = @config.quota_project\n @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id\n\n @identity_aware_proxy_o_auth_service_stub = ::Google::Cloud::Iap::V1::IdentityAwareProxyOAuthService::Rest::ServiceStub.new endpoint: @config.endpoint, credentials: credentials\n end", "def client\n if !@client || @client.hash != options.hash\n @client = Croudia::Client.new\n end\n @client\n end", "def authenticating_client\n #return false unless signed?\n @authenticating_client ||= OohAuth::AuthenticatingClient.first(:api_key=>consumer_key)\n end", "def client\r\n @client ||= APIController.new config\r\n end", "def use_oauth\n\t\t\t\n\t\tend", "def client\n OAuth2::Client.new(api_key,api_secret, :site=>{:url=>'https://graph.renren.com',:response_type=>'code'}, :access_token_url=>'https://graph.renren.com/oauth/token')\n end", "def custom_request()\n\t\treturn CustomRequest.new(@credentials.client_key, @credentials.get_access_token)\n\tend", "def init_client keyfile, options\n verify_keyfile! keyfile\n client_opts = client_options keyfile, options\n Signet::OAuth2::Client.new client_opts\n end", "def client\n if current_account && current_account.fb_token\n FBGraph::Client.new(:client_id => $api_key,:secret_id =>$secret_key,:token=>current_account.fb_token) \n else\n FBGraph::Client.new(:client_id => $api_key,:secret_id =>$secret_key) \n end\n\n # OAuth2::Client.new($api_key, $secret_key, :site => 'https://graph.facebook.com')\n end", "def initialize(options = {})\n opts = {\n oauth_site: 'https://user.gini.net/',\n oauth_redirect: 'http://localhost',\n api_uri: 'https://api.gini.net',\n api_version: 'v1',\n api_type: 'json',\n upload_timeout: 90,\n processing_timeout: 180,\n log: Logger.new(STDOUT),\n user_agent: \"gini-api-ruby/#{VERSION} (Faraday v#{Faraday::VERSION})\"\n }.merge(options)\n\n # Ensure mandatory keys are set\n [:client_id, :client_secret].each do |k|\n raise Gini::Api::Error.new(\"Mandatory option key is missing: #{k}\") unless opts.key?(k)\n end\n\n # Populate instance variables from merged opts\n opts.each do |k, v|\n instance_variable_set(\"@#{k}\", v)\n self.class.send(:attr_reader, k)\n end\n\n # Ensure STDOUT is flushed\n STDOUT.sync = true\n\n # Sanitize api_uri\n @api_uri.sub!(/(\\/)+$/, '')\n\n # Register parser (json+xml) based on API version\n register_parser\n\n @log.info('Gini API client initialized')\n @log.info(\"Target: #{@api_uri}\")\n end", "def initialize(options = nil)\n @options = options || @@default_options\n @api_key = @options[:api_key] || @options[:oauth_consumer_key]\n @shared_secret = @options[:shared_secret]\n @rest_endpoint = @options[:rest_endpoint] || REST_ENDPOINT\n @auth_endpoint = @options[:auth_endpoint] || AUTH_ENDPOINT\n \n if @options[:oauth_access_token] && @options[:oauth_access_token_secret]\n @access_token = OAuth::AccessToken.new(oauth_customer, @options[:oauth_access_token], @options[:oauth_access_token_secret])\n end\n end", "def reset_oauth2_client!\n @oauth2_client = nil\n end", "def api_client\n @api_client ||= ::Lokalise.client LokaliseRails.api_token, {enable_compression: true}.merge(LokaliseRails.timeouts)\n end", "def client\n @client ||= Client.new(configuration)\n end", "def initialize(client_id, client_secret, opts={})\n @id = client_id\n @secret = client_secret\n @site = opts.delete(:site)\n ssl = opts.delete(:ssl)\n @options = { :authorize_url => '/oauth/authorize',\n :access_token_url => '/oauth/access_token', \n :access_token_method => :post,\n :connection_opts => {},\n :parse_json => false,\n :raise_errors => true }.merge(opts)\n @options[:connection_opts][:ssl] = ssl if ssl\n end", "def load_client\n user_agent_suffix = \"fluent-#{NAME}\"\n\n options = {\n user_agent_suffix: user_agent_suffix\n }\n\n if @region\n options[:region] = @region\n end\n\n if @aws_key_id && @aws_sec_key\n options.update(\n access_key_id: @aws_key_id,\n secret_access_key: @aws_sec_key,\n )\n elsif @profile\n credentials_opts = {:profile_name => @profile}\n credentials_opts[:path] = @credentials_path if @credentials_path\n credentials = Aws::SharedCredentials.new(credentials_opts)\n options[:credentials] = credentials\n elsif @role_arn\n credentials = Aws::AssumeRoleCredentials.new(\n client: Aws::STS::Client.new(options),\n role_arn: @role_arn,\n role_session_name: \"fluent-plugin-kinesis-aggregation\",\n external_id: @external_id,\n duration_seconds: 60 * 60\n )\n options[:credentials] = credentials\n end\n\n if @debug\n options.update(\n logger: Logger.new(log.out),\n log_level: :debug\n )\n end\n\n if @http_proxy\n options[:http_proxy] = @http_proxy\n end\n\n @client = Aws::Kinesis::Client.new(options)\n end", "def initialize(client)\n super(client, 'core')\n end", "def get_client(client_class = ::Elarian::BaseClient)\n @default_client ||= client_class.new(connection_credentials)\n on_error = lambda do |error|\n puts \"Error occurred #{error}\"\n disconnect_and_stop_loop\n end\n @default_client.on(:error, on_error)\n connect(@default_client)\n @default_client\n end", "def oauth2_client_id\n is_auth_session? ? self.class.oauth2_client_id : session_class.oauth2_client_id\n end", "def get_client_using_get_with_http_info(client_id, appTokenConfig = {}, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ClientApi.get_client_using_get ...'\n end\n # verify the required parameter 'client_id' is set\n if @api_client.config.client_side_validation && client_id.nil?\n fail ArgumentError, \"Missing the required parameter 'client_id' when calling ClientApi.get_client_using_get\"\n end\n # resource path\n local_var_path = '/nucleus/v1/client/{client_id}'.sub('{' + 'client_id' + '}', client_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['*/*'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['oauth2']\n\n if @api_client.config.client_side_validation && appTokenConfig['basePath'].nil?\n fail ArgumentError, \"Missing the required parameter 'basePath'\"\n end\n\n if @api_client.config.client_side_validation && appTokenConfig['authType'].nil?\n fail ArgumentError, \"Missing the required parameter 'authType'\"\n end\n\n @auth_config.config.host = appTokenConfig['basePath']\n @api_client.config.host = appTokenConfig['basePath']\n\n if appTokenConfig['authType'].downcase == 'client_credentials'\n client_credentials_token = create_client_credential_return(appTokenConfig)\n @api_client.config.access_token = client_credentials_token\n elsif appTokenConfig['authType'].downcase == 'password_credentials'\n password_credential_token = create_password_credential_return(appTokenConfig)\n @api_client.config.access_token = password_credential_token\n elsif appTokenConfig['authType'].downcase == 'client_token_credentials'\n client_token_credential = create_client_token_credential_return(appTokenConfig)\n @api_client.config.access_token = client_token_credential\n end\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Client')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ClientApi#get_client_using_get\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def client\n @client ||= Github::ApiProxy.new(@options[:access_token])\n end", "def post_oauth_clients_with_http_info(body, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: OAuthApi.post_oauth_clients ...\"\n end\n \n \n # verify the required parameter 'body' is set\n fail ArgumentError, \"Missing the required parameter 'body' when calling OAuthApi.post_oauth_clients\" if body.nil?\n \n \n \n \n \n # resource path\n local_var_path = \"/api/v2/oauth/clients\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n local_header_accept = ['application/json']\n local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result\n\n # HTTP header 'Content-Type'\n local_header_content_type = ['application/json']\n header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(body)\n \n auth_names = ['PureCloud OAuth']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'OAuthClient')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: OAuthApi#post_oauth_clients\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def client\n @client ||= ::Twilio::REST::Client.new(@account_sid, @auth_token)\n end", "def client\n # @client ||= MyService::Client.new(SinaToken.consumer.key, SinaToken.consumer.secret, token, secret)\n end", "def set_no_auth\n FHIR.logger.info 'Configuring the client to use no authentication.'\n @use_oauth2_auth = false\n @use_basic_auth = false\n @security_headers = {}\n @client = RestClient\n @client.proxy = proxy unless proxy.nil?\n @client\n end", "def set_oauth_client(id, secret, env)\n @oauth_client = OAuth2::Client.new(\n id,\n secret,\n site: Volabit.site_for(env),\n raise_errors: false\n )\n end", "def initialize\n super('OAuth')\n @config = nil # common config\n @auth = {} # configs for each site\n @nonce_count = 0\n @signature_handler = {\n 'HMAC-SHA1' => method(:sign_hmac_sha1)\n }\n end", "def twitter\n @client ||= Twitter::REST::Client.new do |config|\n config.consumer_key = Rails.application.secrets.twitter_api_key\n config.consumer_secret = Rails.application.secrets.twitter_api_secret\n config.access_token = token\n config.access_token_secret = secret\n end\n end", "def initialize(o_auth_client_id: nil, o_auth_client_secret: nil)\r\n Configuration.o_auth_client_id = o_auth_client_id if\r\n o_auth_client_id\r\n Configuration.o_auth_client_secret = o_auth_client_secret if\r\n o_auth_client_secret\r\n end", "def initialize(client_id=nil, client_secret=nil, callback_url=nil, *args)\n opts = (args.last.is_a?(Hash) ? args.last : {}).with_indifferent_access\n\n opts.delete_if { |k, v| v.nil? }.reverse_merge!(default_tout_configuration)\n\n @client_id = client_id\n @client_secret = client_secret\n @access_token = opts[:access_token]\n @callback_url = callback_url\n @uri_scheme = opts[:uri_scheme]\n @uri_host = opts[:uri_host]\n @uri_port = opts[:uri_port]\n @uri_base_path = opts[:uri_base_path]\n @uri_version = opts[:uri_version]\n @auth_site = opts[:auth_site]\n @authorize_url = opts[:authorize_url]\n @token_url = opts[:token_url]\n @email = opts[:email]\n @password = opts[:password]\n end", "def http_client\n @http_client ||= @http_adapter.new(@site_url, @connection_options)\n end", "def oauth_options\n {\n consumer_key: client_id,\n consumer_secret: client_secret,\n token: access_token,\n token_secret: access_token_secret\n }\n end", "def client\n @client ||= platform_klass::Client.new(@options)\n end", "def create_client_from_outhAccount(scope, oob_uri, user_id, oauth_cred_file)\n #oob_uri = 'urn:ietf:wg:oauth:2.0:oob'\n #user_id = 'eyemole@gmail.com'\n client_id = Google::Auth::ClientId.from_file(oauth_cred_file)\n token_store = Google::Auth::Stores::FileTokenStore.new(:file => 'tokens.yaml')\n authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: oob_uri )\n #Launchy.open(url)\n puts \"Open this URL in Browser and enter the code you got from browser below\"\n puts \"URL: #{url}\"\n print \"enter the code you got from browser here and press Enter: \"\n # code = gets\n code = STDIN.gets.chomp\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: oob_uri)\n end\n blogger = Google::Apis::BloggerV3::BloggerService.new\n blogger.authorization = credentials\n return blogger\nend", "def client\n @client ||= Faraday.new(api_host) do |faraday|\n faraday.headers[\"Authorization\"] = \"Bearer #{access_token}\"\n faraday.response :logger if Rails.env.test?\n faraday.adapter Faraday.default_adapter\n end\n end", "def json\n return @adapters[:json] if @adapters[:json]\n require 'oauth_client/adapters/json'\n @adapters[:json] = OAuthClient::Adapters::Json.new(self)\n end", "def json\n return @adapters[:json] if @adapters[:json]\n require 'oauth_client/adapters/json'\n @adapters[:json] = OAuthClient::Adapters::Json.new(self)\n end", "def authorizator_client\n @authorizator_client ||= Authorizator::Client.new(caller_service: caller_service, authorizator_service: authorizator_service)\n end", "def initialize(client, options = {})\n raise Xeroizer::InvalidClientError.new unless [OAuth, OAuth2].member?(client.class)\n @xero_url = options[:xero_url] || \"https://api.xero.com/api.xro/2.0\"\n @rate_limit_sleep = options[:rate_limit_sleep] || false\n @rate_limit_max_attempts = options[:rate_limit_max_attempts] || 5\n @nonce_used_max_attempts = options[:nonce_used_max_attempts] || 1\n @default_headers = options[:default_headers] || {}\n @before_request = options.delete(:before_request)\n @after_request = options.delete(:after_request)\n @around_request = options.delete(:around_request)\n @client = client\n @logger = options[:logger] || false\n @unitdp = options[:unitdp] || 2\n end", "def method_missing(method, *args, &block)\n if @client.respond_to?(method)\n define_singleton_method(method) do |*args, &block|\n @client.send(method, *args, &block)\n end\n return send(method, *args, &block)\n end\n super\n end" ]
[ "0.7071465", "0.6915986", "0.6905785", "0.6855409", "0.67066187", "0.6700351", "0.669656", "0.66850513", "0.6615154", "0.65906507", "0.65702647", "0.65653515", "0.64839405", "0.64443237", "0.6426523", "0.63746375", "0.63389695", "0.63172853", "0.6254279", "0.6240883", "0.6229124", "0.62247944", "0.62120837", "0.62063825", "0.6204745", "0.61866724", "0.6180744", "0.6175401", "0.6145428", "0.61344975", "0.6127765", "0.60884356", "0.6048212", "0.60438764", "0.60339504", "0.60290253", "0.6002641", "0.5999013", "0.5999013", "0.5984455", "0.5983866", "0.59771633", "0.59709704", "0.5968834", "0.596371", "0.59588563", "0.5937412", "0.5912764", "0.5882576", "0.5881676", "0.5879561", "0.5878229", "0.5877751", "0.58704644", "0.58691263", "0.58540887", "0.5840416", "0.58380765", "0.582772", "0.58208805", "0.5798966", "0.5797177", "0.57939726", "0.5791516", "0.5782274", "0.57702625", "0.5768337", "0.57607424", "0.5760347", "0.5758034", "0.5751605", "0.57496035", "0.57482916", "0.57331866", "0.5732563", "0.5718363", "0.57154703", "0.57036996", "0.5701886", "0.56970686", "0.56838346", "0.56772214", "0.56771165", "0.56749016", "0.5654849", "0.5651356", "0.5645632", "0.5639966", "0.56257397", "0.5614104", "0.56127286", "0.5595501", "0.5594662", "0.5591605", "0.55900156", "0.55884874", "0.55884874", "0.5587839", "0.55803764", "0.5574893" ]
0.63190436
17
Dropping query_string from callback_url prevents some errors in call to /api/oauth.v2.access.
def callback_url full_host + script_name + callback_path end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def callback_url\n if @authorization_code_from_signed_request_in_cookie\n ''\n else\n # Fixes regression in omniauth-oauth2 v1.4.0 by https://github.com/intridea/omniauth-oauth2/commit/85fdbe117c2a4400d001a6368cc359d88f40abc7\n options[:callback_url] || (full_host + script_name + callback_path)\n end\n end", "def authorize_url(callback_url)\n request_token.authorize_url+'&oauth_callback='+CGI.escape(callback_url)\n end", "def callback_url\n options.authorize_params.callback_url or super\n end", "def oauth_callback_url\n end", "def authorize_url(callback_url, options = {})\n url = \"#{BASE_URL}/oauth/authorize?client_id=#{app_id}&redirect_uri=#{callback_url}\"\n scope = options.delete(:scope)\n url += \"&scope=#{scope.join(',')}\" unless scope.blank?\n url += \"&#{options.to_query}\" unless options.blank? # Add other options. FIXME: to_query method requires Rails?!\n return url\n end", "def oauth_redirect_uri\n uri = URI.parse(request.url)\n uri.path = '/sk_auth/callback'\n uri.query = nil\n uri.to_s\n end", "def callback_url\n options[:redirect_uri] || (full_host + script_name + callback_path)\n end", "def callback_url\n options[:redirect_uri] || (full_host + script_name + callback_path)\n end", "def redirect_uri\n @redirect_uri ||= root_url[0..-2] + oauth_callback_path\n end", "def redirect_url\n\t\tcallback_url\n\tend", "def clean_url(url)\n uri = URI.parse(url)\n uri.query = CGI.parse(uri.query || '').reject { |k| k == 'api_key' }.to_query\n uri.to_s\n end", "def get_authorization_url(request_token, callback_url)\n \"#{request_token.authorize_url}&oauth_callback=#{CGI::escape(callback_url)}\"\n end", "def oauth_url\n url = <<-URL\n https://www.facebook.com/dialog/oauth/\n ?client_id=#{Network::Facebook.app_id}\n &redirect_uri=#{URI.escape(\"#{root_url}auth/facebook/?r=#{redirect_for(request.referer)}\")}\n &scope=#{Network::Facebook.scope}\n URL\n url.gsub(/\\s+/, '')\n end", "def callback\n @callback ||= ERB::Util.url_encode(\"#{request.url}&callback\")\n end", "def redirect_to_url(callback_url)\n client_details = \"client_id=#{self.client_id}\"\n return callback_url + \"?#{client_details}\"\n end", "def callback2\n oauth_token = FitbitOauthToken.where(:token=>params[:state]).last\n verifier = params[:code]\n if oauth_token\n return_url = request.original_url\n #xd = YAML::load oauth_token.extra_data\n # if return_url already has a ? in it, then this needs to add an & and not a ? \n #question_mark_or_ampersand = xd[:return_url].to_s =~ /\\?/ ? '&' : '?'\n question_mark_or_ampersand = return_url.to_s =~ /\\?/ ? '&' : '?'\n #There's a code and a state that need to go with:\n url = \"\"\n url += \"#{return_url.gsub(\"callback2\",\"post_authorize\")}\"\n if !verifier.nil? && !verifier.empty? \n #Only add the token and verifier if we have both\n #This way, the recieving application can respond if they're missing\n url += \"#{question_mark_or_ampersand}\"\n url += \"oauth_token=#{params[:state]}\"\n url += \"&oauth_verifier=#{params[:code]}\"\n end\n redirect_to url\n else\n render :text=>\"error processing oauth token\", :layout=>false\n end\n end", "def callback_url\n options[:callback_url] || (full_host + script_name + callback_path)\n end", "def callback_url\n options[:callback_url] || (full_host + script_name + callback_path)\n end", "def callback_url\n options[:callback_url] || (full_host + script_name + callback_path)\n end", "def oauth_url_authorize\n return \"#{$SETTINGS[:oauth_server_url_authorize]}?response_type=code&client_id=#{$SETTINGS[:oauth_client_id]}&scope=ALL&redirect_uri=#{oauth_redirect_uri}\" \n end", "def callback_url\n auth_endpoint_callback_url(org: @organization.id)\n end", "def authorization_url\n uri = URI(OAUTH_URL)\n uri.query = {\n client_id: client_id,\n redirect_uri: redirect_uri,\n scope: scope_url,\n response_type: 'code',\n access_type: 'offline'\n }.to_param\n\n uri.to_s\n end", "def oauth_callback_url\n url_for :action => \"list\"\n end", "def get_oauth_url\n params = {}\n url = @url\n\n if url.include?(\"?\")\n parsed_url = URI::parse(url)\n CGI::parse(parsed_url.query).each do |key, value|\n params[key] = value[0]\n end\n params = Hash[params.sort]\n\n url = parsed_url.to_s.gsub(/\\?.*/, \"\")\n end\n\n nonce_lifetime = 15 * 60 # Woocommerce keeps nonces for 15 minutes\n\n params[\"oauth_consumer_key\"] = @consumer_key\n params[\"oauth_nonce\"] = Digest::SHA1.hexdigest((Time.new.to_f % nonce_lifetime + (Process.pid * nonce_lifetime)).to_s)\n params[\"oauth_signature_method\"] = @signature_method\n params[\"oauth_timestamp\"] = Time.new.to_i\n params[\"oauth_signature\"] = CGI::escape(generate_oauth_signature(params, url))\n\n query_string = URI.encode_www_form(params)\n\n \"#{url}?#{query_string}\"\n end", "def create_oauth_url(cb_url, encoded_auth_state)\n oauth_url = \"https://www.facebook.com/dialog/oauth/?client_id=\" +\n \"#{APP_ID}&redirect_uri=#{cb_url}&state=#{encoded_auth_state}\"\n end", "def get_authorize_url(callback=nil)\n get_request_token()\n\n url = \"/#{Dropbox::API_VERSION}/oauth/authorize?oauth_token=#{URI.escape(@request_token.key)}\"\n if callback\n url += \"&oauth_callback=#{URI.escape(callback)}\"\n end\n if @locale\n url += \"&locale=#{URI.escape(@locale)}\"\n end\n\n \"https://#{Dropbox::WEB_SERVER}#{url}\"\n end", "def redirect_url(callback_url)\n signin_url(callback_url)\n end", "def auth_url(connection = nil)\n state = \"?state=#{Service.encode_state(connection)}\"\n callback = URI.encode_www_form_component(config[:redirect_uri] + state)\n\n uri = URI.parse(base_auth_url)\n uri.query ||= \"\"\n uri.query << \"&#{self.class.callback_param_name}=#{callback}\"\n uri.to_s\n end", "def authorize_endpoint_url\n uri = URI(openid_config['authorization_endpoint'])\n uri.query = URI.encode_www_form(client_id: client_id,\n redirect_uri: callback_url,\n response_mode: response_mode,\n response_type: response_type,\n nonce: new_nonce)\n uri.to_s\n end", "def authorize_url\n client.web_server.authorize_url( :redirect_uri => callback_url )\n end", "def authorization_url\n url = \"#{host}/OAuth2AccessRequest.action?response_type=code&client_id=#{@client_id}\"\n url += \"&redirect_uri=#{Addressable::URI.escape(@redirect_uri)}\" if @redirect_uri\n url += \"&state=#{@state}\" if @state\n url\n end", "def redirect_uri_for base_url\n return @callback_uri if uri_is_postmessage?(@callback_uri) || !URI(@callback_uri).scheme.nil?\n raise format(MISSING_ABSOLUTE_URL_ERROR, @callback_uri) if base_url.nil? || URI(base_url).scheme.nil?\n URI.join(base_url, @callback_uri).to_s\n end", "def authorize_url(options = {})\n options[:response_type] ||= \"code\"\n options[:redirect_uri] ||= redirect_uri\n params = authorization_params.merge(options)\n uri = URI(\"#{base_url}/api/oauth2/auth/\")\n uri.query = URI.encode_www_form(params)\n uri.to_s\n end", "def sso_integration_callback_url\n # Usually http://example.com/auth/:system_name/callback\n url = callback_url(query: {})\n\n case kind\n when 'auth0'\n # e.g. http://example.com/auth/invitations/auth0/auth0_123abc/callback\n invitation_signup = client.callback_url(\"#{base_url}/invitations\")\n\n [url, invitation_signup].join(', ')\n else\n url\n end\n end", "def merge_oauth_redirect_url(url, params = {})\n if url\n raise InvalidRedirectUrl.new(url) unless valid_redirect_uri?(url)\n uri = URI.parse(url)\n else\n uri = URI.parse(self.oauth_redirect_uri)\n end\n if uri.query.present?\n components = Hash[\n *CGI.parse(uri.query).entries.map { |k, v| [k, v[0]] }.flatten]\n components.merge!(params.stringify_keys)\n else\n components = params\n end\n if components.any?\n uri.query = components.map { |k, v|\n CGI.escape(k.to_s) + '=' + CGI.escape(v.to_s) }.join('&')\n else\n uri.query = nil\n end\n uri.to_s\n end", "def facebook_path_scrub(url)\n return url.gsub('facebook/', '').gsub('/facebook', '')\n end", "def callback_phase\n options.client_options[:access_token_path] = \"/oauth/qzoneoauth_access_token?oauth_vericode=#{request['oauth_vericode'] }\" if request['oauth_vericode']\n super\n end", "def to_query\n\t\tif oauth10?\n\t\t\tsuper\n\t\telse\n\t\t\t\"#{super}&oauth_callback_confirmed=true\"\n\t\tend\n\tend", "def extra_query_param\n return \"\" unless env['omniauth.params']\n env['omniauth.params'].map{|k,v| \"&#{k}=#{Rack::Utils.escape(v)}\"}.join\n end", "def build_url(redirect_uri,type)\n path = redirect_uri.split('#',2).first if redirect_uri.include? \"#\"\n path = redirect_uri.split('?',2).first if redirect_uri.include? \"?\"\n case type\n when \"token\"\n return path + \"?access_token=#{self.access_token}\"\n when \"code\"\n return path + \"?request_token=#{self.code}\"\n end\n end", "def authorize_url(redirect_url, state=nil)\n params = {:redirect_uri => redirect_url}\n params[:state] = state if state\n client.auth_code.authorize_url(params).gsub(/api-ssl\\./,'')\n end", "def authorize_url(params={})\n # response_type param included by default by using the OAuth 2.0\n # auth_code strategy\n # client_id param included automatically by the OAuth 2.0 gem\n params[:state] ||= state\n params[:redirect_uri] ||= \"http://localhost\"\n oauth2_client.auth_code.authorize_url(params)\n rescue OAuth2::Error => e\n raise LinkedIn::Errors::UnauthorizedError.new(e.code), e.description\n end", "def openid_callback_url\n \"#{request.protocol}://#{request.host}#{Merb::Router.url(:openid)}\"\n end", "def build_auth_url\n URI.parse(\"https://www.dropbox.com/oauth2/authorize\").tap do |uri|\n uri.query = URI.encode_www_form(\n client_id: DROPBOX_APP_KEY,\n redirect_uri: SHOTTY_CALLBACK_URL,\n response_type: :code,\n state: csrf_token,\n )\n end\nend", "def clear_client_and_redirect_url\n\t session.delete('omniauth.state')\n\t if is_json_request?\n\t \tsession.delete(\"client\")\n\t \tsession.delete(\"redirect_url\")\n\t end\n\tend", "def without_query_string\n query = to_query_string\n without_query_string = query ? gsub(query, '') : self\n\n Wgit::Url.new(without_query_string)\n end", "def url_with_query_string\n if query_string && query_string.size > 0\n base_url + \"?#{query_string}\"\n else\n base_url\n end\n end", "def callback_uri\n return @callback_uri\n end", "def authorize_url\n client = OAuth2::Client.new(client_id, client_secret, :site => oauth_url)\n client.auth_code.authorize_url(:redirect_uri => redirect_uri)\n end", "def get_auth_url(use_callback_flow=true)\n if use_callback_flow\n service_name = service_name_for_user(DATASOURCE_NAME, @user)\n @client.authorization.state = CALLBACK_STATE_DATA_PLACEHOLDER.sub('user', @user.username)\n .sub('service', service_name)\n else\n @client.authorization.redirect_uri = REDIRECT_URI\n end\n @client.authorization.authorization_uri.to_s\n end", "def sso_callback_url_for(user)\n\n sso_token = encrypt_sso_token_for_user(user)\n\n url = sso_callback_url.dup\n if sso_callback_url =~ /\\?/\n url << '&'\n else\n url << '?'\n end\n url << \"sso_token=#{sso_token}\"\n\n url\n\n end", "def authorize_url(client_id, redirect_uri, options={})\n \"https://#{API_URL}/oauth/authorize?#{build_query(options.merge(:client_id => client_id, :redirect_uri => redirect_uri))}\"\n end", "def omit_query\n query = to_query\n omit_query_string = query ? gsub(\"?#{query}\", '') : self\n\n Wgit::Url.new(omit_query_string)\n end", "def oauth_url(response_type = 'code')\n # The Redirect URI must be the same as registered with Put.io\n PUTIO_BASE_URL + \"/oauth2/authenticate?client_id=%i&response_type=%s&redirect_uri=%s\" % [@client_id, response_type, @redirect_uri]\n end", "def authorize_url\n # Fix: replace default oauth2 options, specially to prevent the Faraday gem which\n # concatenates with \"/\", removing the Facebook api version\n options = {\n site: File.join(@site, api_version.to_s),\n authorize_url: File.join(@auth_site, api_version.to_s, auth_path),\n token_url: token_url\n }\n\n @scope = access_permissions.present? ? access_permissions.join(',') : scope\n super(options)\n end", "def callback_uri=(value)\n @callback_uri = value\n end", "def authorize_url(client_id=nil, redirect_uri=@@config.redirect_uri, opts={})\n raise \"client_id required to authorize url. Pass with Geoloqi.config\" unless client_id\n url = \"#{oauth_url}?response_type=code&client_id=#{Rack::Utils.escape client_id}&redirect_uri=#{Rack::Utils.escape redirect_uri}\"\n url += \"&#{Rack::Utils.build_query opts}\" unless opts.empty?\n url\n end", "def oauth_url\n 'https://geoloqi.com/oauth/authorize'\n end", "def auth_url\n MiniFB.oauth_url(@app_id, @redirect_to,\n :scope => 'user_about_me') # See MiniFB.scopes\n end", "def tracking_callback\n return if AhoyEmail.tracking_callback_url.blank?\n return if callback_params[:atid].blank?\n\n begin\n uri = URI(\"#{AhoyEmail.tracking_callback_url}/#{callback_params[:atid]}/#{callback_params[:utm_action]}\")\n dupe_callback_params = callback_params.to_h\n dupe_callback_params[:redirect] = false\n dupe_callback_params[:url] = \"#{request.scheme}://#{request.host.include?(\"www.\") ? request.host : \"www.#{request.host}\"}#{request.path}\"\n uri.query = URI.encode_www_form(dupe_callback_params)\n Net::HTTP.get_response(uri)\n rescue StandardError => e\n Honeybadger.notify(e)\n end\n end", "def callback\n self.oaw_callback(params[:oauth_verifier], params[:oauth_token])\n end", "def callback_options\n options = config.to_hash\n options.deep_symbolize_keys!\n options[:url_options].reject { |k, _v| k == :script_name }\n end", "def callback_url\n File.join([full_host, script_name, callback_path].compact)\n end", "def get_user_auth_url\n @oauth_token = request_oauth_token\n return @authorize_url + \"?oauth_token=\" + @oauth_token[\"oauth_token\"]\n rescue\n puts $! if @@verbose\n return nil\n end", "def oauth_uri(provider=\"FACEBOOK\")\n dest= session[\"return_to\"] || request.env[\"REQUEST_URI\"] || \"/\"\n \"#{oauth_uri_left_part}/account/oauth_start?provider=#{CGI.escape(provider)}&dest_left=#{CGI.escape(request_uri_left_part)}&dest_path=#{CGI.escape(dest)}\"\n end", "def base_url\n @url.to_s.split('?').first\n end", "def scheme_callback_uri\n svc = minter\n return nil if svc.blank?\n\n svc.respond_to?(:callback_path) ? svc.callback_path : nil\n end", "def ios_client_callback_url(user)\n \"lolgramz://auth_callback?instagram_token=#{user.instagram_token}&api_token=#{user.api_token}\"\n end", "def authorize_url_with_buzz options = {}\n options[:scope] ||= @oauth_scope\n options[:domain] ||= self.auth_handler.api_key\n options.inject(authorize_url_without_buzz) do |res, (key, value)|\n res << '&' + CGI.escape(key.to_s) + '=' + CGI.escape(value.to_s)\n end\n end", "def get_authurl\n\t\tlogger.debug \"D, #{__method__.to_s}\"\n\t\tparams = {\n \"client_id\" => @client_id,\n \"response_type\" => \"code\",\n \"redirect_uri\" => @redirect_uri,\n \"prompt\" => \"consent\"\n }\n auth_uri = URI::Generic.new(\"https\", nil, @auth_url, nil, nil, \"authorize\", \n \t\t\t\t\t\t\t nil, nil, nil)\n auth_uri.query = URI.encode_www_form(params)\n logger.debug \"D, #{__method__.to_s}, #{auth_uri.to_s}\"\n return auth_uri.to_s\n\tend", "def auth_callback\n current_user\n omniauth_origin = session[:omniauth_origin]\n session.delete(:omniauth_origin)\n redirect_to omniauth_origin || '/'\n end", "def sanitize_redirect_url\n referer = params[:referer].blank? ? request.referer : params[:referer]\n\n if referer && (referer =~ %r|^https?://#{request.host}#{root_path}| ||\n referer =~ %r|^https?://#{request.host}:#{request.port}#{root_path}|)\n #self-referencing absolute url, make it relative\n referer.sub!(%r|^https?://#{request.host}(:#{request.port})?|, '')\n elsif referer && referer =~ %r|^(\\w+:)?//|\n Rails.logger.debug(\"#post_auth_redirect_url will NOT use third party url for post login redirect: #{referer}\")\n referer = nil\n end\n\n if referer && referer_blacklist.any? {|blacklisted| referer.starts_with?(blacklisted) }\n Rails.logger.debug(\"#post_auth_redirect_url will NOT use a blacklisted url for post login redirect: #{referer}\")\n referer = nil\n elsif referer && referer[0,1] != '/'\n Rails.logger.debug(\"#post_auth_redirect_url will NOT use partial path for post login redirect: #{referer}\")\n referer = nil\n end\n\n return referer || root_path\n end", "def parse_oauth_options\n {\n :request_token_url => full_oauth_url_for(:request_token, :api_host),\n :access_token_url => full_oauth_url_for(:access_token, :api_host),\n :authorize_url => full_oauth_url_for(:authorize, :auth_host),\n :site => @consumer_options[:site] || @consumer_options[:api_host] || DEFAULT_OAUTH_OPTIONS[:api_host]\n }\n end", "def oauth_authorize_url(client_id, redirect_uri, options={})\n self.format_url('/oauth/authorize', {\n :client_id => client_id,\n :redirect_uri => redirect_uri\n }.merge(options))\n end", "def unauthorized_request\n Rails.logger.debug \"------ 'Unauthorized' response from resource server ------\"\n\n authorize_path = @organization.authorization_server.authorize_path(callback_url)\n Rails.logger.debug \"------ Redirecting to: #{authorize_path} ------\"\n redirect_to authorize_path\n end", "def oauth_url\n @oauth_url || File.join(host, \"oauth20/token\")\n end", "def clean_url!\n remove_urchin\n case uri.host\n when 'www.youtube.com'\n self.url = \"#{uri.scheme}://#{uri.host}/watch?v=#{self.params['v'][0]}\"\n when 'boingboing.net'\n self.url = \"#{uri.scheme}://#{uri.host}#{uri.path}\"\n end\n end", "def scheme_callback_uri\n svc = minter\n return nil unless svc.present?\n\n svc.respond_to?(:callback_path) ? svc.callback_path : nil\n end", "def redirect_original(request, state_params, site)\n response = Rack::Response.new\n # Note that app_callback_url is added by OmniAuth.config.before_request_phase\n # any value provided by a client will be overwritten in that method so that we\n # don't use/trust values sent by the client\n return_url = state_params[\"app_callback_url\"]\n query = OauthStateMiddleware.query_string(request.params, SecureRandom.hex(64))\n return_url << \"?\"\n return_url << signed_query_string(query, site.secret)\n response.redirect return_url\n response.finish\n end", "def auth_code_url(options={})\n options = default_auth_code_url_options(options)\n\n if self.options[:raise_errors]\n check_redirect_uri!(options)\n end\n\n @redirect_uri = options[:redirect_uri]\n\n self.auth_code.authorize_url(options)\n end", "def oauth2callback\n @g_cal_api.oauth2callback\n end", "def callback\n connector_response_url(callback_options)\n end", "def unrelativize_url(url)\n url =~ /^\\/\\// ? \"#{scheme}://#{url[2..-1]}\" : url\n end", "def unrelativize_url(url)\n url =~ /^\\/\\// ? \"#{scheme}://#{url[2..-1]}\" : url\n end", "def clean_url\n return # Not yet implemented\n end", "def callback_url\n url = if _workitem.fields['callbacks'].is_a?(String)\n _workitem.fields['callbacks']\n else\n _workitem.fields['callbacks'][participant_name]\n end\n if url.nil?\n raise MissingCallbackUrl\n else\n url\n end\n end" ]
[ "0.70621866", "0.6864417", "0.6837393", "0.6717086", "0.6713367", "0.6649983", "0.647477", "0.647477", "0.6409368", "0.63627714", "0.6346695", "0.632082", "0.6275508", "0.62429696", "0.62285316", "0.62277853", "0.6184288", "0.6184288", "0.6184288", "0.61700106", "0.616855", "0.6145306", "0.6138551", "0.61326677", "0.60674834", "0.6066807", "0.6046435", "0.60367", "0.59687376", "0.59354913", "0.5907827", "0.58978194", "0.58584446", "0.58276606", "0.581745", "0.5808797", "0.5801437", "0.5797741", "0.57651097", "0.5764744", "0.57606757", "0.57581997", "0.57463765", "0.5694129", "0.5676855", "0.5658962", "0.56376404", "0.56316173", "0.56170726", "0.5609052", "0.5603209", "0.5589052", "0.5588741", "0.55556446", "0.55542916", "0.55488974", "0.5542856", "0.552863", "0.55206686", "0.55175024", "0.5511954", "0.54984707", "0.5494472", "0.5484073", "0.5476211", "0.5446668", "0.5445394", "0.5416386", "0.5406314", "0.5405286", "0.5404722", "0.5403636", "0.5368413", "0.53654194", "0.5360687", "0.5359383", "0.5359122", "0.53524387", "0.53473693", "0.5341381", "0.53309584", "0.5314449", "0.5313306", "0.5313306", "0.5309667", "0.53082865" ]
0.57241046
56
Get a mutex specific to the calling method. This operation is synchronized with its own mutex.
def semaphore(method_name = caller[0][/`([^']*)'/, 1]) @main_semaphore.synchronize { @semaphores[method_name] ||= Mutex.new } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mutex\n return @__mutex if @__mutex\n synchronized(self.class) {\n # check again: by the time we get into this synchronized block\n # some other thread might have already created the mutex.\n @__mutex = @__mutex || Mutex.new\n }\n end", "def mutex\n @mutex\n end", "def mutex\n @mutex ||= Mutex.new\n end", "def mutex; end", "def mutex; end", "def mutex; end", "def mutex; end", "def order_creation_mutex\n result = @@order_creation_mutexes[id]\n unless result\n @@order_creation_mutexes.put_if_absent(id, ::Mutex.new)\n result = @@order_creation_mutexes[id]\n end\n result\n end", "def init_mutex\n @mutex = Mutex.new\n end", "def initialize\n @mutex = Mutex.new\n end", "def semaphore\n @semaphore ||= Mutex.new\n @semaphore\n end", "def semaphore\n @semaphore ||= Mutex.new\n @semaphore\n end", "def get_lock_id\n @lock_id\n end", "def locked_by\n @lock_name\n end", "def attr_memoized_mutex\n return @attr_memoized_mutex if @attr_memoized_mutex\n\n self.class.attr_memoized_mutex.synchronize {\n @attr_memoized_mutex ||= Mutex.new\n }\n end", "def synchronized(o)\no.mutex.synchronize { yield }\nend", "def mutex_path(mutex)\n if mutex.start_with? 'tmp'\n mutex\n else\n 'tmp/' << mutex\n end\n end", "def current_concurrency\n self.class.current_concurrency self\n end", "def with_player_mutex(id, zone, no_lock, &blk)\n if no_lock then\n yield\n else\n cache_key = cache_key(id, zone)\n\n @mutex[cache_key] ||= Mutex.new\n this_mutex = @mutex[cache_key]\n\n Boot::Helper.lock_mutex this_mutex, @mutex_try_limit\n begin\n yield\n ensure\n Boot::Helper.unlock_mutex this_mutex\n end\n end\n end", "def lock_interaction(job_id)\n operation_lock = nil\n\n # get the lock object\n @manager_lock.synchronize do\n @job_lock_table[job_id] ||= Mutex.new\n operation_lock = @job_lock_table[job_id]\n end\n\n return operation_lock.lock\n end", "def interceptors_mutex(&block)\n @interceptors_mutex ||= begin\n require 'monitor'\n Monitor.new\n end\n @interceptors_mutex.synchronize(&block)\n end", "def synchronize(&block)\n @mutex.synchronize(&block)\n end", "def synchronize(key = nil)\n mutex[key].synchronize do\n yield\n end\n end", "def find(options)\n type, name = options.to_a.flatten\n\n locks.find { |mutex|\n mutex.type == type &&\n mutex.name == name\n }\n end", "def lock\n @lock ||= Monitor.new\n end", "def obtain_lock(name, id, &block)\n verify_lock_defined!(name)\n raise ArgumentError, \"Missing block to #{self.name}.obtain_lock\" unless block_given?\n lock_name = \"#{name}_lock\"\n Redis::Lock.new(redis_field_key(lock_name, id), redis_field_redis(lock_name), redis_objects[lock_name.to_sym]).lock(&block)\n end", "def shared_locker(name)\n Locker.shared_locker(self, name)\n end", "def find_and_lock_job(node)\r\n\t\t\tArmory::Job.find_job(node).each do |job|\r\n\t\t\t\treturn job if job.aquire_lock?(self.name)\r\n\t\t\tend\r\n\t\t\t\r\n\t\t\treturn nil\r\n\t\tend", "def getMiqAlarm_locked\n raise \"addMiqAlarm_locked: cache lock not held\" unless @cacheLock.sync_locked?\n return(@miqAlarmMor) if @miqAlarmMor\n\n begin\n @cacheLock.sync_lock(:EX) if (unlock = @cacheLock.sync_shared?)\n\n logger.info \"MiqVimVm(#{@invObj.server}, #{@invObj.username}).getMiqAlarm_locked: calling getAlarm\"\n alarms = @invObj.getAlarm(@sic.alarmManager, @vmMor)\n logger.info \"MiqVimVm(#{@invObj.server}, #{@invObj.username}).getMiqAlarm_locked: returned from getAlarm\"\n alarms.each do |aMor|\n ap = @invObj.getMoProp(aMor, \"info.name\")\n next unless ap['info']['name'][MIQ_ALARM_PFX]\n @miqAlarmMor = aMor\n return(aMor)\n end if alarms\n ensure\n @cacheLock.sync_unlock if unlock\n end\n\n (nil)\n end", "def caller\n Thread.current\n end", "def caller\n Thread.current\n end", "def thread_safe=(value)\n @lock = value ? Mutex.new : PlaceboLock.new\n end", "def synchronize(&block)\n @mutex.synchronize(&block)\n end", "def validate_lock\n raise LockRequired.new(__method__, self.class) unless @mutex.owned?\n end", "def initialize()\n @mutex = Mutex.new\n end", "def time_travel_lock\n @time_travel_lock ||= Mutex.new\n end", "def synchronized(*args)\n# Case 1: with one argument and a block, synchronize on the object\n# and execute the block\nif args.size == 1 && block_given?\nargs[0].mutex.synchronize { yield }\n# Case two: with one argument that is not a symbol and no block\n# return a SynchronizedObject wrapper\nelsif args.size == 1 and not args[0].is_a? Symbol and not block_given?\nSynchronizedObject.new(args[0])\n# Case three: when invoked on a module with no block, alias chain the\n# named methods to add synchronization. Or, if there are no arguments,\n# then alias chain the next method defined.\nelsif self.is_a? Module and not block_given?\nif (args.size > 0) # Synchronize the named methods\nargs.each {|m| self.synchronize_method(m) }\nelse\n# If no methods are specified synchronize the next method defined\neigenclass = class<<self; self; end\neigenclass.class_eval do # Use eigenclass to define class methods\n# Define method_added for notification when next method is defined\ndefine_method :method_added do |name|\n# First remove this hook method\neigenclass.class_eval { remove_method :method_added }\n# Next, synchronize the method that was just added\nself.synchronize_method name\nend\nend\nend\n# Case 4: any other invocation is an error\nelse\nraise ArgumentError, \"Invalid arguments to synchronize()\"\nend\nend", "def synchronize\n mutex.synchronize do\n yield\n end\n end", "def synchronize(block_timeout=nil)\n if lock(block_timeout)\n begin\n yield self\n ensure\n unlock\n end\n else\n raise MutexTimeout\n end\n end", "def to_lock\n raise AbstractFunction,\n \"#to_lock must be implemented on #{self.class.name}!\"\n end", "def to_lock\n raise AbstractFunction,\n \"#to_lock must be implemented on #{self.class.name}!\"\n end", "def lock\n @mutex.lock\n end", "def synchronization\n return @synchronization\n end", "def mutex(id, &block)\n is_expired = lambda do |locked_at|\n locked_at.to_f < Time.now.to_f\n end\n bid = batch(id)\n _key_ = \"#{bid}:lock\"\n\n until redis.setnx(_key_, Time.now.to_f + 0.5)\n next unless timestamp = redis.get(_key_)\n\n unless is_expired.call(timestamp)\n sleep(0.1)\n next\n end\n\n break unless timestamp = redis.getset(_key_, Time.now.to_f + 0.5)\n break if is_expired.call(timestamp)\n end\n yield(bid)\n ensure\n redis.del(_key_)\n end", "def bitlocker\n return @bitlocker\n end", "def lock\n @@lock ||= Monitor.new\n end", "def get_thread_by_context(username, job_key, application_id, context = 'Interviews')\n $LOG.i \"running \" + __method__.to_s\n @client.get '/mc/v1/contexts/' + username + '/' + context + ':' + job_key + ':' + application_id\n end", "def lock(&block)\n # TODO: only use replace strategy when server is executing the lock\n return call_strategy unless (locked_token = locksmith.lock(&block))\n\n locked_token\n end", "def get_session( env, sid )\n return _get_session( env, sid ) unless env['rack.multithread']\n mutex.synchronize do\n return _get_session( env, sid )\n end \n end", "def io_lock=(_arg0); end", "def synchronize\n lock(&block)\n end", "def sync\n @mutex.synchronize{yield}\n end", "def sync\n @mutex.synchronize{yield}\n end", "def sync\n @mutex.synchronize{yield}\n end", "def sync\n @mutex.synchronize{yield}\n end", "def server_mutex(&block)\n @server_mutex ||= begin\n require 'monitor'\n Monitor.new\n end\n @server_mutex.synchronize(&block)\n end", "def synchronized(*args)\n # Case 1: with one argument and a block, synchronize on the block\n # and execute the block.\n if args.size == 1 && block_given?\n args[0].mutex.synchronize { yield }\n\n # Case 2: with one agrument that is not a symbol and no block\n # return a SynchronizedObject wrapper.\n elsif args.size == 1 and not args[0].is_a? Symbol and not block_given?\n SynchronizedObject(args[0])\n\n # Case 3: when invoked on a module with no block, alias chain the \n # named method to add synchronization. Or, if there are no arguments,\n # then alias chain the next method defined.\n elsif self.is_a? Module and not block_given?\n if (args.size > 0) # Synchronized the named methods \n args.each {|m| self.synchronize_method(m) }\n else \n # If no methods are specified synchronize the next method defined\n eigenclass = class << self; self; end \n eigenclass.class_eval do # Use eigenclass to define class methods \n # Define method_add for notification when next class method is defined \n define_method :method_add do |name|\n # First remove this hook method \n eigenclass.class_eval { remove_method :method_add }\n # Next, synchronize the method that was just added \n self.synchronize_method name \n end \n end \n end \n\n # Case 4: any other invocation is an error \n else \n raise ArgumentError, \"Invalid arguments to synchronized()\"\n end \nend", "def with_lock(lock_name, options = {})\n build_mutex(lock_name, options).with_lock do\n yield\n end\n end", "def lock\n @mutex.synchronize do\n @locked = true\n end\n self\n end", "def method_context_class\n SingletonMethodContext\n end", "def remote_lock()\n return MicrosoftGraph::Users::Item::ManagedDevices::Item::RemoteLock::RemoteLockRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def with_lock(&block)\n if __locked?\n block.call\n else\n __with_thread_local_lock { attr_memoized_mutex.synchronize(&block) }\n end\n end", "def get_advisory_lock(lock_id) # :nodoc:\n end", "def get_advisory_lock(lock_id) # :nodoc:\n end", "def msg_MLOCK(source, args)\n return nil\n end", "def token\n Valkyrie::Persistence::OptimisticLockToken.new(adapter_id: resource_factory.adapter_id, token: version)\n end", "def initialize\n @mutex = Mutex.new\n @balance = 500\n end", "def lock(worker)\n NotImplementedError\n end", "def try_lock\n end", "def with_lock(name, opts={}, &b)\n mode = opts[:mode] || :exclusive\n\n raise ArgumentError, \":mode option must be either :shared or :exclusive, not #{mode.inspect}\" unless [:shared, :exclusive].include?(mode)\n\n if mode == :shared\n shared_locker(name).with_lock(&b)\n else\n locker(name).with_lock(&b)\n end\n end", "def register(mutex)\n locks.add(mutex)\n end", "def lock_token\n return nil if object[:lock_version].blank?\n @lock_token ||=\n Valkyrie::Persistence::OptimisticLockToken.new(\n adapter_id: resource_factory.adapter_id,\n token: object[:lock_version]\n )\n end", "def current_lock_value\n lock_column_name = self.class.locking_column\n has_attribute?(lock_column_name) && read_attribute(lock_column_name).to_i\n end", "def waitable_for_current_thread\n Waitable.new(self)\n end", "def cache_client\n @m ||= Mutex.new\n @m.synchronize do\n if instance_variable_defined?(:@cache_client)\n @cache_client\n else\n dir = Rails.root.join(CacheDirectory.find_by(name: 'efs_twitter_user')&.dir || 'tmp/efs_cache')\n FileUtils.mkdir_p(dir) unless File.exists?(dir)\n options = {expires_in: 1.month, race_condition_ttl: 5.minutes}\n @cache_client = ActiveSupport::Cache::FileStore.new(dir, options)\n end\n end\n end", "def locker(name)\n Locker.exclusive_locker(self, name)\n end", "def get_current_user(cached: true)\n return @user_cache.fetch(:@me) { super() } if cached\n\n me = super()\n @user_cache.cache(:@me, me)\n end", "def get_token_by_caller_reference(ref)\n submit GetTokenByCaller.new(:caller_reference => ref)\n end", "def lock\n self.is_locked = true\n self\n end", "def task_lock(task_name)\n @task_lock.synchronize do\n @task_locks[task_name] ||= Mutex.new\n end\n \n return if (@task_locks[task_name].locked?)\n \n @task_locks[task_name].synchronize do\n yield if (block_given?)\n end\n end", "def task_lock(task_name)\n @task_lock.synchronize do\n @task_locks[task_name] ||= Mutex.new\n end\n \n return if (@task_locks[task_name].locked?)\n \n @task_locks[task_name].synchronize do\n yield if (block_given?)\n end\n end", "def info\n @info ||= LockInfo.new(key.info)\n end", "def wait(mutex=nil,timeout = nil)\n\n if timeout.nil? && (mutex.nil? || Numeric === mutex)\n timeout = mutex\n mutex = nil\n end\n\n # Get the fiber that called us.\n strand = Thread.current\n # Add the fiber to the list of waiters.\n @waiters << strand\n begin\n sleeper = mutex ? mutex : Thread\n sleeper.sleep(timeout)\n ensure\n # Remove from list of waiters.\n @waiters.delete(strand)\n end\n self\n end", "def get_current_owner #:doc:\n self.send \"current_#{owner_class.name.underscore}\".to_sym\n end", "def lock!\n freeze!\n @locked = true\n self\n end", "def with_serial_lock\n CLIENT_MUTEX.synchronize { yield }\nend", "def get_contract_current()\n self.class.get(\"/api/contracts/current\", :basic_auth => @auth)\n end", "def synchronized?; end", "def get_current_hub\n # we need to assign a hub to the current thread if it doesn't have one yet\n #\n # ideally, we should do this proactively whenever a new thread is created\n # but it's impossible for the SDK to keep track every new thread\n # so we need to use this rather passive way to make sure the app doesn't crash\n Thread.current.thread_variable_get(THREAD_LOCAL) || clone_hub_to_current_thread\n end", "def get_request_token\n @consumer.get_request_token\n end", "def mint\n Mutex.new.synchronize do\n loop do\n pid = next_id\n return pid unless identifier_in_use?(pid)\n end\n end\n end", "def multithreaded\n get_value :multithreaded\n end", "def robots_mutex; end", "def with_lock(key)\n raise NotImplementedError\n end", "def synchronize\n lock\n yield\n ensure\n unlock\n end", "def synchronize_method(m)\n# First, make an alias for the unsynchronized version of the method.\naka = create_alias(m, \"unsync\")\n# Now redefine the original to invoke the alias in a synchronized block.\n# We want the defined method to be able to accept blocks, so we\n# can't use define_method, and must instead evaluate a string with\n# class_eval. Note that everything between %Q{ and the matching }\n# is a double-quoted string, not a block.\nclass_eval %Q{\ndef #{m}(*args, &block)\nsynchronized(self) { #{aka}(*args, &block) }\nend\n}\nend", "def wait(mutex=nil,timeout = nil)\n\n if timeout.nil? && (mutex.nil? || Numeric === mutex)\n timeout = mutex\n mutex = nil\n end\n\n # Get the fiber (Empathy::EM::Thread) that called us.\n thread = Thread.current\n # Add the fiber to the list of waiters.\n @waiters << thread\n begin\n sleeper = mutex ? mutex : Kernel\n if timeout then sleeper.sleep(timeout) else sleeper.sleep() end\n ensure\n # Remove from list of waiters. Note this doesn't run if the thread is killed\n @waiters.delete(thread)\n end\n self\n end", "def async_lock(environment)\n job = Job.new(:lock)\n async(:lock, job, environment)\n job.ticket\n end", "def synchronize\n @mutex.synchronize do\n yield\n end\n end", "def test_mutex\n Job.send(:mutex, @batch_id) do\n assert(true)\n end\n assert_equal(false, redis.exists(\"#{@batch}:lock\"))\n end" ]
[ "0.69130665", "0.6821464", "0.66776854", "0.55062217", "0.55062217", "0.55062217", "0.55062217", "0.5275682", "0.5149322", "0.51008916", "0.5064437", "0.5064437", "0.5058152", "0.49977008", "0.49760187", "0.49593088", "0.4954641", "0.49224377", "0.49222884", "0.49150985", "0.48849186", "0.48756355", "0.48240012", "0.48033392", "0.4761359", "0.4735189", "0.47294307", "0.47235322", "0.47126284", "0.47119793", "0.47119793", "0.47096914", "0.47048628", "0.46761182", "0.46596092", "0.46521708", "0.46433452", "0.4634056", "0.4608611", "0.4597062", "0.4597062", "0.45934585", "0.4587723", "0.45866257", "0.45798966", "0.45769143", "0.45538175", "0.45199338", "0.44695556", "0.44534793", "0.4448469", "0.44430184", "0.44430184", "0.44430184", "0.44430184", "0.44415727", "0.44328323", "0.44245136", "0.44148526", "0.44038406", "0.4398018", "0.43952245", "0.43896484", "0.43896484", "0.437815", "0.4370048", "0.43617028", "0.43553227", "0.4353051", "0.43459675", "0.43299118", "0.4313356", "0.4299249", "0.4297675", "0.42948088", "0.42835388", "0.42770326", "0.4272011", "0.42718616", "0.4269359", "0.42680606", "0.4262997", "0.4261229", "0.42546034", "0.42540702", "0.42493746", "0.4243508", "0.4237987", "0.4230475", "0.42272", "0.42218068", "0.42185023", "0.4212162", "0.4198899", "0.4195672", "0.41871554", "0.41838902", "0.4182816", "0.41769493", "0.41738996" ]
0.5997835
3
Preload additional api calls with a pool of threads.
def preload_data_with_threads(num_threads) return unless num_threads > 0 preload_methods = active_methods.concat(options[:additional_data].keys) log :info, "Preloading (#{preload_methods.size}) data requests using (#{num_threads}) threads." work_q = Queue.new preload_methods.each{|x| work_q.push x } workers = num_threads.to_i.times.map do Thread.new do begin while x = work_q.pop(true) log :debug, "Preloading #{x}." send x end rescue ThreadError end end end workers.map(&:join); "ok" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_apis_asynchronously \n threads = []\n threads << Thread.new { @resp1 = RestClient.get 'https://reqres.in/api/unknown' }\n threads << Thread.new { @resp2 = RestClient.get 'https://reqres.in/api/products' }\n threads.each { |thr| thr.join } \n end", "def concurrent_pgd_requests\n Thread.abort_on_exception = true\n\n # rubocop:disable ThreadSafety/NewThread\n request_threads << Thread.new { @patient = get_patient.resource }\n request_threads << Thread.new { @organizations = get_organizations }\n request_threads << Thread.new { @questionnaires = get_questionnaires.resource&.entry }\n request_threads << Thread.new { @questionnaire_responses = get_questionnaire_responses.resource&.entry }\n request_threads << Thread.new { @save_in_progress = get_save_in_progress }\n # rubocop:enable ThreadSafety/NewThread\n\n request_threads.each(&:join)\n end", "def prefetch(reqs)\n end", "def loadAll()\n # Load the configuration from global.rb\n SHAREDPOOLS.each_key do |k|\n p = Pool.new(k, SHAREDPOOLS[k][:zone],\n SHAREDPOOLS[k][:allocateable_cpus],\n SHAREDPOOLS[k][:allocateable_mem],\n SHAREDPOOLS[k][:service_class])\n\n @poolList.push(p)\n end\n SERVICES.each_key do |k|\n s = Service.new(k, SERVICES[k][:authinfo],\n SERVICES[k][:maxcpus],\n SERVICES[k][:maxmemory],\n SERVICES[k][:priority])\n @svcList.push(s)\n end\n # Load the requests from redis\n @reqList = $eventProcessor.loadRequests()\n # Compute the free/used stats from state of requests\n @reqList.each { |req|\n if req.status == \"ALLOCATED\"\n pmatches = @poolList.select {|p| p.name == req.pool}\n if pmatches == nil || pmatches[0] == nil\n $Logger.error \"Unable to find pool #{req.pool} for ALLOCATED request #{req.reqid}\"\n next\n end\n smatches = @svcList.select {|s| s.name == req.service}\n if smatches == nil || smatches[0] == nil\n $Logger.error \"Unable to find service #{req.service} for ALLOCATED request #{req.reqid}\"\n next\n end\n pool = pmatches[0]\n pool.availvcpus = pool.availvcpus.to_i - req.vcpus.to_i\n pool.availmem = pool.availmem.to_i - req.mem.to_i\n service = smatches[0]\n service.vcpusallocated = service.vcpusallocated.to_i + req.vcpus.to_i\n service.memallocated = service.memallocated.to_i + req.mem.to_i\n end\n }\n end", "def initialize(num_threads)\n @thread_pool = Concurrent::FixedThreadPool.new(num_threads)\n @promises = []\n end", "def collect2 pages\n id = 'joshuabaer'\n results = []\n tasks = []\n 1.upto pages do |page|\n puts \"queueing page #{page}\"\n task = BackgroundTask.new do \n http_get id, page\n end\n tasks << task\n task.run\n end\n tasks.each do |task|\n puts \"task retrieved\"\n results += task.result\n end\n results\nend", "def exec_concurrent_requests(request, count = 20)\n futures = Array.new(count) { Celluloid::Future.new {\n request.call\n }\n }\n futures.each { |f| f.value }\n end", "def prefetch(reqs)\n @sets.each {|s| s.prefetch(reqs) }\n end", "def update_polling_pool(key, thread); end", "def fetch\n requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten\n\n total, done = requests.size, 0\n update_progress(total, done)\n\n before_fetch\n\n backend.new(requests).run do\n update_progress(total, done += 1)\n end\n\n after_fetch\n\n true\n rescue => e\n error(e)\n raise e\n end", "def before_eager_load(&block); end", "def fetch_hooks_to_be_processed\n acquire_lock\n fetch_locked_hooks\n end", "def lazy_preload(*args)\n check_if_method_has_arguments!(:lazy_preload, args)\n spawn.lazy_preload!(*args)\n end", "def poller_threads\n @pollers.synchronize { @pollers.size }\n end", "def loop_threads_and_fetch_url(url_list)\n if @@url_hash.size < @@max_url\n unless url_list.empty?\n if running_thread_count() >= 5\n sleep @@sleep_timer*60\n loop_threads_and_fetch_url(url_list)\n else\n url_list = url_list.map { |url| url if get_host_without_www(url) == 'medium.com' }.compact\n save_data(url_list)\n new_urls_to_scrap = update_url_hash(url_list).compact\n @@retry_counter = 0 #setting the value for every new request\n generate_thread(new_urls_to_scrap)\n end\n end\n end\n end", "def start_api_services()\n # ejabberd uses uaserver for authentication\n # so start it after we find out the uaserver's ip\n threads = []\n if my_node.is_login?\n threads << Thread.new {\n start_ejabberd()\n }\n end\n\n @done_initializing = true\n\n # start zookeeper\n threads << Thread.new {\n if my_node.is_zookeeper?\n configure_zookeeper(@nodes, @my_index)\n start_zookeeper\n end\n\n ZKInterface.init(my_node, @nodes)\n }\n\n if my_node.is_memcache?\n threads << Thread.new {\n start_memcache()\n }\n end\n\n if my_node.is_db_master?\n threads << Thread.new {\n start_db_master()\n # create initial tables\n if my_node.is_db_master?\n prime_database\n end\n\n # Always colocate the Datastore Server and UserAppServer (soap_server).\n if has_soap_server?(my_node)\n @state = \"Starting up SOAP Server and Datastore Server\"\n start_datastore_server()\n start_soap_server()\n HelperFunctions.sleep_until_port_is_open(HelperFunctions.local_ip, UserAppClient::SERVER_PORT)\n end\n\n # If we're starting AppScale with data from a previous deployment, we\n # may have to clear out all the registered app instances from the\n # UserAppServer (since nobody is currently hosting any apps).\n if not @creds['clear_datastore']\n erase_app_instance_info\n end\n }\n end\n\n if my_node.is_db_slave?\n threads << Thread.new {\n start_db_slave()\n\n # Currently we always run the Datastore Server and SOAP\n # server on the same nodes.\n if has_soap_server?(my_node)\n @state = \"Starting up SOAP Server and Datastore Server\"\n start_datastore_server()\n start_soap_server()\n HelperFunctions.sleep_until_port_is_open(HelperFunctions.local_ip,\n UserAppClient::SERVER_PORT)\n end\n }\n end\n\n # All nodes have application managers\n threads << Thread.new {\n start_app_manager_server()\n }\n\n if my_node.is_appengine?\n threads << Thread.new {\n start_blobstore_server()\n }\n end\n\n if my_node.is_taskqueue_master?\n threads << Thread.new {\n start_taskqueue_master()\n }\n elsif my_node.is_taskqueue_slave?\n threads << Thread.new {\n start_taskqueue_slave()\n }\n end\n\n # App Engine apps rely on the above services to be started, so\n # join all our threads here\n Djinn.log_info(\"Waiting for all services to finish starting up\")\n threads.each { |t| t.join() }\n Djinn.log_info(\"API services have started on this node\")\n\n end", "def prepare!\n prepare_in_parallel!\n end", "def collect3 pages\n id = 'barackobama'\n results = []\n tasks = TaskCollection.new( 50 )\n 1.upto pages do |page|\n puts \"queueing page #{page}\"\n task = BackgroundTask.new do \n http_get id, page\n end\n tasks << task\n end\n i=0\n loop do\n i+=1\n puts \"getting next task...\"\n task = tasks.next_finished\n if !task\n puts \"no more tasks\"\n break\n else\n puts \"task retrieved #{i}\"\n results += task.result\n end\n end\n results\nend", "def resume_all; threads.each {|x| resume(x)}; end", "def worker_pool; end", "def worker_pool; end", "def slow_down_api_request\n sleep 1.0\n end", "def fetch_objects(lookup = :parallel)\n items = valid_parse_objects\n lookup == :parallel ? items.threaded_each(2, &:fetch) : items.each(&:fetch)\n #self.replace items\n self\n end", "def initialize_threadpool\n EM.threadpool_size = @poolsize\n end", "def execute_bulk_requests\n begin\n @responses = Hash.new\n @headers = Hash.new\n @all_urls = Hash.new\n data = ActiveSupport::JSON.decode(params[:data])\n @detailed_results = data[\"detailed_results\"]\n num_threads = data[\"threads\"].to_i\n data[\"lines_to_send\"].threadify(num_threads) { |line|\n path = data[\"path\"].gsub(/XXXCHANGEMEXXX/, line)\n headers = data[\"headers\"].gsub(/XXXCHANGEMEXXX/, line)\n body = data[\"body\"].gsub(/XXXCHANGEMEXXX/, line)\n data.each do |key, value|\n if key.start_with?(\"replace_\") && !key.end_with?(\"_by\")\n path.gsub!(\"XXX#{value}XXX\",data[key + \"_by\"]) if data[key + \"_by\"] != \"\"\n headers.gsub!(\"XXX#{value}XXX\",data[key + \"_by\"]) if data[key + \"_by\"] != \"\"\n body.gsub!(\"XXX#{value}XXX\",data[key + \"_by\"]) if data[key + \"_by\"] != \"\"\n end\n end\n if @cloud\n if @cloud.api == \"Atmos\"\n @responses[line], @headers[line], @all_urls[line] = atmos_request(data[\"http_method\"], path, headers, body)\n elsif @cloud.api == \"Amazon\"\n @responses[line], @headers[line], @all_urls[line] = amazon_request(data[\"http_method\"], path, headers, body)\n elsif @cloud.api == \"Swift\"\n @responses[line], @headers[line], @all_urls[line] = swift_request(data[\"http_method\"], path, headers, body)\n end\n else\n url = path\n uri = URI.parse(url)\n headers_to_send = Hash.new\n headers.split(\"\\n\").each do |row|\n hash = eval(row)\n headers_to_send[hash.keys.first.downcase] = hash.values.first.to_s\n end\n @responses[line] = http_request(url, uri.port, data[\"http_method\"], headers_to_send, body)\n @headers[line] = headers_to_send\n end\n }\n rescue Exception => e\n @exception = e\n end\n respond_to do |format|\n format.js { render 'shared/execute_bulk_requests' }\n end\n end", "def prefetch(reqs)\n return unless @remote\n names = reqs.map {|r| r.dependency.name }\n needed = names - @data.keys - @to_fetch\n\n @to_fetch += needed\n end", "def fork_worker(after_requests = T.unsafe(nil)); end", "def load_all\n thread_local_store.load_all\n self\n end", "def fetch(params)\n Resque.logger.info \"Requestable.fetch received #{params.inspect}\"\n past = Time.now\n total = api_count(params)\n remain_requests = (total/250.to_f).ceil\n Resque.logger.info \"pages to request total: #{remain_requests}\"\n batch_num = (remain_requests / BATCH_SIZE.to_f).ceil\n Resque.logger.info \"batch number: #{batch_num}\"\n chap_start = 1\n chap_end = 0\n entity = params.fetch(:entity)\n Resque.logger.info \"entity name: #{entity}\"\n cache = $redis\n pages = []\n batch_num.times do\n entity_url = entity.pluralize\n if remain_requests > BATCH_SIZE\n chap_end += BATCH_SIZE\n remain_requests -= BATCH_SIZE\n else\n chap_end += remain_requests\n end\n hydra = Typhoeus::Hydra.new(max_concurrency: 30)\n\n chap_start.upto(chap_end) do |page|\n pages << page\n # queue up current batch\n request = Typhoeus::Request.new(\n \"https://api.rechargeapps.com/#{entity_url}?#{params[:query]}&limit=250&page=#{page}\",\n # followlocation: true,\n headers: HEADER\n )\n # error logging callbacks\n request.on_complete do |res|\n @used = res.headers['x-recharge-limit'].to_i\n if res.success?\n puts \"#{entity.upcase} request queued\"\n elsif res.timed_out?\n Resque.logger.error \"(HYDRA request) TIMED OUT: #{res.response_headers}\"\n elsif res.code.zero?\n Resque.logger.error \"(HYDRA request) Couldnt get an http response #{res.return_message}\"\n else\n Resque.logger.error(\"(HYDRA request) HTTP request failed: #{res.code}\")\n end\n end\n\n request.on_success do |res|\n # @used = res.headers['x-recharge-limit'].to_i\n # Resque.logger.info res.headers['x-recharge-limit']\n key = \"#{entity}_pull:#{Time.now.strftime(\"%Y%m%d\")}#{page.to_s.rjust(3, '0')}\"\n hash_set(cache, key, res.response_body)\n end\n\n hydra.queue(request)\n chap_start = chap_end\n end\n hydra.run\n batch_throttle(@used)\n end\n Resque.logger.info \"Pages iterated: #{pages.inspect}\"\n Resque.logger.info(\"RUN TIME per #{total} records: #{(Time.now - past)}\")\n end", "def prefetch gems\n end", "def run\n @cluster.retriable(api_name) do\n process(retriable_requests)\n\n # Stop retrying when there are no more requests to retry\n retriable_requests.empty?\n end\n\n responses\n end", "def test_proxies_concurrent_requests_properly\n hydra = Typhoeus::Hydra.new\n requests = Array.new(20) do |index|\n request = Typhoeus::Request.new(\"http://127.0.0.1:9080/api/echo_delayed_chunked\", http_options.deep_merge({\n :params => {\n :input => \"#{unique_test_id}-#{index}-#{SecureRandom.hex(40)}\",\n },\n }))\n hydra.queue(request)\n request\n end\n hydra.run\n\n assert_equal(20, requests.length)\n requests.each do |request|\n assert_response_code(200, request.response)\n assert(request.original_options[:params][:input])\n assert_equal(request.original_options[:params][:input], request.response.body)\n end\n end", "def make_calls\n cnt = 0\n while cnt < COMPONENTS.hammer[:common][:cycle_length] do\n if COMPONENTS.hammer[:common][:thread_cycles] == true\n Thread.new do\n execute_strategies\n end\n else\n execute_strategies\n end\n cnt += 1\n end\n end", "def setup\n return unless connection_pool_enabled?\n\n @connection_pool = ::Queue.new\n\n start_pool_size.times { @connection_pool.push(new_client) }\n\n @created_connections = start_pool_size\n end", "def pull_data\n @pull_data ||= source_classes\n .map { |source| Thread.future { source.run(pull, page) } }\n .reduce({}) { |result, source_future| result.merge(~source_future) }\n end", "def spawn_threads!\n @threads = []\n num_worker_threads.times do |thread_num|\n log(:debug) { \"Spawning background worker thread #{thread_num}.\" }\n\n @threads << Thread.new do\n Thread.current[:influxdb] = object_id\n\n until @should_stop\n check_background_queue(thread_num)\n sleep rand(sleep_interval)\n end\n\n log(:debug) { \"Exit background worker thread #{thread_num}.\" }\n end\n end\n end", "def park(go_fiber)\n pool.prepared_thread << go_fiber\n end", "def collect4 pages\n id = 'barackobama'\n results = []\n tp = ThreadPool.new( 10 )\n tasks = TaskCollection.new( 10, tp )\n i=0\n 1.upto pages do |page|\n puts \"queueing page #{page}\"\n tasks.add_task do\n http_get id, page\n end\n if tasks.task_ready?\n i+=1\n puts \"GOT A TASK FINISHED WHILE STILL ADDING TASKS\"\n results += tasks.next_finished.result\n end\n end\n puts \"getting next task...\"\n while task = tasks.next_finished\n i+=1\n puts \"task retrieved #{i}\"\n results += task.result\n puts \"getting next task...\"\n end\n results\nend", "def engage\n threads = []\n #threads << LisaToolbox.run_in_new_thread(:engage_by_elite_tweets) {engage_by_elite_tweets}\n threads << LisaToolbox.run_in_new_thread(:engage_by_search) {engage_by_search}\n #threads << LisaToolbox.run_in_new_thread(:engage_by_realtime) {engage_by_realtime}\n threads.each { |thread| thread.join }\nend", "def parallelize!\n synchronize do\n be_unprepared!\n @parallel = true\n end\n end", "def client_prefetch\n logger.info \"Populating client cache\"\n kube_client.apis(prefetch_resources: true)\n rescue Excon::Error::Certificate\n logger.warn \"Certificate validation failed\"\n end", "def preload_test_ids\n result = run_in_fork do\n paths = []\n config.file_sets[\"all\"].each do |glob|\n paths.concat(Dir.glob(glob))\n end\n\n paths.each { |path| require File.expand_path(path) }\n\n require File.join(File.dirname(__FILE__), \"minitest_handler\")\n MiniTestHandler.preload_elements\n end\n\n config.cache_test_ids(result) unless result.nil?\n end", "def engage\n threads = []\n threads << LisaToolbox.run_in_new_thread(:engage_by_elite_tweets) {engage_by_elite_tweets}\n threads << LisaToolbox.run_in_new_thread(:engage_by_search) {engage_by_search}\n threads << LisaToolbox.run_in_new_thread(:engage_by_realtime) {engage_by_realtime}\n threads.each { |thread| thread.join }\nend", "def engage\n threads = []\n threads << LisaToolbox.run_in_new_thread(:engage_by_elite_tweets) {engage_by_elite_tweets}\n threads << LisaToolbox.run_in_new_thread(:engage_by_search) {engage_by_search}\n threads << LisaToolbox.run_in_new_thread(:engage_by_realtime) {engage_by_realtime}\n threads.each { |thread| thread.join }\nend", "def defer\n if pool_size < 0 # negative number for blocking call\n self.thread = Thread.current # set working thread\n protected_yield{ yield } # avoid any exception and do the job\n else\n backtrace = caller + self.class.backtrace # retain the backtrace so far\n if pool_size > 0\n mutex.synchronize do\n # still timing it out if the task never processed\n env[TIMER].on_timeout{ cancel_task } if env[TIMER]\n self.task = client_class.thread_pool.defer(mutex) do\n Thread.current[:backtrace] = backtrace\n protected_yield{ yield }\n Thread.current[:backtrace] = nil\n end\n end\n else\n self.thread = Thread.new do\n Thread.current[:backtrace] = backtrace\n protected_yield{ yield }\n end\n end\n end\n end", "def initialize client, service, batch_threads\n @client = client\n @service = service\n @rate_limiter = RateLimiter.new\n @buffered_operations = []\n @batch_threads = (batch_threads || BATCH_THREAD_COUNT).to_i\n @batch_thread_pool = Concurrent::ThreadPoolExecutor.new max_threads: @batch_threads,\n max_queue: 0,\n auto_terminate: true\n @retry_operations = []\n @mutex = Mutex.new\n start_scheduling_operations\n end", "def allow_concurrency; end", "def allow_concurrency; end", "def load_all!\n Log.info \"Loading #{self} list\"\n old_objs = @objs_list || {}\n @objs_list = {}\n each_api_item do |api_hsh|\n params = api_hsh_to_params(api_hsh)\n if obj = old_objs[params[:id]] then obj.update! params\n else obj = self.new(params) end\n register obj\n end\n Log.info \"Loaded list of #{@objs_list.length} #{self}s\"\n @objs_list\n end", "def poll_api(api)\n # blocks the creation of additional threads. Only one live tracker thread may exist at a time,\n # so that the external API is only requested once per minute\n return false if live_thread?\n\n # create an interface, so that we don't communicate with the processing of data directly. Tracker,\n # is only concerned with retrieving information and passing it on.\n interface = INTERFACE.new(api.key)\n\n # start a thread and add it to singleton collection\n threads << Thread.new{\n key = api.key\n klass = api.class\n live = true\n\n # looping once per minute for the API and passing it onto the interface.\n while live do\n # this isn't really required here, but just to protect against the main thread and tracker thread\n # from accessing the database resources simultaneously.\n SEMAPHORE.synchronize {\n interface.track_resource\n live = active_tracking?(klass, key)\n }\n # sleep for N seconds - would some sort of smart scheduling be better or overkill? hmmm...\n sleep(CYCLE_TIME)\n end\n }\n # what to do in case of emergency. . .\n rescue Exception => e\n # api = api.class.where(key: api.key).first\n # deactivate live update of the resource\n api.live_update = false\n api.save\n end", "def initialize\n @threads = []\n end", "def preload!\n end", "def test_concurrent_requests\n app do\n get '/sleep/:i' do\n t = params[:i].to_i * FACTOR\n sleep t\n \"Slept #{t}\"\n end\n end\n \n time = Benchmark.realtime do\n (1..REQUESTS).map do |i|\n Thread.new(i) do |i|\n get \"/sleep/#{i}\"\n \n assert_equal(200, response.status)\n assert_equal(\"Slept #{i * FACTOR}\", response.body)\n end\n end.each(&:join)\n end\n \n assert_in_delta REQUESTS * FACTOR, time, 0.05 # 0.05 is a empirically found ‘overhead’ time\n end", "def full_preload(docs, inclusions, polymorphic_inclusions, nested_inclusions)\n preload(inclusions, docs)\n\n polymorphic_inclusions.each do |metadata|\n preload_polymorphic(metadata, docs)\n end\n\n preload_nested(nested_inclusions, docs)\n end", "def threads\n raise CapabilitiesExceeded\n end", "def preload; end", "def preload; end", "def setup_jobs\n JobLoader.call\n end", "def in_parallel?; end", "def give_others_threads_a_chance_to_run\n sleep(1/(200*1e3))\n end", "def work_pool; end", "def build_threads\n @queue_threads.times { @threads << Queue.new }\n @retry_threads.times { @threads << Retry.new }\n end", "def load\n data = []\n page = 1\n total_size = 0\n\n loop do\n request_url = \"#{@request_url_base}&page=#{page}&api_key=#{@api_key}\"\n response = Faraday.get(request_url)\n\n response_json = JSON.parse(response.body)\n\n break if response_json.empty?\n\n response_json.each do |item|\n data << item\n end\n\n unless @limit.nil?\n total_size += response_json.length\n\n break if total_size > @limit\n end\n\n page += 1\n end\n\n data = data.first(@limit) unless @limit.nil?\n\n data\n end", "def start\n #Parallel.each_with_index(files.take(3), in_processes: 10) do |file_name, index|\n files.each_with_index do |file_name, index|\n begin\n content = JSON.parse(File.read(file_name), symbolize_names: true)\n pr_number_to_be_migrated = content[:number]\n response_temp_file_creation = create_temp_file(file_name, pr_number_to_be_migrated)\n create_ref_to_temp_file(pr_number_to_be_migrated, response_temp_file_creation[:commit][:sha])\n response_pull_request_creation = create_pull_request(pr_number_to_be_migrated)\n update_pull_request(response_pull_request_creation[:number], content)\n delete_ref_to_temp_file(pr_number_to_be_migrated)\n puts '*'\n rescue Exception => e\n puts \"Error: #{e.message}\"\n end\n end\n end", "def zone_load_multi\n send_req(a: :zone_load_multi)\n end", "def fetch\n @github.fetch\n @stackoverflow.fetch\n @acuk.fetch\n @jobs = data.shuffle\n end", "def eager_load!; end", "def eager_load!; end", "def eager_load!; end", "def eager_load!; end", "def preload\n entries\n collections.each &:preload\n nil\n end", "def start\n raise \"Already started.\" if @pool and !@pool.empty?\n \n @pool = Array.new(@args[:threads]) do |i|\n Thread.new do\n begin\n Thread.current[:tpool] = {:i => i}\n \n loop do\n block = @queue.pop\n Thread.current[:tpool][:block] = block\n \n block.run\n Thread.current[:tpool].delete(:block)\n end\n rescue Exception => e\n $stderr.puts e.inspect\n $stderr.puts e.backtrace\n end\n end\n end\n end", "def start threads_count = 10\n\n SuperCrawler::Render.crawling_start_notice( @start_url, threads_count ) if @option_debug # Show message on what will happen\n\n threads = [] # Will contain our n-threads\n @links_queue = Queue.new # Will contain the links queue that the threads will use\n @links = [@start_url] # Re-init the links list\n @crawl_results = [] # Re-init the crawling results\n\n start_time = Time.now if @option_debug # Start the timer\n\n # Let's populate our queue with links and resources from source url\n process_page( @start_url )\n\n # Create threads to handle new links\n threads_count.times do # Create threads_count threads\n\n threads << Thread.new do # Instantiate a new threads\n begin\n while current_link = @links_queue.pop(true) # Pop one link after another\n process_page( current_link ) # Get links and assets of the popped link\n end\n rescue ThreadError # Stop when empty links queue\n end\n end\n\n end\n\n threads.map(&:join) # Activate the threads\n SuperCrawler::Render.crawling_summary_notice(Time.now - start_time, threads_count, @links.count) if @option_debug # Display crawling summary\n\n return true\n end", "def pool\n unless @pool\n self.pool_size ||=2\n threads = [self.pool_size, 2, Concurrent.processor_count].max\n @pool = Concurrent::ThreadPoolExecutor.new(\n min_threads: 2,\n max_threads: threads,\n max_queue: 10*threads,\n fallback_policy: :caller_runs\n )\n end\n @pool\n end", "def import_all_tab_files_parallel(tabs_list, dataset_id, task_id, root_url)\n max_parallelism = 10\n running_parallelism = 0\n wait_seconds = 10\n\n tabs_list.each { |tab_object|\n tab_file = tab_object[\"MzTab_file\"]\n\n running_parallelism += 1\n\n fork do\n #import_dataset_tab_psm_file(dataset_id, task_id, tab_file, root_url)\n import_tab_cmd = \"ruby ./populate_parallel_tab.rb \"\n import_tab_cmd += dataset_id + \" \"\n import_tab_cmd += task_id + \" \"\n import_tab_cmd += tab_file + \" \"\n import_tab_cmd += root_url\n\n puts import_tab_cmd\n `#{import_tab_cmd}`\n\n abort\n end\n\n sleep(wait_seconds)\n if running_parallelism == max_parallelism\n Process.waitall\n running_parallelism = 0\n end\n }\n\n Process.waitall\nend", "def preload=(_); end", "def preload=(_); end", "def snapshot_every_n_requests; end", "def eager_load_all\n Registry.loaders.each(&:eager_load)\n end", "def enable_call_threading\n @actor.enable_call_threading\n nil\n end", "def initialize( api_key )\n @api_key = api_key\n @cached_requests = {}\n end", "def test_concurrent_requests_to_same_url_different_http_method\n delay = $config[\"nginx\"][\"proxy_read_timeout\"] - 1\n assert_operator(delay, :>, 0)\n\n start_time = Time.now.utc\n\n get_thread = Thread.new do\n Thread.current[:response] = Typhoeus.get(\"http://127.0.0.1:9080/api/delay-sec/#{delay}\", http_options)\n end\n\n # Wait 1 second to ensure the first GET request is fully established to the\n # backend.\n sleep 1\n\n post_thread = Thread.new do\n Thread.current[:response] = Typhoeus.post(\"http://127.0.0.1:9080/api/delay-sec/#{delay}\", http_options)\n end\n\n get_thread.join\n post_thread.join\n total_time = Time.now.utc - start_time\n\n assert_response_code(200, get_thread[:response])\n assert_response_code(200, post_thread[:response])\n\n # Sanity check to ensure the 2 requests were made in parallel and\n # overlapped.\n assert_operator(get_thread[:response].total_time, :>=, delay - BUFFER_TIME_LOWER)\n assert_operator(get_thread[:response].total_time, :<, delay + BUFFER_TIME_UPPER)\n assert_operator(post_thread[:response].total_time, :>=, delay - BUFFER_TIME_LOWER)\n assert_operator(post_thread[:response].total_time, :<, delay + BUFFER_TIME_UPPER)\n assert_operator(total_time, :>=, delay + 1 - BUFFER_TIME_LOWER)\n assert_operator(total_time, :<, delay + (BUFFER_TIME_UPPER * 2))\n assert_operator(total_time, :<, (delay * 2) - 1)\n end", "def preconnect(concurrent = nil)\n hold{}\n end", "def setup\n logger.info 'setup workers'\n\n setup_refresh_timer\n setup_analyze_timer\n end", "def import!\n # start_async provided by Asyncable module\n return start_async if run_async?\n process_now\n end", "def eager_load; end", "def eager_load; end", "def eager_load; end", "def eager_load=(_arg0); end", "def eager_load=(_arg0); end", "def eager_load=(_arg0); end", "def perform_request\n returned = nil\n @requests ||= 0\n @requests += 1\n @request_time ||= 0\n @request_time += Benchmark.realtime { returned = yield }\n returned\n ensure\n @handlers.each { |handler| handler.call(@requests, @request_time) }\n end", "def preload_json\n # We don't preload JSON on xhr or JSON request\n return if request.xhr? || request.format.json?\n\n # if we are posting in makes no sense to preload\n return if request.method != 'GET'\n\n preload_anonymous_data\n\n preload_current_user_data if current_user\n end", "def before_starting_workers\n end", "def start_threads\n \n # generate computers cache model shortcuts\n Main.active.clusters.each do |computers|\n computers.each { |c| Main.active.computers_cache[c.id]=c }\n end\n\n # load user names from yppassed\n # TODO: move to user model class?\n #IO.popen(\"ypcat passwd\").each { |line|\n # Main.active.user_list.add(line.split(\":\").values_at(0, 4)) \n #}\n\n refresh = Thread.new {\n session[:old_timestamp] = 0\n\n while true\n puts \"refresh start\"\n # update prectab data\n if Prectab.changed?\n Main.active.computers_cache.each_value {|computer| computer.prectab = [nil,nil]; computer.color_changed; computer.user_changed }\n Debug.log.debug \"working prectab\"\n scatter_prectab(Prectab.now,0)\n scatter_prectab(Prectab.soon,1)\n end\n\n # update computers_cache\n comps = Computer.updated_after session[:old_timestamp]\n comps.each do |computer| \n cache_computer = Main.active.computers_cache[computer.id]\n if cache_computer\n cache_computer.User = computer.user \n cache_computer.Color = computer.color\n end\n end\n session[:old_timestamp] = Time.now.strftime(\"%j%H%M%S\")\n\n # update printers\n @printers.each { |p| p.update_job_count; p.update_accepts; p.update_snmp }\n puts \"refresh end\"\n sleep 20\n end \n }\n \n # read data from scanner and dispatch\n require 'socket'\n begin\n socket = TCPSocket.new('localhost', 7887)\n rescue Errno::ECONNREFUSED\n Main.active.status = [\"Scanner\", t('scanner.no_connection'), \"important\",-1]\n else\n scanner = Thread.new {\n Debug.log.debug \"starting scanner thread ...\"\n while true\n scan = socket.recvfrom(25)\n type, Main.active.scan_string = check_scanner_string(scan[0])\n Debug.log.debug \"Scanner says #{scan} #{type}, #{Main.active.scan_string}\"\n \n case type\n when :card\n accounts = User.find_accounts_by_barcode(Main.active.scan_string)\n fill_accounts(accounts)\n when :matrikel\n accounts = Account.find_accounts_by_barcode(Main.active.scan_string)\n fill_accounts(accounts)\n when :key\n pc = Main.active.computers_cache[Main.active.scan_string]\n puts pc\n unless Main.active.account_list.empty?\n table_register(pc)\n else\n case pc.user\n when \"\"\n Main.active.status = [\"#{pc.id}\", \"ist schon frei\", \"key\",0] \n else\n Main.active.status = [\"#{pc.user}\", \"von <b>#{pc.id}</b> abgemeldet\", \"trashcan_full\",1]\n end\n key_clear(pc)\n end\n else\n Debug.log.debug \"#{type}, #{Main.active.scan_string}\"\n end\n \n sleep 1 # wait some time for next scan atempt\n end\n }\n end\n end", "def before_queue(urls)\n # stub\n end", "def before\n poller.before_request { |stats| yield(stats) }\n end", "def generate_thread(source_url)\n begin\n source_url.each_slice(@@thread_size) do |batch|\n threads = []\n batch.each do |u|\n threads << Thread.new { get_all_links(u) }\n end\n threads.each { |thr| thr.join }\n end\n Thread.list.each do |thread|\n thread.exit unless thread == Thread.current\n end\n rescue Exception => e\n puts \"Exception occurred In Thread #{e.message}\"\n unless @@retry_counter != 0\n puts \"Retrying .....\"\n @@retry_counter = 1\n retry\n end\n end\n end", "def pool; end", "def pool; end" ]
[ "0.6453118", "0.6229834", "0.6211408", "0.5797853", "0.5561706", "0.5507962", "0.55022454", "0.54906505", "0.5468577", "0.54551", "0.54029375", "0.53926635", "0.53891283", "0.53809327", "0.5373321", "0.53664947", "0.5329434", "0.5303737", "0.53003293", "0.5297891", "0.5297891", "0.5267097", "0.52618384", "0.5258209", "0.52557695", "0.5254651", "0.524705", "0.5224185", "0.52079624", "0.5204202", "0.5196227", "0.519095", "0.518859", "0.51725763", "0.5172272", "0.5153357", "0.5151835", "0.51517916", "0.51480085", "0.514738", "0.5139049", "0.51374036", "0.51299727", "0.51299727", "0.51229113", "0.51141876", "0.5107869", "0.5107869", "0.5106358", "0.50929046", "0.5092834", "0.50755143", "0.5058179", "0.5024713", "0.5024707", "0.5020865", "0.5020865", "0.5019039", "0.5016397", "0.5008311", "0.4998336", "0.49695557", "0.49674425", "0.4963998", "0.49570474", "0.49559644", "0.49421644", "0.49421644", "0.49421644", "0.49421644", "0.49298403", "0.49293134", "0.4923093", "0.49226528", "0.49162543", "0.49044505", "0.49044505", "0.49018413", "0.4901394", "0.48815793", "0.48810455", "0.48807496", "0.48726398", "0.48618725", "0.4859606", "0.48576298", "0.48576298", "0.48576298", "0.4855278", "0.4855278", "0.4855278", "0.48537764", "0.48524916", "0.48497844", "0.48493457", "0.48471192", "0.48420355", "0.48415494", "0.48405766", "0.48405766" ]
0.72898734
0
Define methods for addional data from :additional_data option
def define_additional_data hash = options[:additional_data] if !hash.to_h.empty? hash.each do |k,v| define_singleton_method(k) do instance_variable_get(:"@#{k}") || instance_variable_set(:"@#{k}", v.respond_to?(:call) ? v.call(env) : v) end end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_extended_data(type, data); end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data\n return @additional_data\n end", "def additional_data\n return @additional_data\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end", "def additional_data=(value)\n @additional_data = value\n end" ]
[ "0.7356935", "0.72789276", "0.72592163", "0.7225805", "0.7225805", "0.7225805", "0.7225805", "0.7225805", "0.7225805", "0.7225805", "0.7225805", "0.7172823", "0.7172823", "0.71564835", "0.71564835", "0.7143333", "0.7143333", "0.7143333", "0.7129505", "0.7129505", "0.7129505", "0.7129505", "0.71154875", "0.70327085", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593", "0.69911593" ]
0.7723744
0
Parsed data returned from /slack/oauth.v2.access api call.
def auth @auth ||= access_token.params.to_h.merge({'token' => access_token.token}) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def auth_test(access_token:)\n response = HTTParty.post(\"https://slack.com/api/auth.test\", headers: { 'Authorization': \"Bearer #{access_token}\" })\n JSON.parse(response.body, symbolize_names: true)\n end", "def get_acc_info\n JSON.parse(curl_get(\"/api2/account/info/\").body_str)\n end", "def user_info(access_token:, user_id:)\n query = {\n user: user_id\n }.compact\n response = HTTParty.get(\"https://slack.com/api/users.info\",\n query: query,\n headers: { 'Authorization': \"Bearer #{access_token}\" })\n JSON.parse(response.body, symbolize_names: true)\n end", "def raw_info\n @raw_info ||= begin\n access_token.options[:mode] = :query\n access_token.options[:param_name] = 'oauth_token'\n access_token.get('oauth/api/profile').parsed\n end\n end", "def oauth_data(code:)\n res = uphold_conn.post do |req|\n req.url UPHOLD_AUTHENTICATION_PATH\n req.headers['Authorization'] = ActionController::HttpAuthentication::Basic.encode_credentials(client_id, client_secret)\n req.respond_to? :json, content_type: /\\b(?i:json)$/\n req.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n req.body = URI.encode_www_form({code: code, grant_type: 'authorization_code'})\n end\n JSON.parse(res.body, symbolize_names: true).tap do |body|\n @access_token = body[:access_token]\n end\n end", "def get_access\n path = '/v3/oauth/authorize'\n data = \"consumer_key=#{Consumer_key}&code=#{Token}\"\n return pocket_api(path,data)\nend", "def get_oauth_response(res)\n body = res.content\n body.split('&').inject({}) { |r, e|\n key, value = e.split('=', 2)\n r[unescape(key)] = unescape(value)\n r\n }\n end", "def raw_info\n @raw_info ||= access_token.get('/api/me', :headers => {'Accept' => \"application/json; version=1\" }).parsed['payload']['users'].first || {}\n end", "def oauth_data\n {\n consumer_key: @consumer_key,\n consumer_secret: @consumer_secret,\n token: @token,\n token_secret: @token_secret\n }\n end", "def do_auth data_hash\n url = \"#{@@oauth_info[:oauth_url]}/access_token\"\n ssl = @@ssl\n headers = {:content_type => \"application/x-www-form-urlencoded;charset=UTF-8\"}\n\n conn = Faraday.new(:url => url, :ssl => ssl) do |faraday|\n faraday.request :url_encoded\n faraday.adapter Faraday.default_adapter\n faraday.response :logger\n end\n\n response = conn.post url, data_hash, headers\n if response.status == 200\n res_hash = JSON.parse response.body\n @access_token = res_hash[\"access_token\"]\n @refresh_token = res_hash[\"refresh_token\"]\n @expires_at = res_hash[\"expires_in\"].seconds.from_now\n return true\n else\n return false\n end\n end", "def raw_info\n req = access_token.get('/API/v1.1/Rest/ConsoleService.svc/Console/Authentication/Info')\n @raw_info ||= MultiJson.load(req.body)\n end", "def parse_twitter_credentials(response_data)\n account_data = NSString.alloc.initWithData(response_data, encoding:NSUTF8StringEncoding)\n params = {}\n\n account_data.split('&').each do |param|\n key, value = param.split('=')\n params[key] = value\n end\n\n # This is super fragile error handling, but basically check that the token and token secret are there.\n # If not, return the result that Twitter returned.\n if params['oauth_token_secret'] && params['oauth_token']\n params\n else\n { 'error' => account_data }\n end\n end", "def bot_info(access_token:, bot_id:)\n query = {\n bot: bot_id\n }.compact\n response = HTTParty.get(\"https://slack.com/api/bots.info\",\n query: query,\n headers: { 'Authorization': \"Bearer #{access_token}\" })\n JSON.parse(response.body, symbolize_names: true)\n end", "def get_metadata(payload)\n auth_server_id = payload['iss'].split('/').last # iss: \"https://<org>.oktapreview.com/oauth2/<auth_server_id>\"\n client_id = payload['cid']\n metadata_response = client(payload['iss']).get do |req|\n req.url \"/oauth2/#{auth_server_id}/.well-known/oauth-authorization-server?client_id=#{client_id}\"\n end\n JSON.parse(metadata_response.body)\n end", "def oauth_data\n {\n consumer_key: CONSUMER_KEY,\n consumer_secret: CONSUMER_SECRET,\n token: session[:token],\n token_secret: session[:secret],\n realm_id: session[:realm_id]\n }\n end", "def parse_response\n parse_address()\n parse_expires()\n parse_token_type()\n parse_token()\n end", "def remote_info\n return nil unless oauth_token?\n response = api(url: '/user')\n response.data\n end", "def get_auth_data \n auth_data = nil\n [\n 'REDIRECT_REDIRECT_X_HTTP_AUTHORIZATION',\n 'REDIRECT_X_HTTP_AUTHORIZATION',\n 'X-HTTP_AUTHORIZATION', \n 'HTTP_AUTHORIZATION'\n ].each do |key|\n if request.env.has_key?(key)\n auth_data = request.env[key].to_s.split\n break\n end\n end\n if auth_data && auth_data[0] == 'Basic' \n return Base64.decode64(auth_data[1]).split(':')[0..1] \n end \n end", "def access_token\n @data[:access_token]\n end", "def fetch_access_token\n JSON.parse(File.read('/opt/gluu-server/etc/certs/api_token.json'))['token']\n end", "def get_auth_data\n user, pass = nil, nil\n # extract authorisation credentials \n if request.env.has_key? 'X-HTTP_AUTHORIZATION' \n # try to get it where mod_rewrite might have put it \n authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split \n elsif request.env.has_key? 'HTTP_AUTHORIZATION' \n # this is the regular location \n authdata = request.env['HTTP_AUTHORIZATION'].to_s.split \n end \n \n # at the moment we only support basic authentication \n if authdata && authdata[0] == 'Basic' \n user, pass = Base64.decode64(authdata[1]).split(':')[0..1] \n end \n return [user, pass] \n end", "def process_login_response(email, password, response)\n @email = email\n @password = password\n @token = Parser.extract_user_token response\n @id = Parser.login_object_id response\n @xp = Parser.extract_xp response\n end", "def profile_data(access_token)\n response = uphold_conn.get do |req|\n req.url UPHOLD_PROFILE_PATH\n req.respond_to? :json, content_type: /\\b(?i:json)$/\n req.headers[:Authorization] = \"Bearer #{access_token}\"\n end\n JSON.parse(response.body, symbolize_names: true)\n end", "def raw_info\n # This is a public API and does not need signing or authentication\n request = \"/services/rest/?format=json&method=flickr.people.getInfo&nojsoncallback=1&user_id=#{uid}\"\n @raw_info ||= MultiJson.decode(access_token.get(request).body)\n rescue ::Errno::ETIMEDOUT\n raise ::Timeout::Error\n end", "def parse(www_authenticate); end", "def parse_response(context) \n @user_context = {\n :cobrand_id => context[:cobrand_id],\n :channel_id => context[:channel_id],\n :locale => { \n :country => context[:locale][:country], \n :language => context[:locale][:language], \n :variant => context[:locale][:variant] \n },\n :tnc_version => context[:tnc_version],\n :application_id => context[:application_id],\n :cobrand_conversation_credentials => {\n :session_token => context[:cobrand_conversation_credentials][:session_token]\n }, \n :preference_info => {\n :currency_code => context[:preference_info][:currency_code],\n :time_zone => context[:preference_info][:time_zone],\n :date_format => context[:preference_info][:date_format],\n :currency_notation_type => context[:preference_info][:currency_notation_type],\n :number_format => {\n :decimal_separator => context[:preference_info][:number_format][:decimal_separator],\n :grouping_separator => context[:preference_info][:number_format][:grouping_separator],\n :group_pattern => context[:preference_info][:number_format][:group_pattern]\n }\n },\n :conversation_credentials => {\n :session_token => context[:conversation_credentials][:session_token]\n }, \n :valid => context[:valid],\n :is_password_expired => context[:is_password_expired],\n :attributes! => {\n :conversation_credentials => {\"xsi:type\" => \"login:SessionCredentials\"},\n :cobrand_conversation_credentials => { \"xsi:type\" => \"login:SessionCredentials\"}\n }\n }\n end", "def parse_response(context) \n @user_context = {\n :cobrand_id => context[:cobrand_id],\n :channel_id => context[:channel_id],\n :locale => { \n :country => context[:locale][:country], \n :language => context[:locale][:language], \n :variant => context[:locale][:variant] \n },\n :tnc_version => context[:tnc_version],\n :application_id => context[:application_id],\n :cobrand_conversation_credentials => {\n :session_token => context[:cobrand_conversation_credentials][:session_token]\n }, \n :preference_info => {\n :currency_code => context[:preference_info][:currency_code],\n :time_zone => context[:preference_info][:time_zone],\n :date_format => context[:preference_info][:date_format],\n :currency_notation_type => context[:preference_info][:currency_notation_type],\n :number_format => {\n :decimal_separator => context[:preference_info][:number_format][:decimal_separator],\n :grouping_separator => context[:preference_info][:number_format][:grouping_separator],\n :group_pattern => context[:preference_info][:number_format][:group_pattern]\n }\n },\n :conversation_credentials => {\n :session_token => context[:conversation_credentials][:session_token]\n }, \n :valid => context[:valid],\n :is_password_expired => context[:is_password_expired],\n :attributes! => {\n :conversation_credentials => {\"xsi:type\" => \"login:SessionCredentials\"},\n :cobrand_conversation_credentials => { \"xsi:type\" => \"login:SessionCredentials\"}\n }\n }\n end", "def raw_info\n @raw_info ||= access_token.get('/api/v1/me').parsed\n end", "def token_metadata()\n return @data[\"access\"][\"token\"]\n end", "def raw_info\n if access_token\n @raw_info ||= ::JSON.parse(access_token.get('/api/v2/users/me').body)\n elsif signed_request\n @raw_info ||= decode(signed_request)\n end\n rescue ::Errno::ETIMEDOUT\n raise ::Timeout::Error\n end", "def info\n oauth_response = access_token.get \"/api/v1/users/current.json\"\n JSON.parse(oauth_response.body)\n end", "def get_user_info\n get(\"/api/v1/oauth_user_info.json\")\n end", "def raw_info\n @raw_info ||= JSON.parse(access_token.get(ENV['OAUTH_WEDDINGWIRE_PROFILE_URL']).body)\n rescue ::Errno::ETIMEDOUT\n raise ::Timeout::Error\n end", "def raw_info\n yql = \"select * from social.profile where guid='#{uid}'\"\n request = \"https://query.yahooapis.com/v1/yql?q=#{encode_uri_component(yql)}&format=json\"\n @raw_info ||= MultiJson.decode(access_token.get(request).body)\n rescue ::Errno::ETIMEDOUT\n raise ::Timeout::Error\n end", "def twitter_access_level\n twitter_access_token.response.header['x-access-level']\n end", "def twitter_access_level\n twitter_access_token.response.header['x-access-level']\n end", "def get_access_token\n token_hash = Hash.new\n token_obj = get_access_token_json\n if token_obj.response.code.to_i == 200\n response_json = JSON.parse token_obj.response.body\n token_hash[\"access_token\"]= response_json[\"access_token\"]\n token_hash[\"token_type\"]= response_json[\"token_type\"]\n end\n return token_hash\n end", "def get_auth_data\n auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }\n auth_data = request.env[auth_key].to_s.split unless auth_key.blank?\n return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil] \n end", "def oauth_token\n @json['oauthToken']\n end", "def fetch_access_token\n uri = URI.parse Sendible::API::URL + \"/v1/auth?app_id=#{CGI.escape(Sendible.application_id)}&access_key=#{CGI.escape(access_key)}\"\n get = Net::HTTP::Get.new(uri.request_uri)\n response = Net::HTTP.start(uri.host, uri.port) do |http|\n http.request(get)\n end\n response.body\n end", "def scim_oauth_access_token\n @attributes[:scim_oauth_access_token]\n end", "def from_authentication_data response\n load_attributes_from_response(response)\n end", "def get_access_token\n @oauth_access_token = oauth_request.get_access_token\n @authenticated_user_uri = oauth_consumer.token_request_response[\"Content-Location\"]\n end", "def get_access(params: nil, host: nil)\n form = { grant_type: \"authorization\",\n code: params[:code],\n redirect_uri: url_helpers.authorisation_identities_url(host: host)\n }\n Faraday.new do |c|\n c.use Faraday::Request::BasicAuthentication\n end\n conn = Faraday.new(url: Setting.oauth[\"id_token_service_url\"])\n conn.params = form\n conn.basic_auth Setting.oauth[\"client_id\"], Setting.oauth[\"client_secret\"]\n resp = conn.post\n raise if resp.status >= 300\n @access_token = JSON.parse(resp.body)\n validate_id_token(id_token: @access_token[\"id_token\"])\n @user_proxy = UserProxy.set_up_user(access_token: @access_token, id_token: @id_token)\n if @user_proxy.has_a_kiwi?\n @user_proxy.kiwi.check_party\n publish(:valid_authorisation, @user_proxy)\n else\n publish(:create_a_kiwi, @user_proxy)\n end\n end", "def find_oauth_access_token\n end", "def raw_info\n @raw_info ||= JSON.load(access_token.get('v2/profile').body)\n rescue ::Errno::ETIMEDOUT\n raise ::Timeout::Error\n end", "def raw_info\n @raw_info ||= JSON.load(access_token.get('v2/profile').body)\n rescue ::Errno::ETIMEDOUT\n raise ::Timeout::Error\n end", "def get_token_response(url)\n JSON.parse(access_token.get(\"/#{api_version}#{url}\").body)\n end", "def get_access_token_from_API()\n # eventbrite embeds access code in the link it \"returns\"\n \taccess_code = extract_access_code_from_link()\n\n # once user allows access, exchange for access token\n access_token_JSON = exchange_code_for_token( access_code ) \n access_token = parse_for_access_token( access_token_JSON )\n return access_token\n end", "def handle_auth_response(response)\n @auth_token = {}\n\n # TODO: Fix this to handle error cases\n begin\n response = JSON.parse(response.body)\n @auth_token[:token] = response[\"token\"]\n @auth_token[:expires_at] = DateTime.parse(response[\"expires_at\"])\n rescue JSON::ParserError, TypeError\n @auth_token = {}\n end\n end", "def get_user_info\n userTokenInfo = request.env['oauth.token']\n @user = userTokenInfo.user\n end", "def http_auth_hash; end", "def get_access_token(code:, redirect_uri: nil)\n query = {\n code: code,\n client_id: @client_id,\n client_secret: @client_secret,\n redirect_uri: redirect_uri\n }.compact\n response = HTTParty.get(\"https://slack.com/api/oauth.v2.access\", query: query)\n JSON.parse(response.body, symbolize_names: true)\n end", "def user_info\n auth_hash['user_info']\n end", "def facebook_data_about(item, keys = {})\n begin\n res = JSON.parse(token_get(item) || \"{}\") \n keys[:as] ? res[keys[:as]] : res\n rescue SocketError, Errno::ECONNRESET, OAuth2::HTTPError, EOFError => e\n # TODO :: hoptoad\n nil\n end\n end", "def auth2_request(url, data)\r\n byte_array = data.encode('UTF-8')\r\n headers = {\r\n 'Content-Type' => 'application/x-www-form-urlencoded',\r\n }\r\n response = connection.post(url, byte_array, headers)\r\n json_response = JSON.parse(response.body)\r\n json_to_oauth2request(json_response)\r\n end", "def get_auth_data\n auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }\n auth_data = request.env[auth_key].to_s.split unless auth_key.blank?\n return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil] \n end", "def auth\r\n OAuth2\r\n end", "def get_auth_data\n auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }\n auth_data = request.env[auth_key].to_s.split unless auth_key.blank?\n return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil] \n end", "def fetch_access_token\n client.unauthenticated_request(:POST, '/v1/security/oauth2/token',\n grant_type: 'client_credentials',\n client_id: client.client_id,\n client_secret: client.client_secret)\n end", "def authentication_response\n if authenticate_user.success?\n { :token => authenticate_user.result }\n else\n { :error => :unauthorized }\n end\n end", "def parse_facebook_user_data\n access_token = facebook_client.web_server.access_token(params[:code],\n :redirect_uri => Settings.authentication.facebook.callback_url)\n JSON.parse(access_token.get('/me'))\n end", "def tokeninfo(token)\n $client.authorization.update_token!(token)\n oauth2 = $client.discovered_api('oauth2','v2')\n\n puts $client.execute(oauth2.tokeninfo, token).response.body\nend", "def get_auth_data\n auth_key = @@http_auth_headers.find { |h| request.env.key?(h) }\n auth_data = request.env[auth_key].to_s.split unless auth_key.blank?\n auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil]\n end", "def parse_user_response(response)\n\tJSON.parse(response.body)\n\nend", "def parsed_darksky_response_data\n JSON.parse(darksky_response.body, symbolize_names: true)\n end", "def index\n auth_response = plaid_client.auth.get(access_token)\n render json: auth_response.to_json\n end", "def step2\n initialize_vars\n url = \"#{@oauth_vars[:token_url]}?code=#{params[:code]}&grant_type=authorization_code&client_id=#{@oauth_vars[:client_id]}&client_secret=#{@oauth_vars[:client_secret]}&response_type=code&redirect_uri=#{@redirect_uri}\"\n rep = JSON.parse(get_json_from_https(url))\n session[:access_token] = rep[\"access_token\"]\n\n do_API_call\n end", "def get_auth_data\n auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }\n auth_data = request.env[auth_key].to_s.split unless auth_key.blank?\n return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil]\n end", "def get_access(params: nil, host:)\n result = TokenAdapter.new.(client_id: ENV['CLIENT_ID'],\n secret: ENV['CLIENT_SECRET'],\n code: params[:code],\n code_verifier: extract_verifier(params),\n redirect_uri: redirect_callbacks_url(host: host))\n {id_token: validate_id_token(result[\"id_token\"]), result: result}\n end", "def get_access_token_json\n HTTParty.post(get_request_access_token_url)\n end", "def decode_credentials; end", "def oauth_data\n @oauth_data ||= File.exists?(oauth_data_file) ? YAML::load_file(oauth_data_file) : {}\n end", "def do_introspection(token, scopes, subject)\n # Call Authlete's /auth/introspection API.\n response = call_introspection_api(token, scopes, subject)\n\n # The content of the response to the client.\n content = response[\"responseContent\"]\n\n # \"action\" denotes the next action.\n case response[\"action\"]\n when \"INTERNAL_SERVER_ERROR\"\n # 500 Internal Server Error\n # The API request from this implementation was wrong\n # or an error occurred in Authlete.\n raise WebResponse.new(500).wwwAuthenticate(content).to_exception\n\n when \"BAD_REQUEST\"\n # 400 Bad Request\n # The request from the client application does not\n # contain an access token.\n raise WebResponse.new(400).wwwAuthenticate(content).to_exception\n\n when \"UNAUTHORIZED\"\n # 401 Unauthorized\n # The presented access token does not exist or has expired.\n raise WebResponse.new(401).wwwAuthenticate(content).to_exception\n\n when \"FORBIDDEN\"\n # 403 Forbidden\n # The access token does not cover the required scopes\n # or the subject associated with the access token is\n # different.\n raise WebResponse.new(403).wwwAuthenticate(content).to_exception\n\n when \"OK\"\n # The access token is valid (= exists and has not expired).\n return response\n\n else\n # This never happens.\n raise WebResponse.new(500, \"Unknown action\").plain.to_exception\n end\nend", "def parse_ldap(response)\n user = nil\n\n # Check for a successful request\n # Parse the response body, which is in JSON format.\n parsed = JSON.parse(response)\n #puts parsed\n #puts \"Facet #{parsed[\"facet_name\"]}\"\nend", "def get_json_hash(url)\n JSON.parse(@access_token.get(url).body)\nend", "def get_data(str)\n user = @current_user.api_user\n pass = @current_user.api_pass\n \n auth = {username: user, password: pass}\n\n return data = HTTParty.get(str, basic_auth: auth)\n end", "def auth_oauth\n @attributes[:auth_oauth]\n end", "def parse_oauth_headers\n # Pull headers and return blank hash if no header variables found\n headers = env['AUTHORIZATION']; result = {};\n return result unless headers && headers[0,5] == 'OAuth'\n # Headers found. Go ahead and match 'em\n headers.split(/,\\n*\\r*/).each do |param|\n phrase, key, value = param.match(/([A-Za-z0-9_\\s]+)=\"([^\"]+)\"/).to_a.map{|v| v.strip}\n result[(key[\"OAuth\"])? :realm : key.to_sym] = value\n end\n result\n end", "def raw_info\n raw_info_url = \"https://kit.snapchat.com/v1/me?query=%7Bme%7BexternalId%2C+displayName%2C+bitmoji%7Bavatar%7D%7D%7D\"\n @raw_info ||= access_token.get(raw_info_url).parsed[\"data\"]\n end", "def get_access_token\n uri = URI.parse(@token_url)\n http = Net::HTTP.new(uri.host, uri.port)\n req = Net::HTTP::Post.new(uri.request_uri)\n auth = Base64.encode64(@login + ':' + @password).gsub(\"\\n\", \"\")\n req['Authorization'] = \"Basic #{auth}\"\n send = 'grant_type=client_credentials'\n req.body = send\n res = http.request(req)\n if res.code == \"200\"\n data = res.body\n result = JSON.parse(data)\n @access_token = result['access_token']\n else\n puts \"Invalid getting access token\"\n exit\n end\n end", "def parsed_response\n response\n end", "def success_response_data\n {\n api_key: @client.api_key,\n api_secret: @client_api_secret_d\n }\n end", "def get_wechat_access_token\n res = RestClient.get \"https://foodtrust.cn/wx/get-access-token?badge=#{ENV['RDS_AGENT']}\"\n #ap res.code; res.cookies; ap res.headers; ap res.body\n return JSON.parse(res.body)['access_token']\nend", "def parse_api\n\t\t@api_data_on_electeds[\"results\"].map do |info|\n\t\t\tfirst_name = info[\"first_name\"]\n\t\t\tlast_name = info[\"last_name\"]\n\t\t\temail = info[\"oc_email\"]\n\t\t\tphone = info[\"phone\"]\n\t\t\ttwitter = info[\"twitter_id\"]\n\t\tputs \"Your elected official is #{first_name} #{last_name}. Their email is #{email} and you can call them at #{phone}. Also send them a tweet at @#{twitter}!\"\n\tend\nend", "def parse_user_response(response)\n\n user = JSON.parse(response.body)\n\nend", "def credentials\n auth_hash['credentials']\n end", "def get_user_data(code)\n\t\taccess_uri = URI::HTTPS.build(:host => @options['auth_host'], :path => @options['access_token_path'])\n\t\tparams = {\n\t\t\t'client_id' => @options['client_id'],\n\t\t\t'client_secret' => @options['client_secret'],\n\t\t\t'redirect_uri' => @options['redirect_uri'],\n\t\t\t'code' => code\n\t\t}\n\n\t\taccess_request = JSON.parse Net::HTTP.post_form(access_uri, params).body\n\n\t\treturn nil if access_request['access_token'].nil? && access_request['user_id'].nil?\n\n\t\tcurrent_user_uri = URI::HTTPS.build(:host => @options['api_host'], :path => @options[\"method_url_path\"])\n\n\t\tresponse = JSON.parse Net::HTTP.post_form(current_user_uri, {'fields' => @options['user_fields'], 'uid' => access_request['user_id']}).body\n\n\t\treturn nil if response.nil?\n\t\tresponse\n\tend", "def pubsub_auth_msg_2_auth_info(msg)\n msg_split = msg.split(/(?<!\\\\),/)\n service_id = msg_split.first.sub('service_id:'.freeze, ''.freeze)\n creds = Credentials.from(\n msg_split[1..-2].join(',').sub('credentials:'.freeze, ''.freeze))\n metric = msg_split.last.sub('metric:'.freeze, ''.freeze)\n\n res = { service_id: service_id, credentials: creds, metric: metric }\n res.map do |k, v|\n # Credentials are already unescaped\n [k, v.is_a?(Credentials) ? v : v.gsub(\"\\\\,\", ','.freeze)\n .gsub(\"\\\\:\", ':'.freeze)]\n end.to_h\n end", "def strava_access_info(code)\n HTTParty.post(\n 'https://www.strava.com/oauth/token',\n body: {\n 'client_id': Rails.application.secrets.STRAVA_CLIENT_ID,\n 'client_secret': Rails.application.secrets.STRAVA_CLIENT_SECRET,\n 'code': code\n }.to_json,\n headers: { 'Content-Type' => 'application/json' }\n ).parsed_response\n end", "def decode_credentials\n return [] unless request.authorization && request.authorization =~ /^Basic (.*)/mi\n Base64.decode64($1).split(/:/, 2)\n end", "def decode_credentials\n return [] unless request.authorization && request.authorization =~ /^Basic (.*)/mi\n Base64.decode64($1).split(/:/, 2)\n end", "def index\n @access_tokens = AccessToken.all\n\n @oauth = oauth\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @access_tokens }\n end\n end", "def access_token\n @auth.access_token\n end", "def on_simple_outbound\r\n {\"userCredentials\" => {\"accessToken\" => ACCESS_TOKEN}}\r\n end", "def on_simple_outbound\r\n {\"userCredentials\" => {\"accessToken\" => ACCESS_TOKEN}}\r\n end", "def oauth_authentication; end", "def get_info_token_oauth\n response = HTTParty.get('https://graph.facebook.com/debug_token?input_token='+@password+'&access_token='+ENV[\"APP_ID_FACEBOOK\"]+'|'+ENV[\"SECRET_KEY_FACEBOOK\"])\n if response.code == 200\n body = JSON.parse(response.body)\n if body['data']['is_valid']\n return body['data']['user_id']\n else\n errors.add(:token, 'Token not valid')\n end\n else\n errors.add(:token, 'Token not valid')\n end\n nil\n end", "def get_tokens\n resource = \"/oauth/access_token\"\n\n begin\n response = @connection.post resource do |request|\n request.params['client_id'] = @api_key\n request.params['client_secret'] = @secret_key\n request.params['grant_type'] = @grant_type\n request.params['scope'] = 'SPEECH,STTC,TTS'\n end\n\n result = process_response(response)\n\n if result[:access_token].nil? || result[:refresh_token].nil?\n raise RuntimeError, \"Unable to complete oauth: #{response[:error]}\"\n else\n @access_token = result[:access_token]\n @refresh_token = result[:refresh_token]\n end\n rescue => e\n raise RuntimeError, e.to_s\n end\n end", "def oauth_access_token\n session[:access_token]\n end", "def parse_response(response)\n data = response.body\n\n data.split(ROWS_SPLITTER).inject([]) do |array, row|\n suffix, occurrences = row.split(ATTRIBUTES_SPLITTER)\n\n if occurrences.to_i > 0\n array << Models::Password.new(suffix: suffix, occurrences: occurrences.to_i)\n end\n\n array\n end\n end" ]
[ "0.63821006", "0.6263636", "0.6097347", "0.6082701", "0.60452414", "0.6038126", "0.59176666", "0.5915798", "0.5896134", "0.5895652", "0.58949816", "0.5854907", "0.5822499", "0.5799759", "0.57996255", "0.5776106", "0.57636863", "0.5726551", "0.57002944", "0.5683768", "0.56806004", "0.56407654", "0.5634055", "0.5630104", "0.5604303", "0.5601652", "0.5601652", "0.55889755", "0.5576776", "0.55750924", "0.5573232", "0.55726045", "0.5567387", "0.5548484", "0.55330414", "0.55330414", "0.5533003", "0.5528027", "0.5521553", "0.55187696", "0.5513866", "0.5513479", "0.5498609", "0.54985946", "0.5495456", "0.5494582", "0.5494582", "0.5493664", "0.54893667", "0.5482282", "0.5471552", "0.5470796", "0.54679245", "0.5456823", "0.54460734", "0.54404217", "0.5431595", "0.5427535", "0.54266834", "0.5423137", "0.54155076", "0.5408522", "0.5407802", "0.5402308", "0.5402279", "0.53899443", "0.5389716", "0.53874046", "0.53719634", "0.5361364", "0.53588873", "0.5349858", "0.5349257", "0.5345266", "0.5344771", "0.53409284", "0.53375465", "0.5322319", "0.53216547", "0.53166705", "0.52981025", "0.5297", "0.529296", "0.528897", "0.5288831", "0.5278164", "0.52776134", "0.52675366", "0.5260961", "0.5254699", "0.524169", "0.524169", "0.5233867", "0.5217294", "0.5215225", "0.5215225", "0.5214848", "0.5214284", "0.52111924", "0.5200574", "0.519945" ]
0.0
-1
API call to get user permissions for workspace token. This is needed because workspace token 'signinwithslack' is missing scopes in the :scope field (acknowledged issue in developer preview). Returns [: ]
def apps_permissions_users_list return {} unless !skip_info? && is_app_token? && is_not_excluded? semaphore.synchronize { @apps_permissions_users_list_raw ||= access_token.get('/api/apps.permissions.users.list') @apps_permissions_users_list ||= @apps_permissions_users_list_raw.parsed['resources'].inject({}){|h,i| h[i['id']] = i; h} } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def findProjectPermissions(workspace, user)\n query_result = @rally.find(:project_permission, :fetch => true, :pagesize => 100) {\n equal :\"user.login_name\", user.login_name\n }\n \n projectPermissions = []\n query_result.each { |pp|\n if ( pp.project.workspace == workspace)\n projectPermissions.push(pp)\n end\n }\n projectPermissions\n end", "def index\n authorize TokenPermissionType\n @user = current_user\n @token_types = @user.org.token_permission_types\n end", "def permissions\n User.do_find_permissions session_id: kb_session_id\n end", "def get_permissions(poll_path, polls = read_polls_data)\n if signed_in?\n @user.permissions(poll_path, polls)\n else\n []\n end\n end", "def permissions(api_key=KillBillClient.api_key, api_secret=KillBillClient.api_secret)\n User.do_find_permissions :session_id => kb_session_id,\n :api_key => api_key,\n :api_secret => api_secret\n end", "def scopes_for(token)\n token = token.github_oauth_token if token.respond_to? :github_oauth_token\n scopes = GH.with(token: token.to_s) { GH.head('user') }.headers['x-oauth-scopes'] if token.present?\n scopes &&= scopes.gsub(/\\s/,'').split(',')\n Array(scopes).sort\n rescue GH::Error\n []\n end", "def get_current_permissions()\n\t\t\tkparams = {}\n\t\t\tclient.queue_service_action_call('permission', 'getCurrentPermissions', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend", "def project_permissions\n user.project_permissions(rule.project)\n end", "def delete_workspace_permission(user, workspace)\n # queries on permissions are a bit limited - to only one filter parameter\n query_result = @rally.find(:workspace_permission, :fetch => true, :pagesize => 100) {\n equal :\"user.login_name\", user.login_name\n }\n \n # So now we need to find the exact workspace for all the users workspace_permissions\n workspace_permission = nil\n workspace_permission = query_result.find { |wp| wp.workspace == workspace }\n # delete it if it exists\n if workspace_permission != nil\n workspace_permission.delete\n end\n end", "def lookup_permissions(token)\n url = create_url('GetPermissions')\n data = call(url, { 'token' => token })\n\n paypal_scopes = parse_scopes(data)\n raise ::Paypal::Permissions::FaultMessage.new(data) if paypal_scopes.empty?\n\n { :scopes => paypal_scopes }\n end", "def oauth2_permission_scopes\n return @oauth2_permission_scopes\n end", "def apps_permissions_scopes_list\n return {} unless is_app_token?\n semaphore.synchronize {\n @apps_permissions_scopes_list ||= (\n r = get('/api/apps.permissions.scopes.list').parsed\n r['scopes'] || {}\n )\n }\n end", "def index\n @user_workspaces = UserWorkspace.owned_by(current_user)\n end", "def index\n @workspaces = current_api_user.workspaces.all\n end", "def rescope_token\n if @scoped_project_id\n # @scoped_project_id exists -> check if friendly id for this project\n # also exists. The scope controller runs bevore this controller and\n # updates the friendlyId entry if project exists.\n unless FriendlyIdEntry.find_project(@scoped_domain_id, @scoped_project_id)\n # friendly id entry is nil -> reset @can_access_project, render project\n # not found page and return.\n @can_access_project = false\n return render(template: \"application/exceptions/project_not_found\")\n end\n\n # NOTE: LEAVE this here because for better review\n # we do not need extra permissions check for project and domains because elektron and monsoon_openstack_auth\n # are doing the job. If the user has no access with his token monsoon_openstack_auth will trow an NotAuthorized\n # error that we will catch and handle to show 'application/exceptions/unauthorized'\n #\n # if no access this is handled in rescue from above\n # did not return -> check if user projects include the requested project.\n #has_project_access = services.identity.has_project_access(\n # @scoped_project_id\n #)\n\n #unless has_project_access\n # # user has no permissions for requested project -> reset\n # # @can_access_project, render unauthorized page and return.\n # @can_access_project = false\n # return render(template: 'application/exceptions/unauthorized')\n #end\n elsif @scoped_domain_id\n # NOTE: LEAVE hit here because for better review\n # @scoped_project_id is nil and @scoped_domain_id exists -> check if\n # user can access the requested domain.\n\n # check if user has access to current domain, add rescue nil for cases where the token scope inexplicably contains a deleted project\n # without the rescue this call leads to an error message and the user can't see the domain page\n #has_domain_access = services.identity.has_domain_access(@scoped_domain_id) rescue nil\n\n #unless has_domain_access\n # # this can happen if the user is using a link to some domain and project\n # # user has no permissions for the new domain -> rescope to\n # # unscoped token and return this will be the startpoint to rescope again\n # return authentication_rescope_token(domain: nil, project: nil)\n #end\n else\n # both @scoped_project_id and @scoped_domain_id are nil\n # -> render unauthorized page and return.\n @can_access_project = false\n return render(template: \"application/exceptions/unauthorized\")\n end\n # did not return yet -> rescope token to the 'new' scope.\n begin\n authentication_rescope_token\n rescue MonsoonOpenstackAuth::Authentication::NotAuthorized => exception\n if exception.message =~ /has no access to the requested scope/\n if @scoped_project_id.present?\n render(template: \"application/exceptions/unauthorized\")\n elsif @scoped_domain_id.present?\n authentication_rescope_token(domain: nil, project: nil)\n end\n end\n # All other NotAuthorized Errors handled by \"rescue_and_render_exception_page\"\n end\n end", "def list_workspaces()\n # check and reauthenticate\n self.isTokenExpired()\n\n results = []\n url = @api_url + \"/api/workspaces\"\n headers = {:accept => :json, :authorization => \"bearer #{@access_token}\"}\n\n RestClient.proxy = @proxy\n\n begin\n r = RestClient.get url, headers\n rescue RestClient::ExceptionWithResponse => e\n puts e.response\n end\n\n workspaces = JSON.parse(r.body)['data']\n #release_count = JSON.parse(r.body)['TotalResults']\n\n #puts \"workspaces dump is #{JSON.pretty_generate(workspaces)}\\nworkspace count is #{release_count}\"\n\n workspaces.each do |workspace|\n results.push(workspace)\n end\n return results\n end", "def apps_permissions_users_list(_user_id=nil)\n #raise StandardError, \"APUL caller #{caller_method_name} user #{_user_id}\"\n return {} unless is_app_token?\n semaphore.synchronize {\n @apps_permissions_users_list ||= (\n r = get('/api/apps.permissions.users.list').parsed\n r['resources'].to_a.inject({}){|h,i| h[i['id']] = i; h} || {}\n )\n _user_id ? @apps_permissions_users_list[_user_id].to_h['scopes'] : @apps_permissions_users_list\n }\n end", "def permission\n perm = data.fetch(\"permissionSources\")\n .map { |i| i[\"permission\"] }\n .first\n .downcase\n GITHUB_TO_TERRAFORM_PERMISSIONS.fetch(perm)\n end", "def permission_grants()\n return MicrosoftGraph::Me::JoinedTeams::Item::PermissionGrants::PermissionGrantsRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def is_workspace_admin(user, project)\n is_admin = false\n user_permissions = user[\"UserPermissions\"]\n\n this_workspace = project[\"Workspace\"]\n this_workspace_oid = this_workspace[\"ObjectID\"].to_s\n\n if !user_permissions.nil? then\n user_permissions.each do | this_permission |\n if this_permission._type == \"WorkspacePermission\" then\n if this_permission.Workspace.ObjectID.to_s == this_workspace_oid then\n permission_level = this_permission.Role\n if permission_level == $ADMIN then\n is_admin = true\n break\n end\n end\n end\n end\n end\n return is_admin\nend", "def get_relations_of_workspace_and_user(wid)\n get \"/workspaces/#{wid}/workspace_users\"\n end", "def retrieve_tokens\n return false unless oauth_credentials_valid?(@current_user)\n\n tokens = OpenStruct.new(get_tokens(@current_user, 'watch'))\n @watch_token = tokens.action_token\n @access_token = tokens.access_token\n\n !(@watch_token.nil? || @access_token.nil?)\n end", "def get_active_permissions\n set_access_token\n if @access_token && !@permissions && set_uid\n # if we don't have permissions set but have an access token\n # grab the user's info\n @rest = Facebook::RestAPI.new(@access_token) \n result = @rest.fql_query(\"select #{all_permissions.join(\",\")} from permissions where uid = #{@uid.to_s}\")\n result.first\n end \n end", "def admin_grant_permissions\n @user = User.includes(:perms).find(params[:id])\n authorize @user\n user_perms = current_user.perms\n @perms = user_perms & [Perm.grant_permissions, Perm.modify_templates, Perm.modify_guidance, Perm.use_api, Perm.change_org_details]\n end", "def get_user_auth(slack_team_id)\n # this will raise a ActiveRecord::RecordNotFound exception if the Auth data can't be found\n auth = Auth.where(team_id: slack_team_id).first\n raise ArgumentError.new('No authorizations found for this workspace. Please go through the /provision flow first') if auth.nil?\n auth\n end", "def index\n success = false;\n error = \"Resource not available.\"\n project = nil\n\n if params.key?(:project_id)\n project = Project.find_by(id: params[:project_id])\n success = (project and user_can_access_project(project.id, [:can_view]))\n end\n\n if success\n render json: project.project_permissions, \n each_serializer: ProjectPermissionSerializer\n else\n render_error error\n end\n end", "def current_user_ws\n return User.find_by_authentication_token(params[:access_token])\n end", "def permissions_for(game)\n self.permissions.where(\"user_roles.game_id = ?\", game.id)\n end", "def get_fb_permissions\n if fb_access_token\n @graph = Koala::Facebook::API.new(fb_access_token)\n @graph.get_connections('me', 'permissions') rescue []\n else\n []\n end\n end", "def list_channels(workspace)\n puts \"\\nChannel List\\n\\n\"\n tp workspace.channels, \"id\", \"name\", \"topic\", \"member_count\"\nend", "def access_rights_for_user_group(user_group_sym)\n res = []\n permissions_for_user_group(user_group_sym).each do |perm|\n res << access_rights_for_permission(perm)\n end\n res.flatten\n end", "def user_permission(project_id, username, options = {})\n opts = options.dup\n opts[:accept] = 'application/vnd.github.inertia-preview+json' if opts[:accept].nil?\n\n get \"projects/#{project_id}/collaborators/#{username}/permission\", opts\n end", "def oauth2_permission_grants()\n return MicrosoftGraph::Oauth2PermissionGrants::Oauth2PermissionGrantsRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def core_getUsersPermissions\n # definisco permessi iniziali\n initial_permissions = (1...11).to_a\n\n unpermitted = core_getHideUsersPermissionsSettings\n permitted_permissions = initial_permissions\n permitted_permissions = initial_permissions - unpermitted if unpermitted\n\n permissions = []\n names = core_getUsersPermissionsNamesSettings\n return permitted_permissions if !names\n\n permitted_permissions.each do |permission|\n names.each do |name|\n permissions.push([permission, name.last]) if permission === name.first.to_i\n end\n end\n\n return permissions\n end", "def delete_workspace_permission(user, workspace)\n\n if @upgrade_only_mode then\n @logger.info \" #{user[\"UserName\"]} #{workspace[\"Name\"]} - upgrade_only_mode == true.\"\n @logger.warn \" Proposed Permission: #{NOACCESS}\"\n @logger.info \" Proposed Permission change would downgrade permissions. No permission updates applied.\"\n return\n end\n\n # queries on permissions are a bit limited - to only one filter parameter\n workspace_permission_query = RallyAPI::RallyQuery.new()\n workspace_permission_query.type = :workspacepermission\n workspace_permission_query.fetch = \"Workspace,Name,ObjectID,Role,User,UserName\"\n workspace_permission_query.page_size = 200 #optional - default is 200\n workspace_permission_query.order = \"Name Asc\"\n workspace_permission_query.query_string = \"(User.UserName = \\\"\" + user.UserName + \"\\\")\"\n\n query_results = @rally.find(workspace_permission_query)\n\n query_results.each do | this_workspace_permission |\n\n this_workspace = this_workspace_permission.Workspace\n this_workspace_oid = this_workspace[\"ObjectID\"].to_s\n\n if this_workspace_permission != nil && this_workspace_oid == workspace[\"ObjectID\"].to_s\n begin\n @rally.delete(this_workspace_permission[\"_ref\"])\n rescue Exception => ex\n this_user = this_workspace_permission.User\n this_user_name = this_user.Name\n\n @logger.warn \"Cannot remove WorkspacePermission: #{this_workspace_permission.Name}.\"\n @logger.warn \"WorkspacePermission either already NoAccess, or would remove the only WorkspacePermission in Subscription.\"\n @logger.warn \"User #{this_user_name} must have access to at least one Workspace within the Subscription.\"\n end\n end\n end\n end", "def get_permissions who, resource_tree\n who = get_group(who) unless who.is_a?(Group)\n \n last_resource = resource_tree.last\n \n # go down the resource tree to determine the permissions\n resource_tree.each do |resource|\n raise \"unknown resource\" unless resource\n \n # get permissions to resource\n r = w = x = false\n\n ownership = belongs_to_group?(who, resource.owner_uuid)\n\n get_permissions_by_resource(resource).each do |permission|\n next unless belongs_to_group?(who, permission.group_uuid, ownership)\n\n # group has effect on permissions\n r = true if permission.is_readable\n w = true if permission.is_writable\n x = true if permission.is_executable\n end\n \n # return permissions of resource if last\n return [r,w,x] if last_resource == resource\n \n # no read permission => no permission to browse further\n return [false, false, false] unless r\n end\n \n raise \"internal error\"\n end", "def permissions_for(context=nil, force_context=nil)\n auth_scope do\n force_context ||= config.force_context\n context = Zuul::Context.parse(context)\n roles = roles_for(context)\n if force_context\n return role_and_subject_permissions_for(context, roles)\n else\n return role_and_subject_permissions_within(context, roles)\n end\n end\n end", "def admin_grant_permissions\n user = User.find(params[:id])\n authorize user\n\n # Super admin can grant any Perm, org admins can only grant Perms they\n # themselves have access to\n perms = if current_user.can_super_admin?\n Perm.all\n else\n current_user.perms\n end\n\n render json: {\n 'user' => {\n 'id' => user.id,\n 'html' => render_to_string(partial: 'users/admin_grant_permissions',\n locals: { user: user, perms: perms },\n formats: [:html])\n }\n }.to_json\n end", "def list_users(workspace)\n puts \"\\nUser List\\n\\n\"\n tp workspace.users, \"id\", \"name\", \"real_name\", \"status_text\", \"status_emoji\"\nend", "def get_auth_tokens(code)\n oauth_client = TwitchOAuth2::Client.new(\n client_id: 'YOUR_CLIENT_ID',\n client_secret: 'YOUR_CLIENT_SECRET',\n scopes: [\"channel:manage:broadcast\"]\n )\n\n puts oauth_client.token(token_type: :user, code: code)\nend", "def slack_account_for(user)\n user.slack_account_for_github_organization(organization)\n end", "def get_permissions(username)\n p = lookup_permissions(username)\n if p\n return p\n else\n return nil\n end\n end", "def get_permissions\n permissions.keys\n end", "def get_permissions\n permissions.keys\n end", "def permissions\n objects_from_response(Code42::Permission, :get, 'permission')\n end", "def users_with_permissions()\n\t return LiveStreamSeriesPermission.where(:live_stream_series_id => self.id).collect{|p| p.user}\n end", "def getPermissions\n perms = []\n perms.push :disseminate if params[:disseminate_perm] == \"on\"\n perms.push :withdraw if params[:withdraw_perm] == \"on\"\n perms.push :peek if params[:peek_perm] == \"on\"\n perms.push :submit if params[:submit_perm] == \"on\"\n perms.push :report if params[:report_perm] == \"on\" \n perms \n end", "def workspace_list(parameters = {}, invocation_options = {})\n exec(RubyTerraform::Commands::WorkspaceList,\n parameters, invocation_options)\n end", "def fetch_granted_permissions(action:, user:, type:, target:, token:)\n permissions = granted_permissions_for_user(user: user, type: type, target: target, token: token)\n @read = permissions.include?('read')\n @create = permissions.include?('create')\n @update = permissions.include?('update')\n @delete = permissions.include?('delete')\n instance_variable_get(\"@#{action}\")\n end", "def request_token\n json = cli.perform_quietly %Q(curl -u '#{username}:#{password}' -d '{\"scopes\": [\"repo\"], \"notes\": \"Octopolo\"}' https://api.github.com/authorizations)\n self.auth_response = JSON.parse json\n end", "def permissions_assignable_for_user(usr)\n return [] if usr.nil?\n if administrator?(usr)\n get_permissions.collect{|k| Permission.find_by_name(Lockdown.get_string(k)) }.compact\n else\n user_groups_assignable_for_user(usr).collect{|g| g.permissions}.flatten.compact\n end\n end", "def index\n\n @launch_permissions = LaunchPermission.find_for_user(session[:user])\n end", "def does_user_have_workspace_permission?(workspace, user)\n # set default return value\n workspace_permission_exists = false\n\n use_cache = false\n\n # first try to lookup against cached user list -- much faster than re-querying Rally\n if @cached_users != nil then\n if @cached_users.has_key?(user.UserName) then use_cache = true end\n end\n\n # first try to lookup against cached user list -- much faster than re-querying Rally\n if use_cache then\n\n this_user = @cached_users[user.UserName]\n\n # loop through permissions and look to see if there's an existing permission for this\n # workspace, and if so, has it changed\n user_permissions = this_user.UserPermissions\n user_permissions.each do | this_permission |\n if this_permission._type == \"WorkspacePermission\" then\n if this_permission.Workspace.ObjectID.to_s == workspace[\"ObjectID\"].to_s then\n workspace_permission_exists = true\n break\n end\n end\n end\n\n else # Cache does not exist or user isn't in it - query info from Rally\n workspace_permission_query = RallyAPI::RallyQuery.new()\n workspace_permission_query.type = :workspacepermission\n workspace_permission_query.fetch = \"Workspace,Name,ObjectID,Role,User\"\n workspace_permission_query.page_size = 200 #optional - default is 200\n workspace_permission_query.order = \"Name Asc\"\n workspace_permission_query.query_string = \"(User.UserName = \\\"\" + user.UserName + \"\\\")\"\n\n query_results = @rally.find(workspace_permission_query)\n\n workspace_permission_exists = false\n\n # Look to see if any existing WorkspacePermissions for this user match the one we're examining\n # If so, check to see if the workspace permissions are any different\n query_results.each { |wp|\n if ( wp.Workspace.ObjectID == workspace[\"ObjectID\"])\n workspace_permission_exists = true\n break\n end\n }\n end\n return workspace_permission_exists\n end", "def permission_grants()\n return MicrosoftGraph::PermissionGrants::PermissionGrantsRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def list_scope_admins(scope = {})\n role = find_role_by_name(\"admin\")\n list_scope_assigned_users(scope.merge(role: role))\n end", "def list_permissions_with_http_info(opts = {})\n\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RolesAPI.list_permissions ...'\n end\n # resource path\n local_var_path = '/api/v2/permissions'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body]\n\n # return_type\n return_type = opts[:debug_return_type] || 'PermissionsResponse'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || [:apiKeyAuth, :appKeyAuth, :AuthZ]\n\n new_options = opts.merge(\n :operation => :list_permissions,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type,\n :api_version => \"V2\"\n )\n\n data, status_code, headers = @api_client.call_api(Net::HTTP::Get, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RolesAPI#list_permissions\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_authorization_permissions_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: AuthorizationApi.get_authorization_permissions ...\"\n end\n \n \n \n \n \n \n \n \n \n \n \n \n \n # resource path\n local_var_path = \"/api/v2/authorization/permissions\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n query_params[:'pageSize'] = opts[:'page_size'] if opts[:'page_size']\n query_params[:'pageNumber'] = opts[:'page_number'] if opts[:'page_number']\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n local_header_accept = ['application/json']\n local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result\n\n # HTTP header 'Content-Type'\n local_header_content_type = ['application/json']\n header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n \n auth_names = ['PureCloud OAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'PermissionCollectionEntityListing')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: AuthorizationApi#get_authorization_permissions\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_all_workspaces ()\n @all_workspaces = @rallysub.Workspaces\n print \"Subscription contains <#{@all_workspaces.count}> Workspaces.\\n\"\n @all_workspaces.sort {|v1,v2| v1.Name <=> v2.Name}\nend", "def permission_resources\n %w{roles sites employees classrooms students gapps_org_units}\n end", "def permissions_assignable_for_user(usr)\n return [] if usr.nil?\n if administrator?(usr)\n get_permissions.collect do |k| \n ::Permission.find_by_name(Lockdown.get_string(k))\n end.compact\n else\n user_groups_assignable_for_user(usr).collect do |g| \n g.permissions\n end.flatten.compact\n end\n end", "def get_workspace_submissions\n # submissions are loaded from load_valid_submissions\n render '/user_workspaces/submissions/get_workspace_submissions'\n end", "def can_grant_api_to_orgs?\n perms.include? Perm.grant_api\n end", "def can_grant_api_to_orgs?\n perms.include? Perm.grant_api\n end", "def current_tenant_permissions\n if current_or_guest_user\n current_or_guest_user.tenant_ids\n else\n nil\n end\n end", "def permission_level(repo, collaborator, options={})\n get \"#{Repository.path repo}/collaborators/#{collaborator}/permission\", options\n end", "def slack_token\n ENV['SLACK_TOKEN']\n end", "def users_for_a_project\n uri = \"#{@api_url}/#{@project_id}/users?access_token=#{@access_token}\"\n get uri\n end", "def permissions\n\t\tauthorize @user\n\t\t@permissions = []\n\t\tonly_theirs = \"Only theirs\"\n\t\tyes = \"Yes\"\n\t\tno = \"No\"\n\t\tnames = [\"View positions\", \"Create positions\", \"Edit positions\", \"Delete positions\",\n\t\t \"Apply\", \"View applications\", \"Edit applications\", \"Delete applications\",\n\t\t \"Change application submission status\"]\n\t\tadmin_permissions = [yes, yes, yes, yes, yes, \"All\", yes, yes, yes]\n\t\tmod_permissions = [yes, no, yes, no, yes, \"All but incomplete\", only_theirs, only_theirs, yes]\n\t\tuser_permissions = [yes, no, no, no, yes, only_theirs, only_theirs, only_theirs, no]\n\t\tnames.each_with_index do |permission, index|\n\t\t\t@permissions << { name: names[index], admin: admin_permissions[index], mod: mod_permissions[index], user: user_permissions[index]}\n\t\tend\n\n @title = 'Permissions'\n\tend", "def get_user_dms\n request(Route.new(:GET, '/users/@me/channels'))\n end", "def index\n @project_permissions = ProjectPermission.all\n end", "def permissions\n return @permissions\n end", "def show\n\t\t@all_permissions = Lockdown::System.permissions_assignable_for_user(current_user)\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user_group }\n end\n end", "def all_chanperms\n Ricer::Irc::Chanperm.where(:user_id => self.id)\n end", "def permission_grants\n return @permission_grants\n end", "def project_users(project = nil)\n # Check that user has authenticated\n @local_auth_error = local_auth_error\n return Hash[@error => @local_auth_error] if @local_auth_error\n\n # Check that a project slug was passed\n unless project\n return Hash[@error =>\n 'Missing project slug, please include in method call']\n end\n\n # Construct query url\n url = format('%s/projects/%s?token=%s', @baseurl, project, @token)\n # Return valid user object if in test mode\n if @test\n m = MockTimeSync.new\n return m.project_users\n end\n # Try to get the project object\n begin\n # Success!\n response = RestClient.get(url)\n project_object = response_to_ruby(response.body, response.code)\n rescue => e\n # Request Error\n return Hash[@error => e]\n end\n\n # Create the user dict to return\n # There was an error, don't do anything with it, return as a list\n return project_object if project_object.key?('error')\n\n # Get the user object from the project\n users = project_object['users']\n\n # Convert the nested permissions dict to a list containing only\n # relevant (true) permissions\n\n rv = Hash[]\n\n users.each do |user, permissions|\n rv_perms = Array[]\n permissions.each do |perm, value|\n rv_perms.push(perm) if value\n end\n rv[user] = rv_perms\n end\n\n rv\n end", "def all_scopes(_user_id=nil)\n debug{\"_user_id: #{_user_id}, @all_scopes: #{@all_scopes}\"}\n if _user_id && !@all_scopes.to_h.has_key?('identity') || @all_scopes.nil?\n @all_scopes = (\n scopes = case\n when params['scope']\n {'classic' => params['scope'].words}\n when params['scopes']\n params['scopes']\n when is_app_token?\n apps_permissions_scopes_list\n end\n \n scopes['identity'] = apps_permissions_users_list(_user_id) if _user_id && is_app_token?\n params['scopes'] = scopes\n )\n else\n @all_scopes\n end\n end", "def get_permissions\n permissions = Hash.new\n permissions[:CanEditAllTeams] = 1\n permissions[:CanEditAllPlayers] = 2\n permissions[:CanEditAllSeasons] = 3\n permissions[:CanEditAllDivisions] = 4\n permissions[:CanEditAllRatings] = 5\n permissions[:CanEditAllRoles] = 6\n permissions[:CanEditAllPermissions] = 7\n permissions[:CanImport] = 8\n permissions[:CanApproveRatings] = 10\n @permissions = permissions\n end", "def get_authorization_permissions(opts = {})\n data, _status_code, _headers = get_authorization_permissions_with_http_info(opts)\n return data\n end", "def list_scope_assigned_users(options = {})\n admins = []\n project_id = options[:project_id]\n domain_id = options[:domain_id]\n role = options[:role]\n raise_error = options[:raise_error]\n\n # do nothing if role is nil\n return admins if role.nil?\n\n begin\n if project_id\n # get role_assignments for this project_id\n ras =\n role_assignments(\n \"scope.project.id\" => project_id,\n \"role.id\" => role.id,\n :effective => true,\n :include_subtree => true,\n )\n\n # load users (not very performant but there is no other option\n # to get users by ids)\n admins.concat(role_assignments_to_users(ras))\n\n if admins.length.zero?\n # load project\n project = find_project(project_id)\n if project\n # try to get admins recursively by parent_id\n admins =\n list_scope_assigned_users(\n project_id: project.parent_id,\n role: role,\n )\n end\n end\n elsif domain_id\n # get role_assignments for this domain_id\n ras =\n role_assignments(\n \"scope.domain.id\" => domain_id,\n \"role.id\" => role.id,\n :effective => true,\n )\n # load users\n admins.concat(role_assignments_to_users(ras))\n end\n rescue => e\n raise e if raise_error\n end\n\n admins.delete_if { |a| a.id.nil? } # delete crap\n end", "def get_open_projects (input_workspace)\n project_query = RallyAPI::RallyQuery.new()\n project_query.workspace = input_workspace\n project_query.project = nil\n project_query.project_scope_up = true\n project_query.project_scope_down = true\n project_query.type = :project\n project_query.fetch = \"Name,State,ObjectID,Workspace,ObjectID\"\n project_query.query_string = \"(State = \\\"Open\\\")\"\n\n begin\n open_projects = @rally.find(project_query)\n rescue Exception => ex\n open_projects = nil\n end\n return (open_projects)\n end", "def oauth2_permission_scopes=(value)\n @oauth2_permission_scopes = value\n end", "def get_current_permissions\n sd = get_security_descriptor(DO_NOT_REFRESH_SD)\n permissions = []\n unless sd.nil?\n permissions if sd.dacl.nil?\n sd.dacl.each do |ace|\n permissions << Puppet::Type::Acl::Ace.new(convert_to_permissions_hash(ace), self)\n end\n end\n permissions\n end", "def available_projects_list\n uri = \"#{@api_url}?access_token=#{@access_token}\"\n get uri\n end", "def call_introspection_api(token, scopes, subject)\n return call_api(\"/api/auth/introspection\", {\n \"token\" => token,\n \"scopes\" => scopes,\n \"subject\" => subject\n })\nend", "def get_users\n if @project\n if ProjectUser.verify_role(current_user.id, @project, 'client')\n render json: @project.project_users, status: 200\n else\n render json: { error: 'You must be a member of a project to see its content' }, status: :unauthorized\n end\n else\n render json: { error: \"no project found with id of #{params[:id]}\" }, status: 404\n end\n end", "def list_permissions\n BrickFTP::API::Permission.all\n end", "def list_permissions\n BrickFTP::API::Permission.all\n end", "def authorization_token\n credentials = Socialcast::CommandLine.credentials\n return credentials[:scgitx_token] if credentials[:scgitx_token]\n\n username = current_user\n raise \"Github user not configured. Run: `git config --global github.user 'me@email.com'`\" if username.empty?\n password = ask(\"Github password for #{username}: \") { |q| q.echo = false }\n\n payload = {:scopes => ['repo'], :note => 'Socialcast Git eXtension', :note_url => 'https://github.com/socialcast/socialcast-git-extensions'}.to_json\n response = RestClient::Request.new(:url => \"https://api.github.com/authorizations\", :method => \"POST\", :user => username, :password => password, :payload => payload, :headers => {:accept => :json, :content_type => :json, :user_agent => 'socialcast-git-extensions'}).execute\n data = JSON.parse response.body\n token = data['token']\n Socialcast::CommandLine.credentials = credentials.merge(:scgitx_token => token)\n token\n rescue RestClient::Exception => e\n process_error e\n throw e\n end", "def permissions(poll_path, polls = read_polls_data)\n poll = Poll.new(poll_path, polls)\n\n permissions = []\n\n permissions.push('vote') unless votes[poll.id]\n permissions.push('delete') if can_delete?(poll)\n permissions.push('reset') if username == 'admin'\n\n permissions\n end", "def fb_permissions\n fb_user = FbGraph::User.new('me', :access_token => self.access_token)\n fb_user.permissions\n end", "def my_permissions\n @my_permissions ||= self.roles.map {|r| r.permissions.map {|p| p.name}}.flatten.freeze\n end", "def project_users\n request :user\n end", "def get_permissions_for_user(user)\n get_filtered_policy(0, user)\n end", "def role_contexts\n auth_scope do\n send(permission_role_plural_key).group(:context_type, :context_id).map(&:context)\n end\n end", "def user_scope\n User.includes(:notification_settings)\n end", "def get_projects\n me = request('/services/v5/me')\n me['projects']\n end", "def get_permission_menu\n return @client.raw(\"get\", \"/helpers/menu\")\n end", "def users_waiting_for_authorization\n Skype.find_users_of_type \"USERS_WAITING_MY_AUTHORIZATION\"\n end", "def gmail_request\n current_user.refresh_token! if current_user.oauth_expires_at < Time.now\n user_oauth = current_user.oauth_token\n service = Google::Apis::GmailV1::GmailService.new\n service.authorization = user_oauth\n @messages = service.list_user_messages('me', max_results: 10, label_ids:[\"CATEGORY_PERSONAL\", \"INBOX\"])\n @messages_parse = @messages.messages.map {|message| service.get_user_message('me', message.id)}\n end", "def get_token_for(username, password)\n\t\t\t\turl = GITHUB_API_AUTH_LINK \n\t\t\t\tscopes = %w[repo gist]\n\t\t\t\tcontent = generate_scope \"Gistto\", scopes\n\t\t\t\thttps_open_for ({url: url, mthd: \"post\", content: content, username: username, password: password})\n\t\t\tend" ]
[ "0.6519009", "0.59344774", "0.5825381", "0.5773829", "0.57732075", "0.56472045", "0.55737215", "0.55067277", "0.5487154", "0.5486564", "0.54475594", "0.54267025", "0.54189837", "0.53312325", "0.5323245", "0.53118074", "0.5244398", "0.5183052", "0.51570153", "0.5150469", "0.5141716", "0.51337814", "0.51300335", "0.50962514", "0.5083187", "0.5082316", "0.5050268", "0.50359607", "0.5033095", "0.49648118", "0.49581936", "0.49564472", "0.49533302", "0.49379244", "0.4933217", "0.49257538", "0.4916871", "0.48926595", "0.4879376", "0.487124", "0.48577726", "0.48531854", "0.48397338", "0.48397338", "0.48304194", "0.48293388", "0.4827733", "0.48197567", "0.48133886", "0.48060593", "0.48032892", "0.4774773", "0.4759553", "0.475799", "0.47501662", "0.4749844", "0.47450554", "0.47429994", "0.474109", "0.47369745", "0.4735559", "0.47306055", "0.47306055", "0.47305536", "0.4717203", "0.4716814", "0.47129554", "0.47109213", "0.47072193", "0.46959665", "0.4687035", "0.4684717", "0.46776706", "0.46685266", "0.46608326", "0.4659835", "0.46567488", "0.46565822", "0.46525818", "0.4647417", "0.46454936", "0.46398863", "0.46358556", "0.46346396", "0.46297145", "0.46207154", "0.46207154", "0.46179056", "0.46159792", "0.45864987", "0.45854774", "0.45837525", "0.45833093", "0.45816398", "0.45729643", "0.45677236", "0.45661315", "0.45545882", "0.45531133", "0.45487386" ]
0.473925
59
Is this a workspace app token?
def is_app_token? auth['token_type'].to_s == 'app' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_app_token?\n case\n when params['token_type'] == 'app' || token.to_s[/^xoxa/]\n true\n when token.to_s[/^xoxp/]\n false\n else\n nil\n end\n end", "def token_is_for_master?\n token_account['name'] == 'master'\n end", "def valid_token?\n env['HTTP_TOKEN']\n end", "def has_token?\n api.has_token?\n end", "def valid_app_access_token?\n token = request.headers['X-App-Access-Token']\n\n token.present? && token == Rails.application.secrets.app_access_token\n end", "def token?\n @session_token\n end", "def is_token_valid? token\n @browser_token_db.has_token? token\n end", "def valid_app_access_token?\n app_access_token = request.headers['X-App-Access-Token']\n\n app_access_token.present? &&\n app_access_token == Rails.application.secrets.app_access_token\n end", "def token?(token)\n return false\n end", "def access_token?\n payload.typ == 'access'\n end", "def token_authenticated?\n !!access_token\n end", "def token_authenticated?\n !!@access_token\n end", "def token_authenticated?\n !!@access_token\n end", "def token_based?\n @userId && @authToken && !@authToken.empty?\n end", "def client_has_valid_token?\n request.headers[\"Authorization\"] == Rails.application.credentials.guessing_access_token\n end", "def token?\n @token && !@token.empty?\n end", "def has_api_token?\n return false if @configuration.nil?\n RightSignature2013::Connection.api_token_keys.each do |key|\n return false if @configuration[key].nil? || @configuration[key].match(/^\\s*$/)\n end\n\n return true\n end", "def correct_login_token?(given_token)\n false\n end", "def has_valid_token?\n !Slack::Config.token.nil? && Slack::Config.token == \"authorized\"\n end", "def valid_token?\n\t\tif self.moves_token.presence\n\t\t\tresponse = HTTParty.get('https://api.moves-app.com/oauth/v1/tokeninfo?access_token='+\n\t\t\t\tself.moves_token)\n\t\t\tputs \"response.code: #{response.code}\"\n\t\t\tresponse.code == 200\n\t\telse\n\t\t\tfalse\n\t\tend\n\tend", "def token?\n (@token.respond_to?(:empty?) && !@token.empty?)\n end", "def valid_token?\n return false unless token\n begin\n # We use rate limit as its a fast and free way to\n # test the GitHub token.\n octokit.rate_limit\n rescue Octokit::ClientError\n return false\n end\n true\n end", "def logged_in?\n #return true if !session[\"app_user\"].nil? && session[\"app_user\"].id != -1\n validate_token\n return true if !session[\"app_user\"].nil? && session[\"app_user\"].id != -1 \n return false\n end", "def current_token_still_valid?\n begin\n drive = @client.discovered_api('drive', 'v2')\n result = @client.execute(:api_method => drive.about.get)\n rescue\n return false\n end\n \n if result.status == 200\n true\n else\n false\n end\n end", "def is_ostype_token?(token, bhg_version)\n BeakerHostGenerator::Data.get_platforms(bhg_version).each do |platform|\n ostype = platform.split('-')[0]\n if ostype == token\n return true\n end\n end\n return false\n end", "def valid_token?(token)\n exists?(:token => token)\n end", "def is_token?\n !@card_token.nil?\n end", "def valid_access_token?\n token_file = '/opt/gluu-server/etc/certs/api_token.json'\n return false unless File.exist? token_file\n\n token_config = JSON.parse(File.read(token_file))\n expired = token_config['exp'] < Time.now.to_i\n return false if expired\n\n return false unless token_config['token']\n\n true\n end", "def authenticated?\n !!@access_token\n end", "def authenticated?\n @auth_token =~ /^.*$/\n end", "def user_authorizes_token?\n params[:authorize] == '1'\n end", "def user_authorizes_token?\n params[:authorize] == '1'\n end", "def user_authorizes_token?\n params[:authorize] == '1'\n end", "def logged_in?\n !!session[:current_token]\n end", "def authorized?\n !session[:token].nil?\n end", "def is_authorized?\n !!token && !token.expired?\n end", "def is_authorized?\n !!token && !token.expired?\n end", "def generates_tokens?\n has_local_auth_service? && self.clients.any?{|c| !c.bearer_only?}\n end", "def tokens_refreshed?\n\t current_user and current_user.refreshed?\n\tend", "def check_token\n end", "def valid_token?(token)\n return false unless !token.nil? && token_looks_safe?(token)\n result = ApiToken.find_by(token: token)\n !result.nil? && result[:active]\n end", "def api_key_check(api_key)\n if Java::HarbingerSdkData::AppAuthenticationToken.firstWith({\".authToken\" => api_key},@entity_manager)\n true\n else\n false\n end\n end", "def authorized_artsy_token?(token)\n ArtsyAdminAuth.valid?(token)\n end", "def logged_in_with_admin_token?\n !params[:token].blank? && self.action_name.to_sym == :create_as_admin\n end", "def authorization_token_valid?\n id = authorization_token_content.id\n\n return false if id.nil?\n\n user = User.find_by_id id\n\n !user.nil? && user.auth_token == authorization_token\n end", "def connected?\n @token.present?\n end", "def fb_authorized?\n self.access_token.present? \n end", "def valid_for_token_auth?\n token_authenticatable? && auth_token.present? && with_authentication_hash(:token_auth, token_auth_hash)\n end", "def connected?\n !!@access_token\n end", "def connected?\n @token\n end", "def auth_with_yammer?\n yammer_token.present?\n end", "def authenticate_by_token\n token = get_token\n if token.nil?\n render json: \"Missing HTTP_X_NB_AUTHTOKEN HTTP header\", status: :bad_request\n return false\n end\n\n # We verify by two ways:\n # 1. if app session id is present, does the app token match the associated app?\n # 2. does the current track belongs to the app session which the app token points to?\n true_token = Track.find(params[:id]).app_session.app.token\n\n if token != true_token\n render json: \"Token mismatch\", status: :bad_request\n return false\n end\n\n true\n end", "def valid_token?\r\n token = ::AuthToken.where(user_id: decoded_auth_token[:user_id]).newer.first\r\n token&.token == auth_token && token.expire_at >= Time.now if token.present?\r\n end", "def check_magic_token\n params[:magic_token] == Rails.application.secrets.calendly_magic_token\n end", "def valid_token?(token)\n return token == 'TEST_ENV_VALID_TOKEN' if Rails.env.test?\n\n valid_token = config['security_token']\n raise 'Security token is not set! Please set it as soon as possible!' if valid_token.blank?\n\n token == valid_token\n end", "def user_authorizes_token?\n return true if params[:authorize]\n\n end", "def active?\n asana_api_key.present? && workspace.present?\n end", "def authenticated?\n not @access_token.nil?\n end", "def check_access_token(access_token)\n client = Octokit::Client.new(client_id: CLIENT_ID, client_secret: CLIENT_SECRET)\n begin\n client.check_application_authorization access_token\n true\n rescue\n false\n end\n end", "def check_token\n @usuario = Credentials.check_token(authorization: request.headers[\"Authorization\"])\n end", "def token_authenticated?\n !!(@access_token && (@access_token_expires_at.nil? || @access_token_expires_at > Time.now))\n end", "def same_credential?(access_token)\n application_id == access_token.application_id &&\n resource_owner_id == access_token.resource_owner_id\n end", "def auth_token\n return token if token.present?\n\n false\n # raise(CustomException::MissingToken, 'token is missing')\n end", "def authorized?\n !!@access_token\n end", "def check_magic_token\n params[:magic_token] == Rails.application.secrets.salesforce_magic_token\n end", "def refresh_token?\n if (@token_timer + 6000) < Time.now\n self.get_token\n true\n else\n false\n end\n end", "def refresh_token?\n payload.typ == 'refresh'\n end", "def valid_token?\n # we check against a copy invitation object\n match = Invitation.find_by_token(self.token)\n \n if !match\n errors.add :token, 'not found'\n return false\n elsif User.registered.find_by_invitation_id(match)\n errors.add :token, 'already used'\n return false\n end\n \n true\n end", "def app_user?\n member_type == MEMBER_TYPE[:app]\n end", "def is_authorized_for(context)\n\tresult = shared_data_contexts.find_all{|item| item.name == context }\t\n\treturn result != nil && result.length > 0 \n end", "def username_token?\n username && password\n end", "def token_authenticatable?\n mapping.to.http_authenticatable?(:token_options)\n end", "def authorized?\n return if session[:access_token]\n end", "def same_credential?(access_token)\n application_id == access_token.application_id &&\n resource_owner_id == access_token.resource_owner_id\n end", "def same_credential?(access_token)\n application_id == access_token.application_id &&\n resource_owner_id == access_token.resource_owner_id\n end", "def token_valid?\n @session_token and @toodle_token_death > Time.now\n end", "def valid_token?(token, method = :any)\n tokens = settings.subaru_config[:global][:auth_tokens][method]\n return true if tokens.nil?\n tokens.include?(token)\n end", "def is_api?\n current_user\n @env[API_KEY]\n end", "def bearer_authenticated?\n !!@bearer_token\n end", "def mrrt?\n token_response.refresh_token && token_response.resource\n end", "def user_id_included_in_auth_token?\n http_auth_token && decoded_auth_token && decoded_auth_token[:user_id]\n end", "def getCurrentToken\n\t\t\tif !@accessToken\n\t\t\t\treturn false\n\t\t\tend\n\n\t\t\t@accessToken\n\t\tend", "def has?(token)\n store.key? token\n end", "def valid?\n puts \"IN GTOKEN valid? WITH param[authentication_gtoken] \"; puts gtoken\n gtoken\n end", "def getAPIToken(tokenName)\n token = NSBundle.mainBundle.objectForInfoDictionaryKey(tokenName)\n Logger.warn \"Token #{tokenName} is not defined\" unless token\n return token\n end", "def authenticated?\n session[:access_token]\nend", "def authenticated?\n session[:access_token]\nend", "def authenticated?\n session[:access_token]\nend", "def authenticated?\n session[:access_token]\nend", "def authenticated?\n session[:access_token]\nend", "def application_credentials?\n !!application_credentials\n end", "def authenticated?\n @access_token != nil and @access_token.length > 0\n end", "def authenticated?\n current_authentication_token && current_authentication_token == @submission.session_id\n end", "def is_identity_token?\n (params['user_id'] ||\n params['user'].to_h['id']) && true || false\n end", "def check_weixin_token_valid?\n if token_string.blank?\n if token_model_instance.blank?\n render text: \"Forbidden\", status: 403\n return false\n end\n else\n if current_weixin_token != token_string\n render text: \"Forbidden\", status: 403\n return false\n end\n end\n true\n end", "def check_app_token(client_id, client_secret, grant_type)\n e = false\n\n if Settings.multi_application == 'true'\n app = App.where(id: params[:client_id]).first\n if app.nil?\n e = true\n error = {\n error: 'server_error',\n error_description: 'App not found'\n }\n render json: error.to_json, status: 400\n else\n if grant_type == 'password' and !app.enable_password\n e = true\n error = {\n error: 'unauthorized_client',\n error_description: 'Password grant not allowed'\n }\n render json: error.to_json, status: 400\n elsif grant_type == 'refresh_token'\n if !app.enable_code and !app.enable_implicit\n e = true\n error = {\n error: 'unauthorized_client',\n error_description: 'Client grant not allowed'\n }\n render json: error.to_json, status: 400\n elsif !app.password_correct?(client_secret)\n e = true\n error = {\n error: 'server_error',\n error_description: 'wrong secret'\n }\n render json: error.to_json, status: 400\n end\n elsif grant_type == 'authorization_code' and !app.enable_code\n e = true\n error = {\n error: 'unauthorized_client',\n error_description: 'Client grant not allowed'\n }\n render json: error.to_json, status: 400\n elsif grant_type == 'authorization_code' and !app.password_correct?(client_secret)\n e = true\n error = {\n error: 'server_error',\n error_description: 'wrong secret'\n }\n render json: error.to_json, status: 400\n end\n end\n else\n if Settings.single_application_mode_id != client_id\n e = true\n error = {\n error: 'server_error',\n error_description: 'App not found'\n }\n render json: error.to_json, status: 400\n else\n if Settings.single_application_mode_enable_password == 'false' and grant_type == 'password'\n e = true\n error = {\n error: 'unauthorized_client',\n error_description: 'Password grant not allowed'\n }\n render json: error.to_json, status: 400\n elsif grant_type == 'refresh_token'\n if Settings.single_application_mode_enable_code == 'false' or Settings.single_application_mode_enable_implicit == 'false'\n e = true\n error = {\n error: 'unauthorized_client',\n error_description: 'Client grant not allowed'\n }\n render json: error.to_json, status: 400\n elsif Settings.single_application_mode_secret != client_secret\n e = true\n error = {\n error: 'server_error',\n error_description: 'wrong secret'\n }\n render json: error.to_json, status: 400\n end\n elsif grant_type == 'authorization_code'\n if Settings.single_application_mode_enable_code == 'false'\n e = true\n error = {\n error: 'unauthorized_client',\n error_description: 'Client grant not allowed'\n }\n render json: error.to_json, status: 400\n elsif Settings.single_application_mode_secret != client_secret\n e = true\n error = {\n error: 'server_error',\n error_description: 'wrong secret'\n }\n render json: error.to_json, status: 400\n end\n\n end\n\n end\n end\n destroy_session if e\n\n e\n\n end", "def has_token?( token )\n return self.corpus.data.has_key?( token )\n end", "def check_token_deployment\n\n if @token.blank? || @token[:status] == GlobalConstant::ClientToken.not_deployed\n\n @go_to = GlobalConstant::GoTo.token_setup\n\n elsif @token[:status] == GlobalConstant::ClientToken.deployment_started\n\n if @from_page[:by_screen_name] != GlobalConstant::GoTo.developer[:by_screen_name]\n\n @go_to = GlobalConstant::GoTo.token_deploy\n\n end\n\n elsif @token[:status] == GlobalConstant::ClientToken.deployment_failed\n\n @go_to = GlobalConstant::GoTo.token_deploy\n\n elsif @token[:status] == GlobalConstant::ClientToken.deployment_completed\n\n if @from_page[:by_screen_name] == GlobalConstant::GoTo.token_deploy[:by_screen_name] ||\n @from_page[:by_screen_name] == GlobalConstant::GoTo.token_setup[:by_screen_name]\n\n @go_to = GlobalConstant::GoTo.token_mint\n\n end\n\n end\n\n success\n\n end", "def is_access_token_valid?\n response = @client.get(\"#{@base_url}/v1/users/self\", access_token: get_user_access_token )\n code_status = JSON.parse(response.body)[\"meta\"][\"code\"]\n code_status == 200 ? true : false\n end", "def is_token_valid?(token, options={})\n response = els_http_request(\"/isTokenValid\",\"tokenid=#{token}\",options)\n if response.code.eql? \"200\"\n true\n else\n false\n end\n end" ]
[ "0.771789", "0.7274672", "0.72172874", "0.71566266", "0.7029004", "0.6997016", "0.6992928", "0.6986241", "0.69260824", "0.6862502", "0.6833186", "0.68061197", "0.68061197", "0.6802385", "0.6777616", "0.67638683", "0.6733154", "0.6713921", "0.67084825", "0.66970694", "0.6685656", "0.6643842", "0.66286635", "0.65823686", "0.656023", "0.65410703", "0.6528682", "0.6495425", "0.64925367", "0.648258", "0.6476215", "0.6476215", "0.6476215", "0.64745736", "0.6428301", "0.6428149", "0.6428149", "0.6416405", "0.6406175", "0.6402942", "0.6392557", "0.6390924", "0.6387114", "0.6383845", "0.6379427", "0.6358268", "0.6302637", "0.6301039", "0.62960213", "0.62768227", "0.6275234", "0.6273076", "0.6249524", "0.6217136", "0.6210541", "0.6204845", "0.6202372", "0.619444", "0.6175907", "0.6174639", "0.6170327", "0.6159452", "0.61462086", "0.6134612", "0.612937", "0.6127476", "0.6120447", "0.61178523", "0.6113437", "0.6113324", "0.6112924", "0.61078715", "0.6105455", "0.609255", "0.609255", "0.60872555", "0.6083652", "0.60672545", "0.60664", "0.6065592", "0.6064738", "0.60575724", "0.6056774", "0.60494435", "0.60488826", "0.6041345", "0.6041345", "0.6041345", "0.6041345", "0.6041345", "0.6041135", "0.6029299", "0.6025583", "0.60222", "0.6017711", "0.601492", "0.60041004", "0.59990686", "0.5997098", "0.59909135" ]
0.80090237
0
Scopes come from at least 3 different places now. The classic :scope field (string) New workshop token :scopes field (hash) Separate call to apps.permissions.users.list (array) This returns hash of workspace scopes, with classic & new identity scopes in :identity. Lists of scopes are in array form.
def all_scopes @all_scopes ||= {'identity' => (auth['scope'] || apps_permissions_users_list[user_id].to_h['scopes'].to_a.join(',')).to_s.split(',')} .merge(auth['scopes'].to_h) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def all_scopes(_user_id=nil)\n debug{\"_user_id: #{_user_id}, @all_scopes: #{@all_scopes}\"}\n if _user_id && !@all_scopes.to_h.has_key?('identity') || @all_scopes.nil?\n @all_scopes = (\n scopes = case\n when params['scope']\n {'classic' => params['scope'].words}\n when params['scopes']\n params['scopes']\n when is_app_token?\n apps_permissions_scopes_list\n end\n \n scopes['identity'] = apps_permissions_users_list(_user_id) if _user_id && is_app_token?\n params['scopes'] = scopes\n )\n else\n @all_scopes\n end\n end", "def apps_permissions_scopes_list\n return {} unless is_app_token?\n semaphore.synchronize {\n @apps_permissions_scopes_list ||= (\n r = get('/api/apps.permissions.scopes.list').parsed\n r['scopes'] || {}\n )\n }\n end", "def scopes\n params['scope']\n end", "def scopes\n @scopes ||= {}\n end", "def scopes\n env['HTTP_X_AUTHENTICATED_SCOPE'].to_s.split(',')\n end", "def scopes\n scope ? [scope] : []\n end", "def scopes\n @scopes ||= config[:scopes] || []\n end", "def scopes_for(token)\n token = token.github_oauth_token if token.respond_to? :github_oauth_token\n scopes = GH.with(token: token.to_s) { GH.head('user') }.headers['x-oauth-scopes'] if token.present?\n scopes &&= scopes.gsub(/\\s/,'').split(',')\n Array(scopes).sort\n rescue GH::Error\n []\n end", "def scopes\n @@scopes ||= {}\n end", "def scopes_from(request)\n return nil if request.scope.nil?\n\n Array(request.scope).join(' ')\n end", "def scopes\n scope_names.to_a.sort\n end", "def oauth2_scopes(*scopes)\n @oauth2_scope_perms = scopes.map{|i| i.to_s}\n end", "def scopes\n read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})\n end", "def available_scopes\n (default_scopes << Doorkeeper.config.optional_scopes.to_a).flatten.uniq\n end", "def scopes\n scopes = scope ? scope.split(/\\s+/) : []\n scopes = attributes[:scope]\n Set.new(scopes).to_s\n end", "def accessible_scopes\n [uid, shared_space.try(:uid)].compact\n end", "def scopes\n @scope.scopes\n end", "def oauth2_permission_scopes\n return @oauth2_permission_scopes\n end", "def ransackable_scopes(auth_object = nil)\n []\n end", "def all_favorites options = {}\n if options.key?(:multiple_scopes) == false\n validate_scopes __method__, options\n elsif options[:multiple_scopes] == true\n results = {}\n options[:scope].each do |scope|\n favorites_scope = favorites_scoped scope\n results[scope] = favorites_scope = apply_options_to_scope favorites_scope, options\n end\n return results\n else\n favorites_scope = favorites_scoped options[:scope]\n return favorites_scope = apply_options_to_scope(favorites_scope, options)\n end\n end", "def favorites_scoped options = {}\n if options.key?(:multiple_scopes) == false\n validate_scopes __method__, options\n elsif options[:multiple_scopes] == true\n results = {}\n options[:scope].each do |scope|\n results[scope] = favorites.unblocked.send(scope + '_list').includes :favoritable\n end\n return results\n else\n return favorites.unblocked.send(options[:scope] + '_list').includes :favoritable\n end\n end", "def scopes\n model.scopes\n end", "def static_scopes\n scopes = self.scope_definition\n .select { |_k, v| v.blank? }\n .keys\n scopes | [:first, :last, :all]\n end", "def scopes\n self.class.scopes\n end", "def authorize_scopes\n @authorize_scopes ||= (env['omniauth.params']['scope'] || authorize_params['scope']).split(' ')\n end", "def dynamic_scopes\n self.scopes.select { |name, args| args.present? }\n end", "def scopes; end", "def favorites_scoped(options = {})\n if options.key?(:multiple_scopes) == false\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n results[scope] = favorites.unblocked.send(scope + '_list')\n .includes(:favoritable)\n end\n results\n else\n favorites.unblocked.send(options[:scope] + '_list')\n .includes(:favoritable)\n end\n end", "def resource_scopes\n return @resource_scopes\n end", "def resource_scopes\n return @resource_scopes\n end", "def oauth2_permission_scopes=(value)\n @oauth2_permission_scopes = value\n end", "def parse_scopes(data)\n scopes = []\n scopes << data['scope'] if data['scope'] # If there is only one scope\n\n i = 0\n while (data[\"scope(#{i})\"]) do\n scopes << data[\"scope(#{i})\"]; i = i + 1\n end # For multiple scopes\n\n # Convert to symbols\n scopes.collect { |paypal_scope| PERMISSIONS.select { |k,val| val == paypal_scope }.keys.first }\n end", "def authorize_scopes\n scopes = Array(Rack::Utils.parse_query(request.query_string)[\"scope\"])\n return if scopes.empty?\n\n auth_scopes = {}\n\n # First try to fetch the requested scopes and the handler. If no scopes\n # were successfully given, respond with a 401.\n scopes.each do |scope|\n auth_scope, actions = scope_handler(scope)\n\n actions.each do |action|\n # It will try to check if the current user is authorized to access the\n # scope given in this iteration. If everything is fine, then nothing will\n # happen, otherwise there are two possible exceptions that can be raised:\n #\n # - NoMethodError: the targeted resource does not handle the scope that\n # is being checked. It will raise a ScopeNotHandled.\n # - Pundit::NotAuthorizedError: the targeted resource unauthorized the\n # given user for the scope that is being checked. In this case this\n # scope gets removed from `auth_scope.actions`.\n begin\n authorize auth_scope.resource, \"#{action}?\".to_sym\n rescue Portus::AuthScope::NamespaceNotSupport, NoMethodError, Pundit::NotAuthorizedError, Portus::AuthScope::ResourceNotFound => e\n logger.debug e\n logger.debug \"action #{action} not handled/authorized, removing from actions\"\n auth_scope.actions.delete_if { |a| match_action(action, a) }\n end\n end\n\n next if auth_scope.actions.empty?\n # if there is already a similar scope (type and resource name),\n # we combine them into one:\n # e.g. scope=repository:busybox:push&scope=repository:busybox:pull\n # -> access=>[{:type=>\"repository\", :name=>\"busybox\", :actions=>[\"push\", \"pull\"]}\n k = [auth_scope.resource_type, auth_scope.resource_name]\n if auth_scopes[k]\n auth_scopes[k].actions.concat(auth_scope.actions).uniq!\n else\n auth_scopes[k] = auth_scope\n end\n end\n auth_scopes.values\n end", "def scope_chain\n scope ? [[scope]] : [[]]\n end", "def scope_info\n if is_scoped? && scoped_manual.present?\n {\n \"scope\" => {\n \"title\" => scoped_manual.to_hash.fetch(\"title\", \"\"),\n },\n \"unscoped_results\" => unscoped_results,\n }\n else\n {}\n end\n end", "def filter_scopes\n @filter_scopes ||= scopes.inject({}) do |result, element|\n result[element.first] = element.last if element.last[:type] != :boolean\n result\n end\n end", "def all_favorites(options = {})\n if options.key?(:multiple_scopes) == false\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n favorites_scope = favorites_scoped(\n scope: scope, multiple_scopes: false\n )\n results[scope] = apply_options_to_scope(\n favorites_scope, options\n )\n end\n results\n else\n favorites_scope = favorites_scoped(\n scope: options[:scope], multiple_scopes: false\n )\n apply_options_to_scope(\n favorites_scope, options\n )\n end\n end", "def scope(*scopes)\n return if scopes.empty?\n\n unauthorized message: 'User must me authorized' unless current_user\n forbidden messages: 'Not all scope expectations are matched' unless\n current_user.grants_scope?(*scopes)\n end", "def find_scopes\n begin\n pptr = FFI::MemoryPointer.new(:pointer, 128)\n\n result = SLPFindScopes(@handle, pptr)\n raise Error, \"SLPFindScopes(): #{result}\" if result != :SLP_OK\n\n arr = pptr.read_array_of_string\n ensure\n SLPFree(pptr.read_pointer)\n pptr.free unless pptr.null?\n end\n\n arr\n end", "def resource_scopes=(value)\n @resource_scopes = value\n end", "def resource_scopes=(value)\n @resource_scopes = value\n end", "def scope\n if @scope.kind_of? String\n @scope = @scope.split \",\"\n else\n @scope || []\n end\n end", "def default_scopes\n Doorkeeper.config.default_scopes.to_a\n end", "def scope_names\n keys.map { |k| k.to_s }\n end", "def list_scope_admins(scope = {})\n role = find_role_by_name(\"admin\")\n list_scope_assigned_users(scope.merge(role: role))\n end", "def params_auth_hash\n params[scope]\n end", "def params_auth_hash\n params[scope]\n end", "def current_scopes(scopie: default_scopie, hash: params)\n Scopie.current_scopes(hash, method: hash[:action], scopie: scopie)\n end", "def extra_scopes()\n @scopes_added_by_common_scopes\n end", "def get_scope_data(scope)\n return case scope\n when 0 then [false, false, false]\n when 1 then [true, false, false]\n when 2 then [true, false, true]\n when 3 then [false, false, false]\n when 4 then [false, false, true]\n when 5 then [false, true, false]\n when 6 then [false, true, true]\n when 7 then [false, false, false]\n else\n [false, false, false]\n end\n end", "def dynamic_scopes\n self.scope_definition.select { |_k, v| v.present? }\n end", "def downgrade_scopes!\n return unless Feature.enabled?(:omniauth_login_minimal_scopes, current_user,\n default_enabled: :yaml)\n\n auth_type = params.delete('gl_auth_type')\n return unless auth_type == 'login'\n\n ensure_read_user_scope!\n\n params['scope'] = Gitlab::Auth::READ_USER_SCOPE.to_s if application_has_read_user_scope?\n end", "def scopes= new_scopes\n @model.scopes=new_scopes.join(\" \") if new_scopes.respond_to?(:join)\n end", "def apps_permissions_users_list(_user_id=nil)\n #raise StandardError, \"APUL caller #{caller_method_name} user #{_user_id}\"\n return {} unless is_app_token?\n semaphore.synchronize {\n @apps_permissions_users_list ||= (\n r = get('/api/apps.permissions.users.list').parsed\n r['resources'].to_a.inject({}){|h,i| h[i['id']] = i; h} || {}\n )\n _user_id ? @apps_permissions_users_list[_user_id].to_h['scopes'] : @apps_permissions_users_list\n }\n end", "def scope\n @scope ||= Array(@root_scope) + [Inflector.underscore(name)]\n end", "def findProjectPermissions(workspace, user)\n query_result = @rally.find(:project_permission, :fetch => true, :pagesize => 100) {\n equal :\"user.login_name\", user.login_name\n }\n \n projectPermissions = []\n query_result.each { |pp|\n if ( pp.project.workspace == workspace)\n projectPermissions.push(pp)\n end\n }\n projectPermissions\n end", "def get_apps(scope)\n\t\tcase scope\n\t\twhen :added\n\t\t\treturn ClientApplication.select(\"client_applications.*\").\n\t\t\tjoins(:oauth_tokens).\n\t\t\twhere(\"oauth_tokens.invalidated_at is null and oauth_tokens.authorized_at is not null and oauth_tokens.type = 'AccessToken'\").\n\t\t\twhere(\"client_applications.id = oauth_tokens.client_application_id and oauth_tokens.user_id = #{id}\").\n\t\t\tgroup(\"client_applications.id\").\n\t\t\torder(\"oauth_tokens.authorized_at DESC\")\n\t\t\n\t\twhen :created\n\t\t\treturn apps\n\t\tend\n\tend", "def current_user_scope\n current_user\n end", "def resource_role_scopes\n return @resource_role_scopes\n end", "def dom_scopes\n return [@saved_dom_id] if @dom_scope && @saved_dom_id\n if @up\n scopes = @up.dom_scopes\n if @dom_scope\n (scopes.empty? ? [dom_prefix] : scopes) + [make_scope_id]\n else\n scopes\n end\n else\n @dom_scope ? [dom_prefix, make_scope_id] : []\n end\n end", "def params_auth_hash\n if params[scope].kind_of?(Hash) && params[scope].has_key?(authentication_keys.first)\n params[scope]\n else\n params\n end\n end", "def resource_role_scopes=(value)\n @resource_role_scopes = value\n end", "def all\n if current_scope\n current_scope.clone\n else\n default_scoped\n end\n end", "def get_favorite favoritable, options = {}\n if options.key?(:multiple_scopes) == false\n options[:parameter] = favoritable\n validate_scopes __method__, options\n elsif options[:multiple_scopes] == true\n results = {}\n options[:scope].each do |scope|\n results[scope] = favorites.unblocked.send(scope + '_list').for_favoritable(favoritable).first\n end\n return results\n else\n return favorites.unblocked.send(options[:scope] + '_list').for_favoritable(favoritable).first\n end\n end", "def list_scope(field)\n scope_field = self.class.mongoid_list_fields[field][:scope]\n scope_field ? self.class.where(scope_field => self[scope_field]) : self.class.all\n end", "def expand(scopes)\n scopes = Array(scopes.to_a)\n registered_scopes = scopes.filter { |sc| @mapping.key?(sc) }\n result = registered_scopes + registered_scopes.reduce([]) { |memo, sc|\n memo + Array(@mapping.fetch(sc))\n }.uniq\n\n Scopes.wrap(result)\n end", "def aggregate scope\n # TODO fucking slow\n data = {}\n data[:sha] = self.sha\n data[:short_sha] = self.short_sha\n data[:author_name] = self.author.name\n data[:author_email] = self.author.email\n data[:time] = self.time.xmlschema\n data[:message] = self.message\n data[:stats] = self.stats\n if scope == :single\n data[:project] = {}\n data[:current_branch] = @project.branchname\n data[:project][:path] = @project.path\n data[:project][:name] = @project.name\n data[:project][:remotes] = @project.remotes.map(&:name)\n data[:project][:remote_urls] = @project.remotes.map(&:url)\n data[:project][:remote_branches] = @project.remote_branches\n data[:project][:identifier] = self.project_identifier\n end\n data\n end", "def boolean_scopes\n @boolean_scopes ||= scopes.inject({}) do |result, element|\n result[element.first] = element.last if element.last[:type] == :boolean\n result\n end\n end", "def oauth2_scope(value = nil)\n rw_config(:oauth2_scope, value, '')\n end", "def index\n @user_workspaces = UserWorkspace.owned_by(current_user)\n end", "def scope\n return !@scopes.empty? ? @scopes[-1] : @storage[:scope]\n end", "def subsets_scopes\n @subsets_scopes\n end", "def user_credentials_for(scope)\n FileUtils.mkdir_p(File.dirname(token_store_path))\n\n if ENV['GOOGLE_CLIENT_ID']\n client_id = Google::Auth::ClientId.new(ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'])\n else\n client_id = Google::Auth::ClientId.from_file(client_secrets_path)\n end\n token_store = Google::Auth::Stores::FileTokenStore.new(:file => token_store_path)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)\n\n user_id = options[:user] || 'default'\n\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n say \"Open the following URL in your browser and authorize the application.\"\n say url\n code = ask \"Enter the authorization code:\"\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\n end", "def policy_scopes; end", "def validate_scopes\n @original_scopes = @original_scopes || server.jwt['scope']\n return true unless @original_scopes\n ScopeChecker.valid?(scope_str: @original_scopes, server_scopes: configuration.scopes, app_scopes: client.try(:scopes))\n end", "def scope\n scope!(operator) if @scopes.empty?\n scope!(\"AND\") if @scopes.last.is_a?(NestedScope)\n @scopes.last\n end", "def user_scope\n User.includes(:notification_settings)\n end", "def generate_scopes_list(frame_id)\n # Unfortunately we can only respond to Frame 0 as we don't have the variable state in other stack frames\n return [] unless frame_id.zero?\n\n result = []\n\n this_scope = puppet_session_state.saved.scope\n # rubocop:disable Lint/Void Go home rubocop, you're drunk.\n until this_scope.nil? || this_scope.is_topscope?\n result << DSP::Scope.new.from_h!(\n 'name' => this_scope.to_s,\n 'variablesReference' => this_scope.object_id,\n 'namedVariables' => this_scope.to_hash(false).count,\n 'expensive' => false\n )\n this_scope = this_scope.parent\n end\n # rubocop:enable Lint/Void\n\n unless puppet_session_state.actual.compiler.nil?\n result << DSP::Scope.new.from_h!(\n 'name' => puppet_session_state.actual.compiler.topscope.to_s,\n 'variablesReference' => VARIABLES_REFERENCE_TOP_SCOPE,\n 'namedVariables' => puppet_session_state.actual.compiler.topscope.to_hash(false).count,\n 'expensive' => false\n )\n end\n result\n end", "def define_all_scopes\n if self.resource_definition[\"scopes\"]\n self.resource_definition[\"scopes\"].each_pair do |name, opts|\n self.scope(name, opts)\n end\n end\n true\n end", "def expand_scopes(scopes)\n scopes.map do |scope|\n [scope, descendents(scope)]\n end.flatten.uniq.sort\n end", "def stradivari_scopes\n @_stradivari_scopes ||= {}\n end", "def favorites_count options = {}\n if options.key?(:multiple_scopes) == false\n validate_scopes __method__, options\n elsif options[:multiple_scopes] == true\n raise options.to_s\n results = {}\n options[:scope].each do |scope|\n results[scope] = Favorite.unblocked.send(scope + '_list').for_favoritor(self).count\n end\n return results\n else\n return Favorite.unblocked.send(options[:scope] + '_list').for_favoritor(self).count\n end\n end", "def scopes\n ENV.fetch('SCOPES', 'store_v2_products')\nend", "def merge(new_scopes); end", "def get_named_scope_info(klass)\n klass.respond_to?(:scopes) ? klass.scopes.keys.map(&:to_s) : []\n end", "def custom_scope_get scope_name\n\t\t\tThread.current[SESSION].custom_scope_get scope_name\n\t\tend", "def scope\n @scope.dup\n end", "def ransackable_scopes(_auth_object = nil)\n %i(grades)\n end", "def auth_options\n { scope: resource_name }\n end", "def default_scopes(*scopes)\n @config.instance_variable_set(:@default_scopes, OAuth::Scopes.from_array(scopes))\n end", "def reduce_scope_by_authorization(scope)\n return scope unless must_match_user_roles?\n scope.scoped_by_user_roles allowed_roles, match_roles_on\n end", "def scope_name; end", "def role_contexts\n auth_scope do\n send(permission_role_plural_key).group(:context_type, :context_id).map(&:context)\n end\n end", "def get_relations_of_workspace_and_user(wid)\n get \"/workspaces/#{wid}/workspace_users\"\n end", "def devise_scope(scope); end", "def scope\n @scope ||= {}\n end", "def scope\n @scope ||= {}\n end", "def all_favorited(options = {})\n if options.key?(:multiple_scopes) == false\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n results[scope] = all_favorites(options).collect(&:favoritable)\n end\n results\n else\n all_favorites(options).collect(&:favoritable)\n end\n end", "def sufficent_scope?(req_scopes)\n if req_scopes.blank?\n # if no any scopes required, the scopes of token is sufficient.\n true\n else\n # If there are scopes required, then check whether\n # the set of authorized scopes is a superset of the set of required scopes\n required_scopes = Set.new(req_scopes)\n authorized_scopes = Set.new(scopes)\n\n authorized_scopes >= required_scopes\n end\n end", "def scope\n read_attr :scope, :to_sym\n end" ]
[ "0.6774902", "0.67735314", "0.67023057", "0.66939336", "0.66305935", "0.64769953", "0.64670205", "0.6418563", "0.6394966", "0.6382104", "0.6324182", "0.63023543", "0.6266658", "0.6254284", "0.6243248", "0.6169198", "0.6147463", "0.60793805", "0.6078875", "0.6004791", "0.5984675", "0.5911262", "0.590638", "0.5898933", "0.5898783", "0.58876705", "0.5857843", "0.5816015", "0.57766795", "0.57766795", "0.5773413", "0.5756907", "0.5749648", "0.5712218", "0.5687714", "0.56787366", "0.5675357", "0.5646216", "0.55974746", "0.5588651", "0.5588651", "0.55857325", "0.55747133", "0.55344045", "0.5525177", "0.5484408", "0.5484408", "0.5477264", "0.5465761", "0.5437396", "0.54075724", "0.54071563", "0.5404864", "0.5374231", "0.53707916", "0.5366891", "0.53401726", "0.5320829", "0.531992", "0.5314951", "0.53033584", "0.5300883", "0.528484", "0.5272414", "0.52639955", "0.52620935", "0.5260049", "0.525316", "0.5248364", "0.52469105", "0.5241969", "0.522235", "0.5219347", "0.52131325", "0.52029955", "0.519962", "0.51963145", "0.5188233", "0.518413", "0.51828694", "0.5181765", "0.51701516", "0.5165987", "0.5135642", "0.51331234", "0.5132354", "0.5125835", "0.512461", "0.5120975", "0.5106306", "0.51028645", "0.5100928", "0.51002824", "0.5097132", "0.5091373", "0.50739366", "0.50739366", "0.5046864", "0.50417715", "0.50348014" ]
0.74947
0
Determine if given scopes exist in current authorization. Scopes is hash where key == scope type val == array or string of individual scopes.
def has_scope?(**scopes_hash) scopes_hash.detect do |section, scopes| test_scopes = case when scopes.is_a?(String); scopes.split(',') when scopes.is_a?(Array); scopes else raise "Scope must be a string or array" end test_scopes.detect do |scope| all_scopes[section.to_s].to_a.include?(scope.to_s) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def has_any_scope?(*scopes)\n return true if scopes.empty?\n Array(scopes.flatten).any?{ |scope| self.scopes.include?(scope) }\n end", "def has_scope?(*scopes)\n return true if scopes.empty?\n Array(scopes.flatten).none?{ |scope| !self.scopes.include?(scope) }\n end", "def acceptable?(scopes)\n accessible? && includes_scope?(*scopes)\n end", "def sufficent_scope?(req_scopes)\n if req_scopes.blank?\n # if no any scopes required, the scopes of token is sufficient.\n true\n else\n # If there are scopes required, then check whether\n # the set of authorized scopes is a superset of the set of required scopes\n required_scopes = Set.new(req_scopes)\n authorized_scopes = Set.new(scopes)\n\n authorized_scopes >= required_scopes\n end\n end", "def present_in?(token_scopes)\n required_scopes = Set.new(to_array(scopes))\n authorized_scopes = Set.new(to_array(token_scopes))\n\n authorized_scopes >= required_scopes\n end", "def includes_scope? required_scope\n missing_scope = Google::Auth::ScopeUtil.normalize(required_scope) -\n Google::Auth::ScopeUtil.normalize(scope)\n missing_scope.empty?\n end", "def includes_scope? required_scope\n missing_scope = Google::Auth::ScopeUtil.normalize(required_scope) -\n Google::Auth::ScopeUtil.normalize(scope)\n missing_scope.empty?\n end", "def has_scope?( scope )\n scope_names.include?( scope )\n end", "def scopes_match?(token_scopes, param_scopes, app_scopes)\n return true if token_scopes.empty? && param_scopes.empty?\n\n (token_scopes.sort == param_scopes.sort) &&\n Doorkeeper::OAuth::Helpers::ScopeChecker.valid?(\n scope_str: param_scopes.to_s,\n server_scopes: Doorkeeper.config.scopes,\n app_scopes: app_scopes,\n )\n end", "def in_scope?(request_scope)\n [*request_scope].all?(&scopes.method(:include?))\n end", "def has_scope?(scope)\n access_token && access_token.scopes.include?(scope)\n end", "def scope(*scopes)\n return if scopes.empty?\n\n unauthorized message: 'User must me authorized' unless current_user\n forbidden messages: 'Not all scope expectations are matched' unless\n current_user.grants_scope?(*scopes)\n end", "def has_scope(scope_group, *scopes)\n options = scopes.extract_options!\n options.symbolize_keys!\n options.assert_valid_keys(:type, :if, :unless, :default, :as, :using, :allow_blank)\n\n if options.key?(:using)\n if options.key?(:type) && options[:type] != :hash\n raise \"You cannot use :using with another :type different than :hash\"\n else\n options[:type] = :hash\n end\n\n options[:using] = [*options[:using]]\n end\n\n self.scopes_configuration ||= {}\n self.scopes_configuration[scope_group] ||= {}\n\n scopes.each do |scope|\n self.scopes_configuration[scope_group][scope] ||= {\n :as => scope,\n :type => :default\n }\n self.scopes_configuration[scope_group][scope].merge!(options)\n end\n end", "def authorize_scopes\n scopes = Array(Rack::Utils.parse_query(request.query_string)[\"scope\"])\n return if scopes.empty?\n\n auth_scopes = {}\n\n # First try to fetch the requested scopes and the handler. If no scopes\n # were successfully given, respond with a 401.\n scopes.each do |scope|\n auth_scope, actions = scope_handler(scope)\n\n actions.each do |action|\n # It will try to check if the current user is authorized to access the\n # scope given in this iteration. If everything is fine, then nothing will\n # happen, otherwise there are two possible exceptions that can be raised:\n #\n # - NoMethodError: the targeted resource does not handle the scope that\n # is being checked. It will raise a ScopeNotHandled.\n # - Pundit::NotAuthorizedError: the targeted resource unauthorized the\n # given user for the scope that is being checked. In this case this\n # scope gets removed from `auth_scope.actions`.\n begin\n authorize auth_scope.resource, \"#{action}?\".to_sym\n rescue Portus::AuthScope::NamespaceNotSupport, NoMethodError, Pundit::NotAuthorizedError, Portus::AuthScope::ResourceNotFound => e\n logger.debug e\n logger.debug \"action #{action} not handled/authorized, removing from actions\"\n auth_scope.actions.delete_if { |a| match_action(action, a) }\n end\n end\n\n next if auth_scope.actions.empty?\n # if there is already a similar scope (type and resource name),\n # we combine them into one:\n # e.g. scope=repository:busybox:push&scope=repository:busybox:pull\n # -> access=>[{:type=>\"repository\", :name=>\"busybox\", :actions=>[\"push\", \"pull\"]}\n k = [auth_scope.resource_type, auth_scope.resource_name]\n if auth_scopes[k]\n auth_scopes[k].actions.concat(auth_scope.actions).uniq!\n else\n auth_scopes[k] = auth_scope\n end\n end\n auth_scopes.values\n end", "def has_scopes(*scopes)\n self.scope_class_methods = self.scope_class_methods +\n Array.wrap(scopes).map(&:to_sym)\n end", "def valid_for?(access_token)\n scopes.empty? || present_in?(access_token.scopes)\n end", "def validate_scopes\n @original_scopes = @original_scopes || server.jwt['scope']\n return true unless @original_scopes\n ScopeChecker.valid?(scope_str: @original_scopes, server_scopes: configuration.scopes, app_scopes: client.try(:scopes))\n end", "def define_all_scopes\n if self.resource_definition[\"scopes\"]\n self.resource_definition[\"scopes\"].each_pair do |name, opts|\n self.scope(name, opts)\n end\n end\n true\n end", "def scopes\n params['scope']\n end", "def authorize_scopes\n @authorize_scopes ||= (env['omniauth.params']['scope'] || authorize_params['scope']).split(' ')\n end", "def verify_scope(scope)\n self.user_scope.each do |sym|\n raise RuntimeError, \"Expected to be passed a scope containing the key '#{sym.to_s}'\" unless scope.has_key? sym\n end\n scope\n end", "def oauth2_scopes(*scopes)\n @oauth2_scope_perms = scopes.map{|i| i.to_s}\n end", "def scopes\n @scopes ||= {}\n end", "def dynamic_scopes\n self.scopes.select { |name, args| args.present? }\n end", "def scopes\n env['HTTP_X_AUTHENTICATED_SCOPE'].to_s.split(',')\n end", "def scopes\n read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})\n end", "def valid_scope(valid_scopes, scope)\n\t\tend", "def nil_in_scope?(scope, key)\n if scope.is_a?(Hash)\n scope.include?(key)\n else\n scope.exist?(key)\n end\n end", "def scopes\n @scopes ||= config[:scopes] || []\n end", "def available_scopes\n (default_scopes << Doorkeeper.config.optional_scopes.to_a).flatten.uniq\n end", "def scopes\n scope ? [scope] : []\n end", "def all_scopes\n @all_scopes ||=\n {'identity' => (auth['scope'] || apps_permissions_users_list[user_id].to_h['scopes'].to_a.join(',')).to_s.split(',')}\n .merge(auth['scopes'].to_h)\n end", "def scopes\n scope_names.to_a.sort\n end", "def valid_scope?\n scope.to_s == self.class.scope.to_s\n end", "def dynamic_scopes\n self.scope_definition.select { |_k, v| v.present? }\n end", "def scopes\n @@scopes ||= {}\n end", "def authorize_scopes(registry)\n return unless params[:scope]\n\n auth_scope, scopes = scope_handler(registry, params[:scope])\n raise Pundit::NotAuthorizedError, \"No scopes to handle\" if scopes.empty?\n\n scopes.each do |scope|\n begin\n authorize auth_scope.resource, \"#{scope}?\".to_sym\n rescue NoMethodError\n logger.warn \"Cannot handle scope #{scope}\"\n raise ScopeNotHandled, \"Cannot handle scope #{scope}\"\n end\n end\n\n auth_scope\n end", "def check_required_scope_args(scope, params)\n # make sure we have a hash and it has values\n return false unless params.is_a?(Hash) && params.present?\n # find required values\n required = scope.select{ |k,v| v.to_sym == :req }.keys\n # make sure we have all of the required values, we allow false\n required.all? { |key|\n params[key].present? || params[key] == false\n }\n end", "def authorized?(scope = @config.default_scope)\n result = !!permissions(scope)\n yield if block_given? && result\n result\n end", "def scopes\n scopes = scope ? scope.split(/\\s+/) : []\n scopes = attributes[:scope]\n Set.new(scopes).to_s\n end", "def favorites_scoped options = {}\n if options.key?(:multiple_scopes) == false\n validate_scopes __method__, options\n elsif options[:multiple_scopes] == true\n results = {}\n options[:scope].each do |scope|\n results[scope] = favorites.unblocked.send(scope + '_list').includes :favoritable\n end\n return results\n else\n return favorites.unblocked.send(options[:scope] + '_list').includes :favoritable\n end\n end", "def favorites_scoped(options = {})\n if options.key?(:multiple_scopes) == false\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n results[scope] = favorites.unblocked.send(scope + '_list')\n .includes(:favoritable)\n end\n results\n else\n favorites.unblocked.send(options[:scope] + '_list')\n .includes(:favoritable)\n end\n end", "def blocked?(favoritable, options = {})\n if options.key?(:multiple_scopes) == false\n options[:parameter] = favoritable\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n results[scope] = Favorite.blocked.send(scope + '_list')\n .for_favoritor(self)\n .for_favoritable(favoritable).count\n .positive?\n end\n results\n else\n Favorite.blocked.send(options[:scope] + '_list').for_favoritor(self)\n .for_favoritable(favoritable).count.positive?\n end\n end", "def optional_scopes(*scopes)\n @config.instance_variable_set(:@optional_scopes, OAuth::Scopes.from_array(scopes))\n end", "def has_permission? *perms\n permissions.map(&:name).includes_all? *perms\n end", "def _find_non_empty_scope(type, local_scope, *additional_possibilities)\n found = [\n local_scope[:\"#{type}s\"],\n [local_scope[type.to_sym]],\n ::Guard.scope[:\"#{type}s\"],\n additional_possibilities.flatten\n ]\n found.compact.detect { |a| !Array(a).compact.empty? }\n end", "def scope_from_params(params)\n return default_scope if params[:scope].blank?\n scope = params[:scope].is_a?(Array) ? params[:scope] : params[:scope].split(',')\n scope = scope.map(&:downcase).map(&:strip)\n return scope & default_scope\n end", "def all_scopes(_user_id=nil)\n debug{\"_user_id: #{_user_id}, @all_scopes: #{@all_scopes}\"}\n if _user_id && !@all_scopes.to_h.has_key?('identity') || @all_scopes.nil?\n @all_scopes = (\n scopes = case\n when params['scope']\n {'classic' => params['scope'].words}\n when params['scopes']\n params['scopes']\n when is_app_token?\n apps_permissions_scopes_list\n end\n \n scopes['identity'] = apps_permissions_users_list(_user_id) if _user_id && is_app_token?\n params['scopes'] = scopes\n )\n else\n @all_scopes\n end\n end", "def is_sphinx_scope?(scope_name)\n klass.sphinx_scopes.include?(scope_name.to_sym)\n end", "def exists?(path)\n !!scope.get(path)\n end", "def verify_token_and_scope(token, scope)\n response = get_token_response(token, ENV['TOKEN_ENDPOINT'])\n unless response.code.to_i == 200\n raise ForbiddenError.new\n end\n\n response_hash = CGI.parse(response.parsed_response)\n if response_hash.key?('scope') && response_hash['scope'].is_a?(Array)\n scopes = response_hash['scope'][0].split(' ')\n return if scopes.include?(scope)\n # if we want to post and are allowed to create then go ahead\n return if scope == 'post' && scopes.include?('create')\n end\n raise InsufficientScope.new\n end", "def scoped?\n !!scope\n end", "def valid?\n\n auth_params = params[scope]\n return false if !auth_params\n\n (nimbus_auth(auth_params)&.code == 200) ? true : false\n end", "def able_to_any?(*required_permissions)\n perms = required_permissions.map(&:to_sym)\n permissions.any? do |p| \n perms.include?(p.name.to_sym) \n end\n end", "def place_in_scope?(place)\n return false unless place.present?\n @place_ids ||= area.place_ids - exclusions + inclusions\n return true if place.persisted? && @place_ids.include?(place.id)\n political_location = Place.political_division(place).join('/').downcase\n locations.any? { |location| political_location.include?(location.path) }\n end", "def boolean_scopes\n @boolean_scopes ||= scopes.inject({}) do |result, element|\n result[element.first] = element.last if element.last[:type] == :boolean\n result\n end\n end", "def valid_for_scope?(update_params)\n return true if dynamic_scaffold.scope_options[:changeable]\n\n result = true\n scope_params.each do |key, value|\n if update_params.key?(key) && update_params[key] != value\n result = false\n break\n end\n end\n result\n end", "def scoped?\n @scope_block.present? || enabled_dependencies.any? { |d| dependency_scoped?(d) }\n end", "def parse_scopes(data)\n scopes = []\n scopes << data['scope'] if data['scope'] # If there is only one scope\n\n i = 0\n while (data[\"scope(#{i})\"]) do\n scopes << data[\"scope(#{i})\"]; i = i + 1\n end # For multiple scopes\n\n # Convert to symbols\n scopes.collect { |paypal_scope| PERMISSIONS.select { |k,val| val == paypal_scope }.keys.first }\n end", "def favorites_count options = {}\n if options.key?(:multiple_scopes) == false\n validate_scopes __method__, options\n elsif options[:multiple_scopes] == true\n raise options.to_s\n results = {}\n options[:scope].each do |scope|\n results[scope] = Favorite.unblocked.send(scope + '_list').for_favoritor(self).count\n end\n return results\n else\n return Favorite.unblocked.send(options[:scope] + '_list').for_favoritor(self).count\n end\n end", "def in_subsets_scope? name\n self.class.subsets_scope(name).include? subset.to_sym\n end", "def has_named_scope?(name)\n scope_proxy.has_named_scope?(name)\n end", "def defined?( path, limit_scope = false )\n value = resolve( path, limit_scope )\n return value.exists?\n end", "def can? (*perms)\n perms.each {|p| return false if authorize(p).nil?}\n return true\n end", "def all_favorites options = {}\n if options.key?(:multiple_scopes) == false\n validate_scopes __method__, options\n elsif options[:multiple_scopes] == true\n results = {}\n options[:scope].each do |scope|\n favorites_scope = favorites_scoped scope\n results[scope] = favorites_scope = apply_options_to_scope favorites_scope, options\n end\n return results\n else\n favorites_scope = favorites_scoped options[:scope]\n return favorites_scope = apply_options_to_scope(favorites_scope, options)\n end\n end", "def signed_in?(scope)\n warden.authenticate?(:scope => scope)\n end", "def ransackable_scopes(_auth_object = nil)\n %i(grades)\n end", "def scopes_for(token)\n token = token.github_oauth_token if token.respond_to? :github_oauth_token\n scopes = GH.with(token: token.to_s) { GH.head('user') }.headers['x-oauth-scopes'] if token.present?\n scopes &&= scopes.gsub(/\\s/,'').split(',')\n Array(scopes).sort\n rescue GH::Error\n []\n end", "def add_scopes(params, base = self)\n # scopes are stored as strings but we want to allow\n params = params.with_indifferent_access\n base = self.add_static_scopes(params, base)\n return self.add_dynamic_scopes(params, base)\n end", "def valid_scope_name?(name)\n if scopes[name] || respond_to?(name, true)\n if Mongoid.scope_overwrite_exception\n raise Errors::ScopeOverwrite.new(self.name,name)\n else\n if Mongoid.logger\n Mongoid.logger.warn(\n \"Creating scope :#{name}. \" +\n \"Overwriting existing method #{self.name}.#{name}.\"\n )\n end\n end\n end\n end", "def scopes_from(request)\n return nil if request.scope.nil?\n\n Array(request.scope).join(' ')\n end", "def static_scopes\n scopes = self.scope_definition\n .select { |_k, v| v.blank? }\n .keys\n scopes | [:first, :last, :all]\n end", "def reduce_scope_by_authorization(scope)\n return scope unless must_match_user_roles?\n scope.scoped_by_user_roles allowed_roles, match_roles_on\n end", "def scope_info\n if is_scoped? && scoped_manual.present?\n {\n \"scope\" => {\n \"title\" => scoped_manual.to_hash.fetch(\"title\", \"\"),\n },\n \"unscoped_results\" => unscoped_results,\n }\n else\n {}\n end\n end", "def ransackable_scopes(auth_object = nil)\n []\n end", "def scope?\n # context = Ransack::Context.for klass\n # context.respond_to?(:ransackable_scope?) && context.ransackable_scope?(method.to_s, klass)\n false\n end", "def valid?\n filter_group_list = @user_key.whitelists.restrict_to(@resource).to_a.map{|w| w.filters.to_a}\n # If the key has no whitelists at all, the key has no access through normal filters.\n # (If the key has no columns, the key has no access at all, but we check for that in EndpointResponse.)\n # Map the filters for each individual whitelist into a list to be checked.\n return true if filter_group_list.any? { |fg| matches_options? fg }\n\n # No filters were matched, so check for organizations instead.\n return has_valid_organization_id?\n end", "def is_authorized_for(context)\n\tresult = shared_data_contexts.find_all{|item| item.name == context }\t\n\treturn result != nil && result.length > 0 \n end", "def expand(scopes)\n scopes = Array(scopes.to_a)\n registered_scopes = scopes.filter { |sc| @mapping.key?(sc) }\n result = registered_scopes + registered_scopes.reduce([]) { |memo, sc|\n memo + Array(@mapping.fetch(sc))\n }.uniq\n\n Scopes.wrap(result)\n end", "def all_associations_exist?(association_names)\n\t\t\t\tassociation_names.all? do |name| \n\t\t\t\t\tfound_reflection = find_reflection( extract_association(name) )\n\t\t\t\t\tfound_reflection && !(name.to_s.include?(\"_id\") && (found_reflection.macro == :belong_to) ) # TODO very hacky, make it work together with rails scoped_by\n\t\t\t\tend\n\t\t\tend", "def scopes\n @scope.scopes\n end", "def scope(scope_name, scope_enum_keys)\n target_enum = @record_class.defined_enums[@enum_name.to_s]\n sub_enum_values = target_enum.values_at(*scope_enum_keys)\n\n if @record_class.defined_enum_scopes.has_key?(scope_name)\n fail ArgumentError,\n \"Conflicting scope names. A scope named #{scope_name} has already been defined\"\n elsif sub_enum_values.include?(nil)\n unknown_key = scope_enum_keys[sub_enum_values.index(nil)]\n fail ArgumentError, \"Unknown key - #{unknown_key} for enum #{@enum_name}\"\n elsif @record_class.respond_to?(scope_name.to_s.pluralize)\n fail ArgumentError,\n \"Scope name - #{scope_name} conflicts with a class method of the same name\"\n elsif @record_class.instance_methods.include?(\"#{scope_name}?\".to_sym)\n fail ArgumentError,\n \"Scope name - #{scope_name} conflicts with the instance method - #{scope_name}?\"\n end\n\n sub_enum_entries = target_enum.slice(*scope_enum_keys)\n @record_class.defined_enum_scopes[scope_name] = sub_enum_entries\n\n # 1. Instance method <scope_name>?\n @record_class.send(:define_method, \"#{scope_name}?\") { sub_enum_entries.include? self.role }\n\n # 2. The class scope with the scope name\n @record_class.scope scope_name.to_s.pluralize,\n -> { @record_class.where(\"#{@enum_name}\" => sub_enum_entries.values) }\n\n @scope_names << scope_name\n end", "def has_permissions(allowed_permissions)\n #example usage: has_permissions({ \"User\"=>{\"actions\"=>[\"read\",\"update\",\"manage\"], \"action_scope\"=>[\"company\"]}, \"all\"=>{\"actions\"=>[\"read\",\"update\",\"manage\"]} })\n #allowed_permissions (hash) example: allowed_permissions = \"User\"=>{\"actions\"=>[\"read\",\"update\",\"manage\"], \"action_scope\"=>[\"company\"]}, \"all\"=>{\"actions\"=>[\"read\",\"update\",\"manage\"]}\n #Note: Hash \"actions\" and \"action_scope\" can be string or an array. And \"action_scope\" is an optional parameter.\n\n #check allowed_permissions is not empty\n unless allowed_permissions.empty?\n allowed_permissions.each do | permission_key, allowed_permission |\n subject_class = permission_key\n action = allowed_permission[\"actions\"]\n action_scope = allowed_permission[\"action_scope\"]\n\n return true if has_permission(subject_class, action, action_scope) == true\n end\n end #unless allowed_permissions.empty?\n\n false\n end", "def favorites_count(options = {})\n if options.key?(:multiple_scopes) == false\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n results[scope] = Favorite.unblocked.send(scope + '_list')\n .for_favoritor(self).count\n end\n results\n else\n Favorite.unblocked.send(options[:scope] + '_list')\n .for_favoritor(self).count\n end\n end", "def scopes; end", "def uses_defn?(scope)\n if scope.iter? or scope.module?\n true\n elsif scope.class? and %w(Object BasicObject).include?(scope.name)\n true\n else\n false\n end\n end", "def all_favorited(options = {})\n if options.key?(:multiple_scopes) == false\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n results[scope] = all_favorites(options).collect(&:favoritable)\n end\n results\n else\n all_favorites(options).collect(&:favoritable)\n end\n end", "def resource_scopes=(value)\n @resource_scopes = value\n end", "def resource_scopes=(value)\n @resource_scopes = value\n end", "def can_grant_api_to_orgs?\n perms.include? Perm.grant_api\n end", "def can_grant_api_to_orgs?\n perms.include? Perm.grant_api\n end", "def application_scope?\n not session_scope?\n end", "def stradivari_scopes\n @_stradivari_scopes ||= {}\n end", "def invalid_scope?\n ! valid_scope?\n end", "def favorited_type(favoritable, options = {})\n if options.key?(:multiple_scopes) == false\n options[:parameter] = favoritable\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n if Favorite.unblocked.send(scope + '_list').for_favoritor(self)\n .for_favoritable(favoritable).count.positive?\n results[scope] = true\n elsif Favorite.blocked.send(scope + '_list').for_favoritor(self)\n .for_favoritable(favoritable).count.positive?\n results[scope] = false\n else\n results[scope] = nil\n end\n end\n results\n elsif Favorite.unblocked.send(options[:scope] + '_list')\n .for_favoritor(self).for_favoritable(favoritable).count\n .positive?\n true\n elsif Favorite.blocked.send(options[:scope] + '_list')\n .for_favoritor(self).for_favoritable(favoritable).count\n .positive?\n false\n end\n end", "def all_favorites(options = {})\n if options.key?(:multiple_scopes) == false\n validate_scopes(__method__, options)\n elsif options[:multiple_scopes]\n results = {}\n options[:scope].each do |scope|\n favorites_scope = favorites_scoped(\n scope: scope, multiple_scopes: false\n )\n results[scope] = apply_options_to_scope(\n favorites_scope, options\n )\n end\n results\n else\n favorites_scope = favorites_scoped(\n scope: options[:scope], multiple_scopes: false\n )\n apply_options_to_scope(\n favorites_scope, options\n )\n end\n end", "def scopes\n self.class.scopes\n end", "def replace_scopes(*scopes)\n uris = ensure_and_get_uris(scopes.flatten)\n patch('replace', '/scopeUris', uris)\n end", "def key_exists?(path, scope)\n begin\n Win32::Registry::scope.open(path, ::Win32::Registry::KEY_READ)\n return true\n rescue\n return false\n end\n end", "def key_exists?(path, scope)\n begin\n Win32::Registry::scope.open(path, ::Win32::Registry::KEY_READ)\n return true\n rescue\n return false\n end\n end" ]
[ "0.7910931", "0.7870426", "0.76238036", "0.75419444", "0.7368402", "0.7138306", "0.7138306", "0.7121337", "0.70674014", "0.6865917", "0.6765733", "0.6726917", "0.6719299", "0.662583", "0.6595154", "0.6591353", "0.6482237", "0.6383847", "0.62659955", "0.62583", "0.61807144", "0.6023947", "0.6020812", "0.60048306", "0.5977824", "0.5936591", "0.5933526", "0.58853185", "0.58771485", "0.5864972", "0.5862415", "0.58360654", "0.58328134", "0.5796467", "0.57776546", "0.5747721", "0.5739532", "0.5676376", "0.567323", "0.5659993", "0.56119615", "0.5584479", "0.55641985", "0.5555169", "0.5553948", "0.55116946", "0.5509036", "0.5464278", "0.53990173", "0.5392898", "0.53605044", "0.53287023", "0.5318919", "0.53008157", "0.5290429", "0.52828777", "0.5251765", "0.5229095", "0.5227655", "0.51885825", "0.51785755", "0.5158985", "0.5149209", "0.51403654", "0.5137259", "0.5123483", "0.50926864", "0.50837934", "0.50755423", "0.50622755", "0.50598556", "0.5034924", "0.5025622", "0.5025073", "0.5023971", "0.5019881", "0.5010315", "0.50056285", "0.50015503", "0.49954814", "0.4993984", "0.4993939", "0.49867275", "0.49853206", "0.49807096", "0.49742192", "0.4966701", "0.49641517", "0.49641517", "0.49494144", "0.49494144", "0.49455917", "0.49331224", "0.49258995", "0.49252313", "0.4921411", "0.4920092", "0.49151102", "0.4906388", "0.4906388" ]
0.8136706
0
helper methods go here!
def get_item(item) @cache.each do |(k,v)| return [k, v] if v == item end nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def private; end", "def schubert; end", "def probers; end", "def suivre; end", "def weber; end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def who_we_are\r\n end", "def custom; end", "def custom; end", "def helpers; end", "def helpers; end", "def helpers; end", "def operations; end", "def operations; end", "def formation; end", "def identify; end", "def refutal()\n end", "def sitemaps; end", "def stderrs; end", "def terpene; end", "def common\n \n end", "def processor; end", "def strategy; end", "def implementation; end", "def implementation; end", "def relatorios\n end", "def villian; end", "def handle; end", "def extra; end", "def intensifier; end", "def zuruecksetzen()\n end", "def berlioz; end", "def anchored; end", "def apply\n\t\t\n\tend", "def apply\n\t\t\n\tend", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def rossini; end", "def trd; end", "def wrapper; end", "def parts; end", "def parts; end", "def parts; end", "def eplore\n end", "def verdi; end", "def hd\n \n end", "def appraisals; end", "def appraisals; end", "def post_process; end", "def guct\n end", "def transformations; end", "def checks; end", "def malts; end", "def retire\n\n end", "def process; end", "def process; end", "def process; end", "def process; end", "def process; end", "def process; end", "def process; end", "def process; end", "def methods; end", "def methods; end", "def methods; end", "def methods; end", "def internal; end", "def jack_handey; end", "def romeo_and_juliet; end", "def invention; end", "def operation; end", "def feruchemist; end", "def celebration; end", "def scientist; end", "def offences_by; end", "def isolated; end", "def isolated; end", "def apply\n\t\t\t\t\n\t\t\tend", "def methods() end", "def bs; end", "def order; end", "def order; end", "def r; end", "def r; end", "def how_it_works\r\n end", "def apis; end", "def sn\n end", "def details; end", "def private_method\n end", "def gounod; end", "def prepare_result; end" ]
[ "0.7287261", "0.66014576", "0.6562698", "0.6280189", "0.6234601", "0.62198305", "0.62198305", "0.62198305", "0.62198305", "0.61928034", "0.61432976", "0.61432976", "0.6137897", "0.6137897", "0.6137897", "0.6112013", "0.6112013", "0.6097403", "0.60813224", "0.6008863", "0.59900707", "0.59272474", "0.59196824", "0.587315", "0.58657706", "0.58496666", "0.5848236", "0.5848236", "0.5825295", "0.5798949", "0.5798702", "0.579515", "0.57676417", "0.57582897", "0.57513815", "0.57431597", "0.57373804", "0.57373804", "0.5719736", "0.5719736", "0.5719736", "0.5719736", "0.5719736", "0.5719736", "0.5719736", "0.5719736", "0.5719736", "0.5714352", "0.5698544", "0.56854033", "0.5682525", "0.5682525", "0.5682525", "0.5670434", "0.56640244", "0.56614", "0.56608903", "0.56608903", "0.5659861", "0.5615645", "0.5601332", "0.55873996", "0.557986", "0.5572516", "0.5564872", "0.5564872", "0.5564872", "0.5564872", "0.5564872", "0.5564872", "0.5564872", "0.5564872", "0.5552658", "0.5552658", "0.5552658", "0.5552658", "0.5547512", "0.55456793", "0.5525802", "0.5495278", "0.5492856", "0.54884446", "0.548381", "0.54818106", "0.5467665", "0.5465574", "0.5465574", "0.5461255", "0.5457162", "0.5451733", "0.54471004", "0.54471004", "0.54466283", "0.54466283", "0.5429606", "0.5426585", "0.5419248", "0.54045635", "0.53914887", "0.5390889", "0.53865963" ]
0.0
-1
some metaprogramming to simplify adding new fields
def method_missing(sym, *args, &block) str = sym.to_s matches = nil if str == "[]" str = args.shift elsif str == "[]=" str = "#{ args.shift }=" end if @@fields.include?(str) @hash[str] elsif matches = str.match(/(.*)=$/) and @@fields.include?(matches[1]) @hash[matches[1]] = args.first else super(sym, *args, &block) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_fields(fields)\n\t\tend", "def computed_fields; end", "def method_missing(meth, *args, &blk)\n super unless Fields.all.include?(meth)\n field meth, *args\n end", "def add_field(field)\n\t\tend", "def update_fields(fields)\n\n # Also consider extracting this common code between vendor and item to basic_data\n # instead of going through each attribute on self, iterate through each item in field and update from there\n self.attributes.each do |k, v|\n attributes[k.to_sym] = fields[SYMBOL_TO_STRING[k.to_sym]] || fields[k.to_sym] || attributes[k.to_sym]\n end\n\n attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]\n self\n end", "def define_field_methods\n if fields.is_a?(Array)\n fields.each do |field_label|\n field = field_label.downcase.gsub(' ', '_').gsub(/\\W/, '').to_sym\n field_method_name = define_field_name(field)\n define_field_method(field_method_name, field_label)\n end\n elsif fields.is_a?(Hash)\n fields.each do |field, field_string|\n field_method_name = define_field_name(field)\n define_field_method(field_method_name, field_string)\n end\n end\n end", "def method_missing method, *args, &block\n self.class.send(:define_method, method) do \n return @fields[method.to_sym]\n end\n self.send method, *args, &block\n end", "def add_field!(field_name, value = T.unsafe(nil)); end", "def add_field(name, options = {})\n # aliased = options[:as]\n # aliased_fields[aliased.to_s] = name if aliased\n field = field_for(name, options)\n fields[name] = field\n # add_defaults(field)\n create_accessors(name, name, options)\n # process_options(field)\n # create_dirty_methods(name, name)\n # create_dirty_methods(name, aliased) if aliased\n field\n end", "def field(ffield, length, sourcetag, default = nil, &block)\n @fields << {\n afield: ffield,\n length: length, \n stag: sourcetag,\n default: default,\n block: block\n }\n end", "def editable_attribute_names; super + additional_fields end", "def editable_attribute_names; super + additional_fields end", "def editable_attribute_names; super + additional_fields end", "def field(name); end", "def fields_for(record_or_name_or_array, *args, &block)\n options = args.extract_options!.merge(:builder => self.class)\n super(record_or_name_or_array, *(args + [options]), &block)\n end", "def update_fields(fields)\n\n # instead of going through each attribute on self, iterate through each item in field and update from there\n self.attributes.each do |k, v|\n attributes[k.to_sym] = fields[SYMBOL_TO_STRING[k.to_sym]] || fields[k.to_sym] || attributes[k.to_sym]\n end\n\n attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]\n self\n end", "def update_fields(fields)\n\n # instead of going through each attribute on self, iterate through each item in field and update from there\n self.attributes.each do |k, v|\n attributes[k.to_sym] = fields[SYMBOL_TO_STRING[k.to_sym]] || fields[k.to_sym] || attributes[k.to_sym]\n end\n\n attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]\n self\n end", "def update_fields(fields)\n\n # instead of going through each attribute on self, iterate through each item in field and update from there\n self.attributes.each do |k, v|\n attributes[k.to_sym] = fields[SYMBOL_TO_STRING[k.to_sym]] || fields[k.to_sym] || attributes[k.to_sym]\n end\n\n attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]\n self\n end", "def method_missing name, *args, &block\n if name.to_s =~ /^(.+)_fields$/\n self.fields.select {|f| f.data_type.to_s.parameterize.underscore == $1 } || super\n else \n super\n end\n end", "def add_methods_to_flex_column_class!(dynamic_methods_module)\n fn = field_name\n\n dynamic_methods_module.define_method(fn) do\n self[fn]\n end\n\n dynamic_methods_module.define_method(\"#{fn}=\") do |x|\n self[fn] = x\n end\n\n if private?\n dynamic_methods_module.private(fn)\n dynamic_methods_module.private(\"#{fn}=\")\n end\n end", "def iamswer_extra_fields *extra_fields\n @iamswer_defined_extra_fields ||= []\n\n extra_fields.each do |extra_field|\n @iamswer_defined_extra_fields << extra_field.to_sym\n define_extra_field extra_field\n end\n end", "def add_field!(field_name, value = nil)\n fields << Field.new({'name' => field_name}, value)\n end", "def fields(fields = {})\n fields.each do |k,v|\n define_accessor(k.underscore, v)\n end\n end", "def additional_fields; self.class.additional_fields end", "def additional_fields; self.class.additional_fields end", "def additional_fields; self.class.additional_fields end", "def pulp_special_fields(*fields)\n [*fields].each{|f| pulp_special_field(f) }\n end", "def initialize_field(key)\n class_name = model_class.properties[key.to_s].try(:class_name)\n return super unless class_name\n\n self[key] += [class_name.new]\n end", "def history_additionals_fields_mapping fields\n history_additionals_fields_mapping = fields.with_indifferent_access\n\n define_method(:history_additionals_fields_mapping) do\n history_additionals_fields_mapping\n end\n end", "def attr_reader(*fields)\n check_fields(fields)\n added_fields = jiak.data.readable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}\n @jiak.object.data.#{field}\n end\n EOM\n end\n nil\n end", "def update_field_property(source, property, fields=Hamster::Set[])\n field = source[property]\n # collect previous fields if present\n field.each do |value|\n # add previous fields\n fields = fields.add(value)\n end unless field.nil?\n # reassign fields\n source[property] = fields.to_a\n source\n end", "def method_missing(meth,*args,&block)\n\n method = meth.to_s # convert method name to a string\n setter = method.end_with?('=') # determine if this is a setter method (which would have the last character \"=\" in the method name)\n attribute = setter ? method.chop : method # the attribute name needs to have the \"=\" removed if it is a setter\n multivalued_field = attribute.end_with?(self.class.multivalued_field_marker) # in place editing fields can end with the special character marker, which will join arrays when return; and split them when setting\n attribute.gsub!(self.class.multivalued_field_marker,'') if multivalued_field\n\n solr_field_config=self.class.field_mappings[attribute.downcase.to_sym] # lookup the solr field for this accessor\n if solr_field_config\n solr_field_name=solr_field_config[:field].downcase\n default_value=solr_field_config[:default] || ''\n if setter # if it is a setter, cache the edit if it has changed\n old_values=self[solr_field_name]\n new_values=args.first\n if !self.class.is_equal?(old_values,new_values,multivalued_field) # we should only cache the edit if it actually changed\n value = (multivalued_field ? new_values.split(\"|\") : new_values) # split the values when setting if this is an in place edit field\n cache_edit({solr_field_name.to_sym=>value})\n return value\n else\n return old_values\n end\n else # if it is a getter, return the value\n value = unsaved_edits[solr_field_name.to_sym] || self[solr_field_name] # get the field value, either from unsaved edits or from solr document\n value = default_value if value.blank?\n return (multivalued_field && value.class == Array ? value.join(\" | \") : value) # return a joined value if this is an in place edit field, otherwise just return the value\n end\n else\n super # we couldn't find any solr fields configured, so just send it to super\n end\n\n end", "def set_fields(hash, keys=hash.keys)\n super hash, keys\n end", "def nillify_fields\n if self.rate_type == \"Per night\"\n self.number_of_guests = self.max_number_of_guests = nil\n end\n\n if self.rate == \"Rate Amount\"\n self.discount_type = self.discount_amount = nil\n elsif self.rate == \"Discount\"\n self.net_rate = self.commission_percent = nil\n end\n\n super\n end", "def method_missing field, *args, &block\n set field, *args, &block\n end", "def add_hstore_field_accessors\n self.item_category_attributes.pluck(:label).each do |field_name|\n add_store_accessor field_name\n end\n end", "def assign_custom_fields(key_name_hash, entity_hash)\n names = key_name_hash.map do |key, field|\n name = field.name\n name = name.underscore.gsub(' ','_')\n name = name.gsub('%','percent').gsub(/[^a-zA-Z0-9_]/,'')\n name = transform_field_name(key, name)\n if field.field_type == 'enum'\n option_id = entity_hash[key]\n res_field = field.dup\n res_field.option_id = option_id\n instance_variable_set(\"@#{name}\", res_field)\n else\n instance_variable_set(\"@#{name}\", entity_hash[key])\n end\n name\n end\n self.class.class_eval {attr_accessor *names}\n end", "def field(*fields)\n options = fields.extract_options!\n\n fields.each do |f|\n _field(f, options)\n end\n end", "def set_field(field_name, field_value)\n super field_name.to_s, field_value.to_s\n end", "def add_field_to_column_family(*args)\n new_field = self.class.add_field_to_column_family(*args)\n method = \"#{new_field.name}=\"\n send(method, new_field.default) if respond_to? method\n end", "def field(name)\n unless (@fields ||= []).include?(name)\n @fields << name\n\n # field reader\n define_method(name) do\n instance_variable_get(\"@%s\" % name)\n end\n\n # field writer\n define_method(\"%s=\" % name) do |val|\n val = Time.parse(val) if name == :timestamp and val.kind_of?(String)\n instance_variable_set(\"@%s\" % name, val)\n end\n end\n end", "def related_fields(method)\n \n end", "def check_for_new_fields(hash)\n if new_value?('category', hash['category'])\n note(hash['uid'], \"You have created a new category '#{hash['category']}'. Did you mean to?\") \n elsif new_value?('parameter', hash['parameter'])\n note(hash['uid'], \"You have created a new property of '#{hash['category']}', '#{hash['parameter']}'. Did you mean to?\") \n end\n if new_value?('source', hash['source'])\n note(hash['uid'], \"You have created a new source '#{hash['source']}'. Did you mean to?\")\n end \nend", "def field(type_name, *names)\n options = names.extract_options!\n data_field = @field\n changed_ivar = \"#{data_field}_changed\"\n type = SerializableAttributes.types[type_name].new(options)\n names.each do |name|\n name_str = name.to_s\n @fields[name_str] = type\n\n @model.send(:define_method, name) do\n send(data_field)[name_str]\n end\n\n if type.is_a? Boolean\n @model.send :alias_method, \"#{name}?\", name\n end\n\n @model.send(:define_method, \"#{name}=\") do |value|\n write_serialized_field name_str, value\n end\n\n @model.send(:define_method, \"#{name}_changed?\") do\n send(changed_ivar).include?(name_str)\n end\n\n @model.send(:define_method, \"#{name}_before_type_cast\") do\n value = send(name)\n value = type.encode(value) if type\n value.to_s\n end\n\n @model.send(:define_method, \"#{name}_change\") do\n if send(\"#{name}_changed?\")\n [instance_variable_get(\"@#{changed_ivar}\")[name_str], send(data_field)[name_str]]\n else\n nil\n end\n end\n end\n end", "def semantic_fields!(config, added_values = nil)\n values = SEMANTIC_FIELDS\n values = values.merge(added_values) if added_values.present?\n super(config, values)\n end", "def fields; end", "def fields; end", "def fields; end", "def update_fields(fields)\n attributes[:name] = fields['name']\n attributes[:id] = fields['id']\n self\n end", "def register_custom_fields(*names)\n names.each do |name|\n custom_fields[name.to_s] = {}\n custom_fields[name.to_s][\"label\"] = name.to_s\n custom_fields[name.to_s][\"value\"] = CUSTOM_DEFAULT_VALUE\n end\n end", "def process_field(field_name)\n if ['id', 'name', 'first_name', 'node_id'].include?(field_name)\n \"#{table}.#{field_name}\"\n else\n super # raises\n end\n end", "def extend_for_custom_fields(name)\n class_eval do\n field :\"#{name}_custom_fields_version\", type: ::Integer, default: 0\n\n embeds_many :\"#{name}_custom_fields\", class_name: dynamic_custom_field_class_name(name) # , cascade_callbacks: true # FIXME ?????\n\n accepts_nested_attributes_for :\"#{name}_custom_fields\", allow_destroy: true\n end\n\n class_eval <<-EOV, __FILE__, __LINE__ + 1\n after_initialize :refresh_#{name}_metadata\n before_update :bump_#{name}_custom_fields_version\n before_update :collect_#{name}_custom_fields_diff\n after_update :apply_#{name}_custom_fields_diff\n after_update :apply_#{name}_custom_fields_localize_diff\n\n def ordered_#{name}_custom_fields\n self.ordered_custom_fields('#{name}')\n end\n\n protected\n\n def refresh_#{name}_metadata\n self.refresh_metadata_with_custom_fields('#{name}')\n end\n\n def bump_#{name}_custom_fields_version\n self.bump_custom_fields_version('#{name}')\n end\n\n def collect_#{name}_custom_fields_diff\n self.collect_custom_fields_diff(:#{name}, self.#{name}_custom_fields)\n end\n\n def apply_#{name}_custom_fields_diff\n self.apply_custom_fields_diff(:#{name})\n end\n\n def apply_#{name}_custom_fields_localize_diff\n self.apply_custom_fields_localize_diff(:#{name})\n end\n\n EOV\n end", "def initialize(*)\n super\n @extra_fields = []\n end", "def add_field(identifier, value = nil)\n @fields << build_field(identifier, value)\n end", "def add_field(field, data_type = nil, options = {})\n data_type = DataType::String if data_type.nil?\n puts [\":#{field}\", \"#{data_type.class.to_s}\", \"#{options.inspect}\"].collect { |s| s.ljust(25) }.join if ENV['DEBUG']\n \n # Fields that do special things go here.\n if field == :timestamps\n add_field(:updated_at, :datetime)\n add_field(:created_at, :datetime)\n return true\n end\n\n # Add index if explicitly asked\n @indexes << field if options.delete(:index) || data_type.class.to_s == 'Hash' && data_type.delete(:index)\n @validations[field] = options.delete(:validates) if options[:validates]\n options.merge!(:field => field) \n \n # Matches: description DataType::Paragraph, :index => true\n if data_type.is_a?(Class) && data_type.respond_to?(:migrant_data_type?)\n @columns[field] = data_type.new(options)\n # Matches: description :index => true, :unique => true\n else\n begin\n # Eg. \"My field\" -> String -> DataType::String\n @columns[field] = \"DataType::#{data_type.class.to_s}\".constantize.new(options.merge(:value => data_type))\n rescue NameError\n # We don't have a matching type, throw a warning and default to string\n puts \"MIGRATION WARNING: No migration implementation for class #{data_type.class.to_s} on field '#{field}', defaulting to string...\"\n @columns[field] = DataType::Base.new(options)\n end\n end\n end", "def start_field=(_arg0); end", "def add_raw(raw)\n @fields << Field.new(raw)\n self\n end", "def update_fields(fields)\n attributes[:action_id] = fields['id'] || attributes[:action_id]\n attributes[:text] = fields['data']['text'] || attributes[:text]\n attributes[:date] = Time.iso8601(fields['date']) if fields.has_key?('date')\n attributes[:member_creator_id] = fields['idMemberCreator'] || attributes[:member_creator_id]\n self\n end", "def create_fields_of(data, category)\n data.each do |k, v|\n params = Field.class_name_for_type(v['type']).constantize.create_from_hash(k, v)\n params.merge!(category: category)\n field = Field.class_name_for_type(v['type']).constantize.create!(params)\n self.general_fields << field #NOTE Since we have already created the object, the category attribute will not change if we add it to the incorrect set of fields. Hence, just add all to general_fields\n end\n end", "def replace_field_handler(name, handler); end", "def add_field(name, data_lambda = nil)\n name = next_unknown_field_name if name.nil?\n @fields << name.to_sym\n @lambdas[name.to_sym] = data_lambda if data_lambda\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def set_derived_fields\n self.credit_for_mil_training = to_yes_string(vet2)\n self.vet_poc = to_yes_string(vet3)\n self.student_vet_grp_ipeds = to_yes_string(vet4)\n self.soc_member = to_yes_string(vet5)\n self.calendar = to_calendar(calsys)\n self.online_all = to_true_string(distnced)\n\n true\n end", "def set_fields(fields)\n fields.each_pair do |name, value|\n set_field(name, value)\n end\n fields\n end", "def field(*args)\n _instantiate_and_store(:field, *args)\n end", "def create_fields\n create_fields_of(DivaServicesApi::Algorithm.general_information, :general)\n create_fields_of(DivaServicesApi::Algorithm.method_information, :method)\n end", "def update_fields(fields)\n @id = fields['id']\n @name = fields['name']\n @type = fields['type']\n self\n end", "def method_missing(name, *args, &block)\n if self.is_dynamic_field?(name)\n if name.to_s.ends_with?('=')\n name = name.to_s.gsub(/\\=$/, '').to_sym\n self.dynamic_setter(name, args.first)\n else\n self.dynamic_getter(name)\n end\n else\n super\n end\n end", "def custom_fields_basic_attributes\n {}.tap do |hash|\n non_relationship_custom_fields.each do |rule|\n name = rule['name']\n type = rule['type'].to_sym\n\n # method of the custom getter\n method_name = \"#{type}_attribute_get\"\n\n hash.merge!(self.class.send(method_name, self, name))\n end\n end\n end", "def register_field_handler(name, handler); end", "def add_extra_field(extra_field)\n # Try to find an extra field with the same header ID already in the list\n # and merge the new one with that if one exists; otherwise, add the new\n # one to the list.\n existing_extra_field = @extra_fields.find do |ef|\n ef.header_id == extra_field.header_id\n end\n if existing_extra_field.nil? then\n @extra_fields << extra_field\n else\n extra_field = existing_extra_field.merge(extra_field)\n end\n\n # Set some attributes of this entry based on the settings in select types\n # of extra fields.\n if extra_field.kind_of?(ExtraField::ExtendedTimestamp) then\n self.mtime = extra_field.mtime unless extra_field.mtime.nil?\n self.atime = extra_field.atime unless extra_field.atime.nil?\n elsif extra_field.kind_of?(ExtraField::Unix) then\n self.mtime = extra_field.mtime unless extra_field.mtime.nil?\n self.atime = extra_field.atime unless extra_field.atime.nil?\n self.uid = extra_field.uid unless extra_field.uid.nil?\n self.gid = extra_field.gid unless extra_field.uid.nil?\n end\n self\n end", "def method_missing(name, *args, &block)\n #:nodoc:\n # Only take the structured fields, as we could take _anything_ really\n # as it could become an optional field... \"but therin lies the dark side\"\n field_name = underscoreize(name).chomp(\"=\")\n if Mail::Field::KNOWN_FIELDS.include?(field_name)\n if args.empty?\n header[field_name]\n else\n header[field_name] = args.first\n end\n else\n super # otherwise pass it on\n end\n #:startdoc:\n end", "def set_fields(fields)\n fields.each { |key, value| set_field key, value }\n end", "def prepare_custom_fields(fields)\n fields.each_with_object({}) { |e, o| o[\"copyleaks-client-custom-#{e[0]}\"] = e[1] }\n end", "def dynamic_fields\n default_columns.collect do |c|\n {\n :name => c[:name],\n :type => c[:attr_type] == :json ? :text : c[:attr_type], # store :json columns as :text\n :default => c[:default_value]\n }\n end\n end", "def field(name, options={})\n (@value[:fields] ||= {}).update name.to_sym => options\n end", "def configure_field\n end", "def method_missing(method_name, *args, &block)\n name = method_name.to_s\n \n if field_keys.include? name.gsub(/=/, '')\n return name.include?(\"=\") ? self.data[name.gsub(/=/, '').to_sym] = args.first : self.data[method_name]\n else\n logger.debug(\"Form is #{form} and the fields are #{self.form.form_fields if self.form}\")\n super\n end\n end", "def arrangeable_fields\n raise NotImplementedError, 'You need to overwrite this method in the calling class'\n end", "def add_controlled_fields\n metadata_schema.controlled_field_names.each do |field_name|\n field = metadata_schema.get_field(field_name)\n raw_metadata_for_field = {}\n raw_metadata.each do |k, v|\n # Handle both camelCase and snake_case\n if k.match?(/#{field_name.downcase}(_\\d+)?/) || k.match?(/#{field_name.underscore}(_\\d+)?/)\n raw_metadata_for_field[k] = v\n end\n end\n next if raw_metadata_for_field.blank?\n\n all_values = raw_metadata_for_field.values.compact&.map { |value| value.split(/\\s*[|]\\s*/) }&.flatten\n parsed_metadata[field_name] = []\n next if all_values.blank?\n\n parsed_metadata.delete(field_name) # replacing field_name with field_name_attributes\n all_values.each_with_index do |value, i|\n auth_id = sanitize_controlled_field_uri(field, value)\n auth_id ||= search_authorities_for_id(field, value)\n auth_id ||= create_local_authority_id(field, value)\n next unless auth_id.present?\n\n parsed_metadata[\"#{field_name}_attributes\"] ||= {}\n parsed_metadata[\"#{field_name}_attributes\"][i] = { 'id' => auth_id }\n end\n end\n end", "def define_field(field_class, label=nil, opts={}, &extension)\n raise \"method #{self}##{label} already defined\" if method_defined? label\n\n opts[:endian] ||= @endian\n field_class = field_class.by_endian(opts) if field_class.respond_to? :by_endian\n fields[label] = field = field_class.new(opts, &extension)\n\n if opts[:if].kind_of?(Proc) || opts[:if].kind_of?(Symbol)\n class << field\n alias_method :read_val, :read\n alias_method :read_io_val, :read_io\n undef_method :read\n undef_method :read_io\n alias_method :read, :read_if\n alias_method :read_io, :read_io_if\n public(:read, :read_io)\n end\n end\n opts.each do |key, option|\n case option\n when Proc\n define_method(method_sym=:\"_#{label}_#{key}\", &option)\n field.define_singleton_method(key) { @parent.send(method_sym) }\n when Symbol\n field.define_singleton_method(key) { @parent.send(option) }\n end\n end\n\n field.assign(opts[:default]) if opts[:default]\n\n num = values.size\n values << field\n labels << label\n\n # reader method\n define_method(label) {|| @values[num] }\n end", "def initialize type, old, new\n @old = old || {}\n @new = new || {}\n @type = type\n @fields = if type == :tiddler\n %w(title tags content_type text fields user_id created)\n else\n %w(name description)\n end\n end", "def set_fields(fields)\n fields.each { |key, value| set_field key, value }\n end", "def extend_fields\n if username.blank?\n # Synthesize a unique username from the email address or fullname\n n = 0\n startname = handle if (startname = email.sub(/@.*/, '')).blank?\n self.username = startname\n until (User.where(username: username).empty?) do\n n += 1\n self.username = startname+n.to_s\n end\n end\n # Provide a random password if none exists already\n self.password = email if password.blank? # (0...8).map { (65 + rand(26)).chr }.join\n self.fullname = \"#{first_name} #{last_name}\" if fullname.blank? && !(first_name.blank? || last_name.blank?)\n end", "def add_fields_to_request\n @fields.each do |f|\n @request += f + ',' if f\n end\n end", "def modify_attributes_with_fields(attributes)\n attributes = attributes.nil? ? {} : attributes.dup\n\n # this is not possible, because when object is created by association,\n # then attributes like owner_id are set after initializer is run\n # so we cannot lookup fields defininitions source and have to set it this way\n # return attributes unless @owner.new_record?\n\n klass = proxy_association.klass || proxy_association.reflection.klass\n if klass.respond_to?(:has_fields?) && klass.has_fields?\n if attributes.is_a? Array\n attributes.map! {|attrs| attrs[:fields_definitions_source] = proxy_association.owner }\n else\n attributes[:fields_definitions_source] = proxy_association.owner\n end\n end\n\n attributes\n end", "def cas_extra_attributes=(extra_attributes)\n extra_attributes.each do |name, value|\n puts \"DEBUG: cas_extra_attributes CALLED\"\n puts \"extra_attributes:\"+ name.to_s+\" => \"+ value.to_s\n case name.to_sym\n when :fullname\n self.fullname = value\n when :email\n self.email = value\n end\n end\n end", "def <<(field)\n list[field.name] = field\n end", "def create_field_setter(name, meth, field)\n generated_methods.module_eval do\n define_method(\"#{ meth }=\") do |value|\n instance_variable_set \"@#{ name }\", value\n end\n end\n end", "def link_to_add_fields(name, f, type)\n new_object = f.object.send \"build_#{type}\"\n id = \"new_#{type}\"\n fields = f.send(\"#{type}_fields\", new_object, child_index: id) do |builder|\n render(type.to_s + \"_fields\", f: builder)\n end\n link_to(name, '#', class: \"add_fields\", data: {id: id, fields: fields.gsub(\"\\n\", \"\")})\n end", "def process_field(builder, field)\n builder.send(field.field_type.to_sym,\n field.field_name.to_sym,\n\n # Homespree Project Type Optional params\n {\n label: field.label,\n data: field.field_data,\n default: field.default,\n required: field.required,\n position: field.position,\n size: field.size,\n toggleable: field.toggleable\n }\n )\n end", "def fields_for(record_or_name_or_array, *args, &block) #:nodoc:\n opts = args.extract_options!\n opts.merge!(:builder => Transit::Builders::FormBuilder)\n args.push(opts)\n super(record_or_name_or_array, *args, &block)\n end", "def set_additional_values(object, override)\n override.class.attributes.each do |o|\n object.instance_variable_set(\"@#{o}\", override[o])\n object.define_singleton_method(o.to_sym) { instance_variable_get(\"@#{o}\") }\n end\n end", "def set_derived_fields\n self.type = weams_type\n self.va_highest_degree_offered = highest_degree_offered\n\n self.flight = flight?\n self.correspondence = correspondence?\n self.approved = approved?\n\n true\n end", "def fields(value_or_name)\n value = case value_or_name\n when Hash\n value_or_name\n when Array\n value_or_name.reduce({}) { |sum, item| sum.update item.to_sym => {}; sum }\n else\n end\n\n (@value[:fields] ||= {}).update value\n self\n end", "def new_with_default_fields(*a, &b) \n object = new_without_default_fields(*a, &b)\n # object.attributes = a.first || {} <- removed, as we initialize the fields w/ new in previous line already \n object\n end", "def custom_fields_getters_for(name, type)\n case type.to_sym\n when :select then [name, \"#{name}_id\"]\n when :date, :date_time, :money then \"formatted_#{name}\"\n when :file then \"#{name}_url\"\n when :belongs_to then \"#{name}_id\"\n else\n name\n end\n end", "def add_field(field, default=nil)\n _define_method(field.to_sym) unless @options[field.to_sym]\n send(\"#{field.to_sym}=\", default)\n end", "def initialize_simples\n clazz.fields.each do |field|\n proxy_field = proxy_class.add_simple(field[:type],field[:name].to_s)\n field[:args].each do |f1|\n if f1.length > 0\n build_id_for proxy_field if f1[0][:id]\n end\n end\n end\n end", "def field_transform(name, field_type)\n case field_type\n when 'text'\n text_field_tag name\n when 'textbox'\n text_area_tag name\n when 'password'\n password_field_tag name\n when 'email'\n email_field_tag name\n when 'select'\n \"not yet implemented\"\n else\n puts \"LOL\"\n end\n end", "def initialize_custom_fields\n fields = service.get_custom_fields(contact_point_list)\n existing_fields = fields.map(&:FieldName)\n\n [\n { name: \"organization_id\", type: 'Number' },\n { name: \"organization_name\", type: 'Text' },\n { name: \"cop_status\", type: 'Text' },\n { name: \"cop_due_on\", type: 'Text' },\n ].each do |hash|\n create_custom_field(hash.fetch(:name), hash.fetch(:type))\n end\n end" ]
[ "0.70557165", "0.6788116", "0.6718048", "0.6670186", "0.6460089", "0.6455317", "0.64046526", "0.63169235", "0.62844354", "0.6280383", "0.6267154", "0.6267154", "0.6267154", "0.6246747", "0.62184966", "0.6150756", "0.6150756", "0.6150756", "0.61325437", "0.6117017", "0.60977215", "0.60706294", "0.60607016", "0.60590243", "0.60590243", "0.60590243", "0.6040552", "0.60178214", "0.5964043", "0.5916669", "0.5911418", "0.59075236", "0.5903384", "0.590287", "0.590014", "0.586571", "0.5849463", "0.5827683", "0.5822937", "0.58225095", "0.58049923", "0.57848847", "0.57842636", "0.57750404", "0.57733846", "0.577254", "0.577254", "0.577254", "0.5761132", "0.5759754", "0.5757593", "0.5748735", "0.5747577", "0.5728719", "0.5728212", "0.5720841", "0.5720839", "0.5716158", "0.57154065", "0.57153434", "0.57008934", "0.5681412", "0.5680546", "0.56781363", "0.5661701", "0.56610376", "0.56599677", "0.5659058", "0.5650484", "0.56486845", "0.56379324", "0.56356424", "0.56334996", "0.56209415", "0.5615019", "0.56124943", "0.5610897", "0.5606868", "0.5599694", "0.55990446", "0.5597199", "0.5595754", "0.55892116", "0.55888045", "0.55881107", "0.5584397", "0.5582915", "0.5582714", "0.5568364", "0.55669296", "0.5566578", "0.5564417", "0.55637324", "0.5562302", "0.5557648", "0.55548674", "0.5553781", "0.5549022", "0.55479217", "0.55458856", "0.5544552" ]
0.0
-1
method_missing approach won't work with id do it manually
def id @hash["id"] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def method_missing(id, *attr, &block); end", "def method_missing(method_id, object)\n return object(object)\n end", "def method_missing(meth, *args, &blk) \n\t\traise NoMethodError if (meth.to_s == 'id')\n\t\t\t\n\t\tself.bien[0].send(meth, *args, &blk)\n\t\t\n\t\trescue NoMethodError\n\t\t\tsuper\n\tend", "def call_id_as_meth(hash={})\n\t\thash['id'].gsub!(' ', '_')\n\t\tsend(hash['id'], hash) rescue()\n\tend", "def method_missing(method, *args, &blk); end", "def method_missing(method, *args, &block); end", "def method_missing(id, *params, &b)\n @hash.send(id, *params, &b)\n end", "def method_missing(meth, *args); end", "def method_missing(method_name, *args); end", "def method_missing(method_name, *args); end", "def method_missing(selector, *args, &block); end", "def method_missing(method, *arguments, &block); end", "def method_missing(meth, *args, &block); end", "def method_missing(meth, *args, &block); end", "def method_missing(meth, *args, &block); end", "def method_missing(method, *args)\r\n self.class.method_missing(method, *args)\r\n end", "def method_missing(id,*args,&block)\n return @delegated_to_object.send(id,*args,&block) if delegated_instance_methods.include?(id)\n super\n end", "def method_missing(id,*args,&block)\n return @delegated_to_object.send(id,*args,&block) if delegated_instance_methods.include?(id)\n super\n end", "def method_missing(method)\n\t\t self[method]\n\t\tend", "def method_missing(method_id, params = {})\n request(method_id.id2name.gsub(/_/, '.'), params)\n end", "def method_missing(method_name, *args) self end", "def method_missing(method_name, *args) self end", "def method_missing(method, *args)\n self[method]\n end", "def method_missing(*args, &block); end", "def method_missing(*rest) end", "def method_missing(code, *args, &blk); end", "def method_missing(code, *args, &blk); end", "def method_missing(id, *args, &block)\n if id.to_s =~ /=$/\n id = id.to_s.gsub(/=$/,'') \n instance_variable_set(\"@#{id}\", args.first)\n else\n instance_variable_get(\"@#{id}\")\n end\n end", "def method_missing( id, *args )\n DBC.require id.class == Symbol\n\n id_string = \"#{id}\"\n if id_string =~ /=$/\n # C'est un appel de la forme \"os.champ = ...\"\n id = id_string.chop.to_sym\n definir_reader_et_writer( id )\n set_attribut id, args[0]\n else\n raise NoMethodError, \"Methode non-definie `#{id}' pour #{self}\", caller(1)\n end\n end", "def respond_to_missing?(method_name, include_private = false)\n /^(?<id>[^=]+)=?$/ =~ method_name.to_s && self[id] || super\n end", "def method_missing(method, *args)\n send(method, *args)\n end", "def method_missing(method, *args) #:nodoc:\n self[method]\n end", "def method_missing(mth, *args, &block); end", "def method_missing(method, *args)\n self.person.send(method, *args) if self.person\n end", "def method_missing(meth, *args, &block)\n\n end", "def method_missing(name, *args, &block); end", "def method_missing(name, *args, &block); end", "def method_missing(name, *args, &block); end", "def method_missing(name, *args, &block); end", "def method_missing method_sym, *args\n if el.respond_to?(method_sym)\n el.send(method_sym, *args)\n else\n raise NoMethodError, \"No such method #{method_sym} for #{self.class}\"\n end\n end", "def method_missing(name, *args); end", "def method_missing(name, *args); end", "def method_missing(method_id, args = nil)\n args.nil? && to_h[method_id] || super\n end", "def method_missing(meth, *args, &block)\n retrieve(meth.to_s)\n end", "def method_missing(symbol, args)\n\t@obj.send(symbol, args)\nend", "def method_missing(id, *args, &blk)\n if @resource.respond_to?(id, true)\n @resource.send(id, *args, &blk)\n else\n super\n end\n end", "def method_missing(method, *args, &block)\n object.public_send(method, *args, &block)\n end", "def method_missing(method, params={})\n call(method, params)\n end", "def method_missing(meth, *args, &block)\n @object.send(meth, *args, &block)\n end", "def method_missing(method_id, *arguments, &block)\n return data['attributes'][method_id.to_s] if data['attributes'].key?(method_id.to_s) && arguments.none? && block.nil?\n\n super\n end", "def method_missing(*a)\n end", "def method_missing(id, *args)\n # allow only to add methods which end with =\n if id.to_s =~ /=$/\n symbol = id.to_s.chop\n self.class.send(:define_method, symbol ) { args.shift }\n else\n raise \"Method '#{id}' '#{args}' is missing\"\n end\n end", "def method_missing(id, *args)\n\n name = id.id2name\n if( args.length == 1 ) \n\t@options[name] = args[0]\n elsif( args.length == 0 )\n\treturn @options[name]\n end\n end", "def method_missing(call)\n object.send(call)\n end", "def method_missing(*args)\n model.send(*args)\n end", "def method_missing(method_id, *args)\r\n\t\tsymbol_name = \"#{method_id}(\"\r\n\t\targs.each { |arg| symbol_name += arg.to_s + \",\" }\r\n\t\tsymbol_name[0,symbol_name.length-1] + \")\"\r\n\tend", "def method_missing(meth, options = T.unsafe(nil)); end", "def method_missing(method, *args)\n class_for_number(args[0]).public_send(method, *args)\n end", "def method_missing(method, *args)\n class_for_number(args[0]).public_send(method, *args)\n end", "def method_missing(method_id, *args)\n unless args.empty? or args.first.kind_of? Hash\n raise ArgumentError, \"#{self.class}##{method_id.to_s} only accept hash argument\"\n end\n\n command(method_id.to_s.split('_').map(&:capitalize).reverse.join('.'), args)\n\n rescue ArgumentError => message\n puts message\n end", "def method_missing(id, *args)\n method_name = id.to_s\n if method_name =~ /=$/\n # suppoert property? = true\n if method_name =~ /\\?=$/\n method_name = method_name[0..-3]\n value = !!args[0]\n else\n method_name = method_name[0..-2]\n value = args[0]\n end\n print_first_caller(method_name)\n self[method_name.to_sym] = value\n\n # convert property? => !!self[:property]\n elsif method_name =~ /\\?$/\n !!self[method_name[0..-2].to_sym]\n else\n print_first_caller(method_name)\n self[method_name.to_sym]\n end\n end", "def method_missing(id, *args)\n flat_args = args.map(&:inspect).map(&:to_s).join ', '\n \"#{name}.#{id}#{flat_args.empty? ? '' : \"(#{flat_args})\"}\"\n end", "def method_missing(method_id, *args)\n return super unless @resource.respond_to? method_id\n @resource.public_send method_id, *args\n end", "def method_missing(m, *args, &block)\n end", "def method_missing(method_name, *arguments, &block)\n # not a bug here, we want =, not ==\n if /^(?<id>[^=]+)$/ =~ method_name.to_s && (attribute = self[id])\n attribute.value\n else\n nil\n end\n end", "def method_missing(meth, *args, &blk)\n meth.to_s == 'id' ? super : chargeable_unit_properties.send(meth, *args, &blk)\n rescue NoMethodError\n super\n end", "def method_missing(meth, *args, &block)\n Interrogate.is_interrogatory?(meth) ? Interrogate.interrogate(meth, *args, &block) : super\n end", "def perform(id, method, *args)\n if id # instance\n find(id).send(method, *args)\n else # class method\n send(method, *args)\n end\n end", "def method_missing(meth, *args) = parameters.has_key?(meth) ? parameters[meth] : meth", "def method_missing(method, *args, &block)\n if @object.key? method\n @object[method]\n elsif @object.respond_to? method\n @object.send(method, *args, &block)\n end\n end", "def method_missing(id, *args)\n name = id.id2name\n case args.length\n when 1\n\tset_string(name, args.join)\n when 0\n\tset_string(name)\n end\n end", "def method_missing(method, *args)\n @klass[method] = args.first\n end", "def method_missing(name, *args)\n # puts \"method_missing being called in #{self} is being sent to 'el' - #{name} with args #{args.to_s}\"\n as_sym = name.to_sym \n as_string = name.to_s\n if el.respond_to?(as_string, include_private = false)\n el.send(as_string,*args)\n else\n puts \"#{self} does not respond_to #{name}\"\n super # You *must* call super if you don't handle the\n # method, otherwise you'll mess up Ruby's method\n # lookup.\n end\n end", "def method_missing(name, *args)\n # puts \"method_missing being called in #{self} is being sent to 'el' - #{name} with args #{args.to_s}\"\n as_sym = name.to_sym \n as_string = name.to_s\n if el.respond_to?(as_string, include_private = false)\n el.send(as_string,*args)\n else\n puts \"#{self} does not respond_to #{name}\"\n super # You *must* call super if you don't handle the\n # method, otherwise you'll mess up Ruby's method\n # lookup.\n end\n end", "def method_missing(method, *args)\n api_obj.send(method, *args)\n end", "def method_missing(m,*a)\n self[m]\n end", "def method_missing(meth, *args, &block)\n meth = meth.to_s\n taggable_class = ((match = meth.match(/(.+)_ids/)) ? match[1] : meth).singularize.camelize.constantize\n proof_method = :tag_with\n # puts \"Extracted taggable_class '#{taggable_class}'\"\n # puts \"#{taggable_class} \"+(taggable_class.method_defined?(proof_method) ? \"has \" : \"does not have \")+\"'#{proof_method}' method\"\n if taggable_class.method_defined?(proof_method) && Tag.method_defined?(meth)\n begin\n self.method(meth).call *args, &block\n rescue Exception => e\n # puts \"D'OH! Couldn't create association between Tag and #{taggable_class}\"\n super\n end\n else\n super\n end\n end", "def method_missing(m, *args, &block)\n target = self.__getobj__\n unless target.respond_to?(m)\n super(m, *args, &block)\n else\n target.__send__(m, *args, &block)\n end\n end", "def method_missing(name, *args)\n\t\t\tcall name, *args\n\t\tend", "def method_missing(method, *args, &block)\n _target.send method, *args, &block\n end", "def method_missing(*args)\n send(*args)\n end", "def method_missing(method, *args, &block)\n if name?(method.to_sym)\n find(method.to_sym)\n else\n super\n end\n end", "def respond_to_missing?( id, priv = false ) id != :call; end", "def method_missing(methid, *rest)\n meth = methid.id2name\n\t\t\t #$stderr.print \"method_missing: #{meth}\\n\"\n\t\t\t\t#$stderr.print \"parameters: #{@parameters.keys.inspect}\\n\"\n if @parameters.has_key?(meth)\n\t\t\t\t #$stderr.print \"return parm obj\\n\"\n\t\t\t return @parameters[meth].value\n\t\t\t elsif mat = /^(.*?)\\=$/.match(meth)\n\t\t\t\t #$stderr.print \"return parm val\\n\"\n if @parameters.has_key?(mat[1])\n\t\t\t\t\t return @parameters[mat[1]].value = rest[0]\n\t\t\t\t else\n\t\t\t\t\t raise NoMethError\n end\n\t\t\t else\n\t\t\t raise NoMethodError\n\t\t\t end\n end", "def method_missing(m, *args, &block)\n # Attempt to call a method on the object directly\n if(method_names.index(m.to_s))\n $DEBUG and puts(\"Attempting to invoke_method '#{m}'\")\n invoke_method(get_method(m.to_s), args)\n else\n super.method_missing(m, *args, &block)\n end\n end", "def by_id(id)\n raise NotImplementedError.new\n end", "def method_missing(method_name, *args, &block)\n instance.send(method_name, *args, &block)\n end", "def method_missing(meth, *args, &block)\n\t\t@r.send(meth, *args, &block)\n\tend", "def method_missing m,*o,&b\n @element.send m,*o,&b\n end", "def method_missing(meth, *args, &block)\n if respond_to?(meth)\n object.__send__(meth, *args, &block)\n else\n super\n end\n end", "def method_missing(meth, *args)\n if respond_to_missing?(meth)\n person.send(meth)\n else\n super(meth, *args)\n end\n end", "def method_missing(method_sym, *arguments, &block)\n if self[\"#{method_sym.to_s}\"] != nil\n self[\"#{method_sym.to_s}\"]\n else\n super\n end\n end", "def method_missing(:name, *args)\nend", "def method_missing(name, *args)\n cur.send(name, *args)\n end", "def method_missing(method, *args, &block)\n if @hash.key?(method.to_s.to_sym)\n @hash[method.to_s.to_sym]\n else\n @hash.send(method, *args, &block)\n end\n end", "def method_missing(name, *args, &block)\n self[name.to_s]\n end", "def method_missing(sym, *args)\n record.__send__(sym, *args)\n end", "def method_missing(name, *args, &block)\n target.send(name, *args, &block)\n end", "def method_missing(method_name, *args, &block)\n if @object.respond_to? method_name.to_sym\n @object.__send__(method_name, *args, &block)\n else\n super\n end\n end", "def method_missing(method_id, *params)\n _request(method_id.to_s.sub('_api', ''), *params)\n end", "def method_missing(id, *args)\n\t # Check this before valid_conversion? because valid_conversion? has low standards\n\t if (id.to_s =~ /(.+)\\?$/) and Units.valid_unit?($1)\n\t\t@units.is_a?($1)\n\t elsif @units.valid_conversion?(id)\n\t\tunits = Units.new(id)\n\t\t(@units == units) ? self : self.class.new(@units.convert(@value, id), units)\n\t elsif (id.to_s =~ /^to_(.+)$/) and Units.valid_unit?($1)\n\t\tunits = Units.new($1)\n\t\treturn self if @units == units\n\t\tself.class.new(@units.convert(@value, $1), units)\n\t else\n\t\t@value.send(id, *args)\n\t end\n\tend" ]
[ "0.79756457", "0.73780227", "0.72981566", "0.72128934", "0.71858305", "0.71588576", "0.7133411", "0.71270055", "0.71002245", "0.71002245", "0.70505065", "0.7048576", "0.7006543", "0.7006543", "0.7006543", "0.6991585", "0.6961754", "0.6961754", "0.695989", "0.69531775", "0.6944761", "0.6944761", "0.6876957", "0.6866765", "0.68659735", "0.6853995", "0.6853995", "0.6844966", "0.68087614", "0.6803637", "0.6792703", "0.6787657", "0.6776409", "0.67490405", "0.67346704", "0.67196333", "0.67196333", "0.67196333", "0.67196333", "0.67109317", "0.6708639", "0.6708639", "0.6672616", "0.66680807", "0.6661589", "0.66464543", "0.6520995", "0.6499552", "0.6497349", "0.64954704", "0.6449047", "0.6448512", "0.64125496", "0.6406877", "0.64004326", "0.6387557", "0.6384177", "0.63822067", "0.63822067", "0.6371695", "0.6370935", "0.63706964", "0.63609344", "0.6349873", "0.6349216", "0.6344653", "0.63271964", "0.63207865", "0.6315044", "0.6314789", "0.63135993", "0.6281732", "0.6268627", "0.6268627", "0.6268125", "0.6265627", "0.6262416", "0.62617755", "0.6260173", "0.62441754", "0.62377995", "0.6233922", "0.62324136", "0.6182619", "0.61796504", "0.6175371", "0.61745065", "0.6163971", "0.61623883", "0.6146476", "0.61412656", "0.6130713", "0.61019754", "0.60909915", "0.608329", "0.60769564", "0.6073984", "0.6066562", "0.6060624", "0.6054315", "0.6048758" ]
0.0
-1
define the name that a user will see, this method may be deprecated as the display name in PAT comes from the name field in measure.xml
def name return 'AedgSmallToMediumOfficeRoofConstruction' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def display_name \n username\n end", "def display_name\n username\n end", "def name\r\n\t\t@usr_name\r\n\tend", "def name\r\n\t\t@usr_name\r\n\tend", "def user_display_name=(value)\n @user_display_name = value\n end", "def user_display_name=(value)\n @user_display_name = value\n end", "def user_display_name=(value)\n @user_display_name = value\n end", "def name\n\t\tself.rsuser.display_name\n\tend", "def display_name\n \t\"#{name}\"\n end", "def show_username(str_name)\r\n self.title = \"#{APP_CUPERATIVA_NAME} - Utente: #{str_name}\" \r\n #@lbl_username.text = \"#{@comment_init} - Utente: #{str_name}\" \r\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name\n display_name = @current_profile.display_name\n end", "def display_name\n \"#{username} <#{email}>\"\n end", "def name\n userName\n end", "def user_display_name\n @attributes[:user_display_name]\n end", "def display_name\n \"#{user} - #{group}\"\n end", "def name\n\t\tfac_displayname\n\tend", "def display_name=(value)\n @display_name = value\n end", "def full_name\n (@session[:current_user_details] || {})[:description]\n end", "def get_display_name\n @display_name ||= self.user.display_name\n end", "def display_name\n \"#{name}\"\n end", "def display_name\n \"#{name}\"\n end", "def display_name\n \"#{name}\"\n end", "def display_name_for(user)\n user.first_name.capitalize + ' ' + user.last_name.capitalize + ' ( ID: ' + user.reference_number + ')'\n end", "def name\n \"#{user_name.titleize}\"\n end", "def full_name\n full_name = object.first_name + \" \" + object.last_name\n if object.profile.try(:search_engine_privacy).present?\n display_name = object.profile.try(:search_engine_privacy) == \"Show my full name\" ? full_name : object.first_name + \" \" + object.last_name.chr\n else\n display_name = full_name\n end\n return display_name \n end", "def display_name\n NAME\n end", "def display_name\n NAME\n end", "def user_display_name\n return @user_display_name\n end", "def user_display_name\n return @user_display_name\n end", "def user_display_name\n return @user_display_name\n end", "def display_name\n name\n end", "def display_name\n name\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name\n @name\n end", "def display_name\n self.display_name = self.profile.nickname? ? self.profile.nickname : self.username\n end", "def display_name\n @display_name\n end", "def name\n @display_name || @name\n end", "def display_name\n # This display name is different from others.\n # We'll display the station id here, not the regional office,\n # since we don't connect to VACOLS.\n \"#{username} (#{station_id})\"\n end", "def display_name\n return @display_name\n end", "def display_name\n override_name ||= name\n # default to name if the value of override_name is empty string\n override_name = name if override_name.strip == \"\"\n override_name\n end", "def display_name\n name\n end", "def display_name\n name\n end", "def display_name\n name\n end", "def name\r\n\t\t\t`#{BITS::BITSADMIN} /getdisplayname {#{@id}}`\r\n\t\tend", "def display_name\n entry = JSON.parse(self.entry)\n user = User.find(user_id)\n \"#{user.display_name} #{entry['text']}\"\n end", "def display_name_without_user_filter(name)\n name[:display_name]\n end", "def name\n auth[:info][:name] || auth[:info][:display_name] rescue nil\n end", "def display_name\n name\n end", "def display_name=(name)\n @display_name ||= name\n end", "def audithelp_user_name( record )\n return to_descriptive_s( record.user ? record.user.name : nil )\n end", "def name\n\t\tn = names\n\t\treturn n[:fullname] if n[:fullname]\n\t\treturn n[:username] if n[:username]\n\t\treturn I18n.translate(\"user.name.unknown\")\n\tend", "def display_name\n prefered_name\n end", "def name(type=:short)\n if type == :short && !nickname.blank?\n nickname\n elsif type == :short && displayName\n first, last = displayName.split\n \"#{first} #{last[0]}\"\n elsif type == :full && displayName\n displayName\n else\n umbcusername\n end\n end", "def name\n display_name\n end", "def display_name\n #self.email.split('@')[0]\n self.username\n end", "def name\n \"#{@profile[:first_name]} #{@profile[:last_name]}\"\n end", "def display_name\n name # !pseudonym.blank? ? pseudonym : name\n end" ]
[ "0.7340131", "0.73166376", "0.7264374", "0.7264374", "0.7244726", "0.7244726", "0.7244726", "0.7229244", "0.72220355", "0.72023845", "0.71597034", "0.715259", "0.71449405", "0.7139302", "0.7093882", "0.708272", "0.7072226", "0.7061353", "0.70334023", "0.702734", "0.70249605", "0.70249605", "0.70249605", "0.7016991", "0.700592", "0.6997287", "0.69810325", "0.69810325", "0.6978872", "0.6978872", "0.6978872", "0.69747496", "0.69747496", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69734544", "0.69706494", "0.69686323", "0.696502", "0.6964332", "0.6963943", "0.6953893", "0.69510484", "0.6935353", "0.6935353", "0.6935353", "0.6920325", "0.69124436", "0.69000965", "0.6889027", "0.6882051", "0.68757796", "0.685875", "0.6858144", "0.6848599", "0.68469787", "0.68445814", "0.683938", "0.6838762", "0.6826352" ]
0.0
-1
define the arguments that the user will input
def arguments(model) args = OpenStudio::Measure::OSArgumentVector.new # make an argument for material and installation cost material_cost_insulation_increase_ip = OpenStudio::Measure::OSArgument.makeDoubleArgument('material_cost_insulation_increase_ip', true) material_cost_insulation_increase_ip.setDisplayName('Increase Cost per Area of Construction Where Insulation was Improved ($/ft^2).') material_cost_insulation_increase_ip.setDefaultValue(0.0) args << material_cost_insulation_increase_ip # make an argument for material and installation cost material_cost_sri_increase_ip = OpenStudio::Measure::OSArgument.makeDoubleArgument('material_cost_sri_increase_ip', true) material_cost_sri_increase_ip.setDisplayName('Increase Cost per Area of Construction Where Solar Reflectance Index (SRI) was Improved. ($/ft^2).') material_cost_sri_increase_ip.setDefaultValue(0.0) args << material_cost_sri_increase_ip return args end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def arguments; end", "def arguments; end", "def arguments; end", "def arguments\n \"\"\n end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def get_input \n puts \"to save this game, input 's,filename'\"\n puts \"to load a game, input 'l,filename'\"\n puts \"input a coordinate to access. prefix with r for reveal or f for flag\"\n puts \"example 'f,1,2' places a flag at 1,2\"\n input = gets.chomp\n \n args = input.split(',')\n end", "def args(*) end", "def arguments(required, *optional)\n puts \"required: #{required}\"\n puts \"optional: #{optional}\"\nend", "def args()\n #This is a stub, used for indexing\n end", "def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for the variable name\n variable_name = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"variable_name\",true)\n variable_name.setDisplayName(\"Enter Variable Name.\")\n variable_name.setDescription(\"Valid values can be found in the eplusout.rdd file after a simulation is run.\")\n args << variable_name\n \n #make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Detailed\"\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Zone Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"Runperiod\"\n reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName(\"Reporting Frequency.\")\n reporting_frequency.setDefaultValue(\"Hourly\")\n args << reporting_frequency\n\n #make an argument for the key_value\n key_value = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"key_value\",true)\n key_value.setDisplayName(\"Enter Key Name.\")\n key_value.setDescription(\"Enter * for all objects or the full name of a specific object to.\")\n key_value.setDefaultValue(\"*\")\n args << key_value\n \n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\n env.setDisplayName(\"availableEnvPeriods\")\n env.setDescription(\"availableEnvPeriods\")\n env.setDefaultValue(\"RUN PERIOD 1\")\n args << env\n \n return args\n end", "def set_arguments (args)\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make an argument for the variable name\n variable_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable_name', true)\n variable_name.setDisplayName('Enter Variable Name.')\n variable_name.setDescription('Valid values can be found in the eplusout.rdd file after a simulation is run.')\n args << variable_name\n\n # make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency.')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n # make an argument for the key_value\n key_value = OpenStudio::Measure::OSArgument.makeStringArgument('key_value', true)\n key_value.setDisplayName('Enter Key Name.')\n key_value.setDescription('Enter * for all objects or the full name of a specific object to.')\n key_value.setDefaultValue('*')\n args << key_value\n\n env = OpenStudio::Measure::OSArgument.makeStringArgument('env', true)\n env.setDisplayName('availableEnvPeriods')\n env.setDescription('availableEnvPeriods')\n env.setDefaultValue('RUN PERIOD 1')\n args << env\n\n args\n end", "def handle_arguments(args)\n if input_file.nil?\n print_usage\n true\n else\n args.help || args.version\n end\n end", "def arguments=(_arg0); end", "def command_line\r\n ARGV.each do |arg|\r\n if arg == \"instructions\"\r\n instructions\r\n elsif arg == \"calculator\"\r\n ask_for_digits\r\n else\r\n \r\n end\r\n end\r\n \r\n end", "def prescreen_input(args)\n if ((args.nil?) || (args.empty?))\n ['-eq', Date.today.strftime('%Y-%m-%d')]\n elsif ((args.length == 1) && (args[0].is_date?))\n ['-eq', args[0]]\n else\n args\n end\nend", "def varios_args(*args)\n puts \"Tamanho de args: #{args.size}\"\n args.each { |x| p x}\n end", "def process_arguments\n @e_addr = @options.email\n @r_name = @options.run_names\n @m_name = @options.machine_names\n @action = @options.action\n @snfs = @options.snfs\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # url of the city database\n city_db_url = OpenStudio::Measure::OSArgument.makeStringArgument('city_db_url', true)\n city_db_url.setDisplayName('City Database Url')\n city_db_url.setDescription('Url of the City Database')\n city_db_url.setDefaultValue('')\n args << city_db_url\n\n # project id to update\n project_id = OpenStudio::Measure::OSArgument.makeStringArgument('project_id', true)\n project_id.setDisplayName('Project ID')\n project_id.setDescription('Project ID to generate reports for.')\n project_id.setDefaultValue('0')\n args << project_id\n\n # datapoint id to update\n datapoint_id = OpenStudio::Measure::OSArgument.makeStringArgument('datapoint_id', true)\n datapoint_id.setDisplayName('Datapoint ID')\n datapoint_id.setDescription('Datapoint ID to generate reports for.')\n datapoint_id.setDefaultValue('0')\n args << datapoint_id\n\n return args\n end", "def validate_args (args)\n\t# todo\nend", "def args() return @args end", "def input=(_arg0); end", "def process_inputs(args)\n @input = ((name = args[:in_file]) && (IO.read(name, mode: \"rb\"))) ||\n args[:in_str] ||\n fail(\"An input must be specified.\")\n\n @generator = args[:generator] ||\n ((key = args[:key]) && Generator.new(key)) ||\n fail(\"A key or generator must be specified.\")\n\n @window = args[:window] || 16\n\n #The filler value is for testing purposes only. It should\n #not be specified when secure operation is desired.\n @fill_value = args[:filler]\n end", "def parse_args\r\n if(cmd.args =~ /\\=/)\r\n self.names = InputFormatter.titlecase_arg(cmd.args.before(\"=\"))\r\n self.action_args = cmd.args.after(\"=\")\r\n elseif (cmd.args && one_word_command)\r\n self.names = InputFormatter.titlecase_arg(cmd.args)\r\n self.action_args = \"\"\r\n else\r\n self.names = enactor.name\r\n self.action_args = cmd.args\r\n end\r\n\r\n self.names = self.names ? self.names.split(/[ ,]/) : nil\r\n\r\n self.combat_command = cmd.switch ? cmd.switch.downcase : nil\r\n end", "def manage_args(*args)\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make an argument for your name\n user_name = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"user_name\",true)\n user_name.setDisplayName(\"What is your name?\")\n args << user_name\n\n #make an argument to add new space true/false\n add_space = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"add_space\",true)\n add_space.setDisplayName(\"Add a space to your model?\")\n add_space.setDefaultValue(true)\n args << add_space\n \n return args\n end", "def greeting\n puts \"Hello, MTA rider! How can we help?\"\n puts \"please enter one of the following commands:\"\n puts \"lines / stops the_line / calculate Departing_Line Departing_Stop Arriving_Line Arriving_Stop\"\n user_call, *user_args = gets.chomp\n user_args.to_s\n # user_args.split(\" \")\n # puts user_input\n\n if user_call == lines\n show_lines()\n elsif user_call == stops\n show_stops(user_args[0])\n elsif user_call == calculate\n if user_args.length < 4\n puts 'please enter \"Departing_Line Departing_Stop Arriving_Line Arriving_Stop\"'\n puts 'or enter \"exit\" to return to the home screen' \n user_input = gets.chomp\n if user_input == \"exit\"\n greeting()\n end \n user_input = user_input.split(\" \")\n calculate(user_input[0], user_input[1], user_input[2], user_input[3])\n else\n calculate(user_args[0], user_args[1], user_args[2], user_args[3])\n end\n else\n \n end\nend", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n\n\n # Make an argument for evap effectiveness\n input_csv_path = OpenStudio::Measure::OSArgument::makeStringArgument(\"input_csv_folder_path\",true)\n input_csv_path.setDisplayName(\"raw_data_input_folder_path\")\n input_csv_path.setDefaultValue(\"data_file\")\n args << input_csv_path\n\n test_numbers = OpenStudio::StringVector.new\n test_numbers << 'Test_3'\n test_numbers << 'Test_6'\n test_numbers << 'Test_8'\n \n test_names = OpenStudio::StringVector.new\n test_names << 'UA_test'\n test_names << 'Cooling_test'\n test_names << 'Plenum_test'\n\n test_selections = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('test_data',test_numbers,test_names,true)\n\n \n test_selections.setDisplayName(\"Experiment\")\n test_selections.setDefaultValue(\"Test_3\")\n args << test_selections\n\n \n return args\n end", "def arguments\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # URL of the DEnCity server that will be posted to\n hostname = OpenStudio::Ruleset::OSArgument::makeStringArgument('hostname', true)\n hostname.setDisplayName('URL of the DEnCity Server')\n hostname.setDefaultValue('http://www.dencity.org')\n args << hostname\n\n # DEnCity server user id at hostname\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id',true)\n user_id.setDisplayName('User ID for DEnCity Server')\n args << user_id\n\n # DEnCIty server user id's password\n auth_code = OpenStudio::Ruleset::OSArgument::makeStringArgument('auth_code', true)\n auth_code.setDisplayName('Authentication code for User ID on DEnCity server')\n args << auth_code\n\n # Building type for DEnCity's metadata\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDisplayName('Building type')\n args << building_type\n\n # HVAC system for DEnCity's metadata\n primary_hvac = OpenStudio::Ruleset::OSArgument::makeStringArgument('primary_hvac', false)\n primary_hvac.setDisplayName('Primary HVAC system in building')\n args << primary_hvac\n\n args\n\n end", "def arguments\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n #make choice argument for facade\r\n choices = OpenStudio::StringVector.new\r\n choices << \"MessagePack\"\r\n choices << \"CSV\"\r\n choices << \"Both\"\r\n output_format = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"output_format\", choices)\r\n output_format.setDisplayName(\"Output Format\")\r\n output_format.setDefaultValue(\"Both\")\r\n args << output_format\r\n\r\n args\r\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\t\n #make an argument for entering furnace installed afue\n afue = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"afue\",true)\n afue.setDisplayName(\"Installed AFUE\")\n afue.setUnits(\"Btu/Btu\")\n afue.setDescription(\"The installed Annual Fuel Utilization Efficiency (AFUE) of the furnace, which can be used to account for performance derating or degradation relative to the rated value.\")\n afue.setDefaultValue(1.0)\n args << afue\n\n #make an argument for entering furnace installed supply fan power\n fanpower = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"fan_power_installed\",true)\n fanpower.setDisplayName(\"Installed Supply Fan Power\")\n fanpower.setUnits(\"W/cfm\")\n fanpower.setDescription(\"Fan power (in W) per delivered airflow rate (in cfm) of the indoor fan for the maximum fan speed under actual operating conditions.\")\n fanpower.setDefaultValue(0.5)\n args << fanpower\t\n\t\n #make a string argument for furnace heating output capacity\n furnacecap = OpenStudio::Measure::OSArgument::makeStringArgument(\"capacity\", true)\n furnacecap.setDisplayName(\"Heating Capacity\")\n furnacecap.setDescription(\"The output heating capacity of the furnace. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n furnacecap.setUnits(\"kBtu/hr\")\n furnacecap.setDefaultValue(Constants.SizingAuto)\n args << furnacecap\n \n return args\n end", "def greeting(args)\r\n greet = args[:greet] || \"Hi\"\r\n title = args[:title] || \"Citizen\"\r\n name = args[:name] \r\n puts \"#{greet} #{title} #{name}\"\r\nend", "def parse_args\n\t\t@args = @args_a.each_slice(2).to_a.inject({}) { |h, k| h[k[0]] = k[1]; h }\n\t\tkeys = @skeys + @lkeys\n\t\t@args.each do |k, v|\n\t\t\tif !keys.include?(k)\n\t\t\t\tputs \"Unknown option `#{k}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif keys.include?(v)\n\t\t\t\tputs \"Missing values for `#{k}' and `#{v}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif v != nil\n\t\t\t\tif v.start_with?('-')\n\t\t\t\t\tputs \"Warning: Value of `#{k}' appears to be a flag\"\n\t\t\t\tend\n\n\t\t\t\tif @static.has_key?(k)\n\t\t\t\t\tif !@static[k].include?(v)\n\t\t\t\t\t\tputs \"Unknown option `#{v}' for `#{k}'\"\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tif remove_keys(@no_vals).has_blank?\n\t\t\tputs \"Missing argument(s)\"\n\t\t\texit\n\t\tend\t\t\t\n\tend", "def command_line_arguments(array)\n array.size.times do\n if array.include?('-nc')\n colour_changer(:white)\n array.delete('-nc')\n elsif array.any? { |x| ['-d1', '-d2', '-d3', '-d4'].include? x }\n key = (array[0])[1, 2].to_sym\n @difficulty = DIFFICULTY[key]\n @promptarr = prompt_select(key)\n @intro = false\n end\n end\n end", "def arguments()\n args = OpenStudio::Measure::OSArgumentVector.new\n \n #make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Detailed\"\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"Runperiod\"\n reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName(\"Reporting Frequency\")\n reporting_frequency.setDefaultValue(\"Hourly\")\n args << reporting_frequency\n \n # TODO: argument for subset of output meters\n \n return args\n end", "def arguments()\n args = OpenStudio::Measure::OSArgumentVector.new\n\n #make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"RunPeriod\"\n arg = OpenStudio::Measure::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n arg.setDisplayName(\"Reporting Frequency\")\n arg.setDefaultValue(\"Hourly\")\n args << arg\n\n #make an argument for including optional output variables\n arg = OpenStudio::Measure::OSArgument::makeBoolArgument(\"inc_output_variables\", true)\n arg.setDisplayName(\"Include Output Variables\")\n arg.setDefaultValue(false)\n args << arg\n\n return args\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for entering furnace installed afue\n userdefined_eff = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"userdefinedeff\",true)\n userdefined_eff.setDisplayName(\"Efficiency\")\n\tuserdefined_eff.setUnits(\"Btu/Btu\")\n\tuserdefined_eff.setDescription(\"The efficiency of the electric baseboard.\")\n userdefined_eff.setDefaultValue(1.0)\n args << userdefined_eff\n\n #make a choice argument for furnace heating output capacity\n cap_display_names = OpenStudio::StringVector.new\n cap_display_names << Constants.SizingAuto\n (5..150).step(5) do |kbtu|\n cap_display_names << \"#{kbtu} kBtu/hr\"\n end\n\n #make a string argument for furnace heating output capacity\n selected_baseboardcap = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"selectedbaseboardcap\", cap_display_names, true)\n selected_baseboardcap.setDisplayName(\"Heating Output Capacity\")\n selected_baseboardcap.setDefaultValue(Constants.SizingAuto)\n args << selected_baseboardcap\n\t\n return args\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n #make an argument for entering baseboard efficiency\n baseboardeff = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"efficiency\",true)\n baseboardeff.setDisplayName(\"Efficiency\")\n baseboardeff.setUnits(\"Btu/Btu\")\n baseboardeff.setDescription(\"The efficiency of the electric baseboard.\")\n baseboardeff.setDefaultValue(1.0)\n args << baseboardeff\n\n #make a string argument for baseboard heating output capacity\n baseboardcap = OpenStudio::Measure::OSArgument::makeStringArgument(\"capacity\", true)\n baseboardcap.setDisplayName(\"Heating Capacity\")\n baseboardcap.setDescription(\"The output heating capacity of the electric baseboard. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n baseboardcap.setUnits(\"kBtu/hr\")\n baseboardcap.setDefaultValue(Constants.SizingAuto)\n args << baseboardcap\n\t\n return args\n end", "def user_input_command_line_menu\n\tcommand_line_input = gets.strip.to_i\n\tcommand_line_input_logic(command_line_input)\nend", "def cmdarg; end", "def cmdarg; end", "def cmdarg; end", "def check_inputs_g(args)\n raise TypeError, Ajaila::Messager.warning(\"Nothing to generate...\") if args == []\n raise TypeError, Ajaila::Messager.warning(\"Only miners, selectors, presenters supported\\n(ex. miner SomeMiner, selector SomeSelector,\\n presenter SomePresenter, table SomeTable)\") if KNOWN_INSTANCES.include?(args[0]) == false\n raise TypeError, Ajaila::Messager.warning(\"Your #{args[0]} needs a name!\") if args[1] == nil\n raise TypeError, Ajaila::Messager.warning(\"Wrong format of the #{args[0]} name (use only A-Z and a-z symbols)\") if args[1][/^[A-Z]+$/i] == nil\n return 0\n end", "def arguments\n parser.arguments\n end", "def valid_args(type)\n case type\n when 'search' then %i[q format addressdetails extratags namedetails viewbox bounded exclude_place_ids limit accept-language email]\n when 'reverse' then %i[format lat lon zoom addressdetails extratags namedetails accept-language email]\n else []\n end\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n id = OpenStudio::Measure::OSArgument.makeStringArgument('feature_id', false)\n id.setDisplayName('Feature unique identifier')\n id.setDefaultValue('1')\n args << id\n\n name = OpenStudio::Measure::OSArgument.makeStringArgument('feature_name', false)\n name.setDisplayName('Feature scenario specific name')\n name.setDefaultValue('name')\n args << name\n\n feature_type = OpenStudio::Measure::OSArgument.makeStringArgument('feature_type', false)\n feature_type.setDisplayName('URBANopt Feature Type')\n feature_type.setDefaultValue('Building')\n args << feature_type\n\n feature_location = OpenStudio::Measure::OSArgument.makeStringArgument('feature_location', false)\n feature_location.setDisplayName('URBANopt Feature Location')\n feature_location.setDefaultValue('0')\n args << feature_location\n\n # make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n # reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'BillingPeriod' # match it to utility bill object\n ## Utility report here to report the start and end for each fueltype\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDescription('The frequency at which to report timeseries output data.')\n reporting_frequency.setDefaultValue('Timestep')\n args << reporting_frequency\n\n return args\n end", "def madlib_inputs\n print \"Enter a noun: \" \n noun = gets.chomp\n print \"Enter a verb: \" \n verb = gets.chomp\n print \"Enter an adjective: \" \n adjective = gets.chomp\n print \"Enter an adverb: \" \n adverb = gets.chomp\n madlib_line(noun, verb, adjective, adverb)\nend", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make a start date argument\n start_date = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"start_date\",true)\n start_date.setDisplayName(\"Start date\")\n args << start_date\n \n #make an end date argument\n end_date = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"end_date\",true)\n end_date.setDisplayName(\"End date\")\n args << end_date\n \n return args\n end", "def check_arguments\n convert_boolean_strings\n check_output\n check_log_level\n check_input_entry\n check_input_types\n end", "def process_arguments\n # clean unsupport symbols, e.g. JieFang;\n # or error argument due to option typo, e.g. '-list' will put 'ist' into the array in this src.\n @support_newspapers = Array.new #TODO: move to elsewhere\n @support_newspapers << :XM\n @support_newspapers << :WHB\n @support_newspapers << :YZ\n # ATTENTION: command line input is an array of string, to be consistent, internally I use only symbol when using this symbol\n @options.newspapers = @options.newspapers.collect { | item | item.to_sym } & @support_newspapers\n \n if @options.newspapers.size == 0\n @support_newspapers.each do | sym |\n @options.newspapers << sym\n end\n end\n end", "def args\n raw_args\n end", "def argv; end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make an argument for your name\n code_choices = OpenStudio::StringVector.new \n code_choices << \"ASHRAE 90.1-2007\" \n code_choices << \"ASHRAE 90.1-2010\" \n energy_code = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('energy_code', code_choices, true)\n energy_code.setDisplayName(\"Code baseline\")\n energy_code.setDefaultValue(\"ASHRAE 90.1-2010\")\n args << energy_code\n \n #make an argument to add new space true/false\n leed_check = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"leed_check\",true)\n leed_check.setDisplayName(\"Perform typical LEED checks?\")\n leed_check.setDefaultValue(true)\n args << leed_check\n \n return args\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \t\"os_object_type\"\t],\n [ \"weather_file_name\", \"STRING\", true, false, \"Weather File Name\", nil, nil, nil, nil, \t nil\t\t\t\t\t],\n #Default set for server weather folder.\n [ \"weather_directory\", \"STRING\", true, false, \"Weather Directory\", \"../../weather\", nil, nil, nil,\t nil\t\t\t\t\t]\n \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def inflamed _args\n \"inflamed _args;\" \n end", "def more_options\n puts Rainbow(\"Specify your additional options for your search: 'release date', 'search history', or go back\").yellow.underline\n input = gets.chomp.downcase\n \n if input == \"release date\"\n option_release_date\n \n elsif input == \"search history\"\n game_history\n\n elsif input == \"go back\"\n continue_or_exit\n \n else \n puts \"Input not recognized please try again\"\n more_options\n end\n end", "def cmd(options={})\n arguments\n end", "def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # this measure will require arguments, but at this time, they are not known\n geometry_profile = OpenStudio::Ruleset::OSArgument::makeStringArgument('geometry_profile', true)\n geometry_profile.setDefaultValue(\"{}\")\n os_model = OpenStudio::Ruleset::OSArgument::makeStringArgument('os_model', true)\n os_model.setDefaultValue('multi-model mode')\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id', true)\n user_id.setDefaultValue(\"00000000-0000-0000-0000-000000000000\")\n job_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('job_id', true)\n #job_id.setDefaultValue(SecureRandom.uuid.to_s)\n ashrae_climate_zone = OpenStudio::Ruleset::OSArgument::makeStringArgument('ashrae_climate_zone', false)\n ashrae_climate_zone.setDefaultValue(\"-1\")\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDefaultValue(\"BadDefaultType\")\n\n args << geometry_profile\n args << os_model\n args << user_id\n args << job_id\n args << ashrae_climate_zone\n args << building_type\n\n return args\n end", "def user_input\n\tgets\nend", "def input\n @input ||= args.dig(:input)\n end", "def parse_args\n require 'optimist'\n opts = Optimist.options do\n opt :source, \"Inventory Source UID\", :type => :string, :required => ENV[\"SOURCE_UID\"].nil?, :default => ENV[\"SOURCE_UID\"]\n opt :ingress_api, \"Hostname of the ingress-api route\", :type => :string, :default => ENV[\"INGRESS_API\"] || \"http://localhost:9292\"\n opt :config, \"Configuration file name\", :type => :string, :default => ENV[\"CONFIG\"] || \"default\"\n opt :data, \"Amount & custom values of generated items\", :type => :string, :default => ENV[\"DATA\"] || \"default\"\n end\n\n opts\nend", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # lat arg\n lat = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lat\", true)\n lat.setDisplayName(\"Latitude\")\n lat.setDefaultValue(39.7392000000)\n args << lat\n\n # long arg\n lon = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lon\", true)\n lon.setDisplayName(\"Longitude\")\n lon.setDefaultValue(-104.9903000000)\n args << lon\n\n return args\n end", "def add args\n db = get_db\n if args.empty?\n print \"Enter a short summary: \"\n STDOUT.flush\n text = gets.chomp\n if text.empty?\n exit ERRCODE\n end\n else\n # if you add last arg as P1..P5, I'll update priority automatically\n if args.last =~ /P[1-5]/\n $default_priority = args.pop\n end\n text = args.join \" \"\n end\n # convert actual newline to C-a. slash n's are escapes so echo -e does not muck up.\n #atitle=$( echo \"$atitle\" | tr -cd '\\40-\\176' )\n text.tr! \"\\n\", '\u0001'\n title = text\n desc = nil\n if $prompt_desc\n # choice of vim or this XXX also how to store in case of error or abandon\n # and allow user to edit, so no retyping. This could be for mult fields\n message \"Enter a detailed description (. to exit): \"\n desc = Cmdapp.get_lines\n #message \"You entered #{desc}\"\n end\n type = $default_type || \"bug\"\n severity = $default_severity || \"normal\"\n status = $default_status || \"open\"\n priority = $default_priority || \"P3\"\n if $prompt_type\n type = Cmdapp._choice(\"Select type:\", %w[bug enhancement feature task] )\n #message \"You selected #{type}\"\n end\n if $prompt_priority\n #priority = Cmdapp._choice(\"Select priority:\", %w[normal critical moderate] )\n priority = ask_priority\n #message \"You selected #{severity}\"\n end\n if $prompt_severity\n severity = Cmdapp._choice(\"Select severity:\", %w[normal critical moderate] )\n #message \"You selected #{severity}\"\n end\n if $prompt_status\n status = Cmdapp._choice(\"Select status:\", %w[open started closed stopped canceled] )\n #message \"You selected #{status}\"\n end\n assigned_to = $default_assigned_to\n if $prompt_assigned_to\n message \"Assign to:\"\n #assigned_to = $stdin.gets.chomp\n assigned_to = Cmdapp._gets \"assigned_to\", \"assigned_to\", $default_assigned_to\n #message \"You selected #{assigned_to}\"\n end\n project = component = version = nil\n # project\n if $use_project\n project = Cmdapp.user_input('project', $prompt_project, nil, $valid_project, $default_project)\n end\n if $use_component\n component = Cmdapp.user_input('component', $prompt_component, nil, $valid_component, $default_component)\n end\n if $use_version\n version = Cmdapp.user_input('version', $prompt_version, nil, $valid_version, $default_version)\n end\n\n start_date = @now\n due_date = default_due_date\n comment_count = 0\n priority ||= \"P3\" \n description = desc\n fix = nil #\"Some long text\" \n #date_created = @now\n #date_modified = @now\n body = {}\n body[\"title\"]=title\n body[\"description\"]=description\n body[\"type\"]=type\n body[\"status\"]=status\n body[\"start_date\"]=start_date.to_s\n body[\"due_date\"]=due_date.to_s\n body[\"priority\"]=priority\n body[\"severity\"]=severity\n body[\"assigned_to\"]=assigned_to\n body[\"created_by\"] = $default_user\n # only insert if its wanted by user\n body[\"project\"]=project if $use_project\n body[\"component\"]=component if $use_component\n body[\"version\"]=version if $use_version\n\n rowid = db.table_insert_hash(\"bugs\", body)\n puts \"Issue #{rowid} created\"\n logid = db.sql_logs_insert rowid, \"create\", \"#{rowid} #{type}: #{title}\"\n body[\"id\"] = rowid\n mail_issue nil, body\n \n 0\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"Whole Building\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n\r\n return args\r\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\t\t\n\n #Make a string argument for occupants (auto or number)\n num_occ = OpenStudio::Measure::OSArgument::makeStringArgument(\"num_occ\", false)\n num_occ.setDisplayName(\"Number of Occupants\")\n num_occ.setDescription(\"Specify the number of occupants. For a multifamily building, specify one value for all units or a comma-separated set of values (in the correct order) for each unit. A value of '#{Constants.Auto}' will calculate the average number of occupants from the number of bedrooms. Used to specify the internal gains from people only.\")\n num_occ.setDefaultValue(Constants.Auto)\n args << num_occ\n\n #Make a string argument for 24 weekday schedule values\n weekday_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekday_sch\", true)\n weekday_sch.setDisplayName(\"Weekday schedule\")\n weekday_sch.setDescription(\"Specify the 24-hour weekday schedule.\")\n weekday_sch.setDefaultValue(\"1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 0.88310, 0.40861, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.29498, 0.55310, 0.89693, 0.89693, 0.89693, 1.00000, 1.00000, 1.00000\")\n args << weekday_sch\n \n #Make a string argument for 24 weekend schedule values\n weekend_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekend_sch\", true)\n weekend_sch.setDisplayName(\"Weekend schedule\")\n weekend_sch.setDescription(\"Specify the 24-hour weekend schedule.\")\n weekend_sch.setDefaultValue(\"1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 0.88310, 0.40861, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.29498, 0.55310, 0.89693, 0.89693, 0.89693, 1.00000, 1.00000, 1.00000\")\n args << weekend_sch\n\n #Make a string argument for 12 monthly schedule values\n monthly_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"monthly_sch\", true)\n monthly_sch.setDisplayName(\"Month schedule\")\n monthly_sch.setDescription(\"Specify the 12-month schedule.\")\n monthly_sch.setDefaultValue(\"1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0\")\n args << monthly_sch\n\n return args\n end", "def validate_arguments()\n usage unless ARGV.count > 0\nend", "def input args\n if args.state.inputlist.length > 5\n args.state.inputlist.pop\n end\n\n should_process_special_move = (args.inputs.keyboard.key_down.j) ||\n (args.inputs.keyboard.key_down.k) ||\n (args.inputs.keyboard.key_down.a) ||\n (args.inputs.keyboard.key_down.d) ||\n (args.inputs.controller_one.key_down.y) ||\n (args.inputs.controller_one.key_down.x) ||\n (args.inputs.controller_one.key_down.left) ||\n (args.inputs.controller_one.key_down.right)\n\n if (should_process_special_move)\n if (args.inputs.keyboard.key_down.j && args.inputs.keyboard.key_down.k) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"shield\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.inputlist[0] == \"forward-attack\") && ((args.state.tick_count - args.state.lastpush) <= 15)\n args.state.inputlist.unshift(\"dash-attack\")\n args.state.player.dx = 20\n elsif (args.inputs.keyboard.key_down.j && args.inputs.keyboard.a) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.left)\n args.state.inputlist.unshift(\"back-attack\")\n elsif ( args.inputs.controller_one.key_down.x || args.inputs.keyboard.key_down.j)\n args.state.inputlist.unshift(\"forward-attack\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.player.y > 128)\n args.state.inputlist.unshift(\"dair\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"up-attack\")\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a) &&\n (args.state.inputlist[0] == \"<\") &&\n ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.inputlist.unshift(\"<<\")\n args.state.player.dx = -15\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a)\n args.state.inputlist.unshift(\"<\")\n args.state.timeleft = args.state.tick_count\n elsif (args.inputs.controller_one.key_down.right || args.inputs.keyboard.key_down.d)\n args.state.inputlist.unshift(\">\")\n end\n\n args.state.lastpush = args.state.tick_count\n end\n\n if args.inputs.keyboard.space || args.inputs.controller_one.r2 # if the user presses the space bar\n args.state.player.jumped_at ||= args.state.tick_count # jumped_at is set to current frame\n\n # if the time that has passed since the jump is less than the player's jump duration and\n # the player is not falling\n if args.state.player.jumped_at.elapsed_time < args.state.player_jump_power_duration && !args.state.player.falling\n args.state.player.dy = args.state.player_jump_power # change in y is set to power of player's jump\n end\n end\n\n # if the space bar is in the \"up\" state (or not being pressed down)\n if args.inputs.keyboard.key_up.space || args.inputs.controller_one.key_up.r2\n args.state.player.jumped_at = nil # jumped_at is empty\n args.state.player.falling = true # the player is falling\n end\n\n if args.inputs.left # if left key is pressed\n if args.state.player.dx < -5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = -5\n end\n\n elsif args.inputs.right # if right key is pressed\n if args.state.player.dx > 5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = 5\n end\n else\n args.state.player.dx *= args.state.player_speed_slowdown_rate # dx is scaled down\n end\n\n if ((args.state.player.dx).abs > 5) #&& ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.player.dx *= 0.95\n end\nend", "def arguments(model = nil)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n chs = OpenStudio::StringVector.new\n chs << 'Last OSM'\n chs << 'Last IDF'\n file_source = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('file_source', chs, true)\n file_source.setDisplayName('Model Source')\n file_source.setDefaultValue('Last OSM')\n args << file_source\n\n chs = OpenStudio::StringVector.new\n chs << 'Timestep'\n chs << 'Hourly'\n reporting_frequency = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('reporting_frequency', chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n variable1_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable1_name', true)\n variable1_name.setDisplayName('Variable 1 Name')\n variable1_name.setDefaultValue('Surface Outside Face Temperature')\n args << variable1_name\n\n variable2_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable2_name', true)\n variable2_name.setDisplayName('Variable 2 Name')\n variable2_name.setDefaultValue('Surface Inside Face Temperature')\n args << variable2_name\n\n variable3_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable3_name', true)\n variable3_name.setDisplayName('Variable 3 Name')\n variable3_name.setDefaultValue('Zone Mean Radiant Temperature')\n args << variable3_name\n\n return args\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # Create a list of the names and handles of space types\n # used in the building.\n used_space_type_handles = OpenStudio::StringVector.new\n used_space_type_names = OpenStudio::StringVector.new\n model.getSpaceTypes.sort.each do |space_type|\n if space_type.spaces.size > 0 # only show space types used in the building\n used_space_type_handles << space_type.handle.to_s\n used_space_type_names << space_type.name.to_s\n end\n end\n\t\n # Make an argument for plenum space type\n ceiling_return_plenum_space_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"ceiling_return_plenum_space_type\", used_space_type_handles, used_space_type_names,false)\n ceiling_return_plenum_space_type.setDisplayName(\"This space type should be part of a ceiling return air plenum.\")\n args << ceiling_return_plenum_space_type\n\t\n # Make a bool argument to edit/not edit each space type\n\t\tmodel.getSpaceTypes.sort.each do |space_type|\n\t\t\tif space_type.spaces.size > 0 # only show space types used in the building\n\t\t\t\tspace_type_to_edit = OpenStudio::Ruleset::OSArgument::makeBoolArgument(space_type.name.get.to_s,false)\n\t\t\t\t# Make a bool argument for this space type\n\t\t\t\tspace_type_to_edit.setDisplayName(\"Add #{space_type.name.get} space type to GSHP system?\")\n\t\t\t\tspace_type_to_edit.setDefaultValue(false)\t\t\n\t\t\t\targs << space_type_to_edit\n\t\t\tend\n\t\tend\n\t \n\t\t# Heating COP of GSHP\n\t\tgshp_htg_cop = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"gshp_htg_cop\",false)\n\t\tgshp_htg_cop.setDisplayName(\"GSHP DX Heating Coil Heating COP\")\n\t\tgshp_htg_cop.setDefaultValue(4.0)\n\t\targs << gshp_htg_cop\n\t\t\n\t\t# Cooling EER of GSHP\n\t\tgshp_clg_eer = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"gshp_clg_eer\",false)\n\t\tgshp_clg_eer.setDisplayName(\"GSHP DX Cooling Coil Cooling EER\")\n\t\tgshp_clg_eer.setDefaultValue(14)\n\t\targs << gshp_clg_eer\n\t\t\n\t\t# GSHP Fan Type PSC or ECM\n\t\tfan_choices = OpenStudio::StringVector.new\n\t\tfan_choices << \"PSC\"\n\t\tfan_choices << \"ECM\"\n\t\tgshp_fan_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"gshp_fan_type\",fan_choices,true) # note ECM fan type may correspond to different set of heat pump performance curves\n\t\tgshp_fan_type.setDisplayName(\"GSHP Fan Type: PSC or ECM?\")\n\t\tgshp_fan_type.setDefaultValue(\"PSC\")\n args << gshp_fan_type\n\t\t\n\t\t# Condenser Loop Cooling Temperature\n\t\t# condLoopCoolingTemp = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"condLoopCoolingTemp\",false)\n\t\t# condLoopCoolingTemp.setDisplayName(\"Condenser Loop Cooling Temperature (F)\")\n\t\t# condLoopCoolingTemp.setDefaultValue(90)\n\t\t# args << condLoopCoolingTemp\n\t\t\n\t\t# Condenser Loop Heating Temperature\n\t\t# condLoopHeatingTemp = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"condLoopHeatingTemp\",false)\n\t\t# condLoopHeatingTemp.setDisplayName(\"Condenser Loop Heating Temperature (F)\")\n\t\t# condLoopHeatingTemp.setDefaultValue(60)\t\n\t\t# args << condLoopHeatingTemp\n\t\t\n\t\t# Vertical Bore HX\n\t\tbuilding_area = model.getBuilding.floorArea \n\t\tbuilding_cool_ton = building_area*10.7639/500\t\t# 500sf/ton estimated\n\t\tbore_hole_no = OpenStudio::Ruleset::OSArgument::makeIntegerArgument(\"bore_hole_no\",false)\n\t\tbore_hole_no.setDisplayName(\"Number of Bore Holes\")\n\t\tbore_hole_no.setDefaultValue(building_cool_ton.to_i) \n\t\targs << bore_hole_no\n\n\t\t\n\t\tbore_hole_length = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"bore_hole_length\",false)\n\t\tbore_hole_length.setDisplayName(\"Bore Hole Length (ft)\")\n\t\tbore_hole_length.setDefaultValue(200)\n\t\targs << bore_hole_length\n\n\t\tbore_hole_radius = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"bore_hole_radius\",false)\n\t\tbore_hole_radius.setDisplayName(\"Bore Hole Radius (inch)\")\n\t\tbore_hole_radius.setDefaultValue(6.0)\n\t\targs << bore_hole_radius\n\t\t\n\t\tground_k_value = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"ground_k_value\",false)\n\t\tground_k_value.setDisplayName(\"Ground Conductivity (Btu/hr.F.R\")\n\t\tground_k_value.setDefaultValue(0.75)\n\t\targs << ground_k_value\n\t\t\n\t\tgrout_k_value = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"grout_k_value\",false)\n\t\tgrout_k_value.setDisplayName(\"Grout Conductivity (Btu/hr.F.R\")\n\t\tgrout_k_value.setDefaultValue(0.75)\n\t\targs << grout_k_value\n\t\t\n\t\tchs = OpenStudio::StringVector.new\n\t\tchs << \"Yes\"\n\t\tchs << \"No\"\n\t\tsupplemental_boiler = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"supplemental_boiler\",chs, true)\n\t\tsupplemental_boiler.setDisplayName(\"Supplemental Heating Boiler?\")\n\t\tsupplemental_boiler.setDefaultValue(\"No\")\n\t\targs << supplemental_boiler\n\t\t\n\t\t# Boiler Capacity\n\t\tboiler_cap = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_cap\",false)\n\t\tboiler_cap.setDisplayName(\"boiler normal capacity (MBtuh)\")\n\t\tboiler_cap.setDefaultValue(500.0)\n\t\targs << boiler_cap\n\t\t\t\t\n\t\t# Boiler Efficiency\n\t\tboiler_eff = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_eff\",false)\n\t\tboiler_eff.setDisplayName(\"Boiler Thermal Efficiency\")\n\t\tboiler_eff.setDefaultValue(0.9)\n\t\targs << boiler_eff\n\t\t\n\t\t# Boiler fuel Type\n\t\tfuel_choices = OpenStudio::StringVector.new\n\t\tfuel_choices << \"NaturalGas\"\n\t\tfuel_choices << \"PropaneGas\"\n\t\tfuel_choices << \"FuelOil#1\"\n\t\tfuel_choices << \"FuelOil#2\"\n\t\tfuel_choices << \"Electricity\"\n\t\tboiler_fuel_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"boiler_fuel_type\",fuel_choices,false) \n\t\tboiler_fuel_type.setDisplayName(\"Boiler Fuel Type\")\n\t\tboiler_fuel_type.setDefaultValue(\"NaturalGas\")\n\t\targs << boiler_fuel_type\n\t\t\n\t\t# boiler Hot water supply temperature\n\t\tboiler_hw_st = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_hw_st\",false)\n\t\tboiler_hw_st.setDisplayName(\"Boiler Design Heating Water Outlet Temperature (F)\")\n\t\tboiler_hw_st.setDefaultValue(120)\t\n\t\targs << boiler_hw_st\n\t\t\n\t\t# DOAS Fan Type\n\t\tdoas_fan_choices = OpenStudio::StringVector.new\n\t\tdoas_fan_choices << \"Constant\"\n\t\tdoas_fan_choices << \"Variable\"\n\t\tdoas_fan_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_fan_type\",doas_fan_choices,true)\n\t\tdoas_fan_type.setDisplayName(\"DOAS Fan Flow Control - Variable means DCV controls\")\n\t\tdoas_fan_type.setDefaultValue(\"Variable\")\n\t\targs << doas_fan_type\n\t\t\n\t\t# DOAS Energy Recovery\n\t\terv_choices = OpenStudio::StringVector.new\n\t\terv_choices << \"plate w/o economizer lockout\"\n\t\terv_choices << \"plate w/ economizer lockout\"\n\t\terv_choices << \"rotary wheel w/o economizer lockout\"\n\t\terv_choices << \"rotary wheel w/ economizer lockout\"\n\t\terv_choices << \"none\"\n\t\tdoas_erv = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_erv\",erv_choices,true)\n\t\tdoas_erv.setDisplayName(\"DOAS Energy Recovery?\")\n\t\tdoas_erv.setDefaultValue(\"none\")\n\t\targs << doas_erv\n\t\t\n\t\t# DOAS Evaporative Cooling\n\t\tevap_choices = OpenStudio::StringVector.new\n\t\tevap_choices << \"Direct Evaporative Cooler\"\n\t\tevap_choices << \"none\"\n\t\tdoas_evap = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_evap\",evap_choices,true)\n\t\tdoas_evap.setDisplayName(\"DOAS Direct Evaporative Cooling?\")\n\t\tdoas_evap.setDefaultValue(\"none\")\n\t\targs << doas_evap\n\t\t\n\t\t# DOAS DX Cooling\n\t\tdoas_dx_eer = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"doas_dx_eer\",false)\n\t\tdoas_dx_eer.setDisplayName(\"DOAS DX Cooling EER\")\n\t\tdoas_dx_eer.setDefaultValue(10.0)\n\t\targs << doas_dx_eer\n\t\n # make an argument for material and installation cost\n # todo - I would like to split the costing out to the air loops weighted by area of building served vs. just sticking it on the building\n cost_total_hvac_system = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cost_total_hvac_system\",true)\n cost_total_hvac_system.setDisplayName(\"Total Cost for HVAC System ($).\")\n cost_total_hvac_system.setDefaultValue(0.0)\n args << cost_total_hvac_system\n \n #make an argument to remove existing costs\n remake_schedules = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"remake_schedules\",true)\n remake_schedules.setDisplayName(\"Apply recommended availability and ventilation schedules for air handlers?\")\n remake_schedules.setDefaultValue(true)\n args << remake_schedules\n\n return args\n end", "def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n stp = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"stp\", true)\r\n stp.setDisplayName(\"Timeseries Timestep\")\r\n stp.setDescription(\"Timeseries Timestep\")\r\n stp.setDefaultValue(\"Zone Timestep\")\r\n args << stp\r\n \r\n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\r\n env.setDisplayName(\"availableEnvPeriods\")\r\n env.setDescription(\"availableEnvPeriods\")\r\n env.setDefaultValue(\"RUN PERIOD 1\")\r\n args << env\r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n scale = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"scale\", true)\r\n scale.setDisplayName(\"scale factor to apply to the difference\")\r\n scale.setDescription(\"scale factor to apply to the difference\")\r\n scale.setDefaultValue(1)\r\n args << scale \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n \r\n algorithm_download = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"algorithm_download\", true)\r\n algorithm_download.setDisplayName(\"algorithm_download\")\r\n algorithm_download.setDescription(\"algorithm_download\")\r\n algorithm_download.setDefaultValue(false)\r\n args << algorithm_download \r\n \r\n plot_flag = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"plot_flag\", true)\r\n plot_flag.setDisplayName(\"plot_flag timeseries data\")\r\n plot_flag.setDescription(\"plot_flag timeseries data\")\r\n plot_flag.setDefaultValue(true)\r\n args << plot_flag\r\n \r\n plot_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"plot_name\", true)\r\n plot_name.setDisplayName(\"Plot name\")\r\n plot_name.setDescription(\"Plot name\")\r\n plot_name.setDefaultValue(\"\")\r\n args << plot_name\r\n \r\n warning_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"warning_messages\", true)\r\n warning_messages.setDisplayName(\"warning_messages\")\r\n warning_messages.setDescription(\"warning_messages\")\r\n warning_messages.setDefaultValue(false)\r\n args << warning_messages\r\n\r\n return args\r\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # the name of the space to add to the model\n setpoint = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"setpoint_temperature\", true)\n setpoint.setUnits(\"Degrees Celsius\")\n setpoint.setDisplayName(\"Ambient Loop Temperature\")\n setpoint.setDefaultValue(20)\n setpoint.setDescription(\"Temperature setpoint for the ambient loop\")\n args << setpoint\n\n delta = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"design_delta\", true)\n delta.setUnits(\"Delta Temperature\")\n delta.setDefaultValue(5.55) # 10 Deg F default delta\n delta.setDisplayName(\"Delta Design Loop Temperature\")\n delta.setDescription(\"Delta design temperature for the ambient loop\")\n args << delta\n\n return args\n end", "def arguments\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n return args\n end", "def print_two_again(arg1, arg2) # Non-variable list of inputs it will accept\n puts \"arg1: #{arg1}, arg2: #{arg2}\"\nend", "def commander _args\n \"commander _args;\" \n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make a string argument for furnace fuel type\n fuel_display_names = OpenStudio::StringVector.new\n fuel_display_names << Constants.FuelTypeGas\n fuel_display_names << Constants.FuelTypeOil\n fuel_display_names << Constants.FuelTypePropane\n fuel_display_names << Constants.FuelTypeElectric\n fuel_type = OpenStudio::Measure::OSArgument::makeChoiceArgument('fuel_type', fuel_display_names, true)\n fuel_type.setDisplayName('Fuel Type')\n fuel_type.setDescription('Type of fuel used for heating.')\n fuel_type.setDefaultValue(Constants.FuelTypeGas)\n args << fuel_type\n\n # make an argument for entering furnace installed afue\n afue = OpenStudio::Measure::OSArgument::makeDoubleArgument('afue', true)\n afue.setDisplayName('Installed AFUE')\n afue.setUnits('Btu/Btu')\n afue.setDescription('The installed Annual Fuel Utilization Efficiency (AFUE) of the furnace, which can be used to account for performance derating or degradation relative to the rated value.')\n afue.setDefaultValue(0.78)\n args << afue\n\n # make an argument for entering furnace installed supply fan power\n fan_power_installed = OpenStudio::Measure::OSArgument::makeDoubleArgument('fan_power_installed', true)\n fan_power_installed.setDisplayName('Installed Supply Fan Power')\n fan_power_installed.setUnits('W/cfm')\n fan_power_installed.setDescription('Fan power (in W) per delivered airflow rate (in cfm) of the indoor fan for the maximum fan speed under actual operating conditions.')\n fan_power_installed.setDefaultValue(0.5)\n args << fan_power_installed\n\n # make a string argument for furnace heating output capacity\n capacity = OpenStudio::Measure::OSArgument::makeStringArgument('capacity', true)\n capacity.setDisplayName('Heating Capacity')\n capacity.setDescription(\"The output heating capacity of the furnace. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n capacity.setUnits('kBtu/hr')\n capacity.setDefaultValue(Constants.SizingAuto)\n args << capacity\n\n # make a string argument for distribution system efficiency\n dse = OpenStudio::Measure::OSArgument::makeStringArgument('dse', true)\n dse.setDisplayName('Distribution System Efficiency')\n dse.setDescription('Defines the energy losses associated with the delivery of energy from the equipment to the source of the load.')\n dse.setDefaultValue('NA')\n args << dse\n\n # make a bool argument for open hvac flue\n has_hvac_flue = OpenStudio::Measure::OSArgument::makeBoolArgument('has_hvac_flue', true)\n has_hvac_flue.setDisplayName('Air Leakage: Has Open HVAC Flue')\n has_hvac_flue.setDescription('Specifies whether the building has an open flue associated with the HVAC system.')\n has_hvac_flue.setDefaultValue(true)\n args << has_hvac_flue\n\n return args\n end", "def args\n @args\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n return args\n end", "def default_args(a,b,c=1)\n puts \"\\nValues of variables: \",a,b,c\nend", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n \n \t#Make a string argument for 24 weekday cooling set point values\n clg_wkdy = OpenStudio::Measure::OSArgument::makeStringArgument(\"clg_wkdy\", false)\n clg_wkdy.setDisplayName(\"Weekday Setpoint\")\n clg_wkdy.setDescription(\"Specify a single cooling setpoint or a 24-hour comma-separated cooling schedule for the weekdays.\")\n clg_wkdy.setUnits(\"degrees F\")\n clg_wkdy.setDefaultValue(\"76\")\n args << clg_wkdy \n \n \t#Make a string argument for 24 weekend cooling set point values\n clg_wked = OpenStudio::Measure::OSArgument::makeStringArgument(\"clg_wked\", false)\n clg_wked.setDisplayName(\"Weekend Setpoint\")\n clg_wked.setDescription(\"Specify a single cooling setpoint or a 24-hour comma-separated cooling schedule for the weekend.\")\n clg_wked.setUnits(\"degrees F\")\n clg_wked.setDefaultValue(\"76\")\n args << clg_wked\t\n\t\n return args\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n # this measure does not require any user arguments, return an empty list\n return args\n end" ]
[ "0.73753476", "0.73753476", "0.73753476", "0.70890766", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.68296087", "0.6826596", "0.67602986", "0.67480284", "0.6589929", "0.6581451", "0.6579882", "0.65468127", "0.6503042", "0.647451", "0.64706385", "0.64699155", "0.6469245", "0.64641875", "0.64103556", "0.6389132", "0.637863", "0.6374086", "0.6373223", "0.63639134", "0.6358853", "0.6347805", "0.63475585", "0.63470906", "0.6329135", "0.63280094", "0.62932867", "0.6289945", "0.6271416", "0.6257277", "0.6257238", "0.6239814", "0.6235555", "0.62354916", "0.6221531", "0.6221531", "0.6221531", "0.62026656", "0.61958784", "0.61795026", "0.61696565", "0.6168981", "0.6167551", "0.6165484", "0.6161183", "0.6146112", "0.6128867", "0.611614", "0.6099537", "0.609091", "0.608763", "0.6082464", "0.60754794", "0.6075173", "0.60703015", "0.6069249", "0.6053929", "0.60461015", "0.6037139", "0.6037139", "0.603555", "0.6028014", "0.60276234", "0.6026254", "0.6021278", "0.6006005", "0.60050625", "0.60002536", "0.5998068", "0.5990844", "0.5986098", "0.59826887", "0.59739846", "0.59692407", "0.59684443", "0.5966365", "0.59595567" ]
0.0
-1
define what happens when the measure is run
def run(model, runner, user_arguments) super(model, runner, user_arguments) # use the built-in error checking if !runner.validateUserArguments(arguments(model), user_arguments) return false end # assign the user inputs to variables material_cost_insulation_increase_ip = runner.getDoubleArgumentValue('material_cost_insulation_increase_ip', user_arguments) material_cost_sri_increase_ip = runner.getDoubleArgumentValue('material_cost_sri_increase_ip', user_arguments) # no validation needed for cost inputs, negative values are fine, however negative would be odd choice since this measure only improves vs. decreases insulation and SRI performance # global variables for costs expected_life = 25 years_until_costs_start = 0 material_cost_insulation_increase_si = OpenStudio.convert(material_cost_insulation_increase_ip, '1/ft^2', '1/m^2').get material_cost_sri_increase_si = OpenStudio.convert(material_cost_sri_increase_ip, '1/ft^2', '1/m^2').get running_cost_insulation = 0 running_cost_sri = 0 # prepare rule hash rules = [] # climate zone, roof type, thermal transmittance (Btu/h·ft2·°F), SRI # IEAD rules << ['1', 'IEAD', 0.048, 78.0] # R-20.0 ci. rules << ['2', 'IEAD', 0.039, 78.0] # R-25.0 ci. rules << ['3', 'IEAD', 0.039, 78.0] # R-25.0 ci. rules << ['4', 'IEAD', 0.032, 0] # R-30.0 ci., SRI Comply with Standard 90.1 rules << ['5', 'IEAD', 0.032, 0] # R-30.0 ci., SRI Comply with Standard 90.1 rules << ['6', 'IEAD', 0.032, 0] # R-30.0 ci., SRI Comply with Standard 90.1 rules << ['7', 'IEAD', 0.028, 0] # R-35.0 ci., SRI Comply with Standard 90.1 rules << ['8', 'IEAD', 0.028, 0] # R-35.0 ci., SRI Comply with Standard 90.1 # Attic rules << ['1', 'Attic', 0.027, 78.0] # R-38.0 rules << ['2', 'Attic', 0.027, 78.0] # R-38.0 rules << ['3', 'Attic', 0.027, 78.0] # R-38.0 rules << ['4', 'Attic', 0.021, 0] # R-49.0, SRI Comply with Standard 90.1 rules << ['5', 'Attic', 0.021, 0] # R-49.0, SRI Comply with Standard 90.1 rules << ['6', 'Attic', 0.021, 0] # R-49.0, SRI Comply with Standard 90.1 rules << ['7', 'Attic', 0.017, 0] # R-60.0, SRI Comply with Standard 90.1 rules << ['8', 'Attic', 0.017, 0] # R-60.0, SRI Comply with Standard 90.1 # Metal rules << ['1', 'Metal', 0.041, 78.0] # R-19.0 + R-10.0 FC (confirm same change as K12 using 0.041 vs. 0.057) rules << ['2', 'Metal', 0.041, 78.0] # R-19.0 + R-10.0 FC (confirm same change as K12 using 0.041 vs. 0.057) rules << ['3', 'Metal', 0.041, 78.0] # R-19.0 + R-10.0 FC (confirm same change as K12 using 0.041 vs. 0.057) rules << ['4', 'Metal', 0.035, 0] # R-19.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ['5', 'Metal', 0.031, 0] # R-25.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ['6', 'Metal', 0.031, 0] # R-25.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ['7', 'Metal', 0.029, 0] # R-30.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ['8', 'Metal', 0.026, 0] # R-25.0 + R-11 + R-11 Ls, SRI Comply with Standard 90.1 # make rule hash for cleaner code rulesHash = {} rules.each do |rule| rulesHash["#{rule[0]} #{rule[1]}"] = { 'conductivity_ip' => rule[2], 'sri' => rule[3] } end # get climate zone climateZoneNumber = OsLib_AedgMeasures.getClimateZoneNumber(model, runner) # climateZoneNumber = "4" # this is just in for quick testing of different climate zones # add message for climate zones 4-8 about SRI (while the office AEDG doesn't mention this in table like the K-12 AEDG does, still seems like relevant message.) if climateZoneNumber == false return false elsif climateZoneNumber.to_f > 3 runner.registerInfo("For Climate Zone #{climateZoneNumber} Solar Reflectance Index (SRI) should comply with Standard 90.1.") end # get starting r-value and SRI ranges startingRvaluesExtRoof = [] startingRvaluesAtticInterior = [] startingSriExtRoof = [] # flag for roof surface type for tips ieadFlag = false metalFlag = false atticFlag = false # affected area counter insulation_affected_area = 0 sri_affected_area = 0 # construction hashes (construction is key, value is array [thermal transmittance (Btu/h·ft2·°F), SRI,rule thermal transmittance (Btu/h·ft2·°F), rule SRI,classification string) ieadConstructions = {} metalConstructions = {} atticConstructions = {} # will initially load all constructions used in model, and will delete later if passes test # this contains constructions that should not have exterior roofs assigned otherConstructions = [] # make array for spaces that have a surface with at least one exterior attic surface atticSpaces = [] # loop through constructions constructions = model.getConstructions constructions.each do |construction| # skip if not used next if construction.getNetArea <= 0 # skip if not opaque next if !construction.isOpaque # get construction and standard constructionStandard = construction.standardsInformation # get roof type intendedSurfaceType = constructionStandard.intendedSurfaceType constructionType = constructionStandard.standardsConstructionType # get conductivity conductivity_si = construction.thermalConductance.get r_value_ip = OpenStudio.convert(1 / conductivity_si, 'm^2*K/W', 'ft^2*h*R/Btu').get # get SRI (only need of climate zones 1-3) sri = OsLib_Constructions.getConstructionSRI(construction) # flags for construction loop ruleRvalueFlag = true ruleSriFlag = true # IEAD and Metal roofs should have intendedSurfaceType of ExteriorRoof if intendedSurfaceType.to_s == 'ExteriorRoof' if constructionType.to_s == 'IEAD' # store starting values startingRvaluesExtRoof << r_value_ip startingSriExtRoof << sri ieadFlag = true # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} IEAD"] if 1 / r_value_ip > ruleSet['conductivity_ip'] ruleRvalueFlag = false end if sri < ruleSet['sri'] ruleSriFlag = false end if !ruleRvalueFlag || !ruleSriFlag ieadConstructions[construction] = { 'conductivity_ip' => 1 / r_value_ip, 'sri' => sri, 'transmittance_ip_rule' => ruleSet['conductivity_ip'], 'sri_rule' => ruleSet['sri'], 'classification' => 'ieadConstructions' } end elsif constructionType.to_s == 'Metal' # store starting values startingRvaluesExtRoof << r_value_ip startingSriExtRoof << sri metalFlag = true # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} Metal"] if 1 / r_value_ip > ruleSet['conductivity_ip'] ruleRvalueFlag = false end if sri < ruleSet['sri'] ruleSriFlag = false end if !ruleRvalueFlag || !ruleSriFlag metalConstructions[construction] = { 'conductivity_ip' => 1 / r_value_ip, 'sri' => sri, 'transmittance_ip_rule' => ruleSet['conductivity_ip'], 'sri_rule' => ruleSet['sri'], 'classification' => 'metalConstructions' } end else # create warning if a construction passing through here is used on a roofCeiling surface with a boundary condition of "Outdoors" otherConstructions << construction end elsif (intendedSurfaceType.to_s == 'AtticRoof') || (intendedSurfaceType.to_s == 'AtticWall') || (intendedSurfaceType.to_s == 'AtticFloor') # store starting values atticFlag = true atticConstructions[construction] = { 'conductivity_ip' => 1 / r_value_ip, 'sri' => sri } # will extend this hash later else # create warning if a construction passing through here is used on a roofCeiling surface with a boundary condition of "Outdoors" otherConstructions << construction end end # create warning if construction used on exterior roof doesn't have a surface type of "ExteriorRoof", or if constructions tagged to be used as roof, are used on other surface types otherConstructionsWarned = [] atticSurfaces = [] # to test against attic spaces later on surfaces = model.getSurfaces surfaces.each do |surface| if !surface.construction.empty? construction = surface.construction.get # populate attic spaces if (surface.outsideBoundaryCondition == 'Outdoors') && atticConstructions.include?(construction) if !surface.space.empty? if !atticSpaces.include? surface.space.get atticSpaces << surface.space.get end end elsif atticConstructions.include? construction atticSurfaces << surface end if (surface.outsideBoundaryCondition == 'Outdoors') && (surface.surfaceType == 'RoofCeiling') if otherConstructions.include?(construction) && (!otherConstructionsWarned.include? construction) runner.registerWarning("#{construction.name} is used on one or more exterior roof surfaces but has an intended surface type or construction type not recognized by this measure. As we can not infer the proper performance target, this construction will not be altered.") otherConstructionsWarned << construction end else if ieadConstructions.include?(construction) || metalConstructions.include?(construction) runner.registerWarning("#{surface.name} uses #{construction.name} as a construction that this measure expects to be used for exterior roofs. This surface has a type of #{surface.surfaceType} and a a boundary condition of #{surface.outsideBoundaryCondition}. This may result in unexpected changes to your model.") end end end end # hashes to hold classification of attic surfaces atticSurfacesInterior = {} # this will include paris of matched surfaces atticSurfacesExteriorExposed = {} atticSurfacesExteriorExposedNonRoof = {} atticSurfacesOtherAtticDemising = {} # look for attic surfaces that are not in attic space or matched to them. atticSpaceWarning = false atticSurfaces.each do |surface| if !surface.space.empty? space = surface.space.get if !atticSpaces.include? space if surface.outsideBoundaryCondition == 'Surface' # get space of matched surface and see if it is also an attic next if surface.adjacentSurface.empty? adjacentSurface = surface.adjacentSurface.get next if adjacentSurface.space.empty? adjacentSurfaceSpace = adjacentSurface.space.get if !atticSpaces.include? adjacentSurfaceSpace atticSpaceWarning = true end else atticSpaceWarning = true end end end end if atticSpaceWarning runner.registerWarning("#{surface.name} uses #{construction.name} as a construction that this measure expects to be used for attics. This surface has a type of #{surface.surfaceType} and a a boundary condition of #{surface.outsideBoundaryCondition}. This may result in unexpected changes to your model.") end # flag for testing interiorAtticSurfaceInSpace = false # loop through attic spaces to classify surfaces with attic intended surface type atticSpaces.each do |atticSpace| atticSurfaces = atticSpace.surfaces # array for surfaces that don't use an attic construction surfacesWithNonAtticConstructions = [] # loop through attic surfaces atticSurfaces.each do |atticSurface| next if atticSurface.construction.empty? construction = atticSurface.construction.get if atticConstructions.include? construction conductivity_ip = atticConstructions[construction]['conductivity_ip'] r_value_ip = 1 / conductivity_ip sri = atticConstructions[construction]['sri'] else surfacesWithNonAtticConstructions << atticSurface.name next end # warn if any exterior exposed roof surfaces are not attic. if atticSurface.outsideBoundaryCondition == 'Outdoors' # only want to change SRI if it is a roof if atticSurface.surfaceType == 'RoofCeiling' # store starting value for SRI startingSriExtRoof << sri atticSurfacesExteriorExposed[atticSurface] = construction else atticSurfacesExteriorExposedNonRoof[atticSurface] = construction end elsif atticSurface.outsideBoundaryCondition == 'Surface' # get space of matched surface and see if it is also an attic next if atticSurface.adjacentSurface.empty? adjacentSurface = atticSurface.adjacentSurface.get next if adjacentSurface.space.empty? adjacentSurfaceSpace = adjacentSurface.space.get if atticSpaces.include?(adjacentSurfaceSpace) && atticSpaces.include?(atticSpace) atticSurfacesOtherAtticDemising[atticSurface] = construction else # store starting values startingRvaluesAtticInterior << r_value_ip atticSurfacesInterior[atticSurface] = construction interiorAtticSurfaceInSpace = true # this is to confirm that space has at least one interior surface flagged as an attic end else runner.registerWarning("Can't infer use case for attic surface with an outside boundary condition of #{atticSurface.outsideBoundaryCondition}.") end end # warning message for each space that has mix of attic and non attic constructions runner.registerWarning("#{atticSpace.name} has surfaces with a mix of attic and non attic constructions which may produce unexpected results. The following surfaces use constructions not tagged as attic and will not be altered: #{surfacesWithNonAtticConstructions.sort.join(',')}.") # confirm that all spaces have at least one or more surface of both exterior attic and interior attic if !interiorAtticSurfaceInSpace runner.registerWarning("#{atticSpace.name} has at least one exterior attic surface but does not have an interior attic surface. Please confirm that this space is intended to be an attic and update the constructions used.") end # see if attic is part of floor area and/or if it has people in it if atticSpace.partofTotalFloorArea runner.registerWarning("#{atticSpace.name} is part of the floor area. That is not typical for an attic.") end if !atticSpace.people.empty? runner.registerWarning("#{atticSpace.name} has people. That is not typical for an attic.") end end # hash to look for classification conflicts in attic constructions atticConstructionLog = {} # test attic constructions and identify conflicts # conflict resolution order (insulation,sri,nothing-for demising) atticSurfacesInterior.each do |surface, construction| next if atticConstructionLog[construction] == 'atticSurfacesInterior' conductivity_ip = atticConstructions[construction]['conductivity_ip'] # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} Attic"] if conductivity_ip > ruleSet['conductivity_ip'] atticConstructions[construction] = { 'conductivity_ip' => conductivity_ip, 'sri' => 'NA', 'transmittance_ip_rule' => ruleSet['conductivity_ip'], 'sri_rule' => 'NA', 'classification' => 'atticSurfacesInterior' } else # delete const from main hash atticConstructions.delete(construction) end atticConstructionLog[construction] = 'atticSurfacesInterior' # pass in construction object and the type of rule it was tested against end atticSurfacesExteriorExposed.each do |surface, construction| next if atticConstructionLog[construction] == 'atticSurfacesExteriorExposed' sri = atticConstructions[construction]['sri'] # warn user if construction used on attic interior surface if atticConstructionLog[construction] == 'atticSurfacesInterior' runner.registerWarning("#{surface.name} appears to be an exterior surface but uses a construction #{construction.name} that is also used on interior attic surfaces. The construction was classified and tested as an insulated interior attic construction. You may see unexpected results.") next end # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} Attic"] if sri < ruleSet['sri'] atticConstructions[construction] = { 'conductivity_ip' => 'NA', 'sri' => sri, 'transmittance_ip_rule' => 'NA', 'sri_rule' => ruleSet['sri'], 'classification' => 'atticSurfacesExteriorExposed' } else # delete const from main hash atticConstructions.delete(construction) end atticConstructionLog[construction] = 'atticSurfacesExteriorExposed' # pass in construction object and the type of rule it was tested against end atticSurfacesOtherAtticDemising.each do |k, construction| next if atticConstructionLog[construction] == 'atticSurfacesOtherAtticDemising' sri = atticConstructions[construction]['sri'] # warn user if construction used on attic interior surface if atticConstructionLog[construction] == 'atticSurfacesInterior' runner.registerWarning("#{surface.name} appears to be an exterior surface but uses a construction #{construction.name} that is also used on interior attic surfaces. The construction was classified and tested as an insulated interior attic construction. You may see unexpected results.") next elsif atticConstructionLog[construction] == 'atticSurfacesExteriorExposed' runner.registerWarning("#{surface.name} appears to be an surface between two attic spaces uses a construction #{construction.name} that is also used on exterior attic surfaces. The construction was classified and tested as an insulated interior attic construction. You may see unexpected results.") next end # delete const from main hash. atticConstructions.delete(construction) # No rule test needed for demising. atticConstructionLog[construction] = 'atticSurfacesOtherAtticDemising' # pass in construction object and the type of rule it was tested against end # delete constructions from hash that are non used on roof attic surfaces, but are exterior exposed atticSurfacesExteriorExposedNonRoof.each do |surface, construction| if atticSurfacesExteriorExposed.value? construction # make sure I'm checking for value not key runner.registerWarning("#{surface.name} is a non-roof surface but uses a construction that the measure is treating as an exterior attic roof. Having this associated with a non-roof surface may increase affected area of SRI improvements.") else atticConstructions.delete(construction) end end # alter constructions and add lcc constructionsToChange = ieadConstructions.sort + metalConstructions.sort + atticConstructions.sort constructionsToChange.each do |construction, hash| # gather insulation inputs if hash['transmittance_ip_rule'] != 'NA' # gather target decrease in conductivity conductivity_ip_starting = hash['conductivity_ip'] conductivity_si_starting = OpenStudio.convert(conductivity_ip_starting, 'Btu/ft^2*h*R', 'W/m^2*K').get r_value_ip_starting = 1 / conductivity_ip_starting # ft^2*h*R/Btu r_value_si_starting = 1 / conductivity_si_starting # m^2*K/W conductivity_ip_target = hash['transmittance_ip_rule'].to_f conductivity_si_target = OpenStudio.convert(conductivity_ip_target, 'Btu/ft^2*h*R', 'W/m^2*K').get r_value_ip_target = 1 / conductivity_ip_target # ft^2*h*R/Btu r_value_si_target = 1 / conductivity_si_target # m^2*K/W # infer insulation material to get input for target thickness minThermalResistance = OpenStudio.convert(1, 'ft^2*h*R/Btu', 'm^2*K/W').get inferredInsulationLayer = OsLib_Constructions.inferInsulationLayer(construction, minThermalResistance) rvalue_si_deficiency = r_value_si_target - r_value_si_starting # add lcc for insulation lcc_mat_insulation = OpenStudio::Model::LifeCycleCost.createLifeCycleCost("LCC_Mat_Insulation - #{construction.name}", construction, material_cost_insulation_increase_si, 'CostPerArea', 'Construction', expected_life, years_until_costs_start) lcc_mat_insulation_value = lcc_mat_insulation.get.totalCost running_cost_insulation += lcc_mat_insulation_value # adjust existing material or add new one if inferredInsulationLayer['insulationFound'] # if insulation layer was found # gather inputs for method target_material_rvalue_si = inferredInsulationLayer['construction_thermal_resistance'] + rvalue_si_deficiency # run method to change insulation layer thickness in cloned material (material,starting_r_value_si,target_r_value_si, model) new_material = OsLib_Constructions.setMaterialThermalResistance(inferredInsulationLayer['construction_layer'], target_material_rvalue_si) # connect new material to original construction construction.eraseLayer(inferredInsulationLayer['layer_index']) construction.insertLayer(inferredInsulationLayer['layer_index'], new_material) # get conductivity final_conductivity_si = construction.thermalConductance.get final_r_value_ip = OpenStudio.convert(1 / final_conductivity_si, 'm^2*K/W', 'ft^2*h*R/Btu').get # report on edited material runner.registerInfo("The R-value of #{construction.name} has been increased from #{OpenStudio.toNeatString(r_value_ip_starting, 2, true)} to #{OpenStudio.toNeatString(final_r_value_ip, 2, true)}(ft^2*h*R/Btu) at a cost of $#{OpenStudio.toNeatString(lcc_mat_insulation_value, 2, true)}. Increased performance was accomplished by adjusting thermal resistance of #{new_material.name}.") else # inputs to pass to method conductivity = 0.045 # W/m*K thickness = rvalue_si_deficiency * conductivity # meters addNewLayerToConstruction_Inputs = { 'roughness' => 'MediumRough', 'thickness' => thickness, # meters, 'conductivity' => conductivity, # W/m*K 'density' => 265.0, 'specificHeat' => 836.8, 'thermalAbsorptance' => 0.9, 'solarAbsorptance' => 0.7, 'visibleAbsorptance' => 0.7 } # create new material if can't infer insulation material (construction,thickness, conductivity, density, specificHeat, roughness,thermalAbsorptance, solarAbsorptance,visibleAbsorptance,model) newMaterialLayer = OsLib_Constructions.addNewLayerToConstruction(construction, addNewLayerToConstruction_Inputs) # get conductivity final_conductivity_si = construction.thermalConductance.get final_r_value_ip = OpenStudio.convert(1 / final_conductivity_si, 'm^2*K/W', 'ft^2*h*R/Btu').get # report on edited material runner.registerInfo("The R-value of #{construction.name} has been increased from #{OpenStudio.toNeatString(r_value_ip_starting, 2, true)} to #{OpenStudio.toNeatString(final_r_value_ip, 2, true)}(ft^2*h*R/Btu) at a cost of $#{OpenStudio.toNeatString(lcc_mat_insulation_value, 2, true)}. Increased performance was accomplished by adding a new material layer to the outside of #{construction.name}.") end # add to area counter insulation_affected_area += construction.getNetArea # OpenStudio handles matched surfaces so they are not counted twice. end # gather sri inputs if (hash['sri_rule'] == 78.0) && (hash['sri_rule'] > hash['sri']) # hard assign material properies that will result in an SRI of 78 setConstructionSurfaceProperties_Inputs = { 'thermalAbsorptance' => 0.86, 'solarAbsorptance' => 1 - 0.65 } # alter surface properties (construction,roughness,thermalAbsorptance, solarAbsorptance,visibleAbsorptance) surfaceProperties = OsLib_Constructions.setConstructionSurfaceProperties(construction, setConstructionSurfaceProperties_Inputs) sri = OsLib_Constructions.getConstructionSRI(construction) # add lcc for SRI lcc_mat_sri = OpenStudio::Model::LifeCycleCost.createLifeCycleCost("LCC_Mat_SRI - #{construction.name}", construction, material_cost_sri_increase_si, 'CostPerArea', 'Construction', expected_life, years_until_costs_start) lcc_mat_sri_value = lcc_mat_sri.get.totalCost running_cost_sri += lcc_mat_sri_value # add to area counter sri_affected_area += construction.getNetArea # report performance and cost change for material, or area runner.registerInfo("The Solar Reflectance Index (SRI) of #{construction.name} has been increased from #{OpenStudio.toNeatString(hash['sri'], 0, true)} to #{OpenStudio.toNeatString(sri, 0, true)} for a cost of $#{OpenStudio.toNeatString(lcc_mat_sri_value, 0, true)}. Affected area is #{OpenStudio.toNeatString(OpenStudio.convert(construction.getNetArea, 'm^2', 'ft^2').get, 0, true)} (ft^2)") end end # populate AEDG tip keys aedgTips = [] if ieadFlag aedgTips.push('EN01', 'EN02', 'EN17', 'EN19', 'EN21', 'EN22') end if atticFlag aedgTips.push('EN01', 'EN03', 'EN17', 'EN19', 'EN20', 'EN21') end if metalFlag aedgTips.push('EN01', 'EN04', 'EN17', 'EN19', 'EN21') end # create not applicable of no constructions were tagged to change # if someone had a model with only attic floors and no attic ceilings current logic would flag as not applicable, but a warning would be issued alerting them of the issue (attic surface being used outside of attic space) if aedgTips.empty? runner.registerAsNotApplicable('No surfaces use constructions tagged as a roof type recognized by this measure. No roofs were altered.') return true end # populate how to tip messages aedgTipsLong = OsLib_AedgMeasures.getLongHowToTips('SmMdOff', aedgTips.uniq.sort, runner) if !aedgTipsLong return false # this should only happen if measure writer passes bad values to getLongHowToTips end # reporting initial condition of model startingRvalue = startingRvaluesExtRoof + startingRvaluesAtticInterior # adding non attic and attic values together runner.registerInitialCondition("Starting R-values for constructions intended for insulated roof surfaces range from #{OpenStudio.toNeatString(startingRvalue.min, 2, true)} to #{OpenStudio.toNeatString(startingRvalue.max, 2, true)}(ft^2*h*R/Btu). Starting Solar Reflectance Index (SRI) for constructions intended for exterior roof surfaces range from #{OpenStudio.toNeatString(startingSriExtRoof.min, 0, true)} to #{OpenStudio.toNeatString(startingSriExtRoof.max, 0, true)}.") # reporting final condition of model insulation_affected_area_ip = OpenStudio.convert(insulation_affected_area, 'm^2', 'ft^2').get sri_affected_area_ip = OpenStudio.convert(sri_affected_area, 'm^2', 'ft^2').get runner.registerFinalCondition("#{OpenStudio.toNeatString(insulation_affected_area_ip, 0, true)}(ft^2) of constructions intended for roof surfaces had insulation enhanced at a cost of $#{OpenStudio.toNeatString(running_cost_insulation, 0, true)}. #{OpenStudio.toNeatString(sri_affected_area_ip, 0, true)}(ft^2) of constructions intended for roof surfaces had the Solar Reflectance Index (SRI) enhanced at a cost of $#{OpenStudio.toNeatString(running_cost_sri, 0, true)}. #{aedgTipsLong}") return true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def measure; end", "def measure=(_arg0); end", "def measure\n\t\t1\n\tend", "def measure(*args, &b)\n end", "def communicate_measure_result(_ = nil, _ = nil); end", "def communicate_measure_result(_ = nil, _ = nil); end", "def called\n self.measurement.called\n end", "def measure\n start = Time.now\n yield\n Time.now - start\n end", "def measure\n start = Time.now\n yield\n Time.now - start\n end", "def measure\n Measure.new(1, self)\n end", "def measurement(n)\n @options[:before_hook].call(n)\n measure = measure(n, &@options[:fn])\n @options[:after_hook].call(n)\n measure\n end", "def measure\n Measure.new(@counter+=1)\n end", "def communicate_measure_result(_ = nil, _ = nil)\r\n end", "def benchmark\nend", "def calculated; end", "def setup_metrics\n end", "def setup_metrics\n end", "def setup_metrics\n end", "def run()\n\t\tputs \"#{@name} ran for #{@meters} meters in #{self.getTimeLapse} seconds\"\n\t\t# chiama funzione per stampare quante volte ha respirato\n\t\tself.breathe\n\tend", "def runs; end", "def statistics; end", "def medical_use; end", "def measure\n start_real = System.monotonic_time\n start_cpu = System.cpu_time\n retval = yield\n\n real_time = System.monotonic_time - start_real\n cpu_time = System.cpu_time - start_cpu\n\n @real_time += real_time\n @cpu_time += cpu_time\n @call_count += 1\n\n if call_measurement_enabled? && above_threshold?\n self.class.call_duration_histogram.observe(@transaction.labels.merge(labels), real_time / 1000.0)\n end\n\n retval\n end", "def stats; end", "def stats; end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n\n percent_runtime_reduction = runner.getDoubleArgumentValue(\"percent_runtime_reduction\",user_arguments)\n\n \n \n # Check arguments for reasonableness\n if percent_runtime_reduction >= 100\n runner.registerError(\"Percent runtime reduction must be less than 100.\")\n return false\n end\n\n # Find all the original schedules (before occ sensors installed)\n original_lts_schedules = []\n model.getLightss.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end \n\n # Make copies of all the original lights schedules, reduced to include occ sensor impact\n original_schs_new_schs = {}\n original_lts_schedules.uniq.each do |orig_sch|\n # Copy the original schedule\n new_sch = orig_sch.clone.to_ScheduleRuleset.get\n new_sch.setName(\"#{new_sch.name.get} with occ sensor\")\n # Reduce each value in each profile (except the design days) by the specified amount\n runner.registerInfo(\"Reducing values in '#{orig_sch.name}' schedule by #{percent_runtime_reduction}% to represent occ sensor installation.\")\n day_profiles = []\n day_profiles << new_sch.defaultDaySchedule\n new_sch.scheduleRules.each do |rule|\n day_profiles << rule.daySchedule\n end\n multiplier = (100 - percent_runtime_reduction)/100\n day_profiles.each do |day_profile|\n #runner.registerInfo(\"#{day_profile.name}\")\n times_vals = day_profile.times.zip(day_profile.values)\n #runner.registerInfo(\"original time/values = #{times_vals}\")\n times_vals.each do |time,val|\n day_profile.addValue(time, val * multiplier)\n end\n #runner.registerInfo(\"new time/values = #{day_profile.times.zip(day_profile.values)}\")\n end \n #log the relationship between the old sch and the new, reduced sch\n original_schs_new_schs[orig_sch] = new_sch\n end\n \n # Replace the old schedules with the new, reduced schedules\n spaces_sensors_added_to = []\n model.getLightss.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n \n # Report if the measure is not applicable\n num_sensors_added = spaces_sensors_added_to.uniq.size\n if spaces_sensors_added_to.size == 0\n runner.registerAsNotApplicable(\"This measure is not applicable because there were no lights in the building.\")\n return true\n end \n \n # Report final condition\n runner.registerFinalCondition(\"Added occupancy sensors to #{num_sensors_added} spaces in the building.\")\n\n return true\n\n end", "def run\n\t\t\tsummary\n\t\tend", "def quick_stats\n\tend", "def stats\n \n end", "def benchmark(reporter); end", "def stats\n end", "def stats\n end", "def measure(name, &block)\n if self.running? name\n yield\n else\n result = nil\n self.results[name] ||= 0\n self.running << name\n self.results[name] += Benchmark.measure{result = yield}.real\n self.running.delete(name)\n result\n end\n end", "def measure\n start_real = System.monotonic_time\n start_cpu = System.cpu_time\n retval = yield\n\n real_time = System.monotonic_time - start_real\n cpu_time = System.cpu_time - start_cpu\n\n @real_time += real_time\n @cpu_time += cpu_time\n @call_count += 1\n\n if above_threshold?\n self.class.gitlab_method_call_duration_seconds.observe(@transaction.labels.merge(labels), real_time)\n end\n\n retval\n end", "def measure_code(model,runner)\n measure_folder = \"#{File.dirname(__FILE__)}/\"\n baseline_spreadsheet = \"#{File.dirname(__FILE__)}/baseline.csv\"\n #Note: place output folder locally to run faster! (e.g. your C drive)\n output_folder = \"#{File.dirname(__FILE__)}/tests/output\"\n create_models = true\n simulate_models = true\n create_annual_outputs = true\n create_hourly_outputs = true\n #This creates the measures object and collects all the csv information for the\n # measure_id variant.\n csv_measures = BTAP::Measures::CSV_OS_Measures.new(\n baseline_spreadsheet,\n measure_folder#script root folder where all the csv relative paths are used.\n )\n csv_measures.create_cold_lake_vintages(output_folder) unless create_models == false\n BTAP::SimManager::simulate_all_files_in_folder(output_folder) unless simulate_models == false\n BTAP::Reporting::get_all_annual_results_from_runmanger(output_folder) unless create_annual_outputs == false\n #convert eso to csv then create terminus file.\n BTAP::FileIO::convert_all_eso_to_csv(output_folder, output_folder).each {|csvfile| BTAP::FileIO::terminus_hourly_output(csvfile)} unless create_hourly_outputs == false\n\n end", "def cpu_metrics\n super\n end", "def instrument; end", "def profiler; end", "def profiler; end", "def setup\n\t\n # create an instance of the measure\n @measure = VentilationQAQC.new\n \n #create an instance of the runner\n @runner = OpenStudio::Ruleset::OSRunner.new\t\n\t\n # get arguments \n @arguments = @measure.arguments()\n\n # make argument map\n make_argument_map\n\t\n # Make an empty model\n @model = OpenStudio::Model::Model.new\n\t@runner.setLastOpenStudioModel(@model)\n\t\n\t# Create a fake sql file - our measure will crash if @runner has no sql file set.\n\t# We don't get data from this file because we get data from our patched SqlFile class instead (see above)\n\tsqlFile = OpenStudio::SqlFile.new(OpenStudio::Path.new(sqlPath))\n\t@runner.setLastEnergyPlusSqlFilePath(OpenStudio::Path.new(sqlPath))\n\t\n\t$serieses[\"Zone Mechanical Ventilation Mass Flow Rate|ZONE1\"] = OpenStudio::TimeSeries.new(OpenStudio::Date.new, OpenStudio::Time.new(1.0), (0..364).to_a.to_vector, \"m^3/s\")\n end", "def monitor(*args, &bl)\n result = nil\n took = Benchmark.realtime {\n result = bl.call\n }\n Tools.info(args, op_took: took)\n result\n end", "def measure_code(model,runner)\n ################ Start Measure code here ################################\n \n #Check weather directory Weather File\n unless (Pathname.new @lib_directory).absolute?\n @lib_directory = File.expand_path(File.join(File.dirname(__FILE__), @lib_directory))\n end\n lib_file = File.join(@lib_directory, @lib_file_name)\n if File.exists?(lib_file) and @lib_file_name.downcase.include? \".osm\"\n BTAP::runner_register(\"Info\",\"#{@lib_file_name} Found!.\", runner)\n else\n BTAP::runner_register(\"Error\",\"#{lib_file} does not exist or is not an .osm file.\", runner)\n return false\n end\n \n #load model and test.\n construction_set = BTAP::Resources::Envelope::ConstructionSets::get_construction_set_from_library( lib_file, @construction_set_name )\n #Set Construction Set.\n unless model.building.get.setDefaultConstructionSet( construction_set.clone( model ).to_DefaultConstructionSet.get )\n BTAP::runner_register(\"Error\",\"Could not set Default Construction #{@construction_set_name} \", runner)\n return false\n end\n BTAP::runner_register(\"FinalCondition\",\"Default Construction set to #{@construction_set_name} from #{lib_file}\",runner)\n ##########################################################################\n return true\n end", "def run(workspace, runner, user_arguments)\n super(workspace, runner, user_arguments)\n\n # use the built-in error checking \n if !runner.validateUserArguments(arguments(workspace), user_arguments)\n return false\n end\n \n # Report that this is an anti-measure\n runner.registerValue('anti_measure',true) \n \n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n \n\t# Initialize counter variables\n\tno_economizer = 0\n\tfixed_dry_bulb = 0\n\tdifferential_dry_bulb = 0\t\n\tfixed_enthalpy = 0\n\tdifferential_enthalpy = 0\n\tfixed_dew_point_and_dry_bulb = 0\n\telectronic_enthalpy = 0\n\tdifferential_dry_bulb_and_enthalpy = 0\n\t\n\t# Retrieve all Controller:Outdoor air objects in the idf \t\n\toa_controllers = workspace.getObjectsByType(\"Controller:OutdoorAir\".to_IddObjectType)\n\t\n\t# Get the names of each Controller:Outdoor Air object\n\toa_controllers.each do |oa_controller|\n\n\t\toa_controller_name = oa_controller.getString(0).to_s #(0) is field Name\n\t\toa_controller_economizer_control_type = oa_controller.getString(7).to_s #(7) is field Economizer Control Type\n\t\n\t\t# test for presence No economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"NoEconomizer\" # or empty\n\t\t\trunner.registerInfo(\"The Controller:Outdoor air object named #{oa_controller_name} has a disabled airside economizer. Economizer sensor faults will not be added.\")\n\t\t\tno_economizer = no_economizer + 1\n\t\tend\n\t\t\n\t\t# test for presence of differential dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"DifferentialDryBulb\"\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir \n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\tdifferential_dry_bulb = differential_dry_bulb + 1\n\t\t\t# info message\n\t\t\trunner.registerInfo(\"To model dry bulb sensor drift, a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg F has been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\t\n\n\t\tend # OA Controller Type DifferentialDryBulb\n\n\t\t# test for presence of fixed dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"FixedDryBulb\"\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\trunner.registerInfo(\"To model dry bulb sensor drift, a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg F has been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_dry_bulb = fixed_dry_bulb + 1\n\t\t\t\n\t\tend # OA Controller Type = FixedDryBulb \t\t\n\t\t\n\t\t# test for presence of fixed enthalpy economizer controller setting \t\t\t\t\n\t\tif oa_controller_economizer_control_type == \"FixedEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\twworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_enthalpy = fixed_enthalpy + 1\n\t\tend # OA Controller Type = FixedEnthalpy \n\t\t\n\t\t# test for presence of differential enthalpy economizer controller setting \t\t\n\t\tif oa_controller_economizer_control_type == \"DifferentialEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tdifferential_enthalpy = differential_enthalpy + 1\n\t\t\t\n\t\tend # OA Controller Type =\"Differential Enthalpy\"\t\t\n\t\t\n\t\n\t\t# test for presence of electronic enthalpy economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"ElectronicEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\telectronic_enthalpy = electronic_enthalpy + 1\n\n\t\tend # OA Controller Type = \"ElectronicEnthalpy\" \t\t\n\t\t\n\t\t# test for presence of fixed dew point and dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"FixedDewPointAndDryBulb\" \n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model both enthalpy and dry bulb sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb and a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_dew_point_and_dry_bulb = fixed_dew_point_and_dry_bulb + 1\n\n\t\tend # OA Controller Type = \"FixedDewPointAndDryBulb\" \n\t\n\t\t# test for presence of differential dry bulb and enthalpy economizer controller setting \t\t\n\t\tif oa_controller_economizer_control_type == \"DifferentialDryBulbAndEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model both enthalpy and dry bulb sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb and a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tdifferential_dry_bulb_and_enthalpy = differential_dry_bulb_and_enthalpy + 1\n\t\tend # OA Controller Type \"DifferentialDryBulbAndEnthalpy\"\n\t\t\n\t\t\t\t\n\tend # end loop through oa controller objects\n\n\t# reporting when N/A condition is appropriate\n\tif fixed_dry_bulb +\tdifferential_dry_bulb + fixed_enthalpy + differential_enthalpy + fixed_dew_point_and_dry_bulb +\telectronic_enthalpy + differential_dry_bulb_and_enthalpy == 0\n\t\trunner.registerAsNotApplicable(\"Measure not applicable because the model contains no OutdoorAir:Controller objects with operable economizers.\")\n\tend \n\t\n\ttotal = fixed_dry_bulb + differential_dry_bulb + fixed_enthalpy + differential_enthalpy + fixed_dew_point_and_dry_bulb + electronic_enthalpy + differential_dry_bulb_and_enthalpy\n\t\n\t# reporting initial condition of model\n\trunner.registerInitialCondition(\"The measure started with #{total} Outdoor Air Controllers configured for operational airside economizers. #{no_economizer} Outdoor Air Controller had the Economizer Contrrol Type set to 'NoEconomizer'.\")\n\t# reporting final condition of model\n\trunner.registerFinalCondition(\"The measure finished by adding outdoor and return air temperature and enthalpy sensor faults to #{total} economizer configurations.\")\n \n return true\n \n end", "def calculation\n end", "def monitor; end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n # initialize variables\n affected_space_types = []\n affected_flag = false\n power_tot = 0\n power_tot_new = 0\n control_factor = 0.05 #90.1-2010 Table 9.6.2\n\n # standards space types\n affected_space_types << \"BreakRoom\"\n affected_space_types << \"Conference\"\n affected_space_types << \"Office\"\n affected_space_types << \"Restroom\"\n affected_space_types << \"Stair\"\n\n # get model objects\n space_types = model.getSpaceTypes\n\n # DO STUFF\n #TODO account for zone multipliers?\n space_types.each do |st|\n\n std_spc_typ = st.standardsSpaceType.to_s\n area = st.floorArea\n people = st.getNumberOfPeople(area)\n power = st.getLightingPower(area, people)\n power_tot += power\n\n #calcualte LPD\n lpd_area = power / area\n lpd_people = power / people\n\n affected_space_types.each do |ast|\n\n if ast == std_spc_typ\n\n #calculate adjustment and new power\n power_adj = power * control_factor\n power_new = power - power_adj\n\n lpd_area_new = power_new / area\n lpd_people_new = power_new / people\n\n #set new power\n if st.lightingPowerPerFloorArea.is_initialized\n\n runner.registerInfo(\"Adjusting interior lighting power for space type: #{st.name}\")\n st.setLightingPowerPerFloorArea(lpd_area_new)\n\n lpd_area_ip = OpenStudio.convert(lpd_area,\"ft^2\",\"m^2\").get\n lpd_area_new_ip = OpenStudio.convert(lpd_area_new,\"ft^2\",\"m^2\").get\n lpd_area_change = (1 - (lpd_area_new / lpd_area)) * 100\n\n runner.registerInfo(\"=> Initial interior lighting power = #{lpd_area_ip.round(2)} W/ft2\")\n runner.registerInfo(\"=> Final interior lighting power = #{lpd_area_new_ip.round(2)} W/ft2\")\n runner.registerInfo(\"=> Interior lighting power reduction = #{lpd_area_change.round(0)}%\")\n\n elsif st.lightingPowerPerPerson.is_initialized\n\n runner.registerInfo(\"Adjusting interior lighting power for space type: #{st.name}\")\n st.setLightingPowerPerPerson(lpd_people_new)\n\n lpd_people_change = (1 - (lpd_people_new / lpd_people)) * 100\n\n runner.registerInfo(\"=> Initial interior lighting power = #{lpd_people} W/person\")\n runner.registerInfo(\"=> Final interior lighting power = #{lpd_people_new} W/person\")\n runner.registerInfo(\"=> Interior lighting power reduction = #{lpd_people_change.round(0)}%\")\n\n else\n\n runner.registerWarning(\"Lighting power is specified using Lighting Level (W) for affected space type: #{st.name}\")\n\n end #set new power\n\n affected_flag = true\n\n end\n\n end #affected space types\n\n # calculate new total lighting power\n power = st.getLightingPower(area, people)\n power_tot_new += power\n\n end #space types\n\n # report not applicable\n if affected_flag == false\n runner.registerAsNotApplicable(\"No affected space types found\")\n end\n\n # report initial condition\n runner.registerInitialCondition(\"Total interior lighting power = #{power_tot.round(0)} W\")\n\n # report final condition\n runner.registerFinalCondition(\"Total interior lighting power = #{power_tot_new.round(0)} W\")\n\n return true\n\n end", "def measure key,value\n @context= {}\n @path = \"#{key}\" \n @context[:callcount] = 1\n @context[:firsttimestampoffset] = Time.now.to_f*1000 - value\n @context[:name] = @path\n @context[:responsetime] = value\n @context_list << @context\n end", "def total_time=(_arg0); end", "def run(workspace, runner, user_arguments)\n super(workspace, runner, user_arguments)\n\n #use the built-in error checking \n if not runner.validateUserArguments(arguments(workspace), user_arguments)\n return false\n end\n \n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n \n require 'json'\n \n # Get the last openstudio model\n model = runner.lastOpenStudioModel\n if model.empty?\n runner.registerError(\"Could not load last OpenStudio model, cannot apply measure.\")\n return false\n end\n model = model.get\n \n results = {}\n \n #get all DX coils in model\n dx_single = workspace.getObjectsByType(\"Coil:Cooling:DX:SingleSpeed\".to_IddObjectType)\n dx_two = workspace.getObjectsByType(\"Coil:Cooling:DX:TwoSpeed\".to_IddObjectType)\n \n dx_single.each do |dx|\n dx_name = {}\n coil_name = dx.getString(0).get\n runner.registerInfo(\"DX coil: #{coil_name} Initial COP: #{dx.getDouble(4).get}\")\n dx.setDouble(4,7.62)\n runner.registerInfo(\"DX coil: #{coil_name} Final COP: #{dx.getDouble(4).get}\")\n dx_name[:dxname] = \"#{coil_name}\"\n results[\"#{coil_name}\"] = dx_name\n end\n\n dx_two.each do |dx|\n dx_name = {}\n coil_name = dx.getString(0).get\n runner.registerInfo(\"DX coil: #{coil_name} Initial High COP: #{dx.getDouble(4).get}, Initial Low COP: #{dx.getDouble(16).get}\")\n dx.setDouble(4,7.62)\n dx.setDouble(16,7.62)\n runner.registerInfo(\"DX coil: #{coil_name} Final High COP: #{dx.getDouble(4).get}, Final Low COP: #{dx.getDouble(16).get}\")\n dx_name[:dxname] = \"#{coil_name}\"\n results[\"#{coil_name}\"] = dx_name\n end\n \n if results.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\n end\n \n #save airloop parsing results to ems_results.json\n runner.registerInfo(\"Saving ems_results.json\")\n FileUtils.mkdir_p(File.dirname(\"ems_results.json\")) unless Dir.exist?(File.dirname(\"ems_results.json\"))\n File.open(\"ems_results.json\", 'w') {|f| f << JSON.pretty_generate(results)}\n \n if results.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\n #save blank ems_membrane_heat_pump_cooling_only.ems file so Eplus measure does not crash\n ems_string = \"\"\n runner.registerInfo(\"Saving blank ems_membrane_heat_pump_cooling_only file\")\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n return true\n end\n \n timeStep = model.getTimestep.numberOfTimestepsPerHour\n \n runner.registerInfo(\"Making EMS string for Membrane Heat Pump Cooling Only\")\n #start making the EMS code\n ems_string = \"\" #clear out the ems_string\n ems_string << \"\\n\" \n ems_string << \"Output:Variable,*,Cooling Coil Sensible Cooling Energy,timestep; !- HVAC Sum [J]\" + \"\\n\"\n ems_string << \"\\n\" \n \n results.each_with_index do |(key, value), i| \n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}SensibleClgJ,\" + \"\\n\"\n ems_string << \" #{value[:dxname]},\" + \"\\n\"\n ems_string << \" Cooling Coil Sensible Cooling Energy;\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"WaterUse:Equipment,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUse, !- Name\" + \"\\n\"\n ems_string << \" Membrane HP Cooling, !- End-Use Subcategory\" + \"\\n\"\n ems_string << \" 0.003155, !- Peak Flow Rate {m3/s} = 3000 gal/hr\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule; !- Flow Rate Fraction Schedule Name\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"Schedule:Constant,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule, !- Name\" + \"\\n\"\n ems_string << \" , !- Schedule Type Limits Name\" + \"\\n\"\n ems_string << \" 1; !- Hourly Value\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"EnergyManagementSystem:Actuator,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseCtrl,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule,\" + \"\\n\"\n ems_string << \" Schedule:Constant,\" + \"\\n\"\n ems_string << \" Schedule Value;\" + \"\\n\"\n ems_string << \"\\n\" \n end\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgramControl, !- Name\" + \"\\n\"\n ems_string << \" AfterPredictorBeforeHVACManagers, !- EnergyPlus Model Calling Point\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgram; !- Program Name 1\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgram, !- Name\" + \"\\n\"\n ems_string << \" SET TimeStepsPerHr = #{timeStep}\" + \"\\n\"\n results.each_with_index do |(key, value), i|\n ems_string << \" SET MembraneHP#{i+1}SensibleClgTonHr = MembraneHP#{i+1}SensibleClgJ * 0.0000007898,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGal = MembraneHP#{i+1}SensibleClgTonHr * 3.0,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGalPerHr = MembraneHP#{i+1}SensibleWtrGal * TimeStepsPerHr,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}WaterUseCtrl = MembraneHP#{i+1}SensibleWtrGalPerHr / 3000.0,\" + \"\\n\"\n end \n ems_string << \" SET UnusedLine = 0;\" + \"\\n\"\n \n #save EMS snippet\n runner.registerInfo(\"Saving ems_membrane_heat_pump_cooling_only file\")\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n \n #unique initial conditions based on\n runner.registerInitialCondition(\"The building has #{results.size} DX coils for which this measure is applicable.\")\n\n #reporting final condition of model\n runner.registerFinalCondition(\"The efficiency of the following coils was increased to SEER 26 to reflect the replacement of these coils with membrane heatpumps: #{results.keys}\")\n \n ems_path = '../MembraneHeatPumpCoolingOnly/ems_membrane_heat_pump_cooling_only.ems'\n json_path = '../MembraneHeatPumpCoolingOnly/ems_results.json'\n if File.exist? ems_path\n ems_string = File.read(ems_path)\n if File.exist? json_path\n json = JSON.parse(File.read(json_path))\n end\n else\n ems_path2 = Dir.glob('../../**/ems_membrane_heat_pump_cooling_only.ems')\n ems_path1 = ems_path2[0]\n json_path2 = Dir.glob('../../**/ems_results.json')\n json_path1 = json_path2[0]\n if ems_path2.size > 1\n runner.registerWarning(\"more than one ems_membrane_heat_pump_cooling_only.ems file found. Using first one found.\")\n end\n if !ems_path1.nil? \n if File.exist? ems_path1\n ems_string = File.read(ems_path1)\n if File.exist? json_path1\n json = JSON.parse(File.read(json_path1))\n else\n runner.registerError(\"ems_results.json file not located\") \n end \n else\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\")\n end \n else\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\") \n end\n end\n if json.nil?\n runner.registerError(\"ems_results.json file not located\")\n return false\n end\n \n if json.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n return true\n end\n \n idf_file = OpenStudio::IdfFile::load(ems_string, 'EnergyPlus'.to_IddFileType).get\n runner.registerInfo(\"Adding EMS code to workspace\")\n workspace.addObjects(idf_file.objects)\n \n return true\n\n end", "def apply_measure_to_model(test_name, args, model_name = nil, result_value = 'Success', warnings_count = 0, info_count = nil)\n # create an instance of the measure\n measure = ChangeBuildingLocation.new\n\n # create an instance of a runner with OSW\n osw_path = OpenStudio::Path.new(File.dirname(__FILE__) + '/test.osw')\n osw = OpenStudio::WorkflowJSON.load(osw_path).get\n runner = OpenStudio::Measure::OSRunner.new(osw)\n\n # get model\n if model_name.nil?\n # make an empty model\n model = OpenStudio::Model::Model.new\n else\n # load the test model\n translator = OpenStudio::OSVersion::VersionTranslator.new\n path = OpenStudio::Path.new(File.dirname(__FILE__) + '/' + model_name)\n model = translator.loadModel(path)\n assert(!model.empty?)\n model = model.get\n end\n\n # get arguments\n arguments = measure.arguments(model)\n argument_map = OpenStudio::Measure.convertOSArgumentVectorToMap(arguments)\n\n # populate argument with specified hash value if specified\n arguments.each do |arg|\n temp_arg_var = arg.clone\n if args.key?(arg.name)\n assert(temp_arg_var.setValue(args[arg.name]))\n end\n argument_map[arg.name] = temp_arg_var\n end\n\n # temporarily change directory to the run directory and run the measure (because of sizing run)\n start_dir = Dir.pwd\n begin\n unless Dir.exist?(run_dir(test_name))\n Dir.mkdir(run_dir(test_name))\n end\n Dir.chdir(run_dir(test_name))\n\n # run the measure\n measure.run(model, runner, argument_map)\n result = runner.result\n ensure\n Dir.chdir(start_dir)\n\n # delete sizing run dir\n FileUtils.rm_rf(run_dir(test_name))\n end\n\n # show the output\n puts \"measure results for #{test_name}\"\n show_output(result)\n\n # assert that it ran correctly\n if result_value.nil? then result_value = 'Success' end\n assert_equal(result_value, result.value.valueName)\n\n # check count of warning and info messages\n unless info_count.nil? then assert(result.info.size == info_count) end\n unless warnings_count.nil? then assert(result.warnings.size == warnings_count) end\n\n # if 'Fail' passed in make sure at least one error message (while not typical there may be more than one message)\n if result_value == 'Fail' then assert(result.errors.size >= 1) end\n\n # save the model to test output directory\n output_file_path = OpenStudio::Path.new(File.dirname(__FILE__) + \"/output/#{test_name}_test_output.osm\")\n model.save(output_file_path, true)\n end", "def measure_code(model,runner)\n ################ Start Measure code here ################################\n # Argument will be passed as instance variable. So if your argument was height, your can access it using @height. \n\n # report initial condition\n site = model.getSite\n initial_design_days = model.getDesignDays\n if site.weatherFile.is_initialized\n weather = site.weatherFile.get\n runner.registerInitialCondition(\"The initial weather file path was '#{weather.path.get}' and the model had #{initial_design_days.size} design days.\")\n else\n runner.registerInitialCondition(\"The initial weather file has not been set and the model had #{initial_design_days.size} design days.\")\n end\n\n\n #Check form weather directory Weather File\n unless (Pathname.new @weather_directory).absolute?\n @weather_directory = File.expand_path(File.join(File.dirname(__FILE__), @weather_directory))\n end\n weather_file = File.join(@weather_directory, @weather_file_name)\n if File.exists?(weather_file) and @weather_file_name.downcase.include? \".epw\"\n BTAP::runner_register(\"Info\", \"The epw weather file #{weather_file} was found!\", runner)\n else\n BTAP::runner_register(\"Error\",\"'#{weather_file}' does not exist or is not an .epw file.\", runner)\n return false\n end\n\n begin\n weather = BTAP::Environment::WeatherFile.new(weather_file)\n #Set Weather file to model.\n weather.set_weather_file(model)\n #Store information about this run in the runner for output. This will be in the csv and R dumps.\n runner.registerValue( 'city',weather.city )\n runner.registerValue( 'state_province_region ',weather.state_province_region )\n runner.registerValue( 'country',weather.country )\n runner.registerValue( 'hdd18',weather.hdd18 )\n runner.registerValue( 'cdd18',weather.cdd18 )\n runner.registerValue( 'necb_climate_zone',BTAP::Compliance::NECB2011::get_climate_zone_name(weather.hdd18).to_s)\n runner.registerFinalCondition( \"Model ended with weatherfile of #{model.getSite.weatherFile.get.path.get}\" )\n rescue\n BTAP::runner_register(\"Error\",\"'#{weather_file}' could not be loaded into model.\", runner)\n\n return false\n end\n BTAP::runner_register(\"FinalCondition\",\"Weather file set to #{weather_file}\",runner)\n return true\n end", "def run(workspace, runner, user_arguments)\r\n super(workspace, runner, user_arguments)\r\n\r\n #use the built-in error checking \r\n if not runner.validateUserArguments(arguments(workspace), user_arguments)\r\n return false\r\n end\r\n \r\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\r\n if run_measure == 0\r\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\r\n return true \r\n end\r\n \r\n require 'json'\r\n \r\n # Get the last openstudio model\r\n model = runner.lastOpenStudioModel\r\n if model.empty?\r\n runner.registerError(\"Could not load last OpenStudio model, cannot apply measure.\")\r\n return false\r\n end\r\n model = model.get\r\n \r\n results = {}\r\n #get all DX coils in model\r\n dx_single = model.getCoilCoolingDXSingleSpeeds \r\n dx_two = model.getCoilCoolingDXTwoSpeeds\r\n \r\n if !dx_single.empty?\r\n dx_single.each do |dx|\r\n dx_name = {}\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP.get}\")\r\n dx.setRatedCOP(OpenStudio::OptionalDouble.new(7.62))\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP.get}\")\r\n dx_name[:dxname] = \"#{dx.name.get}\"\r\n results[\"#{dx.name.get}\"] = dx_name\r\n end\r\n end\r\n if !dx_two.empty?\r\n dx_two.each do |dx|\r\n dx_name = {}\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial High COP: #{dx.ratedHighSpeedCOP.get} Low COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx.setRatedHighSpeedCOP(7.62)\r\n dx.setRatedLowSpeedCOP(7.62)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final High COP: #{dx.ratedHighSpeedCOP.get} Final COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx_name[:dxname] = \"#{dx.name.get}\"\r\n results[\"#{dx.name.get}\"] = dx_name\r\n end\r\n end\r\n \r\n if results.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n end\r\n \r\n #save airloop parsing results to ems_results.json\r\n runner.registerInfo(\"Saving ems_results.json\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_results.json\")) unless Dir.exist?(File.dirname(\"ems_results.json\"))\r\n File.open(\"ems_results.json\", 'w') {|f| f << JSON.pretty_generate(results)}\r\n \r\n if results.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n #save blank ems_membrane_heat_pump_cooling_only.ems file so Eplus measure does not crash\r\n ems_string = \"\"\r\n runner.registerInfo(\"Saving blank ems_membrane_heat_pump_cooling_only file\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\r\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\r\n f.write(ems_string)\r\n end\r\n return true\r\n end\r\n \r\n timeStep = model.getTimestep.numberOfTimestepsPerHour\r\n \r\n runner.registerInfo(\"Making EMS string for Membrane Heat Pump Cooling Only\")\r\n #start making the EMS code\r\n ems_string = \"\" #clear out the ems_string\r\n ems_string << \"\\n\" \r\n ems_string << \"Output:Variable,*,Cooling Coil Sensible Cooling Energy,timestep; !- HVAC Sum [J]\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n \r\n results.each_with_index do |(key, value), i| \r\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}SensibleClgJ,\" + \"\\n\"\r\n ems_string << \" #{value[:dxname]},\" + \"\\n\"\r\n ems_string << \" Cooling Coil Sensible Cooling Energy;\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"WaterUse:Equipment,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUse, !- Name\" + \"\\n\"\r\n ems_string << \" Membrane HP Cooling, !- End-Use Subcategory\" + \"\\n\"\r\n ems_string << \" 0.003155, !- Peak Flow Rate {m3/s} = 3000 gal/hr\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule; !- Flow Rate Fraction Schedule Name\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"Schedule:Constant,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule, !- Name\" + \"\\n\"\r\n ems_string << \" , !- Schedule Type Limits Name\" + \"\\n\"\r\n ems_string << \" 1; !- Hourly Value\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"EnergyManagementSystem:Actuator,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseCtrl,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule,\" + \"\\n\"\r\n ems_string << \" Schedule:Constant,\" + \"\\n\"\r\n ems_string << \" Schedule Value;\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n end\r\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgramControl, !- Name\" + \"\\n\"\r\n ems_string << \" AfterPredictorBeforeHVACManagers, !- EnergyPlus Model Calling Point\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgram; !- Program Name 1\" + \"\\n\"\r\n ems_string << \"\\n\"\r\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgram, !- Name\" + \"\\n\"\r\n ems_string << \" SET TimeStepsPerHr = #{timeStep}\" + \"\\n\"\r\n results.each_with_index do |(key, value), i|\r\n ems_string << \" SET MembraneHP#{i+1}SensibleClgTonHr = MembraneHP#{i+1}SensibleClgJ * 0.0000007898,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGal = MembraneHP#{i+1}SensibleClgTonHr * 3.0,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGalPerHr = MembraneHP#{i+1}SensibleWtrGal * TimeStepsPerHr,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}WaterUseCtrl = MembraneHP#{i+1}SensibleWtrGalPerHr / 3000.0,\" + \"\\n\"\r\n end \r\n ems_string << \" SET UnusedLine = 0;\" + \"\\n\"\r\n \r\n #save EMS snippet\r\n runner.registerInfo(\"Saving ems_membrane_heat_pump_cooling_only file\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\r\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\r\n f.write(ems_string)\r\n end\r\n \r\n #unique initial conditions based on\r\n runner.registerInitialCondition(\"The building has #{results.size} DX coils for which this measure is applicable.\")\r\n\r\n #reporting final condition of model\r\n runner.registerFinalCondition(\"The efficiency of the following coils was increased to SEER 26 to reflect the replacement of these coils with membrane heatpumps: #{results.keys}\")\r\n \r\n ems_path = '../MembraneHeatPumpCoolingOnlyEms/ems_membrane_heat_pump_cooling_only.ems'\r\n json_path = '../MembraneHeatPumpCoolingOnlyEms/ems_results.json'\r\n if File.exist? ems_path\r\n ems_string = File.read(ems_path)\r\n if File.exist? json_path\r\n json = JSON.parse(File.read(json_path))\r\n end\r\n else\r\n ems_path2 = Dir.glob('../../**/ems_membrane_heat_pump_cooling_only.ems')\r\n ems_path1 = ems_path2[0]\r\n json_path2 = Dir.glob('../../**/ems_results.json')\r\n json_path1 = json_path2[0]\r\n if ems_path2.size > 1\r\n runner.registerWarning(\"more than one ems_membrane_heat_pump_cooling_only.ems file found. Using first one found.\")\r\n end\r\n if !ems_path1.nil? \r\n if File.exist? ems_path1\r\n ems_string = File.read(ems_path1)\r\n if File.exist? json_path1\r\n json = JSON.parse(File.read(json_path1))\r\n else\r\n runner.registerError(\"ems_results.json file not located\") \r\n end \r\n else\r\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\")\r\n end \r\n else\r\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\") \r\n end\r\n end\r\n if json.nil?\r\n runner.registerError(\"ems_results.json file not located\")\r\n return false\r\n end\r\n \r\n if json.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n return true\r\n end\r\n \r\n idf_file = OpenStudio::IdfFile::load(ems_string, 'EnergyPlus'.to_IddFileType).get\r\n runner.registerInfo(\"Adding EMS code to workspace\")\r\n workspace.addObjects(idf_file.objects)\r\n \r\n return true\r\n\r\n end", "def modeler_description\n return 'The measure performs the following functions: (1) IDs all chillers, (2) Locates their performance curves and outputs the data, (3) Adds reporting variables for chiller-related data.'\n end", "def build_timing; end", "def measure_gc\n return unless enabled?\n\n @raw_data << { fake: true }\n @total_time += 1.1\n\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # define if the measure should run to a specific time period or whole day\n apply_to_time = true\n\n # assign the user inputs to variables\n object = runner.getOptionalWorkspaceObjectChoiceValue('space_type', user_arguments, model)\n single_space_type = runner.getDoubleArgumentValue('single_space_type', user_arguments)\n occupied_space_type = runner.getDoubleArgumentValue('occupied_space_type', user_arguments)\n unoccupied_space_type = runner.getDoubleArgumentValue('unoccupied_space_type', user_arguments)\n starttime_winter2 = runner.getStringArgumentValue('starttime_winter2', user_arguments)\n endtime_winter2 = runner.getStringArgumentValue('endtime_winter2', user_arguments)\n starttime_winter1 = runner.getStringArgumentValue('starttime_winter1', user_arguments)\n endtime_winter1 = runner.getStringArgumentValue('endtime_winter1', user_arguments)\n starttime_summer = runner.getStringArgumentValue('starttime_summer', user_arguments)\n endtime_summer = runner.getStringArgumentValue('endtime_summer', user_arguments)\n auto_date = runner.getBoolArgumentValue('auto_date', user_arguments)\n alt_periods = runner.getBoolArgumentValue('alt_periods', user_arguments)\n demo_cost_initial_const=false\n\n winter_start_month1 = 1\n winter_end_month1 = 5\n summer_start_month = 6\n summer_end_month = 9\n winter_start_month2 = 10\n winter_end_month2 = 12\n\n######### GET CLIMATE ZONES ################\n if auto_date\n ashraeClimateZone = ''\n #climateZoneNUmber = ''\n climateZones = model.getClimateZones\n climateZones.climateZones.each do |climateZone|\n if climateZone.institution == 'ASHRAE'\n ashraeClimateZone = climateZone.value\n runner.registerInfo(\"Using ASHRAE Climate zone #{ashraeClimateZone}.\")\n end\n end\n\n if ashraeClimateZone == '' # should this be not applicable or error?\n runner.registerError(\"Please assign an ASHRAE Climate Zone to your model using the site tab in the OpenStudio application. The measure can't make AEDG recommendations without this information.\")\n return false # note - for this to work need to check for false in measure.rb and add return false there as well.\n # else\n # climateZoneNumber = ashraeClimateZone.split(//).first\n end\n # #runner.registerInfo(\"CLIMATE ZONE #{ashraeClimateZone}. Right now does not do anything.\")\n # if !['1', '2', '3', '4', '5', '6', '7', '8'].include? climateZoneNumber\n # runner.registerError('ASHRAE climate zone number is not within expected range of 1 to 8.')\n # return false # note - for this to work need to check for false in measure.rb and add return false there as well.\n # end\n\n if alt_periods\n if ashraeClimateZone == '3A'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4A'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5A'\n starttime_summer = '14:01:00'\n endtime_summer = '17:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n elsif ashraeClimateZone == '6A'\n starttime_summer = '13:01:00'\n endtime_summer = '16:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n end\n else\n if ashraeClimateZone == '2A'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '2B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '3A'\n starttime_summer = '19:01:00'\n endtime_summer = '22:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '3B'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '19:01:00'\n endtime_winter1 = '22:59:00'\n starttime_winter2 = '19:01:00'\n endtime_winter2 = '22:59:00'\n elsif ashraeClimateZone == '3C'\n starttime_summer = '19:01:00'\n endtime_summer = '22:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4A'\n starttime_summer = '12:01:00'\n endtime_summer = '15:59:00'\n starttime_winter1 = '16:01:00'\n endtime_winter1 = '19:59:00'\n starttime_winter2 = '16:01:00'\n endtime_winter2 = '19:59:00'\n elsif ashraeClimateZone == '4B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4C'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5A'\n starttime_summer = '20:01:00'\n endtime_summer = '23:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5C'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '6A'\n starttime_summer = '16:01:00'\n endtime_summer = '19:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n elsif ashraeClimateZone == '6B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '7A'\n starttime_summer = '16:01:00'\n endtime_summer = '19:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n end\n end\n end \n\n # check the lighting power reduction percentages and for reasonableness\n if occupied_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif occupied_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (occupied_space_type < 1) && (occupied_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{occupied_space_type} percent is abnormally low.\")\n elsif occupied_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{occupied_space_type} percent is abnormally high.\")\n elsif occupied_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the equipment_power_reduction_percent and for reasonableness\n if unoccupied_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif unoccupied_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (unoccupied_space_type < 1) && (unoccupied_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{unoccupied_space_type} percent is abnormally low.\")\n elsif unoccupied_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{unoccupied_space_type} percent is abnormally high.\")\n elsif unoccupied_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the equipment_power_reduction_percent and for reasonableness\n if single_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif single_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (single_space_type < 1) && (single_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{single_space_type} percent is abnormally low.\")\n elsif single_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{single_space_type} percent is abnormally high.\")\n elsif single_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the time periods for reasonableness\n if (starttime_winter1.to_f > endtime_winter1.to_f) && (starttime_winter2.to_f > endtime_winter2.to_f) && (starttime_summer.to_f > endtime_summer.to_f)\n runner.registerError('The end time should be larger than the start time.')\n return false\n end\n\n # check the space_type for reasonableness\n space_type = nil\n if object.empty?\n handle = runner.getStringArgumentValue('space_type', user_arguments)\n if handle.empty?\n runner.registerError('No space type was chosen.')\n else\n runner.registerError(\"The selected space type with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if !object.get.to_SpaceType.empty?\n space_type = object.get.to_SpaceType.get\n elsif !object.get.to_Building.empty?\n apply_to_building = true\n else\n runner.registerError('Script Error - argument not showing up as space type or building.')\n return false\n end\n end\n\n\n ############################################\n\n # assign the time duration when DR strategy is applied, from shift_time1 to shift_time2, only applied when apply_to_time is ture\n shift_time1 = OpenStudio::Time.new(starttime_winter1)\n shift_time2 = OpenStudio::Time.new(endtime_winter1)\n shift_time3 = OpenStudio::Time.new(0, 24, 0, 0)\n shift_time4 = OpenStudio::Time.new(starttime_summer)\n shift_time5 = OpenStudio::Time.new(endtime_summer)\n shift_time6 = OpenStudio::Time.new(starttime_winter2)\n shift_time7 = OpenStudio::Time.new(endtime_winter2)\n \n \n # get space types in model\n if apply_to_building\n space_types = model.getSpaceTypes\n else\n space_types = []\n space_types << space_type # only run on a single space type\n end\n\n # make a hash of old defs and new equipments and luminaire defs\n cloned_equi_defs = {}\n # loop through space types\n space_types.each do |space_type|\n\n equi_set_schs = {}\n if apply_to_building # measure will be applied differently to space types, based on whether the space type is occupied\n if !space_type.people.empty?\n equipment_power_reduction_percent = 1 - (occupied_space_type/100)\n else\n equipment_power_reduction_percent = 1 - (unoccupied_space_type/100)\n end\n runner.registerInitialCondition(\"Equipment power will be reduced by #{occupied_space_type}% in occupied spaces, and reduced by #{unoccupied_space_type}% in unoccupied spaces\")\n\n else\n equipment_power_reduction_percent = 1 - (single_space_type/100) # measure will be applied evenly to all zones\n runner.registerInitialCondition(\"Equipment power will be reduced by #{single_space_type}% to '#{space_type.name}'.\")\n end\n\n space_type_equipments = space_type.electricEquipment\n space_type_equipments.each do |space_type_equipment|\n #clone of not already in hash\n equi_set_sch = space_type_equipment.schedule\n if !equi_set_sch.empty?\n # clone of not already in hash\n if equi_set_schs.key?(equi_set_sch.get.name.to_s)\n new_equi_set_sch = equi_set_schs[equi_set_sch.get.name.to_s]\n else\n new_equi_set_sch = equi_set_sch.get.clone(model)\n new_equi_set_sch = new_equi_set_sch.to_Schedule.get\n new_equi_set_sch_name = new_equi_set_sch.setName(\"#{new_equi_set_sch.name} adjusted #{equipment_power_reduction_percent}\")\n # add to the hash\n equi_set_schs[new_equi_set_sch.name.to_s] = new_equi_set_sch\n end\n # hook up clone to equipment\n \n if space_type_equipment.name.to_s != \"OfficeLarge Data Center Elec Equip\" && space_type_equipment.name.to_s != \"OfficeLarge Main Data Center Elec Equip\"\n space_type_equipment.setSchedule(new_equi_set_sch)\n runner.registerInfo(\"#{space_type_equipment.name} has a new electric equipment schedule\")\n end\n else\n runner.registerWarning(\"#{space_type.equipments.name} doesn't have a schedule.\")\n end\n end\n \n if apply_to_time\n runner.registerFinalCondition(\" equipment power is reduced from #{shift_time1} to #{shift_time2}.\")\n runner.registerFinalCondition(\" equipment power is reduced from #{shift_time4} to #{shift_time5} during special between month #{summer_start_month} and #{summer_end_month}\")\n else\n runner.registerFinalCondition(\" equipment power is reduced all day.\")\n end\n\n \n # make equipment schedule adjustments and rename.\n equi_set_schs.each do |k, v| # old name and new object for schedule\n if !v.to_ScheduleRuleset.empty?\n\n schedule = v.to_ScheduleRuleset.get\n default_rule = schedule.defaultDaySchedule\n rules = schedule.scheduleRules\n\n days_covered = Array.new(7, false)\n\n if rules.length > 0\n rules.each do |rule|\n summerStartMonth = OpenStudio::MonthOfYear.new(summer_start_month)\n summerEndMonth = OpenStudio::MonthOfYear.new(summer_end_month)\n summerStartDate = OpenStudio::Date.new(summerStartMonth, 1)\n summerEndDate = OpenStudio::Date.new(summerEndMonth, 30)\n \n summer_rule = rule.clone(model).to_ScheduleRule.get\n summer_rule.setStartDate(summerStartDate)\n summer_rule.setEndDate(summerEndDate)\n\n allDaysCovered(summer_rule, days_covered)\n\n cloned_day_summer = rule.daySchedule.clone(model)\n cloned_day_summer.setParent(summer_rule)\n\n summer_day = summer_rule.daySchedule\n day_time_vector = summer_day.times\n day_value_vector = summer_day.values\n summer_day.clearValues\n \n summer_day = createDaySchedule(summer_day, day_time_vector, day_value_vector, shift_time4, shift_time5, equipment_power_reduction_percent)\n \n ##############################################\n winterStartMonth1 = OpenStudio::MonthOfYear.new(winter_start_month1)\n winterEndMonth1 = OpenStudio::MonthOfYear.new(winter_end_month1)\n winterStartDate1 = OpenStudio::Date.new(winterStartMonth1, 1)\n winterEndDate1 = OpenStudio::Date.new(winterEndMonth1, 31)\n \n winter_rule1 = rule #rule.clone(model).to_ScheduleRule.get\n winter_rule1.setStartDate(winterStartDate1)\n winter_rule1.setEndDate(winterEndDate1)\n\n\n cloned_day_winter = rule.daySchedule.clone(model)\n cloned_day_winter.setParent(winter_rule1)\n\n winter_day1 = winter_rule1.daySchedule\n day_time_vector = winter_day1.times\n day_value_vector = winter_day1.values\n winter_day1.clearValues\n \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time6, shift_time7, equipment_power_reduction_percent)\n if shift_time1 != shift_time6 \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time1, shift_time2, equipment_power_reduction_percent)\n end\n ###################################################\n winterStartMonth2 = OpenStudio::MonthOfYear.new(winter_start_month2)\n winterEndMonth2 = OpenStudio::MonthOfYear.new(winter_end_month2)\n winterStartDate2 = OpenStudio::Date.new(winterStartMonth2, 1)\n winterEndDate2 = OpenStudio::Date.new(winterEndMonth2, 31)\n \n winter_rule2 = winter_rule1.clone(model).to_ScheduleRule.get\n winter_rule2.setStartDate(winterStartDate2)\n winter_rule2.setEndDate(winterEndDate2)\n \n cloned_day_winter2 = winter_day1.clone(model)\n cloned_day_winter2.setParent(winter_rule2)\n end\n end\n #runner.registerInfo(\"BEFORE #{days_covered}\")\n if days_covered.include?(false)\n summerStartMonth = OpenStudio::MonthOfYear.new(summer_start_month)\n summerEndMonth = OpenStudio::MonthOfYear.new(summer_end_month)\n summerStartDate = OpenStudio::Date.new(summerStartMonth, 1)\n summerEndDate = OpenStudio::Date.new(summerEndMonth, 30)\n \n summer_rule = OpenStudio::Model::ScheduleRule.new(schedule)\n summer_rule.setStartDate(summerStartDate)\n summer_rule.setEndDate(summerEndDate)\n coverSomeDays(summer_rule, days_covered)\n allDaysCovered(summer_rule, days_covered)\n\n cloned_day_summer = default_rule.clone(model)\n cloned_day_summer.setParent(summer_rule)\n\n summer_day = summer_rule.daySchedule\n day_time_vector = summer_day.times\n day_value_vector = summer_day.values\n summer_day.clearValues\n \n summer_day = createDaySchedule(summer_day, day_time_vector, day_value_vector, shift_time4, shift_time5, equipment_power_reduction_percent)\n \n ##############################################\n winterStartMonth1 = OpenStudio::MonthOfYear.new(winter_start_month1)\n winterEndMonth1 = OpenStudio::MonthOfYear.new(winter_end_month1)\n winterStartDate1 = OpenStudio::Date.new(winterStartMonth1, 1)\n winterEndDate1 = OpenStudio::Date.new(winterEndMonth1, 31)\n \n winter_rule1 = summer_rule.clone(model).to_ScheduleRule.get #OpenStudio::Model::ScheduleRule.new(schedule)\n winter_rule1.setStartDate(winterStartDate1)\n winter_rule1.setEndDate(winterEndDate1)\n\n #coverSomeDays(winter_rule1, days_covered)\n #allDaysCovered(summer_rule, days_covered)\n\n cloned_day_winter = default_rule.clone(model)\n cloned_day_winter.setParent(winter_rule1)\n\n winter_day1 = winter_rule1.daySchedule\n day_time_vector = winter_day1.times\n day_value_vector = winter_day1.values\n winter_day1.clearValues\n \n\n\n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time6, shift_time7, equipment_power_reduction_percent)\n if shift_time1 != shift_time6 \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time1, shift_time2, equipment_power_reduction_percent)\n end\n ###################################################\n winterStartMonth2 = OpenStudio::MonthOfYear.new(winter_start_month2)\n winterEndMonth2 = OpenStudio::MonthOfYear.new(winter_end_month2)\n winterStartDate2 = OpenStudio::Date.new(winterStartMonth2, 1)\n winterEndDate2 = OpenStudio::Date.new(winterEndMonth2, 31)\n \n winter_rule2 = winter_rule1.clone(model).to_ScheduleRule.get #OpenStudio::Model::ScheduleRule.new(schedule)\n winter_rule2.setStartDate(winterStartDate2)\n winter_rule2.setEndDate(winterEndDate2)\n \n cloned_day_winter2 = winter_day1.clone(model)\n cloned_day_winter2.setParent(winter_rule2)\n end\n #runner.registerInfo(\"AFTER Summer #{days_covered}\")\n else\n runner.registerWarning(\"Schedule '#{k}' isn't a ScheduleRuleset object and won't be altered by this measure.\")\n v.remove # remove un-used clone\n end\n end\n\n end\n return true\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n #use the built-in error checking\n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assume the occ sensors will last the full analysis\n expected_life = 25\n \n #assign the user inputs to variables\n space_type_object = runner.getOptionalWorkspaceObjectChoiceValue(\"space_type\",user_arguments,model)\n percent_runtime_reduction = runner.getDoubleArgumentValue(\"percent_runtime_reduction\",user_arguments)\n material_and_installation_cost_per_space = runner.getDoubleArgumentValue(\"material_and_installation_cost_per_space\",user_arguments)\n\n #check the space_type for reasonableness and see if measure should run on space type or on the entire building\n apply_to_building = false\n space_type = nil\n if space_type_object.empty?\n handle = runner.getStringArgumentValue(\"space_type\",user_arguments)\n if handle.empty?\n runner.registerError(\"No space type was chosen.\")\n else\n runner.registerError(\"The selected space type with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if not space_type_object.get.to_SpaceType.empty?\n space_type = space_type_object.get.to_SpaceType.get\n elsif not space_type_object.get.to_Building.empty?\n apply_to_building = true\n else\n runner.registerError(\"Script Error - argument not showing up as space type or building.\")\n return false\n end\n end\n \n #check arguments for reasonableness\n if percent_runtime_reduction >= 100\n runner.registerError(\"Percent runtime reduction must be less than 100.\")\n return false\n end\n\n #find all the original schedules (before occ sensors installed)\n original_lts_schedules = []\n if apply_to_building #apply to the whole building\n \n model.getLightss.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end\n else #apply to the a specific space type\n #do the lights assigned to the space type itself\n space_type.lights.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end\n #do the lights in each space of the selected space type\n space_type.spaces.each do |space|\n space.lights.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end \n end\n end\n \n #make copies of all the original lights schedules, reduced to include occ sensor impact\n original_schs_new_schs = {}\n original_lts_schedules.uniq.each do |orig_sch|\n #TODO skip non-schedule-ruleset schedules\n \n #copy the original schedule\n new_sch = orig_sch.clone.to_ScheduleRuleset.get\n #reduce each value in each profile (except the design days) by the specified amount\n runner.registerInfo(\"Reducing values in '#{orig_sch.name}' schedule by #{percent_runtime_reduction}% to represent occ sensor installation.\")\n day_profiles = []\n day_profiles << new_sch.defaultDaySchedule\n new_sch.scheduleRules.each do |rule|\n day_profiles << rule.daySchedule\n end\n multiplier = (100 - percent_runtime_reduction)/100\n day_profiles.each do |day_profile|\n #runner.registerInfo(\"#{day_profile.name}\")\n times_vals = day_profile.times.zip(day_profile.values)\n #runner.registerInfo(\"original time/values = #{times_vals}\")\n times_vals.each do |time,val|\n day_profile.addValue(time, val * multiplier)\n end\n #runner.registerInfo(\"new time/values = #{day_profile.times.zip(day_profile.values)}\")\n end \n #log the relationship between the old sch and the new, reduced sch\n original_schs_new_schs[orig_sch] = new_sch\n #runner.registerInfo(\"***\")\n end\n \n #replace the old schedules with the new schedules\n spaces_sensors_added_to = []\n if apply_to_building #apply to the whole building\n runner.registerInfo(\"Adding occupancy sensors to whole building\")\n model.getLightss.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n else #apply to the a specific space type\n #do the lights assigned to the space type itself\n runner.registerInfo(\"Adding occupancy sensors to space type '#{space_type.name}'\")\n space_type.lights.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n #do the lights in each space of the selected space type\n space_type.spaces.each do |space|\n runner.registerInfo(\"Adding occupancy sensors to space '#{space.name}\")\n space.lights.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end \n end\n end \n \n #report if the measure is not applicable\n num_sensors_added = spaces_sensors_added_to.uniq.size\n if spaces_sensors_added_to.size == 0\n runner.registerAsNotApplicable(\"This measure is not applicable because there were no lights in the specified areas of the building.\")\n return true\n end\n \n #report initial condition\n runner.registerInitialCondition(\"The building has several areas where occupancy sensors could be used to reduce lighting energy by turning off the lights while no occupants are present.\") \n \n #add cost of adding occ sensors\n if material_and_installation_cost_per_space != 0\n cost = OpenStudio::Model::LifeCycleCost.createLifeCycleCost(\"Add #{material_and_installation_cost_per_space} Occ Sensors to the Building\", model.getBuilding, material_and_installation_cost_per_space * num_sensors_added, \"CostPerEach\", \"Construction\", expected_life, 0)\n if cost.empty?\n runner.registerError(\"Failed to add costs.\")\n end\n end \n \n #report final condition\n if apply_to_building\n runner.registerFinalCondition(\"Add occupancy sensors to #{num_sensors_added} spaces in the building. The total cost to perform this is $#{material_and_installation_cost_per_space.round} per space, for a total cost of $#{(material_and_installation_cost_per_space * num_sensors_added).round}\")\n else\n runner.registerFinalCondition(\"Add occupancy sensors to #{num_sensors_added} #{space_type.name} spaces in the building. The total cost to perform this is $#{material_and_installation_cost_per_space.round} per space, for a total cost of $#{(material_and_installation_cost_per_space * num_sensors_added).round}\")\n end\n \n return true\n \n end", "def run(model, runner, user_arguments)\r\n super(model, runner, user_arguments)\r\n\r\n #use the built-in error checking \r\n if not runner.validateUserArguments(arguments(model), user_arguments)\r\n return false\r\n end\r\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\r\n if run_measure == 0\r\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\r\n return true \r\n end\r\n \r\n require 'json'\r\n \r\n results = {}\r\n dx_name = []\r\n #get all DX coils in model\r\n dx_single = model.getCoilCoolingDXSingleSpeeds \r\n dx_two = model.getCoilCoolingDXTwoSpeeds\r\n dx_heat = model.getCoilHeatingDXSingleSpeeds\r\n \r\n if !dx_single.empty?\r\n dx_single.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP.get}\")\r\n dx.setRatedCOP(OpenStudio::OptionalDouble.new(6.0))\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP.get}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n if !dx_two.empty?\r\n dx_two.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial High COP: #{dx.ratedHighSpeedCOP.get} Low COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx.setRatedHighSpeedCOP(6.0)\r\n dx.setRatedLowSpeedCOP(6.0)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final High COP: #{dx.ratedHighSpeedCOP.get} Final COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n if !dx_heat.empty?\r\n dx_heat.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP}\")\r\n dx.setRatedCOP(6.0)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n \r\n if dx_name.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n end\r\n \r\n #unique initial conditions based on\r\n runner.registerInitialCondition(\"The building has #{dx_name.size} DX coils for which this measure is applicable.\")\r\n\r\n #reporting final condition of model\r\n runner.registerFinalCondition(\"The COP of the following coils was increased to 6: #{dx_name}\")\r\n return true\r\n\r\n end", "def around_perform_stats(*args)\n start = Time.now\n yield\n time_taken = Time.now - start\n statsd.timing(\"duration:#{self}\", time_taken)\n statsd.increment(\"total_successful:#{self}\")\n statsd.increment(\"total_successful\")\n run_hooks(:duration, :duration, args) {|key| statsd.timing(key, time_taken)}\n end", "def defMeasurement(name,&block)\n mp = {:mp => name, :fields => []}\n @fields = []\n # call the block with ourserlves to process its 'defMetric' statements\n block.call(self) if block\n @fields.each { |f| mp[:fields] << f }\n define_measurement_point(mp)\n end", "def measure(heading)\n start_time = Time.now\n print heading\n result = yield\n end_time = Time.now - start_time\n puts \" (#{end_time} s)\"\n result\nend", "def measure() @measure ||= (nb_weight == 0.0 ? 0.0 : sum_weight / nb_weight) end", "def record_measure(label)\n $logger.debug(\n tms = Benchmark.measure(label) do\n yield\n end.format(\"%n: %10.6rreal %10.6u user %10.6y sys\")\n )\nend", "def run_examination\n true\n end", "def update\n if @clock1_measure.nil?\n discipline_freq\n else\n elapsed = @clock1.time - @clock1_measure.local_time\n discipline_freq if elapsed > @frequency_discipline_interval\n end\n if @clock2_measure.nil?\n discipline_phase\n else\n elapsed = @clock2.time - @clock2_measure.local_time\n discipline_phase if elapsed > @phase_discipline_interval\n end\n end", "def benchmark!\n @benchmark = true\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n\n pct_red = runner.getDoubleArgumentValue(\"pct_red\",user_arguments)\n start_hr = runner.getDoubleArgumentValue(\"start_hr\",user_arguments)\n end_hr = runner.getDoubleArgumentValue(\"end_hr\",user_arguments)\n \n\n\n #check the fraction for reasonableness\n if not 0 <= pct_red and pct_red <= 100\n runner.registerError(\"Percent reduction value needs to be between 0 and 100.\")\n return false\n end\n\n #check start_hr for reasonableness and round to 15 minutes\n start_red_hr = nil\n start_red_min = nil\n if not 0 <= start_hr and start_hr <= 24\n runner.registerError(\"Time in hours needs to be between or equal to 0 and 24\")\n return false\n else\n rounded_start_hr = ((start_hr*4).round)/4.0\n if not start_hr == rounded_start_hr\n runner.registerInfo(\"Start time rounded to nearest 15 minutes: #{rounded_start_hr}\")\n end\n start_red_hr = rounded_start_hr.truncate\n start_red_min = (rounded_start_hr - start_red_hr)*60\n start_red_min = start_red_min.to_i\n end\n\n #check end_hr for reasonableness and round to 15 minutes\n end_red_hr = nil\n end_red_min = nil \n if not 0 <= end_hr and end_hr <= 24\n runner.registerError(\"Time in hours needs to be between or equal to 0 and 24.\")\n return false\n elsif end_hr > end_hr\n runner.registerError(\"Please enter an end time later in the day than end time.\")\n return false\n else\n rounded_end_hr = ((end_hr*4).round)/4.0\n if not end_hr == rounded_end_hr\n runner.registerInfo(\"End time rounded to nearest 15 minutes: #{rounded_end_hr}\")\n end\n end_red_hr = rounded_end_hr.truncate\n end_red_min = (rounded_end_hr - end_red_hr)*60\n end_red_min = end_red_min.to_i\n end\n\n # Translate the percent reduction into a multiplier\n red_mult = pct_red/100\n\n # Get schedules from all lights.\n original_lights_schs = []\n model.getLightss.each do |lights|\n if lights.schedule.is_initialized\n lights_sch = lights.schedule.get\n original_lights_schs << lights_sch\n end\n end\n\n # loop through the unique list of lights schedules, cloning\n # and reducing schedule fraction during the specified time range.\n original_lights_schs_new_schs = {}\n original_lights_schs.uniq.each do |lights_sch|\n if lights_sch.to_ScheduleRuleset.is_initialized\n new_lights_sch = lights_sch.clone(model).to_ScheduleRuleset.get\n new_lights_sch.setName(\"#{lights_sch.name} with Solar Cogeneration and Daylighting\")\n original_lights_schs_new_schs[lights_sch] = new_lights_sch\n new_lights_sch = new_lights_sch.to_ScheduleRuleset.get\n \n # method to adjust the values in a day schedule by a \n # specified percentage during a range of hours.\n def reduce_schedule(day_sch, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n start_time = OpenStudio::Time.new(0, start_red_hr, start_red_min, 0)\n end_time = OpenStudio::Time.new(0, end_red_hr, end_red_min, 0)\n\n # Get the original values at the desired start and end times\n # and put points into the schedule at those times.\n day_sch.addValue(start_time, day_sch.getValue(start_time))\n day_sch.addValue(end_time, day_sch.getValue(end_time))\n \n # Store the original time/values then clear the schedule\n times = day_sch.times\n values = day_sch.values\n day_sch.clearValues\n\n # Modify the time/values and add back to the schedule\n for i in 0..(values.length - 1)\n if times[i] > start_time and times[i] <= end_time # Inside range\n day_sch.addValue(times[i], values[i] * red_mult)\n else\n day_sch.addValue(times[i], values[i])\n end\n end\n\n end #end reduce schedule\n\n # Reduce default day schedule\n if new_lights_sch.scheduleRules.size == 0\n runner.registerWarning(\"Schedule '#{new_lights_sch.name}' applies to all days. It has been treated as a Weekday schedule.\")\n end\n reduce_schedule(new_lights_sch.defaultDaySchedule, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n \n # Reduce all other schedule rules\n new_lights_sch.scheduleRules.each do |sch_rule|\n reduce_schedule(sch_rule.daySchedule, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n end\n \n end \n end #end of original_lights_schs.uniq.each do\n\n #loop through all lights instances, replacing old lights schedules with the reduced schedules\n model.getLightss.each do |lights|\n if lights.schedule.empty?\n runner.registerWarning(\"There was no schedule assigned for the lights object named '#{lights.name}. No schedule was added.'\")\n else\n old_lights_sch = lights.schedule.get\n lights.setSchedule(original_lights_schs_new_schs[old_lights_sch])\n runner.registerInfo(\"Schedule for the lights object named '#{lights.name}' was reduced to simulate the application of Solar Cogeneration and Daylighting.\")\n end\n end\n\n # NA if the model has no lights\n if model.getLightss.size == 0\n runner.registerNotAsApplicable(\"Not Applicable - There are no lights in the model.\")\n end\n\n # Reporting final condition of model\n runner.registerFinalCondition(\"#{original_lights_schs.uniq.size} schedule(s) were edited to reflect the addition of Solar Cogeneration and Daylighting to the building.\")\n \n return true\n\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n \n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n\n\t#initialize variables\n\ttz_count = 0\n\tclg_tstat_schedule = []\n\tthermal_zone_array = []\n\t\t\n\t# get the thermal zones and loop through them \n\tmodel.getThermalZones.each do |thermal_zone|\n\t\n\t\tthermal_zone_array << thermal_zone\n\t\t\n\t\t# test to see if thermal zone has a thermostat object assigned or is unconditioned. \n\t\tif thermal_zone.thermostatSetpointDualSetpoint.is_initialized\n\t\t\tzone_thermostat = thermal_zone.thermostatSetpointDualSetpoint.get\n\t\t\ttz_count += 1\n\t\t\t\n\t\t\tif zone_thermostat.coolingSetpointTemperatureSchedule.is_initialized\n\t\t\t\tclg_tstat_schedule = zone_thermostat.coolingSetpointTemperatureSchedule.get\n\t\t\t\t\n\t\t\t\t# clone the existing cooling T-stat schedule in case it is used somewhere else in the model\n\t\t\t\tcloned_clg_tstat_schedule = clg_tstat_schedule.clone\n\t\t\t\t@new_clg_tstat_schedule_name = (\"#{clg_tstat_schedule.name}+1.5F\")\n\t\t\t\n\t\t\t\tif cloned_clg_tstat_schedule.to_ScheduleRuleset.is_initialized\n\t\t\t\t\tschedule = cloned_clg_tstat_schedule.to_ScheduleRuleset.get\n\t\t\t\t\t# gather profiles of cloned schedule\n\t\t\t\t\tprofiles = []\n\t\t\t\t\tcooling_thermostat_array = []\n\t\t\t\t\tdefaultProfile = schedule.to_ScheduleRuleset.get.defaultDaySchedule\n\t\t\t\t\n\t\t\t\t\tprofiles << defaultProfile\n\t\t\t\t\trules = schedule.scheduleRules\n\t\t\t\t\n\t\t\t\t\trules.each do |rule|\n\t\t\t\t\t\tprofiles << rule.daySchedule\n\t\t\t\t\tend # end the do loop through the rulesetsdo\n\n\t\t\t\t\t#adjust profiles of temperature schedule of cloned schedule by + 1.5 deg F delta (0.833 C)\n\t\t\t\t\tprofiles.each do |profile|\n\t\t\t\t\t\ttime = profile.times\n\t\t\t\t\t\ti = 0\n\t\t\t\t\t\t#TODO - name new profile\n\t\t\t\t\t\tprofile.values.each do |value|\n\t\t\t\t\t\t\tdelta = 0.8333\n\t\t\t\t\t\t\tnew_value = value + delta # Note this is where the cooling setpoint is raised\n\t\t\t\t\t\t\tprofile.addValue(time[i], new_value)\n\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\tcloned_clg_tstat_schedule.setName(@new_clg_tstat_schedule_name)\n\t\t\t\t\t\t\tcooling_thermostat_array << cloned_clg_tstat_schedule\n\t\t\t\t\t\tend # end loop through each profile values\n\t\t\t\t\tend # end loop through each profile\n\t\t\t\t\t\n\t\t\t\t\tzone_thermostat.setCoolingSetpointTemperatureSchedule(cloned_clg_tstat_schedule.to_ScheduleRuleset.get)\n\t\t\t\t\trunner.registerInfo(\"The existing cooling thermostat '#{clg_tstat_schedule.name}' has been changed to #{cloned_clg_tstat_schedule.name}. Inspect the new schedule values using the OS App.\")\n\t\t\t\tend # end if statement for cloning and modifying cooling tstat schedule object\n\t\t\telse\n\t\t\t\trunner.registerInfo(\"The dual setpoint thermostat object named #{zone_thermostat.name} serving thermal zone #{thermal_zone.name} did not have a cooling setpoint temperature schedule associated with it. The measure will not alter this thermostat object\")\n\t\t\tend # end if statement for cooling Setpoint Temperature is initialized\n\t\t\t\n\t\t\tif zone_thermostat.heatingSetpointTemperatureSchedule.is_initialized\n\t\t\t\thtg_tstat_schedule = zone_thermostat.heatingSetpointTemperatureSchedule.get\n\t\t\t\t\t\t\n\t\t\t\t# clone the existing heating T-stat schedule in case it is used somewhere else\n\t\t\t\tcloned_htg_tstat_schedule = htg_tstat_schedule.clone\n\t\t\t\t\n\t\t\t\t#name cloned heating t-stat schedule\n\t\t\t\tcloned_htg_tstat_schedule.setName(\"#{htg_tstat_schedule.name}-1.5F\")\n\n\t\t\t\tif cloned_htg_tstat_schedule.to_ScheduleRuleset.is_initialized\n\t\t\t\t\tschedule = cloned_htg_tstat_schedule.to_ScheduleRuleset.get\n\t\t\t\t\n\t\t\t\t\t# gather profiles of cloned schedule\n\t\t\t\t\tprofiles_h = []\n\t\t\t\t\tdefaultProfile = schedule.to_ScheduleRuleset.get.defaultDaySchedule\n\t\t\t\t\t\n\t\t\t\t\tprofiles_h << defaultProfile\n\t\t\t\t\trules_h = schedule.scheduleRules\n\t\t\t\t\trules_h.each do |rule_h|\n\t\t\t\t\t\tprofiles_h << rule_h.daySchedule\n\t\t\t\t\tend # end the rule_h do\n\n\t\t\t\t\t#adjust profiles_h of temperature schedule of cloned schedule by + 1.5 deg F delta (0.833 C)\n\t\t\t\t\tprofiles_h.each do |profile_h|\n\t\t\t\t\t\ttime_h = profile_h.times\n\t\t\t\t\t\ti = 0\n\t\t\t\t\t\t#TODO - name new profile\n\t\t\t\t\t\tprofile_h.values.each do |value_h|\n\t\t\t\t\t\t\tdelta_h = 0.8333\n\t\t\t\t\t\t\tnew_value_h = value_h - delta_h # Note this is where the heating setpoint is lowered \n\t\t\t\t\t\t\tprofile_h.addValue(time_h[i], new_value_h)\n\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\tend # end loop through each profile values\n\t\t\t\t\tend # end loop through each profile_h\n\t\t\t\t\t\n\t\t\t\t\tzone_thermostat.setHeatingSetpointTemperatureSchedule(cloned_htg_tstat_schedule.to_ScheduleRuleset.get)\n\t\t\t\t\trunner.registerInfo(\"The existing heating thermostat '#{htg_tstat_schedule.name}' has been changed to #{cloned_htg_tstat_schedule.name}. Inspect the new schedule values using the OS App.\")\n\t\t\t\tend # end if statement for cloning and modifying heating tstat schedule object\t\n\t\t\telse\n\t\t\t\trunner.registerInfo(\"The dual setpoint thermostat object named #{zone_thermostat.name} serving thermal zone #{thermal_zone.name} did not have a heating setpoint temperature schedule associated with it. The measure will not alter this thermostat object\")\n\t\t\tend # end if statement for heating Setpoint Temperature is initialized\n\t\tend\t# end if statement for zone_thermstat cooling schedule\n\t\t\n\tend # end loop through thermal zones\t\t\t\n\t\t\t\n\t# Add ASHRAE 55 Comfort Warnings are applied to people objects\n\t# get people objects and people definitions in model\n\tpeople_defs = model.getPeopleDefinitions\n\tpeople_instances = model.getPeoples\n\n\t# loop through people objects\n\tpeople_def_counter = 0\n\tpeople_defs.sort.each do |people_def|\n\t next if not people_def.instances.size > 0\n\t people_def_counter += 1\n\t people_def.setEnableASHRAE55ComfortWarnings(true)\n\tend\n\t\t\t\n\treporting_frequency = \"Timestep\"\n\toutputVariable = OpenStudio::Model::OutputVariable.new(\"Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status []\",model)\n\toutputVariable.setReportingFrequency(reporting_frequency)\n\trunner.registerInfo(\"Adding output variable for 'Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status' reporting '#{reporting_frequency}'\")\n\n\t# write As Not Applicable message\n\tif tz_count == 0\n\t\trunner.registerAsNotApplicable(\"Measure is not applicable. There are no conditioned thermal zones in the model.\")\n\t\treturn true\n\tend\n\n\t# report initial condition of model\n\trunner.registerInitialCondition(\"The initial model contained #{tz_count} thermal zones with #{thermal_zone_array.length} 'Cooling Thermostat Schedule' and #{thermal_zone_array.length} 'Heating Thermostat Schedule' objects for which this measure is applicable.\")\n\n\t# report final condition of model\n\trunner.registerFinalCondition(\"The #{thermal_zone_array.length} Heating and #{thermal_zone_array.length} Cooling Thermostats schedules for #{thermal_zone_array.length} Thermal Zones were altered to reflect a additional deadband width of 3 Deg F . \")\n\treturn true\n\n end", "def stat(*args)\n @recorder.call(*args) if @recorder\n end", "def measure (n=1)\n cnt=0\nelapsed_time=Time.now\n\nn.times {\n cnt+=1\n yield} \nelapsed_time=(Time.now-elapsed_time)/cnt\n\nend", "def run() end", "def running_test_step; end", "def stat() end", "def measure(msg)\n start = Time.now\n yield\n printf \"%<msg>s in %<elapsed>.2f seconds\\n\", msg: msg, elapsed: Time.now - start\nend", "def measure(msg)\n start = Time.now\n yield\n printf \"%<msg>s in %<elapsed>.2f seconds\\n\", msg: msg, elapsed: Time.now - start\nend", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n #initialize variables\n zone_hvac_count = 0\n pump_count = 0\n air_loop_count = 0\n \n #loop through each air loop in the model\n model.getAirLoopHVACs.sort.each do |air_loop|\n\n # call the method to generate a new occupancy schedule based on a 5% threshold\n occ_sch = air_loop.get_occupancy_schedule(0.15)\n old_sch = air_loop.availabilitySchedule\n next unless compare_eflh(runner, old_sch, occ_sch)\n # set the availability schedule of the airloop to the newly generated schedule\n air_loop.setAvailabilitySchedule(occ_sch)\n runner.registerInfo(\"The availability schedule named #{old_sch.name} for #{air_loop.name} was replaced with a new schedule named #{occ_sch.name} which tracks the occupancy profile of the thermal zones on this airloop.\")\n air_loop_count +=1\n \n end\n\n #loop through each thermal zone\n model.getThermalZones.sort.each do |thermal_zone|\n \n # zone equipments assigned to thermal zones\n thermal_zone_equipment = thermal_zone.equipment \n \n if thermal_zone_equipment.size >= 1\n # run schedule method to create a new schedule ruleset, routines \n occ_sch = thermal_zone.get_occupancy_schedule(0.15)\n \n #loop through Zone HVAC Equipment\n thermal_zone_equipment.each do |equip|\n \n # getting the fan exhaust object & getting relevant information for it. \n if equip.to_FanZoneExhaust.is_initialized\n zone_equip = equip.to_FanZoneExhaust.get\n old_schedule = zone_equip.availabilitySchedule.get\n next unless compare_eflh(runner, old_schedule, occ_sch)\n #assign the 'occ_sch' here as exhaust's availability schedule\n zone_equip.setAvailabilitySchedule(occ_sch)\n runner.registerInfo(\"The availability schedule named #{old_schedule.name} for the OS_Fan_ZoneExhaust named #{zone_equip.name} was replaced with a new schedule named #{occ_sch.name} representing the occupancy profile of the thermal zone named #{thermal_zone.name}.\")\n zone_hvac_count += 1 \t\n elsif equip.to_RefrigerationAirChiller.is_initialized\n zone_equip = equip.to_RefrigerationAirChiller.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_WaterHeaterHeatPump.is_initialized\n zone_equip = equip.to_WaterHeaterHeatPump.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardConvectiveElectric.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardConvectiveElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardConvectiveWater.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardConvectiveWater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardRadiantConvectiveElectric.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardRadiantConvectiveElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardRadiantConvectiveWater.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardRadiantConvectiveWater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACDehumidifierDX.is_initialized\n zone_equip = equip.to_ZoneHVACDehumidifierDX.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACEnergyRecoveryVentilator.is_initialized\n zone_equip = equip.to_ZoneHVACEnergyRecoveryVentilator.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\n elsif equip.to_ZoneHVACFourPipeFanCoil.is_initialized\n zone_equip = equip.to_ZoneHVACFourPipeFanCoil.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACHighTemperatureRadiant.is_initialized\n zone_equip = equip.to_ZoneHVACHighTemperatureRadiant.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\n elsif equip.to_ZoneHVACIdealLoadsAirSystem.is_initialized\n zone_equip = equip.to_ZoneHVACIdealLoadsAirSystem.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t \n elsif equip.to_ZoneHVACLowTemperatureRadiantElectric.is_initialized\n zone_equip = equip.to_ZoneHVACLowTemperatureRadiantElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACLowTempRadiantConstFlow.is_initialized\n zone_equip = equip.to_ZoneHVACLowTempRadiantConstFlow.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t \t\n elsif equip.to_ZoneHVACLowTempRadiantVarFlow.is_initialized\n zone_equip = equip.to_ZoneHVACLowTempRadiantVarFlow.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized\n zone_equip = equip.to_ZoneHVACPackagedTerminalAirConditioner.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACPackagedTerminalHeatPump.is_initialized\n zone_equip = equip.to_ZoneHVACPackagedTerminalHeatPump.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.is_initialized\n next unless compare_eflh(runner, old_schedule, occ_sch) \n equip.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.get.setTerminalUnitAvailabilityschedule(occ_sch)\n runner.registerInfo(\"The availability schedule for the Zone HVAC Terminal Unit Variable Refrigerant Flow Object has been replaced with a new schedule named #{occ_sch.name} representing the occupancy profile of the thermal zone named #{thermal_zone.name}.\")\t\t\t\t\t\n zone_hvac_count += 1 \n elsif equip.to_ZoneHVACUnitHeater.is_initialized\n zone_equip = equip.to_ZoneHVACUnitHeater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\n elsif equip.to_ZoneHVACUnitVentilator.is_initialized\n zone_equip = equip.to_ZoneHVACUnitVentilator.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneVentilationDesignFlowRate.is_initialized\n runner.registerInfo(\"Thermal Zone named #{thermal_zone.name} has a Zone Ventilation Design Flow Rate object attacjhed as a ZoneHVACEquipment object. No modification were made to this object.\")\t\t\n end \t\n \n end # end loop through Zone HVAC Equipment\n \n else\n runner.registerInfo(\"Thermal Zone named #{thermal_zone.name} has no Zone HVAC Equipment objects attached - therefore no schedule objects have been altered.\")\t\n end # end of if statement\n \n end # end loop through thermal zones\n\n # Change pump control status if any airloops or\n # zone equipment were changed.\n if air_loop_count > 0 || zone_hvac_count > 0\n model.getPlantLoops.each do |plantLoop|\n #Loop through each plant loop demand component\n plantLoop.demandComponents.each do |dc|\n if dc.to_PumpConstantSpeed.is_initialized\n cs_pump = dc.to_PumpConstantSpeed.get\n if cs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Demand side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{dc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Pump Control Type attribute of Demand side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{dc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end\n end\n \n if dc.to_PumpVariableSpeed.is_initialized\n vs_pump = dc.to_PumpVariableSpeed.get\n if vs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Demand side Variable Speed Pump named #{vs_pump.name} on the plant loop named #{dc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Demand side Pump Control Type attribute of Variable Speed Pump named #{vs_pump.name} on the plant loop named #{dc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end\n end\n end\n \n #Loop through each plant loop supply component\n plantLoop.supplyComponents.each do |sc|\n if sc.to_PumpConstantSpeed.is_initialized\n cs_pump = sc.to_PumpConstantSpeed.get\n if cs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Supply side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{sc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Supply Side Pump Control Type atteribute of Constant Speed Pump named #{cs_pump.name} on the plant loop named #{sc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end #end if statement\t\n end #end if statement for changing supply component constant speed pump objects\n \n if sc.to_PumpVariableSpeed.is_initialized\n vs_pump = sc.to_PumpVariableSpeed.get\n if vs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Supply side Variable Speed Pump object named #{vs_pump.name} on the plant loop named #{sc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Pump Control Type attribute of Supply Side Variable Speed Pump named #{vs_pump.name} on the plant loop named #{sc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end #end if statement\t\n end #end if statement for changing supply component variable speed pump objects\n \n end # end loop throught plant loop supply side components\n \n end # end loop through plant loops\n end\n \n #Write N/A message\n if air_loop_count == 0 && zone_hvac_count == 0 && pump_count == 0 \n runner.registerAsNotApplicable(\"The model did not contain any Airloops, Thermal Zones having ZoneHVACEquipment objects or associated plant loop pump objects to act upon. The measure is not applicable.\")\n return true\n end\t\n \n #report initial condition of model\n runner.registerInitialCondition(\"The model started with #{air_loop_count} AirLoops, #{zone_hvac_count} Zone HVAC Equipment Object and #{pump_count} pump objects subject to modifications.\")\n \n # report final condition of model\n runner.registerFinalCondition(\"The measure modified the availability schedules of #{air_loop_count} AirLoops and #{zone_hvac_count} Zone HVAC Equipment objects. #{pump_count} pump objects had control settings modified.\")\n \n # Add ASHRAE Standard 55 warnings\n reporting_frequency = \"Timestep\"\n outputVariable = OpenStudio::Model::OutputVariable.new(\"Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status []\",model)\n outputVariable.setReportingFrequency(reporting_frequency)\n runner.registerInfo(\"Adding output variable for 'Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status' reporting at the model timestep.\")\n \n return true\n\t\n end", "def calc_next_run\n nil\n end", "def calc_next_run\n nil\n end", "def running_test_case; end", "def estimate\n # (native code) \n end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def run; end", "def tick; end", "def tick; end", "def tick; end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n verbose_info_statements = runner.getBoolArgumentValue(\"verbose_info_statements\",user_arguments)\n fixed_window_subsurface = runner.getOptionalWorkspaceObjectChoiceValue('fixed_window_subsurface', user_arguments, model) # model is passed in because of argument type\n internal_variable_availability_dictionary_reporting = runner.getStringArgumentValue('internal_variable_availability_dictionary_reporting', user_arguments)\n ems_runtime_language_debug_output_level = runner.getStringArgumentValue('ems_runtime_language_debug_output_level', user_arguments) \n actuator_availability_dictionary_reporting = runner.getStringArgumentValue('actuator_availability_dictionary_reporting', user_arguments) \n \n runner.registerInitialCondition(\"Measure began with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n \n # declare arrys for scope\n array_of_21_sets = []\n material_property_glazing_spectral_data_vector = []\n standard_glazing_layer_array = []\n construction_array = []\n ems_window_construction_array = []\n \n # load idf into workspace\n workspace = OpenStudio::Workspace::load(OpenStudio::Path.new(\"#{File.dirname(__FILE__)}/resources/EMSThermochromicWindow.idf\")).get\n \n # get all MaterialPropertyGlazingSpectralData objects from within the idf\n # material_property_glazing_spectral_datas = source_idf.getObjectsByType(\"MaterialProperty:GlazingSpectralData\".to_IddObjectType)\n material_property_glazing_spectral_datas = workspace.getObjectsByType(\"MaterialProperty:GlazingSpectralData\".to_IddObjectType)\n if verbose_info_statements == true\n runner.registerInfo(\"The model has #{material_property_glazing_spectral_datas.size} material_property_glazing_spectral_datas objects.\")\n end\n \n material_property_glazing_spectral_datas.each do |material_property_glazing_spectral_data|\n \n spectral_data = {\"name\" => \"\",\"properties\" => []}\n spectral_data[\"name\"] = material_property_glazing_spectral_data.getString(0).to_s\n \n # Note: EnergyPlus file MaterialProperty:GlazingSpectralData objects have 1764 /4 = 441 sets of 4 values each \n n = material_property_glazing_spectral_data.numFields\n (1..n).each do |i| \n spectral_data[\"properties\"] << material_property_glazing_spectral_data.getString(i).to_s \n end\n array_of_21_sets << spectral_data\n end\n \n array_of_21_sets.each do |set|\n \n props = set[\"properties\"]\n material_property_glazing_spectral_data = OpenStudio::Model::MaterialPropertyGlazingSpectralData.new(model)\n material_property_glazing_spectral_data.setName(\"#{set[\"name\"]}\")\n \n k = (props.length / 4) - 1\n (0..k).each do |i| # note 440 uniques (a, b, c, d) pairs of attributes for each spectral data field object\n material_property_glazing_spectral_data.addSpectralDataField(props[(i*4)+0].to_f, props[(i*4)+1].to_f, props[(i*4)+2].to_f, props[(i*4)+3].to_f)\t\n end\n \n material_property_glazing_spectral_data_vector << material_property_glazing_spectral_data\n end \n \n # create (2) required new air gas materials to used by all EMS window constructions \n air_gas_3mm_material = OpenStudio::Model::Gas.new(model, \"Air\", 0.003) \n air_gas_3mm_material.setName(\"AIR 3MM\")\n \n air_gas_8mm_material = OpenStudio::Model::Gas.new(model, \"Air\", 0.008) \n air_gas_8mm_material.setName(\"AIR 8MM\")\n \n # loop through array of OS MaterialPropertyGlazingSpectralData objects and create 21 new Standard Glazing objects \n material_property_glazing_spectral_data_vector.each do |spec_data_obj|\n spec_data_obj_name = spec_data_obj.name\n layer_name = spec_data_obj_name.to_s.slice(\"sp\")\n if ((spec_data_obj_name == \"WO18RT25SP\") || (spec_data_obj_name == \"Clear3PPGSP\"))\n layer = OpenStudio::Model::StandardGlazing.new(model, 'Spectral', 0.0075)\n else\n layer = OpenStudio::Model::StandardGlazing.new(model, 'Spectral', 0.003276)\n end\n layer.setName(\"#{layer_name}\")\n layer.setWindowGlassSpectralDataSet(spec_data_obj)\n layer.setInfraredTransmittanceatNormalIncidence(0) # same for all 21 constructions\n layer.setFrontSideInfraredHemisphericalEmissivity(0.84) # same for all 21 constructions\n layer.setBackSideInfraredHemisphericalEmissivity(0.84) # same for all 21 constructions\n if ((spec_data_obj_name == \"WO18RT25SP\") || (spec_data_obj_name == \"Clear3PPGSP\"))\n layer.setConductivity(1.0) \n else\n layer.setConductivity(0.6) \n end\n layer.setDirtCorrectionFactorforSolarandVisibleTransmittance(1) # same for all 21 constructions\n layer.setSolarDiffusing(false)\n standard_glazing_layer_array << layer\n end\n\n # Create (2) unique standard glazing layers not used for Thermochromatic performance \n sb60_clear_3_ppg_layer = standard_glazing_layer_array[0]\n clear_3ppg_layer = standard_glazing_layer_array[1]\n remaining_standard_glazing_layer_array = standard_glazing_layer_array.drop(2)\n \n # create (19) new arrays of layered constructions representing thermochromatic layers\n remaining_standard_glazing_layer_array.each do |remaining_standard_glazing_layer|\n construction = [sb60_clear_3_ppg_layer, air_gas_3mm_material, remaining_standard_glazing_layer, air_gas_8mm_material, sb60_clear_3_ppg_layer]\n construction_array << construction\n end\n \n # create 19 new OS:Construction objects representing EMS thermochromatic windows\n name_index_array = [25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 50, 55, 60, 65, 70, 75, 80, 85]\n index = 0\n \n construction_array.each do |const|\n ems_window_construction = OpenStudio::Model::Construction.new(const)\n ems_window_construction.setName(\"TCwindow_#{name_index_array[index]}\")\n if verbose_info_statements == true\n runner.registerInfo(\"Created a new Construction named #{ems_window_construction.name} representing a thermochromatic window construction.\")\n end\n ems_window_construction_array << ems_window_construction\n index +=1\n end\n\n # check the user argument of the fixed window subsurface for reasonableness\n if fixed_window_subsurface.empty?\n handle = runner.getStringArgumentValue('fixed_window_subsurface', user_arguments)\n if handle.empty?\n runner.registerError('No fixed window subsurface was chosen.')\n else\n runner.registerError(\"The selected fixed window subsurface with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if !fixed_window_subsurface.get.to_SubSurface.empty?\n fixed_window_subsurface = fixed_window_subsurface.get.to_SubSurface.get\n else\n runner.registerError('Script Error - argument not showing up as construction.')\n return false\n end\n end\n \n # Create a new EnergyManagementSystem:Sensor object representing the Surface Outside Face temp of the EMS thermochromatic window subsurface\n ems_win_Tout_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"Surface Outside Face Temperature\")\n ems_win_Tout_sensor.setName(\"Win1_Tout\")\n ems_win_Tout_sensor.setKeyName(\"#{fixed_window_subsurface.name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Sensor object named '#{ems_win_Tout_sensor.name}' representing the Surface Outside Face temp of the EMS thermochromatic window subsurface was added to the model.\") \n end\n \n # Create a new EMS Actuator Object representing the construction state of the EMS generated thermochromatic window \n ems_win_construct_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(fixed_window_subsurface, \"Surface\", \"Construction State\")\n ems_win_construct_actuator.setName(\"Win1_Construct\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Actuator object named '#{ems_win_construct_actuator.name}' representing construction state of the EMS generated thermochromatic window was added to the model.\") \n end\n \n # Create 19 EnergyManagementSystem:ConstructionIndexVariable objects for each unique thermochromatic construction\n ems_window_construction_array.each do |ems_window_construction|\n ems_constr_index_var = OpenStudio::Model::EnergyManagementSystemConstructionIndexVariable.new(model, ems_window_construction ) \n ems_constr_index_var.setName(\"#{ems_window_construction.name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS SystemConstructionIndexVariable object named '#{ems_constr_index_var.name}' representing the the EMS construction state of the thermochromatic window was added to the model.\") \n end\n end\n \n # Create new EnergyManagementSystem:Program object for assigning different window constructions by dynamically evaluating the exterior surface temp of the fixed window subsurface \n ems_apply_thermochromatic_constructions_prgm = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n ems_apply_thermochromatic_constructions_prgm.setName(\"#{fixed_window_subsurface.name}_Control\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"IF #{ems_win_Tout_sensor.name} <= 26.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_25\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 28.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_27\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 30.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_29\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 32.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_31\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 34.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_33\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 36.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_35\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 38.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_37\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 40.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_39\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 42.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_41\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 44.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_43\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 47.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_45\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 52.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_50\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 57.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_55\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 62.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_60\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 67.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_65\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 72.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_70\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 77.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_75\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 82.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_80\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSE\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_85\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ENDIF\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Program Object named '#{ems_apply_thermochromatic_constructions_prgm.name}' for dynamically assigning different window constructions based on the exterior surface temp was added to the model.\") \n end\n \n # Create a new EnergyManagementSystem:ProgramCallingManager object configured to call the EMS programs\n ems_prgm_calling_mngr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n ems_prgm_calling_mngr.setName(\"My thermochromic window emulator\")\n ems_prgm_calling_mngr.setCallingPoint(\"BeginTimestepBeforePredictor\")\n ems_prgm_calling_mngr.addProgram(ems_apply_thermochromatic_constructions_prgm)\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program Calling Manager object named '#{ems_prgm_calling_mngr.name}' added to call EMS program for dynamically applying a thermochromatic window.\") \n end\n \n # create unique object for OutputEnergyManagementSystems and configure to allow EMS reporting\n outputEMS = model.getOutputEnergyManagementSystem\n outputEMS.setInternalVariableAvailabilityDictionaryReporting(\"internal_variable_availability_dictionary_reporting\")\n outputEMS.setEMSRuntimeLanguageDebugOutputLevel(\"ems_runtime_language_debug_output_level\")\n outputEMS.setActuatorAvailabilityDictionaryReporting(\"actuator_availability_dictionary_reporting\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS OutputEnergyManagementSystem object configured per user arguments.\") \n end\n \n runner.registerFinalCondition(\"Measure finished with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n\n end", "def bench(action, msg = nil)\n @t ||= Time.now\n @total ||= 0\n @step ||= 0\n case action\n when :start\n @step = 0\n @total = 0\n @t = Time.now\n when :step\n @step += 1\n int = Time.now - @t\n @total += int\n @t = Time.now\n dbg(\"Benchmark #{msg.nil? ? (\"%02d\" % @step) : msg}: #{\"%8.3fms\" % (int * 1000)} (Total: #{\"%8.3fms\" % (@total * 1000)}).\")\n end\nend", "def apply_measure_and_run(test_name, measure, argument_map, osm_path, epw_path, run_model: false)\n assert(File.exist?(osm_path))\n assert(File.exist?(epw_path))\n\n # create run directory if it does not exist\n if !File.exist?(run_dir(test_name))\n FileUtils.mkdir_p(run_dir(test_name))\n end\n assert(File.exist?(run_dir(test_name)))\n\n # change into run directory for tests\n start_dir = Dir.pwd\n Dir.chdir run_dir(test_name)\n\n # remove prior runs if they exist\n if File.exist?(model_output_path(test_name))\n FileUtils.rm(model_output_path(test_name))\n end\n if File.exist?(report_path(test_name))\n FileUtils.rm(report_path(test_name))\n end\n\n # copy the osm and epw to the test directory\n new_osm_path = \"#{run_dir(test_name)}/#{File.basename(osm_path)}\"\n FileUtils.cp(osm_path, new_osm_path)\n new_epw_path = \"#{run_dir(test_name)}/#{File.basename(epw_path)}\"\n FileUtils.cp(epw_path, new_epw_path)\n # create an instance of a runner\n runner = OpenStudio::Measure::OSRunner.new(OpenStudio::WorkflowJSON.new)\n\n # load the test model\n model = load_model(new_osm_path)\n\n # set model weather file\n epw_file = OpenStudio::EpwFile.new(OpenStudio::Path.new(new_epw_path))\n OpenStudio::Model::WeatherFile.setWeatherFile(model, epw_file)\n assert(model.weatherFile.is_initialized)\n\n # run the measure\n puts \"\\nAPPLYING MEASURE...\"\n measure.run(model, runner, argument_map)\n result = runner.result\n\n # show the output\n show_output(result)\n\n # save model\n model.save(model_output_path(test_name), true)\n\n errs = []\n if run_model && (result.value.valueName == 'Success')\n puts \"\\nRUNNING ANNUAL SIMULATION...\"\n\n std = Standard.build('NREL ZNE Ready 2017')\n std.model_run_simulation_and_log_errors(model, run_dir(test_name))\n\n # check that the model ran successfully and generated a report\n assert(File.exist?(model_output_path(test_name)))\n assert(File.exist?(sql_path(test_name)))\n assert(File.exist?(report_path(test_name)))\n\n # set runner variables\n runner.setLastEpwFilePath(epw_path)\n runner.setLastOpenStudioModelPath(OpenStudio::Path.new(model_output_path(test_name)))\n runner.setLastEnergyPlusSqlFilePath(OpenStudio::Path.new(sql_path(test_name)))\n sql = runner.lastEnergyPlusSqlFile.get\n model.setSqlFile(sql)\n\n # test for unmet hours\n unmet_heating_hrs = std.model_annual_occupied_unmet_heating_hours(model)\n unmet_cooling_hrs = std.model_annual_occupied_unmet_cooling_hours(model)\n unmet_hrs = std.model_annual_occupied_unmet_hours(model)\n max_unmet_hrs = 550\n if unmet_hrs\n if unmet_hrs > 550\n errs << \"For #{test_name} there were #{unmet_heating_hrs.round(1)} unmet occupied heating hours and #{unmet_cooling_hrs.round(1)} unmet occupied cooling hours (total: #{unmet_hrs.round(1)}), more than the limit of #{max_unmet_hrs}.\" if unmet_hrs > max_unmet_hrs\n else\n puts \"There were #{unmet_heating_hrs.round(1)} unmet occupied heating hours and #{unmet_cooling_hrs.round(1)} unmet occupied cooling hours (total: #{unmet_hrs.round(1)}).\"\n end\n else\n errs << \"For #{test_name} could not determine unmet hours; simulation may have failed.\"\n end\n end\n\n # change back directory\n Dir.chdir(start_dir)\n\n assert(errs.empty?, errs.join(\"\\n\"))\n\n return result\n end", "def after_assumption(name); end", "def call\n result = while_measuring_memory_usage { action.call }\n\n Measurement.from_result(result)\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n retrofit_month = runner.getStringArgumentValue('retrofit_month', user_arguments).to_i\n retrofit_day = runner.getStringArgumentValue('retrofit_day', user_arguments).to_i\n\n # report initial condition of model\n runner.registerInitialCondition(\"Measure started successfully.\")\n\n # TODO: check the month and day for reasonableness\n runner.registerInfo(\"User entered retrofit month: #{retrofit_month}\")\n runner.registerInfo(\"User entered retrofit day: #{retrofit_day}\")\n\n prog_calling_manager = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n prog_calling_manager.setCallingPoint('BeginTimestepBeforePredictor')\n\n # Remove old and add new equip with EMS by spaces\n hash_space_epd = Hash.new\n v_spaces = model.getSpaces\n v_spaces.each do |space|\n current_space_equip = space.electricEquipment[0]\n unless current_space_equip.nil?\n\n # Get equipment power density for each space type\n new_space_epd = runner.getOptionalDoubleArgumentValue(\"new_#{space.name.to_s}_epd\", user_arguments)\n if new_space_epd.is_initialized\n hash_space_epd[\"new_#{space.name.to_s}_epd\"] = new_space_epd\n runner.registerInfo(\"User entered new electric equipment power density for #{space.name.to_s} is #{new_space_epd} W/m2\")\n # Set ems\n current_space_equip_def = current_space_equip.electricEquipmentDefinition\n equip_sch_name = current_space_equip.schedule.get.nameString\n equip_sch_ems_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n equip_sch_ems_sensor.setKeyName(equip_sch_name)\n runner.registerInfo(\"Delete old equip object for #{space.name}\")\n current_space_equip.remove\n\n new_equip = add_equip_space(space, current_space_equip_def)\n equip_level_w = new_space_epd.to_f * space.floorArea.to_f\n ems_equip_program = add_equip_ems(model, new_equip, equip_level_w, equip_sch_ems_sensor, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n else\n # Get equipment power ratio for each space type\n new_space_ratio = runner.getDoubleArgumentValue(\"new_#{space.name.to_s}_ratio\", user_arguments)\n\n old_equip_sch = current_space_equip.schedule.get\n ems_equip_program = add_equip_ems_w_occ_var(model, current_space_equip, old_equip_sch, new_space_ratio, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n # runner.registerInfo(\"Delete old equip object for #{space.name}\")\n # current_space_equip.remove\n end\n\n end\n end\n\n # Remove old and add new equip with EMS by space types\n hash_space_type_epd = Hash.new\n v_space_types = model.getSpaceTypes\n v_space_types.each do |space_type|\n current_spaces = space_type.spaces\n current_space_type_equip = space_type.electricEquipment[0]\n unless current_space_type_equip.nil?\n # Get equipment power density for each space type\n current_space_type_epd = runner.getStringArgumentValue(\"new_#{space_type.name.to_s}_epd\", user_arguments)\n hash_space_type_epd[\"new_#{space_type.name.to_s}_epd\"] = current_space_type_epd\n runner.registerInfo(\"User entered new electric equipment power density for #{space_type.name.to_s} is #{current_space_type_epd} W/m2\")\n\n # Set ems\n current_space_type_equip_def = current_space_type_equip.electricEquipmentDefinition\n current_space_type_sch_set = space_type.defaultScheduleSet.get\n current_space_type_equip_sch_set = current_space_type_sch_set.electricEquipmentSchedule.get\n\n equip_sch_name = current_space_type_equip_sch_set.nameString\n equip_sch_ems_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n equip_sch_ems_sensor.setKeyName(equip_sch_name)\n\n puts \"Delete old equip object for #{space_type.name}\"\n current_space_type_equip.remove\n\n current_spaces.each do |space|\n # Calculate equipemtn electric power for each space\n new_equip = add_equip_space_type(model, space, space_type, current_space_type_equip_def)\n equip_level_w = current_space_type_epd.to_f * space.floorArea.to_f\n ems_equip_program = add_equip_ems(model, new_equip, equip_level_w, equip_sch_ems_sensor, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n end\n end\n end\n\n # echo the model updates back to the user\n runner.registerInfo(\"The electric equipment retrofit measure is applied.\")\n\n # report final condition of model\n runner.registerFinalCondition(\"Measure ended successfully.\")\n\n return true\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n runner.registerInfo(\"Start to create lighting measure from occupant schedule\")\n\n ### Get user selected lighting space assumptions for each space\n v_space_types = model.getSpaceTypes\n i = 1\n lght_space_type_arg_vals = {}\n # Loop through all space types, group spaces by their types\n v_space_types.each do |space_type|\n # Loop through all spaces of current space type\n v_current_spaces = space_type.spaces\n next if not v_current_spaces.size > 0\n v_current_spaces.each do |current_space|\n lght_space_type_val = runner.getStringArgumentValue(@@v_space_args[current_space.nameString], user_arguments)\n lght_space_type_arg_vals[current_space.nameString] = lght_space_type_val\n i += 1\n end\n end\n\n puts lght_space_type_arg_vals\n\n ### Start creating new lighting schedules based on occupancy schedule\n occ_schedule_dir = runner.getStringArgumentValue('occ_schedule_dir', user_arguments)\n model_temp_run_path = Dir.pwd + '/'\n measure_root_path = File.dirname(__FILE__)\n\n puts '=' * 80\n puts measure_root_path\n\n if File.file?(occ_schedule_dir)\n # Check if user provided a occupancy schedule CSV file\n csv_file = occ_schedule_dir\n puts 'Use user provided occupancy schedule file at: ' + csv_file.to_s\n runner.registerInitialCondition('Location check:' + File.expand_path(\"../..\", measure_root_path))\n # runner.registerInitialCondition('Use user provided occupancy schedule file at: ' + csv_file.to_s)\n else\n # Check if schedule file at several places\n # 1. Default fils path when run with OSW in CLI\n csv_path_lookup_1 = File.expand_path(\"../..\", measure_root_path) + \"/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"First lookup location: \" + csv_path_lookup_1\n runner.registerInfo(\"First lookup location: \" + csv_path_lookup_1)\n # 2. Default path when run with OpenStudio CLI\n csv_path_lookup_2 = File.expand_path(\"../..\", model_temp_run_path) + \"/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Second lookup location: \" + csv_path_lookup_2\n runner.registerInfo(\"Second lookup location: \" + csv_path_lookup_2)\n # 3. Default path when run with OpenStudio GUI\n csv_path_lookup_3 = File.expand_path(\"../../..\", model_temp_run_path) + \"/resources/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Third lookup location: \" + csv_path_lookup_3\n runner.registerInfo(\"Third lookup location: \" + csv_path_lookup_3)\n # 4. Generated files folder when run with rspec\n csv_path_lookup_4 = File.expand_path(\"..\", model_temp_run_path) + \"/generated_files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Forth lookup location: \" + csv_path_lookup_4\n runner.registerInfo(\"Forth lookup location: \" + csv_path_lookup_4)\n # 5. Generated files folder with OpenStudio V2.9.0+\n csv_path_lookup_5 = File.join(File.expand_path(\"../..\", model_temp_run_path), 'generated_files', @@default_occupant_schedule_filename)\n puts '#' * 80\n puts \"Fifth lookup location: \" + csv_path_lookup_5\n runner.registerInfo(\"Fifth lookup location: \" + csv_path_lookup_5)\n\n if File.file?(csv_path_lookup_1)\n csv_file = csv_path_lookup_1\n elsif File.file?(csv_path_lookup_2)\n csv_file = csv_path_lookup_2\n elsif File.file?(csv_path_lookup_3)\n csv_file = csv_path_lookup_3\n elsif File.file?(csv_path_lookup_4)\n csv_file = csv_path_lookup_4 \n elsif File.file?(csv_path_lookup_5)\n csv_file = csv_path_lookup_5\n else\n csv_file = ''\n end\n puts 'Use default occupancy schedule file at: ' + csv_file.to_s\n runner.registerInfo('Use default occupancy schedule file at: ' + csv_file.to_s)\n end\n\n # Get the spaces with occupancy count schedule available\n v_spaces_occ_sch = File.readlines(csv_file)[3].split(',') # Room ID is saved in 4th row of the occ_sch file\n v_headers = Array.new\n v_spaces_occ_sch.each do |space_occ_sch|\n if !['Room ID', 'Outdoor', 'Outside building'].include? space_occ_sch and !space_occ_sch.strip.empty?\n v_headers << space_occ_sch\n end\n end\n v_headers = [\"Time\"] + v_headers\n\n # report initial condition of model\n runner.registerInfo(\"The building has #{v_headers.length - 1} spaces with available occupant schedule file.\")\n\n # Read the occupant count schedule file and clean it\n clean_csv = File.readlines(csv_file).drop(6).join\n csv_table_sch = CSV.parse(clean_csv, headers: true)\n new_csv_table = csv_table_sch.by_col!.delete_if do |column_name, column_values|\n !v_headers.include? column_name\n end\n\n runner.registerInfo(\"Successfully read occupant count schedule from CSV file.\")\n runner.registerInfo(\"Creating new lighting schedules...\")\n\n # Create lighting schedule based on the occupant count schedule\n v_cols = Array.new\n v_ts = new_csv_table.by_col!['Time']\n v_headers.each do |header|\n if header != 'Time'\n space_name = header\n v_occ_n = new_csv_table.by_col![space_name]\n v_light = create_lighting_sch_from_occupancy_count(space_name, v_ts, v_occ_n, @@off_delay)\n v_cols << v_light\n end\n end\n\n runner.registerInfo(\"Writing new lighting schedules to CSV file.\")\n # Write new lighting schedule file to CSV\n file_name_light_sch = \"#{model_temp_run_path}/#{@@lighting_schedule_CSV_name}\"\n vcols_to_csv(v_cols, file_name_light_sch)\n\n # Add new lighting schedule from the CSV file created\n runner.registerInfo(\"Removing old OS:Lights and OS:Lights:Definition for office and conference rooms.\")\n # Remove old lights definition objects for office and conference rooms\n v_space_types.each do |space_type|\n space_type.spaces.each do |space|\n selected_space_type = lght_space_type_arg_vals[space.name.to_s]\n if (@@office_type_names.include? selected_space_type) || (@@conference_room_type_names.include? selected_space_type)\n space_type.lights.each do |lght|\n puts 'Remove old lights definition object: ' + lght.lightsDefinition.name.to_s\n lght.lightsDefinition.remove\n end\n end\n end\n end\n\n # Remove old lights objects for office and conference rooms\n # Caution: the order of deletion matters\n v_space_types.each do |space_type|\n space_type.spaces.each do |space|\n selected_space_type = lght_space_type_arg_vals[space.name.to_s]\n if (@@office_type_names.include? selected_space_type) || (@@conference_room_type_names.include? selected_space_type)\n space_type.lights.each do |lght|\n puts 'Remove old lights object: ' + lght.name.to_s\n lght.remove\n end\n end\n end\n end\n\n puts '---> Create new lighting schedules from CSV.'\n\n runner.registerInfo(\"Adding new OS:Schedule:File objects to the model....\")\n v_spaces = model.getSpaces\n v_spaces.each do |space|\n v_headers.each_with_index do |s_space_name, i|\n if s_space_name == space.name.to_s\n col = i\n temp_file_path = file_name_light_sch\n sch_file_name = space.name.to_s + ' lght sch'\n schedule_file = get_os_schedule_from_csv(model, temp_file_path, sch_file_name, col, skip_row = 1)\n schedule_file.setMinutesperItem(@@minute_per_item.to_s)\n model = add_light(model, space, schedule_file)\n end\n end\n end\n\n # report final condition of model\n runner.registerFinalCondition(\"Finished creating and adding new lighting schedules for #{v_headers.length - 1} spaces.\")\n\n return true\n end", "def span\n measure\n @span\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n #use the built-in error checking \n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # System Type 2: PTHP, Residential\n # This measure creates:\n # a constant volume packaged terminal heat pump unit with DX heating \n # and cooling for each zone in the building\n \n always_on = model.alwaysOnDiscreteSchedule\n\n # Make a PTHP for each zone\n model.getThermalZones.each do |zone|\n \n fan = OpenStudio::Model::FanConstantVolume.new(model,always_on)\n fan.setPressureRise(300)\n\n supplemental_htg_coil = OpenStudio::Model::CoilHeatingElectric.new(model,always_on)\n\n clg_cap_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)\n clg_cap_f_of_temp.setCoefficient1Constant(0.942587793)\n clg_cap_f_of_temp.setCoefficient2x(0.009543347)\n clg_cap_f_of_temp.setCoefficient3xPOW2(0.0018423)\n clg_cap_f_of_temp.setCoefficient4y(-0.011042676)\n clg_cap_f_of_temp.setCoefficient5yPOW2(0.000005249)\n clg_cap_f_of_temp.setCoefficient6xTIMESY(-0.000009720)\n clg_cap_f_of_temp.setMinimumValueofx(17.0)\n clg_cap_f_of_temp.setMaximumValueofx(22.0)\n clg_cap_f_of_temp.setMinimumValueofy(13.0)\n clg_cap_f_of_temp.setMaximumValueofy(46.0)\n\n clg_cap_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)\n clg_cap_f_of_flow.setCoefficient1Constant(0.718954)\n clg_cap_f_of_flow.setCoefficient2x(0.435436)\n clg_cap_f_of_flow.setCoefficient3xPOW2(-0.154193)\n clg_cap_f_of_flow.setMinimumValueofx(0.75)\n clg_cap_f_of_flow.setMaximumValueofx(1.25)\n\n clg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)\n clg_energy_input_ratio_f_of_temp.setCoefficient1Constant(0.342414409)\n clg_energy_input_ratio_f_of_temp.setCoefficient2x(0.034885008)\n clg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(-0.000623700)\n clg_energy_input_ratio_f_of_temp.setCoefficient4y(0.004977216)\n clg_energy_input_ratio_f_of_temp.setCoefficient5yPOW2(0.000437951)\n clg_energy_input_ratio_f_of_temp.setCoefficient6xTIMESY(-0.000728028)\n clg_energy_input_ratio_f_of_temp.setMinimumValueofx(17.0)\n clg_energy_input_ratio_f_of_temp.setMaximumValueofx(22.0)\n clg_energy_input_ratio_f_of_temp.setMinimumValueofy(13.0)\n clg_energy_input_ratio_f_of_temp.setMaximumValueofy(46.0)\n\n clg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)\n clg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.1552)\n clg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.1808)\n clg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0256)\n clg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.5)\n clg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.5)\n\n clg_part_load_fraction = OpenStudio::Model::CurveQuadratic.new(model)\n clg_part_load_fraction.setCoefficient1Constant(0.75)\n clg_part_load_fraction.setCoefficient2x(0.25)\n clg_part_load_fraction.setCoefficient3xPOW2(0.0)\n clg_part_load_fraction.setMinimumValueofx(0.0)\n clg_part_load_fraction.setMaximumValueofx(1.0)\n\n clg_coil = OpenStudio::Model::CoilCoolingDXSingleSpeed.new(model,\n always_on,\n clg_cap_f_of_temp,\n clg_cap_f_of_flow,\n clg_energy_input_ratio_f_of_temp,\n clg_energy_input_ratio_f_of_flow,\n clg_part_load_fraction)\n\n htg_cap_f_of_temp = OpenStudio::Model::CurveCubic.new(model)\n htg_cap_f_of_temp.setCoefficient1Constant(0.758746)\n htg_cap_f_of_temp.setCoefficient2x(0.027626)\n htg_cap_f_of_temp.setCoefficient3xPOW2(0.000148716)\n htg_cap_f_of_temp.setCoefficient4xPOW3(0.0000034992)\n htg_cap_f_of_temp.setMinimumValueofx(-20.0)\n htg_cap_f_of_temp.setMaximumValueofx(20.0)\n\n htg_cap_f_of_flow = OpenStudio::Model::CurveCubic.new(model)\n htg_cap_f_of_flow.setCoefficient1Constant(0.84)\n htg_cap_f_of_flow.setCoefficient2x(0.16)\n htg_cap_f_of_flow.setCoefficient3xPOW2(0.0)\n htg_cap_f_of_flow.setCoefficient4xPOW3(0.0)\n htg_cap_f_of_flow.setMinimumValueofx(0.5)\n htg_cap_f_of_flow.setMaximumValueofx(1.5)\n\n htg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveCubic.new(model)\n htg_energy_input_ratio_f_of_temp.setCoefficient1Constant(1.19248)\n htg_energy_input_ratio_f_of_temp.setCoefficient2x(-0.0300438)\n htg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(0.00103745)\n htg_energy_input_ratio_f_of_temp.setCoefficient4xPOW3(-0.000023328)\n htg_energy_input_ratio_f_of_temp.setMinimumValueofx(-20.0)\n htg_energy_input_ratio_f_of_temp.setMaximumValueofx(20.0)\n\n htg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)\n htg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.3824)\n htg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.4336)\n htg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0512)\n htg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.0)\n htg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.0)\n\n htg_part_load_fraction = OpenStudio::Model::CurveQuadratic.new(model)\n htg_part_load_fraction.setCoefficient1Constant(0.75)\n htg_part_load_fraction.setCoefficient2x(0.25)\n htg_part_load_fraction.setCoefficient3xPOW2(0.0)\n htg_part_load_fraction.setMinimumValueofx(0.0)\n htg_part_load_fraction.setMaximumValueofx(1.0)\n\n htg_coil = OpenStudio::Model::CoilHeatingDXSingleSpeed.new( model,\n always_on,\n htg_cap_f_of_temp,\n htg_cap_f_of_flow,\n htg_energy_input_ratio_f_of_temp,\n htg_energy_input_ratio_f_of_flow,\n htg_part_load_fraction ) \n\n pthp = OpenStudio::Model::ZoneHVACPackagedTerminalHeatPump.new(model,\n always_on, \n fan,\n htg_coil,\n clg_coil,\n supplemental_htg_coil)\n\n pthp.setName(\"#{zone.name} PTHP\")\n pthp.addToThermalZone(zone)\n\n end\n\n \n return true\n \n end" ]
[ "0.79848564", "0.7639647", "0.76355976", "0.7170129", "0.66926914", "0.66926914", "0.66718984", "0.66311747", "0.6599127", "0.65870225", "0.65324444", "0.6481582", "0.6405596", "0.64028287", "0.6333309", "0.6283632", "0.6283632", "0.6283632", "0.6281165", "0.6269874", "0.62425435", "0.62203735", "0.6198304", "0.6196627", "0.6196627", "0.61319697", "0.6107745", "0.60714525", "0.60513526", "0.601827", "0.6008391", "0.6008391", "0.60008335", "0.5976995", "0.59641606", "0.5962238", "0.5958165", "0.59570605", "0.59570605", "0.59439784", "0.5934565", "0.5928137", "0.5920926", "0.5916211", "0.59129107", "0.5911706", "0.59022516", "0.5872101", "0.5865909", "0.58645797", "0.5847354", "0.583844", "0.58373237", "0.57887447", "0.5772885", "0.57687855", "0.5756301", "0.5745138", "0.5740855", "0.5723286", "0.57180965", "0.5713821", "0.5698708", "0.5697907", "0.56978434", "0.56891346", "0.5688938", "0.5685465", "0.56740844", "0.5662743", "0.5649326", "0.56483626", "0.5646554", "0.56390476", "0.56390476", "0.5633756", "0.56218606", "0.56218606", "0.5608723", "0.5608213", "0.55982304", "0.55982304", "0.55982304", "0.55982304", "0.55982304", "0.55982304", "0.55982304", "0.55982304", "0.55982304", "0.559522", "0.559522", "0.559522", "0.55878526", "0.558349", "0.55677843", "0.5567233", "0.5564496", "0.55636495", "0.55590993", "0.5556679", "0.5547891" ]
0.0
-1
main parser invoked with command `sepp scan`
def scanfile(source, options) fn = File.basename(source,".*") if options[:backup] fback = File.join( File.dirname(source), "#{fn}_bak.md" ) `cp #{source} #{fback}` end # read and mark up {bibliography} for later use File.open(source) { |mdf| @md = mdf.read.gsub('{bibliography}','[--bib--]') } # get all citation ids (as matchData, therefore enumerate and not just .scan ) cids = @md.to_enum(:scan, /\{.+?\}/).map { Regexp.last_match } # get all inline references from Sente inl = sente6('create bibliography elements current library from tags "' + cids.join('||').gsub(/[\{\}]/,'').gsub('\\', '\&\&') + '" for intext').split('||') bib = sente6('create bibliography elements current library from tags "' + cids.join('||').gsub(/[\{\}]/,'').gsub('\\', '\&\&') + '" for bibliography') # inverse arrays cids = cids.reverse inl = inl.reverse.drop(1) log = [] err = [] if cids.count == inl.count cids.to_enum.with_index.each { |cid, i| # log this to allow for unscanning later # original citation id, formated inline citation, pre-match string (if formated in not unique) log << cid.to_s + '|' + inl[i] + '|' + cid.pre_match.split(//).last($handle).join # through error if no match found err << cid.to_s if inl[i] == '()' # replace citation id with formated string, using the offsets in cids's matchData o = cid.offset(0) @md[(o[0])..(o[1] - 1)] = inl[i] } end if err.count > 0 # notity @message = 'No match found for: ' + err.join(", ") if options[:notify] TerminalNotifier.notify(@message, :title => "No bibliography produced...", :open => "http://www.something.com") end puts @message else # Write output file (with added bibliography) File.open(source, 'w') {|f| f << @md.gsub('[--bib--]', bib.gsub('.<i> ','. *').gsub("<br>", "\n\n").gsub('<i>','*').gsub('</i>','*'))} # Write log file `mkdir -p "$HOME/Library/Application Support/sepp"` File.open(ENV["HOME"] + '/Library/Application Support/sepp/' + fn + '.log', 'w') {|f| f << log.join("\n")} #notify @message = 'Inline: ' + inl.count.to_s + '; References: ' + bib.gsub("<br>", "\n").lines.count.to_s + '.' if options[:notify] TerminalNotifier.notify(@message, :title => "Successfully produces bibliography", :open => "http://www.something.com") end puts @message end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse(args)\n #add the possible arguments to the argument parser\n\topt_parser = OptionParser.new do |opts|\n\t\topts.banner = \"Usage: Scanner.rb [options] file [files...]\"\n\t\topts.on(\"-s [FILE]\", \"--save [FILE]\", \"Saves to file [FILE]\") do |file|\n\t\t\t$save2File = true\n\t\t\t$file = File.new(Pathname.new(file).realpath, \"w+\")\n\t\tend\n opts.on(\"-x [FILE]\", \"--xml [FILE]\", \"Saves to XML file [FILE]\") do |file|\n $save2XML = true\n $xmlFile = File.new(Pathname.new(file).realpath, \"w+\")\n end\n\t\topts.on(\"-q\", \"--quiet\", \"Do not show output on console\") do\n\t\t\t$quiet = true\n\t\tend\n opts.on(\"-v\", \"--verbose\", \"Show additional output on the console, overwrites quiet\") do\n $verbose = true\n end\n\tend\n\t#start the parsing of the arguments\n\topt_parser.parse!(args)\nend", "def scanner; end", "def scanner; end", "def scanner; end", "def scanner; end", "def process(parser)\n end", "def parser; end", "def parser; end", "def parser; end", "def parser; end", "def scan\n #Puppet.debug(\"entering scan\")\n lex_error \"Internal Error: No string or file given to lexer to process.\" unless @scanner\n\n # Skip any initial whitespace.\n skip\n\n until token_queue.empty? and @scanner.eos? do\n offset = @scanner.pos\n matched_token, value = find_token\n end_offset = @scanner.pos\n\n # error out if we didn't match anything at all\n lex_error \"Could not match #{@scanner.rest[/^(\\S+|\\s+|.*)/]}\" unless matched_token\n\n newline = matched_token.name == :RETURN\n\n lexing_context[:start_of_line] = newline\n lexing_context[:offset] = offset\n lexing_context[:end_offset] = end_offset\n\n final_token, token_value = munge_token(matched_token, value)\n # update end position since munging may have moved the end offset\n lexing_context[:end_offset] = @scanner.pos\n\n unless final_token\n skip\n next\n end\n\n lexing_context[:after] = final_token.name unless newline\n if final_token.name == :DQPRE\n lexing_context[:interpolation_stack] << lexing_context[:brace_count]\n elsif final_token.name == :DQPOST\n lexing_context[:interpolation_stack].pop\n end\n\n value = token_value[:value]\n\n if match = @@pairs[value] and final_token.name != :DQUOTE and final_token.name != :SQUOTE\n @expected << match\n elsif exp = @expected[-1] and exp == value and final_token.name != :DQUOTE and final_token.name != :SQUOTE\n @expected.pop\n end\n\n yield [final_token.name, token_value]\n\n if @previous_token\n namestack(value) if @previous_token.name == :CLASS and value != '{'\n\n if @previous_token.name == :DEFINE\n if indefine?\n msg = \"Cannot nest definition #{value} inside #{@indefine}\"\n self.indefine = false\n raise Puppet::ParseError, msg\n end\n\n @indefine = value\n end\n end\n @previous_token = final_token\n skip\n end\n # Cannot reset @scanner to nil here - it is needed to answer questions about context after\n # completed parsing.\n # Seems meaningless to do this. Everything will be gc anyway.\n #@scanner = nil\n\n # This indicates that we're done parsing.\n yield [false,false]\n end", "def scan_tokens(tokens, options); end", "def scanner=(_arg0); end", "def scanner=(_arg0); end", "def scan\n PS2.scan(@options.scan, @options)\n end", "def scan\n @top_level.comment = remove_private_comments(@content)\n @top_level.parser = self.class\n @top_level\n end", "def parse(source)\n @parser.parse(@scanner.scan(source))\n end", "def scan(pattern); end", "def parser=(_arg0); end", "def parse(source); end", "def scan(**kw)\n result = (parse(**kw) + errors + @stack.flatten).uniq.sort_by {|e| [*e.pos, (e.message ? -1 : 0)]}\n result.each_with_index do |e, i|\n if e.event == :on_parse_error and e.tok.empty? and (pre = result[i-1]) and\n pre.pos[0] == e.pos[0] and (pre.pos[1] + pre.tok.size) == e.pos[1]\n e.tok = pre.tok\n e.pos[1] = pre.pos[1]\n result[i-1] = e\n result[i] = pre\n end\n end\n result\n end", "def parseProg\n\t\tputs \"parseProg\"\n\n\t\tparseMainClass()\n\t\twhile showNext.kind != :rsbrace\n\t\t\tparseClassDeclaration()\n\t\tend\n\t\texpect :rsbrace\n\n\t\treturn nil\n\tend", "def configure_parser; end", "def scan\n reset\n\n catch :eof do\n begin\n parse_top_level_statements @top_level\n\n rescue StandardError => e\n if @content.include?('<%') and @content.include?('%>') then\n # Maybe, this is ERB.\n $stderr.puts \"\\033[2KRDoc detects ERB file. Skips it for compatibility:\"\n $stderr.puts @file_name\n return\n end\n\n if @scanner_point >= @scanner.size\n now_line_no = @scanner[@scanner.size - 1][:line_no]\n else\n now_line_no = peek_tk[:line_no]\n end\n first_tk_index = @scanner.find_index { |tk| tk[:line_no] == now_line_no }\n last_tk_index = @scanner.find_index { |tk| tk[:line_no] == now_line_no + 1 }\n last_tk_index = last_tk_index ? last_tk_index - 1 : @scanner.size - 1\n code = @scanner[first_tk_index..last_tk_index].map{ |t| t[:text] }.join\n\n $stderr.puts <<-EOF\n\n#{self.class} failure around line #{now_line_no} of\n#{@file_name}\n\n EOF\n\n unless code.empty? then\n $stderr.puts code\n $stderr.puts\n end\n\n raise e\n end\n end\n\n @top_level\n end", "def parse_options\n @options = Slop.parse do\n banner \"ps2 [filename] [options]\\n\"\n \n on :name, 'Do not parse the name of the game from the ISO and use the given NAME instead.'\n on :code, 'Do not parse the code of the game from the ISO and use the given CODE instead.'\n on :scan, 'Scan the current or given DIRECTORY for ISO files and run ps2 on each, skipping failures. This ignores any other options.'\n on :version, 'Print the current version of ps2. This ignores any other options.'\n end\n \n @options.scan = Pathname.pwd if @options.scan == true\n end", "def run(argv = ARGV)\n parser.parse(argv)\n end", "def parse_all\n #check for skipping the block using add on module...\n parse_spc\n if @skiper.select{|f|send(f)}.length>0\n p \"skip > #{@row}\" if @dbg[:parse]\n else\n @plt_opt= '' \n #rtn= true if @selector.select{|f|send(f)}.length>0\n rtn = true if shortcut_exec( /(^[\\t ]*)\\-([\\w\\-&\\/:#.%]*\\{.*\\}=*) *([^\\n]*)\\n/) \n rtn = true if shortcut_exec( /(^[\\t ]*)\\-([\\w\\-&\\/:#.%=]*) *([^\\n]*)\\n/) \n rtn = true if shortcut_equal( /(^[\\t ]*)=([\\w\\-&\\/:#.%=]*) *([^\\n]*)\\n/) \n \n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]]+\\{.*?\\}[= ]*)([^\\n]*)\\n/)\n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]]+\\{.*?\\}[= ]*)()\\n/)\n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]%=]+ )([^\\n]*)\\n/) \n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]%=]+)()\\n/) \n \n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.]*\\{.*\\}[= ]*)([^\\n]*)\\n/)\n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.]*\\{.*\\}[= ]*)()\\n/)\n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.=]* )([^\\n]*)\\n/) \n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.=]*)()\\n/) \n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.]*\\{.*\\}[= ]*)([^\\n]*)\\n/)\n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.]*\\{.*\\}[= ]*)()\\n/)\n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.=]* )([^\\n]*)\\n/) \n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.=]*)()\\n/) \n rtn = true if parse_hot\n rtn = true if merge_hot\n rtn = true if merge_w2x\n rtn = true if parse_set_var\n rtn = true if parse_set_mem\n rtn = true if parse_get_mem\n rtn = true if inline_tag\n rtn = true if parse_end\n if parse_tags\n rtn = nil\n elsif !rtn\n auto_close \n end\n end\n rtn\n end", "def pluggable_parser; end", "def scan\n reset\n\n @container = @rake_tasks\n\n @stats.add_module @container\n\n catch :eof do\n catch :enddoc do\n parse_rakefile\n end\n end\n\n @top_level\n end", "def scan\n remove_commented_out_lines\n do_classes\n do_constants\n do_methods\n do_includes\n do_aliases\n @top_level\n end", "def scanner(lang, options = T.unsafe(nil), &block); end", "def interactive_parser ( )\n puts 'Press <Enter> to exit...'\n #\n # Цикл обработки ввода.\n loop {\n\tstr = interactive_input( )\n\tbreak if str == \"\"\n\t#\n\t# Цикл посимвольной классификаци.\n\tstr.bytes.each do |c|\n\t parse( c.chr )\n\t puts 'parser: ' + @parserstate\n\t puts 'symbol: ' + interactive_output( c.chr ).to_s\n\t puts 'buffer: ' + @buffer.to_s\n\t puts 'state: ' + @chain.last.statename\n\t puts\n\tend\n }\n end", "def parse!\n raise NotImplementedError, \"this class is intended to be a top class, not a useful parser\"\n end", "def scan(options={},&block)\n return enum_for(__method__,options) unless block\n\n scan_sources(options,&block)\n scan_specs(options,&block)\n\n return self\n end", "def parser( &block )\n nested_class( 'Parser', Yacl::Define::Cli::Parser, &block )\n end", "def scan; return nil; end", "def filter_single(text,args)\n Ritex::Parser.new.parse(args)\n end", "def scan\n # Ruby's 'extend' is a different from Python's\n $stack += $stack.pop.split\nend", "def start(name)\n reset\n @name_str = name\n @name = str_to_sym(name)\n @code << <<-CODE\n\t\t\tdef parse_#{name}\n\t\t\t\tresult = productions[#{@name}].default.call(@scanner,self)\n\t\tCODE\n self\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse(program)\n return read_the_tokens(tokenize(program))\nend", "def ps\n [VishParser.new, SexpTransform.new]\nend", "def parse(input = nil, options = 0)\n end", "def step\n case\n when check( /program\\s+/ )\n start_group :keyword, scan( /program\\s+/ )\n start_group :function, scan_until( /(?=[;(\\s]|#{EOL})/ )\n when check( /subroutine\\s+/ )\n start_group :keyword, scan( /subroutine\\s+/ )\n start_group :function, scan_until( /(?=[;(\\s]|#{EOL})/ )\n when check( /function\\s+/ )\n start_group :keyword, scan( /function\\s+/ )\n start_group :function, scan_until( /(?=[;(\\s]|#{EOL})/ )\n when check( /module\\s+/ )\n start_group :keyword, scan( /module\\s+/ )\n start_group :function, scan_until( /(?=[;\\s]|#{EOL})/ )\n when check( /\\.true\\.|\\.false\\.|\\.TRUE\\.|\\.FALSE\\./ )\n start_group :constant,\n scan(/\\.true\\.|\\.false\\.|\\.TRUE\\.|\\.FALSE\\./)\n when scan( /(\\d+\\.?\\d*|\\d*\\.?\\d+)([eEdDqQ][+-]?\\d+)?(_\\w+)?/ )\n start_group :number, matched\n when scan( /[bB]\\'[01]+\\'|[oO]\\'[0-7]+\\'|[zZ]\\'[0-9a-fA-F]+\\'/ )\n start_group :number, matched\n else\n case peek(1)\n when /[\\n\\r]/\n start_group :normal, scan( /\\s+/ )\n when /\\s/\n start_group :normal, scan( /\\s+/ )\n when \"!\"\n start_group :comment, scan( /![^\\n\\r]*/ )\n when /[A-Za-z]/\n word = scan( /\\w+/ )\n if KEYWORDS.include?(word)\n start_group :keyword, word\n elsif TYPES.include?(word)\n start_group :type, word\n elsif INTRINSICS.include?(word)\n start_group :function, word\n elsif\n start_group :ident, word\n end\n when '\"'\n # allow for continuation characters within strings\n start_group :string, scan(/\"([^\"]*(&[ ]*[\\n\\r]+)?)*\"/)\n when \"'\"\n # allow for continuation characters within strings\n start_group :string, scan(/'([^']*(&[ ]*[\\n\\r]+)?)*'/)\n when /[-!?*\\/+=<>()\\[\\]\\{}:;,&|%]/\n start_group :punct, scan(/./)\n else\n # pass everything else through\n append getch\n end\n end\n end", "def start\n parse!\n run\n end", "def _parse\n scanner = @scanner\n\n output = []\n\n while not scanner.eos? do\n output << handle_empty\n break if scanner.eos?\n\n if scanner.match?(BEGIN_SCOPE)\n output << handle_scope\n next\n end\n\n if scanner.match?(THEME_DIRECTIVE)\n output << handle_theme\n next\n end\n\n if scanner.match?(SELECTOR_THEME_VARIABLE)\n output << handle_theme_variable\n next\n end\n\n if scanner.match?(INCLUDE_SLICES_DIRECTIVE)\n output << handle_slices\n next\n end\n\n if scanner.match?(INCLUDE_SLICE_DIRECTIVE)\n output << handle_slice_include\n next\n end\n\n if scanner.match?(CHANCE_FILE_DIRECTIVE)\n handle_file_change\n next\n end\n\n break if scanner.match?(END_SCOPE)\n\n # skip over anything that our tokens do not start with\n res = scanner.scan(NORMAL_SCAN_UNTIL)\n if res.nil?\n output << scanner.getch\n else\n output << res\n end\n\n end\n\n output = output.join\n return output\n end", "def cli_parse\n @command = nil\n\n cli @argv,\n \"-R --rules\" => lambda{ @command = :list },\n \"-H --help\" => lambda{ @command = :help },\n \"-a --auto\" => method(:watch=),\n \"-f --fresh\" => method(:fresh!),\n \"-s --script\" => method(:script=),\n \"-D --debug\" => method(:debug!)\n end", "def scan\n remove_commented_out_lines\n\n do_classes_and_modules\n do_missing\n\n do_constants\n do_methods\n do_includes\n do_aliases\n do_attrs\n\n @store.add_c_variables self\n\n @top_level\n end", "def parse!\n begin\n parse\n rescue StandardError => e\n raise e if @options[:trace] || e.is_a?(SystemExit)\n $stderr.puts \"#{e.class}: \" + e.message.to_s\n exit 1\n end\n exit 0\n end", "def start(options={},&block)\n @stdout = options[:stdout] || $stdout\n @stderr = options[:stdout] || @stdout\n @stdin = options[:stdin] || $stdin\n while line = @stdin == $stdin ? Readline.readline(\"> \", true) : @stdin.gets \n line.strip!\n next if line.length==0\n parse_tree_node = parser.parse line\n if parse_tree_node\n evaluate parse_tree_node, &block\n else\n errputs parser.parser_failure_info :verbose => true\n end\n end\n end", "def run_scanner\n Bundler::Audit::Scanner.new.scan\n end", "def scan_for_all(token); end", "def scan_for_all(token); end", "def scan_for_all(token); end", "def analyse(string = nil)\n raise(ArgumentError, 'Lexer: failed to start analysis: no source given!') unless\n string || @scanner\n\n self.data = string || @scanner.string\n\n until @scanner.eos?\n send(\"parse_#{MODE[@mode]}\")\n end\n\n push([false, '$end'])\n end", "def start\n @cmd.parse\n end", "def parse(string = nil)\n if self.file =~ /\\.rb$/\n main = parse_ruby_file\n else\n self.string = string if string\n begin\n @yydebug = false\n main = yyparse(@lexer,:scan)\n rescue Racc::ParseError => except\n error = Puppet::ParseError.new(except)\n error.line = @lexer.line\n error.file = @lexer.file\n error.set_backtrace except.backtrace\n raise error\n rescue Puppet::ParseError => except\n except.line ||= @lexer.line\n except.file ||= @lexer.file\n raise except\n rescue Puppet::Error => except\n # and this is a framework error\n except.line ||= @lexer.line\n except.file ||= @lexer.file\n raise except\n rescue Puppet::DevError => except\n except.line ||= @lexer.line\n except.file ||= @lexer.file\n raise except\n rescue => except\n error = Puppet::DevError.new(except.message)\n error.line = @lexer.line\n error.file = @lexer.file\n error.set_backtrace except.backtrace\n raise error\n end\n end\n # Store the results as the top-level class.\n return Puppet::Parser::AST::Hostclass.new('', :code => main)\n ensure\n @lexer.clear\n end", "def scanner()\n raise NotImplementedError\n end", "def scan\n @top_level.comment ||= \"\"\n state=:code_blank\n line_number = 0\n line = nil\n\n # This started out as a really long nested case statement,\n # which also led to repetitive code. I'd like to avoid that\n # so I'm using a \"table\" instead.\n\n # Firstly we need some procs to do the transition and processing\n # work. Because these are procs they are closures, and they can\n # use variables in the local scope.\n #\n # First, the \"nothing to see here\" stuff.\n code_noop = lambda do\n if line =~ /^\\s+$/\n state = :code_blank\n end\n end\n\n pod_noop = lambda do\n if line =~ /^\\s+$/\n state = :pod_blank\n end\n @top_level.comment += filter(line)\n end\n\n begin_noop = lambda do\n if line =~ /^\\s+$/\n state = :begin_blank\n end\n @top_level.comment += filter(line)\n end\n\n # Now for the blocks that process code and comments...\n\n transit_to_pod = lambda do\n case line\n when /^=(?:pod|head\\d+)/\n state = :pod_no_blank\n @top_level.comment += filter(line)\n when /^=over/\n state = :over_no_blank\n @top_level.comment += filter(line)\n when /^=(?:begin|for)/\n state = :begin_no_blank\n end\n end\n\n process_pod = lambda do\n case line\n when /^\\s*$/ then\n state = :pod_blank\n @top_level.comment += filter(line)\n when /^=cut/ then\n state = :code_no_blank\n when /^=end/ then\n $stderr.puts \"'=end' unexpected at #{line_number} in #{@file_name}\"\n else\n @top_level.comment += filter(line)\n end\n end\n\n process_begin = lambda do\n case line\n when /^\\s*$/ then\n state = :begin_blank\n @top_level.comment += filter(line)\n when /^=end/ then\n state = :code_no_blank\n when /^=cut/\n $stderr.puts \"'=cut' unexpected at #{line_number} in #{@file_name}\"\n else\n @top_level.comment += filter(line)\n end\n end\n\n transitions = { :code_no_blank => code_noop,\n :code_blank => transit_to_pod,\n :pod_no_blank => pod_noop,\n :pod_blank => process_pod,\n :begin_no_blank => begin_noop,\n :begin_blank => process_begin,\n }\n\n @content.each_line do |l|\n line = l\n line_number += 1\n transitions[state].call\n end\n\n @top_level\n end", "def run\n\t\terror_free = true\n\t\tprogram = []\n\t\twhile @tokens.peak and @tokens.peak.type != \"EOF\" # Not EOF\n\t\t\tbegin\n\t\t\t\tprogram.append(parse_next)\n\t\t\trescue => e\n\t\t\t\tputs e.message\n\t\t\t\terror_free = false # Allows parsing full file to get as many errors as possible.\n\t\t\tend\n\t\tend\n\n\t\tif error_free\n\t\t\treturn Program.new(0,0, program)\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n if ss.check(/\\n/) then\n self.lineno += 1\n # line starts 1 position after the newline\n self.start_of_current_line_pos = ss.pos + 1\n end\n self.old_pos = ss.pos\n token =\n case state\n when nil, :option, :inner, :start, :macro, :rule, :group then\n case\n when ss.skip(/options?.*/) then\n [:state, :option]\n when ss.skip(/inner.*/) then\n [:state, :inner]\n when ss.skip(/macros?.*/) then\n [:state, :macro]\n when ss.skip(/rules?.*/) then\n [:state, :rule]\n when ss.skip(/start.*/) then\n [:state, :start]\n when ss.skip(/end/) then\n [:state, :END]\n when ss.skip(/\\A((?:.|\\n)*)class ([\\w:]+.*)/) then\n action { [:class, *matches] }\n when ss.skip(/\\n+/) then\n # do nothing\n when text = ss.scan(/\\s*(\\#.*)/) then\n action { [:comment, text] }\n when (state == :option) && (ss.skip(/\\s+/)) then\n # do nothing\n when (state == :option) && (text = ss.scan(/stub/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/debug/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/do_parse/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/lineno/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/column/i)) then\n action { [:option, text] }\n when (state == :inner) && (text = ss.scan(/.*/)) then\n action { [:inner, text] }\n when (state == :start) && (text = ss.scan(/.*/)) then\n action { [:start, text] }\n when (state == :macro) && (ss.skip(/\\s+(\\w+)\\s+#{RE}/o)) then\n action { [:macro, *matches] }\n when (state == :rule) && (ss.skip(/\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:rule, *matches] }\n when (state == :rule) && (ss.skip(/\\s*:[\\ \\t]*#{RE}/o)) then\n action { [:grouphead, *matches] }\n when (state == :group) && (ss.skip(/\\s*:[\\ \\t]*#{RE}/o)) then\n action { [:grouphead, *matches] }\n when (state == :group) && (ss.skip(/\\s*\\|\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:group, *matches] }\n when (state == :group) && (ss.skip(/\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:groupend, *matches] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :END then\n case\n when ss.skip(/\\n+/) then\n # do nothing\n when text = ss.scan(/.*/) then\n action { [:end, text] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def scan(code, lang, options = T.unsafe(nil), &block); end", "def usage\n puts \"usage: jstags.rb [-e] [-i] [-h] [-u] directory_name\"\n\n puts \"args :\\n\"\n puts \" -e exclude path(s) matching regex argument\\n\"\n puts \" -i include path(s) matching regex argument\\n\"\n puts \" -h output a standard set of ctags headers\\n\"\n puts \" -u produce this output; override other flags\\n\"\n puts \" directory_name - name of directory to scan\\n\"\n\n puts \"\\nOutput is written to stdout so you can redirect/filter as needed.\\n\"\n puts \"\\nSupported source code patterns for locating tag symbols include:\\n\"\n puts \" sym=function, sym=new Function, sym:function, and function sym().\\n\\n\"\n\n exit(0)\nend", "def parse(argv)\n rdoc_parse(argv)\n if %w{redfish twofish blackfish longfish onefish newfish}.include?(@template)\n require \"webri/generators/#{template}\"\n @generator = WebRI.const_get(@template.capitalize)\n end\n end", "def scan_rest; end", "def initialize parser\n @parser = parser\n end", "def scanner\n return @scanner if @scanner\n @scanner = Rink::Lexer.new\n @scanner.exception_on_syntax_error = false\n @scanner\n end", "def scan(pattern)\n do_scan pattern, true, true, true\n end", "def scanner\n @scanner\n end", "def command_parse(argv)\n end", "def parse!\n begin\n parse\n rescue Exception => e\n raise e if @options[:trace] || e.is_a?(SystemExit)\n\n $stderr.print \"#{e.class}: \" unless e.class == RuntimeError\n $stderr.puts \"#{e.message}\"\n exit 1\n end \n exit 0\n end", "def yyaccept; end", "def yyaccept; end", "def parser (tokens)\n\n\t# create the new, concrete syntax tree\n\t# making it global to reduce headaches (hopefully XD )\n\t$cst = ConcreteSyntaxTree.new\n\t\n\t# define some other useful, global vars\n\t$tokens = tokens\n\t$index = 0\n\t\n\t# have to ask alan about this\n\tif $tokens.length <= 1\n\t\tputs \"Insufficient code present! There is only #{$tokens.length} token here!\"\n\t\texit\n\tend\t\n\t\n\t\n\t# Engine to full burn!!!\n\t#parse(\"Program\", program)\n\tprogram\n\t\n\t\n\tbegin\n\t\tif $tokens.length != $index\n\t\t\traise EOFDetectionError.new(\"early\", $tokens[$index - 1].lineno, $tokens[$index - 1].pos)\n\t\tend\n\trescue EOFDetectionError\n\tend\n\t\t\n\t\n\t\n\treturn $cst\nend", "def program(tokens, types, i)\n @program = Prog.new()\n x = @program.ParseProg(tokens, types, i)\n @program.PrintProg\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when ss.skip(/\\s+/) then\n # do nothing\n when ss.skip(/:(#{SYMBOL_NAME})/o) then\n action { emit :tSYMBOL, &:to_sym }\n when ss.skip(/\"(.+?)\"/) then\n action { emit :tSTRING }\n when ss.skip(/[-+]?\\d+\\.\\d+/) then\n action { emit :tNUMBER, &:to_f }\n when ss.skip(/[-+]?\\d+/) then\n action { emit :tNUMBER, &:to_i }\n when ss.skip(/#{Regexp.union(\n %w\"( ) { | } [ ] < > $ ! ^ ` ... + * ? ,\"\n )}/o) then\n action { emit ss.matched, &:to_sym }\n when ss.skip(/#{REGEXP}/o) then\n action { emit_regexp }\n when ss.skip(/%?(#{CONST_NAME})/o) then\n action { emit :tPARAM_CONST }\n when ss.skip(/%([a-z_]+)/) then\n action { emit :tPARAM_NAMED }\n when ss.skip(/%(\\d*)/) then\n action { emit(:tPARAM_NUMBER) { |s| s.empty? ? 1 : s.to_i } } # Map `%` to `%1`\n when ss.skip(/_(#{IDENTIFIER})/o) then\n action { emit :tUNIFY }\n when ss.skip(/_/o) then\n action { emit :tWILDCARD }\n when ss.skip(/\\#(#{CALL})/o) then\n action { @state = :ARG; emit :tFUNCTION_CALL, &:to_sym }\n when ss.skip(/#{IDENTIFIER}\\?/o) then\n action { @state = :ARG; emit :tPREDICATE, &:to_sym }\n when ss.skip(/#{NODE_TYPE}/o) then\n action { emit :tNODE_TYPE, &:to_sym }\n when ss.skip(/\\#.*/) then\n action { emit_comment }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :ARG then\n case\n when ss.skip(/\\(/) then\n action { @state = nil; emit :tARG_LIST }\n when ss.skip(//) then\n action { @state = nil }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def parser\n @parser ||= (\n parser = ::OptionParser.new\n parser.on_tail('--quiet', 'Turn on $QUIET mode.') do\n $QUIET = true\n end\n parser.on_tail('--debug', 'Turn on $DEBUG mode.') do\n $DEBUG = true\n end\n parser.on_tail('-v', '--version', 'Display current version.') do\n puts \"Smeagol #{Smeagol::VERSION}\"\n exit 0\n end\n parser.on_tail('-h', '-?', '--help', 'Display this help screen.') do\n puts parser\n exit 0\n end\n parser\n )\n end", "def configure!(parser); end", "def parse; end", "def parse; end", "def parse; end", "def scan\n source.each.with_index do |line, index|\n loc_num = index + 1\n\n line_detection = AxR.app.layer_names.detect { |layer| line.include?(layer) }\n line_detection = check_space_before(line, line_detection)\n line_detection = nil if context && module_definition?(line, line_detection)\n line_detection = nil if commented?(line, line_detection)\n context_detection = AxR.app.layer_names.detect { |layer| module_definition?(line, layer) }\n\n next unless context_detection || line_detection\n\n detect_context(context_detection, line, loc_num) if context_detection && !context\n detect_dependency(line_detection, line, loc_num)\n detect_warning(line_detection, line, loc_num) if context && line_detection\n end\n\n self\n end", "def get_parse(s);end", "def parse\n IniParse::Generator.gen do |generator|\n @source.split(\"\\n\", -1).each do |line|\n generator.send(*Parser.parse_line(line))\n end\n end\n end", "def run!\n @opts = slop_parse\n @skip = @opts[:skip] || []\n\n display_version if @opts[:v]\n run_checks\n end", "def step\n case\n when bol? && check( /=begin/ )\n start_group( :comment, scan_until( /^=end#{EOL}/ ) )\n when bol? && check( /__END__#{EOL}/ )\n start_group( :comment, scan_until( /\\Z/ ) )\n else\n case\n when check( /def\\s+/ )\n start_group :keyword, scan( /def\\s+/ )\n start_group :method, scan_until( /(?=[;(\\s]|#{EOL})/ )\n when check( /class\\s+/ )\n start_group :keyword, scan( /class\\s+/ )\n start_group :class, scan_until( /(?=[;\\s<]|#{EOL})/ )\n when check( /module\\s+/ )\n start_group :keyword, scan( /module\\s+/ )\n start_group :module, scan_until( /(?=[;\\s]|#{EOL})/ )\n when check( /::/ )\n start_group :punct, scan(/::/)\n when check( /:\"/ )\n start_group :symbol, scan(/:/)\n scan_delimited_region :symbol, :symbol, \"\", true\n @allow_operator = true\n when check( /:'/ )\n start_group :symbol, scan(/:/)\n scan_delimited_region :symbol, :symbol, \"\", false\n @allow_operator = true\n when scan( /:[_a-zA-Z@$][$@\\w]*[=!?]?/ )\n start_group :symbol, matched\n @allow_operator = true\n when scan( /\\?(\\\\[^\\n\\r]|[^\\\\\\n\\r\\s])/ )\n start_group :char, matched\n @allow_operator = true\n when check( /(__FILE__|__LINE__|true|false|nil|self)[?!]?/ )\n if @selector || matched[-1] == ?? || matched[-1] == ?!\n start_group :ident,\n scan(/(__FILE__|__LINE__|true|false|nil|self)[?!]?/)\n else\n start_group :constant,\n scan(/(__FILE__|__LINE__|true|false|nil|self)/)\n end\n @selector = false\n @allow_operator = true\n when scan(/0([bB][01]+|[oO][0-7]+|[dD][0-9]+|[xX][0-9a-fA-F]+)/)\n start_group :number, matched\n @allow_operator = true\n else\n case peek(2)\n when \"%r\"\n scan_delimited_region :punct, :regex, scan( /../ ), true\n @allow_operator = true\n when \"%w\", \"%q\"\n scan_delimited_region :punct, :string, scan( /../ ), false\n @allow_operator = true\n when \"%s\"\n scan_delimited_region :punct, :symbol, scan( /../ ), false\n @allow_operator = true\n when \"%W\", \"%Q\", \"%x\"\n scan_delimited_region :punct, :string, scan( /../ ), true\n @allow_operator = true\n when /%[^\\sa-zA-Z0-9]/\n scan_delimited_region :punct, :string, scan( /./ ), true\n @allow_operator = true\n when \"<<\"\n saw_word = ( chunk[-1,1] =~ /[\\w!?]/ )\n start_group :punct, scan( /<</ )\n if saw_word\n @allow_operator = false\n return\n end\n\n float_right = scan( /-/ )\n append \"-\" if float_right\n if ( type = scan( /['\"]/ ) )\n append type\n delim = scan_until( /(?=#{type})/ )\n if delim.nil?\n append scan_until( /\\Z/ )\n return\n end\n else\n delim = scan( /\\w+/ ) or return\n end\n start_group :constant, delim\n start_group :punct, scan( /#{type}/ ) if type\n @heredocs << [ float_right, type, delim ]\n @allow_operator = true\n else\n case peek(1)\n when /[\\n\\r]/\n unless @heredocs.empty?\n scan_heredoc(*@heredocs.shift)\n else\n start_group :normal, scan( /\\s+/ )\n end\n @allow_operator = false\n when /\\s/\n start_group :normal, scan( /\\s+/ )\n when \"#\"\n start_group :comment, scan( /#[^\\n\\r]*/ )\n when /[A-Z]/\n start_group @selector ? :ident : :constant, scan( /\\w+/ )\n @allow_operator = true\n when /[a-z_]/\n word = scan( /\\w+[?!]?/ )\n if !@selector && KEYWORDS.include?( word )\n start_group :keyword, word\n @allow_operator = false\n elsif\n start_group :ident, word\n @allow_operator = true\n end\n @selector = false\n when /\\d/\n start_group :number,\n scan( /[\\d_]+(\\.[\\d_]+)?([eE][\\d_]+)?/ )\n @allow_operator = true\n when '\"'\n scan_delimited_region :punct, :string, \"\", true\n @allow_operator = true\n when '/'\n if @allow_operator\n start_group :punct, scan(%r{/})\n @allow_operator = false\n else\n scan_delimited_region :punct, :regex, \"\", true\n @allow_operator = true\n end\n when \"'\"\n scan_delimited_region :punct, :string, \"\", false\n @allow_operator = true\n when \".\"\n dots = scan( /\\.{1,3}/ )\n start_group :punct, dots\n @selector = ( dots.length == 1 )\n when /[@]/\n start_group :attribute, scan( /@{1,2}\\w*/ )\n @allow_operator = true\n when /[$]/\n start_group :global, scan(/\\$/)\n start_group :global, scan( /\\w+|./ ) if check(/./)\n @allow_operator = true\n when /[-!?*\\/+=<>(\\[\\{}:;,&|%]/\n start_group :punct, scan(/./)\n @allow_operator = false\n when /[)\\]]/\n start_group :punct, scan(/./)\n @allow_operator = true\n else\n # all else just falls through this, to prevent\n # infinite loops...\n append getch\n end\n end\n end\n end\n end", "def scan_tokens(encoder, options); end", "def scan_tokens(encoder, options); end", "def scanner\n @scanner ||= CodeRay.scanner(lang, options, &block)\n end", "def scan(html)\n @parser = HtmlParser.new\n @parser.scan html.strip, Builder.new(@output, self.tab_stops)\n end", "def parse str\n self.ss = scanner_class.new str\n self.lineno = 1\n self.start_of_current_line_pos = 0\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.lineno = 1\n self.start_of_current_line_pos = 0\n self.state ||= nil\n\n do_parse\n end", "def parse_input(input_file); end", "def parse_input(input_file); end", "def call(*args)\n puts parser.help\n exit 1\n end", "def parse(argv=ARGV, options={}) # :yields: parser\n parse!(argv.dup, options)\n end", "def parse!\n begin\n parse\n rescue Exception => e\n raise e if @options[:tron] || e.is_a?(SystemExit) || true\n\n $stderr.print \"#{e.class}: \" unless e.class == RuntimeError\n $stderr.puts \"#{e.message}\"\n $stderr.puts \" Use --tron for stacktrace.\"\n exit 1\n end\n exit 0\n end", "def parserDidStartDocument(parser)\n puts \"starting parsing..\"\n end" ]
[ "0.66263777", "0.6449215", "0.6449215", "0.6449215", "0.6449215", "0.6363091", "0.63622653", "0.63622653", "0.63622653", "0.63622653", "0.63011444", "0.62813514", "0.6229778", "0.6229778", "0.61380994", "0.6133653", "0.61229753", "0.60990256", "0.6063994", "0.60474896", "0.6045595", "0.6014471", "0.59187037", "0.5913287", "0.5890321", "0.5867082", "0.5850999", "0.5837926", "0.5827392", "0.5814153", "0.5788266", "0.5779587", "0.57584774", "0.57351553", "0.57338995", "0.569885", "0.5697182", "0.5670651", "0.5661369", "0.56435126", "0.56435126", "0.56435126", "0.56435126", "0.5643226", "0.56025624", "0.5601076", "0.5593565", "0.5572617", "0.5562979", "0.55589676", "0.55579793", "0.55507374", "0.5542433", "0.5534578", "0.55183953", "0.55183953", "0.55183953", "0.5515543", "0.55113584", "0.55105793", "0.55074227", "0.55069333", "0.5506082", "0.54999065", "0.54961133", "0.5492933", "0.54723585", "0.54720306", "0.54703915", "0.54664594", "0.54632527", "0.54517174", "0.54395306", "0.5430432", "0.5415886", "0.5415886", "0.5412704", "0.5409997", "0.54022175", "0.5399854", "0.53984064", "0.5394939", "0.5394939", "0.5394939", "0.5393554", "0.5389671", "0.53888476", "0.5371723", "0.53703433", "0.53619874", "0.53619874", "0.53324395", "0.53307134", "0.53292155", "0.53292155", "0.53205055", "0.53205055", "0.53115577", "0.53001803", "0.529778", "0.52956134" ]
0.0
-1
Ensure deleted users cannot sign in def active_for_authentication? super && !deleted_at end Used for user authentication
def ensure_authentication_token (remember) token = AuthToken.create!(token: generate_authentication_token, remember: remember, user_id: self.id) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted_at\n end", "def active_for_authentication? \n super && !deleted_at\n end", "def active_for_authentication?\n super && !deleted?\n end", "def active_for_authentication?\n super && !deleted?\n end", "def active_for_authentication?\n super && !deleted?\n end", "def active_for_authentication?\n super and not self.deleted?\n end", "def active_for_authentication? \n super && !deleted_at \n end", "def active_for_authentication? \n super && !deleted_at \n end", "def active_for_authentication? \n super && !is_deleted \n end", "def active_for_authentication?\n\t\tsuper && !deleted_at\n\tend", "def active_for_authentication?\n super && !delete_flag\n end", "def active_for_authentication?\n super && !delete_flag?\n end", "def active_for_authentication?\n \tsuper && !delete_flag\n end", "def active_for_authentication?\n super && !deleted_at && self.enabled?\n end", "def active_for_authentication? \n raise ErrorHandling::Errors::User::DeletedUser.new(deleted_at: deleted_at) if deleted_at? \n return true\n end", "def active_for_authentication?\n super && !deleted? && approved?\n end", "def active_for_authentication?\n super && !deleted? && approved?\n end", "def active_for_authentication?\n super && !deactivated_at\n end", "def active_for_authentication?\n super && !deactivated_at\n end", "def active_for_authentication?\n super && !deactivated_at\n end", "def authorized_for_delete?\n return !self.is_default?\n end", "def user_can_delete?\n false\n end", "def active_for_authentication?\n !deactivated? && super\n end", "def active_for_authentication?\n super && !expired?\n end", "def active_for_authentication?\n super && !disabled_at\n end", "def owner_deleted?\n !!User.with_deleted.find_by_id(user_id).try(:deleted?)\n end", "def active_for_authentication?\n super && !suspended_account\n end", "def active_for_authentication?\n super && !self.deactivated # i.e. super && self.is_active\n end", "def active_for_authentication?\n super and self.locked != 1\n end", "def active_for_authentication?\n super && !self.deactivated_staff?\n end", "def active_for_authentication?\n super && active\n end", "def active_for_authentication? \n super && approved? \n end", "def is_safe_deleted?\n return !self.deleted_at.nil?\n end", "def active_for_authentication?\n super\n end", "def before_destory\n if User.count(:all, :conditions => [\"is_superuser = 1 and active = 1\"]) <= 1\n errors.add_to_base \"Cannot delete #{self.username.upcase} because it is the last admin user\"\n return false\n else\n return true\n end\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && approved?\n end", "def active_for_authentication?\n super && active?\n end", "def active_for_authentication?\n super && active?\n end", "def active_for_authentication?\n super && active?\n end", "def authorized_for_destroy?\n current_user.es_admin?\n end", "def can_delete?(current_user)\n raise \"current_user == nil\" if current_user.nil?\n raise \"user == nil\" if user.nil?\n\n user.id == current_user.id && !current_user.anonymous?\n end", "def before_destroy\n if public?\n errors.add_to_base _('Public user cannot be deleted.')\n end\n if last_admin?\n errors.add_to_base _(\"Cannot delete. User '{{username}}' is the last available admin.\", :username => username)\n end\n if current?\n errors.add_to_base _('You cannot delete your own account.')\n end\n errors.empty?\n end", "def active_for_authentication?\n super && !disabled\n end", "def active_for_authentication?\n super && !disabled?\n end", "def active_for_authentication?\n super && isActive\n end", "def authorized_for_destroy?\n return false unless current_user && current_user.is_admin_type?\n end", "def active_for_authentication?\n super && account_active?\n end", "def active_for_authentication?\n super && !access_locked?\n end", "def active_for_authentication? \n super && (approved? || self.admin) \n end", "def active_for_authentication?\n super and !self.disabled?\n end", "def active_for_authentication?\n super && is_active?\n end", "def active_for_authentication?\n super && !banned\n end", "def active_for_authentication?\n super && assigned?\n end", "def active_for_authentication?\n super && !banned?\n end", "def active_for_authentication?\n super && bloqueado == 0\n end", "def active_for_authentication?\n active? && super\n end", "def active_for_authentication?\r\n super && active_status?\r\n end", "def can_delete?(user)\n self.user_id == user.id || user.admin?\n end", "def active_for_authentication?\n super && self.is_active?\n end", "def active_for_authentication? \n super && is_approved? \n end", "def active_for_authentication?\n super && self.approved?\n end", "def active_for_authentication? \n \tsuper && approved?\n \t\n\tend", "def active_for_authentication?\n super && !disabled?\n end", "def active_for_authentication?\n super && un_blocked?\n end", "def active_for_authentication?\n super && self.active? # i.e. super && self.active\n end", "def active_for_authentication?\n super && !self.blocked\n end", "def active_for_authentication?\n super && !self.blocked\n end", "def active_for_authentication?\n super && !self.is_disabled\n end", "def active_for_authentication?\n super && (!confirmation_required? || confirmed? || confirmation_period_valid?)\n end", "def active_for_authentication? \n super && (self.is_disabled == 0)\n end", "def active_for_authentication?\n super && activation_status == true\nend", "def before_destroy\r\n errors.add(:base, I18n.t(\"activerecord.errors.models.user.self_delete\")) if current_user_id == self.id\r\n errors.add(:base, I18n.t(\"activerecord.errors.models.user.delete\")) if User.count == 1\r\n errors.blank?\r\n end", "def before_destroy\n return false if super == false\n\n if admins = User.filter(:admin => true) and admins.count == 1 and admins.first.id == self.id\n self.errors.add nil, \"Can't destroy the only administrator.\"\n return false\n end\n end", "def active_for_authentication?\n super and !self.is_archived? #determine \"active\" state using our own \"is_archived\" column\n end", "def not_active_on_create!\n self.deleted_at ||= Time.zone.now\n end" ]
[ "0.89555746", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.894714", "0.8938769", "0.8898861", "0.8873535", "0.8873535", "0.8873535", "0.8850816", "0.88441473", "0.88441473", "0.8783095", "0.87640715", "0.84497315", "0.8435981", "0.832439", "0.82306296", "0.82106036", "0.81903875", "0.81903875", "0.7601445", "0.7601445", "0.7601445", "0.7436608", "0.72857046", "0.7234782", "0.7147992", "0.7072358", "0.70380634", "0.6978188", "0.6968296", "0.6892869", "0.68749744", "0.6865258", "0.68507904", "0.683852", "0.6815437", "0.6814662", "0.681171", "0.6804803", "0.6804803", "0.6804803", "0.6804803", "0.6804803", "0.6804803", "0.6804803", "0.67976964", "0.67976964", "0.67976964", "0.6769201", "0.6752162", "0.67411536", "0.67364365", "0.67329675", "0.6723829", "0.6710037", "0.6706211", "0.66667295", "0.6665829", "0.6656462", "0.6655146", "0.6643282", "0.6639461", "0.6638067", "0.6637297", "0.6634338", "0.66288203", "0.6615737", "0.6610324", "0.660702", "0.6598402", "0.6595536", "0.65954125", "0.6593354", "0.6591273", "0.6565936", "0.6565936", "0.6564706", "0.65617216", "0.6543548", "0.64815074", "0.64733875", "0.6473046", "0.64497113", "0.6422751" ]
0.0
-1
Difficulty: medium/hard Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array. You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2. The array will always contain letters in only one case. Example: missing_letter(['a','b','c','d','f']) > 'e' missing_letter(['O','Q','R','S']) > 'P' Included test uses rspec 22 May 2019
def missing_letter2(word) alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" for letter in alphabet.split("") if letter == word[0] start = alphabet.index(letter) break end end for letter in word if letter != alphabet[start] return alphabet[start] else start +=1 end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_missing_letter(arr)\n alphabets = (arr[0]..arr[-1]).to_a # [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n \n (alphabets - arr)[0] # \"e\"\nend", "def determine_missing_letter(arr)\n alpha = ('A'..'z').to_a\n current_index = alpha.index(arr.first)\n arr.each_with_index do |char, index|\n next if index == 0\n if alpha.index(char) != current_index + 1\n return alpha[current_index + 1]\n end\n current_index += 1\n end\nend", "def find_missing_letter(arr)\n((arr.first..arr.last).to_a - arr).first\nend", "def find_missing_letter(arr)\n ((arr.first..arr.last).to_a - arr).first\nend", "def find_missing_letter(arr)\n missing_letter = ''\n (arr[0]...arr[-1]).each do |x|\n if !arr.include?(x)\n print x\n end\n end\n\nend", "def find_missing_letter(range)\n array_1 = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n start_index = array_1.index(range[0]) \n\n range.split(//).each do |letter|\n if letter == array_1[start_index]\n start_index += 1\n else\n return array_1[start_index] \n end\n end\n nil\nend", "def find_missing_letter(string)\n string = string.split(\"\")\n f_letter = string.first\n l_letter = string.last\n all_letters = f_letter.upto(l_letter).to_a\n missing = all_letters - string \n if missing == []\n return nil\n else\n return missing\n end \nend", "def find_missing_letter(arr)\n ((arr.first..arr.last).to_a - arr).first\n\n # or...\n # letters = (arr.first..arr.last).to_a\n # return (letters - arr).first\nend", "def find_missing_letter(range)\n start_index = 0\n reference = \"abcdefghijklmnopqrstuvwxyz\".split(\"\")\n sorted_range = range.split(\"\").sort\n missing_letters = []\n\n reference.each_with_index do |letter, index|\n if sorted_range[0] == letter\n start_index = index\n end\n end\n\n sorted_range.each do |letter|\n unless letter == reference[start_index]\n missing_letters << reference[start_index]\n start_index+=1 #If a letter is missing, need to add twice to skip over to the next one\n end\n start_index+=1\n end\n\n if missing_letters.any?\n return missing_letters.join(\"\")\n else\n return nil\n end\n\nend", "def find_missing_letter(arr)\n arr.each_with_index { |ltr, i| return ltr.next unless ltr.next == arr[i + 1] }\nend", "def find_missing_letter(range)\n missing_letters = []\n user_input = range.split('')\n alphabet = user_input[0].upto(user_input.last).to_a\n\n alphabet.each do |letter|\n missing_letters << letter unless user_input.include? letter\n # missing_letters << letter\n # end\n end\n\n # if missing_letters.empty?\n # return nil\n # else\n # missing_letters.join\n # end\n\n missing_letters.join if missing_letters.empty?\nend", "def find_missing_letter(arr)\n ([*arr.first..arr.last] - arr).first\nend", "def find_missing_letter(range)\n letters = range.split(\"\")\n full_letters = (letters[0]..letters[-1]).to_a\n full_letters.each do |letter|\n if letters.include?(letter) \n\n elsif not letters.include?(letter)\n return letter\n end\n if letters == full_letters\n return nil\n end\n end\n \n \n\nend", "def find_missing_letter(arr)\n lower_case_alphabet = (\"a\"..\"z\").to_a\n upper_case_alphabet = (\"A\"..\"Z\").to_a\n\n if lower_case_alphabet.include?(arr.first)\n min = lower_case_alphabet.index(arr.first)\n max = lower_case_alphabet.index(arr.last)\n lower_case_alphabet[min..max].select { |letter| !arr.include?(letter) }.first\n else\n min = upper_case_alphabet.index(arr.first)\n max = upper_case_alphabet.index(arr.last)\n upper_case_alphabet[min..max].select { |letter| !arr.include?(letter) }.first\n end\nend", "def missing_letter(word)\n word.each_with_index do |letter, i|\n return letter.next if word[i + 1] != letter.next\n end\nend", "def find_missing_letter(range)\n # result = []\n # prev_char = \"\"\n # array = range.split(\"\")\n\n # array.each do |char|\n # if prev_char.next != char\n # result << prev_char.next\n # end\n # prev_char = char\n # end\n # result\n\n first_letter = range[0]\n last_letter = range[-1]\n\n test_range = (first_letter..last_letter).to_a\n result = \"\"\n\n test_range.each do |letter|\n result += letter unless range.include?(letter)\n end\n \n result != \"\" ? result : nil \nend", "def find_missing_letter(string)\n if string.empty?\n missing_letters = (\"a\"..\"z\").to_a\n else\n alphabet = (\"a\"..\"z\").to_a\n missing_letters = alphabet[alphabet.index(string.split(\"\").first)..alphabet.index(string.split(\"\").last)]- string.split(\"\")\n end\n missing_letters.empty? ? nil : missing_letters.join\nend", "def find_missing_letter(range)\n numbers = []\n\n range.each_byte do |number|\n numbers << number\n end\n\n starting_point = numbers[0]\n ending_point = numbers.last\n\n new_array = []\n\n range_length = range.length\n\n range_length.times do\n new_array << starting_point.next\n starting_point += 1\n end\n\n missing_letter = \"\"\n counter = 0\n range_length.times do\n if new_array[counter] == numbers[counter + 1]\n counter += 1\n else\n missing_letter = new_array[counter]\n end\n end\n\n if missing_letter < ending_point\n return missing_letter.chr\n else\n return nil\n end\nend", "def missing_letters(string)\n missing = []\n ('a'..'z').each do |letter|\n if !string.include?(letter)\n missing << letter\n end\n end\n missing\nend", "def missing_letters(string)\n alphabet = (\"a\"..\"z\").to_a\n alphabet.reject { |x| string.downcase.include?(x) }\nend", "def find_missing_letter(range)\n results = []\n range.chars.each_slice(2) do |a, b|\n next if b.nil?\n results << a.next unless a.next == b\n end\n\n return nil if results.empty?\n results\nend", "def find_missing_letter(range)\nsplit_range = []\nsplit_range = range.split(//)\narray = []\n\nrange_two = (split_range[0]..split_range[-1]).to_a\narray << range_two - split_range\n\n if array.length > 0\n p array.join\n else\n p nil\n end\nend", "def missing_letters(string)\n a_to_z_array = (\"a\"..\"z\").to_a\n a_to_z_array - string.chars\n\nend", "def missing_letters\n missing = Array.new\n ('a'..'z').each {|l| missing << l if @hist[l] == 0}\n missing\n end", "def missing_letters(string)\n missing_letters = []\n str = string.downcase\n ('a'..'z').each do |c|\n missing_letters << c if !str.include?(c)\n end\n missing_letters\nend", "def missing_letters(string)\n ('a'..'z').to_a.reject { |letter| string.include?(letter) }\nend", "def missing_letters(string)\n alphabet='a'..'z'\n alphabet.reject {|el|string.downcase.include?(el)}\nend", "def missing_letters(string)\n return ('a'..'z').to_a.select {|e| !string.include?(e)}\nend", "def missing_letters(string)\n string = string.downcase\n (\"a\"..\"z\").to_a.reject {|letter| string.include?(letter) }\nend", "def find_missing_letter(arr)\n #your code here\n result = 0\n base_arr = arr.join().codepoints\n base_arr.each_with_index do |item,index|\n if base_arr[index+1] != item + 1\n result = item + 1\n break\n end\n end\n result.chr\nend", "def missing_letters(string)\n letters = ('a'..'z').to_a\n letters.reject { |char| string.downcase.include?(char) }\nend", "def missing_letter(word)\n # your code goes here\n alpha = ('a'..'z').to_a\n index = alpha.index word.first.downcase\n word.each do |letter|\n if letter.downcase != alpha[index]\n alpha[index] < letter ? (return alpha[index]) : (return alpha[index].upcase)\n end\n index +=1\n end\n\nend", "def missing_letters(string)\n output = []\n\n ('a'..'z').each do |el|\n if !string.include?(el) \n output << el\n end\n end\n output\nend", "def missing_letters(string)\n ('a'..'z').reject { |letter| string.downcase.include? letter }\nend", "def missing_letters(string)\n letters = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z]\n letters.select { |c| c unless string.include?(c) }\nend", "def missing_letters(string)\n ('a'..'z').reject {|letter| string.include?(letter)}\nend", "def missing_letters(string)\n\n result = []\n\n (\"a\"..\"z\").each do |ch|\n result << ch if string.downcase.include?(ch) == false\n\n end\n result\nend", "def missingChars(str)\n\t\n\t# A boolean array to store characters\n\t# present in string.\t\n\n alfabeto = 'abcdefghijklmnopqrstuvxyz' \n arr = alfabeto.split('');\n\n arrstr = str.split('');\n arrmissing = [] \n \n \n\t# Traverse string and mark characters\n\t# present in string.\n\tfor i in 0..arr.length() - 1 do\n if (arrstr.include?(arr[i].downcase) == false) and (arrstr.include?(arr[i].upcase) == false)\n arrmissing.push(arr[i].downcase) \n end \n end \n \n return arrmissing.join();\n\n \n\n\t# Store missing characters in alphabetic\n\t# order.\n\t\nend", "def missing_from_letters\n word.chars.uniq.inject(\"\") do |memo, l|\n difference = word.count(l) - letters.count(l)\n if difference > 0\n memo += l * difference\n end\n memo\n end\n end", "def missing_letters(string)\nend", "def missing_letters(phrase)\n counts = Hash.new(0)\n phrase.chars.each do |character|\n counts[character] += 1\n end\n missing = []\n ('a'..'z').each do |letter|\n missing << letter if counts[letter] == 0\n end\n missing\nend", "def test_12_add_wrong_letter_to_wrong_count_array\r\n $wrong_count = [\"z\", \"x\", \"w\", \"q\", \"d\", \"f\", \"k\", \"m\"]\r\n letter = \"u\"\r\n results = wrong_letter(letter)\r\n assert_equal([\"z\", \"x\", \"w\", \"q\", \"d\", \"f\", \"k\", \"m\", \"u\"], $wrong_count)\r\n end", "def missing(arr)\n (arr[0]..arr[-1]).select { |num| !arr.include?(num) }\nend", "def unmatch_letter(word_array, letter, unmatch_array)\n\n word_array.length.times do |i|\n if word_array[i] == letter\n return 1\n end\n end\n\n return letter\nend", "def missing(arr)\n missing_integers = []\n counter = arr.first + 1\n counter.upto(arr.last - 1) do |c|\n missing_integers << c unless arr.include?(c)\n end\n missing_integers\nend", "def missing(array)\n result = []\n (array.first).upto(array.last) do |num|\n result << num if !array.include?(num)\n end\n result\nend", "def first_non_repeating_letter(string)\n letter_group = letters.split('').group_by{ |x| x.downcase }\n uniqs = letter_group.reject{ |letter, arr| arr.count > 1 }.keys\n for x in 0..uniqs.length\n\n end\n\n\n\n # letters = string.split('')\n # letter_group = letters.group_by{ |x| x.downcase }\n # p letter_group\n # uniqs = letter_group.reject{ |letter, arr| arr.count > 1 }.keys\n # p uniqs\n # '' + uniqs[0].to_s\nend", "def find_missing_number(sequence)\n p '--- Jan-05-2017 problem -----'\n # non-numeric characters will be 0\n seq = sequence.split.map(&:to_i).sort\n p seq\n # Assigin the starting index at 1\n # will return 1 if it contains 0 (non-numerics)\n seq.each.with_index(1) do |e, i|\n p \"index is #{i} and e is #{e}\"\n return i unless e == i\n end\n # return 0 if it all passes\n 0\nend", "def missing(arr)\n starting_num = arr[0]\n ending_num = arr[-1]\n complete_arr = []\n\n (ending_num - starting_num + 1).times do\n complete_arr << starting_num\n starting_num += 1\n end\n\n complete_arr - arr\nend", "def uses_available_letters?(input, letters_in_hand)\n\n input_array = input.upcase.chars\n\n letters_in_hand.each do |letter|\n\n if input_array.include? letter\n index = input_array.index(letter)\n input_array.delete_at(index)\n end\n end\n\n return input_array.length == 0\n\nend", "def missing(array)\n result = []\n num = array.first + 1\n loop do\n result << num if !array.include?(num)\n num += 1\n break if num == array.last\n end\n result\nend", "def missing(arr)\n (arr[0]..arr[-1]).to_a - arr\nend", "def check_duplicate_letter(words)\n # The reject method return a new Array without the items defined by its input block.\n return words.reject {\n # The word has each letter counted .chars .count\n # If the word with any repeating characters removed is not the same as the length of the word\n # The uniq method returns a new array by removing duplicate values in self.\n |word| word.chars.uniq.count != word.length\n }\n end", "def check_guessed_letter(word,letter,available_letters)\n\n\tif word.include?(letter)\n\t\treturn 0\n\telsif !available_letters.include?(letter)\n\t\treturn 0\n\telse\n\t\t$missed_letters.push(letter)\n\t\treturn -1\n\tend\nend", "def missing(array)\n range = (array[0]..array[-1]).to_a\n\n range.select do |num|\n !array.include?(num)\n end\nend", "def non_unique_letters(string)\n string.chars.reduce([]) do |array,letter|\n if string.count(letter) > 1 && array.include?(letter) == false && letter != \" \"\n array << letter\n else\n array\n end\n end\nend", "def missing(array)\n result = []\n array.each_cons(2) do |first, second|\n result.concat(((first + 1)..(second - 1)).to_a)\n end\n result\nend", "def missing(array)\n result = []\n array.each_cons(2) do |first, second|\n result.concat(((first + 1)..(second - 1)).to_a)\n end\n result\nend", "def non_unique_letters(string)\n alpha = ('a'..'z').to_a\n our_new_letters = []\n counters = Hash.new(0)\n arr = string.downcase.split(\"\").select {|letter| string.count(letter) > 1}\n arr.each do |c|\n counters[c] += 1\n our_new_letters << c if counters[c] <= 1\n end\n our_new_letters.select {|x| alpha.include?(x)}\nend", "def missing(array)\n result = []\n array.each_cons(2) do |first, second| \n result.concat(((first + 1)..(second - 1)).to_a)\n end\n result\nend", "def missing(arr)\n missing = []\n\n (arr.min + 1).upto(arr.max - 1) do |el|\n next if arr.include?(el)\n missing << el\n end\n\n missing\nend", "def uses_available_letters?(input, letters_in_hand)\n input = input.split('')\n letters_in_hand.reject do |letter|\n if input.include?(letter)\n input.slice!(input.index(letter))\n end\n end\n # the length of the input checks that the user used only available letters\n if input.length == 0\n return true\n else\n return false\n end\nend", "def first_non_repeating_letter(s)\n letters = s.downcase.split('')\n\n letters&.each_with_index do |l,i|\n return s[i] if letters.count(l) == 1\n end\n ''\nend", "def find_missing(arr)\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - arr.uniq.sort\nend", "def find_letters str\n arr = str.split('')\n count = 0\n arr2 = []\n for i in arr\n if (arr.count(i) <= 1)\n arr2.push(i)\n end\n end\n arr2\nend", "def test_4_verify_number_not_added_to_bucket_array_if_already_present\r\n $bucket = [\"b\"]\r\n letter = \"b\"\r\n results = good_letter(letter)\r\n assert_equal([\"b\"], $bucket)\r\n end", "def non_unique_letters(string)\n letters = string.chars.uniq\n letters.select {|letter| string.count(letter) > 1 }\nend", "def missing(numbers)\n missed = []\n numbers.first.upto(numbers.last) do |num|\n missed << num unless numbers.include?(num)\n end\n missed\nend", "def non_unique_letters(string)\n\n result = [] # empty accumulator\n\n string.split(\"\").uniq.each do |uni| # finding character present in the string\n each_char = 0\n\n string.split(\"\").each do |ltr| # iterating array of string\n each_char += 1 if ltr == uni\n end\n result << uni if each_char > 1\n end\n\n result\nend", "def getletters(string)\n arr = []\n pos = 0\n i = 0\n x = string.length\n while i < x\n if arr.include?(string[i])\n i += 1\n elsif !arr.include?(string[i])\n arr[pos] = string[i]\n i += 1\n pos += 1\n end\n end\n return arr\nend", "def first_non_repeating_letter(str)\n non_repeats = str.chars.reject do |chr|\n str.downcase.count(chr.downcase) > 1\n end\n non_repeats.empty? ? \"\" : non_repeats.first\nend", "def NonrepeatingCharacter(str)\n str.chars.each_with_index do |char,idx|\n after = idx + 1\n return char unless str.chars[after..str.length - 1].include?(char)\n end\nend", "def missing(ordered)\n first_index = 0\n missings = []\n while first_index < ordered.size - 1\n second_index = first_index + 1\n\n first_missing = ordered[first_index] + 1\n\n until first_missing == ordered[second_index]\n missings << first_missing\n\n first_missing += 1\n end\n\n first_index += 1\n end\n missings\nend", "def missing1(array)\n (array.first..array.last).to_a - array\nend", "def non_unique_letters(string)\n uniq_letters = string.chars.uniq\n uniq_letters.select { |ch| string.count(ch) > 1 }\nend", "def missing(numbers)\n (numbers.first..numbers.last).to_a.select do |current_number|\n !numbers.include?(current_number)\n end\nend", "def non_unique_letters(string)\n character=string.chars.uniq\n character.delete(\" \")\n character.select {|char| string.count(char)>1}\nend", "def missing(array)\n full_array_set = (array.first..array.last).to_a\n missing_numbers = []\n full_array_set.each do |number|\n if array.include?(number)\n next\n else\n missing_numbers << number\n end\n end\n missing_numbers\nend", "def non_unique_letters(string)\n new_arr = string.chars.select {|c| string.chars.count(c) > 1 }\n new_arr.delete(' ')\n new_arr.uniq!\n new_arr.sort!\n return new_arr\nend", "def guess_letter\n @unused_letters.pop\n end", "def non_unique_letters(string)\n arr = string.split.join.split('')\n arr.select { |c| c if arr.count(c) > 1 }.uniq.sort\nend", "def next_unused_letter sol\n\n\tx = 'a'.ord\n\n\tfor i in 0...sol.size\n\t\tfor j in 0...sol[0].size\n\t\t\tif sol[i][j].ord > x\n\t\t\t\tx = sol[i][j].ord\n\t\t\tend\n\t\tend\n\tend\n\n\treturn (x + 1).chr\nend", "def missing_numbers(input)\n input.sort!\n p (input[0]..input[-1]).to_a - input\nend", "def first_non_repeating_letter(str)\n return '' if str.empty? || str.chars.uniq.size <= str.size/2\n str.chars.each { |e| return e if str.downcase.count(e.downcase) == 1 }\nend", "def find_first_non_repeated_letter(str)\n flag = 0 #flag used to test for same character\n i = 0 #counter\n a = str.length #length of string for loop\n while i < a do \n\n if str[i] == str[i + 1] #compares character and next character\n flag = 1 #if match set flag\n elsif flag == 0 #check to see if flag has been set \n return str[i] #if flag not set return character\n else\n if i == str.length - 1 #check to see if reached end of string\n return nil #return nil\n end\n flag = 0 #no match at this point set flag to 0\n end\n i += 1 #advance counter\n end\nend", "def non_unique_letters(string)\nend", "def test_6_verify_number_not_added_to_bucket_array\r\n $bucket = []\r\n letter = \"7\"\r\n results = good_letter(letter)\r\n assert_equal([], $bucket)\r\n end", "def first_non_repeating_letter(str)\n str.chars.each { |char| return char if str.downcase.count(char.downcase) == 1 }\n ''\nend", "def find_missing_number(sequence)\r\n return 0 if sequence.empty?\r\n return 1 if /[a-z]/.match(sequence)\r\n \r\n ary = sequence.split.map!(&:to_i).sort\r\n return 1 if ary.first != 1\r\n \r\n \r\n ary.each_with_index do |num, index|\r\n if ary[index+1] != num + 1 && index != ary.length-1\r\n return num + 1\r\n end\r\n end\r\n 0\r\nend", "def uses_available_letters? (input, drawn_letters)\n is_valid = \"default\"\n word_letters = make_word_array(input)\n word_letters.each do |letter|\n if drawn_letters.include?letter\n is_valid = true\n puts \"letter valid \" + \"#{is_valid}\"\n letter_index = drawn_letters.index(letter)\n drawn_letters.delete_at(letter_index)\n else\n is_valid = false\n puts \"letter not valid \" + \"#{is_valid}\"\n return is_valid\n end\n end\n return is_valid\nend", "def first_non_repeating_letter(s) \n chars = []\n s.split(//).each do |character|\n if chars.include?(character) || chars.include?(character.downcase) || chars.include?(character.upcase)\n chars.delete(character)\n else\n chars << character \n end\n end\n # return chars[0] \n chars.empty? ? \"\" : chars[0]\nend", "def same_letter(arr)\n new_str = arr.shift\n\n loop do\n if arr[0] == new_str[-1]\n new_str << arr.shift\n else\n break\n end\n end\n new_str\nend", "def find_first_non_repeated_letter(str)\n ary = str.split(\"\")\n ary.detect { |e| ary.count(e) == 1 }\nend", "def missingNumber(array)\n (1..100).each do |i|\n return i if !array.index(i)\n end\nend", "def missing(array)\n (array.min..array.max).reject { |n| array.include?(n) }\nend", "def exclude(arr, char)\n output = []\n i = 0\n charlength = char.length\n while i < arr.length\n if arr[i] != char\n output << arr[i]\n i += 1\n else\n i += 1\n end\n end\n return output\nend", "def missing\n\t\t\tmissing, array = [], self.rangify\n\t\t\ti, length = 0, array.size - 1\n\n\t\t\twhile i < length \n\t\t\t\tcurrent = comparison_value(array[i], :last)\n\t\t\t\tnextt = comparison_value(array[i+1], :first)\n\t\t\t\tmissing << (current + 2 == nextt ? current + 1 : (current + 1)..(nextt - 1))\n\t\t\t\ti += 1\n\t\t\tend\n\t\t\tmissing\n\t\tend", "def find_the_missing_numbers(arr)\n example = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n send_back = []\n\n index = 0\n example.each do |num|\n if arr.include? num\n \n else\n send_back.insert(index, num)\n\n index += 1\n end\n \n end\n\n return send_back\nend", "def first_non_repeating_letter(s)\n s.chars.find{|char| s.downcase.count(char.downcase) <= 1} || ''\nend", "def non_unique_letters(string)\n answer = string.chars.select {|char| string.count(char) > 1}\n answer.delete(' ')\n answer.sort.uniq\nend" ]
[ "0.84147185", "0.826034", "0.8207233", "0.8195958", "0.8122356", "0.81194705", "0.80738145", "0.8004391", "0.79845405", "0.7968818", "0.7930456", "0.7927365", "0.7817498", "0.78102314", "0.77927554", "0.7764586", "0.7754829", "0.7641039", "0.7620936", "0.7615697", "0.75935477", "0.75717604", "0.7507128", "0.75006753", "0.7453003", "0.74429065", "0.74426687", "0.7425535", "0.7424243", "0.7390246", "0.7370202", "0.7341357", "0.7340674", "0.73140675", "0.72938293", "0.72849786", "0.72417027", "0.71462566", "0.7088879", "0.7006104", "0.696439", "0.68830055", "0.672433", "0.6718437", "0.6568073", "0.65444946", "0.6496127", "0.6490189", "0.6468087", "0.6459389", "0.6454263", "0.6426058", "0.6408016", "0.6404764", "0.6381376", "0.63428634", "0.6329077", "0.6329077", "0.6326574", "0.6303767", "0.62904954", "0.6288736", "0.6285133", "0.6284825", "0.6282875", "0.6277141", "0.6271842", "0.6232257", "0.62306505", "0.6212317", "0.6207932", "0.6168744", "0.61631083", "0.61629206", "0.6153702", "0.6134905", "0.6126132", "0.61087036", "0.61080956", "0.61074156", "0.6104923", "0.6101569", "0.6089576", "0.60862195", "0.60821235", "0.60745615", "0.6066638", "0.6065404", "0.60595375", "0.603911", "0.60371876", "0.6033834", "0.60321546", "0.6027063", "0.60216546", "0.601209", "0.60082406", "0.60064507", "0.599222", "0.5968523" ]
0.7392816
29
22 May 2019 learnt .each_with_index, .map.with_index (have nuanced differences) also .next and .succ (mean the same)
def missing_letter(word) word.each_with_index do |letter, i| return letter.next if word[i + 1] != letter.next end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def map_with_index &block\n index = 0\n map do |element|\n result = yield element, index\n index += 1\n result\n end\n end", "def map_with_index(array, &block)\n result = []\n index = 0\n array.each do |element|\n result << block.call(element, index)\n index += 1\n end\n result\nend", "def map_with_index(array, index = 0, &block)\n result = []\n i = index\n array.each do |element|\n result << block.call(element, i)\n i += 1\n end\n result\nend", "def my_each_with_index\n return to_enum unless block_given?\n\n index = 0\n my_each do |value|\n yield(value, index)\n index += 1\n end\n end", "def my_each_with_index\n i = 0\n while i < self.length\n yield self[i], i\n i += 1\n end\n self\n end", "def my_each_with_index\n i = 0\n while i < self.size\n yield(self[i], i)\n i += 1\n end\n self\n end", "def my_each_with_index\n i = 0\n while i < self.size\n yield self[i], i\n i += 1\n end\n end", "def my_each_with_index\n i = 0\n while i < self.length\n yield(self[i], i)\n i += 1\n end\n self\n end", "def my_each_with_index\n i = 0\n while i < self.to_a.length\n yield self.to_a[i], i\n i += 1\n end\n end", "def each_with_index(node=@head)\n i = 0\n until node.nil?\n result = yield(node, i)\n node = node.next_node\n i += 1\n end\n result\n end", "def each_with_index(arr)\n arr.size.times do |i|\n yield(arr[i], i)\n end\n arr\nend", "def map_with_index # :yields: e, i, j\n m = self.class.reserve(self.vsize, self.hsize)\n each_with_index { |e, i, j|\n m[i,j] = yield e, i, j\n }\n m\n end", "def index_from_start(index); end", "def shift_out_with_index(&block)\n each_with_index(&block)\n end", "def each_with_index(&block)\n return to_enum :each_with_index unless block\n\n i = 0\n self.each{|*val|\n block.call(val.__svalue, i)\n i += 1\n }\n self\n end", "def test_0655_each_with_index\n @@log.debug \"test_0655_each_with_index starts\" if @@log.debug?\n assert_respond_to(@list, :each_with_index, \"test_0655_each_with_index_respond\")\n # Type check\n enum = @list.each_with_index\n result = enum.is_a? Enumerator\n assert(result,\"test_0655_each_with_index_class\") \n # Check each index number\n @list.each_with_index {|item, index|\n case\n when item == @aen\n assert(index == 0, \"test_0655_each_with_index_i0\")\n when item == @bsb\n assert(index == 1, \"test_0655_each_with_index_i1\")\n when item == @cab\n assert(index == 2, \"test_0655_each_with_index_i2\")\n when item == @dad\n assert(index == 3, \"test_0655_each_with_index_i3\")\n else\n flunk(\"test_0655_each_with_index_invalid\")\n end\n }\n#\n# The author's paper copy of the 1.9 Pickaxe implies that each_with_index\n# can be invoked with one or more arguments as shown below.\n#\n# This appears to be incorrect, which can be confirmed by either:\n#\n# * Attempting to run the code shown\n# * Documentation at http://ruby-doc.org/core-1.9/classes/Enumerable.html\n#\n=begin\n # Invoke with argument(s)\n myarg = \"-tag\"\n accum = \"\"\n @list.each_with_index(myarg) {|item, index|\n case\n when item == @aen\n assert(index == 0, \"test_0655_each_with_index_i0a\")\n assert(myarg == \"-tag\", \"test_0655_each_with_index_tag0\")\n when item == @bsb\n assert(index == 1, \"test_0655_each_with_index_i1a\")\n assert(myarg == \"-tag\", \"test_0655_each_with_index_tag1\")\n when item == @cab\n assert(index == 2, \"test_0655_each_with_index_i2a\")\n assert(myarg == \"-tag\", \"test_0655_each_with_index_tag2\")\n when item == @dad\n assert(index == 3, \"test_0655_each_with_index_i3a\")\n assert(myarg == \"-tag\", \"test_0655_each_with_index_tag3\")\n else\n flunk(\"test_0655_each_with_index_invalid\")\n end\n }\n=end\n @@log.debug \"test_0655_each_with_index ends\" if @@log.debug?\n end", "def my_each_with_index(arr)\n \n\n for element in arr\n index = arr.index(element)\n yield(element, index)\n end\n \n \nend", "def each_index\n return to_enum(__callee__) unless block_given?\n \n each_with_index{ |_, idx| yield(idx) }\n end", "def my_each_with_index\n return to_enum unless block_given?\n\n i = 0\n while i < size\n yield(self[i], i)\n i += 1\n end\n self\n end", "def each_with_index(&block)\n to_a.each_with_index(&block)\n end", "def each_with_index(&block)\n to_a.each_with_index(&block)\n end", "def count_next_index()\n if @operation == :pour\n if @second_index + 1 >= @original_state.size\n @second_index = 0\n @first_index += 1\n else\n @second_index += @second_index + 1 == @first_index ? 2 : 1\n end\n if @first_index + 1 == @original_state.size && @second_index + 1 >= @original_state.size\n @operation = :nop\n end\n else\n if @first_index + 1 < @original_state.size\n @first_index += 1\n else\n @first_index = 0\n @operation = @operation == :fill ? :empty : :pour\n end\n end\n end", "def my_each_with_index\n if block_given?\n for i in 0.upto(self.length-1)\n yield self[i], i\n end\n else\n self.to_enum\n end\n end", "def my_each_with_index\n return to_enum unless block_given?\n\n i = 0\n while i < length\n yield(self[i], i)\n i += 1\n end\n end", "def index()\n INDEXES.find { |i| (self + i).exist? }&.yield_self { |i| self + i }\n end", "def my_each_with_index\n\t\tself.length.times do |index|\n\t\t\tyield(self[index], index)\n\t\tend\n\tend", "def slow_dance(direction, arr)\n arr.each_with_index do |el, i|\n return i if el == direction\n end\nend", "def my_each_with_index\n i = 0\n while i < size\n yield(self[i], i)\n i += 1\n end\n self\n end", "def each_index(*_arg0); end", "def my_each_with_index\n \ti = 0\n \twhile i < self.length\n \t\tif block_given?\n \t\t\tyield(self[i], i)\n \t\telse\n \t\t\treturn self\n \t\tend\n \t\ti +=1\n \tend\n \tself\n end", "def my_each_with_index\n for i in 0..self.length-1\n yield(self[i], i) if block_given?\n end\n self\n end", "def my_each_with_index\n for i in 0...self.length do\n yield(self[i], i)\n end\n return self\n end", "def magic_slow(arr)\n arr.each_with_index do |val, index|\n return index if val === index\n end\nend", "def my_each_with_index\n a = (is_a? Hash) ? to_a : self\n i = 0\n while i < a.count\n yield a[i], i\n i += 1\n end\n end", "def element_times_index(nums)\n nums.map.with_index{|num, idx| num * idx}\nend", "def test_0160_each_with_index\n @@log.debug \"test_0160_each_with_index starts\" if @@log.debug?\n assert_respond_to(@list, :each_with_index, \"test_0160_each_with_index_respond\")\n # Basic operation\n ta = []\n @list.each_with_index do |obj, ndx|\n ta << \"#{obj.first}-#{ndx}\"\n end\n assert_equal([\"Alfred-0\", \"Bob-1\", \"Charlie-2\", \"Dilbert-3\"], ta, \"test_0160_each_with_index_basic\")\n # Check Enumerator or Enumerable::Enumerator return, no block given\n new_list = @list.each_with_index\nif RUBY_VERSION >= \"1.9\"\n result = new_list.is_a? Enumerator\n assert(result, \"test_0160_each_with_index_enumcheck\")\nelse\n result = new_list.is_a? Enumerable::Enumerator\n assert(result, \"test_0160_each_with_index_enumenumcheck\")\nend\n @@log.debug \"test_0160_each_with_index ends\" if @@log.debug?\n end", "def each_with_index\n return nil if @head.nil?\n node_index = 1 #I'll consider first node as 1 \n entry = @head\n until entry.nil?\n yield entry, node_index\n entry = entry.next\n node_index +=1\n end\n end", "def at(index)\n\t\tx = @head\n\t\ty = 0\n\t\tuntil x == nil\n\t\t\tif y == index\n\t\t\t\treturn x\n\t\t\tend\n\t\t\ty += 1\n\t\t\tx = x.next\n\t\tend\n\tend", "def each_with_index(&blk)\n (0..@size-1).each { |i| blk.call(self.[](i),i) }\n end", "def index(element); end", "def each_index(&block)\n return enum_for(:each_index) unless block_given?\n 0.upto(size-1, &block)\n self\n end", "def lazy_index(index)\n index -= @map.keys.select{|e| e < index}.size\n result = 0\n @deleted.each do |deleted_index|\n if deleted_index - result > index\n return result + index\n else\n index -= deleted_index - result\n result = deleted_index + 1\n end\n end\n result + index\n end", "def roll_call_dwarves(array)\n # .each_with_index(1) --> use 1-based enumerator (start index at 1)\n # each.with_index method takes an optional parameter to offset the starting index\n # each_with_index does the same thing, but has no optional starting index\n array.each.with_index(1) do |name, index|\n puts \"#{index}. #{name}\"\n end\nend", "def returned_accumulator_index(return_values, accumulator_name, element_name); end", "def succ\n from_index(to_index.succ % DAY_SYM_SEQ.length)\n end", "def next\n last? ? nil : locate + 1\n end", "def new_step\n # noinspection RubyMismatchedReturnType\n index(index&.succ || 0)\n end", "def my_each_with_index\n return to_enum unless block_given?\n i = 0\n array = []\n while i < size\n yield to_a[i], i\n array << to_a[i]\n i += 1\n end\n array\n end", "def each_with_index\n ordered_values = values\n ordered_values.each_with_index do |v,i|\n yield ordered_values[i], min_index + (i*@range)\n end\n end", "def magic_slow(arr)\n arr.each_with_index do |val, index|\n if val === index\n return index\n end\n end\nend", "def shift_out_left_with_index\n # This is functionally equivalent to reverse_shift_out_with_index\n reverse_each.with_index { |bit, i| yield bit, i }\n end", "def get_new_idx(i, n)\n # I use the number 4 here but it correlates to the number of series.\n # For example, I only have \"a\", \"b\", \"c\", and \"d\" series so I use 4.\n (i % 4) * n + (i / 4)\nend", "def map_then_iterate_two_sum(array, target)\n hash = {}\n array.each.with_index do |i, index|\n hash[i] = index\n end\n indexes = []\n array.each.with_index do |ii, index|\n complement = target - ii \n if hash.has_key?(complement) && hash.fetch(complement) != index\n indexes.push(index, hash.fetch(complement))\n return indexes\n end\n end\nend", "def each_index(&block)\n enum = Enumerator.new do |yielder|\n begin\n @each_index = {}\n\n count = 0\n self.each do |ele|\n # Remove previous element to not take up memory.\n count_before = count - 1\n @each_index.delete(count_before) if @each_index.key?(count_before)\n\n # Add current element to cache.\n @each_index[count] = ele\n yield(count)\n\n # Increase count for next run.\n count += 1\n end\n ensure\n @each_index = nil\n end\n end\n\n if block\n enum.each(&block)\n return nil\n else\n return enum\n end\n end", "def each_pair_with_index\n index = 0\n self.each_pair do |key, value|\n yield key, value, index\n index += 1\n end\n end", "def [](index)\n i = 0\n each { |x| return x if i == index; i += 1 }\n nil # out of index\n end", "def slow_dance(step, array)\n index = 0\n array.each_with_index do |el, i|\n index = i if el == step\n end\n index\nend", "def find_index(a, target) # this is where returning directly from withing block is ok!\n a.each_with_index do |e, index|\n return index if e == target # returns to caller on line 19. This is exactly what we want\n end\n return nil # omitting return here is OK and doing so is more idiomatic\nend", "def get_next_index(current_index, direction, num_players)\n\t\tif direction == true\n\t\t\tif current_index == num_players - 1\n\t\t\t\t0\n\t\t\telse\n\t\t\t\tcurrent_index += 1\n\t\t\tend\n\t\telse\n\t\t\tif current_index == 0\n\t\t\t\tnum_players - 1\n\t\t\telse\n\t\t\t\tcurrent_index -= 1\n\t\t\tend\n\t\tend\n\tend", "def increase_index\n @i +=1\n end", "def iterativeMap(list)\n list.each do |i|\n list[i-1] = list[i-1] * 2\n end\n return list\nend", "def see_next\n if @index >= @normalized_numbers.length\n return -1\n else\n return @normalized_numbers[@index]\n end\n end", "def next_element\n validates_possibility_of :next\n self.index += 1\n self.current\n end", "def each_with_index(&block)\n @delegate.each_with_index(&block)\n end", "def each_value_with_index\n @nz.each do |i, j, v|\n yield v, i, j\n end\n end", "def each_with_index\n\t\t@array.each_with_index do |v,i|\n\t\t\tyield v & 0x0F, i * 2 #Bottom Nibble\n\t\t\tyield (v >> 4) & 0x0F, i * 2 + 1#Top Nibble\n\t\tend\n\tend", "def next_open_index(index)\n (index...(index + @size)).each do |i|\n if i >= @size\n i = i % @size\n end\n\n if @nodes[i] == nil\n return i\n end\n end\n\n return -1\n end", "def slow_dance(direction, array)\n array.each_with_index do |el, idx|\n return idx if el == direction\n end\nend", "def my_each_with_index(&block)\n return to_enum(:my_each_with_index) unless block_given?\n n = 0\n while n < length\n block.call(self[n], n) if is_a?(Array)\n block.call(keys[n], self[keys[n]]) if is_a?(Hash)\n block.call(self[n]) if is_a?(Range)\n n += 1\n end\n self\n end", "def map_with_siblings\n self.map.with_index { |_, index|\n yield(\n index > 0 ? self.at(index - 1) : nil,\n self[index],\n index < self.count() - 1 ? self[index + 1] : nil\n )\n }\n end", "def each_lower_with_index # :yields: e, i, j\n (0...hsize).each { |j|\n ((j+1)...vsize).each { |i|\n yield self[i,j], i, j\n }\n }\n self\n end", "def eachio_index(&block) # :yield: index\n 0.upto(length-1, &block)\n self\n end", "def each_with_index # :yields: e, i, j\n (0...hsize).each { |j|\n (0...vsize).each { |i|\n yield self[i,j], i, j\n }\n }\n self\n end", "def each_with_index\n each_linked_list_item_with_index do |node, index|\n yield node.payload, index\n end\n end", "def remap_index(index, options)\n if index == options.length - 1\n 0\n else\n index + 1\n end\n end", "def each_child_with_index\n end", "def at(index); end", "def loop_with_index_again(puppies)\n puppies.each_with_index { |val, idx| \n puts \"#{idx}: #{val}\"\n }\nend", "def slow_dance(move, arr)\n arr.each_with_index do |dir, idx|\n return idx if move == dir\n end\nend", "def find_at(index)\n return if (index + 1) > count || index < 0\n\n item = @head\n index.times { item = item.next }\n item.value\n end", "def at(index)\n curr = head\n index.downto(1) do |_|\n break if curr.nil?\n\n curr = curr.next\n end\n curr\n end", "def each_index\n (0...hsize).each { |j|\n (0...vsize).each { |i|\n yield i, j\n }\n }\n self\n end", "def each_with_index(&block)\n examples.each_with_index(&block)\n end", "def slow_dance(dir, array)\n array.each.with_index do |el, idx|\n return idx if dir == el\n end\nend", "def each_with_index(zeroes = false, &_block)\n return enum_for :each_with_index, zeroes unless block_given?\n if zeroes\n row_count.times do |row|\n column_count.times do |_col|\n element = self[row, column]\n yield [element, row, column]\n end\n end\n else\n ia.each_cons(2).each_with_index do |indexes, row|\n row_start, row_end = *indexes\n a[row_start...row_end].each_with_index do |element, index|\n yield [element, row, ja[row_start + index]]\n end\n end\n end\n end", "def get(index)\n current = get_next\n index.times { current = get_next(current) }\n current\n end", "def next_idx(list)\n return 0 if list.empty?\n list.map { |item| item[:idx] }.max + 1\n end", "def index(value)\n index = nil\n\n self.each_with_indices do |yields|\n if yields.first == value\n yields.shift\n index = yields\n break\n end\n end\n\n index\n end", "def index_by\n\t\t\t\tmap { |n| [yield(n), n] }.to_hash\n\t\t end", "def test_small_offset_for_index\n expected = [0x001ac4c3, 0x001bcaab, 0x001a82fe, 0x0003518e]\n 0.upto(3) do |idx|\n assert_equal expected[idx], @index.offset_for_index(idx)\n end\n end", "def next_number(num, index, numbers, ph, lh)\n if index < numbers.size\n num = numbers[index]\n ph[num] = index\n return num\n end\n\n if lh[num] # second repeat\n nnum = lh[num] - ph[num]\n ph[nnum] ? lh[nnum] = index : ph[nnum] = index\n ph[num] = index - 1\n num = nnum\n else\n num = 0\n lh[num] = index # works because we know 0 has occurred before\n end\n num\nend", "def fibonacci_table_2(position)\n return 1 if position == 1 || position == 2\n\n prev_1 = 1\n prev_2 = 1\n\n (3..position).map do |index|\n result = prev_1 + prev_2\n\n prev_1 = prev_2\n prev_2 = result\n end\n\n prev_2\nend", "def next_player_index(current_index)\n (current_index + 1) % num_players\n end", "def advance\n @current += 1 unless at_end?\n return previous\n end", "def slow_dance(dir, arr)\n arr.each_with_index do |el, idx|\n return idx if dir == el\n end\nend", "def slow_dance(direction, array)\n array.each_with_index do |tile, idx|\n return idx if tile == direction\n end\nend", "def next()\n result = current\n @index += 1\n @got_next_element = false\n @next_element = nil\n result\n end", "def fix_index_plus(index, _max_index)\n delta = index - @index.to_i\n if delta == 2 # DOWN\n return 0 if @index == 0 || @index == 2\n return 1\n end\n return 0\n end", "def next\n peek.tap { @position += 1 }\n end", "def roll_call_dwarves(dwarf_name_array)\n puts dwarf_name_array.each_with_index { |a,b| puts \"(#{b+1} #{a})\" }\n # of \n # dwarf_name_array.each_with_index do |dwarf, index| \n # puts \"#{index+1}. #{dwarf}\" }\n # end\n\n # uses each and with_index separately\n # dwarf_name_array.each.with_index(1) do |dwarf, index| \n # puts \"#{index+1}. #{dwarf}\" }\n # end\n\nend", "def first_index(arr, &blck)\n #arr.find_index { |el| blck.call(el) }\n arr.each_with_index do |el, i|\n if blck.call(el)\n return i\n end\n end\n return nil\nend" ]
[ "0.7425129", "0.68470335", "0.67555577", "0.671061", "0.65570855", "0.64828056", "0.64720297", "0.64579433", "0.6445572", "0.64334136", "0.64287263", "0.6378571", "0.6369443", "0.6353472", "0.63479966", "0.6318665", "0.6314452", "0.63143396", "0.6307565", "0.6300601", "0.6300601", "0.62902576", "0.62561476", "0.6255318", "0.6251805", "0.62486976", "0.6244301", "0.6216195", "0.62047625", "0.6175117", "0.61666", "0.6144313", "0.61420715", "0.6140285", "0.61334765", "0.61213535", "0.61179954", "0.61012346", "0.6092457", "0.60894483", "0.60890406", "0.60766184", "0.6048854", "0.6036288", "0.60263234", "0.602525", "0.6017005", "0.600871", "0.6006478", "0.5966025", "0.5951718", "0.5951065", "0.5950677", "0.595034", "0.59453744", "0.5940165", "0.59336495", "0.59329325", "0.5925611", "0.59161127", "0.5908426", "0.59053063", "0.5898844", "0.5898055", "0.58918536", "0.588727", "0.5882782", "0.58784115", "0.58725125", "0.5867382", "0.58663", "0.58599836", "0.5856274", "0.5854172", "0.5850095", "0.584022", "0.58384633", "0.581062", "0.5808481", "0.5786664", "0.5783374", "0.5775176", "0.57520336", "0.5748175", "0.5740633", "0.5737055", "0.5728691", "0.5727035", "0.57180417", "0.5717612", "0.57123715", "0.5706544", "0.56944567", "0.5687766", "0.56811064", "0.5674385", "0.56734556", "0.5672138", "0.5659293", "0.5655692", "0.56544626" ]
0.0
-1
GET /reqcargos GET /reqcargos.json
def index @reqcargos = Reqcargo.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list_tenants_for_circles(args = {}) \n get(\"/tenants.json/circles\", args)\nend", "def list_tenants_for_circle(args = {}) \n get(\"/tenantcircles.json/tenants\", args)\nend", "def request(args = {})\n response = @client.get(args[:url],\n argument_hash(args[:args] || {},\n args[:symbols] || []))\n JSON.parse(response.body)\n end", "def requests\n @requests_obj.list\n end", "def requests\n REQUESTS\n end", "def list_requests\n # stub\n end", "def get_request(options, path)\n\n result = {}\n\n http = Net::HTTP.new(ENV['NESSUS_HOST'], options[:port])\n http.use_ssl = @use_ssl\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n http.start do |http|\n req = Net::HTTP::Get.new(path)\n\n # we make an HTTP basic auth by passing the\n # username and password\n req['X-ApiKeys'] = \"accessKey=#{ENV['NESSUS_ACCESS_KEY']}; secretKey=#{ENV['NESSUS_SECRET_KEY']}\"\n \n resp, data = http.request(req)\n \n if resp.code.eql? '200'\n #print \"Data: \" + JSON.pretty_generate(JSON.parse(resp.body.to_s))\n result = JSON.parse(resp.body.to_s)\n else\n puts \"Error: \" + resp.code.to_s + \"\\n\" + resp.body\n end\n end\n\n return result\n end", "def queryOS(args)\n begin\n p = Hash.new\n uri = URI(args[:entrypoint])\n p[\"header\"] = {'Content-type'=>'application/json','Accept-type'=>'application/json','X-Auth-Token'=>args[:token]}\n case args[:component].to_s\n when \"Nova\"\n p[\"port\"] = uri.port || 8774\n\tp[\"path\"] = uri.path\n when \"Glance\"\n p[\"port\"] = uri.port || 9292\n p[\"path\"] = uri.path || \"/v1\"\n when \"Volume\"\n p[\"port\"] = uri.port || 8776\n\tp[\"path\"] = uri.path\n when \"Swift\" \n p[\"port\"] = uri.port || 8080\n\tp[\"path\"] = uri.path\n when \"Keystone\"\n p[\"port\"] = uri.port || 35357\n p[\"path\"] = uri.path || \"/v2/tokens\"\n when \"Cloud\"\n p[\"port\"] = uri.port || 8773\n p[\"path\"] = uri.path || \"/services/Cloud\"\n p[\"header\"] = {'Content-type'=>'application/xml','Accept-type'=>'application/xml'}\n else\n return false\n end\n p[\"location\"] = uri.host || \"\"\n p[\"path\"] = p[\"path\"] + args[:path] || uri.path\n p[\"request\"] = args[:request] || \"\"\n os = Net::HTTP.new(p[\"location\"],p[\"port\"])\n if uri.scheme == \"https\"\n os.use_ssl = true\n else\n os.use_ssl = false\n end\n resp = nil\n case args[:method].to_s\n when \"post\"\n resp = os.post(p[\"path\"], p[\"request\"], p[\"header\"])\n when \"get\"\n resp = os.get(p[\"path\"], p[\"header\"])\n when \"update\"\n resp = os.put(p[\"path\"], p[\"request\"], p[\"header\"])\n when \"delete\"\n resp = os.delete(p[\"path\"], p[\"header\"])\n end\n newdata = false\n if resp.code.to_i >= 200 and resp.code.to_i < 300\n if args[:component].to_s == \"Cloud\"\n newdata = resp.body\n else\n\t if args[:method].to_s == \"delete\"\n\t newdata = true\n else\n newdata = JSON resp.body\n end\n end\n end\n os = nil\n p = nil\n return newdata\n rescue Errno::EHOSTUNREACH\n false\n end\n end", "def list_all_tenantcircles_for_a_version_box(args = {}) \n get(\"/aosversions.json/aosversionbox/circles/#{args[:aosVersionBoxId]}\", args)\nend", "def get_all_orders() \n\tputs \"Getting all orders\"\n\tresponse = request_get(\"/api/order\")\n\tputs response.body\nend", "def index\n @requests = ::Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def index\n @reqs = Req.all\n end", "def index\n #@csosns = Csosn.all\n @csosns = Csosn.paginate(:page => params[:page], :per_page => 10)\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @csosns }\n end\n end", "def index\n @cfos = Cfo.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cfos }\n end\n end", "def getApplications(ak)\n uri='https://api.newrelic.com/v2/applications.json'\n parseUrl=URI.parse(uri)\n host=parseUrl.host\n path=parseUrl.path\n getRequest(ak,uri,host,path)\nend", "def cf_curl(*args)\n output = capture('cf', 'curl', *args)\n JSON.parse output\nend", "def info\n CouchRest.get \"#{@uri}/\"\n end", "def index\n @requests = Request.all\n\n render json: @requests\n end", "def getCounchDBData \r\n url = URI.parse(\"http://citivan.iriscouch.com/_utils\") \r\n server = Couch::Server.new(url.host, url.port) \r\n res = server.get(\"/sms/currentUsers\") \r\n json = res.body \r\n json = JSON.parse(json) \r\nend", "def list_active_aos_versions(args = {}) \n get(\"/aosversions.json/\", args)\nend", "def get_cabinets(options={})\n parser.cabinets_parser(get({ path: ROUTES[:get_cabinets].call, headers: authorization_header_for_rest_api }))\n end", "def index\n @concursos = Concurso.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @concursos }\n end\n end", "def index\n @cargo_manifests = CargoManifest.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cargo_manifests }\n end\n end", "def index\n @cocktails = Cocktail.where(\"oficial = ?\", false)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @cocktails }\n end\n end", "def index\n @colegios = Colegio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @colegios }\n end\n end", "def search_requests( cid )\n url = \"#{self.url}?auth=#{self.authtoken}&cid=#{cid}\"\n status, response = rest_get( url )\n return status, response['details'] if ok?( status ) && response['details']\n return status, ''\n end", "def api_request\n url = URI.parse(\"https://catfact.ninja/fact\")\n response = Net::HTTP.get_response(url)\n JSON.parse(response.body)[\"fact\"]\n end", "def request(*args); end", "def index\n if current_user.has_role? :admin\n @requests = Request.ordered\n else\n @requests = current_user.requests.ordered\n end\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def get_products()\n\tputs \"Getting products\"\n\tresponse = request_get(\"/api/product\")\n\tputs response.body\nend", "def request(*args)\n end", "def index\n @ctos = Cto.all\n end", "def index\n @coocos = Cooco.all\n end", "def listJobsForProject(project_mame)\n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/1/jobs')\n params = { 'project' => project_mame }\n headers = {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}\n connection = Excon.new('http://build01:4440/api/1/jobs')\n return connection.get(:query => { 'project' => project_mame },:headers => {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}).body.force_encoding(\"UTF-8\")\n\nend", "def index\n @requests = Request.all\n\n respond_to do |format|\n format.json { render :json => @requests}\n end\n end", "def index\n @bill_cargos = @bill.bill_cargos\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @bill_cargos }\n end\n end", "def api_request(input_args)\n addr = URI(api_url)\n parms = input_args.clone\n parms = api_defaults.merge(parms)\n addr.query = URI.encode_www_form(parms)\n JSON.parse(Net::HTTP.get(addr))\n end", "def json\n Oj.to_json(@req)\n end", "def index\n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def index\n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def request_info\n @requests = Request.ordered\n end", "def get_requests\n @requests\n end", "def certs\n request :get, '/certs'\n end", "def index\n @cofis = Cofi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cofis }\n end\n end", "def get_citations(word, *args)\n http_method = :get\n path = '/word/{word}/citations'\n path.sub!('{word}', word.to_s)\n\n # Ruby turns all key-value arguments at the end into a single hash\n # e.g. Wordnik.word.get_examples('dingo', :limit => 10, :part_of_speech => 'verb')\n # becomes {:limit => 10, :part_of_speech => 'verb'}\n last_arg = args.pop if args.last.is_a?(Hash)\n last_arg = args.pop if args.last.is_a?(Array)\n last_arg ||= {}\n\n # Look for a kwarg called :request_only, whose presence indicates\n # that we want the request itself back, not the response body\n if last_arg.is_a?(Hash) && last_arg[:request_only].present?\n request_only = true\n last_arg.delete(:request_only)\n end\n\n params = last_arg\n body ||= {}\n request = Wordnik::Request.new(http_method, path, :params => params, :body => body)\n request_only ? request : request.response.body\n end", "def req\n \n end", "def index\n @cys_envs = CysEnv.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cys_envs }\n end\n end", "def index\n @ctypes = Ctype.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ctypes }\n end\n end", "def index\n @congressos = Congresso.all\n end", "def get_conversations_cobrowsesessions_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: ConversationsApi.get_conversations_cobrowsesessions ...\"\n end\n \n # resource path\n local_var_path = \"/api/v2/conversations/cobrowsesessions\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n local_header_accept = ['application/json']\n local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result\n\n # HTTP header 'Content-Type'\n local_header_content_type = ['application/json']\n header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n \n auth_names = ['PureCloud OAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'CobrowseConversationEntityListing')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ConversationsApi#get_conversations_cobrowsesessions\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def index\n @occasions = current_user.occasions.sorteddesc.all.paginate(page: params[:page], :per_page => 10)\n @products = Product.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @occasions }\n end\n end", "def requests\n\t\tRequest.find(:all)\n\tend", "def index\n @http_requests = HttpRequest.order(\"created_at DESC\").page(params[:page]).per(10)\n end", "def create\n @reqcargo = Reqcargo.new(reqcargo_params)\n\n respond_to do |format|\n if @reqcargo.save\n format.html { redirect_to @reqcargo, notice: 'Reqcargo was successfully created.' }\n format.json { render :show, status: :created, location: @reqcargo }\n else\n format.html { render :new }\n format.json { render json: @reqcargo.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @crawl_requests = CrawlRequest.all\n \n render json: @crawl_requests\n end", "def all_companies_information\n\t\tbegin\n\t url = URI.parse(Rails.application.secrets[:api_endpoints]['onething']['url_company_info'])\n\t\t url_params = {}\n\t\t path = \"#{url.path}?#{url_params.collect { |k,v| \"#{k}=#{CGI::escape(v.to_s)}\"}.join('&')}\"\n\t\t request = Net::HTTP::Get.new(path) \n\t\t response = Net::HTTP.start(url.host, url.port, :use_ssl => false, :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http| \n\t\t http.request(request)\n\t\t end \n\t\t json_data = JSON.parse(response.body) rescue nil\n\t\t if !json_data.present?\n\t\t \treturn {}\n\t\t else\n\t\t return json_data\n\t\t end\n\t rescue => e\n\t \treturn {:message => 'Error in fetchng API data. Please try again.'}\t\n\t end\n\tend", "def index\n @http_requests = HttpRequest.all\n end", "def get_available_cartridges\n args = Hash.new\n args['--porcelain'] = true\n args['--with-descriptors'] = true\n result = execute_direct(@@C_CONTROLLER, 'cartridge-list', args, false)\n result = parse_result(result)\n cart_data = JSON.parse(result.resultIO.string)\n cart_data.map! {|c| OpenShift::Cartridge.new(YAML.load(c))}\n end", "def index\n url = \"https://data.cityofchicago.org/resource/x2n5-8w5q.json\"\n options = { :body => {:status => text}, :basic_auth => @auth }\n @response = HTTParty.get(url, options)\n\n @crime = Hash.new\n\n #@crime['block'] = @response[0]['block']\n @crime = @response\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gittos }\n end\n end", "def request\n @req\n end", "def index\n @contact = current_user.contacts.find(params[:contact_id])\n @requests = @contact.requests\n\n respond_with @requests\n end", "def index\n organizations = if params[:q]\n CclaSignature.search(params[:q])\n else\n Organization.includes(:ccla_signatures)\n end\n\n respond_to do |format|\n format.json do\n render json: organizations.to_json(only: [:id], methods: [:company])\n end\n end\n end", "def index\n @requests = Request.paginate(:page => params[:page], :per_page => 8).order(\"created_at DESC\").find_all_by_user_id(current_user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def set_reqcargo\n @reqcargo = Reqcargo.find(params[:id])\n end", "def requests\n @requests = @startup.requests.startup_related_requests(current_user.brand_id)\n .order(created_at: :desc)\n end", "def list_all_aos_versions(args = {}) \n get(\"/aosversions.json/all\", args)\nend", "def index\n @ccostos = Ccosto.all\n end", "def tecnicos_postulados\n coleccion = []\n self.request.each do |request|\n info = {}\n info[:id] = request.id\n info[:article] = request.article\n info[:servicio] = request.service.description\n info[:tecnicos] = request.proposal\n coleccion.append(info)\n end\n coleccion\n end", "def get_request(url,args)\n uri = URI.parse url\n\n # ck is the current unix timestamp\n args[:ck] = Time.now.to_i unless args[:ck]\n\n req = Net::HTTP::Get.new(\"#{uri.path}?#{argument_string(args)}\")\n request(uri,req)\n end", "def index\n if current_client\n @current_client_requests = current_client.requests\n else\n end\n end", "def index\n @capacites = Capacite.paginate(page: params[:page], per_page: 25)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @capacites }\n end\n end", "def getorders(args={})\n {\n :method=> \"GetOrders\"\n }.to_json\n end", "def list(*args)\n fail \"Unacceptable HTTP Method #{request.env['REQUEST_METHOD']} for list\" unless request.get?\n {:action => 'list',\n :args => args}\n end", "def index\n @converstation_requests = ConverstationRequest.all\n end", "def request (url_requested, api_key)\n url_builded = url_requested + \"&api_key=\" + api_key\n\n url = URI(url_builded)\n\n https = Net::HTTP.new(url.host, url.port)\n https.use_ssl = true\n\n request = Net::HTTP::Get.new(url)\n\n response = https.request(request)\n\n JSON.parse(response.read_body)\nend", "def index\n #data = HTTParty.get(\"http://localhost:8081/customers.json\")\n #p data.parsed_response[0]['email']\n if params[:customerId].present?\n @orders = Order.where(\"customerId\": params[:customerId].to_i)\n render json: @orders, status: 200\n elsif params[:id].present?\n @orders = Order.find_by id: params[:id]\n render json: @orders, status:200\n elsif params[:email].present?\n res = HTTParty.get(\"http://localhost:8081/customers/?email=#{params['email']}\")\n p res\n res = res.parsed_response\n @orders = Order.where(\"customerId\": res['id'].to_i)\n render json: @orders, status:200\n else\n @orders = Order.all\n end\n end", "def everything\n raw = JSON.parse(`curl -sX GET 'https://api.nirvanahq.com/?api=rest&appid=gem&authtoken=#{@token}&method=everything&since=0'`)\n raw['results']\n end", "def index\n @copenometros = Copenometro.all\n end", "def get_jobs_sample(client)\n response = client['jobs'].get\n\n p ''\n p 'Get jobs'\n p response\nend", "def index\n @consorciots = Consorciot.all\n end", "def simple_request(method, url)\n uri = URI.parse(url)\n request = Net::HTTP::Get.new(uri)\n request.content_type = \"application/json\"\n request[\"Accept\"] = \"application/json\"\n request[\"App-Id\"] = ENV[\"salt_edge_app_id\"]\n request[\"Secret\"] = ENV[\"salt_edge_secret\"]\n\n req_options = {\n use_ssl: uri.scheme == \"https\",\n } \n\n response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|\n http.request(request)\n end\n\n #puts response.body\n return JSON.parse(response.body)\n end", "def listcrts(options = {})\n server.force_response_type = :ssl\n result = server.perform_request('listcrts', options.merge(:response_key => 'crt'))\n end", "def cost(args = {})\n make_request(\n http_method: :get,\n endpoint: path_for(:cost),\n access_token: args.delete(:access_token),\n options: { query: args }\n )\n end", "def make_api_call(args)\n uri = URI(\"https://classes.cornell.edu/api/2.0/search/classes.json?roster=#{args[0]}&subject=#{args[1]}&acadCareer[]=#{args[2]}&classLevels[]=#{args[3]}\")\n begin\n Net::HTTP.start(uri.host, uri.port,\n :use_ssl => uri.scheme == 'https') do |http|\n request = Net::HTTP::Get.new uri\n\n response = http.request request # Net::HTTPResponse object\n hash_response = JSON.parse(response.body)\n hash_response\n end\n rescue JSON::ParserError\n {\"status\": \"Error\"} # Returning an empty hash\n end\nend", "def index\n require 'rest-client'\n response = RestClient::Request.execute(method: :get, url: 'localhost:3001/colores',\n headers: {page: params[:page], items: 9})\n if response.code == 200\n body = JSON.parse(response.body)\n @colors = body[\"data\"]\n @page = body[\"page\"]\n end\n end", "def index\n respond_to do |format|\n format.html { @chefs = Chef.all }\n format.json { @chefs = Chef.order(:name) }\n end\n end", "def index\n @ginasios = Ginasio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ginasios }\n end\n end", "def index\n @xrf_cocs = XrfCoc.all\n end", "def index\n @distros = getmydata(\"Distro\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @distros }\n end\n end", "def http( *args )\n p http_get( *args )\n end", "def ocs(args)\n OcsApi.new(args)\n end", "def contas\n list_contas = JSON.parse(get_and_give_me_a_json(\"/contas\"))\n rtn = []\n list_contas.each do |c_map|\n conta = Taxcalendario::Admin::Client::Entities::Conta.new\n conta.from_hash(c_map)\n rtn << conta\n end\n rtn\n end", "def obtenerOc(id) #CHECK\n\tjsonResponse = requestWebWithoutParams('GET', (ENV[\"url_oc\"]+\"obtener/\"+id.to_s))\n\tif(jsonResponse==false)\n\t\treturn jsonResponse\n\telse\n\t\tjsonResponse = jsonResponse.first\n\t\tparamsOc = { _id: jsonResponse['_id'],\n\t\t\t\tcliente: jsonResponse['cliente'],\n\t\t\t\tproveedor: jsonResponse['proveedor'],\n\t\t\t\tsku: jsonResponse['sku'],\n\t\t\t\tdireccion: '',\n\t\t\t\tfechaEntrega: jsonResponse['fechaEntrega'],\n\t\t\t\tprecioUnitario: jsonResponse['precioUnitario'],\n\t\t\t\tcantidadDespachada: jsonResponse['cantidadDespachada'],\n\t\t\t\tcantidad: jsonResponse['cantidad'],\n\t\t\t\tcanal: jsonResponse['canal'],\n\t\t\t\tfechaCreacion: jsonResponse['created_at'],\n\t\t\t\testado: jsonResponse['estado']\n\t\t}\n\t\treturn paramsOc\n\tend\nend", "def list # rubocop:disable Metrics/AbcSize\n authcookie = ComputeBase.new\n authcookie = authcookie.authenticate(id_domain, user, passwd, restendpoint)\n url = restendpoint + @function + container\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port, @proxy_addr, @proxy_port) # Creates a http object\n http.use_ssl = true # When using https\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Get.new(uri.request_uri)\n request.add_field 'accept', 'application/oracle-compute-v3+json' if action == 'details'\n request.add_field 'accept', 'application/oracle-compute-v3+directory+json' if action == 'list'\n request.add_field 'Cookie', authcookie\n http.request(request)\n end", "def list\n get('/')\n end", "def index\n @requests = Request.all\n end", "def index\n @requests = Request.all\n end", "def index\n @requests = Request.all\n end", "def index\n @requests = Request.all\n end", "def index\n @requests = Request.all\n end" ]
[ "0.6043053", "0.596949", "0.58654505", "0.5772901", "0.5599491", "0.5525767", "0.54969394", "0.5478865", "0.54684436", "0.5465827", "0.5415466", "0.5407471", "0.54027385", "0.5386744", "0.5374827", "0.5365918", "0.53389347", "0.53317386", "0.53213364", "0.53172064", "0.5310385", "0.52970386", "0.5290572", "0.5287599", "0.5284589", "0.5277883", "0.5254174", "0.52475953", "0.5236426", "0.5225588", "0.5225067", "0.52027786", "0.51998836", "0.5199709", "0.5198287", "0.5197183", "0.5197168", "0.519164", "0.5191123", "0.5191123", "0.51874083", "0.51850545", "0.5172628", "0.51615465", "0.51589936", "0.5150973", "0.51474035", "0.5146714", "0.51333505", "0.5133221", "0.51280713", "0.51278085", "0.5126093", "0.51250875", "0.5120812", "0.511667", "0.51156807", "0.51108795", "0.5106014", "0.5100288", "0.5090328", "0.5087679", "0.50846195", "0.50823355", "0.50818735", "0.50814825", "0.5079318", "0.5076356", "0.507594", "0.50736296", "0.50724095", "0.50721663", "0.50673723", "0.5067258", "0.50667036", "0.5062349", "0.5059604", "0.50580764", "0.5054946", "0.5051721", "0.50477946", "0.50457233", "0.5043864", "0.5041332", "0.50362384", "0.5030268", "0.5029584", "0.5028123", "0.50269437", "0.5019388", "0.5004278", "0.5001126", "0.49959424", "0.49935162", "0.49887055", "0.49875644", "0.49875644", "0.49875644", "0.49875644", "0.49875644" ]
0.65913725
0
GET /reqcargos/1 GET /reqcargos/1.json
def show add_breadcrumb "Detalles", @reqcargos end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @reqcargos = Reqcargo.all\n end", "def request(args = {})\n response = @client.get(args[:url],\n argument_hash(args[:args] || {},\n args[:symbols] || []))\n JSON.parse(response.body)\n end", "def list_tenants_for_circles(args = {}) \n get(\"/tenants.json/circles\", args)\nend", "def list_tenants_for_circle(args = {}) \n get(\"/tenantcircles.json/tenants\", args)\nend", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n puts JSON.pretty_generate(result)\n result\nend", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def index\n @requests = Request.all\n\n render json: @requests\n end", "def get_request(options, path)\n\n result = {}\n\n http = Net::HTTP.new(ENV['NESSUS_HOST'], options[:port])\n http.use_ssl = @use_ssl\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n http.start do |http|\n req = Net::HTTP::Get.new(path)\n\n # we make an HTTP basic auth by passing the\n # username and password\n req['X-ApiKeys'] = \"accessKey=#{ENV['NESSUS_ACCESS_KEY']}; secretKey=#{ENV['NESSUS_SECRET_KEY']}\"\n \n resp, data = http.request(req)\n \n if resp.code.eql? '200'\n #print \"Data: \" + JSON.pretty_generate(JSON.parse(resp.body.to_s))\n result = JSON.parse(resp.body.to_s)\n else\n puts \"Error: \" + resp.code.to_s + \"\\n\" + resp.body\n end\n end\n\n return result\n end", "def index\n @requests = ::Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def index\n url = \"https://data.cityofchicago.org/resource/x2n5-8w5q.json\"\n options = { :body => {:status => text}, :basic_auth => @auth }\n @response = HTTParty.get(url, options)\n\n @crime = Hash.new\n\n #@crime['block'] = @response[0]['block']\n @crime = @response\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gittos }\n end\n end", "def get_json(path)\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n #puts \"🤖 GET #{path}\"\n #puts \"HTTP #{response.code}\"\n #puts JSON.pretty_generate(result)\n result\nend", "def index\n @reqs = Req.all\n end", "def index\n @requests = Request.all\n\n respond_to do |format|\n format.json { render :json => @requests}\n end\n end", "def requests\n @requests_obj.list\n end", "def index\n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def index\n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def get_request(url,args)\n uri = URI.parse url\n\n # ck is the current unix timestamp\n args[:ck] = Time.now.to_i unless args[:ck]\n\n req = Net::HTTP::Get.new(\"#{uri.path}?#{argument_string(args)}\")\n request(uri,req)\n end", "def request(*args); end", "def ocRecibir\n id = params[:id]\n ocClass = Oc.new\n result = ocClass.recibirOC(id) \n render :json => {:aceptado => result, :idoc => id} \n\n end", "def index\n @colegios = Colegio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @colegios }\n end\n end", "def request(*args)\n end", "def index\n temp = current_user.id\n # Auf Methode warten, nur noch offene, in der Zukunft liegende Requests \n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def info\n CouchRest.get \"#{@uri}/\"\n end", "def getCounchDBData \r\n url = URI.parse(\"http://citivan.iriscouch.com/_utils\") \r\n server = Couch::Server.new(url.host, url.port) \r\n res = server.get(\"/sms/currentUsers\") \r\n json = res.body \r\n json = JSON.parse(json) \r\nend", "def http( *args )\n p http_get( *args )\n end", "def index\n @cargo_manifests = CargoManifest.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cargo_manifests }\n end\n end", "def index\n @cocktails = Cocktail.where(\"oficial = ?\", false)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @cocktails }\n end\n end", "def index\n @cfos = Cfo.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cfos }\n end\n end", "def get_json()\n\n http = Net::HTTP.new(STATUS_URI.host, STATUS_URI.port)\n http.use_ssl = false\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Get.new(\"/api/services.json\")\n\n response = http.request(request)\n JSON.parse(response.body)\nend", "def requests\n REQUESTS\n end", "def room_descriptions_method\r\n my_port = 8081\r\n htttproomnumber = $roomnumber\r\n roomsNtext = \"/#{htttproomnumber}\"\r\n rooms_message = \"/rooms#{roomsNtext}\"\r\n url = URI.parse(\"http://localhost:#{my_port}#{rooms_message}\")\r\n req = Net::HTTP::Get.new(url.to_s)\r\n res = Net::HTTP.start(url.host, url.port){|http|\r\n http.request(req)\r\n }\r\n my_json = JSON.parse(res.body) \r\n return my_json[\"room\"].to_s\r\nend", "def get\n start { |connection| connection.request http :Get }\n end", "def json\n Oj.to_json(@req)\n end", "def create\n @reqcargo = Reqcargo.new(reqcargo_params)\n\n respond_to do |format|\n if @reqcargo.save\n format.html { redirect_to @reqcargo, notice: 'Reqcargo was successfully created.' }\n format.json { render :show, status: :created, location: @reqcargo }\n else\n format.html { render :new }\n format.json { render json: @reqcargo.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_reqcargo\n @reqcargo = Reqcargo.find(params[:id])\n end", "def index\n @concursos = Concurso.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @concursos }\n end\n end", "def index\n @requisitions = Requisition.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requisitions }\n end\n end", "def api_request(input_args)\n addr = URI(api_url)\n parms = input_args.clone\n parms = api_defaults.merge(parms)\n addr.query = URI.encode_www_form(parms)\n JSON.parse(Net::HTTP.get(addr))\n end", "def get(connection, path, args = {})\n host, port = connection_host_and_port(connection)\n\n res = open(\n \"http://#{host}:#{port}#{path}#{to_get_params(args)}\"\n ).read\n puts res if @debug\n\n begin\n res = JSON.parse(res)\n raise res['error'] if res.is_a?(Hash) and res['error']\n return res\n rescue JSON::ParserError => e\n end\n\n res\n end", "def json_get(path, params={})\n json_request(:get, path, params)\n end", "def show\n @corgi = Corgi.find(params[:id])\n respond_to do |format|\n format.html \n format.json { render json: @corgi }\n end \n end", "def index\n @requests = Request.paginate(:page => params[:page], :per_page => 8).order(\"created_at DESC\").find_all_by_user_id(current_user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def simple_request(method, url)\n uri = URI.parse(url)\n request = Net::HTTP::Get.new(uri)\n request.content_type = \"application/json\"\n request[\"Accept\"] = \"application/json\"\n request[\"App-Id\"] = ENV[\"salt_edge_app_id\"]\n request[\"Secret\"] = ENV[\"salt_edge_secret\"]\n\n req_options = {\n use_ssl: uri.scheme == \"https\",\n } \n\n response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|\n http.request(request)\n end\n\n #puts response.body\n return JSON.parse(response.body)\n end", "def index\n @requests = Request.where(status: -1)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def show\n @colegio = Colegio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @colegio }\n end\n end", "def list_active_aos_versions(args = {}) \n get(\"/aosversions.json/\", args)\nend", "def list_requests\n # stub\n end", "def index\n @cofis = Cofi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cofis }\n end\n end", "def obtenerOc(id) #CHECK\n\tjsonResponse = requestWebWithoutParams('GET', (ENV[\"url_oc\"]+\"obtener/\"+id.to_s))\n\tif(jsonResponse==false)\n\t\treturn jsonResponse\n\telse\n\t\tjsonResponse = jsonResponse.first\n\t\tparamsOc = { _id: jsonResponse['_id'],\n\t\t\t\tcliente: jsonResponse['cliente'],\n\t\t\t\tproveedor: jsonResponse['proveedor'],\n\t\t\t\tsku: jsonResponse['sku'],\n\t\t\t\tdireccion: '',\n\t\t\t\tfechaEntrega: jsonResponse['fechaEntrega'],\n\t\t\t\tprecioUnitario: jsonResponse['precioUnitario'],\n\t\t\t\tcantidadDespachada: jsonResponse['cantidadDespachada'],\n\t\t\t\tcantidad: jsonResponse['cantidad'],\n\t\t\t\tcanal: jsonResponse['canal'],\n\t\t\t\tfechaCreacion: jsonResponse['created_at'],\n\t\t\t\testado: jsonResponse['estado']\n\t\t}\n\t\treturn paramsOc\n\tend\nend", "def index\n #data = HTTParty.get(\"http://localhost:8081/customers.json\")\n #p data.parsed_response[0]['email']\n if params[:customerId].present?\n @orders = Order.where(\"customerId\": params[:customerId].to_i)\n render json: @orders, status: 200\n elsif params[:id].present?\n @orders = Order.find_by id: params[:id]\n render json: @orders, status:200\n elsif params[:email].present?\n res = HTTParty.get(\"http://localhost:8081/customers/?email=#{params['email']}\")\n p res\n res = res.parsed_response\n @orders = Order.where(\"customerId\": res['id'].to_i)\n render json: @orders, status:200\n else\n @orders = Order.all\n end\n end", "def get(path)\n request = Net::HTTP::Get.new @uri.path+'/'+path\n request.basic_auth @api_key, ''\n request['User-Agent'] = USER_AGENT\n response = @https.request request\n JSON.parse response.body\n end", "def getApplications(ak)\n uri='https://api.newrelic.com/v2/applications.json'\n parseUrl=URI.parse(uri)\n host=parseUrl.host\n path=parseUrl.path\n getRequest(ak,uri,host,path)\nend", "def req\n \n end", "def get(*args)\n prepare_request(:get, args)\n @@client.add(:get, @path, *args)\n end", "def cmd_get argv\n setup argv\n e = @hash['element']\n response = @api.get(e)\n msg JSON.pretty_generate(response)\n return response\n end", "def index\n @gets = Get.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gets }\n end\n end", "def search_requests( cid )\n url = \"#{self.url}?auth=#{self.authtoken}&cid=#{cid}\"\n status, response = rest_get( url )\n return status, response['details'] if ok?( status ) && response['details']\n return status, ''\n end", "def index\n @http_requests = HttpRequest.order(\"created_at DESC\").page(params[:page]).per(10)\n end", "def get_all_orders() \n\tputs \"Getting all orders\"\n\tresponse = request_get(\"/api/order\")\n\tputs response.body\nend", "def requests\n\t@title = \"Gate Requests\"\n\t@user = User.find(params[:id])\n\t@requests = Relationship.where(:accessed_id => params[:id], :accepted => false)\n\t\n\trender 'requests'\n end", "def request (url_requested, api_key)\n url_builded = url_requested + \"&api_key=\" + api_key\n\n url = URI(url_builded)\n\n https = Net::HTTP.new(url.host, url.port)\n https.use_ssl = true\n\n request = Net::HTTP::Get.new(url)\n\n response = https.request(request)\n\n JSON.parse(response.read_body)\nend", "def list_all_tenantcircles_for_a_version_box(args = {}) \n get(\"/aosversions.json/aosversionbox/circles/#{args[:aosVersionBoxId]}\", args)\nend", "def index\n @bill_cargos = @bill.bill_cargos\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @bill_cargos }\n end\n end", "def index\n @ginasios = Ginasio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ginasios }\n end\n end", "def index\n @contact = current_user.contacts.find(params[:contact_id])\n @requests = @contact.requests\n\n respond_with @requests\n end", "def get(path, query={})\n request_json :get, path, query\n end", "def index\n @distros = getmydata(\"Distro\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @distros }\n end\n end", "def api_request\n url = URI.parse(\"https://catfact.ninja/fact\")\n response = Net::HTTP.get_response(url)\n JSON.parse(response.body)[\"fact\"]\n end", "def make_api_call(args)\n uri = URI(\"https://classes.cornell.edu/api/2.0/search/classes.json?roster=#{args[0]}&subject=#{args[1]}&acadCareer[]=#{args[2]}&classLevels[]=#{args[3]}\")\n begin\n Net::HTTP.start(uri.host, uri.port,\n :use_ssl => uri.scheme == 'https') do |http|\n request = Net::HTTP::Get.new uri\n\n response = http.request request # Net::HTTPResponse object\n hash_response = JSON.parse(response.body)\n hash_response\n end\n rescue JSON::ParserError\n {\"status\": \"Error\"} # Returning an empty hash\n end\nend", "def index\n #@csosns = Csosn.all\n @csosns = Csosn.paginate(:page => params[:page], :per_page => 10)\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @csosns }\n end\n end", "def invoke_request(url)\n site = RestClient::Resource.new(url, \"dHgVM1emGoTyr8zHmVNH\")\n return JSON.parse(site.get(:accept=>\"application/json\"))\nend", "def invoke_request(url)\n site = RestClient::Resource.new(url, \"dHgVM1emGoTyr8zHmVNH\")\n return JSON.parse(site.get(:accept=>\"application/json\"))\nend", "def queryOS(args)\n begin\n p = Hash.new\n uri = URI(args[:entrypoint])\n p[\"header\"] = {'Content-type'=>'application/json','Accept-type'=>'application/json','X-Auth-Token'=>args[:token]}\n case args[:component].to_s\n when \"Nova\"\n p[\"port\"] = uri.port || 8774\n\tp[\"path\"] = uri.path\n when \"Glance\"\n p[\"port\"] = uri.port || 9292\n p[\"path\"] = uri.path || \"/v1\"\n when \"Volume\"\n p[\"port\"] = uri.port || 8776\n\tp[\"path\"] = uri.path\n when \"Swift\" \n p[\"port\"] = uri.port || 8080\n\tp[\"path\"] = uri.path\n when \"Keystone\"\n p[\"port\"] = uri.port || 35357\n p[\"path\"] = uri.path || \"/v2/tokens\"\n when \"Cloud\"\n p[\"port\"] = uri.port || 8773\n p[\"path\"] = uri.path || \"/services/Cloud\"\n p[\"header\"] = {'Content-type'=>'application/xml','Accept-type'=>'application/xml'}\n else\n return false\n end\n p[\"location\"] = uri.host || \"\"\n p[\"path\"] = p[\"path\"] + args[:path] || uri.path\n p[\"request\"] = args[:request] || \"\"\n os = Net::HTTP.new(p[\"location\"],p[\"port\"])\n if uri.scheme == \"https\"\n os.use_ssl = true\n else\n os.use_ssl = false\n end\n resp = nil\n case args[:method].to_s\n when \"post\"\n resp = os.post(p[\"path\"], p[\"request\"], p[\"header\"])\n when \"get\"\n resp = os.get(p[\"path\"], p[\"header\"])\n when \"update\"\n resp = os.put(p[\"path\"], p[\"request\"], p[\"header\"])\n when \"delete\"\n resp = os.delete(p[\"path\"], p[\"header\"])\n end\n newdata = false\n if resp.code.to_i >= 200 and resp.code.to_i < 300\n if args[:component].to_s == \"Cloud\"\n newdata = resp.body\n else\n\t if args[:method].to_s == \"delete\"\n\t newdata = true\n else\n newdata = JSON resp.body\n end\n end\n end\n os = nil\n p = nil\n return newdata\n rescue Errno::EHOSTUNREACH\n false\n end\n end", "def index\n if current_user.has_role? :admin\n @requests = Request.ordered\n else\n @requests = current_user.requests.ordered\n end\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end", "def get(path, params={})\n params = merge_set_up_params(params)\n @token = \"b3688c52-9235-45ca-b01f-c5b2b83a4f4f\"\n @result = Typhoeus::Request.get(API_URL + path, :params => params,\n :headers => {\"Authorization\" => \"Basic#{@token}\"})\n puts @result.body\n # check if the url looks correct in the log\n puts @result.effective_url\n # parse the result to json\n return JSON.parse(@result.body)\n end", "def listJobsForProject(project_mame)\n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/1/jobs')\n params = { 'project' => project_mame }\n headers = {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}\n connection = Excon.new('http://build01:4440/api/1/jobs')\n return connection.get(:query => { 'project' => project_mame },:headers => {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}).body.force_encoding(\"UTF-8\")\n\nend", "def index\n @crate_priorities = CratePriority.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @crate_priorities }\n end\n end", "def get_client_summary_for_tenant(args = {}) \n get(\"/tenants.json/backoffice/clients/summary/#{args[:tenantId]}\", args)\nend", "def request(url, expires_in)\n return [] unless enabled?\n\n response = http.cache(expires_in).get(url)\n return [] if response.status != 200\n JSON.parse(response.to_s.force_encoding(\"utf-8\"))\n end", "def index\n @ctypes = Ctype.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ctypes }\n end\n end", "def index\n @recipies = Recipy.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @recipies }\n end\n end", "def get_jobs_sample(client)\n response = client['jobs'].get\n\n p ''\n p 'Get jobs'\n p response\nend", "def show\n @cerc = Cerc.find(params[:id])\n\n render json: @cerc\n end", "def request\n @req\n end", "def index\n @http_requests = HttpRequest.all\n end", "def requests_get\n @attributes[:requests_get]\n end", "def index\n @request_calls = RequestCall.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @request_calls }\n end\n end", "def index\n if current_client\n @current_client_requests = current_client.requests\n else\n end\n end", "def show\n @cofi = Cofi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cofi }\n end\n end", "def GET; end", "def get(path)\n response = Excon.get(\n 'https://' + @host + '/' + path + '.json?print=pretty',\n headers: {\n 'x-rapidapi-host' => @host,\n 'x-rapidapi-key' => @key,\n }\n )\n\n return false if response.status != 200\n\n JSON.parse(response.body)\n end", "def index\n @crawl_requests = CrawlRequest.all\n \n render json: @crawl_requests\n end", "def index\n @capacites = Capacite.paginate(page: params[:page], per_page: 25)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @capacites }\n end\n end", "def index\n @client_releases = ClientRelease.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @client_releases }\n end\n end", "def getinfo\n request :getinfo\n end", "def index\n @cys_envs = CysEnv.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cys_envs }\n end\n end", "def index\n @crates = Crate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @crates }\n end\n end", "def get(path, params = {})\n path = File.join(@prefix, path)\n JSON.parse @conn.get(path, params).body\n end", "def json_req(uri)\n begin\n resp = RestClient.get(uri, accept: :json)\n rescue RestClient::ExceptionWithResponse => e\n code = e.response.code\n raise RequestError.new(\"failed to retrieve JWK, status #{code}\", code)\n end\n\n JSON.parse resp.body\n end", "def get_request(req)\n m = /GET\\s+KEY=(?<key>\\S+)\\s*/i.match(req)\n return $database[ m[:key] ]\nend" ]
[ "0.6250531", "0.5993591", "0.59115326", "0.5737192", "0.56888354", "0.56508946", "0.56508946", "0.56002825", "0.55560195", "0.5546309", "0.5544354", "0.55347097", "0.5504108", "0.5493895", "0.5487917", "0.5486926", "0.5486926", "0.54837763", "0.5443829", "0.5427351", "0.54142964", "0.54056513", "0.5379063", "0.53746665", "0.5360185", "0.53470504", "0.5338907", "0.5332374", "0.532268", "0.53216463", "0.5312217", "0.5304543", "0.5300069", "0.5298724", "0.52903193", "0.5283968", "0.52802694", "0.52722424", "0.52679795", "0.526772", "0.52606773", "0.52592015", "0.52554756", "0.5250507", "0.52483326", "0.5247246", "0.52461904", "0.5241859", "0.5235518", "0.52326167", "0.52314454", "0.52305514", "0.5230218", "0.5225162", "0.5223764", "0.5218514", "0.5217873", "0.5217785", "0.5215788", "0.52060246", "0.5202463", "0.5200682", "0.51987374", "0.51910347", "0.5190812", "0.5183903", "0.51634127", "0.5159033", "0.5158731", "0.5153489", "0.51498246", "0.51464415", "0.51464415", "0.514346", "0.51425064", "0.5141183", "0.51405394", "0.5140206", "0.5135098", "0.5126997", "0.51235294", "0.51171964", "0.5113972", "0.51105046", "0.5107348", "0.5107285", "0.51062554", "0.5103785", "0.50997216", "0.5091879", "0.5076914", "0.50768286", "0.50761896", "0.50761807", "0.50718117", "0.50699776", "0.5067786", "0.5067448", "0.50591135", "0.50561666", "0.5055869" ]
0.0
-1
POST /reqcargos POST /reqcargos.json
def create @reqcargo = Reqcargo.new(reqcargo_params) respond_to do |format| if @reqcargo.save format.html { redirect_to @reqcargo, notice: 'Reqcargo was successfully created.' } format.json { render :show, status: :created, location: @reqcargo } else format.html { render :new } format.json { render json: @reqcargo.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reqcargo_params\n params.require(:reqcargo).permit(:cargo_id, :nomrequis, :lactivo)\n end", "def add_tenant_circle(args = {}) \n post(\"/tenantcircles.json/\", args)\nend", "def do_coaps_posted_03\n # get the Base64 of the incoming signed request\n body = IO.read(\"spec/files/vr_00-D0-E5-F2-00-03.vrq\")\n\n env = Hash.new\n env[\"SSL_CLIENT_CERT\"] = cbor_clientcert_03\n env[\"HTTP_ACCEPT\"] = \"application/voucher-cose+cbor\"\n env[\"CONTENT_TYPE\"] = \"application/voucher-cose+cbor\"\n\n $FAKED_TEMPORARY_KEY = temporary_key\n post '/e/rv', :params => body, :headers => env\n end", "def do_coaps_posted_02\n # get the Base64 of the incoming signed request\n body = IO.read(\"spec/files/vr_00-D0-E5-F2-00-02.vrq\")\n\n env = Hash.new\n env[\"SSL_CLIENT_CERT\"] = cbor_clientcert_02\n env[\"HTTP_ACCEPT\"] = \"application/voucher-cose+cbor\"\n env[\"CONTENT_TYPE\"] = \"application/voucher-cose+cbor\"\n\n $FAKED_TEMPORARY_KEY = temporary_key\n post '/e/rv', :params => body, :headers => env\n end", "def create_recipe_request(version, auth_headers, data = {})\n post \"/api/recipes\", params: data, headers: {'Content-Type' => \"application/json\", 'Accept' => \"application/vnd.ink.#{version}\" }.merge(auth_headers)\nend", "def index\n @reqcargos = Reqcargo.all\n end", "def cto_params\n params.require(:cto).permit(:cto)\n end", "def post_check(excon, body)\n excon.request(\n method: :post,\n path: '/check',\n headers: { 'Content-Type' => 'application/json' },\n body: body\n )\nend", "def cooco_params\n params.require(:cooco).permit(:content, :user_id)\n end", "def xrf_coc_params\n params.require(:xrf_coc).permit(:date, :turnaround, :xrfunit, :xrfmode, :actionlevel, :abatementlevel, :job_id, :user_id, :job_type, :cli_type)\n end", "def create\n @cargo = Cargo.new(cargo_params)\n if @cargo.save\n render json: @cargo\n else\n render json: @cargo.errors, status: :unprocessable_entity\n end\n end", "def tecnicos_postulados\n coleccion = []\n self.request.each do |request|\n info = {}\n info[:id] = request.id\n info[:article] = request.article\n info[:servicio] = request.service.description\n info[:tecnicos] = request.proposal\n coleccion.append(info)\n end\n coleccion\n end", "def req\n \n end", "def ocs_generada_params\n params.require(:ocs_generada).permit(:oc_request_id, :oc_id, :grupo, :cliente, :proveedor, :sku, :fechaEntrega, :cantidad, :cantidadDespachada, :precioUnitario, :canal, :notas, :urlNotificacion, :estado)\n end", "def couch_params\n params.require(:couch).permit(:marque, :modele, :taille)\n end", "def _build_request resource, request\n admin_token = resource.bootstrap_token\n request.add_field 'X-Auth-Token', admin_token\n request.add_field 'Content-type', 'application/json'\n request.add_field 'user-agent', 'Chef keystone_register'\n request\nend", "def create\n @cooco = Cooco.new(cooco_params)\n\n respond_to do |format|\n if @cooco.save\n format.html { redirect_to @cooco, notice: 'Cooco was successfully created.' }\n format.json { render :show, status: :created, location: @cooco }\n else\n format.html { render :new }\n format.json { render json: @cooco.errors, status: :unprocessable_entity }\n end\n end\n end", "def json\n Oj.to_json(@req)\n end", "def ccosto_params\n params.require(:ccosto).permit(:code, :name, :comments)\n end", "def build_request(*args); end", "def create\n\t\turi = URI.parse(Counter::Application.config.simplyurl)\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\t\n\t\trequest = Net::HTTP::Post.new('/offsets.json')\n\t\tputs params\n\t\tputs params.slice(*['custids','acctids','itemids'])\n\t\t\n\t\t# ok, this join stuff is bogus - it encodes properly, but the other side only sees the last element and loses the array type - it's just string\n\t\t# this way, i 'split' it at the other side to recover my array\n\t\t# it should work without the join/split crap, but it doesn't\n\t\trequest.set_form_data({:custids => ( params['custids'] || []).join(','), :acctids => ( params['acctids'] || []).join(','), :itemids => ( params['itemids'] || []).join(','), :amount => params['amount'], :type => params['type']})\n\t\t\n\t\tputs request.body\n\t\t\n\t\tresponse = http.request(request)\n\t\tputs response.body\n\n respond_to do |format|\n format.html { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n format.json { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n end\n end", "def _build_request resource, request\n admin_token = resource.bootstrap_token\n request.add_field 'X-Auth-Token', admin_token\n request.add_field 'Content-type', 'application/json'\n request.add_field 'user-agent', 'Chef keystone_credentials'\n request\nend", "def cotizacione_params\n params.require(:cotizacione).permit(:token, :paqueteria, :producto, :precio)\n end", "def set_reqcargo\n @reqcargo = Reqcargo.find(params[:id])\n end", "def send_request(path,arg = {})\n url= URI.parse(@@api_root + @@resources[path].to_s)\n post_arg = {'devKey'=>@dev_key , 'headers'=>@header_string }\n post_arg.merge!(arg)\n res = Net::HTTP.post_form(url, post_arg)\n end", "def req_params\n params.require(:req).permit(:dbr_id,\n :req_number, \n :fiscal_year, \n :create_by_org, \n :status, \n :operating_entity, \n :title, \n :pec, \n :sag, \n :panel, \n :majcom_panel, \n :majcom_directorate, \n :eeic, \n :object_class, \n :esp, \n :rccc, \n :aai, \n :req_total, \n :funding_secured, \n :authorized_amount, \n :owner_priority, \n :grp, \n :unit, \n :final_FY, \n :pop_start_date, \n :pop_end_date, \n :method_of_purchase, \n :priority_level, \n :budget_authority, \n :needby_date, \n :contract_number, \n :reviewed_by, \n :point_of_contact,\n :installation,\n answers_attributes: [\n :question_id,\n :id,\n :text,\n :boolean,\n :answer\n ]\n )\n end", "def create_kyc_using_post_with_http_info(kyc_request_co, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: KYCApi.create_kyc_using_post ...'\n end\n # verify the required parameter 'kyc_request_co' is set\n if @api_client.config.client_side_validation && kyc_request_co.nil?\n fail ArgumentError, \"Missing the required parameter 'kyc_request_co' when calling KYCApi.create_kyc_using_post\"\n end\n # resource path\n local_var_path = '/kyc'\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['*/*'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(kyc_request_co)\n auth_names = ['oauth2']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'KycResponseVo')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: KYCApi#create_kyc_using_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create(args) \n help_form = {:tNote => args[:note],\n :xCategory => args[:category],\n :sFirstName => args[:first_name],\n :sLastName => args[:last_name],\n :sUserId => args[:user_id],\n :sEmail => args[:email],\n :sPhone => args[:phone],\n :fUrgent => args[:urgent]}.reject!{|k,v| v == nil}\n \n JSON.parse(api_request('request.create', 'POST', help_form))['xRequest'] rescue []\n end", "def cuota_curso_params\n params.require(:cuota_curso).permit(:nombre, :descripcion)\n end", "def caixa_params\n params.require(:caixa).permit(:data, :responsavel, :status)\n end", "def create\n response = post_request(URI.parse(\"http://\"+Storage.find(cookies[:donabe_ip]).data+\"/\"+Storage.find(cookies[:current_tenant]).data+\"/containers.json\"), params[:container].to_json, Storage.find(cookies[:current_token]).data)\n json_respond response.body \n\n end", "def cncoperation_params\n params.require(:cncoperation).permit(:operation_name, :description, :plan_status, :cncjob_id, :tenant_id)\n end", "def cf_curl(*args)\n output = capture('cf', 'curl', *args)\n JSON.parse output\nend", "def create\n @oncokb = Oncokb.new(oncokb_params)\n\n respond_to do |format|\n if @oncokb.save\n format.html { redirect_to @oncokb, notice: 'Oncokb was successfully created.' }\n format.json { render :show, status: :created, location: @oncokb }\n else\n format.html { render :new }\n format.json { render json: @oncokb.errors, status: :unprocessable_entity }\n end\n end\n end", "def request_params\n params.require(:request).permit( :description, :completed, :user_id, :auto_id, service:[])\n end", "def cocktail_params\n params.require(:cocktail).permit(:name, :ingredients, :doses)\n end", "def request_json\n @request.headers[\"Content-Type\"] = 'application/json'\n @request.headers[\"Accept\"] = 'application/json'\n end", "def caso_params\n params.require(:caso).permit(:fecha, :titulo,\n :caso_presponsable_attributes => [\n :id, :id_presponsable, :otro, :_destroy\n ]\n )\n end", "def concert_params\n params.require(:concert).permit(:title, :description, :cdatetime, :location_name, :ccity, :buy_tickets_website)\n end", "def cupo_params\n params.require(:cupo).permit(:parqueadero_id, :tipo_de_cupo_id, :cantidad)\n end", "def generate_request\r\n end", "def create\n @congresso = Congresso.new(congresso_params)\n\n respond_to do |format|\n if @congresso.save\n format.html { redirect_to @congresso, notice: 'Congresso was successfully created.' }\n format.json { render :show, status: :created, location: @congresso }\n else\n format.html { render :new }\n format.json { render json: @congresso.errors, status: :unprocessable_entity }\n end\n end\n end", "def circus_params\n params.require(:circus).permit(:name, :flea_ids => [])\n end", "def exec_post(req, data, exit_on_fail = false)\n response_hash = exec_api_call('POST', req, data, exit_on_fail)\n response_hash[:response]\n end", "def post_request(options, path, post_data)\n\n result = {}\n\n http = Net::HTTP.new(ENV['NESSUS_HOST'], options[:port])\n http.use_ssl = @use_ssl\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n http.start do |http|\n req = Net::HTTP::Post.new(path)\n\n req['X-ApiKeys'] = \"accessKey=#{ENV['NESSUS_ACCESS_KEY']}; secretKey=#{ENV['NESSUS_SECRET_KEY']}\"\n req.body = post_data\n \n resp, data = http.request(req)\n \n if resp.code.eql? '200'\n #print \"Data: \" + JSON.pretty_generate(JSON.parse(resp.body.to_s))\n result = JSON.parse(resp.body.to_s)\n else\n puts \"Error: \" + resp.code.to_s + \"\\n\" + resp.body\n end\n end\n\n return result\n end", "def create\n @cerc = Cerc.new(params[:cerc])\n\n if @cerc.save\n render json: @cerc, status: :created, location: @cerc\n else\n render json: @cerc.errors, status: :unprocessable_entity\n end\n end", "def create\n response = post_request(URI.parse(\"http://\"+(sesh :donabe_ip)+\"/\"+(sesh :current_tenant)+\"/containers.json\"), params[:container].to_json, (sesh :current_token))\n json_respond response.body \n\n end", "def cta_cte_params\n params.require(:cta_cte).permit(:matriculacion_id, :nro_cta_cte)\n end", "def ciclistum_params\n params.require(:ciclistum).permit(:cic_run, :cic_cant_rep, :cic_cant_den, :cic_fono, :cic_estado, :usuario_id)\n end", "def corrida_params\n params.require(:corrida).permit(:fechaInicio, :fechaFin, :estado)\n end", "def send_request(req); end", "def resto_params\n params.require(:resto).permit(:name, :address, :contact, :cuisine_id)\n end", "def recibir_oc\n begin\n logger.debug(\"...Inicio recibir oc\")\n id_order = params.require(:idoc)\n url = Rails.configuration.oc_api_url + \"obtener/\" + id_order\n request = Typhoeus::Request.new(\n url, \n method: :get,\n headers: { ContentType: \"application/json\"})\n response = request.run\n oc_order = JSON.parse(response.body)[0]\n product = Product.where('sku = ?',oc_order['sku']).first\n if product.nil?\n OrdersController.new.rechazar_oc(id_order,'No hay producto en existencia')\n data_result = {:aceptado => false, :idoc => id_order }\n #Spawnling.new do\n # sleep(5)\n # logger.info('#####_produccion')\n #end\n else\n total = consultar_stock(oc_order['sku'])\n if(oc_order['cantidad'] < total) \n response_recep = OrdersController.new.recepcionar_oc(id_order)\n if response_recep[:status] \n \n ###### Guardamos datos orden localmente ######\n order_obj = Order.create!({\n :_id => oc_order['_id'], \n :canal => oc_order['canal'],\n :proveedor => oc_order['proveedor'], \n :cliente => oc_order['cliente'],\n :sku => oc_order['sku'].to_i, \n :cantidad => oc_order['cantidad'].to_i, \n :cantidadDespachada => oc_order['cantidadDespachada'].to_i,\n :precioUnitario => oc_order['precioUnitario'].to_i, \n :fechaEntrega => oc_order['fechaEntrega'],\n :fechaDespachos => oc_order['fechaDespachos'], \n :estado => oc_order['estado'],\n :tipo => 1\n })\n response_inv = InvoicesController.new.emitir_factura(id_order)\n if response_inv[:status]\n result = response_inv[:result]\n ##### Guardamos factura localmente #####\n factura_obj = Factura.create!({\n :_id => result['_id'], \n :bruto => result['bruto'].to_f,\n :iva => result['iva'].to_f, \n :total => result['total'].to_f,\n\t\t :order_id => order_obj['id'] })\n Spawnling.new do\n enviar_factura(result)\n end\n data_result = {:aceptado => true, :idoc => id_order}\n else\n OrdersController.new.rechazar_oc(id_order,'OC invalida')\n data_result = {:aceptado => false, :idoc => id_order }\n end \n else\n OrdersController.new.rechazar_oc(id_order,'No hay producto en existencia')\n data_result = {:error => response_recep [:result], :aceptado => false, :idoc => id_order}\n end\n else\n OrdersController.new.rechazar_oc(id_order,'No hay producto en existencia')\n data_result = {:aceptado => false, :idoc => id_order }\n end\n end\n logger.debug(\"...Fin recibir oc\")\n respond_to do |format|\n format.json { render json: data_result}\n format.html { render json: data_result }\n end\n rescue => ex\n Applog.debug(ex.message,'recibir_oc')\n respond_to do |format|\n format.json { render json: {:aceptado => false}}\n format.html { render json: {:aceptado => false}}\n end\n end\nend", "def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end", "def trein_consul_comercial_params\n params.require(:trein_consul_comercial).permit(:estatus, :data, :interessado_id)\n end", "def consorciot_params\n params.require(:consorciot).permit(:nombre, :abrebiatura, :telefono)\n end", "def build\n CircleCi.request(conf, base_path).post\n end", "def post_evaluate(excon, body)\n excon.request(\n method: :post,\n path: '/evaluate',\n headers: { 'Content-Type' => 'application/json' },\n body: body\n )\nend", "def termination_request_params\n params[:termination_request].permit! #allow all parameters for now\n end", "def create\n @request = Request.new(request_params)\n @request.user_id = current_user.id\n @request.assign_json_attributes(params) if @request.resume?\n\n respond_to do |format|\n if @request.save\n @request.set_folio\n format.html { redirect_to @request, notice: 'Request was successfully created.' }\n format.json { render :show, status: :created, location: @request }\n else\n format.html { render :new }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def concert_params\n params.require(:concert).permit(:concert_name, :source, :done, :image, :tm_id, :local_date, :date, :timezone, :venue_id, :origin)\n end", "def post_json(path, body)\n uri = build_uri(path)\n #puts \"🤖 POST #{path}\"\n #puts JSON.pretty_generate(body)\n\n post_request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')\n post_request.body = JSON.generate(body)\n\n response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|\n http.request(post_request)\n end\n\n #puts \"HTTP #{response.code}\"\n result = JSON.parse(response.body)\n #puts result[:result]\n result\nend", "def create_kyc_using_post(kyc_request_co, opts = {})\n data, _status_code, _headers = create_kyc_using_post_with_http_info(kyc_request_co, opts)\n data\n end", "def cncoperation_params\n params.require(:cncoperation).permit!\n end", "def recla_params\n params.require(:recla).permit(:reclamo, :tienda, :cliente_id)\n end", "def cio_params\n params.require(:cio).permit(:data_cio, :animal_id, cobertura_attributes: [:animal_id])\n end", "def prod_coti_params\n params.require(:prod_coti).permit(:cod_cotiza, :cod_producto)\n end", "def create_json_request(code)\n parameters = {\n \t\"code\" => code,\n\t\"level\" => self.level,\n\t\"format\" => \"json\",\n\t\"info\" => self.op\n }\n end", "def create\n @couch = Couch.new(couch_params)\n\n respond_to do |format|\n if @couch.save\n format.html { redirect_to @couch, notice: 'Couch was successfully created.' }\n format.json { render :show, status: :created, location: @couch }\n else\n format.html { render :new }\n format.json { render json: @couch.errors, status: :unprocessable_entity }\n end\n end\n end", "def submit_order()\n\tputs \"Submitting order\"\n\tdata = create_order()\n\tresponse = request_post(\"/api/order\", data)\n\tputs response.body\nend", "def crediario_params\n params.require(:crediario).permit(:client_id, :amount, :emission, :maturity, :doc_number, :printed, :status)\n end", "def create\n @consorciot = Consorciot.new(consorciot_params)\n\n respond_to do |format|\n if @consorciot.save\n format.html { redirect_to @consorciot, notice: 'Consorciot was successfully created.' }\n format.json { render :show, status: :created, location: @consorciot }\n else\n format.html { render :new }\n format.json { render json: @consorciot.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cto = Cto.new(cto_params)\n\n respond_to do |format|\n if @cto.save\n format.html { redirect_to @cto, notice: 'Cto was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cto }\n else\n format.html { render action: 'new' }\n format.json { render json: @cto.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(path, data = {})\n request 'POST', path, body: data.to_json\n end", "def cuota_params\n params.require(:cuota_clientes).permit(:cantidad_cuota, :estado, :intereses, :monto_cuota, :monto_pagado, :vencimiento, :credito_cliente_id )\n\nend", "def prepare_doc(req, json)\n var = requestor(req, json)\n parse var.body\n end", "def cuenta_params\n params.require(:cuenta).permit(:cliente_id, :nombre, :dirpostal_id, :tpago_id, :timpagado_id, :tvencimiento_id, :tenvio_id)\n end", "def putFactura(oc)\n\n facturax= JSON.parse(HTTP.headers(:\"Content-Type\" => \"application/json\").put(\"http://\"+ $url +\"/facturas/\", :json => {:oc => oc}).to_s, :symbolize_names => true)\n return facturax\n end", "def post_to_cc(data)\n post_args = { \n 'js_code' => data[\"code\"],\n 'compilation_level' => data[\"level\"],\n 'output_format' => data[\"format\"],\n 'output_info' => data[\"info\"]\n }\n\n if $debug\n puts \"#DEBUG post_args \\n\"\n p post_args\n puts \"\\n\"\n end\n\n # send the request\n resp, data = Net::HTTP.post_form(URI.parse(GOOGLE_SERVICE_ADDRESS), post_args)\n end", "def cachorro_params\n params.require(:cachorro).permit(:nome, :data_de_nascimento, :data_aproximada, :porte, :sexo, :saude, :temperamento, :foto, :equipamento, :dupla_para_passeio_id, :frequencia_de_passeio, :tempo_de_passeio, :habilitado_para_passeio)\n end", "def post_json(path, body)\n uri = build_uri(path)\n puts \"*** POST #{path}\"\n puts JSON.pretty_generate(body)\n\n post_request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')\n post_request.body = JSON.generate(body)\n\n response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|\n http.request(post_request)\n end\n\n puts \"HTTP #{response.code}\"\n result = JSON.parse(response.body)\n puts JSON.pretty_generate(result)\n result\nend", "def casa_params\n params.require(:casa).permit(:metragem, :local, :dormitorios, :suites, :banheiro, :garagem, :preco, :condominio, :desconto_num)\n end", "def create\n @ccosto = Ccosto.new(ccosto_params)\n\n respond_to do |format|\n if @ccosto.save\n format.html { redirect_to @ccosto, notice: 'Ccosto was successfully created.' }\n format.json { render :show, status: :created, location: @ccosto }\n else\n format.html { render :new }\n format.json { render json: @ccosto.errors, status: :unprocessable_entity }\n end\n end\n end", "def request_body\n request_body = {\n :active => 'true',\n :category => 'Other',\n :subcategory => 'Other',\n :u_service_provider => 'Duke University',\n :u_it_service => 'Public Computing Labs',\n :service_offering => 'Public Computing Labs Offering',\n :contact_type => 'email',\n :description => 'This is the lengthier description!',\n :impact => 'Individual',\n :urgency => 'Medium',\n :priority => 'Low',\n :incident_state => 'New',\n :notify => '1',\n :state => '1',\n :assignment_group => 'Service Desk-OIT',\n :short_description => 'This is the title of the the ticket!',\n :caller_id => CALLER\n }\n end", "def ocorrencia_params\n params.require(:ocorrencia).permit(:ocolocal, :ocostatus, :ocomunicipio, :ocosentido, :ocodataocorrencia, :ocodataregistro, :ocotipo, :ococomid, :ocoidorigem, :ococpfretif, :ococpfretif)\n end", "def cofre_params\n params.require(:cofre).permit(:data, :dineiro, :moeda, :chqvista, :dolares, :euros)\n end", "def cargo_params\n params.require(:cargo).permit(:nome, :descricao)\n end", "def couch_params\n params.require(:couch).permit(:name, :couchTypeID, :description, :location, :dateBegin, :dateEnd, :maxHosts, :image)\n end", "def citacao_params\n params.require(:citacao).permit(:trecho, :pagina_inicial, :palavras_chave, :livro_id)\n end", "def create\n @prod_coti = ProdCoti.new(prod_coti_params)\n\n respond_to do |format|\n if @prod_coti.save\n format.html { redirect_to @prod_coti, notice: 'Prod coti was successfully created.' }\n format.json { render :show, status: :created, location: @prod_coti }\n else\n format.html { render :new }\n format.json { render json: @prod_coti.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @req = Req.new(req_params)\n @req.office = current_user.office\n @req.user = current_user\n\n\n respond_to do |format|\n if @req.save\n flash[:notice] = \"Your requirement has been saved\"\n format.html { redirect_to @req }\n format.json { render :show, status: :created, location: @req }\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @req.errors, status: :unprocessable_entity }\n end\n end\n end", "def cta_params\n params.require(:cta).permit(:cta1_header, :cta1_caption, :cta1_url, :cta1_button, :cta2_header, :cta2_caption, :cta2_url, :cta2_button, :cta3_header, :cta3_caption, :cta3_url, :cta3_button)\n end", "def req_ord_params\n params.require(:req_ord).permit(:uuid, :matkl, :status, :ord_no, :ord_at, :due_at, :ex_curr, :ex_rate, :subject, :remark, :req_by, :req_remark, :sent_by, :sent_at, :sent_ip, :reply_at, :sent_cnt, :reply_cnt, :creator, :updater, :approver, :finish_at, {werkss: []}, :vtweg, :matgrp, :matgrp_id)\n end", "def corpu_params\n params.require(:corpu).permit(:name, :description, :end_date_build, :building_id)\n end", "def request(*args); end", "def create(url, data)\n RestClient.post ENV['APIBASE']+url, data, :content_type => :json\nend", "def ciclo_params\n params.require(:ciclo).permit(:nomeciclo, :numerociclo, :valorciclo, :qtdreentradas, :qtdreentradasparareentradas)\n end", "def concert_params\n params.fetch(:concert, {}).permit(:title, :artist, :location, :start_time, :end_time, :seats, :ticket_price, :date, :quantity, :email)\n end", "def test_client_post\n client = CoAP::Client.new\n answer = client.post('coap.me', 5683, '/test', 'TD_COAP_CORE_04')\n assert_equal(2, answer.mcode[0])\n assert_equal(1, answer.mcode[1])\n assert_equal('POST OK', answer.payload)\n end", "def cartella_clinica_params\n params.require(:cartella_clinica).permit(:diagnosi, :valutazione_anatomica, :valutazione_funzionale, :iniziale_finale, :anamnesi, :paziente_id, :data, :chiave)\n end" ]
[ "0.5948494", "0.58488387", "0.5842652", "0.5673049", "0.5657613", "0.5448429", "0.544024", "0.5406381", "0.53049535", "0.5302718", "0.52997845", "0.52974343", "0.5248637", "0.52108425", "0.5198508", "0.5189851", "0.51875246", "0.51829207", "0.51804996", "0.51787615", "0.51628685", "0.5153064", "0.5129409", "0.51195735", "0.51031476", "0.50732124", "0.50624466", "0.5051397", "0.50486034", "0.5047594", "0.50437033", "0.5041312", "0.5039578", "0.5017249", "0.5012108", "0.500934", "0.49970025", "0.49967396", "0.49961677", "0.49886355", "0.498164", "0.4975429", "0.49753347", "0.49698633", "0.49602643", "0.49566984", "0.49551916", "0.49551848", "0.49425092", "0.4941178", "0.49291316", "0.4923306", "0.4922301", "0.49222416", "0.49175254", "0.49165273", "0.49133983", "0.4909014", "0.49024108", "0.48994526", "0.4897508", "0.48949778", "0.4894941", "0.48915184", "0.48875898", "0.48869187", "0.48828992", "0.48827016", "0.48691148", "0.4868711", "0.4868414", "0.48670727", "0.48586985", "0.48581457", "0.4856657", "0.48525974", "0.48464072", "0.48424116", "0.48407754", "0.48406595", "0.48383257", "0.48370925", "0.4831862", "0.48316535", "0.48300794", "0.48265186", "0.48263916", "0.48244947", "0.4813286", "0.48119065", "0.48118708", "0.48103598", "0.48101133", "0.48054537", "0.48001927", "0.47963473", "0.47963417", "0.47896555", "0.47892907", "0.4788636" ]
0.63217616
0
PATCH/PUT /reqcargos/1 PATCH/PUT /reqcargos/1.json
def update respond_to do |format| if @reqcargo.update(reqcargo_params) format.html { redirect_to @reqcargo, notice: 'Reqcargo was successfully updated.' } format.json { render :show, status: :ok, location: @reqcargo } else format.html { render :edit } format.json { render json: @reqcargo.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def patch!\n request! :patch\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end", "def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end", "def update\n# respond_to do |format|\n# if @req.update(req_params)\n format.json { render :json => {:status => 'success'}}\n# format.html { redirect_to @req, notice: 'Req was successfully updated.' }\n# format.json { render :show, status: :ok, location: @req }\n# else\n format.json { render :json => {:status => 'failed'}}\n# format.html { render :edit }\n# format.json { render json: @req.errors, status: :unprocessable_entity }\n# end\n# end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def rm_update path, data, msg\n\n re = rm_request path, data, 'PUT'\n puts re.body\n chk (re.code!='200'), msg + \"\\n#{re.code} #{re.msg}\\n\\n\"\n return true\n\nend", "def put!\n request! :put\n end", "def patch(path, **args); end", "def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end", "def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end", "def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end", "def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end", "def patch(path, data, params = {}, request_options = {})\n request(:patch, path, data, params)\n end", "def patch\n req.patch?\n end", "def patch(path, params = {})\n request(:patch, path, params)\n end", "def patch(path, params = {})\n request(:patch, path, params)\n end", "def update\n @request.assign_json_attributes(params) if @request.resume?\n respond_to do |format|\n if @request.update(request_params)\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { render :show, status: :ok, location: @request }\n else\n format.html { render :edit }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @req.update(req_params)\n flash[:notice] = \"Your requirement has been saved\"\n format.html { redirect_to @req }\n format.json { render :show, status: :ok, location: @req }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @req.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, opts = {})\n request(:patch, path, opts).body\n end", "def patch(type, info)\n path, info = type_info(type, :path), force_case(info)\n ida = type == :client ? 'client_id' : 'id'\n raise ArgumentError, \"info must include #{ida}\" unless id = info[ida]\n hdrs = headers\n if info && info['meta'] && (etag = info['meta']['version'])\n hdrs.merge!('if-match' => etag)\n end\n reply = json_parse_reply(@key_style,\n *json_patch(@target, \"#{path}/#{Addressable::URI.encode(id)}\", info, hdrs))\n\n # hide client endpoints that are not quite scim compatible\n type == :client && !reply ? get(type, info['client_id']): reply\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def update\n respond_to do |format|\n if @reqstatus.update(reqstatus_params)\n format.html { redirect_to @reqstatus, notice: 'Reqstatus was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @reqstatus.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def put(*args)\n request :put, *args\n end", "def http_put(path, data, content_type = 'application/json')\n http_methods(path, :put, data, content_type)\n end", "def patch\n end", "def patch(operation, path, value = nil)\n ensure_client && ensure_uri\n body = {\n 'op' => operation,\n 'path' => path,\n 'value' => value\n }\n response = @client.rest_patch(@data['uri'], { 'Content-Type' => 'application/json-patch+json', 'body' => [body] }, @api_version)\n @client.response_handler(response)\n end", "def update\n @treq = Treq.find(params[:id])\n\n respond_to do |format|\n unless params[:treq_files].blank?\n params[:treq_files]['file'].each do |a|\n @treq_file = @treq.treq_files.create!(:file => a, :treq_id => @treq.id)\n end\n end\n if @treq.update_attributes(params[:treq])\n format.html { redirect_to @treq, notice: 'Treq was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @treq.errors, status: :unprocessable_entity }\n end\n end\n end", "def update # PATCH\n raise NotImplementedError\n end", "def update!(**args)\n @client = args[:client] if args.key?(:client)\n @list_update_requests = args[:list_update_requests] if args.key?(:list_update_requests)\n end", "def update(&block)\n validate_request()\n\n # Params includes all of the PATCH data at the top level along with other\n # other Rails-injected params like 'id', 'action', 'controller'. These\n # are harmless given no namespace collision and we're only interested in\n # the 'Operations' key for the actual patch data.\n #\n render(json: yield(self.safe_params()[:id], self.safe_params().to_hash()))\n end", "def update\n @request_for_change.set_manager(force: true)\n @request_for_change.set_security_officer(force: true)\n\n respond_to do |format|\n if @request_for_change.update(request_for_change_params)\n format.html { redirect_to edit_request_for_change_path(@request_for_change), notice: 'Request for change was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @request_for_change.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(request)\n request.method = :patch\n request.call\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def update\n respond_to do |format|\n if @reqpriority.update(reqpriority_params)\n format.html { redirect_to @reqpriority, notice: 'Reqpriority was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @reqpriority.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_todo.update(api_v1_todo_params)\n format.json { render json: @api_v1_todo, status: :ok }\n else\n format.json { render json: @api_v1_todo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def update\n @request = Request.find(params[:id])\n\n if @request.update(params[:request])\n head :no_content\n else\n render json: @request.errors, status: :unprocessable_entity\n end\n end", "def patch(path, body_params = {})\n debug_log \"PATCH #{@host}#{path} body:#{body_params}\"\n headers = { 'Content-Type' => 'application/json' }\n res = connection.run_request :put, path, body_params.to_json, headers\n debug_log \"Response status:#{res.status}, body:#{res.body}\"\n res\n end", "def update\n # { clinic: {id: references, \"license_id\"=>nil, \"name\"=>string } }\n \n if @clinic.update_attributes(params[:clinic].except(:api_license_id))\n head :no_content\n else\n render json: clinic.errors.full_messages, status: :unprocessable_entity\n end\n end", "def update\n @request = Request.find(params[:id])\n\n respond_to do |format|\n if @request.update_attributes(params[:request])\n format.html { redirect_to @request, :notice => 'Request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @request.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update(request)\n end", "def update(request)\n end", "def update\n #respond_to do |format|\n # if @request.update(request_params)\n # format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n # format.json { head :no_content }\n # else\n # format.html { render action: 'edit' }\n # format.json { render json: @request.errors, status: :unprocessable_entity }\n # end\n #end\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def patch(path, data, options = {})\n uri = build_uri(path, options)\n\n request = Net::HTTP::Patch.new(uri.request_uri)\n set_authorisation_header(request)\n request.set_form_data(data)\n\n response = https_client(uri).request(request)\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update!(**args)\n @request_id = args[:request_id] if args.key?(:request_id)\n @resource_info = args[:resource_info] if args.key?(:resource_info)\n @validate_only = args[:validate_only] if args.key?(:validate_only)\n end", "def patch(path, params)\n time(\"PATCH #{path}\") { Cloudflarer.new.patch(path, params) }\n end", "def update\n @request = Request.find(params[:id])\n\n respond_to do |format|\n if @request.update_attributes(params[:request])\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @request = Request.find(params[:id])\n\n respond_to do |format|\n if @request.update_attributes(params[:request])\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(*args)\n request(:put, *args)\n end", "def patch(path, opts = {}, &block)\n request(:patch, path, opts, &block)\n end", "def patch(path, opts = {}, &block)\n request(:patch, path, opts, &block)\n end", "def update_request?(http_method = nil)\n http_method = http_method.downcase.to_sym if http_method.is_a?(String)\n %i[put post patch].include?(http_method || @verb)\n end", "def update\n respond_to do |format|\n if @request.update(request_params)\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :edit }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @request = Request.find(params[:id])\n\n respond_to do |format|\n if @request.update_attributes(params[:request])\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @request = Request.find(params[:id])\n\n respond_to do |format|\n if @request.update_attributes(params[:request])\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch_kubernetes_version_with_http_info(moid, kubernetes_version, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: KubernetesApi.patch_kubernetes_version ...'\n end\n # verify the required parameter 'moid' is set\n if @api_client.config.client_side_validation && moid.nil?\n fail ArgumentError, \"Missing the required parameter 'moid' when calling KubernetesApi.patch_kubernetes_version\"\n end\n # verify the required parameter 'kubernetes_version' is set\n if @api_client.config.client_side_validation && kubernetes_version.nil?\n fail ArgumentError, \"Missing the required parameter 'kubernetes_version' when calling KubernetesApi.patch_kubernetes_version\"\n end\n # resource path\n local_var_path = '/api/v1/kubernetes/Versions/{Moid}'.sub('{' + 'Moid' + '}', CGI.escape(moid.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n content_type = @api_client.select_header_content_type(['application/json', 'application/json-patch+json'])\n if !content_type.nil?\n header_params['Content-Type'] = content_type\n end\n header_params[:'If-Match'] = opts[:'if_match'] if !opts[:'if_match'].nil?\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(kubernetes_version)\n\n # return_type\n return_type = opts[:debug_return_type] || 'KubernetesVersion'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']\n\n new_options = opts.merge(\n :operation => :\"KubernetesApi.patch_kubernetes_version\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: KubernetesApi#patch_kubernetes_version\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update\n @reqinfo = Reqinfo.find(params[:id])\n\n respond_to do |format|\n if @reqinfo.update_attributes(params[:reqinfo])\n flash[:notice] = 'Reqinfo was successfully updated.'\n format.html { redirect_to(@reqinfo) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @reqinfo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def api_put(path, data = {})\n api_request(:put, path, :data => data)\n end", "def patch request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n uri, body, query_string_params = transcode_patch_request request_pb\n response = @client_stub.make_patch_request(\n uri: uri,\n body: body,\n params: query_string_params,\n options: options\n )\n result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, response if block_given?\n result\n end", "def patch request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n uri, body, query_string_params = transcode_patch_request request_pb\n response = @client_stub.make_patch_request(\n uri: uri,\n body: body,\n params: query_string_params,\n options: options\n )\n result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, response if block_given?\n result\n end", "def patch(operation, path, value)\n response = @client.rest_patch(@data['uri'], 'body' => [{ op: operation, path: path, value: value }])\n @client.response_handler(response)\n end", "def patch(action, **args); end", "def update\n # actions\n path = URI(@endpoint).path\n action = URI(@req.request_uri).path.sub(path, '').split('/')\n action -= ['']\n if action.include?('_history')\n @actions = [action[0], '_history']\n else\n @actions = [action[0]]\n end\n\n # search param\n req_query = URI(@req.request_uri).query\n unless req_query.nil?\n @req_params = URI::decode_www_form(req_query).to_h\n end\n\n # requst method\n if @req.request_method == \"GET\" and @actions.include? '_history'\n @req_method = 'vread'\n elsif @req.request_method == \"GET\" and @req_params != nil\n @req_method = 'search-type'\n elsif @req.request_method == \"PUT\"\n @req_method = 'update'\n elsif @req.request_method == \"POST\"\n @req_method = 'create'\n else\n @req_method = 'read'\n end\n\n # interaction\n int1 = Interaction.last type: @actions[0], code: @req_method\n if int1.nil?\n @present = 0\n else\n @present = int1.id\n @intCode = int1.valueCode\n end\n end", "def update!(**args)\n @client_id = args[:client_id] if args.key?(:client_id)\n @recurrence = args[:recurrence] if args.key?(:recurrence)\n @recurrence_id = args[:recurrence_id] if args.key?(:recurrence_id)\n @server_id = args[:server_id] if args.key?(:server_id)\n end", "def rm_request path, data = nil,method = nil, verbose = false\n reply = nil\n hdrs = {'Content-Type'=>'application/json', 'X-Redmine-API-Key' => $settings['redmine_api_key']}\n reply = Net::HTTP.start($settings['redmine_host'], $settings['redmine_port']) do |http|\n if data\n if !method || method == 'POST'\n puts \"POST #{path}\" if verbose\n http.request_post(path,data.to_json, hdrs)\n elsif method == 'PUT'\n # code for PUT here\n puts \"PUT #{path}\" if verbose\n http.send_request 'PUT', path, JSON.unparse(data), hdrs\n end\n else\n puts \"GET #{path}\" if verbose\n http.request_get(path, hdrs)\n end\n end\n return reply\nend", "def update(attrs, path=nil)\n resp = api_client.put(path || url, JSON.dump(attrs))\n refresh(JSON.load(resp.body))\n end", "def rest_patch(base_uri,json_payload,params)\n begin\n @response = RestClient.patch(base_uri,json_payload,params)\n rescue => e\n puts @response.code\n end\n return @response\n end", "def patch(path, to: nil, as: nil, **constraints, &blk)\n add_route(::Rack::PATCH, path, to, as, constraints, &blk)\n end", "def update\n respond_to do |format|\n if @request.update(request_params)\n format.html { redirect_to @request, notice: 'request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\t@request = Request.unscoped.find(params[:id])\n\n\t\trespond_to do |format|\n\t\t\tif @request.update_attributes( update_request_params )\n\t\t\t\tformat.json { render json: @request, status: :created }\t\t\t\t\n\t\t\telse\n\t\t\t\tformat.json { render json: @request.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def update\n request = Request.find_by_id(params[:id])\n if request\n request.status = 1\n if request.save\n render json: {\n status: 'success',\n message: 'Request marked as fulfilled',\n },\n status: :ok\n else\n render json: {\n status: 'error',\n message: 'Request failed',\n data: request.errors,\n },\n status: :unprocessable_entity\n end\n else\n render status: :unauthorized\n end\n end", "def update\n respond_to do |format|\n if @cto.update(cto_params)\n format.html { redirect_to @cto, notice: 'Cto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @update_photo_requests = args[:update_photo_requests] if args.key?(:update_photo_requests)\n end", "def update!(**args)\n @request_metadata = args[:request_metadata] if args.key?(:request_metadata)\n end", "def update!(**args)\n @request_metadata = args[:request_metadata] if args.key?(:request_metadata)\n end", "def update!(**args)\n @request_metadata = args[:request_metadata] if args.key?(:request_metadata)\n end", "def update!(**args)\n @request_metadata = args[:request_metadata] if args.key?(:request_metadata)\n end", "def patch(uri, options = T.unsafe(nil)); end", "def update\n #@service_request = ServiceRequest.find(params[:id])\n\n respond_to do |format|\n if @service_request.update_attributes(service_request_params)\n format.html { redirect_to @service_request, notice: 'Service request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update attrs\n put '', :body => {self.class.api_name => self.class.opts_to_query_opts(attrs)}\n end", "def update\n respond_to do |format|\n if @http_request.update(http_request_params)\n format.html { redirect_to @http_request, notice: 'Http request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @http_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @http_request.update(http_request_params)\n format.html { redirect_to @http_request, notice: 'Http request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @http_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(payload)\n post_like payload, Net::HTTP::Patch.new(@uri.path)\n end", "def update\n @todo = Todo.find(params[:id])\n @todo.update_attributes(params[:todo])\n render :json => @todo\n end", "def update_radios_for_array(args = {}) \n id = args['id']\n temp_path = \"/radios.json/{arrayId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"radioId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def update!(**args)\n @http_body = args[:http_body] if args.key?(:http_body)\n end", "def put(path, body = nil, ctype = 'application/json')\n make_call(mk_conn(path, 'Content-Type': ctype,\n 'Accept': 'application/json'),\n :put, nil, body.to_json)\n end", "def update\n @todo = Todo.find(params[:id])\n if @todo.update_attributes(todo_params)\n render json: @todo, status: :ok\n else\n render json: @todo.errors, status: 422\n end\n end" ]
[ "0.66986567", "0.6543164", "0.62974703", "0.629693", "0.6295578", "0.62917954", "0.6291602", "0.6291602", "0.6220814", "0.61976075", "0.6148801", "0.614587", "0.614587", "0.614587", "0.614587", "0.60867625", "0.6045554", "0.60430604", "0.60430604", "0.6033557", "0.6029839", "0.602899", "0.5983946", "0.5973558", "0.5910238", "0.58925724", "0.5886739", "0.5836591", "0.5827718", "0.5823869", "0.5819689", "0.5816424", "0.5810389", "0.5795475", "0.57952744", "0.5785576", "0.5764969", "0.5764969", "0.57454777", "0.574441", "0.574184", "0.5714282", "0.56921", "0.56906044", "0.5686289", "0.5676545", "0.5676545", "0.5673711", "0.5672815", "0.5672815", "0.5672815", "0.5672815", "0.5672815", "0.5672815", "0.5661995", "0.5643226", "0.56384325", "0.56353444", "0.5632429", "0.5632429", "0.5630584", "0.56248343", "0.56248343", "0.5622307", "0.5605318", "0.55988765", "0.55988765", "0.5595167", "0.55811447", "0.5574292", "0.5571919", "0.5571919", "0.5571614", "0.5556572", "0.55558336", "0.55534434", "0.5552178", "0.5550407", "0.5547997", "0.5541181", "0.5535431", "0.5533626", "0.55276775", "0.5526832", "0.55260706", "0.5520786", "0.5520786", "0.5520786", "0.5520786", "0.5519998", "0.55182666", "0.5508923", "0.5502984", "0.5502555", "0.54912573", "0.5489249", "0.5486847", "0.5484482", "0.5481483", "0.5481412" ]
0.64072025
2
DELETE /reqcargos/1 DELETE /reqcargos/1.json
def destroy @reqcargo.destroy respond_to do |format| format.html { redirect_to reqcargos_url, notice: 'Reqcargo was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def delete(path)\n RestClient.delete request_base+path\n end", "def delete(*args)\n request(:delete, *args)\n end", "def delete\n request(:delete)\n end", "def delete path\n make_request(path, \"delete\", {})\n end", "def deleteRequest\n\n end", "def delete(*args)\n prepare_request(:delete, args)\n @@client.add(:delete, @path, *args)\n end", "def delete!\n request! :delete\n end", "def destroy\n @req.destroy\n respond_to do |format|\n flash[:notice] = \"Req was successfully destroyed.\"\n format.html { redirect_to reqs_url }\n format.json { head :no_content }\n end\n end", "def api_delete(path, data = {})\n api_request(:delete, path, :data => data)\n end", "def delete\n start { |connection| connection.request http :Delete }\n end", "def delete(*args)\n Request.delete(*args)\n end", "def do_delete(uri = \"\")\n @connection.delete do |req|\n req.url uri\n req.headers['Content-Type'] = 'application/json'\n end\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def delete!( opts = {} )\n http_action :delete, nil, opts\n end", "def http_delete(path, data = nil, content_type = 'application/json')\n http_methods(path, :delete, data, content_type)\n end", "def delete(path)\n request(:delete, path)\n end", "def delete endpoint\n do_request :delete, endpoint\n end", "def delete(path)\n\t\trequest(path, :delete)\n\tend", "def destroy\n @treq = Treq.find(params[:id])\n @treq.destroy\n\n respond_to do |format|\n format.html { redirect_to treqs_url }\n format.json { head :no_content }\n end\n end", "def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end", "def delete(path)\n request 'DELETE', path\n end", "def cmd_delete argv\n setup argv\n uuid = @hash['uuid']\n response = @api.delete(uuid)\n msg response\n return response\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end", "def orchio_delete\n response = client.send_request :delete, inst_args\n orchio_status response, 204\n end", "def delete(path, params = {})\n Chirpy.request params.merge({:path => path, :method => 'delete'}.merge(authentication))\n end", "def destroy\n client=Client.find_by_id(params[:id])\n if client != nil\n if client.destroy\n head 204\n end\n else\n head 404\n end\n end", "def delete(*rest) end", "def destroy\n @reqstatus.destroy\n respond_to do |format|\n format.html { redirect_to reqstatuses_url }\n format.json { head :no_content }\n end\n end", "def delete(request)\n @connection.delete request.path do |req|\n req.body = request.params\n end\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def delete\n url = prefix + \"delete\" + id_param\n return response(url)\n end", "def deletes_to(path,opts={},&block) #:nodoc: \n crud_to(:delete,path,opts[:params] || {},opts,&block)\n end", "def destroy\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @curso.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n client.delete(url)\n @deleted = true\nend", "def destroy\n @request.destroy\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request.destroy\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request.destroy\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params)\n headers = {:Authorization => \"token #{token}\", :content_type => :json, :accept => :json}\n res = RestClient.delete(\"#{github_api_uri}/#{path}\", params.to_json, headers)\n Yajl.load(res)\n end", "def delete(path, data={})\n request(:delete, path, data)\n end", "def delete(path)\n request(:delete, path)\n end", "def delete(path, params)\n request(:delete, path, {})\n end", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def delete(path, opts = {})\n request(:delete, path, opts).body\n end", "def destroy\n @couch.destroy\n respond_to do |format|\n format.html { redirect_to couches_url, notice: 'Couch was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :ok }\n end\n end", "def delete(path, params = {}, request_options = {})\n request(:delete, path, params)\n end", "def delete\n execute_request('DELETE') do |uri, headers|\n HTTP.http_client.delete(uri, header: headers)\n end\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(requested_object_id, options = {})\n post(requested_object_id, options.merge(:method => 'delete'))\n end", "def destroy\n @api_v1_todo.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def delete\n RestClient.delete(url, @header) do |rso, req, res|\n setup(rso, req, res)\n end\n end", "def destroy\n @reqinfo = Reqinfo.find(params[:id])\n @reqinfo.destroy\n\n respond_to do |format|\n format.html { redirect_to(reqinfos_url) }\n format.xml { head :ok }\n end\n end", "def delete(path, params)\n parse_response @client[path].delete(:params => params)\n end", "def delete(request)\n _request(request) { |client, options| client.delete options }\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def delete(path, params = {})\n debug_log \"DELETE #{@host}#{path} params:#{params}\"\n res = connection.delete path, params\n debug_log \"Response status:#{res.status}, body:#{res.body}\"\n res\n end", "def delete(path, params={}, options={})\n request(:delete, api_path(path), params, options)\n end", "def destroy\n\n\t\turi = URI.parse(Counter::Application.config.simplyurl)\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\t\n\t\trequest = Net::HTTP::Delete.new('/offsets/doit.json')\n\t\tputs params\n\t\tputs params.slice(*['custids','acctids'])\n\t\t\n\t\t# ok, this join stuff is bogus - it encodes properly, but the other side only sees the last element and loses the array type - it's just string\n\t\t# this way, i 'split' it at the other side to recover my array\n\t\t# it should work without the join/split crap, but it doesn't\n\t\trequest.set_form_data({:custids => ( params['custids'] || []).join(','), :acctids => ( params['acctids'] || []).join(','), :itemids => ( params['itemids'] || []).join(',')})\n\t\t\n\t\tputs request.body\n\t\t\n\t\tresponse = http.request(request)\n\t\tputs response.body\n\n respond_to do |format|\n format.html { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n format.json { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n end\n end", "def delete(path, params = {})\n post(path, params.merge(\"_method\" => \"delete\"))\n end", "def deleteExecution(execution_id)\n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/12/execution/' + execution_id)\n http = Net::HTTP.new(uri.host, uri.port)\n headers = {'Content-Type'=> 'application/jsonr','X-RunDeck-Auth-Token'=> API_KEY }\n r = http.delete(uri.path, headers) \n return r\nend", "def destroy\n @couch.destroy\n respond_to do |format|\n format.html { redirect_to couches_url, notice: 'Couche was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def rm_update path, data, msg\n\n re = rm_request path, data, 'PUT'\n puts re.body\n chk (re.code!='200'), msg + \"\\n#{re.code} #{re.msg}\\n\\n\"\n return true\n\nend", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def delete(request)\n do_request(request) { |client| client.http_delete }\n end", "def delete\n if body.empty? && params[:id]\n client.delete(params)\n elsif body.empty?\n client.delete_by_query(params.merge(body: body.merge(ALL)))\n else\n client.delete_by_query(params.merge(body: body))\n end\n end", "def deleted_request\n r = {}\n render json: r,\n root: :data,\n status: :no_content\n end", "def destroy\n @http_request.destroy\n respond_to do |format|\n format.html { redirect_to http_requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @http_request.destroy\n respond_to do |format|\n format.html { redirect_to http_requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @taxirequest = Taxirequest.find(params[:id])\n @taxirequest.destroy\n\n respond_to do |format|\n format.html { redirect_to taxirequests_url }\n format.json { head :no_content }\n end\n end", "def cmd_delete argv\n setup argv\n e = @hash['element']\n response = @api.delete(e)\n msg response\n return response\n end", "def destroy\n @cto.destroy\n respond_to do |format|\n format.html { redirect_to ctos_url }\n format.json { head :no_content }\n end\n end", "def cancelReservation(lease_uuid)\n broker_url = APP_CONFIG['broker_ip'] + ':' + APP_CONFIG['broker_port'].to_s \n cert_path = APP_CONFIG['cert_path']\n \n header = {\"Content-Type\" => \"application/json\"}\n options = {uuid: lease_uuid}\n\n #puts options.to_json \n uri = URI.parse(broker_url+\"/resources/leases\")\n pem = File.read(cert_path)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.cert = OpenSSL::X509::Certificate.new(pem)\n http.key = OpenSSL::PKey::RSA.new(pem)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Delete.new(uri.request_uri, header)\n request.body = options.to_json\n\n response = http.request(request)\n puts response\n if response.header.code != '200'\n puts \"Something went wrong\"\n puts response\n end\n end", "def destroy\n @request_datum.destroy\n respond_to do |format|\n format.html { redirect_to request_data_url }\n format.json { head :no_content }\n end\n end", "def do_delete(uri = '')\n build_request(:delete, uri)\n end" ]
[ "0.72877944", "0.70265955", "0.6978186", "0.695261", "0.692509", "0.6921337", "0.6902557", "0.68772715", "0.68576765", "0.6856065", "0.68432945", "0.68214524", "0.67697966", "0.676899", "0.67601794", "0.67601794", "0.6754053", "0.6733256", "0.6717482", "0.6716133", "0.6712523", "0.67079175", "0.67047536", "0.6694742", "0.6669464", "0.6666983", "0.6636088", "0.6636088", "0.6636088", "0.6636088", "0.659432", "0.6582058", "0.6571552", "0.6559841", "0.6555869", "0.65453774", "0.6538831", "0.65326333", "0.6531834", "0.65275013", "0.6526051", "0.6524239", "0.65232736", "0.65232736", "0.6520848", "0.6513632", "0.6513632", "0.6513632", "0.6510117", "0.6510117", "0.6510117", "0.6510117", "0.6510117", "0.6510117", "0.6510117", "0.6489508", "0.64883894", "0.6483106", "0.6472902", "0.64721924", "0.64721924", "0.64721924", "0.64624995", "0.6445594", "0.64410496", "0.64392036", "0.6438221", "0.64317113", "0.6429375", "0.6428873", "0.64282954", "0.6424808", "0.64219785", "0.641827", "0.6415972", "0.6415972", "0.6415972", "0.6415972", "0.6415972", "0.6415972", "0.641343", "0.6411932", "0.6407238", "0.6403903", "0.6398035", "0.63851243", "0.63834", "0.63775134", "0.63775134", "0.6374792", "0.636798", "0.6363475", "0.6360075", "0.6360075", "0.63577104", "0.63572943", "0.63556165", "0.63519496", "0.63453585", "0.6338872" ]
0.71188056
1
Use callbacks to share common setup or constraints between actions.
def set_reqcargo @reqcargo = Reqcargo.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def reqcargo_params params.require(:reqcargo).permit(:cargo_id, :nomrequis, :lactivo) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def active_code_params\n params[:active_code].permit\n end", "def filtering_params\n params.permit(:email)\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
GET /profiles GET /profiles.json
def index @profiles = Profile.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n authorize Profile\n @profiles = ProfilePolicy::Scope.new(current_user, @user.profiles).resolve\n render json: @profiles\n end", "def get_default_profile \n get(\"/profiles.json/default\")\nend", "def profiles \n personid = params[:id]\n @response = JSON.parse(current_user.access_token.token.get('/api/v0/aspects/profiles?ids=['+params[:id]+']'))\n respond_to do |format|\n format.html\n format.json {render :json=> @response, :callback=>params[:callback]}#{render json: @response}\n end\n end", "def index\n @profiles = Profile.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def profiles\n collection(\"profiles\", paged: true)\n end", "def my_profiles\n @user = User.find(params[:user_id])\n @profiles = @user.profiles\n end", "def index\n @profiles = current_user.profiles\n end", "def index\n @profiles = current_user.profiles\n end", "def profiles(fields: nil)\n params = build_fields_params fields\n res = @connection.get profile_path, params\n map_as_collection res, Profile\n end", "def index\n @profiles = Profile.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @profiles }\n end\n end", "def show\n profile = Profile.find(params[:id])\n render status: 200, json: profile\n end", "def profile\n check_auth :profile\n \n response = connection.post do |req|\n req.url '/user/profile'\n req.body = { :format => @format }\n end\n response.body[0]\n end", "def show\n @profile = @user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def index\n @profiles = Profile.all.paginate :page => params[:page], :per_page => 3\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def profile(user_id: '-')\n return get(\"#{API_URI}/#{PROFILE_API_VERSION}/user/#{user_id}/profile.json\")\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def get_profile\n \n profil =\n Excon.get(\n 'https://eastus.api.cognitive.microsoft.com/speaker/identification/v2.0/text-independent/profiles',\n headers: {\n 'Content-Type' => 'application/json',\n 'Ocp-Apim-Subscription-Key' => \"3c43bca9ad884fe39518a5cf3925e707\"\n },\n body: JSON.generate(\"locale\": 'en-us')\n )\n return profil.body\n parsed = JSON.parse(profil.body)\n return parsed['profiles']\n rescue Excon::Error => e\n puts \"Error: #{e}\"\n\n end", "def show\n @profile = Profile.find(params[:id])\n render json: @profile.to_json(include_hash)\n end", "def show\n @profile = current_user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def profile\n p @user.as_json\n render json: @user.as_json\n end", "def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @user_profiles }\n end\n end", "def index\n @profiles = Profile.all\n @profile = Profile.find_by_id(params[:profile_id])\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def index\n @profiles = Profile.all\n @original_niche = get_subscriber_details(@profiles, \"niche\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def users_profile\n @usersProfile = User.find(params[:id]).to_json(:include => :user_connections)\n render json: { data: @usersProfile }\n end", "def get_profile_configuration(args = {}) \n get(\"/profiles.json/#{args[:profileId]}/configuration\", args)\nend", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def retrieve_profile(id, content_type)\n call(:get, path(\"#{id}/profiles/#{content_type}/\"))\n end", "def get_profile\n path = self.api_root + '/register/profile'\n process_firecloud_request(:get, path)\n end", "def profile(profile_name:)\n claim_url = \"#{@@profile_service_url}/profile/#{profile_name}/next\"\n response = Faraday.get claim_url\n profile = JSON.parse(response.body)\n raise \"No profile available for #{profile_name}\" unless profile\n profile\n end", "def index\n @skill_user_profiles = SkillUserProfile.all\n\n render json: @skill_user_profiles\n end", "def index\n @profiles = current_user\n end", "def index\n @profiles = Profile.all\n respond_to do |format|\n format.html\n format.json do\n @profiles = Profile.near(\n [\n current_user.profile.latitude,\n current_user.profile.longitude\n ], params[:radius]\n ).distinct\n @profiles = @profiles.where.not(id: current_user.profile.id)\n @profiles = @profiles.min_age(params[:min_age]) if params[:min_age].present?\n @profiles = @profiles.max_age(params[:max_age]) if params[:max_age].present?\n @profiles = @profiles.by_gender(params[:gender]) if params[:gender].present?\n @profiles = @profiles.by_activity(params[:activity])\n\n render json: @profiles.map{|profile| profile.attributes.merge(image: profile.image.url(:medium))}\n end\n end\n end", "def index\n @profiles = Profile.all\n\n end", "def show\n @user_profile = UserProfile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user_profile }\n end\n end", "def index\r\n @profiles = Profile.all\r\n end", "def index\r\n @profiles = Profile.all\r\n end", "def show\n\t\t# begin\n\t\t\tprofile = Profile.find(params[:id])\n\t @conversation = current_profile.find_conversation(profile)\n\t respond_to do |format|\n\t format.html {render \"profiles/#{profile._type.underscore}_show\"}\n\t format.json { render :json => @profile }\n\t end\n\t\t# rescue => error\n\t\t# \trender \"profiles/not_found\"\n\t\t# \tputs error.message\n\t\t# end\n end", "def index\n @profiles = Profile.all\n end", "def profile\n raw = client.get @json['user']['links']['self']\n client.factory.create(GoodData::Profile, raw)\n end", "def show\n @profile = current_user.profile\n\n # ToDo: error message if no profile is found for user\n\n puts 'Got profile='\n pp @profile\n \n\n puts 'got other_names='\n pp @profile.other_names\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @profile }\n format.json { render :json => @profile }\n end\n \n end", "def show\n @providers = @profile.providers_data\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @profile }\n end\n end", "def team_profile_get(options={})\n post(\"team.profile.get\", options)\n end", "def pull_profiles\n \tprofiles_from_api = self.client.profiles\n\t\tprofiles_array = []\n\t\tprofiles_from_api.each do |p|\n\t\t\tif p.service == \"twitter\"\n\t\t\t\tprofiles_array << p\n\t\t\tend\n\t\tend\n\t\tprofiles_array\n end", "def get_profile_information\n # body = {\n # cmd: \"get_profile_information\"\n # }\n\n end", "def profile\n # (1) the request go into the headers and grab the key authorization and give us the value back (this's the token our server gave us originally)\n # the server only knows about the system\n # byebug/\n token = request.headers[\"Authorization\"]\n # what makes it secure? only the server knows about the secret 'pegasuscode'; the data is encoded using this secret, only server knows it so when server gets the information back, it must be the same information server encoded using the secret. Otherwise, it will break.\n # server uses the secret to encode and decode information\n decoded_token = JWT.decode(token, 'pegasuscode', true, { algorithm: 'HS256' })\n\n user_id = decoded_token[0][\"user_id\"] # user id\n\n user = User.find(user_id)\n\n # get the user back\n render json: user\n end", "def show\n @profile = Profile.find_by_user_id(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile.to_json(:include => [:faculty, :course]) }\n end\n end", "def show\n @profiles = @grab.profiles\n end", "def user_profile(id)\n users(request(\"users/profile/#{id}.xml\", :auth => true))\n end", "def show_current\n user = current_user\n profile = Profile.find_by user_id: user.id\n\n render json: profile\n end", "def get_profile\n begin\n client.profile(fields: PROFILE_FIELDS)\n rescue Exception => e\n logger.error \"Linkedin #get_profile error #{e}\"\n end\n end", "def get_profile\n\n # Auth\n token = auth\n\n # Get Client info based on fields provided\n client = LinkedIn::Client.new(API_KEY, API_SECRET, token)\n client.profile(:fields => @profile_fields)\n end", "def profiles\n Management::Profile.all(self)\n end", "def profile(profile_id, fields: nil)\n check_not_empty profile_id, 'profile_id'\n params = build_fields_params fields\n res = @connection.get profile_path(profile_id), params\n Profile.new res.body, self\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @user_profile }\n end\n end", "def details\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # details.html.erb\n format.json { render json: @profile }\n end\n end", "def index\n @profile_attributes = current_user.profile_attributes\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @profile_attributes }\n format.json { render :json => @profile_attributes }\n end\n end", "def profile\n render_json 0,\"ok\",current_member.as_profile\n end", "def show\n @private_profile = PrivateProfile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @private_profile }\n end\n end", "def friend_requests\n friends = current_user.friends.where accepted: false\n profiles = friends.map{ |friend| Profile.find(friend.profile_id)}\n render json: profiles\n end", "def index\n @github_profiles = GithubProfile.all\n end", "def profiles; end", "def index\n @student_profiles = StudentProfile.all \n render json: @student_profiles\n end", "def profile\n service_response = UserManagement::ProfileDetail.new(params).perform\n render_api_response(service_response)\n end", "def index\n @userprofiles = Userprofile.all\n end", "def GetProfileData()\n uri = URI(API_URL + 'me')\n\n return PerformRestrictedGet(uri)\n end", "def show\n @profile = Profile.find(params[:id])\n @checkin = CheckIn.find_last_by_user_id(@profile.user_id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n @checkin = CheckIn.find_last_by_user_id(@profile.user_id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def profile_data(access_token)\n response = uphold_conn.get do |req|\n req.url UPHOLD_PROFILE_PATH\n req.respond_to? :json, content_type: /\\b(?i:json)$/\n req.headers[:Authorization] = \"Bearer #{access_token}\"\n end\n JSON.parse(response.body, symbolize_names: true)\n end", "def get_profile\n self.class.get '/members/private', @options\n end", "def profile\n render json: @current_user\n end", "def profile\n if object = send(:\"current_#{resource_name}\")\n self.resource = resource_class.to_adapter.get!(object.to_key)\n respond_with self.resource\n else\n render json: '', status: 404\n end\n end", "def index\n @user_profiles = UserProfile.paginate(page: params[:page])\n end", "def get_user_detail\n user_id = params[:id]\n user = User.find(user_id)\n\n render json: UserSerializer.new(user).profile_detail_hash\n end", "def fetch_profiles\n UI.message \"Fetching profiles...#{Sigh.config[:app_identifier]}\"\n results = profile_type.find_by_bundle_id(Sigh.config[:app_identifier])\n\n #Take the provisioning profile name into account\n #if Sigh.config[:provisioning_name].to_s.length > 0\n #filtered = results.select { |p| p.name.strip == Sigh.config[:provisioning_name].strip }\n #if Sigh.config[:ignore_profiles_with_different_name]\n #results = filtered\n #else\n #results = filtered if (filtered || []).count > 0\n #end\n #end\n\n if results \n return [results]\n else\n return []\n end\n \n\n\n #return results if Sigh.config[:skip_certificate_verification]\n\n #return results.find_all do |a|\n ## Also make sure we have the certificate installed on the local machine\n #installed = false\n #a.certificates.each do |cert|\n #file = Tempfile.new('cert')\n #file.write(cert.download_raw)\n #file.close\n #installed = true if FastlaneCore::CertChecker.installed?(file.path)\n #end\n #installed\n #end\n end", "def profile; Profile.get(self.profile_id); end", "def index\n @user_profiles = UserProfile.all\n end", "def index\n @user_profiles = UserProfile.all\n end", "def index\n @user_profiles = UserProfile.all\n end", "def index\n @user_profiles = UserProfile.all\n end", "def show\n @spot = Spot.find(params[:id])\n @users = UserSpots.find_all_by_spot_id(params[:id])\n @profiles = []\n @users.each { |item| @profiles << Profile.find_by_user_id(item.user_id) }\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: [@spot, @profiles] }\n end\n end", "def load_profiles()\n # read profiles\n puts \"Loading configs from #{@server_host}:#{@server_port}\" # Rails.logger.info\n\n res = Net::HTTP.start(@server_host, @server_port) {|http|\n http.open_timeout = 5\n http.read_timeout = 10\n http.get('/api/profiles')\n }\n raise \"HTTP status is not succeeded\" if res.code != '200'\n\n profiles_arr = JSON.parse(res.body)\n @table = ProfileTable.new(profiles_arr)\n end", "def show\n @profile = Profile.find(params[:id])\n end" ]
[ "0.7720244", "0.7511753", "0.7511205", "0.7474065", "0.747391", "0.7429771", "0.7368022", "0.7368022", "0.7277252", "0.72754085", "0.72646606", "0.7194632", "0.71890444", "0.7109752", "0.7068873", "0.7061951", "0.7061951", "0.7061951", "0.7036681", "0.70242476", "0.699903", "0.69940346", "0.6987963", "0.6956225", "0.6945531", "0.69381684", "0.6886625", "0.68714726", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6858518", "0.6830315", "0.68182325", "0.68014896", "0.6796628", "0.6788923", "0.6788018", "0.6785816", "0.67847836", "0.6770176", "0.6770176", "0.67426187", "0.6741879", "0.6733079", "0.6716385", "0.6691481", "0.6688806", "0.668109", "0.66723466", "0.6657511", "0.6657501", "0.66566384", "0.6641745", "0.66245764", "0.66203684", "0.6606441", "0.65896416", "0.6577502", "0.657", "0.65648276", "0.65374047", "0.6536674", "0.6536111", "0.6534627", "0.6521954", "0.65166444", "0.64936286", "0.64924353", "0.648049", "0.6479729", "0.64773184", "0.64773184", "0.6474976", "0.6474441", "0.64718795", "0.6466817", "0.6466672", "0.6457106", "0.6455558", "0.6455189", "0.64467984", "0.64467984", "0.64467984", "0.64467984", "0.64417386", "0.6436329", "0.64360434" ]
0.6769825
54
GET /profiles/1 GET /profiles/1.json
def show @country = Carmen::Country.coded(@profile.country_code) @subregions = @country.subregions @state = @subregions.coded(@profile.state_code) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_default_profile \n get(\"/profiles.json/default\")\nend", "def my_profiles\n @user = User.find(params[:user_id])\n @profiles = @user.profiles\n end", "def show\n profile = Profile.find(params[:id])\n render status: 200, json: profile\n end", "def index\n authorize Profile\n @profiles = ProfilePolicy::Scope.new(current_user, @user.profiles).resolve\n render json: @profiles\n end", "def profiles \n personid = params[:id]\n @response = JSON.parse(current_user.access_token.token.get('/api/v0/aspects/profiles?ids=['+params[:id]+']'))\n respond_to do |format|\n format.html\n format.json {render :json=> @response, :callback=>params[:callback]}#{render json: @response}\n end\n end", "def index\n @profiles = Profile.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def profile\n check_auth :profile\n \n response = connection.post do |req|\n req.url '/user/profile'\n req.body = { :format => @format }\n end\n response.body[0]\n end", "def show\n @profile = @user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def index\n @profiles = current_user.profiles\n end", "def index\n @profiles = current_user.profiles\n end", "def index\n @profiles = Profile.all\n @profile = Profile.find_by_id(params[:profile_id])\n end", "def profile(user_id: '-')\n return get(\"#{API_URI}/#{PROFILE_API_VERSION}/user/#{user_id}/profile.json\")\n end", "def index\n @profiles = Profile.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @profiles }\n end\n end", "def get_profile_configuration(args = {}) \n get(\"/profiles.json/#{args[:profileId]}/configuration\", args)\nend", "def retrieve_profile(id, content_type)\n call(:get, path(\"#{id}/profiles/#{content_type}/\"))\n end", "def show\n @profile = current_user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def profile(profile_name:)\n claim_url = \"#{@@profile_service_url}/profile/#{profile_name}/next\"\n response = Faraday.get claim_url\n profile = JSON.parse(response.body)\n raise \"No profile available for #{profile_name}\" unless profile\n profile\n end", "def show\n @profile = Profile.find(params[:id])\n render json: @profile.to_json(include_hash)\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def index\n @profiles = Profile.all.paginate :page => params[:page], :per_page => 3\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def show\n @user_profile = UserProfile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user_profile }\n end\n end", "def profile\n p @user.as_json\n render json: @user.as_json\n end", "def index\n @profiles = Profile.all\n @original_niche = get_subscriber_details(@profiles, \"niche\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def show\n\t\t# begin\n\t\t\tprofile = Profile.find(params[:id])\n\t @conversation = current_profile.find_conversation(profile)\n\t respond_to do |format|\n\t format.html {render \"profiles/#{profile._type.underscore}_show\"}\n\t format.json { render :json => @profile }\n\t end\n\t\t# rescue => error\n\t\t# \trender \"profiles/not_found\"\n\t\t# \tputs error.message\n\t\t# end\n end", "def get_profile\n path = self.api_root + '/register/profile'\n process_firecloud_request(:get, path)\n end", "def profile; Profile.get(self.profile_id); end", "def get_profile\n \n profil =\n Excon.get(\n 'https://eastus.api.cognitive.microsoft.com/speaker/identification/v2.0/text-independent/profiles',\n headers: {\n 'Content-Type' => 'application/json',\n 'Ocp-Apim-Subscription-Key' => \"3c43bca9ad884fe39518a5cf3925e707\"\n },\n body: JSON.generate(\"locale\": 'en-us')\n )\n return profil.body\n parsed = JSON.parse(profil.body)\n return parsed['profiles']\n rescue Excon::Error => e\n puts \"Error: #{e}\"\n\n end", "def profiles\n collection(\"profiles\", paged: true)\n end", "def profile\n raw = client.get @json['user']['links']['self']\n client.factory.create(GoodData::Profile, raw)\n end", "def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @user_profiles }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n end", "def show\n @profile = Profile.find(params[:id])\n end", "def show\n @profile = Profile.find(params[:id])\n end", "def show\n @profile = Profile.find(params[:id])\n end", "def show\n @profile = Profile.find(params[:id])\n end", "def show\n @profile = Profile.find(params[:id])\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def index\n @profiles = Profile.all\n end", "def show\n @profile = Profile.find(params[:id])\n @checkin = CheckIn.find_last_by_user_id(@profile.user_id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n @checkin = CheckIn.find_last_by_user_id(@profile.user_id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = current_user.profile\n\n # ToDo: error message if no profile is found for user\n\n puts 'Got profile='\n pp @profile\n \n\n puts 'got other_names='\n pp @profile.other_names\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @profile }\n format.json { render :json => @profile }\n end\n \n end", "def details\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # details.html.erb\n format.json { render json: @profile }\n end\n end", "def index\n @profiles = Profile.all\n\n end", "def index\n @profiles = current_user\n end", "def index \n @profiles = Profile.all\n end", "def profile\n @oneuser = User.find_by(username: params[:username]) \n profile = user_profile(@oneuser.id, @oneuser.username, @oneuser.email, @oneuser.first_name, @oneuser.last_name, @oneuser.avatar_img, @oneuser.created_at) \n render json: profile\n end", "def show\n @private_profile = PrivateProfile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @private_profile }\n end\n end", "def user_profile(id)\n users(request(\"users/profile/#{id}.xml\", :auth => true))\n end", "def index\r\n @profiles = Profile.all\r\n end", "def index\r\n @profiles = Profile.all\r\n end", "def index\n @profiles = Profile.all\n end", "def users_profile\n @usersProfile = User.find(params[:id]).to_json(:include => :user_connections)\n render json: { data: @usersProfile }\n end", "def find_profile\n\t\t# Find particular Profile \n\t\t@profile = Profile.where(id:params[:id])[0]\n\t\trender json: {success: false, message: 'Invalid Profile ID !'}, status: 400 if @profile.nil?\n\tend", "def profile\n @profile ||= GATEWAY.get_profile_details(self.profile_id) unless profile_id.nil?\n end", "def get_profile\n begin\n client.profile(fields: PROFILE_FIELDS)\n rescue Exception => e\n logger.error \"Linkedin #get_profile error #{e}\"\n end\n end", "def profile\n render_json 0,\"ok\",current_member.as_profile\n end", "def show\n @profiles = @grab.profiles\n end", "def show_current\n user = current_user\n profile = Profile.find_by user_id: user.id\n\n render json: profile\n end", "def profile\n if object = send(:\"current_#{resource_name}\")\n self.resource = resource_class.to_adapter.get!(object.to_key)\n respond_with self.resource\n else\n render json: '', status: 404\n end\n end", "def get_profile_information\n # body = {\n # cmd: \"get_profile_information\"\n # }\n\n end", "def getUserProfile(uid)\r\n uri = sprintf(\"/api/v1/users/%d/profile\",uid)\r\n dbg(uri)\r\n profile = $canvas.get(uri)\r\n return profile\r\nend", "def getUserProfile(uid)\r\n uri = sprintf(\"/api/v1/users/%d/profile\",uid)\r\n dbg(uri)\r\n profile = $canvas.get(uri)\r\n return profile\r\nend", "def show\n \t@profile = Profile.where(profile_name: params[:id]).first\n end", "def profile\n service_response = UserManagement::ProfileDetail.new(params).perform\n render_api_response(service_response)\n end", "def profile(profile_id, fields: nil)\n check_not_empty profile_id, 'profile_id'\n params = build_fields_params fields\n res = @connection.get profile_path(profile_id), params\n Profile.new res.body, self\n end", "def profile\n @user = UserService.getUserById(params[:id])\n end", "def profile\n # (1) the request go into the headers and grab the key authorization and give us the value back (this's the token our server gave us originally)\n # the server only knows about the system\n # byebug/\n token = request.headers[\"Authorization\"]\n # what makes it secure? only the server knows about the secret 'pegasuscode'; the data is encoded using this secret, only server knows it so when server gets the information back, it must be the same information server encoded using the secret. Otherwise, it will break.\n # server uses the secret to encode and decode information\n decoded_token = JWT.decode(token, 'pegasuscode', true, { algorithm: 'HS256' })\n\n user_id = decoded_token[0][\"user_id\"] # user id\n\n user = User.find(user_id)\n\n # get the user back\n render json: user\n end", "def profiles(fields: nil)\n params = build_fields_params fields\n res = @connection.get profile_path, params\n map_as_collection res, Profile\n end", "def index\n @skill_user_profiles = SkillUserProfile.all\n\n render json: @skill_user_profiles\n end", "def get_user_detail\n user_id = params[:id]\n user = User.find(user_id)\n\n render json: UserSerializer.new(user).profile_detail_hash\n end", "def index\n @github_profiles = GithubProfile.all\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @user_profile }\n end\n end", "def show\n @providers = @profile.providers_data\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @profile }\n end\n end", "def show\n @profile = @user.profile\n end", "def get_profile\n\n # Auth\n token = auth\n\n # Get Client info based on fields provided\n client = LinkedIn::Client.new(API_KEY, API_SECRET, token)\n client.profile(:fields => @profile_fields)\n end", "def get_profile\n self.class.get '/members/private', @options\n end", "def profile\n @user = User.find(params[:id])\n end", "def show\n @profile_attribute = current_user.profile_attributes.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @profile_attribute }\n format.json { render :json => @profile_attribute }\n end\n end", "def profile_url\n @json['profile']['url'] rescue nil\n end", "def user\n\n \n @profile = Profile.find_by_user_id(params[:id])\n\n\nend", "def profile\n\n end", "def show\n @profile = Profile.find(params[:id]) || current_user.profile\n end", "def profile\n \t@user = UsersService.findUserById(params[:id])\n end", "def show\n @pay_profile = PayProfile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pay_profile }\n end\n end" ]
[ "0.7775649", "0.74931335", "0.74876684", "0.736598", "0.7305961", "0.7302657", "0.7301793", "0.72450936", "0.72319347", "0.72319347", "0.72319347", "0.72181976", "0.72181976", "0.71651715", "0.71410364", "0.7114219", "0.70800215", "0.7046293", "0.70175827", "0.69905627", "0.6979416", "0.6963506", "0.6949695", "0.6949417", "0.6944366", "0.69396454", "0.6939536", "0.693113", "0.689453", "0.68904406", "0.68776876", "0.6877267", "0.68713915", "0.68072224", "0.68072224", "0.68072224", "0.68072224", "0.68072224", "0.68072224", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.68003213", "0.6794084", "0.6794084", "0.6785742", "0.6778292", "0.6747371", "0.6733857", "0.673254", "0.6726048", "0.6722431", "0.6712619", "0.67064255", "0.67064255", "0.6694039", "0.66878724", "0.6684493", "0.66746897", "0.66709715", "0.6670069", "0.66673183", "0.66668266", "0.6663944", "0.6662953", "0.66600823", "0.66600823", "0.6630042", "0.6615606", "0.66123694", "0.66001725", "0.65985155", "0.65976495", "0.6587206", "0.65623456", "0.65559983", "0.6549218", "0.65359396", "0.65318197", "0.65105855", "0.65088606", "0.6495757", "0.64841706", "0.64789206", "0.6470903", "0.6460017", "0.64593554", "0.6449851", "0.64454615" ]
0.0
-1
POST /profiles POST /profiles.json
def create @profile = current_user.build_profile(pro_params) respond_to do |format| if @profile.save format.html { redirect_to @profile, notice: 'Profile was successfully created.' } format.json { render :show, status: :created, location: @profile } else format.html { redirect_to new_profile_path, alert: 'Please fill all fields' } format.json { render json: @profile.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @profile = current_user.profiles.build(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n if @profile.save\n render json: @profile, status: :created\n else\n render json: @profile.errors, status: :unprocessable_entity\n end\n end", "def create\n @profile = Profile.create({\n name: params['profile']['name'],\n speciality: params['profile']['speciality'],\n city: params['profile']['city'],\n user_id: current_user['id']\n })\n @profile.save\n respond_with(@profile)\n end", "def create\n logger.info(\"CREATE PROFILE #{params[:profile].inspect}\")\n @profile = Profile.new(params[:profile])\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n @profile.profile_id = UUIDTools::UUID.timestamp_create().to_s\n @profile.user_id = current_user.id\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to users_profile_index_path, notice: t(:profile_successfully_created) }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n \n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, :notice => 'Profile was successfully created.' }\n format.json { render :json => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @profiles = current_user.profiles.new(profile_params)\n\n if @profiles.save\n redirect_to profiles_path, notice: 'Profile was successfully created.'\n else\n render :new\n end\n end", "def create\n # Buidles a profile in association witht eh user\n @user = User.find(current_user.id)\n @profile = @user.build_profile(params[:user])\n @profile.update_attributes(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n @profile.user = current_user\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to root_path, notice: t('controller.profiles.create.success') }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n respond_to do |format|\n if @profile.save\n format.html do\n redirect_to @profile, notice:\n \"Profile was successfully created.\"\n end\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json do\n render json: @profile.errors,\n status: :unprocessable_entity\n end\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to root_path, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to '/', notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = current_user.build_profile\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, :notice => 'Profile was successfully created.' }\n format.json { render :json => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n @profile.user = current_user\n \n respond_to do |format|\n if @profile.save\n \n # Get photos directly from the params and save them to the database one by one\n if params[:profile][:photos]\n params[:profile][:photos].each { |photo|\n ProfilePhoto.create!(profile: @profile, photo: photo)\n }\n end\n \n format.html { redirect_to @profile, notice: 'profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n @profile.save\n \n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @user = current_user\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n params[:profile][:tag_list] = params[:profile][:tag_list]\n @profile = Profile.new(profile_params)\n @profile.user_id = current_user.id\n\n # Store friendly profile URI\n current_user.profile_uri = getUniqueURI(current_user) \n current_user.save\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to profile_path(@profile), notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user_id = current_user.id\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user_id = current_user.id\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user_id = current_user.id\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @profile = Profile.new(profile_params)\r\n\r\n respond_to do |format|\r\n if @profile.save\r\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\r\n format.json { render :show, status: :created, location: @profile }\r\n else\r\n format.html { render :new }\r\n format.json { render json: @profile.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @profile = Profile.new(profile_params)\n authorize @profile\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to quit_user_profile_path, notice: \"Profile: #{I18n.t('helpers.saved')}\" }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n respond_to do |format|\n if @profile.save\n format.html { redirect_to manage_profile_path(@profile), notice: 'Profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user_id = current_user.id\n\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.my_id = current_user.id\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to profiles_path, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = @account.build_profile(profile_attributes)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to root_path, notice: 'Анкета успешно сохранена. Ваш магазин добавлен в очередь на оптимизацию.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n \n @profile.user_id = current_user.id\n @profile.full_name = @profile.first_name + @profile.last_name\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, :notice => t('alerts.profiles.create') }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user=current_user\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # TO DO: make this for just generic creation.\n @profile = Profile.find_by_email(params[:profile][:email])\n @profile.user_id = current_user.id\n\n if @profile.nil?\n @profile = Profile.new(params[:profile])\n add_to_list_niche(params[:profile][:fname], params[:profile][:email], params[:profile][:niche], list_id=ENV[\"MAILCHIMP_LISTID\"])\n @profile.save\n else\n @profile.update_attributes(params[:profile])\n end\n\n redirect_to profiles_path, notice: 'Profile was successfully created.' \n # format.json { render json: @profile, status: :created, location: @profile }\n end", "def create\n @profile = Profile.new(params[:profile])\n @profile.user_id = current_user.id\n authorize! :create, @profile\n \n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @security_profile = Security::Profile.new(security_profile_params)\n @security_profile.user_created_id = current_user.id\n respond_to do |format|\n if @security_profile.save\n format.html { redirect_to security_profiles_path, notice: I18n.t('profiles.controller.create')}\n format.json { render :show, status: :created, location: @security_profile }\n else\n format.html { render :new }\n format.json { render json: @security_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_profile = UserProfile.new(params[:user_profile])\n\n respond_to do |format|\n if @user_profile.save\n format.html { redirect_to @user_profile, notice: 'User profile was successfully created.' }\n format.json { render json: @user_profile, status: :created, location: @user_profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_profile = UserProfile.new(params[:user_profile])\n\n respond_to do |format|\n if @user_profile.save\n format.html { redirect_to @user_profile, notice: 'User profile was successfully created.' }\n format.json { render json: @user_profile, status: :created, location: @user_profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n @profile = current_user.create_profile(params[:profile])\n if @profile \n format.html { redirect_to(profile_url(@profile.user_id), :notice => 'Profile was successfully created.') }\n format.xml { render :xml => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n profile = Payments::Profile.new(profile_params)\n profile.user = current_user\n\n respond_to do |format|\n if profile.save\n format.html {redirect_to payments_profiles_path}\n else\n format.html {redirect_to :back, flash: {error: \"Error saving payment profile\"}}\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n authorize! :update, @profile\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n current_user.profile = Profile.new(params[:profile])\n @profile = current_user.profile\n\n if !@profile.valid?\n flash[:error_created] = @profile.errors.full_messages.join(\"<br>\").html_safe\n redirect_to new_user_profile_path(current_user)\n else\n respond_to do |format|\n if @profile.save\n format.html { redirect_to user_profile_path(current_user), notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end \n end\n end", "def create\n @userprofile = Userprofile.new(userprofile_params)\n\n respond_to do |format|\n if @userprofile.save\n format.html { redirect_to @userprofile, notice: 'Userprofile was successfully created.' }\n format.json { render :show, status: :created, location: @userprofile }\n else\n format.html { render :new }\n format.json { render json: @userprofile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_profile\n new_profile = Profile.new\n new_profile.user_id = self.id\n new_profile.save!\n end", "def create\n if current_user.profile.nil?\n profile = Profile.new(profile_params)\n profile.user = current_user\n if profile.save\n redirect_to profiles_path\n return\n end\n end\n redirect_to profiles_path\n end", "def create\n \n @user.profile = Profile.new(params[:profile])\n if params[:goal_worth]\n @goal = @user.goals.create do |g|\n g.goal_type = \"recurring\"\n g.started_on = Date.today\n g.name = \"What my time is worth\"\n g.goal_amount_score = params[:goal_worth].to_i\n end\n else\n @goal = nil\n end\n \n respond_to do |format|\n \n if @user.profile && @goal\n \n format.html { redirect_to user_profiles_path, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: :created, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n user = User.find(params[:user_id])\n @profile = Profile.new(params[:profile])\n @profile.user = user\n\n if @profile.save\n redirect_to user_profile_path(params[:user_id])\n else\n flash[:alert] = @profile.errors.full_messages.join(\",\")\n render :template => \"profiles/new\"\n end\n\n end", "def create\n @profile = Profile.new(req_params)\n if @profile.save\n redirect_to new_partnership_path(p_id: @profile.id)\n else\n flash[:profile_attempt] = req_params\n respond_with_submission_error(@profile.errors.messages, new_dummy_profile_path)\n end\n end", "def add_profile(post, profile)\n post[:profile] = profile\n post[:profileupdate] = 'Y'\n end", "def create\n @admin_profile = Admin::Profile.new(admin_profile_params)\n\n respond_to do |format|\n if @admin_profile.save\n unless params[:admin_profile][:avatar].blank?\n preloaded = Cloudinary::Uploader.upload(params[:admin_profile][:avatar], :use_filename => true, :public_id => \"profiles/#{@admin_profile.id}\")\n end\n\n unless params[:admin_profile][:profile_skills_attributes].blank?\n params[:admin_profile][:profile_skills_attributes].each do |skill|\n admin_skill = Admin::ProfileSkill.create({profile_id: @admin_profile.id, name: skill[1][:name], skill: skill[1][:skill]})\n admin_skill.save\n end\n end\n\n unless params[:admin_profile][:profile_hobbies_attributes].blank?\n params[:admin_profile][:profile_hobbies_attributes].each do |hobby|\n admin_hobby = Admin::ProfileHobby.create({profile_id: @admin_profile.id, name: hobby[1][:name]})\n admin_hobby.save\n end\n end\n\n format.html { redirect_to admin_root_path, notice: 'Profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @admin_profile }\n else\n format.html { render action: 'new'}\n format.json { render json: @admin_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n Userprofile.create(\"name\" => params[\"full_name\"], \"photo_url\" => params[\"url\"])\n redirect_to \"/userprofiles\"\n end", "def set_profile(profile_contents)\n path = self.api_root + '/register/profile'\n process_firecloud_request(:post, path, profile_contents.to_json)\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n flash[:notice] = 'Profile was successfully created.'\n format.html { redirect_to profile_url(@profile) }\n format.xml { head :created, :location => profile_url(@profile) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @profile.errors.to_xml }\n end\n end\n end", "def create\n \t@profile = Profile.new(profile_params)\n\n \trespond_to do |format|\n if @profile.save\n UserMailer.delay.registration_confirmation(@profile)\n format.json { render action: 'show', status: :create, location: @profile }\n else\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_profile = UserProfile.new(user_profile_params)\n\n respond_to do |format|\n if @user_profile.save\n format.html { redirect_to @user_profile, notice: 'User profile was successfully created.' }\n format.json { render :show, status: :created, location: @user_profile }\n else\n format.html { render :new }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def my_profiles\n @user = User.find(params[:user_id])\n @profiles = @user.profiles\n end", "def create\n @profile = Profile.new(profile_params)\n if params['internal_setting_ids'].present?\n params['internal_setting_ids'].each do |internal_setting_id|\n @profile_internal_setting = @profile.profile_internal_settings.build(:internal_setting_id => internal_setting_id)\n @profile_internal_setting.save\n end \n end\n\n if params['email_access_ids'].present?\n params['email_access_ids'].each do |email_access_id|\n @profile_email_access = @profile.profile_email_accesses.build(:email_access_id => email_access_id)\n @profile_email_access.save\n end \n end\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user_id = current_user.id\n\n respond_to do |format|\n if @profile.save\n good_change(format, :created)\n else\n bad_change(format, :new)\n end\n end\n end", "def create\n @user_profile = UserProfile.new(user_profile_params) \n\n respond_to do |format| \n if @user_profile.save\n format.html { redirect_to @user_profile, notice: 'User profile was successfully created.' }\n format.json { render :show, status: :created, location: @user_profile }\n else\n format.html { render :new }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile_user = ProfileUser.new(profile_user_params)\n\n respond_to do |format|\n if @profile_user.save\n format.html { redirect_to @profile_user, notice: 'Profile user was successfully created.' }\n format.json { render :show, status: :created, location: @profile_user }\n else\n format.html { render :new }\n format.json { render json: @profile_user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @github_profile = GithubProfile.new(github_profile_params)\n\n respond_to do |format|\n if @github_profile.save\n format.html { redirect_to @github_profile, notice: 'Github profile was successfully created.' }\n format.json { render :show, status: :created, location: @github_profile }\n else\n format.html { render :new }\n format.json { render json: @github_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n flash[:notice] = 'Profile was successfully created.'\n format.html { redirect_to(@profile) }\n format.xml { render :xml => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n flash[:notice] = 'Profile was successfully created.'\n format.html { redirect_to(@profile) }\n format.xml { render :xml => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n flash[:notice] = 'Profile was successfully created.'\n format.html { redirect_to(@profile) }\n format.xml { render :xml => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def profile_params\n params.require(:profile).permit(:user_id, :name, :surname, :age, :profile_picture, :gender, :relationship_status)\n end", "def create\n @cleaners_profile = Cleaners::Profile.new(cleaners_profile_params)\n\n respond_to do |format|\n if @cleaners_profile.save\n format.html { redirect_to after_signup_path(:preference) }\n format.json { render action: 'show', status: :created, location: @cleaners_profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @cleaners_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n @user = current_user\n\n @user.profile = @profile\n @profile.save\n\n\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to profile, notice: 'Profile was successfully created.' }\n format.json { render :show, profile: :created, location: profile }\n @profile.create(profile_image: image)\n\n else\n format.html { render :new }\n format.json { render json: status.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @representative_profile = RepresentativeProfile.new(representative_profile_params)\n\n respond_to do |format|\n if @representative_profile.save\n format.html { redirect_to @representative_profile, notice: 'Representative profile was successfully created.' }\n format.json { render :show, status: :created, location: @representative_profile }\n else\n format.html { render :new }\n format.json { render json: @representative_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(params[:profile])\n @profile.user = current_user\n respond_to do |format|\n if @profile.save\n flash[:notice] = t('profiles.new.success')\n format.html { redirect_to(@user) }\n format.xml { render :xml => @profile, :status => :created, :location => @user }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @personal_profile = PersonalProfile.new(personal_profile_params)\n @personal_profile.user_id=current_user.id\n respond_to do |format|\n if @personal_profile.save\n format.html { redirect_to resume_path, notice: 'Personal profile was successfully created.' }\n format.json { render :show, status: :created, location: resume_path }\n else\n format.html { render :new }\n format.json { render json: @personal_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @profile = Profile.new\n @profile.build_user\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @profile }\n end\n end", "def profile_params\n params.require(:profile).permit(:name, :bio, :country_id, :picture, interest_ids: [])\n end", "def profiles \n personid = params[:id]\n @response = JSON.parse(current_user.access_token.token.get('/api/v0/aspects/profiles?ids=['+params[:id]+']'))\n respond_to do |format|\n format.html\n format.json {render :json=> @response, :callback=>params[:callback]}#{render json: @response}\n end\n end", "def update_profile(params)\n post 'account/update_profile', :post => params\n end", "def create_profile\n Profile.create(user_id: self.id)\n end", "def create\n respond_to do |format|\n if @user_profile.save\n format.html { redirect_to @user_profile, :notice => 'Корисничкиот профил е успешно создаден.' }\n format.json { render :json => @user_profile, :status => :created, :location => @user_profile }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @user_profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def assign_default_profile(args = {}) \n put(\"/profiles.json/#{args[:profileId]}/default\", args)\nend", "def create\n @client_profile = ClientProfile.new(client_profile_params)\n\n respond_to do |format|\n if @client_profile.save\n format.json { render :show, status: :created, location: @client_profile }\n else\n format.json { render json: @client_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_profile = UserProfile.new(user_profile_params)\n\n respond_to do |format|\n if @user_profile.save\n flash[:success] = 'User profile was successfully created.'\n format.html { redirect_to @user_profile}\n format.json { render :show, status: :created, location: @user_profile }\n else\n flash[:danger] = \"There are some mistakes, please try again\"\n format.html { render :new }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n authorize Profile\n @profiles = ProfilePolicy::Scope.new(current_user, @user.profiles).resolve\n render json: @profiles\n end", "def create\n @profile = Profile.new(profile_params)\n @profile.user = current_user\n @profile.site_identifier = params[:profile][:site_identifier]\n\n respond_to do |format|\n if @profile.save\n# current_user.default_profile = @profile\n set_banner\n format.html do\n redirect_to profile_home_path(@profile.site_identifier), notice: 'Profile was successfully created.'\n end\n format.json { render action: 'show', status: :created, location: profile_home_path(@profile.site_identifier) }\n else\n format.html { render action: 'new' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n authorize @profile\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :created, location: @profile }\n else\n format.html { render :new }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # Ensure that we have the right user\n @user = User.find( params[:user_id] )\n # Create profile linked to this specific user\n @profile = @user.build_profile( profile_params )\n @profile.save\n if @profile.save\n flash[:success] = \"Profile updated!\"\n # TODO: Redirect to profile page, once there is one. \n redirect_to user_path(params[:user_id])\n else\n # TODO: don't dump the user's inputs if save to database fails. \n render action: :new\n end\n end", "def create\n assign_params_to_attributes\n @profile = Profile.new(params[:profile])\n @profile.user_id = current_user.id\n if @profile.save\n flash[:notice] = I18n.t('profile.create.notice')\n redirect_to user_path(current_user)\n else\n @user = current_user\n assing_attributes_to_params\n flash.now[:error] = I18n.t('profile.create.error')\n render :action => \"new\"\n end\n end" ]
[ "0.73701555", "0.7367171", "0.72288865", "0.71786684", "0.7172963", "0.7170674", "0.71145105", "0.7096289", "0.707034", "0.7002038", "0.7002038", "0.7002038", "0.7002038", "0.7002038", "0.7002038", "0.7002038", "0.6997514", "0.69700205", "0.69617796", "0.6937631", "0.6937631", "0.6937631", "0.6937631", "0.6937631", "0.6937631", "0.6937631", "0.6937631", "0.69146293", "0.69033545", "0.6885607", "0.68802375", "0.6870222", "0.68624455", "0.6859433", "0.6858937", "0.6858937", "0.6858937", "0.68550336", "0.6835788", "0.683444", "0.683444", "0.6829081", "0.68168384", "0.6766037", "0.67580324", "0.6755173", "0.6721227", "0.66896856", "0.6656213", "0.6624241", "0.66153675", "0.6593402", "0.658363", "0.658363", "0.6582606", "0.65731853", "0.6565113", "0.6556708", "0.65421325", "0.6523615", "0.6523474", "0.65118587", "0.649321", "0.6491338", "0.6482218", "0.6480695", "0.6472119", "0.6464902", "0.6459156", "0.6436519", "0.6423614", "0.6421916", "0.638889", "0.63844866", "0.63807064", "0.6350672", "0.6344352", "0.6339668", "0.6339668", "0.6339668", "0.6338429", "0.63312715", "0.63294077", "0.63256717", "0.6323012", "0.63147956", "0.6311688", "0.62725914", "0.62598944", "0.62459344", "0.624297", "0.6238812", "0.6235083", "0.6233593", "0.62270284", "0.6220057", "0.6217489", "0.62169695", "0.6204191", "0.6203904" ]
0.6739768
46
PATCH/PUT /profiles/1 PATCH/PUT /profiles/1.json
def update respond_to do |format| if @profile.update(pro_params) format.html { redirect_to @profile, notice: 'Profile was successfully updated.' } format.json { render :show, status: :ok, location: @profile } else format.html { render :edit } format.json { render json: @profile.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @profiles = current_user.profiles.find(params[:id])\n\n respond_to do |format|\n if @profiles.update(profile_params)\n format.html { redirect_to profiles_path, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profiles }\n else\n format.html { render :edit }\n format.json { render json: @profiles.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n logger.debug(\"UPDATE PROFILE @profile = #{@profile.inspect}\")\n logger.debug(\"UPDATE PROFILE params = #{params[:profile].inspect}\")\n logger.debug(\"UPDATE PROFILE update_attributes #{@profile.update_attributes(params[:profile]).inspect}\")\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile.update(profile_params)\n respond_with(@profile)\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to edit_profile_path(current_user.profile), notice: t('controller.profiles.update.success') }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to vanity_profile_path(:id => @profile.user.name), notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = current_user.profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, :notice => 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to user_path, notice: 'Profile was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_profile(body={})\n perform_post(\"/account/update_profile.json\", :body => body)\nend", "def update\n if user_signed_in?\n if @profile.update(profile_params)\n render json: @profile, status: :ok\n else\n render json: @profile.errors, status: :unprocessable_entity\n end\n end\n end", "def update\n @profile = Profile.find(current_user.id)\n @profile.update_attributes(params[:profile])\n respond_with @profile\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n Rails.logger.info(\"PARAMS: #{profile_params}\")\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = current_user.profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to (user_profile_path(current_user)), notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n #format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n #format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to root_url, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n #@profile = UsersDisciplines.find(params[:id])\n @profile = Profile.find_by_user_id(current_user.id)\n \n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to users_profile_index_path, notice: t(:profile_successfully_updated) }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to root_path, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n new_properties = params[:d]\n profile = Profile[params[:id]]\n profile.update_with(new_properties)\n\n respond_with(profile) do |format|\n format.json { render json: profile.stripped }\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to '/', notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to edit_profile_path(), notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html do\n redirect_to @profile,\n notice: \"Profile was successfully updated.\"\n end\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json do\n render json: @profile.errors,\n status: :unprocessable_entity\n end\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(profile_attributes)\n format.html { redirect_to root_path, notice: 'Анкета успешно обновлена.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n params = profile_params\r\n params.delete(\"id\")\r\n params.delete(\"user\")\r\n respond_to do |format|\r\n if @profile.update(params)\r\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\r\n format.json { render :show, status: :ok, location: @profile }\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @profile.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n current_user.admin? ? true : params[:profile][:id] = current_user.id\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n current_user.admin? ? true : params[:profile][:id] = current_user.id\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n respond_to do |format|\r\n if @profile.update(profile_params)\r\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\r\n format.json { render :show, status: :ok, location: @profile }\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @profile.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n good_change(format, :ok)\n else\n bad_change(format, :edit)\n end\n end\n end", "def update\n @profile = @user.profile \n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = t('profiles.new.success')\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def assign_default_profile(args = {}) \n put(\"/profiles.json/#{args[:profileId]}/default\", args)\nend", "def update_profile! (data = {})\n check_auth :update\n \n response = connection.put do |req|\n req.url '/user/update'\n req.body = { :format => @format }.merge(data)\n end\n response\n end", "def update\n @profile = @user.profile\n @profile.update_attributes(params[:profile])\n if params[\"starting\"] == \"pending\"\n @profile.started_on = nil\n @profile.target_completion_date = nil\n end\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to user_profile_path, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update_attributes profile_params\n format.html { redirect_to(@profile, notice: 'Profile was successfully updated.') }\n format.xml { head :ok }\n else\n @original_profile = Profile.find(@profile.id)\n format.html { render action: \"edit\" }\n format.xml { render xml: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\t@user = current_user\n\t\t@profile = @user.profile\n\t\t@profile.update_columns(profile_params)\n\t\trespond_with @profile \n\tend", "def update\n respond_to do |format|\n # This must be update_attributes, to do validations\n if @profile.update(profile_params)\n format.html { redirect_to profile_home_path(@profile.site_identifier), notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find_by_user_id(current_user.id)\n authorize! :update, @profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update_attributes(profile_params)\n format.html {\n flash[:notice] = t('Profile was successfully update.')\n redirect_to home_path\n }\n format.json { render json: {ok: true}, status: :ok }\n else\n format.html { redirect_to profile_edit_url, notice: t('Profile not saved !') }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n @profile.photo.data.blank? ? @profile.photo.update_attributes(photo_type: 2) : @profile.photo.update_attributes(photo_type: 1)\n\n current_user.user_tries.last.state_machine.transition_to(:pending)\n format.html { redirect_to root_path, notice: 'Profile was successfully created.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to profile_path(@profile.user_id) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n \n # Get photos directly from the params and save them to the database one by one\n if params[:profile][:photos]\n params[:profile][:photos].each { |photo|\n ProfilePhoto.create(profile: @profile, photo: photo)\n }\n end\n \n format.html { redirect_to @profile, notice: 'profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def clear_default_profile \n put(\"/profiles.json/default/clear\")\nend", "def update\n # FIXME There's probably a better way to manage STI.\n profile_params = (@profile.type == DeveloperProfile.to_s ? params[:developer_profile] : params[:contractor_profile])\n profile_params[:project_type_ids] ||= []\n\n respond_to do |format|\n if @profile.update_attributes(profile_params)\n format.html { redirect_to(profile_path(@profile), :notice => 'Profile was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_profile(params)\n post 'account/update_profile', :post => params\n end", "def update_profile(params)\n post('/account/update_profile.json', params)\n end", "def update\n respond_to do |format|\n if @profile.update_attributes params[:profile]\n @profile.user.index!\n format.html { redirect_to get_stored_location, :notice => t('profile.profile_updated') }\n else\n format.html { render :action => :edit }\n end\n end\n end", "def update\n @profile = current_user.profile\n respond_to do |format|\n if @profile\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to(@profile, :notice => 'Profile was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n else\n format.html { render :text => \"You currently do not have a profile.\" }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to profile_path, notice: \"Book was successfully updated.\" }\n format.json { render profile_path, status: :ok, location: @profile }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @personal_profile.update(personal_profile_params)\n format.html { redirect_to resume_path, notice: 'Your Personal profile was successfully updated.' }\n format.json { render :show, status: :ok, location: resume_path }\n else\n format.html { render :edit }\n format.json { render json: @personal_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @user_profile = UserProfile.find(params[:id])\n\n respond_to do |format|\n if @user_profile.update_attributes(params[:user_profile])\n format.html { redirect_to @user_profile, notice: 'User profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @user_profile = UserProfile.find(params[:id])\n\n respond_to do |format|\n if @user_profile.update_attributes(params[:user_profile])\n format.html { redirect_to @user_profile, notice: 'User profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Din profil uppdaterades!' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to [@stakeholder, @profile], notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: [@stakeholder, @profile] }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to(@profile) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n # render :text => \"<pre>#{params.to_yaml}</pre>\" and return\n @profile = Profile.find(params[:id])\n # @profile = Profile.find_or_create_by_user_id(@user.id)\n unless params.empty?\n @profile.update_attributes(params[:profile])\n @profile.user.update_attributes(params[:user])\n end\n respond_to do |format|\n if @profile.errors.empty? && @profile.user.errors.empty?\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to(@profile) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors + @profile.user.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n authorize @profile\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to quit_user_profile_path , notice: \"Profile: #{I18n.t('helpers.saved')}\" }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n @profile.user_id = current_user.id\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to(show_user_path(current_user.username)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_profile(body)\n post(\"user/#{user_id}/profile.json\", body)\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n format.js\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = current_user.profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = \"Ваш профиль успешно обновлён\"\n format.html { redirect_to(profile_path) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\t\t\n\t\t# Check to see if this user matches the profile, if not don't let them do anything\n\t\tif @profile.id != Profile.find_by_user_id(current_user.id).id\n \tredirect_to :permission_error\n end\n\t\t\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Your profile was successfully updated'\n format.html { render action: 'edit', notice: 'Profile was successfully updated' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n # byebug\n if @profile.update(profile_params)\n format.html { redirect_to vendor_path(current_user.username), notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: t(\"controller.shared.flash.update.notice\", model: pick_model_from_locale(:profile)) }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n current_user.profile.update_attributes(profile_params)\n redirect_to '/profiles'\n end", "def update\n @profile_attribute = current_user.profile_attributes.find(params[:id])\n\n respond_to do |format|\n if @profile_attribute.update_attributes(params[:profile_attribute])\n format.html { redirect_to(@profile_attribute, :notice => 'Profile attribute was successfully updated.') }\n format.xml { head :ok }\n format.json { render :json => {:profile_attribute => @profile_attribute} }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile_attribute.errors, :status => :unprocessable_entity }\n format.json { render :json => {:error => @profile_attribute.errors.full_messages} }\n end\n end\n end", "def update_profile\n \t@user = User.find_by_id(params[:id])\n \tif @user.nil?\n render :json => {:message => \"User not exists\"}, :status => :not_acceptable\n else\n \tbegin\n\t @user.update_attributes(params[:user])\n\t @user.save!\n\t render :json => {:success => true, :message => \"User updated\", :user =>@user}, :status => :ok\n\t rescue Exception => e\n\t \tp e.backtrace\n\t render :json => {:success => false, :message => e.backtrace}, :status => :not_acceptable\n\t end\n end\n end", "def update\n respond_to do |format|\n if @client_profile.update(client_profile_params)\n format.json { render :show, status: :ok, location: @client_profile }\n else\n format.json { render json: @client_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize! :update, @profile\n respond_to do |format|\n if @user.update_attributes(params[:user].permit(:username)) && @profile.update_attributes(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n # puts \"profile_params: #{profile_params[:sport_ids]}\"\n\n respond_to do |format|\n begin\n if current_user != @profile.user\n performing_follow?\n @profile.user.toggle_followed_by(current_user)\n # the next two lines are all about the redirecting or the 'resheshing' of a page so that you can see the result of follow and unfollow without having to refresh.\n format.html { redirect_to @profile.user }\n format.json { render :show, status: :ok, location: @profile }\n end\n\n @profile.update(profile_params)\n # add skill objects and save to db\n # profile_params[:sport_ids].each do |sport_id|\n # Skill.create!(profile_id: @profile.user.id, sport_id: sport_id)\n # end\n format.html { redirect_to profile_url, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n rescue\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find_by_user_id(params[:user_id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to profile_url(@profile) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors.to_xml }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n @profile.update_attributes(profile_params)\n @profile = Profile.all\n respond_to do |page|\n page.js\n end\n end", "def update_profile(options = {}) \n # query profile info\n response = HTTP.auth('Bearer ' + Asca::Tools::Token.new_token).get(URI_PROFILES, :params => { 'filter[name]' => options[:name] })\n if response.status.success?\n responseObj = JSON.parse(response.body)\n queried_profile_list = responseObj[\"data\"]\n if queried_profile_list.length() > 0\n profile = queried_profile_list[0]\n end\n else\n Asca::Tools::Log.error(response.body)\n return\n end\n \n if !profile\n Asca::Tools::Log.error(\"No profile named #{options[:name]} found\")\n return\n end\n # create new profile\n profile_type = profile[\"attributes\"][\"profileType\"]\n \n # get bundle id\n response = HTTP.auth('Bearer ' + Asca::Tools::Token.new_token).get(profile[\"relationships\"][\"bundleId\"][\"links\"][\"self\"])\n bundle_id = JSON.parse(response.body)[\"data\"][\"id\"]\n response = HTTP.auth('Bearer ' + Asca::Tools::Token.new_token).get(profile[\"relationships\"][\"certificates\"][\"links\"][\"self\"])\n certificate_ids = JSON.parse(response.body)[\"data\"].map { |cer| cer[\"id\"] }\n \n # get all device ids\n device_ids = Asca::REST::Provisioning::Devices.list_devices.map { |device|\n device[\"id\"]\n }\n \n # delete old prifile\n delete_profile :name => options[:name]\n \n if profile_type.include? 'APP_STORE'\n create_new_profile :name => options[:name], :type => profile_type, :bundle_id => bundle_id, :certificate_ids => certificate_ids\n else\n create_new_profile :name => options[:name], :type => profile_type, :bundle_id => bundle_id, :device_ids => device_ids, :certificate_ids => certificate_ids\n end\n \n return true\n end", "def update\n respond_to do |format|\n if @user_profile.update(user_profile_params)\n format.html { redirect_to @user_profile, notice: 'User profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_profile }\n else\n format.html { render :edit }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @user_profile.update(user_profile_params)\n format.html { redirect_to @user_profile, notice: 'User profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_profile }\n else\n format.html { render :edit }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = Profile.find(params[:id])\n\n if @profile.update_attributes(params[:profile])\n redirect_to @profile, notice: 'Profile was successfully updated.'\n else\n render action: \"edit\"\n end\n end", "def update\n begin\n @profile.update!(metadata_profile_params)\n rescue => e\n render partial: \"shared/validation_messages\",\n locals: { object: @profile.errors.any? ? @profile : e },\n status: :bad_request\n else\n toast!(title: \"Profile updated\",\n message: \"The metadata profile \\\"#{@profile.name}\\\" has been \"\\\n \"updated.\")\n render \"shared/reload\"\n end\n end", "def update\n @profile = Profile.find(params[:id])\n work_name\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to(@profile, :notice => 'Profile ha sido modificado.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @user_profile.update(user_profile_params)\n format.html { redirect_to @user_profile, notice: \"User profile was successfully updated.\" }\n format.json { render :show, status: :ok, location: @user_profile }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @profile.update(req_params)\n redirect_to show_path, notice: 'Profile was successfully updated.'\n else\n respond_with_submission_error(@profile.errors.messages, edit_path)\n end\n end", "def create_or_update_profile_configuration(args = {}) \n id = args['profileId']\n temp_path = \"/profiles.json/{profileId}/configuration\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"profileId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend" ]
[ "0.7385554", "0.7121749", "0.7113102", "0.7096679", "0.7091465", "0.7091465", "0.7091465", "0.7076842", "0.707045", "0.7063198", "0.70600575", "0.7022012", "0.70120174", "0.699651", "0.6985236", "0.6985236", "0.6985236", "0.6985236", "0.6979028", "0.697453", "0.6968044", "0.6967269", "0.69600093", "0.6953779", "0.6948602", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6940231", "0.6928283", "0.692623", "0.6923915", "0.69152933", "0.69120854", "0.6905072", "0.6905072", "0.6870408", "0.6863119", "0.68528676", "0.68429637", "0.6834663", "0.682247", "0.68176895", "0.6814143", "0.68059534", "0.6783105", "0.6760196", "0.6758649", "0.6743165", "0.67362434", "0.67348063", "0.67336524", "0.67280525", "0.6714092", "0.6712624", "0.6702015", "0.6691855", "0.6672218", "0.6657492", "0.6657492", "0.665591", "0.6652365", "0.6643084", "0.66245157", "0.6615003", "0.65870106", "0.65640306", "0.6560384", "0.6551966", "0.6543359", "0.6539523", "0.6537327", "0.6534612", "0.6533719", "0.6527972", "0.6524115", "0.65115166", "0.65014225", "0.6499302", "0.6497949", "0.64870906", "0.64701694", "0.64701694", "0.6459732", "0.6457896", "0.6442181", "0.6436961", "0.6430309", "0.6425514" ]
0.680932
55
DELETE /profiles/1 DELETE /profiles/1.json
def destroy @profile.destroy respond_to do |format| format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :ok }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :ok }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :ok }\n end\n end", "def destroy\n # @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_path, :notice => \"profile was successfully delete.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url, :notice => t('alerts.profiles.destroy') }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = current_user.profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n \t@profile.destroy\n\n \trespond_to do |format|\n \t\tprofiles = Profile.all\n \t\tformat.json { render json: profiles}\n \tend\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to root_path, notice: \"Profile was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n # @profile = Profile.find(params[:id])\n # authorize! :destroy, @profile\n\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url, notice: '*Profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @user_profile = UserProfile.find(params[:id])\n @user_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to user_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_profile = UserProfile.find(params[:id])\n @user_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to user_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @user_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to user_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n end", "def destroy\n raise params.inspect\n @user_profile = UserProfile.find(params[:id])\n @user_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to user_profiles_url }\n format.json { head :ok }\n end\n end", "def destroy\n @profile.destroy\n @profile.requests.destroy_all\n @profile.member.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url, notice: 'El perfil fue eliminado exitosamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.xml { head :ok }\n end\n end", "def destroy\n @user.profile.destroy\n respond_to do |format|\n format.html { redirect_to(profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n\n format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to disciplines_url }\n format.json { head :ok }\n end\n end", "def destroy\n # Delete profile\n @profil.destroy\n respond_to do |format|\n format.html { redirect_to profils_url, notice: 'Profil was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html do\n redirect_to profiles_url, notice:\n \"Profile was successfully destroyed.\"\n end\n format.json { head :no_content }\n end\n end", "def destroy\n @users_profile = Users::Profile.find(params[:id])\n @users_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profile_url, notice: 'Profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n redirect_to profiles_url\n end", "def destroy\r\n @profile.destroy\r\n respond_to do |format|\r\n format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @profile = @user.profile\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to user_path(@user) }\n format.json { head :no_content }\n end\n #redirect_to user_path(@user)\n end", "def destroy\n authorize @profile\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url, notice: \"Profile: #{I18n.t('helpers.deleted')}\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n redirect_to '/'\n end", "def destroy\n @profile.destroy\n respond_with(@profile)\n end", "def destroy\n @profile.destroy\n session[:profile_id] = nil\n respond_to do |format|\n format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to partnerships_url, notice: 'Profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @pay_profile = PayProfile.find(params[:id])\n @pay_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to pay_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client_profile.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @personal_profile.destroy\n respond_to do |format|\n format.html { redirect_to resume_path, notice: 'Personal profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_profile = UserProfile.find(params[:id])\n @user_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @user_profile.destroy\n respond_to do |format|\n format.html { redirect_to user_profiles_url, notice: 'User profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url, notice: 'Perfil destruido correctamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile_detail.destroy\n respond_to do |format|\n format.html { redirect_to profile_details_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_profile.destroy\n respond_to do |format|\n format.html { redirect_to admin_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n if current_profile!=@profile\n redirect_to root_url, notice: 'Permission denied'\n end\n\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @private_profile = PrivateProfile.find(params[:id])\n @private_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to private_profiles_url }\n format.json { head :no_content }\n end\n end", "def clear_default_profile \n put(\"/profiles.json/default/clear\")\nend", "def destroy\n @project_profile.destroy\n respond_to do |format|\n format.html { redirect_to project_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize @client_profile\n \n @client_profile.destroy\n respond_to do |format|\n format.html { redirect_to client_profiles_url, notice: 'Client profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @retailer_profile.destroy\n respond_to do |format|\n format.html { redirect_to retailer_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @userprofile.destroy\n respond_to do |format|\n format.html { redirect_to userprofiles_url, notice: 'Userprofile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @github_profile.destroy\n respond_to do |format|\n format.html { redirect_to github_profiles_url, notice: 'Github profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_profile = UserProfile.find(params[:id])\n @user_profile.destroy\n\n format.html { redirect_to(user_profiles_url) }\n end", "def destroy\n @vet_profile.destroy\n respond_to do |format|\n format.html { redirect_to vet_profiles_url, notice: 'Vet profile was successfully removed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @monitor_profile = MonitorProfile.find(params[:id])\n @monitor_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to monitor_profiles_url }\n format.json { head :ok }\n end\n end" ]
[ "0.7739456", "0.7739456", "0.7739456", "0.7707937", "0.77065504", "0.77065504", "0.77065504", "0.77065504", "0.77065504", "0.77065504", "0.77065504", "0.77065504", "0.7706363", "0.7704212", "0.769637", "0.7687797", "0.7687588", "0.7687588", "0.76273435", "0.7588475", "0.75627995", "0.75245315", "0.7503449", "0.75018144", "0.7498817", "0.7498817", "0.74581385", "0.74581385", "0.7456729", "0.7456729", "0.7456729", "0.7456729", "0.7456729", "0.7454245", "0.742901", "0.7427498", "0.7422489", "0.74219066", "0.74209017", "0.7410241", "0.7405282", "0.7403725", "0.7402013", "0.73968756", "0.7396158", "0.7385945", "0.73832124", "0.7320039", "0.73195565", "0.73191196", "0.7318569", "0.72908765", "0.7288395", "0.72759897", "0.72652495", "0.7219208", "0.7190267", "0.71853673", "0.717773", "0.7173035", "0.7170404", "0.71691376", "0.7147211", "0.71275276", "0.7123824", "0.71233344", "0.71214837", "0.7120485", "0.7112716", "0.70621276", "0.7058789", "0.70282286" ]
0.74744916
53
Use callbacks to share common setup or constraints between actions.
def set_profile @profile = Profile.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def profile_params params.fetch(:profile, {}) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def active_code_params\n params[:active_code].permit\n end", "def filtering_params\n params.permit(:email)\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
Initializes a new AttributeGroupData instance with the specified name and an empty set of rows. +name+:: The name of the attribute group whose data is being represented.
def initialize(name) @name = name @rows = Array.new end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize(name)\n @name = name\n @groups = Levels::KeyValues.new\n end", "def initialize(name)\n @name = name.to_s\n @attributes = {}\n @criteria = []\n end", "def initialize(name)\n raise BadDataException, \"No name present\" if name.empty?\n @name = name\n end", "def initialize( name, group=nil )\n @name = name\n @group = group\n\n @count = nil\n end", "def initialize(name=nil)\n @name = name\n @data = {}\n end", "def initialize(name, default, count=0)\n\n # We need to store the name and default for later.\n @name = name\n @default = default\n\n # This will contain all of our column data\n @storage = []\n\n # We need to populate our storage array with default data until it is as long as our count\n while @storage.length < count\n @storage.push(default)\n end\n\n end", "def initialize(name=nil)\n # Create the record grouping\n super()\n @records[Elements] = Elements.new\n @records[GRT_ENDSTR] = Record.new(GRT_ENDSTR)\n\n # set the name\n self.name = name unless name.nil?\n\n # Set create/modify time to the current time\n now = Time.now\n self.create_time = now\n self.modify_time = now\n\n yield self if block_given?\n end", "def dataset(name)\n sets[name] = Dataset.new(name, connection)\n end", "def build!(data_set_name)\n interface(data_set_name).create_empty_data_set\n library[data_set_name] = DataSet.new(data_set_name, interface(data_set_name))\n end", "def initialize name, data\r\n @name = name\r\n merge! data\r\n end", "def new_group(group_data)\n [:id, :name].each { |attr| raise(ArgumentError, \"Missing or Invalid Parameter(s)\") unless group_data.key?(attr) }\n set_values group_data\n end", "def dataset(name)\n self[name] || connection.create_dataset(name)\n end", "def ungrouped\n cached_dataset(:_ungrouped_ds){clone(:group => nil, :having => nil)}\n end", "def initialize(group_name, file_path) # overriding the default initialize with a positional arguement group name\n @name = group_name # setting instance variable @name\n @path = file_path\n @names_array = self.path_to_array\n end", "def dataset(name)\n @datasets[name.to_sym] = Dataset.new(session, *split(name))\n end", "def initialize(name)\n @name = name\n @key_value_pairs = []\n end", "def initialize(data=[], options={})\n @headers = options[:headers]\n if @headers\n @column_names = data.shift\n @rows = data\n else\n @rows = data\n end\n end", "def dataset(name)\n datasets[name] = Dataset.new(connection.fetch(name.to_s))\n end", "def dataset(name)\n fetch_or_store(name) { Dataset.new(rql.table(name), rql, self) }\n end", "def initialize( name, workbook )\n @workbook = workbook\n @name = name\n @header_rows = 1\n @data = Data.new( self, [[]] )\n end", "def initialize(name)\n @name = name #has a name\n @@all << self\n end", "def create_attribute_group\n\t\tif AttributeGroup.where(name: \"Otros\", company_id: self.id).count < 1\n\t\t\tAttributeGroup.create(name: \"Otros\", company_id: self.id, order: 1)\n\t\tend\n\tend", "def dataset(name)\n datasets[name] = Dataset.new(sources.fetch(name.to_s))\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize( nodes=[], name: nil, group: nil )\n super( nodes )\n\n @name = name\n @group = group\n\n @count = nil\n end", "def initialize(name, group=nil)\n @name = name\n @group = group\n @pred = []\n @succ = []\n end", "def group(name)\n @_group = name\n end", "def initialize(file,name)\n @file = file\n @name = name\n @attr = Hash.new\n @miss = false\n @dims = Array.new\n end", "def initialize(name)\n @name = name\n raise ArgumentError, \"No name present\" if name.empty?\n end", "def initialize(name, options={})\n @name = name.to_sym\n @options = options\n @columns = []\n @indexes = []\n end", "def initialize(name, header, tuples = Empty::ZERO_TUPLE)\n super(header, tuples)\n @name = Immutable.freeze_object(name.to_s)\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(name)\n @name = name\n @@all << self\n end", "def initialize(attributes={})\n super\n self.name = nil unless name\n end", "def initialize(rows=0, columns=0)\n @data = Data.new(rows, columns)\n end", "def group(path, name)\n RubyAem::Resources::Group.new(@client, path, name)\n end", "def initialize(name)\n self.name = name\n reset\n end", "def initialize(name)\n @name = name\n @edges = Hash.new\n end", "def initialize(name)\n name(name)\n end", "def initialize name\n\t\t\t@name = name\n\t\tend", "def initialize(name)\n\n @name = name # The name of the entry\n\n end", "def initialize name\n @name = name\n @sql = nil\n @negative = false\n end", "def initialize(name)\n\n\t\t@name = name\n\n\t\t\t# empty array for the ingredients\n\t\t@ingredient = []\n\tend", "def initialize(name)\n self.name = name.to_s\n self.attributes = []\n self.single_associations = []\n self.array_associations = []\n self.hash_associations = []\n CLASSES << self\n end", "def initialize(name)\n @name = name\n @klass = name.classify\n @table_name = name.tableize\n @custom_table_name = resolve_custom_table_name \n @fields = {}\n @link_fields = {}\n @fields_registered = false\n self\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n @name = name\n @item_array = []\n end", "def initialize()\n @name = '';\n @headers = Array.new;\n @params = Hash.new;\n\t\t@rows = Array.new;\n end", "def group(name)\n return false unless present?(name)\n\n model.group = name\n\n Vedeu.groups.by_name(name).add(model.name)\n end", "def group(name)\n return false unless present?(name)\n\n model.group = name\n\n Vedeu.groups.by_name(name).add(model.name)\n end", "def initialize(name)\n self.name = name\n end", "def initialize(name)\n \n @name = name\n end", "def initialize(name)\n @name = name\n end", "def initialize(name)\n\t\t@name = name\n\t\t@transactions = []\n\tend", "def initialize(name:)\n @name = name\n @@all << self\n end", "def name=(name)\n attributes[:name] = name\n end", "def build(data_set_name)\n raise Interfaces::DataSetAlreadyExists if interface(data_set_name).data_set_exists?\n build!(data_set_name)\n end", "def initialize(name, attributes)\n @name = name\n @attributes = attributes\n end", "def initialize(rows, rownames: nil, colnames: nil)\n @rows = rows\n @rownames = (rownames || Hash[*rows.length.times.map do |i| [i, i] end.flatten(1)]).to_ordered_hash\n unless colnames then\n colnames = {}\n rows.each do |row| row.keys.each do |colname| colnames[colname] = true end end\n colnames = colnames.keys\n end\n @colnames = colnames.collect do |colname| colname.to_s.to_sym end\n end", "def initialize(name = self.class.name, limit: 0)\n @name = name\n @beds = {}\n @max_beds = {}\n @limit = limit\n end", "def +(data)\n DataArray.new(x_name: @x_name, y_axis: @y_axis, data: super(normalize(data)))\n end", "def initialize(name)\n @name = name.to_sym\n @value = {}\n end", "def initialize name\n @name = name\n end", "def dataset(table_name)\n Dataset.new(self, table_name)\n end", "def initialize(name, attr_hash)\n @name = name\n @attr_hash = attr_hash\n end", "def initialize(name)\n super(name)\n @children = {}\n end", "def initialize(name) #initialize with a name\n @@all << self\n\n @name = name\n end", "def group(name = nil)\n if name\n @groups << name\n self.class.groups[name] ||= []\n self.class.groups[name] << self\n else\n @groups\n end\n end", "def initialize(name)\n @name = name\n @gemset_versions = {}\n @gemsets_containing = []\n end", "def initialize(name)\r\n @name=name\r\n\r\n @@all << self\r\n end", "def create_empty_data_set\n BasicInterfaceRegister[@data_lib][@data_set_name] = true\n end", "def initialize(name)\n @name = name \n @@all << self\n end", "def initialize(name)\n @name = name \n @@all << self\n end", "def initialize(name)\n @name = name \n @@all << self\n end", "def initialize(name)\n raise StandardError, 'No name provided!' if name.nil?\n @name = name.to_s\n @start_time = nil\n @end_time = nil\n end", "def reinitialize(name)\r\n @data_stack = @data_stack.clone\r\n @name = name\r\n @data = @data.full_clone\r\n end", "def initialize(name=nil, &block)\n @value = name ? { name: name } : {}\n super\n end", "def initialize(name, params = {})\n params.symbolize_keys!.assert_valid_keys(:name, :tag, :count)\n params.merge!(:name => name, :original_name => name)\n assign params\n end", "def initialize(table, id, data = {})\n @row_id = id\n @table = table\n @attributes = data\n @attributes.clone.\n keep_if{ |col, _| @table.indices.include? col }.\n each_pair{ |col, val| add_to_index(col, val) }\n end", "def initialize(name = '')\r\n @name = ''\r\n @failure_count = 0\r\n end", "def initialize(name, uid)\n @callback_cache = LRUCache.new(ttl: 30.minutes)\n @name = name\n @uid = uid\n group = OmfEc::Group.new(name)\n OmfEc.experiment.add_group(group)\n group.add_resource(uid)\n @group = group\n info \"Finished intialization of WiseGroup (#{name})\"\n end", "def minimal_name_data(name)\n return nil unless name\n\n [\n name.id, # 0\n name.correct_spelling_id, # 1\n name.synonym_id, # 2\n name.text_name # 3\n ]\n end", "def set_group_by(attributes)\n @group_by = GroupByClause.new(attributes)\n end", "def initialize(name, id, year, genre, artist) ##CHANGE # We've added id as a second parameter.\n @name = name\n @id = id || @@total_rows += 1 # We've added code to handle the id.\n @year = year\n @genre = genre\n @artist = artist\n end", "def initialize(name)\n @name = name\n end" ]
[ "0.6130959", "0.59542716", "0.5819765", "0.58026236", "0.56381595", "0.5405932", "0.5394563", "0.5389596", "0.53759176", "0.53447115", "0.52595925", "0.5246296", "0.52027625", "0.50712967", "0.5062148", "0.50427884", "0.5036842", "0.5033747", "0.5016151", "0.50087273", "0.49593017", "0.4938095", "0.49354178", "0.49348858", "0.49348858", "0.49348858", "0.49103335", "0.4896948", "0.48863083", "0.4879535", "0.4872942", "0.48671687", "0.48601156", "0.48267955", "0.48259348", "0.48259348", "0.48259348", "0.48259348", "0.48259348", "0.48228705", "0.48136744", "0.47996008", "0.47980794", "0.47756794", "0.4772956", "0.47682413", "0.47674224", "0.47603294", "0.4757817", "0.47561723", "0.47551468", "0.4754447", "0.4754447", "0.4754447", "0.4754447", "0.4754447", "0.4754447", "0.4754447", "0.4754447", "0.4754447", "0.4754447", "0.4749244", "0.47463563", "0.4743617", "0.4743617", "0.4727695", "0.47251174", "0.4724485", "0.4722357", "0.47176734", "0.46909752", "0.4687336", "0.46859744", "0.46777755", "0.4669186", "0.46578914", "0.46499178", "0.46492407", "0.46463785", "0.46343204", "0.46254987", "0.46210024", "0.46164718", "0.46115822", "0.46044526", "0.4604377", "0.46025458", "0.46025458", "0.46025458", "0.4599194", "0.45978552", "0.45973375", "0.45969108", "0.45964843", "0.4592988", "0.45897302", "0.45872128", "0.45868272", "0.45803374", "0.4573326" ]
0.6525518
0
Simply passes on Enumerable calls to the instance's rows.
def each(&block) @rows.each(&block) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def map!\n @rows = @rows.map { |row| yield row, self }\n end", "def each_row\n @rows.each { |row| yield(row) }\n self\n end", "def each_row\n end", "def each(&block)\n rows.each(&block)\n end", "def each(&block)\n @rows.each(&block)\n end", "def each(&block)\n @rows.each(&block)\n end", "def call!\n rows.map.with_index do |row, row_num|\n process_entities(row, row_num, &:call!)\n end\n end", "def rows\n @rows ||= _row_args.map.with_index do |row_args, i|\n klass, args = row_args\n\n args = args.dup\n options = args.extract_options!\n proc = _row_scopes[i]\n scope = self.instance_eval(&proc)\n\n klass.new(*args, scope, options)\n end\n end", "def rows\n fail \"Implement #{self.class}#rows\"\n end", "def each_row\n return rows.each unless block_given?\n\n rows.each { |row| yield(row) }\n end", "def each\n if block_given?\n rows.each do |row|\n yield row\n end\n self\n else\n to_enum(:each)\n end\n end", "def call\n rows.map.with_index do |row, row_num|\n process_entities(row, row_num, &:call)\n end\n end", "def apply_rows\n return to_enum unless block_given?\n DataFrame.new(each.collect do |row| {:value => yield(row)} end, rownames: @rownames, colnames: [:value])\n end", "def rows\n @rows.lazy\n end", "def each\n while row = next_row\n yield row\n end\n return self\n end", "def row\n new_row = RowBuilder.new\n\n yield new_row\n\n @rows << new_row\n end", "def rows_for(record, &block)\n [row_for(record)].product(*associated_rows_for(record), &block)\n end", "def rows\n RowCollection.new(@data)\n end", "def each\n value.each_with_index do |resource, index|\n yield Row.new(resource, self, index)\n end\n end", "def each\n @rows.each {|x| x.each {|e| yield(e)}}\n nil\n end", "def each\n @reaktor_rows\n end", "def each_row\n @sheet.rowIterator.each { |row| yield row }\n end", "def each\r\n assert_exists\r\n arr_rows = rows\r\n for i in 0..arr_rows.length - 1 do\r\n yield arr_rows[i]\r\n end\r\n end", "def each\n if block_given?\n to_a.each { |row| yield row }\n else\n to_a.each\n end\n end", "def each\n @worksheet.rows.each { |row| yield row.values }\n end", "def rows( start_row = 1, end_row = data.rows )\n return to_enum(:rows, start_row, end_row) unless block_given?\n ( start_row..end_row ).each { |idx| yield row( idx ) }; self\n end", "def rows\n @rows\n end", "def rows\r\n @all_rows\r\n end", "def rows \n @r\n end", "def rows\n Array.new self\n end", "def rows\n @rows\n end", "def rows\n @rows\n end", "def rows\n @rows\n end", "def row; end", "def all_rows\n @rows\n end", "def each\n while row=self.next\n yield row\n end\n end", "def each\n while row=self.next\n yield row\n end\n end", "def method_missing(*args)\n @row.send(*args)\n end", "def with_sql_each(sql)\n if row_proc\n super(sql) do |obj|\n obj.forbid_lazy_load if obj.is_a?(InstanceMethods)\n yield obj\n end\n else\n super\n end\n end", "def each(&block)\n worksheet.rows.each { |row| block.call(row.values) }\n end", "def rows\n return enum_for(:rows) unless block_given?\n\n col_sep = @options['col_sep']\n liberal = @options['liberal_parsing'].presence\n\n delimited_rows(@filename, col_sep, liberal) { |row| yield row }\n end", "def row(row)\n Row.new(@data, row)\n end", "def by_row\r\n Enumerator.new do |yielder|\r\n indices(1) do |ind|\r\n yielder << self[true, *ind]\r\n end\r\n end\r\n end", "def each\n @data.each do |row|\n yield row\n end\n end", "def results_with_rows\n load_from_rows(@dataset.all, true)\n end", "def each_row\n @rows_processed = 0\n @data.each do |h|\n h = h.clone\n transform_row!(h)\n yield h\n @rows_processed += 1\n end\n end", "def each(&block)\n return enum_for :each unless block\n\n %x{\n for (var i = 0, length = #@native.rows.length; i < length; i++) {\n #{block.call(self[`i`])};\n }\n }\n\n self\n end", "def in_rows(renderer, *rows, cols: nil, offset: nil)\n rows += yield(renderer) if block_given?\n\n inner_self = self\n\n renderer.call do\n rows.flatten.compact.map do |row|\n div :row do\n html_class = inner_self.col_offset_class(offset) +\n inner_self.col_class(cols)\n\n div(html_class) { row }\n end\n end\n end\n end", "def rows\n return @rows if @rows\n if execute && result['rows']\n @rows ||= result['rows'].map{|v| ViewRow.new(v, model)}\n else \n [ ]\n end\n end", "def rows\n return @rows\n end", "def rows\n RowEnum.new(self)\n end", "def fetch_rows(sql, &block)\n raise NotImplementedError, NOTIMPL_MSG\n end", "def initialize(rows)\n @rows = rows\n end", "def each( &blk )\n @table.each( &blk )\n end", "def rows\n return enum_for(:rows) unless block_given?\n\n safe_path = SafeFile.safepath_to_string(@filename)\n\n # By now, we know `encodings` should let us read the whole\n # file succesfully; if there are problems, we should crash.\n CSVLibrary.foreach(safe_path, encodings(safe_path)) do |line|\n yield line.map(&:to_s)\n end\n end", "def each_row\n @board.each do |row|\n yield row\n end\n end", "def each_row(batch = ETL::Batch.new)\n @rows_processed = 0\n @data.each do |h|\n h = h.clone\n transform_row!(h)\n yield h\n @rows_processed += 1\n end\n end", "def mapped_rows(custom_mapper = nil)\n local_mapper = custom_mapper || mapper\n return rows if local_mapper.nil?\n\n rows do |row|\n mapped = local_mapper.apply(row)\n if block_given?\n yield mapped\n else\n mapped\n end\n end\n end", "def each_row(batch = ETL::Batch.new)\n log.warning(\"Called ETL::Input::Base::each_row()\")\n end", "def process_row(row)\n row\n end", "def each(&block)\n @table.values.each(&block)\n end", "def rows\n @array\n end", "def rows=(value)\n @rows = value\n end", "def fetch_rows(sql, &block)\n execute(sql) do |r|\n r.each(:symbolize_keys => true, &block)\n end\n self\n end", "def fetch_rows(sql, opts=OPTS, &block)\n db.execute(sql){|result| process_result_set(result, opts, &block)}\n self\n end", "def format_rows\n [trait.format_row(self)]\n end", "def each_entry(&b)\n @table.each(&b)\n end", "def each_entry(&b)\n @table.each(&b)\n end", "def each_item\n each {|row| row.each { |item| yield item }}\n end", "def set_dataset_row_proc(ds)\n ds.with_row_proc(self)\n end", "def set_dataset_row_proc(ds)\n ds.with_row_proc(self)\n end", "def within_row(*arguments, **options, &block)\n within(:row, *arguments, **options, &block)\n end", "def each!\r\n each do |item, i, j|\r\n @table[i][j] = yield(@table[i][j], i, j) || @table[i][j]\r\n end\r\n\r\n self # Chainability! Yay!\r\n end", "def each_row_streaming(&block)\n Roo::Utils.each_element(@path, 'row', &block)\n end", "def _row_processor\n schema = @table.schema\n lambda do |rec|\n if rec[:domain] == \"sys\" && rec[:key] == \"state\"\n @experiment.state = rec[:value]\n if @experiment.completed?\n EM.defer do\n begin\n v = JSON.parse(Net::HTTP.get(URI(\"#{@experiment.job_url}/verifications\")))[\"verification\"].first\n if v && v[\"href\"]\n r = JSON.parse(Net::HTTP.get(URI(v[\"href\"])))[\"result\"]\n\n r.each do |k, v|\n v = v.nil? ? \"_undefined_\" : v.to_s\n @table << schema.hash_to_row(domain: \"verify\", key: k, value: v)\n end\n end\n rescue => ex\n warn \"Exception while querying a job - #{ex}\"\n debug \"While querying a job - \\n\\t#{ex.backtrace.join(\"\\n\\t\")}\"\n end\n end\n end\n end\n @table << schema.hash_to_row(rec)\n end\n end", "def each_row\n\t\t@grid.each do |row|\n\t\t\tyield row\n\t\tend\n\tend", "def prefetch_rows\n raise NoMethodError, \"Not implemented for this raw driver\"\n end", "def row\n get_row\n respond_to_action(:row)\n end", "def rows\n @rows ||= begin\n row_indexes.map do |e|\n e.map do |e|\n @input[e]\n end\n end\n end\n end", "def each_row(&block)\n ::Enumerator.new { |enumerator|\n headers, eof = *self.read_headers\n\n until eof\n row, eof = *self.read_row\n\n unless eof\n enumerator << row\n end\n end\n }.each(&block)\n end", "def iterator\n @table.iterator\n end", "def row(i) # :yield: e\n if block_given?\n for e in @rows[i]\n yield e\n end\n else\n Vector.elements(@rows[i])\n end\n end", "def associated_rows_for(record)\n @includes.map do |method, attributes|\n associated_rows(Array.wrap(record.send(method)), attributes)\n end\n end", "def each(&block)\n\t plan.query_each(result_set, &block)\n\t self\n\tend", "def handle_row(business, row)\n\n end", "def each\n @pool.with do |conn|\n conn.send_query @sql\n conn.set_single_row_mode\n loop do\n res = conn.get_result\n break unless res\n res.check\n res.stream_each { |row| yield row }\n end\n end\n end", "def rows\n @rows.to_enum\n end", "def each_row\n return enum_for(:each_row) unless block_given?\n\n batch.un_pre_assembled_objects.each do |dobj|\n row = process_dobj(dobj)\n summary[:total_size] += row.counts[:total_size]\n if row.errors.empty?\n status = 'success'\n else\n summary[:objects_with_error] += 1\n status = 'error'\n end\n row.counts[:mimetypes].each { |k, v| summary[:mimetypes][k] += v }\n # log the output to a running progress file\n File.open(batch.batch_context.progress_log_file, 'a') { |f| f.puts log_progress_info(dobj, status).to_yaml }\n yield row.to_h\n end\n end", "def each(&block)\n table.values.each(&block)\n end", "def each(&block)\n @result_records.each(&block)\n end", "def with_row_proc(attribute)\n row_proc = row_proc_from(attribute)\n yield(row_proc) if row_proc\n end", "def map!(&block_)\n raise TableLockedError if @parent\n @vals.map!(&block_)\n self\n end", "def each(&block)\n @records.each(&block)\n end", "def rows\n CellCollection.new(@data, @column)\n end", "def each_row\n return enum_for(__method__) unless block_given?\n yield codec.decode( io ) until io.eof?\n end", "def each(opts = nil, &block)\n if graph = @opts[:graph]\n graph_each(opts, &block)\n else\n row_proc = @row_proc unless opts && opts[:naked]\n transform = @transform\n fetch_rows(select_sql(opts)) do |r|\n r = transform_load(r) if transform\n r = row_proc[r] if row_proc\n yield r\n end\n end\n self\n end", "def each\n raise ResultsAlreadyConsumedException unless @unread\n\n if block_given?\n @unread = false\n @source.each { |row| yield symbolize_row_keys(row) }\n else\n Enumerator.new(self)\n end\n end", "def each(_skip = nil, &block)\n @sheet.rowIterator.each(&block)\n end", "def each\n @rows.each do |row|\n row.each do |col|\n\tyield col\n end\n end\n end" ]
[ "0.7541582", "0.7363567", "0.725783", "0.7149952", "0.71447235", "0.71447235", "0.7054897", "0.7043491", "0.7016991", "0.70161694", "0.6978905", "0.685917", "0.6853187", "0.6813307", "0.68119425", "0.674367", "0.6717421", "0.67022157", "0.66690457", "0.6616909", "0.6603494", "0.6586878", "0.65702266", "0.65692765", "0.65277594", "0.6522521", "0.6521855", "0.6499528", "0.6488251", "0.64689606", "0.64577085", "0.64577085", "0.64577085", "0.6441209", "0.6433971", "0.6433965", "0.6433965", "0.64187396", "0.6410592", "0.64079326", "0.6351528", "0.6347532", "0.63466", "0.6312709", "0.6310183", "0.63067096", "0.63049376", "0.63011754", "0.6278667", "0.62692314", "0.6264672", "0.6263633", "0.6258898", "0.62407607", "0.62326294", "0.62179047", "0.6200889", "0.6185238", "0.6175041", "0.6163664", "0.61504495", "0.61400956", "0.6098623", "0.60931134", "0.6078814", "0.60690904", "0.6054971", "0.6054971", "0.6042374", "0.6040577", "0.6040577", "0.6034911", "0.6034224", "0.6018039", "0.60046184", "0.6004223", "0.600308", "0.5999123", "0.59922034", "0.5987893", "0.5973436", "0.5965636", "0.5964091", "0.5960531", "0.59601516", "0.59585375", "0.59518915", "0.594689", "0.59435517", "0.5936348", "0.5932521", "0.59253496", "0.59155196", "0.5914168", "0.59096205", "0.59083945", "0.5898332", "0.58630246", "0.584778" ]
0.72366005
4
Returns a tabular string representation of the attribute group's data. If +column_names+ is non+nil+, only returns data for the columns specified; otherwise returns data for all columns. +column_names+:: An array of columsn to display data for. +format+:: The format to output data in. Must be either :text or :html. If it is not one of these, outputs as text.
def to_table(column_names=nil, format="text") require 'tabular' stringio = StringIO.new; $stderr.puts "Request for #{@name} data returned #{@rows.length} #{@rows.length != 1 ? "rows" : "row"}." if rows.length > 0 # If no column names were specified, use all the columns in the first row (in alphabetical order) column_names = @rows[0].keys.sort if !column_names # Create a table with a Column for each column name columns = column_names.collect { |column_name| Tabular::Column.new(column_name) } table = Tabular::Table.new(*columns) # Create our array of data rows data = @rows.collect { |row| column_names.collect { |column_name| row[column_name] } } # Set the table's data and write out the tabular representation to stringio table.data = data stringio.puts(format == :html ? table.to_html("Data for #{self.name}") : table.to_s) end stringio.string end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def serialize_attributes(format, *columns)\n if format.is_a?(Symbol)\n unless format = REGISTERED_FORMATS[format]\n raise(Error, \"Unsupported serialization format: #{format} (valid formats: #{REGISTERED_FORMATS.keys.map(&:inspect).join})\")\n end\n end\n serializer, deserializer = format\n raise(Error, \"No columns given. The serialization plugin requires you specify which columns to serialize\") if columns.empty?\n define_serialized_attribute_accessor(serializer, deserializer, *columns)\n end", "def to_csv(format = :long)\n output = ''\n \n columns = []\n # only output\n case format\n when :long\n columns.concat([@id, @updated, @title])\n end\n \n # output all dimensions\n columns.concat(@dimensions.map {|d| d.values.first})\n \n # output all metrics\n columns.concat(@metrics.map {|m| m.values.first})\n\n output = CSV.generate_line(columns) \n return output\n end", "def format\n text = \"[#{name}]\\n\"\n @entries.each do |entry|\n if entry.is_a?(Array)\n key, value = entry\n text << \"#{key}=#{value}\\n\" unless value.nil?\n else\n text << entry\n end\n end\n text\n end", "def to_html(options = {})\n case axes_count\n when 1\n builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |doc|\n doc.table do\n doc.tr do\n column_full_names.each do |column_full_name|\n column_full_name = column_full_name.join(',') if column_full_name.is_a?(Array)\n doc.th column_full_name, :align => 'right'\n end\n end\n doc.tr do\n (options[:formatted] ? formatted_values : values).each do |value|\n doc.td value, :align => 'right'\n end\n end\n end\n end\n builder.doc.to_html\n when 2\n builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |doc|\n doc.table do\n doc.tr do\n doc.th\n column_full_names.each do |column_full_name|\n column_full_name = column_full_name.join(',') if column_full_name.is_a?(Array)\n doc.th column_full_name, :align => 'right'\n end\n end\n (options[:formatted] ? formatted_values : values).each_with_index do |row, i|\n doc.tr do\n row_full_name = row_full_names[i].is_a?(Array) ? row_full_names[i].join(',') : row_full_names[i]\n doc.th row_full_name, :align => 'left'\n row.each do |cell|\n doc.td cell, :align => 'right'\n end\n end\n end\n end\n end\n builder.doc.to_html\n else\n raise ArgumentError, \"just columns and rows axes are supported\"\n end\n end", "def format_for(location, **fmts)\n unless LOCATIONS.include?(location)\n raise UserError, \"unknown format location '#{location}'\"\n end\n\n fmts = fmts.transform_keys do |k|\n if k == :nilclass\n :nil\n elsif k == :date\n :datetime\n else\n k\n end\n end\n\n @format_at[location] ||= {}\n table.headers.each do |h|\n # Build the inner hash of formatting instructions for this column h,\n # beginning with the default formatting hash or any existing inner\n # hash.\n format_h =\n if format_at[location][h].empty?\n default_format\n else\n format_at[location][h].to_h\n end\n\n # Merge in string and nil formatting for this column h, but not in\n # header location. Header is always typed a string, so it will get\n # formatted in type-based formatting below. And headers are never nil.\n unless location == :header\n if fmts.key?(:string)\n typ_fmt = parse_fmt_string(fmts[:string])\n format_h = format_h.merge(typ_fmt)\n end\n if fmts.key?(:nil)\n typ_fmt = parse_nilclass_fmt(fmts[:nil], strict: false).first\n format_h = format_h.merge(typ_fmt)\n end\n end\n\n # Merge in formatting instructions for column h based on the column\n # name, or if there is no formatting instructions for the column by\n # name, merge in the formatting instructions based on the column's\n # type. Insist on only the string type for the header location.\n typ = (location == :header ? :string : table.type(h).as_sym)\n parse_typ_method_name = 'parse_' + typ.to_s + '_fmt'\n if fmts[h]\n # Merge in column formatting\n col_fmt = send(parse_typ_method_name, fmts[h],\n strict: location != :header).first\n format_h = format_h.merge(col_fmt)\n elsif fmts.key?(typ)\n # Merge in type-based formatting\n typ_fmt = send(parse_typ_method_name, fmts[typ]).first\n format_h = format_h.merge(typ_fmt)\n end\n\n # Copy :body formatting for column h to :bfirst and :gfirst if they\n # still have the default formatting. Can be overridden with a\n # format_for call with those locations.\n if location == :body\n format_h.each_pair do |k, v|\n if format_at[:bfirst][h].send(k) == self.class.default_format[k]\n format_at[:bfirst][h].send(\"#{k}=\", v)\n end\n if format_at[:gfirst][h].send(k) == self.class.default_format[k]\n format_at[:gfirst][h].send(\"#{k}=\", v)\n end\n end\n elsif location == :gfirst\n # Copy :gfirst formatting to :bfirst if it is still the default\n format_h.each_pair do |k, v|\n if format_at[:bfirst][h].send(k) == self.class.default_format[k]\n format_at[:bfirst][h].send(\"#{k}=\", v)\n end\n end\n end\n\n # Record its origin (using leading underscore so not to clash with any\n # headers named h or location) and convert to struct\n format_h[:_h] = h\n format_h[:_location] = location\n format_at[location][h] = OpenStruct.new(format_h)\n end\n self\n end", "def format_for(location, **fmts)\n unless LOCATIONS.include?(location)\n raise UserError, \"unknown format location '#{location}'\"\n end\n\n valid_keys = table.headers + %i[string numeric datetime boolean nil]\n invalid_keys = (fmts.keys - valid_keys).uniq\n unless invalid_keys.empty?\n msg = \"invalid #{location} column or type: #{invalid_keys.join(',')}\"\n raise UserError, msg\n end\n\n @format_at[location] ||= {}\n table.headers.each do |h|\n # Default formatting hash\n format_h =\n if format_at[location][h].empty?\n default_format.dup\n else\n format_at[location][h].to_h\n end\n\n unless location == :header\n # Merge in string and nil formatting, but not in header. Header is\n # always typed a string, so it will get formatted in type-based\n # formatting below. And headers are never nil.\n if fmts.key?(:string)\n typ_fmt = parse_string_fmt(fmts[:string])\n format_h = format_h.merge(typ_fmt)\n end\n if fmts.key?(:nil)\n typ_fmt = parse_nil_fmt(fmts[:nil]).first\n format_h = format_h.merge(typ_fmt)\n end\n end\n typ = location == :header ? :string : table.type(h).as_sym\n parse_typ_method_name = 'parse_' + typ.to_s + '_fmt'\n if fmts.key?(typ)\n # Merge in type-based formatting\n typ_fmt = send(parse_typ_method_name, fmts[typ])\n format_h = format_h.merge(typ_fmt)\n end\n if fmts[h]\n # Merge in column formatting\n col_fmt = send(parse_typ_method_name, fmts[h],\n strict: location != :header)\n format_h = format_h.merge(col_fmt)\n end\n\n if location == :body\n # Copy :body formatting for column h to :bfirst and :gfirst if they\n # still have the default formatting. Can be overridden with a\n # format_for call with those locations.\n format_h.each_pair do |k, v|\n if format_at[:bfirst][h].send(k) == default_format[k]\n format_at[:bfirst][h].send(\"#{k}=\", v)\n end\n if format_at[:gfirst][h].send(k) == default_format[k]\n format_at[:gfirst][h].send(\"#{k}=\", v)\n end\n end\n elsif location == :gfirst\n # Copy :gfirst formatting to :bfirst if it is still the default\n format_h.each_pair do |k, v|\n if format_at[:bfirst][h].send(k) == default_format[k]\n format_at[:bfirst][h].send(\"#{k}=\", v)\n end\n end\n end\n\n # Record its origin (using leading underscore so not to clash with any\n # headers named h or location) and convert to struct\n format_h[:_h] = h\n format_h[:_location] = location\n format_at[location][h] = OpenStruct.new(format_h)\n end\n self\n end", "def format_html\n formatted = \"<table summary=\\\"Tide tables with columns for time of day and tide height (in meters).\\\">\\n\\t<thead>\\n\\t\\t<tr><th scope=\\\"col\\\">Time</th><th scope=\\\"col\\\">Height</th></tr>\\n\\t</thead>\\n\"\n last_date = nil\n to_csv.each_line do |row|\n row = row.chomp.split(',')\n if row[0] != last_date\n formatted += \"\\t</tbody>\\n\" unless last_date.nil?\n formatted += \"\\t<tbody>\\n\\t\\t<tr><th scope=\\\"rowgroup\\\" colspan=\\\"2\\\">#{row[0]}</th></tr>\\n\"\n last_date = row[0]\n end\n formatted += \"\\t\\t<tr><td>#{row[1]}</td><td>#{row[2]}m</td></tr>\\n\"\n end\n formatted += \"\\t</tbody>\\n</table>\\n\"\n formatted\n end", "def output\n # If there are neither headers nor any rows in the table, return an\n # empty string.\n return '' if table.empty? && table.headers.empty?\n\n # This results in a hash of two-element arrays. The key\n # is the header and the value is an array of the header and formatted\n # header. We do the latter so the structure parallels the structure for\n # rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n if loc_row.nil?\n result += hline(widths)\n next\n end\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end", "def serialize_attributes(format, *columns)\n raise(Error, \"Unsupported serialization format (#{format}), should be :marshal, :yaml, or :json\") unless [:marshal, :yaml, :json].include?(format)\n raise(Error, \"No columns given. The serialization plugin requires you specify which columns to serialize\") if columns.empty?\n define_serialized_attribute_accessor(format, *columns)\n end", "def format_rows descriptions\n formatted = descriptions.map do |description|\n @column_descriptions.map do |field, _, format,|\n format % description[field]\n end\n end\n\n [@headers].concat formatted\n end", "def output\n # This results in a hash of two-element arrays. The key is the header and\n # the value is an array of the header and formatted header. We do the\n # latter so the structure parallels the structure for rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n result += hline(widths) if loc_row.nil?\n next if loc_row.nil?\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end", "def to_s\n empty = ''.freeze\n tr = 'tr'.freeze\n th = 'th'.freeze\n td = 'td'.freeze\n nl = \"\\n\".freeze\n tr_attr = @opts[:tr]\n th_attr = @opts[:th]\n td_attr = @opts[:td]\n col_th = @opts[:column_th]\n\n t = tag('table', empty, @opts[:table])\n s = t.open.dup\n s << nl\n\n if caption = @opts[:caption]\n s << tag(:caption, caption).to_s\n end\n\n if widths = @opts[:widths]\n s << \"<colgroup>\\n\"\n widths.each do |w|\n s << \"<col width=\\\"#{w.to_i}\\\" />\\n\"\n end\n s << \"</colgroup>\\n\"\n end\n\n if headers = @opts[:headers]\n s << \"<thead>\\n\"\n headers = headers.split(',') if headers.is_a?(String)\n trh = tag(tr, empty, handle_proc(tr_attr, headers))\n s << trh.open\n s << nl\n headers.each_with_index do |header, i|\n s << tag(th, header, handle_proc(th_attr, header)).to_s\n end\n s << trh.close\n s << \"</thead>\\n\"\n end\n\n s << \"<tbody>\\n\"\n @rows.each do |row|\n trh = tag(tr, empty, handle_proc(tr_attr, row))\n s << trh.open\n s << nl\n row.each_with_index do |col, i|\n s << tag((col_th && i == 0 ? th : td), col, handle_proc(td_attr, col, i, row)).to_s\n end\n s << trh.close\n end\n s << \"</tbody>\\n\"\n s << t.close\n end", "def format_metadata(obj)\n '<table class=\"table table-sm table-responsive\">' +\n obj.metadata.data.map do |k, v|\n case k\n when /^run_/, :plugins, :user\n next\n when :web_assembly_gz\n v = \"<a href='#{v}'>#{v[0..50]}...</a>\"\n when :datasets\n v = v.size\n end\n \"<tr><td class='text-right pr-4'><b>#{format_name(k)}</b></td>\" \\\n \"<td>#{v}</td></tr>\"\n end.compact.join('') +\n '</table>'\n end", "def column_attrs\n attrs = {}\n\n if params[:institution_id]\n attrs[Institution] = [params[:institution_id], :abbreviation]\n end\n\n if params[:provider_id]\n attrs[Provider] = [params[:provider_id], :abbreviation]\n end\n\n if params[:program_id]\n attrs[Program] = [params[:program_id], :abbreviation]\n end\n\n if params[:core_id]\n attrs[Core] = [params[:core_id], :abbreviation]\n end\n\n attrs[\"Unique PI Last Name\"] = :last_name\n attrs[\"Unique PI First Name\"] = :first_name\n attrs[\"Email\"] = :email\n attrs[\"Institution\"] = \"try(:professional_org_lookup, 'institution')\"\n attrs[\"College\"] = \"try(:professional_org_lookup, 'college')\"\n attrs[\"Department\"] = \"try(:professional_org_lookup, 'department')\"\n attrs[\"Division\"] = \"try(:professional_org_lookup, 'division')\"\n attrs[\"ERA Commons Name\"] = :era_commons_name\n attrs[\"ORCID\"] = :orcid\n\n if Setting.get_value(\"displayed_demographics_fields\").include?(\"gender\")\n attrs[\"Gender\"] = \"self.display_gender\"\n end\n\n if Setting.get_value(\"displayed_demographics_fields\").include?(\"age_group\")\n attrs[\"Age Group\"] = \"self.display_age_group\"\n end\n\n if Setting.get_value(\"displayed_demographics_fields\").include?(\"ethnicity\")\n attrs[\"Hispanic/Latino?\"] = \"self.display_ethnicity\"\n end\n\n if Setting.get_value(\"displayed_demographics_fields\").include?(\"race\")\n attrs[\"Race\"] = \"self.display_races\"\n end\n attrs\n end", "def default_formats\n attr_formats = {}\n columns.each do |column|\n attr_formats[column.name] = case column.type\n when :integer, :float\n {:class => :right, :formatter => :number_with_delimiter}\n when :text, :string\n {}\n when :date, :datetime\n {}\n else\n {}\n end\n end\n attr_formats\n end", "def format(id, value, options = {})\n id.split(/,\\s/).each do |i|\n col = col_by_id i, true\n col.format = value\n col.format_options = options\n end\n end", "def build_formatted_headers(_widths = {})\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n map = {}\n table.headers.each do |h|\n istruct = format_at[:header][h]\n map[h] = [h, format_cell(h.as_string, istruct, decorate: decorate)]\n end\n map\n end", "def build_formatted_headers(_widths = {})\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n map = {}\n table.headers.each do |h|\n istruct = format_at[:header][h]\n map[h] = [h, format_cell(h.as_string, istruct, decorate: decorate)]\n end\n map\n end", "def _prepare_format #:nodoc:\n fmstr = nil\n fmt = []\n each_column { |c, i|\n ## trying a zero for hidden columns\n ## worked but an extra space is added below and the sep\n w = c.width\n case c.align\n when :right\n #fmt << \"%.#{w}s \"\n fmt << \"%#{w}.#{w}s \"\n else\n fmt << \"%-#{w}.#{w}s \"\n end\n }\n ## the next line will put a separator after hidden columns also\n fmstr = fmt.join(@y)\n #puts \"format: #{fmstr} \" # 2011-12-09 23:09:57\n return fmstr\n end", "def to_s\n result = \"\"\n\n separator = []\n result += @header.map do |key|\n separator << sprintf(\"%-#{@max_length[key.to_sym]}s\", @@header_line*(@max_length[key.to_sym]+2))\n sprintf \" %-#{@max_length[key.to_sym]}s \", key\n end.join(@@separator)\n result += \"\\n\"\n result += separator.join(@@header_separator) + \"\\n\"\n\n @data.each do |row|\n result += @header.map do |key|\n additional_width = 0\n value = format_value(row, key)\n if value.is_a? String\n additional_width = value.length - value.uncolorize.length\n end\n sprintf \" %-#{@max_length[key.to_sym] + additional_width}s \", value\n end.join(@@separator)\n result += \"\\n\"\n end\n result\n end", "def formats\n format\n end", "def format(name=nil)\n @format = name.to_s if name\n @format || DEFAULT_FORMAT\n end", "def formats\n attributes.fetch(:formats)\n end", "def attributes\n table = terminal_table do |t|\n t.title = name.upcase\n t.add_row [\"Price USD:\", \"$#{price_usd}\"]\n t.add_row [\"Price BTC:\", \"#{price_btc}\"]\n t.add_row [\"Market Cap USD:\", \"$#{market_cap_usd}\"]\n t.add_row [\"Change Last 24h:\", \"#{percent_change_24h}%\"]\n t.add_row [\"Last Updated:\", \"#{Time.at(last_updated_unix.to_i)}\"]\n t.style = { all_separators: true, width: 60 }\n end\n puts table\n end", "def format\n @item_attributes.first.format.collect {|f| f.to_s}\n end", "def format_options(options)\n data = []\n options.each do |name, option_spec|\n data << format_option(option_spec)\n end\n \"Options:\\n\" + render_table(data, \": \")\n end", "def show(*args)\n r=map { |record| \n args.map { |attr| \n # If the attribute has a . in it, we split it and go down it recursively, so we can \n # print items in associated models\n as = attr.to_s.split('.')\n r = record.send(as.shift.to_sym)\n as.each { |a| \n r = r.send(a.to_sym)\n }\n if Array === r \n r = r*','\n elsif Hash ===r\n r = r.inspect\n else\n r.to_s \n end\n } \n }\n # Find the max width for each column\n max = (0...args.length).map { |i| \n column = r.map { |row| row[i] }\n column.map{ |s| s.length}.max \n }\n format = max.map{ |l| \"%#{l}s\"}.join(\" : \") + \"\\n\" \n r.each { |row|\n printf format,*row\n }\n nil\n end", "def format(**fmts)\n %i[header bfirst gfirst body footer gfooter].each do |loc|\n format_for(loc, **fmts)\n end\n self\n end", "def format(**fmts)\n %i[header bfirst gfirst body footer gfooter].each do |loc|\n format_for(loc, **fmts)\n end\n self\n end", "def header_str\n @columns.collect {|c|\n if @table[c]\n #{}\"%#{@table[c][:size]}s\" % [@table[c][:name]]\n format_data(c, @table[c][:name])\n else\n nil\n end\n }.compact.join(' ')\n end", "def inspect\n to_table.render :ascii\n end", "def print_table(columns, data, print_headings = true)\n\n # Fill base lengths\n columns.each do |col|\n col[:length] = (print_headings ? col[:title].length : 0)\n end\n\n # Compute maximum length of each field\n data.each do |datum|\n\n columns.each do |col|\n if (col[:func] != nil)\n str = col[:func].call(datum).to_s\n else\n str = datum[col[:key]].to_s\n end\n str = str.gsub(/\\e\\[[0-9;]*m/, '') # eliminate \"colors\"\n col[:length] = [ col[:length], str.length ].max\n end\n\n end\n\n # Create the format string\n table_format_row = '|'\n columns.each do |col|\n if (col[:type] == :int)\n table_format_row << sprintf(\" %%%dd |\", col[:length])\n else\n table_format_row << sprintf(\" %%-%ds |\", col[:length])\n end\n end\n table_format_row << \"\\n\"\n\n # Special line: title\n table_format_title = \"\\e[1m\\e[4m\" +\n table_format_row.gsub(/%-?([0-9]+)[a-z]/, '%-\\1s').gsub(/\\|/, ' ') + \"\\e[m\"\n\n # Create the horizontal line\n table_horizontal = '+'\n columns.each do |col|\n table_horizontal << '-' * (col[:length]+2) << '+'\n end\n\n # Print table\n if (print_headings)\n titles = []\n columns.each do |col|\n titles << col[:title]\n end\n #puts table_horizontal\n printf(table_format_title, *titles);\n else\n puts table_horizontal\n end\n\n data.each do |datum|\n cols_ary = []\n columns.each do |col|\n if (col[:func])\n cols_ary << col[:func].call(datum)\n else\n cols_ary << datum[col[:key]]\n end\n end\n printf(table_format_row, *cols_ary)\n #puts table_horizontal\n end\n puts table_horizontal\n\nend", "def fmt(*spec)\n ::Col::Formatter.new(@strings, *spec).result\n end", "def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n out_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # NB: grp is an array of hashes, one for each row in the group.\n #\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n out_rows << nil if include_header_row? || grp_k.positive?\n # Format group body rows\n grp.each_with_index do |row, grp_row_k|\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n\n out_row = {}\n row.each_pair do |h, v|\n istruct = format_at[location][h]\n out_row[h] = [row[h], format_cell(row[h], istruct, decorate: decorate)]\n end\n out_rows << [location, out_row]\n tbl_row_k += 1\n end\n # Format group footers\n gfooters.each_pair do |label, gfooter|\n out_rows << nil\n gfoot_row = Hash.new([nil, ''])\n gfooter.to_h(grp_k).each_pair do |h, v|\n istruct = format_at[:gfooter][h]\n gfoot_row[h] = [v, format_cell(v, istruct, decorate: decorate)]\n end\n out_rows << [:gfooter, gfoot_row]\n end\n end\n out_rows\n end", "def to_html\n %Q|<table border=1>\\n<caption>#@name</caption>\\n| + data.map { |row| '<tr>' + row.map { |v| '<td>' + CGI.escapeHTML(v.to_s) }.join }.join(\"\\n\") + \"\\n</table>\"\n end", "def render(columns)\n output = ''\n columns.each do |column|\n m = column.name\n output << if m == :name && @selected\n column.render(color.white.bold(@name) + color.bold.yellow('>'))\n else\n column.render(send(m))\n end\n end\n output\n end", "def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n new_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n new_rows << nil if include_header_row? || grp_k.positive?\n # Compute group body\n grp_col = {}\n grp.each_with_index do |row, grp_row_k|\n new_row = {}\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n table.headers.each do |h|\n grp_col[h] ||= Column.new(header: h)\n grp_col[h] << row[h]\n istruct = format_at[location][h]\n new_row[h] = [row[h], format_cell(row[h], istruct,\n decorate: decorate)]\n end\n new_rows << [location, new_row]\n tbl_row_k += 1\n end\n # Compute group footers\n gfooters.each_pair do |label, gfooter|\n # Mark the beginning of a group footer\n new_rows << nil\n gfoot_row = {}\n first_h = nil\n grp_col.each_pair do |h, col|\n first_h ||= h\n gfoot_row[h] =\n if gfooter[h]\n val = col.send(gfooter[h])\n istruct = format_at[:gfooter][h]\n [val, format_cell(val, istruct, decorate: decorate)]\n else\n [nil, '']\n end\n end\n if gfoot_row[first_h].last.blank?\n istruct = format_at[:gfooter][first_h]\n gfoot_row[first_h] =\n [label, format_cell(label, istruct, decorate: decorate)]\n end\n new_rows << [:gfooter, gfoot_row]\n end\n end\n new_rows\n end", "def format\n collect { |a| a.format }\n end", "def format\n @format\n end", "def format(format_name)\n valid_for 'string'\n assert_string format_name\n set format: format_name\n end", "def to_s\n columns.each{|c| \"#{c}: #{self.send(c)}\\n\"}\n end", "def table(header, values, io = $stdout)\n self.puts(io, MiGA.tabulate(header, values, self[:tabular]))\n end", "def to_s\n stringio = StringIO.new\n\n # Set the column widths\n if @data\n @data.each do |row|\n next if row.length != @columns.length\n\n @columns.each_with_index do |column, i|\n data_string = column.data_to_s.call(row[i])\n column.width = data_string.length if data_string.length > column.width\n end\n end\n else\n @columns.each { |column| column.width = column.label.length }\n end\n\n # Print the column headers\n stringio.puts(@columns.collect do |column|\n padding = column.padding || \" \"\n padding + column.label.center(column.width) + padding\n end.join(\"|\"))\n\n total_width = stringio.string.length - 1\n\n # Print the bar below the column header\n stringio.puts(@columns.collect do |column|\n padding = column.padding || \" \"\n \"-\" * (column.width + 2 * padding.length)\n end.join(\"+\"))\n\n # If we have rows, print each one, otherwise print \"No rows\"\n if @data\n @data.each do |row|\n # Skip rows that have the wrong number of columns\n next if row.length != @columns.length\n\n # Generate the row of data. These machinations with the index variable are because collect_with_index doesn't exist\n # and Ruby 1.8.x doesn't support each_with_index.collect.\n i = 0\n stringio.puts(row.collect do |data|\n padded_aligned_data = @columns[i].padded_aligned_data(data)\n i += 1\n padded_aligned_data\n end.join(\"|\"))\n end\n else\n stringio.puts(\"No rows\".center(total_width))\n end\n\n stringio.string\n end", "def column_attrs\n attrs = {}\n attrs[\"Service Provider\"] = \"identity.full_name\"\n attrs[\"Provider/Program (First Available)\"] = \"self.identity.display_available_provider_program_name\"\n attrs[\"Date Entered\"] = \"self.created_at.try(:strftime, \\\"%Y-%m-%d\\\")\"\n attrs[\"Subject of Interaction\"] = :display_subject\n attrs[\"Type of Interaction\"] = :display_interaction_type\n attrs[\"Duration in minutes\"] = :duration_in_minutes\n attrs[\"Investigator Name\"] = :name\n attrs[\"Investigator Email\"] = :email\n attrs[\"Investigator Institution\"] = :institution\n attrs[\"Notes\"] = :note\n \n attrs\n end", "def to_s\n header_output = build_header_output\n data_output = build_data_output\n\n string = ''\n string << Yummi.colorize(@title, @style[:title]) << $/ if @title\n string << Yummi.colorize(@description, @style[:description]) << $/ if @description\n table_data = header_output + data_output\n if @layout == :vertical\n # don't use array transpose because the data may differ in each line size\n table_data = rotate table_data\n end\n string << content(table_data)\n end", "def render\n raise \"tabular:: list is nil \" unless @list\n $log.debug \" render list:: #{@list.size} \"\n #$log.debug \" render list:1: #{@list} \"\n raise \"tabular:: columns is nil \" unless @columns\n buffer = []\n @separ = nil\n _guess_col_widths\n rows = @list.size.to_s.length\n #@rows = rows\n fmstr = _prepare_format\n $log.debug \"tabular: fmstr:: #{fmstr}\"\n $log.debug \"tabular: cols: #{@columns}\"\n #$log.debug \"tabular: data: #{@list}\"\n\n str = \"\"\n if @numbering\n str = \" \"*(rows+1)+@y\n end\n #str << fmstr % visible_column_names()\n str << convert_heading_to_text(visible_column_names(), fmstr)\n buffer << str\n #puts \"-\" * str.length\n buffer << separator if @use_separator\n if @list ## XXX why wasn't numbering done in _prepare_format ???? FIXME\n if @numbering\n fmstr = \"%#{rows}d \"+ @y + fmstr\n end\n #@list.each { |e| puts e.join(@y) }\n count = 0\n @list.each_with_index { |r,i| \n if r == :separator\n buffer << separator\n next\n end\n if @_hidden_columns_flag\n r = visible_columns(r)\n end\n if @numbering\n r.insert 0, count+1\n end\n #value = convert_value_to_text r, count\n value = convert_value_to_text r, fmstr, i\n buffer << value\n count += 1\n }\n end\n buffer\n end", "def inspect\n pairs = []\n # Use the table's column list to order our columns\n @table.columns.each { |name| pairs << \"#{name}: #{@attributes[name].inspect}\"}\n inspection = pairs.compact.join(', ')\n \"#<#{self.class} #{inspection}>\"\n end", "def format_data\n formatted_rows = []\n @data.each do |row|\n values = []\n row.each_with_index do |entry,index|\n # Format/escape individual values for javascript, checking column types, and the ruby value as a failsafe\n safe_val = if @column_types[index] == \"date\" || entry.is_a?(Date)\n # Format a date object as a javascript date\n entry.is_a?(String) ? entry : \"new Date (#{entry.year},#{entry.month - 1},#{entry.day})\"\n elsif @column_types[index] == \"datetime\" || entry.is_a?(Time)\n # Format a Time (datetime) as a javascript date object down to seconds\n entry.is_a?(String) ? entry : \"new Date (#{entry.year},#{entry.month - 1},#{entry.day},#{entry.hour},#{entry.min},#{entry.sec})\"\n else\n # Non date/time values can be JS escaped/formatted safely with # to_json\n entry.to_json\n end\n values << safe_val\n end\n rowstring = \"[#{values.join(\", \")}]\"\n formatted_rows << rowstring\n end\n \"[#{formatted_rows.join(', ')}]\"\n end", "def inspect(format=\"%12.4f\",indent=0)\n indt = \" \" * indent\n s = \"\"\n if @deps[0].kind_of? Table\n @inds.each_index do |i|\n s << indt << format % @inds[i]\n s << \"\\n\"\n s << @deps[i].inspect(format,indent+1)\n s << \"\\n\" if i!=(@inds.size-1)\n end\n else\n s << indt\n @inds.each_index do |i|\n s << format % @inds[i]\n end\n s << \"\\n\"\n s << indt\n @deps.each_index do |i|\n s << format % @deps[i]\n end\n end\n s\n end", "def ability_table(target = nil, columns: ABILITY_COLUMNS, **table_opt)\n row_count = 0\n\n heading_rows =\n html_tag(:thead, role: 'rowgroup') do\n html_tag(:tr, role: 'row') do\n row_count += 1\n columns.map do |css_class, label|\n html_tag(:th, label, role: 'columnheader', class: css_class)\n end\n end\n end\n\n data_rows =\n html_tag(:tbody, role: 'rowgroup') do\n divider = ability_table_divider\n ability_table_rows(target).flat_map do |_, rows|\n row_count += rows.size\n rows.values << divider\n end\n end\n\n table_opt[:role] ||= 'table'\n table_opt[:'aria-colcount'] = columns.size\n table_opt[:'aria-rowcount'] = row_count\n html_tag(:table, table_opt) do\n heading_rows << data_rows\n end\n end", "def format(args = {})\n to_s\n end", "def format\n output = @sum.to_s\n\n if @verbose\n @raw.each do |h|\n @display << \"#{h.keys[0]}:#{h.values[0]} \"\n end\n\n output << \" -- #{@display.strip}\"\n end\n\n output\n end", "def format\n rows = @children\n rows = @children[1..-1] if @skip_first_row\n rows ||= []\n rows = rows.collect { |row| row.format }.join(\"\\n\")\n\n return nil if rows.length == 0\n rows\n end", "def format\n @data_chunk_reader.format\n end", "def format\n @data_chunk_reader.format\n end", "def formatted_attributes\n Hash[display_key.downcase.to_sym, values.collect { |el| el[:displayValue] }]\n end", "def to_text_from_groups(resolved)\n columns = @group_keys + [\"count\"]\n\n keys = resolved.is_a?(Hash) ? resolved.keys : resolved.map(&:first)\n widths = columns.each_with_index.map do |column, idx|\n (keys.map { |group| group[idx].to_s.size } << columns[idx].to_s.size).max\n end\n\n text = []\n\n text << columns.each_with_index.map { |attr, idx|\n attr.to_s.center(widths[idx])\n }.join(\" \").rstrip\n\n text << widths.map { |width| \"-\" * width }.join(\" \")\n\n text += resolved.map { |group, allocations|\n line = group.each_with_index.map { |attr, idx|\n NUMERIC_COLUMNS.include?(columns[idx]) ?\n attr.to_s.rjust(widths[idx]) :\n attr.to_s.ljust(widths[idx])\n }.join(\" \")\n\n line << \" \" + allocations.size.to_s.rjust(5)\n }\n\n text.join(\"\\n\")\n end", "def format\n @_format\n end", "def print_usage_table(options={})\n fields = get_usage_fields options[:fields]\n fields, opts = get_fields_and_options(fields, options)\n render_table(fields, opts, options)\n end", "def monolith_table(groups, metadata)\n checkmark = \" <span style='color: limegreen'>&#x2714</span>\"\n\n # TODO: The checkmark crap below needs to be abstracted.\n formatters = {\n 'New' => proc { |f, l| ['', '', l] },\n 'Updated' => proc { |f, l| ['', '', l + (metadata[f]['installed'].any? ? checkmark : '' ) ] },\n 'Renamed' => proc { |f, l| [\"#{metadata[f]['oldname']}\" + (metadata[f]['installed'].any? ? checkmark : '' ), \"&rarr;\", l ] }\n }\n\n table = HTML::Table.new do |t|\n t.align = 'center'\n end\n\n groups.each do |group_name, members|\n title = Table::Row.new do |r|\n r.content = ['', '', group_name]\n end\n title.class_ = 'title'\n table.push title\n\n formatter = formatters[group_name]\n\n members.each do |formula|\n content = Table::Row.new do |r|\n link = \"<a href=#{metadata[formula]['homepage']}>#{formula}</a>\"\n r.content = formatter.call(formula, link).push(\n h(metadata[formula]['desc'])\n )\n r.first.class_ = 'name'\n end\n table.push content\n end\n end\n\n table\nend", "def columns(*args, &block)\n column_options, html_options = get_column_and_html_options( args.extract_options! )\n @collection.each do |object|\n @current_object = object\n if block_given?\n @lines << FormatLine.new(args, column_options, html_options)\n yield(object)\n else\n @lines << FormatLine.new(args, column_options, html_options, object)\n end\n end\n render_tbody\n end", "def summary_table_headers(args={})\n\t\t'''\n\t\t\t<thead>\n\t <tr>\n\t <th>Created At</th>\n\t <th>Payable To Organization Id</th>\n\t <th>Payable From Organization Id</th>\n\t <th>Payable From Patient Id</th>\n\t <th>Total</th>\n\t <th>Paid</th>\n\t <th>Pending</th>\n\t <th>Options</th>\n\t </tr>\n\t </thead>\n\t\t'''\n\tend", "def format\n return @format\n end", "def format\n return @format\n end", "def format\n return @format\n end", "def render\n return '' if values.blank? && !options[:include_empty]\n\n markup = %(<tr><th>#{label}</th>\\n<td><ul class='tabular'>\\n)\n\n attributes = microdata_object_attributes(field).merge(class: \"attribute attribute-#{field}\")\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"field=#{field}\",\n \"values=#{values}\",\n \"options=#{options}\",\n \"attributes=#{attributes}\",\n \"\" ] if creator_attribute_renderer_debug_verbose\n attributes.delete(:itemscope) # remove :itemscope\n attributes.delete(:itemtype) # remove :itemtype\n if values.count <= 5\n markup += Array(values).map do |value|\n %(<li#{html_attributes(attributes)}>#{attribute_value_to_html(value.to_s)}</span></li>)\n end.join(\"\\n\")\n else\n markup += %(<li#{html_attributes(attributes)}>#{creators_compact}</li>)\n end\n\n markup += %(\\n</ul></td></tr>)\n\n markup.html_safe\n end", "def format_for_export(row, formats)\n formatted_row = []\n row.zip(formats).each do |val, format|\n formatted = val\n if format == :boolean\n formatted = val ? 'Yes' : ''\n elsif format == :fiscal_year\n formatted = val.blank? ? '' : format_as_fiscal_year(val.to_i)\n end\n formatted_row << formatted\n end\n formatted_row\n end", "def format!\n tables.map { |t|\n SimpleReports::TableFormatter.new(t).format_table!\n }\n end", "def print(ids = nil)\n string = \"[ID]\\t\"\n string << \"[MGI SYMBOL]\\t\"\n string << \"[DATASET]\\t\"\n string << \"[VALUE]\\t\"\n string << \"[RANK]\\t\"\n string << \"[PERCENTILE]\\n\"\n\n if ids.nil?\n @data.each do |key, value|\n string << add_string(key, value)\n end\n else\n ids.each do |id|\n string << add_string(id, @data[id])\n end\n end\n return string\n end", "def to_text_from_plain(resolved, columns: DEFAULT_COLUMNS)\n getters = attribute_getters(columns)\n\n widths = getters.each_with_index.map do |attr, idx|\n (resolved.map { |a| attr.call(a).to_s.size } << columns[idx].to_s.size).max\n end\n\n text = []\n\n text << columns.each_with_index.map { |attr, idx|\n attr.to_s.center(widths[idx])\n }.join(\" \").rstrip\n\n text << widths.map { |width| \"-\" * width }.join(\" \")\n\n text += resolved.map { |allocation|\n getters.each_with_index.map { |getter, idx|\n value = getter.call(allocation).to_s\n NUMERIC_COLUMNS.include?(columns[idx]) ? value.rjust(widths[idx]) : value.ljust(widths[idx])\n }.join(\" \").rstrip\n }\n\n text.join(\"\\n\")\n end", "def format\n f = @item_attributes.first.format\n f.to_s unless f.nil?\n end", "def as_row(result, columns)\n columns.map { |column| column.format_value(result) }\n end", "def metadata_print\n build_metadata_output\n if options[:metadata_output]\n if options[:out_format] == :json\n json_print_to_file\n end\n if options[:out_format] == :csv\n csv_print_to_file\n end\n end\n return JSON.pretty_generate(metadata)\n end", "def render\n return '' if values.blank? && !options[:include_empty]\n\n markup = []\n markup << %(<tr><th>#{label}</th>\\n<td><ul class='tabular_list'>)\n attributes = microdata_object_attributes(field).merge(class: \"attribute attribute-#{field}\")\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"attributes=#{attributes}\",\n \"\" ] if fundedby_other_attribute_renderer_debug_verbose\n\n values.each_with_index do |value, index|\n markup << %(<li#{html_attributes(attributes)}>)\n attribute_value_index_to_html(markup, value.to_s, index, values.size)\n end\n markup << %(\\n</ul></td></tr>)\n markup.join(\"\\n\").html_safe\n end", "def family_data_formatted(member, options={:show_private=>false, :include_contacts=>true})\n formatted = {}\n wife = member.wife\n emails = []\n member_name = member.last_name_first(:short=>true, :middle=>false)\n wife_name = wife ? \" & #{wife.short}\" : ''\n formatted[:couple]= member_name + wife_name\n if member.in_country \n away_string = ''\n else\n away_string = \"*\"\n away_string << \" (#{t(:return)} ~ #{member.arrival_date})\" if \n (member.arrival_date && member.arrival_date >= Date.today)\n end\n formatted[:couple_w_status] = member_name + wife_name + away_string\n return formatted unless options[:include_contacts]\n emails[0] = member.email_1 || '---'\n if wife # if there IS a wife\n emails[1] = wife.email_1 if wife.email_1 &&\n wife.email_1 != member.email_1\n end\n # Add a second phone & email if they exist and only one has been used already\n emails[1] = member.email_2 if member.email_2 && emails.length < 2\n formatted[:phones] = phone_string_couple(member)\n formatted[:emails] = emails\n return formatted\n end", "def format data\n data\n end", "def format_data\n formatted_data = nil\n unless @raw_data.class == Hash # Webmock hack\n case options.format.to_sym\n when :json\n formatted_data = JSON.parse(@raw_data, symbolize_names: true)\n when :xml\n formatted_data = MultiXml.parse(@raw_data)['userinfo']\n end\n end\n\n formatted_data\n end", "def column_attrs\n attrs = {}\n\n attrs[\"Last Name\"] = :last_name\n attrs[\"First Name\"] = :first_name\n attrs[\"Email\"] = :email\n attrs[\"Institution\"] = \"try(:professional_org_lookup, 'institution')\"\n attrs[\"College\"] = \"try(:professional_org_lookup, 'college')\"\n attrs[\"Department\"] = \"try(:professional_org_lookup, 'department')\"\n attrs[\"Account Created Date\"] = \"self.created_at.try(:strftime, \\\"%D\\\")\"\n attrs[\"ID\"] = :id\n attrs[\"LDAP_UID\"] = :ldap_uid\n attrs[\"Approved/Activated?\"] = \"self.approved? ? \\\"Y\\\" : \\\"N\\\"\"\n attrs[\"Overlord?\"] = \"self.catalog_overlord? ? \\\"Y\\\" : \\\"N\\\"\"\n\n attrs\n end", "def grouped_column_names_for(object)\n object.column_names.map { |column| \"#{object.table_name}.#{column}\" }.join(', ')\n end", "def format_attributes(attributes)\n if attributes.size > 0\n \" \" + attributes.map{ |k, v, attr| format_attribute(k, v, attr)}.join(\" \")\n else\n \"\"\n end\n end", "def print(*columns)\n rows = [columns.join(COL_SEP)]\n rows += @rows.map do |row|\n values = columns.map do |col|\n value = row[col.to_sym] \n\n if value.respond_to?(:strftime)\n value.strftime(\"%m/%d/%Y\")\n else\n value\n end\n end\n\n values.join(COL_SEP)\n end\n \n rows.join(ROW_SEP)\n end", "def format descriptions\n formatted = format_rows descriptions\n\n aligned = formatted.transpose.map do |column|\n width = column.map { |entry| entry.length }.max\n\n column.map { |entry| entry.rjust width }\n end\n\n aligned.transpose.map do |row|\n row.join ' '\n end\n end", "def ps_format\n return nil unless options.format\n\n \"table {{.ID}}\\t{{.Mounts}}\" if options.format.eql?('mounts')\n end", "def group_by_columns\n @group = \" GROUP BY #{column_list_for(@columns)}\" if @columns.any?\n end", "def format_descriptions\n formats = MetricFu::Formatter::BUILTIN_FORMATS\n max = formats.keys.map(&:length).max\n formats.keys.sort.map do |key|\n \" #{key}#{' ' * (max - key.length)} : #{formats[key][1]}\"\n end\n end", "def table(*columns, &block)\n\n rows = Array.new\n yield(rows)\n\n # determine maximum cell widths\n max_cell_widths = rows.inject(Array.new(columns.length, 0)) do |result, row|\n lengths = row.map { |column| column.to_s.length }\n result.each_with_index { |length, index| result[index] = ([length, lengths[index]].max rescue length) }\n end\n columns.each_with_index { |col, index| col[:actual_width] ||= max_cell_widths[index] }\n\n # determine actual column width\n column_widths = columns.map do |column|\n if column[:width] == :rest\n nil\n elsif column[:width]\n column[:width]\n elsif column[:min_width]\n [column[:min_width], column[:actual_width]].max\n elsif column[:max_width]\n [column[:max_width], column[:actual_width]].min\n else\n column[:actual_width]\n end\n end\n\n if column_widths.include?(nil)\n fill_column = columns[column_widths.index(nil)]\n width_left = options[:width] - ((columns.length - 1) * (style[:cell_separator] ? 3 : 1)) - column_widths.compact.inject(0) { |sum, col| sum + col}\n column_widths[column_widths.index(nil)] = width_left\n end\n\n line(:green) if @style[:top_line]\n\n # Print table header\n if table_has_header?(columns)\n column_titles = []\n columns.each_with_index do |column, index|\n width = column_widths[index]\n alignment = (column[:align] == :right ? '' : '-')\n column_titles.push(colorize(\"%#{alignment}#{width}s\" % column[:title].to_s[0...width], :bold))\n end\n\n puts column_titles.join(style[:cell_separator] ? \" #{characters[:vertical_line]} \" : ' ')\n line(:green)\n end\n\n # Print the rows\n rows.each do |row|\n row_values = []\n columns.each_with_index do |column, index|\n width = column_widths[index]\n case column[:type]\n when :ratio\n if width > 4\n if column[:treshold] && column[:treshold] < row[index].to_f\n bar = ''\n bar << characters[:block] * (width.to_f * column[:treshold]).round\n bar << colorize(characters[:block] * (width.to_f * (row[index].to_f - column[:treshold])).round, :red)\n row_values.push(bar)\n else\n # Create a bar by combining block characters\n row_values.push(characters[:block] * (width.to_f * row[index].to_f).round)\n end\n else\n # Too few characters for a ratio bar. Display nothing\n row_values.push('')\n end\n else\n alignment = (columns[index][:align] == :right ? '' : '-')\n cell_value = \"%#{alignment}#{width}s\" % row[index].to_s[0...width]\n cell_value = colorize(cell_value, :bold, :brown) if columns[index][:highlight]\n row_values.push(cell_value)\n end\n end\n puts row_values.join(style[:cell_separator] ? \" #{characters[:vertical_line]} \" : ' ')\n end\n end", "def formatter\n raw_data['formatter']\n end", "def get_formatting_data\n format = @data[country][:format]\n prefix = @data[country][Core::NATIONAL_PREFIX]\n rule = (format[Core::NATIONAL_PREFIX_RULE] ||\n @data[country][Core::NATIONAL_PREFIX_RULE] || '$1')\n\n [format, prefix, rule]\n end", "def format\n raise NotImplementedError\n end", "def formattable? format\n Hash.instance_methods.collect(&:to_sym).include? to_format(format)\n end", "def render_for_webquery( statement, group_by_columns )\n\n report_state_hash = YAML.load(self.view_state)\n conn = User.connection\n recordset = conn.select_all(Globals.cleanup_where(statement))\n\n if group_by_columns.nil? || group_by_columns.empty?\n if report_state_hash[:columns_list].nil? || report_state_hash[:columns_list].empty?\n if recordset.empty?\n keys = ['No records found']\n else\n keys = recordset[0].keys\n end\n else\n # Use the provided list of columns.\n keys = report_state_hash[:columns_list].map {|k| k.gsub('\"', '').strip }\n end\n else\n keys = group_by_columns\n # Include the sum or count columns.\n unless recordset.empty?\n extra_cols = recordset[0].keys - keys\n keys += extra_cols\n end\n end\n\n s = \"<table><tr><th>#{keys.join('</th><th>')}</th></tr>\"\n recordset.each do |record|\n s << '<tr>'\n keys.each do |k|\n s << \"<td>#{format_for_spreadsheet(record[k])}</td>\"\n end\n s << '</tr>'\n end\n s << '</table>'\n end", "def format_metadata\n [ {:key => :department, :value => @options[:department]},\n {:key => :project, :value => @options[:project]},\n {:key => :jenkins_build_url, :value => @options[:jenkins_build_url]},\n {:key => :sshKeys, :value => \"google_compute:#{File.read(find_google_ssh_public_key).strip}\" }\n ].delete_if { |member| member[:value].nil? or member[:value].empty?}\n end", "def to_formatted_s(format = :default)\n case format\n when :db\n if empty?\n 'null'\n else\n collect { |element| element.id }.join(',')\n end\n else\n to_default_s\n end\n end", "def table_csv_string(options = {})\n opt = {\n :klass => nil,\n :header_row => true\n }.merge!(options)\n str = ''\n \n return false if !opt[:klass]\n\n klass_name = opt[:klass].name\n tbl = ActiveSupport::Inflector.tableize(opt[:klass].name.to_s)\n\n cols = []\n sql = ''\n\n if klass_name == \"Person\" \n cols = %w(id last_name first_name middle_name login)\n else\n cols = opt[:klass].columns.map(&:name) \n end\n\n cols_str = cols.join(\", \")\n\n case opt[:klass].name\n when \"Person\"\n sql = \"SELECT #{cols_str} FROM people p INNER JOIN people_projs pp on p.id = pp.person_id WHERE pp.proj_id = #{self.id};\"\n when \"Ref\"\n cols_str = cols.collect{|c| \"r.#{c}\"}.join(\", \") # refs shared across projects, be more explicit for the join table\n sql = \"SELECT #{cols_str} FROM refs r INNER JOIN projs_refs pr on r.id = pr.ref_id WHERE pr.proj_id = #{self.id};\"\n when \"TaxonName\"\n sql = \"SELECT #{cols_str} FROM taxon_names WHERE #{self.sql_for_taxon_names}\"\n when \"Author\"\n sql = \"SELECT #{cols_str} FROM authors a WHERE a.ref_id IN (SELECT r.id FROM refs r INNER JOIN projs_refs pr on r.id = pr.ref_id WHERE pr.proj_id = #{self.id})\"\n when \"ChrState\"\n sql = \"SELECT #{cols_str} FROM chr_states cs WHERE cs.chr_id IN (SELECT chrs.id from chrs WHERE chrs.proj_id = #{self.id})\" \n # when \"Identifier\"\n # sql = \"SELECT #{cols_str} FROM identifiers si WHERE si.specimen_id IN (SELECT specimens.id from specimens WHERE specimens.proj_id = #{self.id})\"\n when \"SpecimenDetermination\"\n sql = \"SELECT #{cols_str} FROM specimen_determinations sd WHERE sd.specimen_id IN (SELECT specimens.id from specimens WHERE specimens.proj_id = #{self.id})\"\n\n else\n sql = \"SELECT #{cols_str} FROM #{tbl}\" \n end\n\n # add the project level restrictions if they exist\n sql << \" WHERE proj_id = #{self.id}\" if opt[:klass].columns.collect{|c| c.name}.include?(\"proj_id\")\n\n # build the str\n str << cols.join(\"\\t\") if opt[:header_row]# the header row\n str << \"\\n\"\n\n ActiveRecord::Base.connection.select_rows(sql).each do |row| \n # not filtering for tab characters here, likely should\n str << row.collect{|c| c == nil ? nil : c.gsub(/\\n|\\r\\n|\\r/, '\\n')}.join(\"\\t\") + \"\\n\"\n end\n str\n end", "def to_csv(options={})\n include_column_titles = options.delete(:include_column_titles){true} #default: true\n n = naked\n cols = n.columns\n csv_string = CSV.generate(options) do |csv|\n csv << cols if include_column_titles\n n.each{|r| csv << cols.collect{|c| r[c] } }\n end\n csv_string\n end", "def inspect\n attributes_as_nice_string = self.class.column_names.collect { |name|\n if has_attribute?(name) || new_record?\n \"#{name}: #{attribute_for_inspect(name)}\"\n end\n }.compact.join(\", \")\n \"#<#{self.class} #{attributes_as_nice_string}>\"\n end", "def to_s\n [\n @member_id,\n [:spm, :mpm, :ser, :pd, :extra, :subtotal, :total].map{ |x| self.costs[x] }\n ].flatten.join(\"\\t\");\n end", "def generate_table(name, data_set1, data_set2 , data_set3, data_set4 , assignment_names,data_set1_name , data_set2_name, data_set3_name, data_set4_name )\n table = \"#{name}\"\n\n table << \"<br/><table border='1' align='left'>\"\n\n table << \"<tr><td></td>\"\n assignment_names.each_with_index do |assignment,index|\n table << \"<td>(#{index+1})#{assignment}</td>\"\n end\n\n color = '#'+COLOR_1+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set1_name}</td>\"\n data_set1.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n color = '#'+COLOR_2+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set2_name}</td>\"\n data_set2.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n if(data_set3)\n color = '#'+COLOR_3+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set3_name}</td>\"\n data_set3.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n if(data_set4)\n color = '#'+COLOR_4+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set4_name}</td>\"\n data_set4.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n table << \"</tr></table>\"\n @table = table\n end", "def to_s()\n\n # Immediately return records that have no data\n if @data.type == GDT_NO_DATA then\n return self.name\n end\n\n # Raise an exception if an invalid record is encountered\n unless RECORD_INFO[@type].valid\n raise \"Record type #{self.name} is not valid\"\n end\n \n # Format other data types...\n case @type\n when GRT_STRING\n self.name + \" \\\"#{@data.to_s}\\\"\"\n when GRT_BGNLIB, GRT_BGNSTR\n # Format dates for library & structure\n out_arr = []\n tmpar = (@type == GRT_BGNLIB) ? [\"LASTMOD\",\"LASTACC\"] : [\"LASTMOD\",\"CREATION\"]\n tmpar.each_with_index do |label, i|\n j = i * 6\n out_arr.push sprintf(\"%s %02d/%02d/%02d %02d:%02d:%02d\",label,\n @data[j],@data[j+1],@data[j+2],\n @data[j+3],@data[j+4],@data[j+5])\n end\n self.name + \"\\n\" + out_arr.join(\"\\n\")\n when GRT_UNITS\n# @@file_user_units[file] = @data[0].to_f\n \"UNITS\\nUSERUNITS #{@data[0].to_s}\\nPHYSUNITS #{data[1].to_s}\"\n when GRT_WIDTH\n units = 1\n# units = @@file_user_units[file] || 1\n self.name + \" #{@data[0]}\"\n when GRT_XY\n units = 1\n# units = @@file_user_units[file] || 1\n out_arr = [\"XY \" + (@data.value.length/2).to_s]\n 0.step(@data.value.length-2, 2) do |i|\n out_arr.push \" X #{@data[i]*units}; Y #{@data[i+1]*units}\"\n end\n out_arr.join(\";\\n\") + ';'\n when GRT_PRESENTATION, GRT_STRANS\n if @type == GRT_PRESENTATION then\n str = [@data.to_s[10,2], @data.to_s[12,2], @data.to_s[14,2]].map {|twobits|\n [(\"0\"*32+twobits)[-32..-1]].pack(\"B32\").unpack(\"N\")[0].to_s\n }.join(',')\n elsif @type == GRT_STRANS then\n str =[@data.to_s[0,1], @data.to_s[13,1], @data.to_s[14,1]].map {|onebit|\n [(\"0\"*32+onebit)[-32..-1]].pack(\"B32\").unpack(\"N\")[0].to_s\n }.join(',')\n end\n self.name + ' ' + str\n else\n self.name + ' ' + @data.to_s\n end\n \n end", "def to_tsv\n \"#{@data[:format]}\\t#{@data[:type]}\\t#{@data[:subtype]}\\t#{@data[:actor]}\\t#{@data[:target]}\\t#{@data[:damage]}\\t#{@data[:ability_name]}\\t#{@data[:light]}\"\n end" ]
[ "0.53699476", "0.5357202", "0.5232327", "0.51930964", "0.5192452", "0.51601917", "0.51322305", "0.5056988", "0.5056476", "0.50357574", "0.4994563", "0.49546322", "0.49168053", "0.49091384", "0.49007094", "0.4882268", "0.4877234", "0.4877234", "0.4839324", "0.47806492", "0.47742808", "0.4767829", "0.4766178", "0.47622198", "0.47528946", "0.47418296", "0.4727385", "0.47086087", "0.47086087", "0.47048384", "0.4695313", "0.46903396", "0.46864384", "0.46840385", "0.4683651", "0.46796498", "0.46793032", "0.46721113", "0.46696636", "0.46548942", "0.4646596", "0.46361092", "0.462842", "0.46253785", "0.4616121", "0.46133348", "0.46126845", "0.46095198", "0.45865512", "0.4585389", "0.4576391", "0.45741242", "0.45596313", "0.4555751", "0.4555751", "0.45541513", "0.45536816", "0.45448837", "0.45410886", "0.4535487", "0.45306122", "0.45237884", "0.45202896", "0.45202896", "0.45202896", "0.45196632", "0.45105144", "0.45104322", "0.45093206", "0.45081788", "0.45001993", "0.44941187", "0.44868016", "0.4484942", "0.44845715", "0.44786853", "0.44751063", "0.4475013", "0.44590124", "0.44576696", "0.44536492", "0.44525585", "0.4441033", "0.44410297", "0.44375923", "0.4435783", "0.44327912", "0.44248897", "0.44141462", "0.441262", "0.4412365", "0.4410582", "0.44071996", "0.44025105", "0.4401797", "0.43988216", "0.43985972", "0.43958148", "0.43953946", "0.43793547" ]
0.6304722
0
Gets the specified attribute group's data from the agent/service_point specified and returns a new AttributeGroupData object which contains that data. +agent_address+:: The address of the machine on which the agent resides. +service_point+:: The service point of the agent from which to collect the data. +username+:: The username to use when connecting to the specified service point. +password+:: The password to use when connecting to the specified service point. +attribute_group+:: The TEMS name of the attribute group whose data should be collected. +subnodes+:: An array of subnode managed system names for which to collect data. +port+:: The port via which to communicate with the agent. Defaults to 1920.
def get_attribute_group_data(agent_address, service_point, username, password, attribute_group, subnodes, port=1920) require 'net/http' uri = URI("http://#{agent_address}:#{port}///#{service_point}/#{service_point}") body = "<REPORT><SQLTABLE NULLATTROUTPUT=\"Y\"><TABLENAME>#{attribute_group}</TABLENAME><SUBNODES>#{subnodes.join(",")}</SUBNODES></SQLTABLE></REPORT>" # warn "Sending HTTP POST to #{uri} with body #{body}" request = Net::HTTP::Post.new(uri.path) request.basic_auth(username, password) request.body = body response = Net::HTTP.start(uri.host, uri.port) { |http| http.request(request) } if not response.is_a?(Net::HTTPOK) $stderr.puts "Response #{response.code}: #{response.body}" return nil end # warn "Received #{response.body}" return AttributeGroupData.new_with_xml(response.body) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_args(args)\n require 'ostruct'\n require 'optparse'\n\n parser = OptionParser.new\n options = OpenStruct.new\n\n options.output = STDOUT\n options.format = :text\n options.columns = nil\n options.subnodes = [ ]\n\n parser.banner = \"Usage: #{$0} [options] agent_address service_point username password attribute_group\"\n parser.on(\"-h\", \"--help\", \"Show this message.\") { $stderr.puts parser; exit }\n parser.on(\"-f\", \"--format [ 'text' | 'html' ]\", [:text, :html],\n \"Set the output format to either plain text or HTML.\", \"[default: text]\") do |f|\n options.format = f\n end\n parser.on(\"-c\", \"--columns c1,...,cN\", Array, \"Output columns c1,...,cN.\", \"[default: all columns]\") { |c| options.columns = c }\n parser.on(\"-s\", \"--subnodes s1,...,sN\", Array, \"Collects data for subnodes s1,...,sN.\", \"[default: no subnodes]\") { |s| options.subnodes = s }\n\n rest = parser.parse(args)\n\n # Ensure we have all the required args\n if rest.length != 5\n $stderr.puts parser\n exit\n end\n\n return *rest, options\nend", "def attributes_from_group\n group_attributes = {}\n self.ldap_attribute_map.each do |ldap_attr, attr|\n group_attributes[ldap_attr] = attr.is_a?(Proc) ? attr.call(self.group) : self.group[attr]\n end\n group_attributes\n end", "def parse_attribute attribute_for_group\n return UNPARSED unless scan(ATTRIBUTE)\n\n value = ''\n\n until eos?\n case\n when check(SEPARATOR)\n break\n when scan(ESCAPE)\n value += getch\n else\n value += getch\n end\n end\n\n if value =~ /^[\\^\\!\\+\\-]?(.*)^?$/\n key = $1\n if value[0] == '+' or value[0] == '^'\n attribute_for_group[key] = true\n elsif value[0] == '-' or value[0] == '!'\n attribute_for_group[key] = false\n else\n next_value = parse_value\n if next_value == UNPARSED\n raise ParseError, \"Attribute for \\\"#{key}\\\" is not found\"\n end\n\n attribute_for_group[key] = next_value\n end\n IGNORABLE\n else\n raise \"Should never reach here\"\n end\n end", "def group_get_info(attribs, dir_info)\n attribs = group_record_name_alternatives(attribs)\n\n check_critical_attribute( attribs, :record_name )\n\n command = {action: 'read', scope: 'Groups', value: nil}\n user_attrs = attribs.merge(command)\n\n dscl( user_attrs, dir_info )\n end", "def calculate_group_points\n attributes_groups.each do |group|\n if group.group_points_formula.present?\n character_group = self.find_attributes_group(group.name)\n character_group.points = self.calculator.evaluate(group.group_points_formula)\n end\n end\n end", "def whats_my_node_group(data={}, service_delimeter=\":\")\n env = data[:env]\n runway = data[:runway]\n if data[:product] == \"shared\" or data[:product] == \"\"\n product = nil\n else\n product = data[:product]\n end\n service = data[:service]\n env_prod = [env, runway, product].compact.join(\"-\")\n env_prod = nil if env_prod.empty?\n node_group = [env_prod, service].compact.join(service_delimeter)\n return node_group\n end", "def get_ldap_group_members(groupname:)\n begin\n group = []\n get_ldap_group_member(groupname: groupname) do |_g, m|\n if block_given?\n yield get_ldap_user_attributies(upi: m, attributes: { 'sn' => 'surname', 'givenname' => 'given_name', 'mail' => 'email', 'cn' => 'external_id' })\n else\n group << get_ldap_user_attributies(upi: m, attributes: { 'sn' => 'surname', 'givenname' => 'given_name', 'mail' => 'email', 'cn' => 'external_id' })\n end\n end\n return group unless block_given?\n rescue StandardError => e\n warn e\n end\n end", "def get_attribute_group(id)\n @client.raw('get', \"/config/attribute-groups/#{id}\")\n end", "def chef_node_attribute_data\n node_data = node.to_h\n node_data['chef_environment'] = node.chef_environment\n\n node_data\n end", "def add_clamps_group_agent(classifier, pe_infra)\n clamps_agents_group = {\n \"name\" => \"Clamps - Agent Nodes\",\n \"rule\" => [\"and\", [\"=\", %w[fact id], \"root\"], [\"=\", \"name\", metric.node_name]],\n \"parent\" => pe_infra[\"id\"],\n \"classes\" => {\n \"clamps::agent\" => {\n \"amqpass\" => \"\",\n \"master\" => any_hosts_as?(:loadbalancer) ? \"puppet\" : master.node_name,\n \"nonroot_users\" => options[:scale][:num_nonroot_users] || 2,\n \"daemonize\" => options[:scale][:daemonize] || false,\n \"mco_daemon\" => options[:scale][:mco_daemon],\n \"num_facts_per_agent\" => options[:scale][:facts_per_agent] || 500,\n \"percent_changed_facts\" => options[:scale][:percent_facts_to_change] || 15,\n \"splay\" => options[:scale][:splay] || false,\n \"splaylimit\" => options[:scale][:splaylimit] || false\n }.reject { |_k, v| v.nil? }\n }\n }\n classifier.find_or_create_node_group_model(clamps_agents_group)\nend", "def user_data_obj(registry_endpoint, instance_id, dns, agent_id, network_spec, environment, vm_params, config, computer_name = nil)\n user_data = { registry: { endpoint: registry_endpoint } }\n if computer_name\n user_data[:'instance-id'] = instance_id\n user_data[:server] = { name: computer_name }\n else\n user_data[:server] = { name: instance_id }\n end\n user_data[:dns] = { nameserver: dns } if dns\n\n unless @uses_registry\n user_data.merge!(initial_agent_settings(agent_id, network_spec, environment, vm_params, config))\n user_data.delete(:registry)\n end\n\n user_data\n end", "def initialize(pds_url, calling_system, pds_handle, attribute)\n raise ArgumentError.new(\"Argument Error in #{self.class}. :pds_url not specified in config.\") if pds_url.nil?;\n raise ArgumentError.new(\"Argument Error in #{self.class}. :calling_system not specified in config.\") if calling_system.nil?;\n raise ArgumentError.new(\"Argument Error in #{self.class}. :pds_handle is null.\") if pds_handle.nil?;\n raise ArgumentError.new(\"Argument Error in #{self.class}. :attribute is null.\") if pds_handle.nil?;\n pds_uri = URI.parse(\"#{pds_url}/pds?func=get-attribute&attribute=#{attribute}&calling_system=#{calling_system}&pds_handle=#{pds_handle}\")\n http = Net::HTTP.new(pds_uri.host, pds_uri.port)\n # Set read timeout to 15 seconds.\n http.read_timeout = 15\n http.use_ssl = true if pds_uri.is_a?(URI::HTTPS)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?\n response = http.post(pds_uri.path, pds_uri.query)\n begin\n response.value\n rescue Exception => e\n raise \"Error in #{self.class}. Invalid HTTP response status.\\n#{e.message}\"\n end\n # PDS returns as HTML content type, unfortunately.\n @response = Nokogiri.XML(response.body)\n @error = @response.at(\"//error\").inner_text unless @response.at(\"//error\").nil?\n # Don't raise an error, because user not found is reported as an error.\n end", "def group\n @gp40s = Gp40.find_measure_group(params[:gp40_id], params[:machine_id])\n\n sort_ad()\n set_graph()\n end", "def new_group(group_data)\n [:id, :name].each { |attr| raise(ArgumentError, \"Missing or Invalid Parameter(s)\") unless group_data.key?(attr) }\n set_values group_data\n end", "def group\n attribute_prop(7)\n end", "def get_agent_contacts(params)\n message = {\n serviceGroupID: params[:service_group_id],\n serviceID: params[:service_id],\n teamID: params[:team_name],\n agentID: params[:agent_id],\n startDate: params[:start_date],\n endDate: params[:end_date],\n contactTypes: params[:contact_type],\n useServiceTime: false\n }\n\n reply = @client.call(:get_contacts, message: message)\n data = reply.body.dig(:get_contacts_response,\n :get_contacts_result,\n :array_of_string)\n\n data = check_if_data_exists(data)\n data = map_contacts_data(data)\n delete_contact_headers(data)\n data\n end", "def create_ad_group(client, customer_id, campaign_resource_name)\n ad_group = client.resource.ad_group do |ag|\n ag.type = :SEARCH_DYNAMIC_ADS\n ag.name = \"Earth to Mars Cruises #{(Time.now.to_f * 1000).to_i}\"\n\n ag.campaign = campaign_resource_name\n\n ag.status = :PAUSED\n ag.tracking_url_template = \"http://tracker.example.com/traveltracker/{escapedlpurl}\"\n\n ag.cpc_bid_micros = 3_000_000\n end\n\n operation = client.operation.create_resource.ad_group(ad_group)\n\n response = client.service.ad_group.mutate_ad_groups(\n customer_id: customer_id,\n operations: [operation],\n )\n\n puts(\"Created ad group with ID: #{response.results.first.resource_name}\")\n response.results.first.resource_name\nend", "def group_service\n\t\tid = params[:id]\n\t\tTheCityAdmin::AdminApi.connect(Rcplugin::CITY_ADMIN_SECRET,Rcplugin::CITY_USER_TOKEN)\n\t\t@members = TheCityAdmin::GroupRoleList.new({:group_id => id})\n\n\t\t@total_count = @members.total_pages\n\t\t@membersList = Array.new\n\t\t@membersListv1 = Array.new\n\t\tfor i in 2..@total_count\n\t\t\t@members_v1 = TheCityAdmin::GroupRoleList.new({:group_id => id,:page => i})\n\t\t\t@mem_json = @members_v1.to_json\n\t\t\t@membersList[i] = @mem_json\n\t\tend\t\n\n\n\tend", "def get_groups_for_ip_address_with_http_info(ip_address, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address ...'\n end\n # verify the required parameter 'ip_address' is set\n if @api_client.config.client_side_validation && ip_address.nil?\n fail ArgumentError, \"Missing the required parameter 'ip_address' when calling PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address\"\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/global-infra/ip-address-group-associations'\n\n # query parameters\n query_params = {}\n query_params[:'ip_address'] = ip_address\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'enforcement_point_path'] = opts[:'enforcement_point_path'] if !opts[:'enforcement_point_path'].nil?\n query_params[:'include_mark_for_delete_objects'] = opts[:'include_mark_for_delete_objects'] if !opts[:'include_mark_for_delete_objects'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'PolicyResourceReferenceForEPListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicyInventoryGroupsGroupMembersApi#get_groups_for_ip_address\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def assign_dataset_attributes\n if dataset\n reset_dataset_attributes\n @dataset_attributes = (dataset.data[dataset_group][dataset_key] ||= {})\n end\n rescue => e\n raise \"Qernel::Dataset: missing dataset item for #{dataset_group.inspect} #{dataset_key}. #{e.inspect}\"\n end", "def group_data\n data_hash = {color: @color, bling: @bling, age: @age, functional: @functional}\n end", "def get_hiera_data_from_key(key, options)\n certname = options[:certname_for_facts]\n global_config = get_global_config\n Puppet.info(\"Finding our node's facts and merging them with global data\n\")\n global_config = find_facts(certname).merge(global_config)\n hiera_data = compile_all_data(global_config, [], options, key)\n Puppet.info(\"Found value: '#{hiera_data}'\")\n hiera_data\n end", "def getToolsSyndicateInfogroup( entity_id, destructive)\n params = Hash.new\n params['entity_id'] = entity_id\n params['destructive'] = destructive\n return doCurl(\"get\",\"/tools/syndicate/infogroup\",params)\n end", "def fetch(group, id_or_name, attribute_name)\n return [] if attribute_name.empty?\n attribute_name = normalize_attribute_name(attribute_name)\n value = entry(group, id_or_name)[attribute_name]\n value ? value.dup : []\n end", "def get_nodes_from_group(node_group, options = {})\n options[:exactget] ||= {}\n options[:exactget]['node_group[name]'] = node_group\n options[:includes] ||= []\n options[:includes] << ['status'] # we're always interested in status\n return get_nodes(options)\n end", "def get_graph_data(gid,t_start=nil,t_end=nil)\n t_end ||= Time.new.to_i\n t_start ||= (t_end - 600)\n g = get_graph(gid)\n params = {'end'=>t_end.to_i,'start'=>t_start.to_i}\n g['datapoints'].each do |dp|\n res = get_data(dp['check_id'],dp['metric_name'],params)\n data = res['data']\n dp['data'] = _data_derive(data,dp)\n end\n g['composites'].each do |cmp|\n cmp['data'] = _composite_formula(cmp['data_formula'],g)\n end\n return g\n end", "def assign_data_point_attributes\n \t@field_id = params[:field_id]\n \t@outcome_id = params[:outcome_id]\n \toutcome = Outcome.find(@outcome_id)\n \t@selected_timepoints = params[:selected_timepoints]\n \tdatapoint_id = params[:datapoint_id]\n \tdatapoint_type = params[:datapoint_type] # either outcome or comparison\n \tis_calculated = params[:is_calculated]\n \tfootnote = params[:footnote]\n \tunless params[:subgroup_id].nil?\n\t\t\t@subgroup = OutcomeSubgroup.find(params[:subgroup_id])\n\t\telse\n\t\t\t@subgroup = nil\n\t\tend\n \t@datapoint,@footnote_removed = OutcomeDataEntry.assign_data_point_attributes(datapoint_id, datapoint_type, is_calculated, footnote, @outcome_id, @subgroup.id)\n \t\n \t@footnotes = outcome.get_foot_notes(@subgroup.id)\n \t\n end", "def _from_xml(xml)\n return XmlSimple.xml_in(xml, {\n 'ForceArray'=>['accessGroup'],\n 'GroupTags'=>{\n 'services'=>'service',\n 'metros'=>'metro',\n 'networkIdentifiers'=>'ni'\n },\n 'KeyAttr'=>['id','name']\n })\n end", "def get_node_group request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_get_node_group_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Cloud::Dataproc::V1::NodeGroup.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end", "def feature_group=(value)\n @feature_group = value\n end", "def feature_group\n return @feature_group\n end", "def get_hosts netgroup\n hosts = []\n # Bind RO to ldap for recursive searching netgroup. FIXME: hardcoded\n auth = { :method => :simple, :username => 'uid=network,ou=Netgroup,dc=catnip', :password => 'sedLdapPassword' }\n Net::LDAP.open(:host => 'ldap.cat.pdx.edu', :port => 636, :auth => auth, :encryption => :simple_tls) do |ldap|\n filter = Net::LDAP::Filter.eq( \"cn\", netgroup )\n attrs = [\"nisNetgroupTriple\",\"memberNisNetgroup\"]\n ldap.search(:base => 'ou=Netgroup,dc=catnip', :filter => filter, :attributes => attrs) do |entry|\n [*entry[\"nisNetgroupTriple\"]].each do |triple|\n host = (/([-\\w]+\\.)+\\w+/.match(triple)).to_s\n hosts << host unless host == \"\"\n end\n [*entry[\"memberNisNetgroup\"]].each do |memberNetgroup|\n hosts += get_hosts(memberNetgroup) #get subgroups\n end\n end\n end\n return hosts\nend", "def set_group\n data[:group]\n end", "def get_groups_for_ip_address_0_with_http_info(ip_address, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address_0 ...'\n end\n # verify the required parameter 'ip_address' is set\n if @api_client.config.client_side_validation && ip_address.nil?\n fail ArgumentError, \"Missing the required parameter 'ip_address' when calling PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address_0\"\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address_0, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_groups_for_ip_address_0, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/infra/ip-address-group-associations'\n\n # query parameters\n query_params = {}\n query_params[:'ip_address'] = ip_address\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'enforcement_point_path'] = opts[:'enforcement_point_path'] if !opts[:'enforcement_point_path'].nil?\n query_params[:'include_mark_for_delete_objects'] = opts[:'include_mark_for_delete_objects'] if !opts[:'include_mark_for_delete_objects'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'PolicyResourceReferenceForEPListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicyInventoryGroupsGroupMembersApi#get_groups_for_ip_address_0\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create_ns_service_group_with_http_info(ns_service_group, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: GroupingObjectsApi.create_ns_service_group ...\"\n end\n # verify the required parameter 'ns_service_group' is set\n if @api_client.config.client_side_validation && ns_service_group.nil?\n fail ArgumentError, \"Missing the required parameter 'ns_service_group' when calling GroupingObjectsApi.create_ns_service_group\"\n end\n # resource path\n local_var_path = \"/ns-service-groups\"\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(ns_service_group)\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'NSServiceGroup')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: GroupingObjectsApi#create_ns_service_group\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_group_vm_statistics_with_http_info(domain_id, group_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics ...'\n end\n # verify the required parameter 'domain_id' is set\n if @api_client.config.client_side_validation && domain_id.nil?\n fail ArgumentError, \"Missing the required parameter 'domain_id' when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics\"\n end\n # verify the required parameter 'group_id' is set\n if @api_client.config.client_side_validation && group_id.nil?\n fail ArgumentError, \"Missing the required parameter 'group_id' when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics\"\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/infra/domains/{domain-id}/groups/{group-id}/statistics/virtual-machines'.sub('{' + 'domain-id' + '}', domain_id.to_s).sub('{' + 'group-id' + '}', group_id.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'enforcement_point_path'] = opts[:'enforcement_point_path'] if !opts[:'enforcement_point_path'].nil?\n query_params[:'include_mark_for_delete_objects'] = opts[:'include_mark_for_delete_objects'] if !opts[:'include_mark_for_delete_objects'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'RealizedVirtualMachineListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicyInventoryGroupsGroupMembersApi#get_group_vm_statistics\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_members(group_ldap_dn)\n ldap = Net::LDAP.new :host => SiteSetting.ldap_hostname,\n :port => SiteSetting.ldap_port,\n :auth => {\n :method => :simple,\n :username => SiteSetting.ldap_bind_dn,\n :password => SiteSetting.ldap_password\n }\n\n filter = Net::LDAP::Filter.construct('(memberOf='+ group_ldap_dn +')')\n \n treebase = SiteSetting.ldap_base\n\n result_attrs =[\"mail\"]\n \n group_members = []\n ldap.search(:base => treebase, :filter =>\n filter, :attributes => result_attrs,:return_result =>\n false) do |entry|\n group_members.append(entry[\"mail\"])\n end\n group_members\n end", "def convert_attributes attributes, dropped_attributes_count,\n include_agent_attribute: false\n attribute_map = {}\n if include_agent_attribute\n attribute_map[AGENT_KEY] = convert_attribute_value AGENT_VALUE\n end\n attributes.each do |k, v|\n attribute_map[convert_attribute_name k] =\n convert_attribute_value v\n end\n TraceProtos::Span::Attributes.new \\\n attribute_map: attribute_map,\n dropped_attributes_count: dropped_attributes_count\n end", "def all(domain,username,password,dc_ip)\n\n enum_dom_users(domain,username,password,dc_ip)\n\n enum_dom_groups(domain,username,password,dc_ip)\n\n groupArr = [\"Domain Admins\",\"Domain Computers\",\"Enterprise Admins\",\"Administrators\"]\n\n groupArr.each {|group| enum_group_membership(domain,username,password,dc_ip,group)}\n\n priv_groups(domain,username,password,dc_ip)\n\n grab_attr(domain,username,password,dc_ip)\nend", "def acquire_service_data\n if config[:tags] && config[:service]\n tags = config[:tags].split(',').to_set\n services = []\n Diplomat::Health.service(config[:service]).each do |s|\n if s['Service']['Tags'].to_set.superset? tags\n services.push(*s['Checks'])\n end\n end\n services\n elsif config[:nodename]\n data = []\n begin\n services = Diplomat::Node.get(config[:nodename]).Services\n rescue StandardError\n services = {}\n end\n services.each_value do |service|\n Diplomat::Health.checks(service['Service']).each do |check|\n data.push(check) if check.Node == config[:nodename]\n end\n end\n data\n elsif config[:all]\n Diplomat::Health.state('any')\n else\n Diplomat::Health.checks(config[:service])\n end\n end", "def postEntityGroup( entity_id, group_id)\n params = Hash.new\n params['entity_id'] = entity_id\n params['group_id'] = group_id\n return doCurl(\"post\",\"/entity/group\",params)\n end", "def groups_base\n get_groups_base\n# get_attribute_from_auth_source('groups_base')\n end", "def get_cgroup_attribute_cgget(attribute, username)\n cmd = \"cgget -n -v -r #{attribute} /openshift/#{username}\"\n # This would be simple, but we can't catch errors\n #value = %x[%{cmd}]\n pid, stdin, stdout, stderr = open4(cmd)\n\n # get the error string (if any). Remove trailing newlines.\n error = stderr.read.strip\n\n if not error == \"\" then\n $stderr.puts \"Could not find attribute #{attribute}\"\n $stderr.puts error\n exit 2\n end\n\n # Get the output string. Remove trailing newlines (just one)\n value = stdout.read.strip\nend", "def discover\n data[@group]\n end", "def get_service_contacts(service_id, start_date, end_date)\n get_agent_contacts(service_group_id: -1,\n service_id: service_id,\n team_name: '',\n agent_id: -1,\n start_date: start_date,\n end_date: end_date,\n contact_type: 'PBX EMAIL SMS FAX SCAN CHAT COBRO MANUAL FACE TASK VIDEO')\n end", "def test_get_ad_group\n test_add_ad_group_cpc() unless @ad_group\n selector = @ad_group_srv.module::AdGroupSelector.new\n selector.adGroupIds = [@ad_group.id]\n response = @ad_group_srv.get(selector)\n assert_not_nil(response.rval.entries, 'Empty result set returned')\n assert_equal(1, response.rval.entries.size,\n 'Unexpected number of entries returned')\n assert_equal(@ad_group.id, response.rval.entries.first.id)\n end", "def extract_group_members(grouplink, groupname)\n mahara_group_overview_page = @agent.get(grouplink)\n # selecting group member page ...\n mahara_group_members_page_1 = mahara_group_overview_page.link_with(:href => /mahara\\/group\\/members/).click\n # selecting complete view of members\n form = mahara_group_members_page_1.form_with(:class => 'form-pagination js-pagination form-inline pagination-page-limit dropdown')\n PortfolioAnalyzerTools.select_option(form, 'setlimitselect', '500')\n mahara_group_members_page_2 = form.submit\n\n # extract members\n main_column = mahara_group_members_page_2.css('div.main-column')[0]\n # an alternative, more general approach might be: mahara_group_members_page_2.css('div.list-group-item').each do |row|\n\n group_members = extract_members(main_column, grouplink, groupname)\n end", "def parse_service_data_from_options\n data = {}\n data[:strategy] = deploy_strategy if deploy_strategy\n data[:ports] = parse_ports(ports_list) unless ports_list.empty?\n data[:links] = parse_links(link_list) unless link_list.empty?\n data[:memory] = parse_memory(memory) if memory\n data[:memory_swap] = parse_memory(memory_swap) if memory_swap\n data[:shm_size] = parse_memory(shm_size) if shm_size\n data[:cpus] = cpus if cpus\n data[:cpu_shares] = cpu_shares if cpu_shares\n data[:affinity] = affinity_list unless affinity_list.empty?\n data[:env] = env_list unless env_list.empty?\n data[:secrets] = parse_secrets(secret_list) unless secret_list.empty?\n data[:container_count] = instances if instances\n data[:cmd] = Shellwords.split(cmd) if cmd\n data[:user] = user if user\n data[:image] = parse_image(image) if image\n data[:privileged] = privileged?\n data[:cap_add] = cap_add_list if cap_add_list\n data[:cap_drop] = cap_drop_list if cap_drop_list\n data[:net] = net if net\n data[:log_driver] = log_driver if log_driver\n data[:log_opts] = parse_log_opts(log_opt_list) if log_opt_list\n deploy_opts = parse_deploy_opts\n data[:deploy_opts] = deploy_opts unless deploy_opts.empty?\n health_check = parse_health_check\n data[:health_check] = health_check unless health_check.empty?\n data[:pid] = pid if pid\n data[:stop_signal] = stop_signal if stop_signal\n data[:stop_grace_period] = stop_timeout if stop_timeout\n data\n end", "def get_group_vm_statistics_0_with_http_info(domain_id, group_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics_0 ...'\n end\n # verify the required parameter 'domain_id' is set\n if @api_client.config.client_side_validation && domain_id.nil?\n fail ArgumentError, \"Missing the required parameter 'domain_id' when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics_0\"\n end\n # verify the required parameter 'group_id' is set\n if @api_client.config.client_side_validation && group_id.nil?\n fail ArgumentError, \"Missing the required parameter 'group_id' when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics_0\"\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics_0, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyInventoryGroupsGroupMembersApi.get_group_vm_statistics_0, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/global-infra/domains/{domain-id}/groups/{group-id}/statistics/virtual-machines'.sub('{' + 'domain-id' + '}', domain_id.to_s).sub('{' + 'group-id' + '}', group_id.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'enforcement_point_path'] = opts[:'enforcement_point_path'] if !opts[:'enforcement_point_path'].nil?\n query_params[:'include_mark_for_delete_objects'] = opts[:'include_mark_for_delete_objects'] if !opts[:'include_mark_for_delete_objects'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'RealizedVirtualMachineListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicyInventoryGroupsGroupMembersApi#get_group_vm_statistics_0\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def parse_group_of_flights data_to_parse\n out = {}\n counter = 0\n data_to_parse.xpath(\"flightDetails\").each do |fd|\n counter += 1\n flight_segment_detail = {}\n flight_segment_detail[:dateOfDeparture] = fd.xpath(\"flightInformation/productDateTime/dateOfDeparture\").first.content\n flight_segment_detail[:timeOfDeparture] = fd.xpath(\"flightInformation/productDateTime/timeOfDeparture\").first.content\n flight_segment_detail[:dateOfArrival] = fd.xpath(\"flightInformation/productDateTime/dateOfArrival\").first.content\n flight_segment_detail[:timeOfArrival] = fd.xpath(\"flightInformation/productDateTime/timeOfArrival\").first.content\n flight_segment_detail[:from] = fd.xpath(\"flightInformation/location[1]/locationId\").first.content\n flight_segment_detail[:to] = fd.xpath(\"flightInformation/location[2]/locationId\").first.content\n attr_name = \"segment_#{counter}\".to_sym\n out[attr_name] = flight_segment_detail\n end\n out\n\n end", "def get_groups(host, base='dc=griddynamics,dc=net', scope=LDAP::LDAP_SCOPE_SUBTREE)\n attrs = ['cn', 'memberUid']\n\n conn = LDAP::Conn.new(host)\n conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)\n puts conn.bind('','')\n\n conn.perror(\"bind\")\n\n begin\n groups = Hash.new\n conn.search(base, scope, '(objectClass=groupOfNames)', attrs) { |entry|\n groups[entry.vals('cn')[0]] = entry.vals('memberUid')\n }\n return groups\n rescue LDAP::ResultError\n conn.perror(\"search\")\n exit\n end\n conn.perror(\"search\")\n conn.unbind\nend", "def group_by(attribute)\n @group_by = Dynamicloud::API::Criteria::GroupByClause.new(attribute)\n self\n end", "def fetch_group_data\n response = fetch_data(@@SETTINGS.group_tab)\n unless response.nil?\n adjust_groups response\n end\n end", "def topo_data\n data = { 'tp-id' => @name }\n data['supporting-termination-point'] = @supports.map(&:topo_data) unless @supports.empty?\n data[@attribute.type] = @attribute.topo_data unless @attribute.empty?\n data\n end", "def build_activity_set(activity_group, agb)\n scores = Models::Collection.new\n activities = Models::Collection.new\n activity_group.assessment_activity_profile.assessment_activities.each do |activity|\n activity_component = new_activity(activity)\n activities.push activity_component\n scores.push new_score(agb, activity, activity_component)\n end\n \n return Models::ActivitySet.new(\n :name => activity_group.display_name,\n :profile_name => activity_group.assessment_activity_profile.name ,\n :activities => activities,\n :scores => scores,\n :term_name => term_name(activity_group),\n :code =>activity_group.code\n )\n end", "def create(opts = {})\n port = opts.fetch(:port)\n value = opts.fetch(:value)\n timestamp = opts.fetch(:timestamp, DateTime.now)\n\n body = {\n data: {\n attributes: {\n port: port,\n value: value,\n timestamp: datetime_to_iso(timestamp)\n },\n type: 'data-point'\n }\n }\n\n response = @client.post(@path, body: body)\n resource_data = JSON.parse(response.body)[\"data\"]\n\n return DataPoint.new(client: self, params: resource_data)\n end", "def grab_attr(domain,username,password,dc_ip)\n cmd = `rpcclient -U '#{domain}\\\\\\\\#{username}%#{password}' #{dc_ip} -c lsaquery | head -n 1`\n ip_check(dc_ip,cmd)\n\n output = \"#{domain}-attributes.txt\"\n temp_file = \"temp1\"\n\n cmd = `rpcclient -U '#{domain}\\\\\\\\#{username}%#{password}' #{dc_ip} -c enumdomusers | cut -d \" \" -f 2 | sed 's/rid:\\\\[//g' | sed 's/\\\\]//g' > #{temp_file}`\n\n puts \"Looking up user account attrubutes for each user.\"\n puts \"\"\n\n user_arr = Array.new\n r = File.open(temp_file)\n r.each_line {|line| user_arr.push line.chomp}\n del_temp = `rm #{temp_file}`\n\n File.open(output, 'w') do |file|\n user_arr.peach(2) do |user|\n puts \"Attributes for RID: #{user}\"\n attrib = `rpcclient -U '#{domain}\\\\\\\\#{username}%#{password}' #{dc_ip} -c 'queryuser #{user}'`\n puts attrib\n file.write(\"Attributes for RID: #{user}\\n#{attrib}\")\n end\n end\n puts \"[+] Success! All users attributes have been stored in #{output}\"\nend", "def add_hosts_group\n puppet_ip = any_hosts_as?(:loadbalancer) ? loadbalancer.ip : master.ip\n hosts_group = {\n \"name\" => \"Clamps Managed Hosts\",\n \"rule\" => [\"or\", [\"=\", %w[fact id], \"root\"]],\n \"parent\" => pe_infra_uuid,\n \"classes\" => {\n \"hosts\" => {\n \"purge_hosts\" => false,\n \"collect_all\" => true,\n \"host_entries\" => {\n \"puppet\" => { \"ip\" => puppet_ip }\n }\n }\n }\n }\n\n dispatcher.find_or_create_node_group_model(hosts_group)\nend", "def set_service_group\n @service_group = ServiceGroup.find(params[:id])\n end", "def add_openldap_group\n return unless any_hosts_as?(:openldap)\n\n openldap_group = {\n \"name\" => \"OpenLDAP Server\",\n \"rule\" => [\"or\", [\"=\", \"name\", openldap.node_name]], # pinned node\n \"parent\" => pe_infra_uuid,\n \"classes\" => {\n \"openldap::server\" => {\n \"databases\" => { \"dc=delivery,dc=puppetlabs,dc=net\" => {\n \"rootdn\" => \"cn=admin,dc=delivery,dc=puppetlabs,dc=net\",\n \"rootpw\" => \"Puppet11\"\n } }\n }\n }\n }\n\n dispatcher.find_or_create_node_group_model(openldap_group)\nend", "def load_group(group_entry)\n if @virtual_attributes.enabled?\n VirtualGroup.new(self, group_entry)\n elsif posix_support_enabled? && PosixGroup.valid?(group_entry)\n PosixGroup.new(self, group_entry)\n else\n Group.new(self, group_entry)\n end\n end", "def groups\n return @groups if @groups\n @groups = AaaGroups.new node\n @groups\n end", "def create_entity_group\n @entity_group = EntityGroup.create!(client_id: @client_id,\n uuid: Util::Encryption::Admin.get_uuid,\n creator_admin_id: @admin_id,\n status: GlobalConstant::EntityGroup.active_status,\n activated_at: Time.now.to_i)\n end", "def peer_group\n sales = @current_policy ? @current_policy.sales : @company_info.sales_volume.to_i\n stress_score = @company_info.financial_stress_score.to_i\n DnoGroup.peer_group(industry_group, sales, stress_score)\n end", "def create_ad_group(client, customer_id, campaign)\n # Creates an ad group operation.\n operation = client.operation.create_resource.ad_group do |ag|\n ag.name = \"Earth to Mars Cruises #{(Time.new.to_f * 1000).to_i}\"\n ag.campaign = campaign\n ag.status = :PAUSED\n end\n\n # Issues a mutate request to add the ad group.\n response = client.service.ad_group.mutate_ad_groups(\n customer_id: customer_id,\n operations: [operation],\n )\n\n # Print out some information about the added ad group.\n resource_name = response.results.first.resource_name\n puts \"Added ad group named #{resource_name}\"\n\n resource_name\nend", "def get_node_data(url)\n begin\n response = RestClient.get(url,\n authorization: \"Basic #{Base64.strict_encode64(\"#{@username}:#{@password}\")}\",\n content_type: 'application/json',\n accept: 'application/json',\n timeout: 120)\n response_data = JSON.parse(response)\n result = response_data['result'][0]\n\n rescue RestClient::ExceptionWithResponse => e\n e.response\n @logger.err(e.response) unless @logger.nil?\n result = nil\n end\n\n update_attributes(result)\n end", "def get_ldap_group_member(groupname:)\n filter = Net::LDAP::Filter.eq( 'objectCategory', 'group' ) & Net::LDAP::Filter.eq('cn', \"#{groupname}\")\n @treebase = 'OU=Groups,dc=UoA,dc=auckland,dc=ac,dc=nz'\n\n @ldap.search( base: @treebase, filter: filter, attributes: [ 'member' ] ) do |entry|\n group = entry.dn.split('=')[1].split(',')[0]\n entry.each do |attribute, values|\n next unless attribute.to_s == 'member'\n\n values.each do |value|\n member = value.split('=')[1].split(',')[0]\n yield group, member\n end\n end\n end\n end", "def user_in_group?(attribs, dir_info)\n temp = user_record_name_alternatives(attribs)\n username = temp[:record_name]\n # pp username\n # pp attribs\n\n attribs = group_record_name_alternatives(attribs)\n # groupname = attribs[:record_name]\n attribs[:value] = username\n # pp attribs\n\n check_critical_attribute( attribs, :value, :username )\n check_critical_attribute( attribs, :record_name, :groupname )\n attribs = tidy_attribs(attribs)\n\n command = {action: 'read', scope: 'Groups', attribute: nil, value: nil}\n cmd_attribs = attribs.merge(command)\n\n dscl( cmd_attribs, dir_info )\n end", "def initialize(options = {})\n @uid = options[:uid] || \"sAMAccountName\"\n\n # Keep a reference to these as default auth for a Global Catalog if needed\n @admin_user = options[:admin_user]\n @admin_password = options[:admin_password]\n @port = options[:port]\n\n @connection = Net::LDAP.new({\n host: options[:host],\n port: options[:port],\n hosts: options[:hosts],\n instrumentation_service: options[:instrumentation_service]\n })\n\n if options[:admin_user] && options[:admin_password]\n @connection.authenticate(options[:admin_user], options[:admin_password])\n end\n\n if encryption = check_encryption(options[:encryption], options[:tls_options])\n @connection.encryption(encryption)\n end\n\n configure_virtual_attributes(options[:virtual_attributes])\n\n # enable fallback recursive group search unless option is false\n @recursive_group_search_fallback = (options[:recursive_group_search_fallback] != false)\n\n # enable posixGroup support unless option is false\n @posix_support = (options[:posix_support] != false)\n\n # search_domains is a connection of bases to perform searches\n # when a base is not explicitly provided.\n @search_domains = Array(options[:search_domains])\n\n # configure both the membership validator and the member search strategies\n configure_search_strategy(options[:search_strategy])\n\n # configure the strategy used by Domain#user? to look up a user entry for login\n configure_user_search_strategy(options[:user_search_strategy])\n\n # enables instrumenting queries\n @instrumentation_service = options[:instrumentation_service]\n end", "def api_v11_clusters_cluster_name_services_service_name_role_config_groups_post_with_http_info(service_name, cluster_name, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: DefaultApi#api_v11_clusters_cluster_name_services_service_name_role_config_groups_post ...\"\n end\n \n # verify the required parameter 'service_name' is set\n fail \"Missing the required parameter 'service_name' when calling api_v11_clusters_cluster_name_services_service_name_role_config_groups_post\" if service_name.nil?\n \n # verify the required parameter 'cluster_name' is set\n fail \"Missing the required parameter 'cluster_name' when calling api_v11_clusters_cluster_name_services_service_name_role_config_groups_post\" if cluster_name.nil?\n \n # resource path\n path = \"/api/v11/clusters/{clusterName}/services/{serviceName}/roleConfigGroups\".sub('{format}','json').sub('{' + 'serviceName' + '}', service_name.to_s).sub('{' + 'clusterName' + '}', cluster_name.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = []\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = []\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n \n\n auth_names = []\n data, status_code, headers = @api_client.call_api(:POST, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: DefaultApi#api_v11_clusters_cluster_name_services_service_name_role_config_groups_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def add_clamps_group_ca(classifier, pe_infra)\n # The Clamps::master class manages auth.conf for the agents - by setting it\n # to allow all. This is insecure and worth looking at overriding at some\n # point, but this should only be used for metrics / load testing on a private\n # network, so shouldn't be an issue short term.\n clamps_ca_group = {\n \"name\" => \"Clamps CA\",\n \"rule\" => [\"or\", [\"=\", \"name\", master.node_name]], # pinned node\n \"parent\" => pe_infra[\"id\"],\n \"classes\" => {\n \"clamps::master\" => {}\n }\n }\n classifier.find_or_create_node_group_model(clamps_ca_group)\nend", "def group_variable(group, key)\n get(\"/groups/#{url_encode group}/variables/#{key}\")\n end", "def group(name, args)\n raise \":data is needed as an argument to group metrics\" unless args[:data]\n raise \":subgroup is needed as an argument to group metrics\" unless args.include?(:subgroup)\n\n args[:aggregator] = \"sumSeries\" unless args[:aggregator]\n\n group_args = args.clone\n group_args[:data] = \"groupByNode(#{group_args[:data]},#{group_args[:subgroup]},\\\"#{group_args[:aggregator]}\\\")\"\n field \"#{name}_group\", group_args\n\n end", "def ad_group!(options = {})\n ad_group = post options.merge(:connection => :adgroups)\n\n adgroup_id = ad_group[:id]\n\n merged_attrs = options.merge(\n :access_token => options[:access_token] || self.access_token,\n :ad_id => adgroup_id.to_i,\n :adgroup_id => adgroup_id.to_i\n )\n\n if options[:redownload]\n merged_attrs = merged_attrs.merge(ad_group[:data][:adgroups][adgroup_id]).with_indifferent_access\n end\n\n AdGroup.new ad_group[:id], merged_attrs\n end", "def get_groups(cookie, event_id=nil)\n group_hash = Rails.cache.fetch(Person.groups_cache_key(id,cookie), :expires_in => PERSON_HASH_CACHE_EXPIRE_TIME) {PersonConnection.get_groups(self.id, cookie, event_id)}\n return group_hash\n end", "def agents\n return @agents unless @agents.nil?\n agents_array = []\n agents = @doc.xpath('//mets:agent')\n agents.each do |agent|\n type = agent.attr('TYPE')\n role = agent.attr('ROLE')\n id = agent.attr('ID')\n if agent.element_children.first.name == 'name'\n name = agent.element_children.first.text\n else\n name = ''\n end\n\n agent_object = {\n type: type, \n role: role,\n id: id,\n name: name\n }\n\n agents_array << agent_object\n end\n\n @agents = agents_array\n @agents\n end", "def create_ns_service_group_with_http_info(ns_service_group, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiGroupingObjectsNsServiceGroupsApi.create_ns_service_group ...'\n end\n # verify the required parameter 'ns_service_group' is set\n if @api_client.config.client_side_validation && ns_service_group.nil?\n fail ArgumentError, \"Missing the required parameter 'ns_service_group' when calling ManagementPlaneApiGroupingObjectsNsServiceGroupsApi.create_ns_service_group\"\n end\n # resource path\n local_var_path = '/ns-service-groups'\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(ns_service_group)\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'NSServiceGroup')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiGroupingObjectsNsServiceGroupsApi#create_ns_service_group\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def getEntityBy_groupid( group_id)\n params = Hash.new\n params['group_id'] = group_id\n return doCurl(\"get\",\"/entity/by_groupid\",params)\n end", "def parse_attribute(attribute, default, opts)\n opts, default = default, nil if default.is_a?(Hash)\n # Merge-in default opts!\n opts = {upcase: true}.merge!(opts)\n caseattr = opts[:upcase] == true ? attribute.to_s.upcase : attribute.to_s\n value = ENV[opts[:from] || caseattr]\n if opts[:reset]\n # don't parse env variable, just set value\n [caseattr, default, opts]\n elsif value == \"\"\n # use default, when passed env is empty\n [caseattr, default, opts]\n else\n [caseattr, value || default, opts]\n end\n end", "def get_node_and_component_attributes(_opts = {})\n node_attrs = get_node_attributes_stub\n component_attrs = get_objs(cols: [:component_attrs]).map { |r| r[:attribute] }\n component_attrs + node_attrs\n end", "def api_v11_clusters_cluster_name_services_service_name_role_config_groups_get_with_http_info(service_name, cluster_name, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: DefaultApi#api_v11_clusters_cluster_name_services_service_name_role_config_groups_get ...\"\n end\n \n # verify the required parameter 'service_name' is set\n fail \"Missing the required parameter 'service_name' when calling api_v11_clusters_cluster_name_services_service_name_role_config_groups_get\" if service_name.nil?\n \n # verify the required parameter 'cluster_name' is set\n fail \"Missing the required parameter 'cluster_name' when calling api_v11_clusters_cluster_name_services_service_name_role_config_groups_get\" if cluster_name.nil?\n \n # resource path\n path = \"/api/v11/clusters/{clusterName}/services/{serviceName}/roleConfigGroups\".sub('{format}','json').sub('{' + 'serviceName' + '}', service_name.to_s).sub('{' + 'clusterName' + '}', cluster_name.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = []\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = []\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n \n\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: DefaultApi#api_v11_clusters_cluster_name_services_service_name_role_config_groups_get\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def user_service\n\t\tTheCityAdmin::AdminApi.connect(Rcplugin::CITY_ADMIN_SECRET,Rcplugin::CITY_USER_TOKEN)\n\n\t\t@group = TheCityAdmin::GroupList.new\n\tend", "def read_ns_service_group_with_http_info(ns_service_group_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: GroupingObjectsApi.read_ns_service_group ...\"\n end\n # verify the required parameter 'ns_service_group_id' is set\n if @api_client.config.client_side_validation && ns_service_group_id.nil?\n fail ArgumentError, \"Missing the required parameter 'ns_service_group_id' when calling GroupingObjectsApi.read_ns_service_group\"\n end\n # resource path\n local_var_path = \"/ns-service-groups/{ns-service-group-id}\".sub('{' + 'ns-service-group-id' + '}', ns_service_group_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'NSServiceGroup')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: GroupingObjectsApi#read_ns_service_group\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def describe_image_attribute(image_id, attribute='launchPermission')\n image_attr = @ec2.describe_image_attribute(image_id, attribute)\n { :users => image_attr.launchPermission.userIds,\n :groups => image_attr.launchPermission.groups }\n \n rescue Exception\n on_query_exception('describe_image_attribute')\n end", "def get_datasource()\n # was an input file arg provided?\n if ($input_file)\n # yes -- use local xml file as source\n source_xml = get_local_datasource($input_file)\n else\n # no -- get sourcex xml from account\n source_xml = get_remote_datasource($account, $userid, $passwd, $instance_id)\n end\n\n dsobj = Nokogiri::XML(source_xml)\n\n return dsobj\n end", "def json_data\n members = self.members.map do |member|\n member.group_json_data(self.id)\n end\n { group: self, members: members, member_split: self.member_split.round(2), total_spend: self.expenses_total.round(2)}\n end", "def get_contact_group_by_id(contact_group_id)\n request_params = { :ContactGroupID => contact_group_id }\n response_xml = http_get(@client, \"#{@xero_url}/ContactGroups/#{CGI.escape(contact_group_id)}\", request_params)\n\n parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contactgroup'})\n end", "def describe_load_balancer_u_d_p_listener_attribute(listener_port, load_balancer_id, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancerUDPListenerAttribute'\n\t\targs[:query]['LoadBalancerId'] = load_balancer_id\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\traise ArgumentError, 'listener_port must be equal or greater than 1' unless listener_port < 1\n\t\traise ArgumentError, 'listener_port must be equal or less than 65535' unless listener_port > 65535\n\t\targs[:query]['ListenerPort'] = listener_port\n\t\tself.run(args)\n\tend", "def initialize(redcap_data)\n\t\t# Everything is pretty self-explainatory. You're essentially creating the 'data' hash to prepare for a data download of all individuals \n\t\t@data_set = []\n\t\tredcap_data.each do |participant|\n\t\t\tsfs = calculate_sfs(participant)\n\t\t\tedss = calculate_edss(participant, sfs)\n\t\t\taI = calculate_AI(participant)\n\t\t\tnrs = calculate_nrs(participant, sfs)\t\n\t\t\tmds = calculate_mds(edss, nrs, aI, participant[\"fs\"].to_i, sfs)\n\t\t\tdata = {\n\t\t\t\t\trecord_id: participant[\"record_id\"].to_i,\n\t\t\t\t\tfirst_name: participant[\"first_name\"],\n\t\t\t\t\tlast_name: participant[\"last_name\"],\n\t\t\t\t\tsfs: sfs[:sfs],\n\t\t\t\t\tedss: edss,\n\t\t\t\t\taI: aI,\n\t\t\t\t\tnrs: nrs,\n\t\t\t\t\tmds: mds,\n\t\t\t\t\tf1: sfs[:f1],\n\t\t\t\t\tf2: sfs[:f2],\n\t\t\t\t\tf3: sfs[:f3],\n\t\t\t\t\tf4:sfs[:f4],\n\t\t\t\t\tf5: sfs[:f5],\n\t\t\t\t\tf6: sfs[:f6],\n\t\t\t\t\tf7: sfs[:f7],\n\t\t\t\t\tf8: sfs[:f8],\n\t\t\t\t\ta1: participant[\"a1\"],\n\t\t\t\t\ta21: participant[\"a21\"],\n\t\t\t\t\ta22: participant[\"a22\"],\n\t\t\t\t\ta23: participant[\"a23\"],\n\t\t\t\t\ta24: participant[\"a24\"],\n\t\t\t\t\tf2a: participant[\"f2a\"],\n\t\t\t\t\tf2b: participant[\"f2b\"],\n\t\t\t\t\tf2c: participant[\"f2c\"],\n\t\t\t\t\tf2d: participant[\"f2d\"],\n\t\t\t\t\tbal: participant[\"bal\"],\n\t\t\t\t\tb3: participant[\"b3\"],\n\t\t\t\t\tf1fr: participant[\"f1fr\"],\n\t\t\t\t\tf1fl: participant[\"f1fl\"],\n\t\t\t\t\tf4fr: participant[\"f4fr\"],\n\t\t\t\t\tfrfl: participant[\"frfl\"],\n\t\t\t\t\tb1: participant[\"b1\"],\n\t\t\t\t\tf2s: participant[\"f2s\"],\n\t\t\t\t\tb2: participant[\"b2\"],\n\t\t\t\t\tb4: participant[\"b4\"],\n\t\t\t\t\tf4a: participant[\"f4a\"],\n\t\t\t\t\tf4b: participant[\"f4b\"],\n\t\t\t\t\tf4c: participant[\"f4c\"],\n\t\t\t\t\tf4d: participant[\"f4d\"],\n\t\t\t\t\tf5ta: participant[\"f5ta\"],\n\t\t\t\t\tf6a: participant[\"f6a\"],\n\t\t\t\t\tf6b: participant[\"f6b\"],\n\t\t\t\t\tf7t: participant[\"f7t\"],\n\t\t\t\t\tc1: participant[\"c1\"],\n\t\t\t\t\tf1a: participant[\"f1a\"],\n\t\t\t\t\tf1b: participant[\"f1b\"],\n\t\t\t\t\tf1c: participant[\"f1c\"],\n\t\t\t\t\tf1d: participant[\"f1d\"],\n\t\t\t\t\tf8a: participant[\"f8a\"],\n\t\t\t\t\tf8b: participant[\"f8b\"],\n\t\t\t\t\tf8c: participant[\"f8c\"],\n\t\t\t\t\tf8d: participant[\"f8d\"]\n\t\t\t}\n\t\t\t@data_set<< data\n\t\tend\n\tend", "def agent_group_id\n super\n end", "def read_ns_service_group_with_http_info(ns_service_group_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiGroupingObjectsNsServiceGroupsApi.read_ns_service_group ...'\n end\n # verify the required parameter 'ns_service_group_id' is set\n if @api_client.config.client_side_validation && ns_service_group_id.nil?\n fail ArgumentError, \"Missing the required parameter 'ns_service_group_id' when calling ManagementPlaneApiGroupingObjectsNsServiceGroupsApi.read_ns_service_group\"\n end\n # resource path\n local_var_path = '/ns-service-groups/{ns-service-group-id}'.sub('{' + 'ns-service-group-id' + '}', ns_service_group_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'NSServiceGroup')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiGroupingObjectsNsServiceGroupsApi#read_ns_service_group\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def geographic(subject, data, predicate=RDF::Vocab::DC[:spatial], extra_params={})\n @log.debug(\"Geographic: \" + data)\n\n graph = RDF::Graph.new\n\n Array(data.split(';')).each do |location|\n location.strip!\n\n @log.debug(\"Geographic split: \" + location)\n\n unless geocache.include? location\n begin\n geonames_search(location, extra_params)\n rescue => e\n puts subject, location, e.backtrace\n end\n end\n\n if geocache.include? location\n graph << RDF::Statement.new(subject, predicate, geocache[location][:uri])\n else\n @log.warn(\"Geographic URI not found: \" + location)\n# graph << RDF::Statement.new(subject, predicate, location)\n end\n end\n\n graph\n end", "def get_full_data(data)\n @client.api_request(\n :method => \"usergroup.get\", \n :params => {\n :filter => [data[:name]],\n :output => \"extend\"\n }\n )\n end", "def get_attributes(node)\n unless inside_testkitchen?\n data = get_search(:node, \"name:#{node}\")\n\n merge_attributes(data)\n else\n kitchen_provisioner_config[:attributes]\n end\n end", "def get_dynamic_attributes__node_components!(attr_names)\n ret = {}\n return ret unless attr_names.delete(:node_components)\n # TODO: hack\n ipv4_val = CommandAndControl.get_and_update_node_state!(self[:node], [:host_addresses_ipv4])\n return ret if ipv4_val.empty?\n cmps = self[:node].get_objs(cols: [:components]).map { |r| r[:component][:display_name].gsub('__', '::') }\n ret = { node_components: { ipv4_val.values.first[0] => cmps } }\n if attr_names.delete(:host_addresses_ipv4)\n ret.merge!(ipv4_val)\n end\n ret\n end", "def get_service_options\n begin\n @dt_service = @services.find_service(DT_SERVICE_NAME)\n dt_profile_name = vcap_dt_profile ? vcap_dt_profile : DT_DEFAULT_PROFILE_NAME\n if vcap_dt_server.nil?\n raise 'Dynatrace Appmon server is not set, server must be set in service credentials.'\n end\n @dt_options = \"name=#{dt_profile_name},server=#{vcap_dt_server}\"\n\n if @dt_service.key?(OPTIONS_KEY) && @dt_service[OPTIONS_KEY].any?\n @dt_service[OPTIONS_KEY].each do |k, v|\n @dt_options << \",#{k}=#{v}\"\n end\n end\n rescue => e\n @logger.error(\"Unable to process the service options for the Dynatrace Appmon Agent framework. #{e.message}\")\n end\n\n @dt_options.nil? ? nil : @dt_options\n end", "def normalize_data(sort_mode)\n $logger.info('Normalizing group data...')\n groups_grouped = @groups.collect(&:to_hash).group_by do|a|\n { 'gid' => a['gid'],\n 'name' => a['name'],\n 'members' => a['members'] }\n end\n out = groups_grouped.collect do |a|\n a[0].merge('nodes' => a[1].collect { |b| b['source_node'] }.uniq.sort!)\n end\n out.compact!\n out = out.group_by do |a|\n { 'gid' => a['gid'], 'name' => a['name'], 'membership' => { 'members' => a['members'], 'nodes' => a['nodes'] } }\n end\n out = out.keys\n out = out.group_by { |a| { 'gid' => a['gid'], 'name' => a['name'] } }.collect do |a|\n a[0].merge('membership' => a[1].collect { |b| b['membership'] })\n end\n sort_key = sort_mode == 'id' ? 'gid' : 'name'\n out.sort! { |a, b| a[sort_key] <=> b[sort_key] }\n end", "def build_data\n agent = Mechanize.new\n\n # Raise an particular ConnectionToBBCError exception\n # on connectivity issues\n begin\n page = agent.get(URL)\n rescue *CONNECTION_ERRORS => error\n raise ConnectionToBBCError, error\n end\n\n locations = {}\n\n # For each location...\n 1.upto(NUMBER_OF_LOCATIONS) do |i|\n area = page.search(\"#area-#{i}\")\n location = area.search(\"h2\").text\n\n # Warnings, if any\n warning = nil\n warning_detail = area.search(\".warning-detail\")\n\n # Search for the warning title\n warning_title = warning_detail.search(\"strong\").text.gsub(':', '')\n\n # Check if there is a warning before proceeding\n if !warning_title.empty?\n warning = {}\n\n # Breakout the particular warnings\n warning[:title] = warning_title\n warning[:issued] = warning_detail.search(\".issued\").text\n warning[:summary] = warning_detail.search(\".summary\").text\n end\n\n # Build up all the conditions\n location_report = {}\n breakdown = area.search(\"ul\").children.search(\"span\")\n\n location_report[:warning] = warning\n location_report[:location] = location\n location_report[:wind] = breakdown[0].text\n location_report[:seas] = breakdown[1].text\n location_report[:weather] = breakdown[2].text\n location_report[:visibility] = breakdown[3].text\n\n # Set the report for this location in the locations hash\n locations[location] = location_report\n end\n\n locations\n end", "def set_group_member_attribute(opts)\n opts = check_params(opts,[:member_attrs])\n super(opts)\n end", "def data_service\n DataServicesApi::Service.new(url: api_service_url)\n end" ]
[ "0.48148233", "0.4416741", "0.42515406", "0.42063287", "0.41547632", "0.4098359", "0.40892184", "0.4080662", "0.40591976", "0.40394482", "0.39851138", "0.39571363", "0.39442456", "0.3898882", "0.3848071", "0.3843621", "0.3828492", "0.38222227", "0.38091433", "0.3783533", "0.37829858", "0.37809983", "0.37780428", "0.3772843", "0.37643614", "0.37619668", "0.37473732", "0.367954", "0.3678245", "0.36758745", "0.36722544", "0.36633876", "0.3659077", "0.36570233", "0.36329964", "0.36311293", "0.36305857", "0.36219752", "0.362039", "0.36167625", "0.36161777", "0.36119977", "0.3604564", "0.35948363", "0.35897374", "0.35884267", "0.3587841", "0.358592", "0.35793233", "0.35765862", "0.35691017", "0.35657984", "0.3562629", "0.35550097", "0.35522294", "0.35521472", "0.35512963", "0.35467008", "0.35465166", "0.3546205", "0.3544236", "0.35353872", "0.35335237", "0.35275018", "0.3523786", "0.3522765", "0.35217044", "0.3513868", "0.35071868", "0.35058737", "0.35049376", "0.35027647", "0.34972274", "0.34963146", "0.34957394", "0.34946522", "0.34914055", "0.34888405", "0.34859794", "0.34846467", "0.34807086", "0.34780774", "0.34771174", "0.3475638", "0.34711662", "0.34642226", "0.34634155", "0.346309", "0.34609526", "0.34597722", "0.34562153", "0.34549773", "0.34526172", "0.34521306", "0.34475985", "0.34464902", "0.34461853", "0.34421164", "0.3441393", "0.34404576" ]
0.7813658
0
Parses the specified arguments (presumably ARGV), returning the agent address, service point, username, password, and attribute group that were specified on the command line, in addition a list of columns and subnodes in an OpenStruct object. +args+:: The arguments to parse. These presumably came from the commandline.
def parse_args(args) require 'ostruct' require 'optparse' parser = OptionParser.new options = OpenStruct.new options.output = STDOUT options.format = :text options.columns = nil options.subnodes = [ ] parser.banner = "Usage: #{$0} [options] agent_address service_point username password attribute_group" parser.on("-h", "--help", "Show this message.") { $stderr.puts parser; exit } parser.on("-f", "--format [ 'text' | 'html' ]", [:text, :html], "Set the output format to either plain text or HTML.", "[default: text]") do |f| options.format = f end parser.on("-c", "--columns c1,...,cN", Array, "Output columns c1,...,cN.", "[default: all columns]") { |c| options.columns = c } parser.on("-s", "--subnodes s1,...,sN", Array, "Collects data for subnodes s1,...,sN.", "[default: no subnodes]") { |s| options.subnodes = s } rest = parser.parse(args) # Ensure we have all the required args if rest.length != 5 $stderr.puts parser exit end return *rest, options end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_args()\n opts = GetoptLong.new(\n ['--host', GetoptLong::OPTIONAL_ARGUMENT],\n ['--port', GetoptLong::OPTIONAL_ARGUMENT],\n ['--columns', GetoptLong::OPTIONAL_ARGUMENT],\n ['--index', GetoptLong::REQUIRED_ARGUMENT],\n ['--type', GetoptLong::REQUIRED_ARGUMENT]\n )\n\n opts.each do |opt, arg|\n case opt\n when '--host'\n @host = arg\n when '--port'\n @port = arg\n when '--columnns'\n @cols = arg.split(\",\")\n when '--index'\n @index = arg\n when '--type'\n @type = arg\n end\n end\n\n if @index.nil?\n STDERR.puts 'missing argument: --index'\n exit 1\n end\n\n if @type.nil?\n STDERR.puts 'missing argument: --type'\n exit 1\n end\n\n if ARGV.length != 1\n STDERR.puts 'Missing argument: file'\n exit 1\n end\n\n @file = ARGV.shift\nend", "def parse_args( args )\n\toptions = OpenStruct.new\n\toptions.database = Etc.getpwuid( Process.uid ).name\n\toptions.host = '127.0.0.1'\n\toptions.port = 5432\n\toptions.user = Etc.getpwuid( Process.uid ).name\n\toptions.sslmode = 'prefer'\n\toptions.interval = 5\n\n\topts = OptionParser.new do |opts|\n\t\topts.banner = \"Usage: #{$0} [options]\"\n\n\t\topts.separator ''\n\t\topts.separator 'Connection options:'\n\n\t\topts.on( '-d', '--database DBNAME',\n\t\t\t\t\"specify the database to connect to (default: \\\"#{options.database}\\\")\" ) do |db|\n\t\t\toptions.database = db\n\t\tend\n\n\t\topts.on( '-h', '--host HOSTNAME', 'database server host' ) do |host|\n\t\t\toptions.host = host\n\t\tend\n\n\t\topts.on( '-p', '--port PORT', Integer,\n\t\t\t\t\"database server port (default: \\\"#{options.port}\\\")\" ) do |port|\n\t\t\toptions.port = port\n\t\tend\n\n\t\topts.on( '-U', '--user NAME',\n\t\t\t\t\"database user name (default: \\\"#{options.user}\\\")\" ) do |user|\n\t\t\toptions.user = user\n\t\tend\n\n\t\topts.on( '-W', 'force password prompt' ) do |pw|\n\t\t\tprint 'Password: '\n\t\t\tbegin\n\t\t\t\tsystem 'stty -echo'\n\t\t\t\toptions.pass = gets.chomp\n\t\t\tensure\n\t\t\t\tsystem 'stty echo'\n\t\t\t\tputs\n\t\t\tend\n\t\tend\n\n\t\topts.separator ''\n\t\topts.separator 'Other options:'\n\n\t\topts.on_tail( '--help', 'show this help, then exit' ) do\n\t\t\t$stderr.puts opts\n\t\t\texit\n\t\tend\n\n\t\topts.on_tail( '--version', 'output version information, then exit' ) do\n\t\t\tputs SCRIPT_VERSION\n\t\t\texit\n\t\tend\n\tend\n\n\topts.parse!( args )\n\treturn options\nend", "def parse_arguments(args)\n ret = {}\n ret[\"timeout\"] = 15\n op = OptionParser.new do |opts|\n opts.banner = \"Usage: #{__FILE__} [options]\"\n opts.separator \"\"\n opts.separator \"Specific options:\"\n\n opts.on(\"-a\", \"--argument=[JSON]\",\n \"Pass the supplied JSON data over the bridge\") do |v|\n ret[\"argument\"] = v\n end\n\n opts.on(\"-b\", \"--b64argument=[B64-JSON]\",\n \"Pass the base64-encoded JSON data over the bridge\") do |v|\n ret[\"b64argument\"] = v\n end\n\n opts.on(\"-s\", \"--selector=SELECTOR\",\n \"Call the given function (selector) via the bridge\") do |v|\n ret[\"selector\"] = v\n end\n\n opts.on(\"-c\", \"--callUID=UID\",\n \"Use the given UID to properly identify the return value of this call\") do |v|\n ret[\"callUID\"] = v\n end\n\n opts.on(\"-r\", \"--hardwareID=[HARDWAREID]\",\n \"If provided, connect to the physical iOS device with this hardware ID instead of a simulator\") do |v|\n ret[\"hardwareID\"] = v\n end\n\n opts.on(\"-t\", \"--timeout=[TIMEOUT]\",\n \"The timeout in seconds for reading a response from the bridge (default 15)\") do |v|\n ret[\"timeout\"] = v.to_i\n end\n\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n puts opts\n exit\n end\n\n end\n op.parse!(args)\n return ret\nend", "def parse_args(args)\n options = OpenStruct.new\n\n options[:html] = false\n options[:directory] = './'\n options[:ext] = '.jpg'\n\n opt_parser = OptionParser.new do |opts|\n opts.banner = 'Usage: main.rb [options]'\n opts.separator ''\n opts.separator 'Options:'\n\n opts.on('-f', '--filename FILE', 'Filename to write') do |f|\n options[:filename] = f\n end\n\n opts.on('-d', '--directory DIRECTORY', 'Image directory to process') do |d|\n options[:directory] = d\n end\n\n opts.on('--html', 'Output HTML instead of CSV') do\n options[:html] = true\n end\n\n opts.on('-h', '--help', 'Help') do\n puts opts\n exit\n end\n end\n\n begin\n opt_parser.parse(args)\n rescue OptionParser::ParseError\n $stderr.print(\"Argument Error: #{$ERROR_INFO}\\n\")\n exit\n end\n\n # set default filename if not supplied\n unless options[:filename]\n ext = options[:html] ? 'html' : 'csv'\n options[:filename] = \"exif_data_#{Time.now.strftime('%s')}.#{ext}\"\n end\n\n options\n end", "def arguments\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # URL of the DEnCity server that will be posted to\n hostname = OpenStudio::Ruleset::OSArgument::makeStringArgument('hostname', true)\n hostname.setDisplayName('URL of the DEnCity Server')\n hostname.setDefaultValue('http://www.dencity.org')\n args << hostname\n\n # DEnCity server user id at hostname\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id',true)\n user_id.setDisplayName('User ID for DEnCity Server')\n args << user_id\n\n # DEnCIty server user id's password\n auth_code = OpenStudio::Ruleset::OSArgument::makeStringArgument('auth_code', true)\n auth_code.setDisplayName('Authentication code for User ID on DEnCity server')\n args << auth_code\n\n # Building type for DEnCity's metadata\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDisplayName('Building type')\n args << building_type\n\n # HVAC system for DEnCity's metadata\n primary_hvac = OpenStudio::Ruleset::OSArgument::makeStringArgument('primary_hvac', false)\n primary_hvac.setDisplayName('Primary HVAC system in building')\n args << primary_hvac\n\n args\n\n end", "def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # this measure will require arguments, but at this time, they are not known\n geometry_profile = OpenStudio::Ruleset::OSArgument::makeStringArgument('geometry_profile', true)\n geometry_profile.setDefaultValue(\"{}\")\n os_model = OpenStudio::Ruleset::OSArgument::makeStringArgument('os_model', true)\n os_model.setDefaultValue('multi-model mode')\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id', true)\n user_id.setDefaultValue(\"00000000-0000-0000-0000-000000000000\")\n job_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('job_id', true)\n #job_id.setDefaultValue(SecureRandom.uuid.to_s)\n ashrae_climate_zone = OpenStudio::Ruleset::OSArgument::makeStringArgument('ashrae_climate_zone', false)\n ashrae_climate_zone.setDefaultValue(\"-1\")\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDefaultValue(\"BadDefaultType\")\n\n args << geometry_profile\n args << os_model\n args << user_id\n args << job_id\n args << ashrae_climate_zone\n args << building_type\n\n return args\n end", "def parse_args(args)\n options = {\n :console => false,\n :tag => nil\n }\n\n opt_parser = OptionParser.new do |opts|\n opts.banner = \"Usage: #{$0} <input filepath> [options]\"\n\n opts.separator \"\"\n opts.separator \"Data options:\"\n\n opts.on(\"-t T\", String, \"Tag\") do |t|\n options[:tag] = t\n end\n opts.separator \"\"\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n puts opts\n exit\n end\n end\n\n opt_parser.parse!(args)\n options\nend", "def parse(args)\n opts = OptionParser.new\n opts.banner = usage\n\n descriptions.each do |text|\n opts.separator ' ' + text\n end\n\n set_options(opts)\n parse_options(opts, args)\n end", "def parse(args)\n # The options specified on the command line will be collected in\n # *options*.\n\n @options = CLIOptions.new\n @args = OptionParser.new do |parser|\n @options.define_options(parser, help_info)\n parser.parse!(args)\n end\n\n @cdb_path = args.shift\n if @options.debug\n validate_debug!(@options.debug)\n self.file_logger.add_appenders(Logging.appenders.file(@options.debug))\n end\n\n self.logger.level = 4 - @options.verbose\n\n @options\n end", "def parse_args\n options = { :agent_name => 'instance', :verbose => false }\n\n parser = Trollop::Parser.new do\n opt :level, \"\", :type => String, :long => \"--log-level\", :short => \"-l\"\n opt :agent\n opt :verbose\n version \"\"\n end\n\n parse do\n options.merge!(parser.parse)\n if options[:level]\n fail(\"Invalid log level '#{options[:level]}'\") unless AgentManager::LEVELS.include?(options[:level].to_sym)\n end\n options\n end\n end", "def parse_arguments(args = ARGV)\n parser = ArgParser::Parser.new(self.class.args_def)\n result = parser.parse(args)\n # As an arguments definition can change when command arguments are\n # used, and we +collapse+ the arguments for each command into the\n # Definition during parsing, we capture the collapsed Definition\n # and save it on our object instance.\n @args_def = parser.definition\n result\n end", "def parse(args)\n @options = Options.new\n @args = OptionParser.new do |parser|\n @options.define_options(parser)\n begin\n parser.parse!(args)\n rescue OptionParser::InvalidOption => e\n puts e.message\n exit\n end\n end\n @options\n rescue OptionParser::MissingArgument => e\n puts e.message\n exit\n end", "def parse_arguments(args, logger)\n options = OpenStruct.new\n options.api_url = 'http://127.0.0.1:3081'\n logger.level = Logger::INFO\n options.files = []\n\n parser = OptionParser.new do |opts|\n opts.banner = 'Usage: flapjack_configurator [options]'\n\n opts.separator ''\n opts.separator 'Specific options:'\n\n opts.on('-u', '--apiurl URL', String, 'Flapjack API URL') do |url|\n options.api_url = url\n logger.debug(\"API URL set to #{url}\")\n end\n\n opts.on('-v', '--verbosity [level]', Integer, \"Set Verbosity, level corresponds to Ruby logger levels (#{Logger::DEBUG}: debug, #{Logger::FATAL}: fatal)\") do |level|\n if level\n logger.level = level\n else\n logger.level -= 1 if logger.level > 0\n end\n logger.debug('Log level set to #{logger.level}')\n end\n\n opts.on('-f', '--files file1,file2,file3', Array, 'List of YAML config files to load, increasing precidence') do |files|\n options.files += files\n end\n\n opts.on_tail('-h', '--help', 'Show this message') do\n puts opts\n exit\n end\n\n opts.on_tail('--version', 'Show version') do\n puts \"Flapjack Configurator #{Gem.loaded_specs['flapjack_configurator'].version}\"\n exit\n end\n end\n\n parser.parse!(args)\n\n if options.files.length < 1\n logger.fatal('Option --files is required')\n exit\n end\n\n return options\nend", "def parse_cmd_arguments( args ) # {{{\n\n original_args = args.dup\n options = OpenStruct.new\n\n # Define default options\n options.verbose = false\n options.colorize = false\n options.process = []\n options.sources = []\n options.debug = false\n options.db_path = \"data/databases/test.sqlite3\"\n options.db_type = \"sqlite3\"\n options.read = false\n options.automatic = false\n options.interval = 3600 # update normally only every hour\n options.rate = false\n options.username = \"\"\n options.manual_input = false\n options.joke_count = false\n options.random_intervals = false\n options.random_interval_time = 25\n\n pristine_options = options.dup\n\n opts = OptionParser.new do |opts|\n opts.banner = \"Usage: #{__FILE__.to_s} [options]\"\n\n opts.separator \"\"\n opts.separator \"General options:\"\n\n opts.on(\"-d\", \"--db-path PATH\", \"Use the database which can be found in PATH\") do |d|\n options.db_path = d\n end\n\n opts.on(\"-t\", \"--db-type TYPE\", \"Use the database of class TYPE (e.g. sqlite3)\") do |t|\n options.db_type = t\n end\n\n opts.on(\"-r\", \"--read\", \"Read jokes that are stored in the DB\") do |r|\n options.read = r\n end\n\n opts.on(\"-r\", \"--rate\", \"Rate jokes that are stored in the DB for user account\") do |r|\n options.rate = r\n end\n\n opts.on(\"-u\", \"--username OPT\", \"Use username OPT\") do |u|\n options.username = u\n end\n\n opts.on(\"-m\", \"--manual-input\", \"Input a joke manually to the Database\") do |m|\n options.manual_input = m\n end\n\n opts.on(\"-j\", \"--joke-count\", \"Count how many jokes we have in the Database\") do |j|\n options.joke_count = j\n end\n\n opts.on(\"-r\", \"--random-intervals\", \"Use random intervals when downloading to mask our usage pattern\") do |r|\n options.random_intervals = r\n end\n\n opts.separator \"\"\n opts.separator \"Specific options:\"\n\n # Boolean switch.\n opts.on(\"-a\", \"--automatic\", \"Run automatically every #{options.interval.to_s} seconds unless the --interval option is given\") do |a|\n options.automatic = a\n end\n\n opts.on(\"-i\", \"--interval OPT\", \"Run every OPT seconds (works only with --automatic together)\") do |i|\n options.interval = i.to_i\n end\n\n # Set of arguments\n opts.on(\"-p\", \"--process OPT\", @configurations, \"Process one or more detected configuration (OPT: #{ @configurations.sort.join(', ') })\" ) do |d|\n options.process << d\n end\n\n # Set of arguments\n opts.on(\"-s\", \"--sources OPT\", @configurations, \"Use only these sources for read and rate (OPT: #{ @configurations.sort.join(', ') })\" ) do |d|\n options.sources << d\n end\n\n # Boolean switch.\n opts.on(\"-v\", \"--verbose\", \"Run verbosely\") do |v|\n options.verbose = v\n end\n\n opts.on(\"-d\", \"--debug\", \"Run in debug mode\") do |d|\n options.debug = d\n end\n\n # Boolean switch.\n opts.on(\"-q\", \"--quiet\", \"Run quietly, don't output much\") do |v|\n options.verbose = v\n end\n\n opts.separator \"\"\n opts.separator \"Common options:\"\n\n # Boolean switch.\n opts.on(\"-c\", \"--colorize\", \"Colorizes the output of the script for easier reading\") do |c|\n options.colorize = c\n end\n\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n puts opts\n exit\n end\n\n # Another typical switch to print the version.\n opts.on_tail(\"--version\", \"Show version\") do\n puts `git describe --tags`\n exit\n end\n end\n\n opts.parse!(args)\n\n # Show opts if we have no cmd arguments\n if( original_args.empty? )\n puts opts\n exit\n end\n\n options\n end", "def parse_options(args)\n args.each do |arg|\n case arg\n when '-h', '--help' then @opts[:help] = true\n when '-un', '--user' then @opts[:user] = args.next(arg)\n when '-pw', '--pass' then @opts[:pass] = args.next(arg)\n when '-t', '--token' then @opts[:token] = args.next(arg)\n when '-g', '--get' then @opts[:get] = args.next(arg)\n when '-d', '--debug' then @opts[:debug] = true\n when '-r', '--random' then @opts[:get] = nil\n else next\n end\n end\n end", "def initialize(args)\n @args = args\n @options = OpenStruct.new\n\n parse\n validate\n end", "def parse(args)\n rest = args.clone\n rest.delete_at(0)\n return args[0], rest\n end", "def parse_args\n { :ip => ARGV[1] || '0.0.0.0', :port => (ARGV[0] || '9000').to_i,\n :logging => !(ENV['DEBUG'] &&\n ['0', 'no', 'false'].include?(ENV['DEBUG'].downcase)) }\nend", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # url of the city database\n city_db_url = OpenStudio::Measure::OSArgument.makeStringArgument('city_db_url', true)\n city_db_url.setDisplayName('City Database Url')\n city_db_url.setDescription('Url of the City Database')\n city_db_url.setDefaultValue('')\n args << city_db_url\n\n # project id to update\n project_id = OpenStudio::Measure::OSArgument.makeStringArgument('project_id', true)\n project_id.setDisplayName('Project ID')\n project_id.setDescription('Project ID to generate reports for.')\n project_id.setDefaultValue('0')\n args << project_id\n\n # datapoint id to update\n datapoint_id = OpenStudio::Measure::OSArgument.makeStringArgument('datapoint_id', true)\n datapoint_id.setDisplayName('Datapoint ID')\n datapoint_id.setDescription('Datapoint ID to generate reports for.')\n datapoint_id.setDefaultValue('0')\n args << datapoint_id\n\n return args\n end", "def parse_args\n opt = {}\n opt_parser = OptionParser.new do |opts|\n opts.banner = \"Usage: testLogin.rb [options]\"\n opts.separator('')\n opts.on('-b', '--browser [BROWSER]', \"Default is Chrome\") do |driver|\n opt[:browser] = driver\n end\n opts.on('-v', '--version [BUILDNO]', 'CODAP build number (build_0xxx). Default is latest') do |build|\n opt[:version] = build\n end\n opts.on('-r', '--root_dir [ROOTDIR]', 'Root directory of CODAP. Default is localhost:4020/dg') do |root|\n opt[:root]=root\n end\n opts.on('-t', '--trials [NUMBER OF TRIALS]') do |num_trials|\n opt[:num_trials]=num_trials\n end\n opts.on('-c', '--cases [NUMBER OF CASES]') do |cases|\n opt[:num_cases]=cases\n end\n opts.on('-d', '--delay [DELAY BETWEEN TRIALS (ms)]') do |delay|\n opt[:delay]=delay\n end\n opts.on('-f', '--filename [FILENAME where to save results]','Must be specified if writing to a new file') do |filename|\n opt[:filename]=filename\n end\n opts.on('-p', '--path [PATH where to save results, do not include home in path]') do |path|\n opt[:path]=path\n end\n opts.on('-s', '--sleep [SLEEP time between runs (s)]') do |sleep_time|\n opt[:sleep_time]=sleep_time\n end\n opts.on('-w', '--[no-]write [WRITE]', 'write to a new file-> must specify filename, default is append (no-write). If no file name is specified, results will be appended.') do |write|\n opt[:write]=write\n end\n\n end\n opt_parser.parse!(ARGV)\n return opt\nend", "def parse_arguments(args)\n Trollop::with_standard_exception_handling argument_parser do\n if args.empty? || args.include?('-h') || args.include?('--help')\n raise Trollop::HelpNeeded\n elsif args.include?('--examples')\n print_examples\n end\n argument_parser.parse args\n end\n end", "def parse(args)\r\n full_args_str = args.to_s\r\n args_list = _trim_end_caps(full_args_str)\r\n args_arr = []\r\n\r\n loop do\r\n match = false\r\n ARGUMENT_REGEXP.match(args_list) do |match_context|\r\n match = true\r\n args_arr << _unescape_arg(match_context[:first_arg])\r\n if match_context[:other_args]\r\n args_list = match_context[:other_args]\r\n else\r\n return args_arr\r\n end\r\n end\r\n\r\n fail unless match\r\n end\r\n end", "def args_from_node(args_node); end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def parse_args(args)\n options = {\n :excount => 5,\n :testdata => nil,\n :console => false,\n :raw => false,\n :pronounciation_offset => 1,\n :definition_offset => 2,\n :url => \"m\"\n }\n\n opt_parser = OptionParser.new do |opts|\n opts.banner = \"Usage: #{$0} <input filepath> [options]\"\n\n opts.separator \"\"\n opts.separator \"Data options:\"\n opts.on(\"-p N\", Integer, \"Offset to pronunciation column, default 1\") do |n|\n options[:pronounciation_offset] = n\n end\n opts.on(\"-d N\", Integer, \"Offset to definition column, default 2\") do |n|\n options[:definition_offset] = n\n end\n opts.on(\"-n N\", Integer, \"Number of example sentences, default 5\") do |n|\n options[:excount] = n\n end\n opts.on(\"-u U\", String, \"Source url (#{WWWJDICExampleProvider::SOURCES.to_s}), default #{options[:url]}\") do |u|\n options[:url] = u\n end\n\n opts.separator \"\"\n opts.separator \"Testing:\"\n opts.on(\"-t\", \"--testdata [DATAFILE]\",\n \"Path to yaml data file of examples (useful for testing)\") do |d|\n options[:testdata] = d\n end\n\n opts.separator \"\"\n opts.separator \"Output:\"\n opts.on(\"-c\", \"--console\", \"Dump to console only\") do |c|\n options[:console] = c\n end\n opts.on(\"-r\", \"--raw\", \"Output raw data (all examples)\") do |c|\n options[:raw] = c\n end\n\n opts.separator \"\"\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n puts opts\n exit\n end\n end\n\n opt_parser.parse!(args)\n options\nend", "def parse_command_line(args)\n all_opts = OptionParser.new do |opts|\n opts.banner = \"Usage: #{PROGRAM_NAME} [OPTIONS] PASSWORD\"\n opts.separator ''\n\n opts.on(\n '-t',\n '--load-timeout [TIMEOUT_SECONDS]',\n Integer,\n 'Timeout in seconds to wait for',\n 'gitlab-rails console to load',\n 'and process the change.',\n \"Defaults to #{DEFAULT_LOAD_TIMEOUT} seconds.\"\n ) do |timeout|\n @options.load_timeout = timeout\n end\n\n opts.on(\n '-v',\n '--verbose',\n 'Print out debug info when processing.'\n ) do\n @options.debug = true\n end\n\n opts.on(\n '-h',\n '--help',\n 'Help Message'\n ) do\n puts opts\n @options.help_requested = true\n end\n end\n\n all_opts.parse!(args)\n\n unless @options.help_requested\n fail('ERROR: You must specify the password to set') if (ARGV.length < 1)\n\n @options.password = ARGV[0]\n fail('ERROR: Password cannot be empty') if @options.password.strip.empty?\n end\n end", "def parse_args\n require 'optimist'\n opts = Optimist.options do\n opt :source, \"Inventory Source UID\", :type => :string, :required => ENV[\"SOURCE_UID\"].nil?, :default => ENV[\"SOURCE_UID\"]\n opt :ingress_api, \"Hostname of the ingress-api route\", :type => :string, :default => ENV[\"INGRESS_API\"] || \"http://localhost:9292\"\n opt :config, \"Configuration file name\", :type => :string, :default => ENV[\"CONFIG\"] || \"default\"\n opt :data, \"Amount & custom values of generated items\", :type => :string, :default => ENV[\"DATA\"] || \"default\"\n end\n\n opts\nend", "def parse_args\n @args.extend OptionParser::Arguable\n opts = @args.getopts('cdDi:lm:n:o:s:St:uvVz')\n @nsocks = opts['s'] ? opts['s'].to_i : 1\n @max_idle = opts['i'] ? opts['i'].to_i : DEFAULT_MAX_IDLE\n @max_use = opts['m'] ? opts['m'].to_i : DEFAULT_MAX_USE\n $VERBOSE = true if opts['v']\n end", "def parse(args)\n @cmd_opts = Options.new\n @args = OptionParser.new do |parser|\n @cmd_opts.define_options(parser)\n parser.parse!(args)\n\n # take care of positional arguments\n raise OptionParser::MissingArgument, \"Both srcdir and dstdir must be provided!\" unless args.count == 2\n\n # we always work with absolute paths\n @cmd_opts.srcdir, @cmd_opts.dstdir = [args[0], args[1]].collect do |arg|\n d = Pathname.new(arg)\n d = Pathname.new(Dir.pwd) / d unless d.absolute?\n d.cleanpath\n end\n\n validate_options(@cmd_opts)\n end\n @cmd_opts\n end", "def parse(args)\n actions,urls,queries,styles = [],[],[],[]\n \n OptionParser.new do |opts|\n opts.banner = \"Usage: rubium.rb [options]\"\n \n opts.on(\"-u x,y,z\", \"--[no-]url x,y,z\",\n Array, \"Comma delimited URL strings for which to navigate to\") { |u| urls = u }\n \n opts.on(\"-q x,y,z\", \"--[no-]query x,y,z\",\n Array, \"Comma delimited query strings specifying the DOM node to inspect\") { |q| queries = q }\n \n opts.on(\"-s x,y,z\", \"--[no-]style x,y,z\",\n Array, \"Comma delimited strings with the CSS style in inspect\") { |s| styles = s }\n\n opts.on_tail(\"-v\", \"--version\", \"Show version\") do\n puts \"@1321\"\n exit\n end\n \n end.parse!\n \n urls.each do |url|\n queries.each do |query|\n styles.each do |style|\n actions.push( @ref.new(url,query,style) )\n end\n end\n end\n \n return actions\n end", "def parse(args)\n # The options specified on the command line will be collected in\n # *options*.\n @options = ScriptOptions.new\n\n @args = OptionParser.new do |parser|\n @options.define_options(parser)\n parser.parse!(args)\n end\n\n @options\n end", "def parse(args)\n arg_list = arg_groups(args)\n options = DEFAULT_OPTIONS.dup\n options[:exclude] += default_excludes\n options[:locations] = arg_list.shift\n\n arg_list.reject(&:empty?).each do |set|\n flag, *args = set\n args.map! { |arg| arg.delete(\"/\") } # \"log/\" => \"log\"\n\n case flag\n when '-f', '--flags' then options[:flags] += args\n when '-e', '--exclude' then options[:exclude] += args\n else puts \"Unknown argument: #{flag}\"\n end\n end\n\n options\n end", "def parse_command_line_args(args)\n opts = OptionParser.new do |opts|\n opts.banner = 'Usage: tbibtools [OPTIONS] [FILES] < IN > OUT'\n opts.separator ''\n opts.separator 'tbibtools is a free software with ABSOLUTELY NO WARRANTY under'\n opts.separator 'the terms of the GNU General Public License version 2 or newer.'\n opts.separator ''\n \n opts.on('-c', '--config=FILE', String, 'Configuration file') do |value|\n @configuration.config value\n end\n\n opts.on('-e', '--regexp=REGEXP', String, 'Display entries matching the regexp') do |value|\n @configuration.filter Regexp.new(value)\n end\n\n opts.on('-f', '--format=STRING', String, 'Re-format entries (order matters)') do |value|\n @configuration.format *value.split(/,/)\n end\n\n opts.on('--[no-]formatted', 'Unformatted output') do |bool|\n unless bool\n @configuration.entry_format = []\n @configuration.entry_format_default = []\n end\n end\n\n opts.on('-i', '--[no-]case-sensitive', 'Case insensitive') do |bool|\n @configuration.sort_case bool\n end\n \n opts.on('-l', '--format-list=[STRING]', String, 'Format string for list (implies --ls)') do |value|\n @configuration.shortcut_ls\n @configuration.list_format value if value\n end\n\n opts.on('--ls', 'Synonym for: -f list,stripPrelude (\"list\" implies \"unwrap\")') do |bool|\n @configuration.shortcut_ls if bool\n end\n\n opts.on('-o', '--output=FILE', String, 'Output file') do |value|\n @configuration.output value\n end\n\n opts.on('-P', '--strip-prelude', 'Strip the prelude: same as -f stripPrelude but helps to maintain the original formatting') do |bool|\n @configuration.strip_prelude\n end\n\n opts.on('-q', '--query=FIELD=REGEXP', String, 'Show entries for which field matches the regexp') do |value|\n field, rx = value.split(/=/, 2)\n @configuration.query field => Regexp.new(rx, Regexp::IGNORECASE)\n end\n\n opts.on('-s', '--sort=STRING', String, 'Sort (default: sort by key; key = _id, type = _type)') do |value|\n @configuration.sort_key value\n end\n\n opts.on('-S', '--[no-]expand-strings', 'Replace/expand strings') do |bool|\n @configuration.expand_strings bool\n end\n\n opts.on('--strip=FIELDS', String, 'Ignore/strip fields') do |value|\n @configuration.strip value.split(/,/)\n end\n\n opts.on('-u', '--unsorted', 'Unsorted output') do |bool|\n @configuration.sort_key nil\n end\n\n opts.separator ''\n opts.separator 'Other Options:'\n \n opts.on('--debug', Integer, 'Show debug messages') do |v|\n $DEBUG = true\n $VERBOSE = true\n end\n \n opts.on('-v', '--verbose', 'Run verbosely') do |v|\n $VERBOSE = true\n end\n \n opts.on('-h', '--help', 'Show this message') do\n puts opts\n exit 1\n end\n\n opts.separator ''\n opts.separator 'Available formats:'\n format_rx = /^(format|preprocess|head|body|tail)_/\n format_names = (['nnIsYear', 'sortCrossref', 'downcaseType', 'upcaseType'] + \n @configuration.methods.find_all{|m| m =~ format_rx}.collect{|m| m.sub(format_rx, '')}).uniq.sort.join(', ')\n opts.separator format_names\n\n opts.separator ''\n opts.separator 'Known format shortcuts:'\n acc = []\n @configuration.methods.find_all{|m| m =~ /^shortcut_/}.sort.each do |meth|\n fn = meth.sub(/^shortcut_/, '')\n fs = @configuration.send(meth, acc)\n opts.separator \"#{fn}: #{fs.join(',')}\"\n end\n end\n @configuration.input *opts.parse!(args)\n self\n end", "def parse_options(args)\n options = OpenStruct.new\n options.br = \"\"\n options.reset = false\n options.stash = false\n options.verb = false\n\n opt_parser = OptionParser.new do | opts |\n opts.banner = \"Usage: git-checkout.rb --br BranchName [options]\"\n opts.separator \"\"\n opts.separator \"Specific options:\"\n\n\t opts.on(\"--br BranchName\", String, \"Branch name\") do | name |\n options.br = name\n end\n\n\t opts.on(\"--reset\", \"Reset hard to origin/Branch/HEAD\") do\n options.reset = true\n end\n\n\t opts.on(\"--stash\", \"Auto stash uncommited changes\") do\n options.stash = true\n end\n\n opts.on(\"--verb\", \"Output trivial information\") do\n options.verb = true\n end\n end\n\n opt_parser.parse!(args)\n options\nend", "def parse_arguments\n @cmd_line_arguments = {}\n\n @options = OptionParser.new do |opt|\n opt.on('-C', '--change-dir DIR', 'Change working directory to DIR') do |directory|\n @cmd_line_arguments[:working_directory] = directory\n end\n\n opt.on('-d', '--debug', 'Debug mode') do\n @cmd_line_arguments[:debug] = true\n end\n\n opt.on('-e', '--environment NAME', 'set environment to NAME') do |environment|\n @cmd_line_arguments[:environment] = environment\n end\n\n opt.on('-G', '--generate-json', 'Generate json files, which are commited to api') do\n @cmd_line_arguments[:generate_json_file] = true\n @cmd_line_arguments[:action] ||= :generate\n end\n\n opt.on('--generate-report', 'Generate report csv in output directory') do\n @cmd_line_arguments[:generate_report] = true\n end\n\n opt.on('-g', '--group NAME[,NAME]', Array, 'set groups') do |groups|\n @cmd_line_arguments[:groups] ||= []\n @cmd_line_arguments[:groups] += groups\n end\n\n opt.on('-j', '--job JOB[,JOB,...]', Array, 'Limit action to JOB, which is a regexpression') do |jobs|\n @selected_jobs += jobs\n end\n\n opt.on('-l', '--list', 'List available jobs') do\n @cmd_line_arguments[:action] = :list\n end\n\n opt.on('-p', '--project NAME', 'set project') do |project|\n @cmd_line_arguments[:project] = project\n end\n\n opt.on('-o', '--output-directory DIR', 'generate json file into DIR directory', 'default: ' + @config.output_directory) do |directory|\n @cmd_line_arguments[:output_directory] = directory\n end\n\n opt.on('-q', '--quiet', 'be quiet') do\n @cmd_line_arguments[:quiet] = true\n end\n\n opt.on('-r', '--run', 'Run all configured jobs or all jobs passed with -j') do\n @cmd_line_arguments[:action] = :run\n end\n\n opt.on('-R', '--report', 'show report') do\n @cmd_line_arguments[:report] = true\n end\n\n opt.on('-s', '--save-response', 'save respone in output directory') do\n @cmd_line_arguments[:save_response] = true\n end\n\n opt.separator \"\n\n Examples:\n # List all available jobs\n #{File.basename $0} -l\n\n # List all available jobs in a specific directory\n #{File.basename $0} -C api-helper -p LISU -l\n\n # Run all configured jobs\n #{File.basename $0} -r\n\n # Run all configured jobs and show a report\n #{File.basename $0} -r --report\n\n # Run all configured jobs in a specific directory\n #{File.basename $0} -C api-helper -p LISU -r\n\n # Run Job_A and Job_B, which must configured in project.yml or group.yml\n #{File.basename $0} -r -j Job_A -j Job_B\n\n # Run all Jobs, which beginn with JOB\n #{File.basename $0} -r -j JOB.*\n\n # Run all Jobs, which contains with JOB\n #{File.basename $0} -r -j .*JOB.*\n\n # Generate json files, which are going to be requested, for all configured jobs\n #{File.basename $0} -G\n\n # Generate json file, which are going to be requested, for Job_A\n #{File.basename $0} -G -j Job_A\n\n # Run jobs for delti group and generate json files\n #{File.basename $0} -r -G -g delti\n\n Available template macros:\n\n Variables and Responses:\n response('<job_name>', '<name>') - return value from the response of a job (see examples)\n response('<job_name>', - return value from the response of a job in another group (must be run before)\n '<name>',\n group: '<group_name>')\n var('<name>', - return variable defined in Job in Vars section.\n default: nil, when default is set (not nil) and variable is undefined, return default\n ignore_error: false) when variable is undefined, do not throw an error\n\n Date and Time:\n now() - returns today (now) in seconds\n yesterday() - returns yesterday in iso8601\n time([<day_shift>[, format: <format>]]) - returns time in specificied format\n defaults: day_shift = 0, format = :seconds\n format:\n :seconds : return time in seconds\n :iso8601 : return timestamp in iso8601\n :iso8601utc : return timestamp in iso8601 (utc)\n\n Examples:\n # get variable test\n var('test')\n\n # get value pdfToken from register response\n response('Delti_Create_DE', 'pdfToken')\n\n # get value pdfToken from register response, where job name is defined as variable in cancel job\n response(var('CreateJob'), 'pdfToken')\n\n # get value token from GenerateToken response in group auth\n response('GenerateToken', 'token', group: 'auth')\n\n # return time of today in seconds\n time()\n\n # return timestamp of today in iso8601\n time(format: :iso8601)\n\n # return timestamp of yesterday in iso8601\n time(-1, format: :iso8601)\n\n # return timestamp of last year in iso8601\n time(-365, format: :iso8601)\n\n # return timestamp of tomorrow in iso8601\n time(1, format: :iso8601)\n\n # return credential\n credential('PROJECT_NAME_username')\n\n # return basic auth header value\n basicauth('PROJECT_NAME_username', 'PROJECT_NAME_password')\n \"\n end\n @options.parse!\n\n @config.insert 0, '<command_line>', @cmd_line_arguments\n\n unless File.directory?(@config.output_directory)\n Dir.mkdir @config.output_directory\n end\n\n Dir.chdir @config.working_directory\n end", "def parse_args(args)\n opts = {}\n args.each do |(k, v)|\n if v.index('name=') == 0\n parts = v.split('=')\n opts[:names] ||= []\n opts[:names] << parts.last\n elsif v.include?('=')\n parts = v.split('=')\n opts[parts.first.to_sym] = parts.last\n elsif k != :suite\n opts[v.to_sym] = true\n end\n end\n opts\n end", "def process_arguments( *args )\n @options = {}\n @username = ENV['USER'] || ENV['USERNAME']\n\n raise ArgumentError,\n \"you must specify the host to connect to\" if args.length < 1\n\n @host = args.shift\n\n # support for both named arguments, and positional arguments...\n if args.length == 1 && args[0].is_a?( Hash ) &&\n ( args[0][:username] || args[0][:password] ||\n args[0][:port] || args[0][:options] )\n # then\n @username = args[0][:username] || @username\n @password = args[0][:password]\n\n @options.update args.shift\n else\n @options[ :port ] = args.shift if args.first.is_a? Numeric\n if args.first.nil? || args.first.is_a?( String )\n @username = args.shift || @username\n end\n if args.first.nil? || args.first.is_a?( String )\n @password = args.shift\n end\n @options.update args.shift if args.first.is_a?( Hash )\n end\n\n if !args.empty?\n raise ArgumentError, \"extra parameters detected: #{args.inspect}\"\n elsif @username.nil?\n raise ArgumentError, \"no username was given and none could be inferred from the environment\"\n end\n\n @keys = @options[ :keys ]\n @host_keys = @options[ :host_keys ]\n @auth_methods = @options[ :auth_methods ]\n @forward_agent = @options[ :forward_agent ] || false\n @crypto_backend = @options.fetch( :crypto_backend, :ossl )\n @host_key_verifier = host_key_verifier_from(@options.fetch(:paranoid, true))\n\n verbose = @options.fetch( :verbose, :warn )\n log = @options.fetch( :log, STDERR )\n\n @registry_options = @options.fetch( :registry_options, {} )\n\n @registry_options[ :logs ] ||= {}\n @registry_options[ :logs ][ :default_level ] = verbose\n\n if log.is_a? IO\n @registry_options[ :logs ][ :device ] ||= log\n else\n @registry_options[ :logs ][ :filename ] ||= log\n end\n\n @registry = @options[ :container ] ||\n Needle::Registry.new( @registry_options )\n\n [ :keys, :host_keys, :auth_methods, :username, :password,\n :crypto_backend, :registry_options, :container, :log, :verbose,\n :forward_agent, :paranoid\n ].each do |i|\n @options.delete i\n end\n\n @options.freeze\n end", "def parse_args\n parser = Trollop::Parser.new do\n opt :list\n opt :add, \"\", :type => :string\n opt :remove, \"\", :type => :string\n opt :query, \"\", :type => :strings\n opt :verbose\n opt :die, \"\", :short => \"-e\"\n opt :format, \"\", :type => :string, :default => \"json\"\n opt :timeout, \"\", :type => :int, :default => TAG_REQUEST_TIMEOUT\n version \"\"\n end\n\n parse do\n options = parser.parse\n options[:action] = :get_tags if options.delete(:list)\n if options[:add]\n options[:action] = :add_tag\n options[:tag] = options.delete(:add).strip\n raise ::Trollop::CommandlineError.new(\"Non-empty value required\") if options[:tag].empty?\n end\n if options[:remove]\n options[:action] = :remove_tag\n options[:tag] = options.delete(:remove).strip\n raise ::Trollop::CommandlineError.new(\"Non-empty value required\") if options[:tag].empty?\n end\n if options[:query]\n options[:action] = :query_tags\n options[:tags] = options.delete(:query).map { |tag| tag.strip }\n end\n options[:format] = parse_format(options[:format])\n options\n end\n end", "def parse_args(args)\n result = {}\n args.each do |arg|\n pair = arg.split(\"=\")\n result[pair[0]]=pair[1]\n end\n result\n end", "def get_options(args)\n options = DEFAULT_OPTIONS\n status = 0\n\n parser = OptionParser.new do |opts|\n opts.banner = \"Usage: #{$0} proxy [options]\"\n opts.separator \"\"\n opts.separator \"Specific options:\"\n\n opts.on(\"-h\", \"--host\", \"=IP_ADDRESS\", \"IP address to listen on. Default: binds to all IP addresses of the computer\") do |arg|\n options[:host] = arg\n end\n\n opts.on(\"-p\", \"--port\", \"=PORT_NUMBER\", Integer, \"TCP port to listen on. Default port: #{DatabaseProxy::DEFAULT_PORT}\") do |arg|\n options[:port] = arg\n end\n\n opts.on(\"-k\", \"--key\", \"=FILE\", \"File containing the SSL private key\") do |arg|\n options[:key] = arg\n end\n\n opts.on(\"-c\", \"--certificate\", \"=FILE\", \"File containing the SSL certificate\") do |arg|\n options[:certificate] = arg\n end\n \n opts.on_tail(\"--help\", \"Show this message\") do\n $stderr.puts opts\n options = nil\n end\n end\n\n begin\n parser.parse!(args)\n rescue Exception => e\n $stderr.puts \"Command line parsing failed: #{e}\"\n $stderr.puts parser.help\n options = nil\n status = 1\n end\n \n return options, status\n end", "def parse_options(args)\n @options = OpenStruct.new\n @options.emacs = !args.delete('--emacs').nil?\n @options.wrap = !args.delete('--wrap').nil?\n @options.inner = !args.delete('--inner').nil?\n @options.jruby = !args.delete('--jruby').nil?\n @options.nojruby = !args.delete('--nojruby').nil?\n @options.action = args[0] || nil\n @options.path = args[1] || File.basename(Dir.pwd + '.rb')\n @options.args = args[2..-1] || []\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make an argument for the variable name\n variable_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable_name', true)\n variable_name.setDisplayName('Enter Variable Name.')\n variable_name.setDescription('Valid values can be found in the eplusout.rdd file after a simulation is run.')\n args << variable_name\n\n # make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency.')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n # make an argument for the key_value\n key_value = OpenStudio::Measure::OSArgument.makeStringArgument('key_value', true)\n key_value.setDisplayName('Enter Key Name.')\n key_value.setDescription('Enter * for all objects or the full name of a specific object to.')\n key_value.setDefaultValue('*')\n args << key_value\n\n env = OpenStudio::Measure::OSArgument.makeStringArgument('env', true)\n env.setDisplayName('availableEnvPeriods')\n env.setDescription('availableEnvPeriods')\n env.setDefaultValue('RUN PERIOD 1')\n args << env\n\n args\n end", "def parse_args\n args = {\n :stack_name => nil,\n :parameters => {},\n :interactive => false,\n :region => default_region,\n :profile => nil,\n :nopretty => false,\n :s3_bucket => nil,\n }\n ARGV.slice_before(/^--/).each do |name, value|\n case name\n when '--stack-name'\n args[:stack_name] = value\n when '--parameters'\n args[:parameters] = Hash[value.split(/;/).map { |pair| parts = pair.split(/=/, 2); [ parts[0], Parameter.new(parts[1]) ] }]\n when '--interactive'\n args[:interactive] = true\n when '--region'\n args[:region] = value\n when '--profile'\n args[:profile] = value\n when '--nopretty'\n args[:nopretty] = true\n when '--s3-bucket'\n args[:s3_bucket] = value\n end\n end\n\n args\nend", "def parse_args\n doc = <<DOCOPT\nschwifty saves and downloads objects from ipfs, keeping track of their hashes in a garbage collection file in ~/.ipfs/ipfs_pinned_objects.yaml and an objects file in ./ipfs_objects.yaml\n\nUsage:\n schwifty add <files>...\n schwifty bootstrap (--clear | <nodes>... | --file=<bootstrap_list_yaml>)\n schwifty get <files_or_hashes>...\n schwifty gc\n schwifty -h | --help\n schwifty --version\n\nOptions:\n -h --help Show this screen.\n --version Show version.\nDOCOPT\n begin\n Docopt.docopt(doc)\n rescue Docopt::Exit => e\n puts e.message\n exit\n end\n end", "def parseOptions(args)\n require 'optparse'\n\n cfgFile = nil\n @interactive = false\n @logConfigFile = ENV['RES_MGR_LOG'] || \"/etc/omf-resmgr-#{OMF_MM_VERSION}/omf-resmgr_log.xml\"\n\n opts = OptionParser.new\n opts.banner = \"Usage: omf-resmgr [options]\"\n @config = {:communicator => {}, :manager => {}}\n @config[:communicator] = {:xmpp => {}}\n\n opts.on(\"--pubsub-gateway HOST\",\n \"Hostname of the local PubSub server to connect to\") {|name|\n @config[:communicator][:xmpp][:pubsub_gateway] = name\n }\n opts.on(\"--pubsub-user NAME\",\n \"Username for connecting to the local PubSub server (if not set, RM \"+\n \"will register its own new user)\") {|name|\n @config[:communicator][:xmpp][:pubsub_user] = name\n }\n opts.on(\"--pubsub-pwd PWD\",\n \"Password for connecting to the local PubSub server (if not set, RM \"+\n \"will register its own new user)\") {|name|\n @config[:communicator][:xmpp][:pubsub_pwd] = name\n }\n \n # Instance Options\n opts.on('--name NAME',\n \"Checkin name of the manager (unique HRN for this resource)\") {|name|\n @config[:manager][:name] = name\n }\n\n # Signing/Verification Options\n opts.on(\"-p\", \"--private_key FILE\", \"Set your RSA/DSA SSH private key file location\") { |file| \n @config[:communicator][:private_key] = file \n }\n opts.on(\"-P\", \"--public_key_dir DIRECTORY\", \"Set the directory holding the public keys of your OMF peers\") { |dir| \n @config[:communicator][:public_key_dir] = dir \n } \n opts.on(\"-a\", \"--auth YES|NO\", \"Enable or disable signature checks and message signing (default is no)\") { |auth|\n @config[:communicator][:authenticate_messages] = (auth.downcase == \"yes\") \n }\n\n # General Options\n opts.on(\"-i\", \"--interactive\",\n \"Run the manager in interactive mode\") {\n @interactive = true\n }\n opts.on(\"--log FILE\",\n \"File containing logging configuration information\") {|file|\n @logConfigFile = file\n }\n opts.on(\"-n\", \"--just-print\",\n \"Print the commands that would be executed, but do not execute them\") {\n ResourceManager.JUST_PRINT = true\n }\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") { puts opts; exit }\n opts.on_tail(\"-v\", \"--version\", \"Show the version\") {\n puts VERSION_STRING\n exit\n }\n\n rest = opts.parse(args)\n\n # Make sure log exists ...\n @logConfigFile = File.exists?(@logConfigFile) ? @logConfigFile : nil\n MObject.initLog('resourceManager', nil, {:configFile => @logConfigFile})\n\n # Read config file\n if cfgFile.nil?\n name = \"omf-resmgr.yaml\"\n path = [\"../etc/omf-resmgr/#{name}\", \"/etc/omf-resmgr-#{OMF_MM_VERSION}/#{name}\"]\n cfgFile = path.detect {|f|\n File.readable?(f)\n }\n else\n if (!File.readable?(cfgFile))\n raise \"Can't find configuration file '#{cfgFile}'\"\n end\n end\n if (cfgFile.nil?)\n raise \"Can't find a configuration file\"\n else\n require 'yaml'\n h = YAML::load_file(cfgFile)\n if ((p = h[:rmanager]) == nil)\n raise \"Missing ':rmanager' root in '#{cfgFile}'\"\n end\n @config = p.merge_deep!(@config)\n end\n\n # At this point, we should now have a name \n if @config[:manager][:name] == nil \n raise \"Manager's Name is not defined in config file or as arguments!\"\n else\n # substitute hostname or mac address, if required\n @config[:manager][:name].gsub!(/%hostname%/, `/bin/hostname`.chomp)\n @config[:manager][:name].gsub!(/%macaddr%/, `ifconfig control | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'`)\n @managerName = @config[:manager][:name] \n end\n \n kl = nil\n if @config[:communicator][:authenticate_messages]\n MObject.info(\"Message authentication is enabled\")\n if @config[:communicator][:private_key] == nil\n error \"No private key file specified on command line or config file! Exiting now!\\n\"\n\t exit\n end\n if @config[:communicator][:public_key_dir] == nil\n error \"No public key directory specified on command line or config file! Exiting now!\\n\"\n\t exit\n end\n kl = KeyLocator.new(@config[:communicator][:private_key], @config[:communicator][:public_key_dir])\n else\n MObject.info(\"Message authentication is disabled\")\n end\n\n ## TODO: initialize message envelope here with kl and authenticate_messages\n \n end", "def process_args\n if has_directory?\n @directory_to_parse = @args[0]\n else\n @files = @args[0...@args.count-3]\n @owner = @args[@args.count-3]\n @repo = @args[@args.count-2]\n @token = @args[@args.count-1]\n end\n end", "def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for the variable name\n variable_name = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"variable_name\",true)\n variable_name.setDisplayName(\"Enter Variable Name.\")\n variable_name.setDescription(\"Valid values can be found in the eplusout.rdd file after a simulation is run.\")\n args << variable_name\n \n #make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Detailed\"\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Zone Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"Runperiod\"\n reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName(\"Reporting Frequency.\")\n reporting_frequency.setDefaultValue(\"Hourly\")\n args << reporting_frequency\n\n #make an argument for the key_value\n key_value = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"key_value\",true)\n key_value.setDisplayName(\"Enter Key Name.\")\n key_value.setDescription(\"Enter * for all objects or the full name of a specific object to.\")\n key_value.setDefaultValue(\"*\")\n args << key_value\n \n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\n env.setDisplayName(\"availableEnvPeriods\")\n env.setDescription(\"availableEnvPeriods\")\n env.setDefaultValue(\"RUN PERIOD 1\")\n args << env\n \n return args\n end", "def parse(args)\n @options = ScriptOptions.new\n @args = OptionParser.new do |parser|\n @options.define_options(parser)\n parser.parse!(args)\n end\n @options\n end", "def parse(args)\n @options = {}\n @options[:command] = :scan # Default command is to scan for lints\n\n OptionParser.new do |parser|\n parser.banner = \"Usage: #{@application.executable_name} [options] [file1, file2, ...]\"\n\n add_linter_options parser\n add_file_options parser\n add_misc_options parser\n add_info_options parser\n end.parse!(args)\n\n # Any remaining arguments are assumed to be files that should be linted\n @options[:included_paths] = args\n\n @options\n rescue OptionParser::InvalidOption => ex\n raise InvalidCliOptionError,\n \"#{ex.message}\\nRun `#{@application.executable_name} --help` to \" \\\n 'see a list of available options.'\n end", "def parse_args(arg)\n if arg.is_a?(Hash) and Knj::ArrayExt.hash_numeric_keys?(arg)\n arr = []\n \n arg.each do |key, val|\n arr << val\n end\n \n return self.parse_args(arr)\n elsif arg.is_a?(Hash)\n arg.each do |key, val|\n arg[key] = self.parse_args(val)\n end\n \n return arg\n elsif arg.is_a?(Array)\n arg.each_index do |key|\n arg[key] = self.parse_args(arg[key])\n end\n \n return arg\n elsif arg.is_a?(String) and match = arg.match(/^#<Model::(.+?)::(\\d+)>$/)\n return @ob.get(match[1], match[2])\n else\n return arg\n end\n end", "def parse_arguments\n OptionParser.new do |parser|\n # parser.banner = \"Usage: init.rb -c <integer>\"\n parser.on(\"-c\", \"--count COUNT\", Integer, \"Specify number of uuid's to generate\") do |c|\n @options[:count] = c\n end\n parser.on(\"-f\", \"--file FILE\", \"Specify path to save csv file example -f '/path/to/file.csv'\") do |path|\n @options[:path] = path\n end\n end.parse!\n end", "def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"Whole Building\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n\r\n return args\r\n end", "def parse(args)\n optparser = new_option_parser\n optparser.parse!(args)\n abort_missing_options(optparser)\n @options\n end", "def parse_options(args) # :nodoc:\n global_options,command,options,arguments = parse_options_helper(args.clone,Hash.new,nil,Hash.new,Array.new)\n flags.each { |name,flag| global_options[name] = flag.default_value if !global_options[name] }\n command.flags.each { |name,flag| options[name] = flag.default_value if !options[name] }\n return [global_options,command,options,arguments]\n end", "def parse_arguments(arguments)\n unless arguments.class == Array\n raise ArgumentError, \"arguments must be an Array\"\n end\n @options = Trollop::options arguments do\n opt :csv_path, \"Full path to output csv file (Required)\",\n :type => :string, :short => \"-c\", :required => true\n opt :database_host,\n \"Host IP of the database (Only required if connecting via TCP)\",\n :type => :string, :short => \"-h\"\n opt :database_name, \"Database name (Required)\", :type => :string,\n :short => \"-n\", :required => true\n opt :database_user, \"Database username (Required)\", :type => :string,\n :short => \"-u\", :required => true\n opt :database_password, \"Database password (Required)\",\n :type => :string, :short => \"-p\", :required => true\n opt :skip_fund_indexing, \"Skip fund indexing from Bloomberg site\"\n version \"Bargain Stock Funds Scraper version #{Bsf::Scraper::VERSION}\"\n end\n end", "def parse_options(args)\n\t\t\t\tbegin\n\t\t\t\t\t@options['output'] = :stdout\n\t\t\t\t\t@options['verbose'] = false\n\t\t\t\t\t@options['rescan'] = false\n\t\t\t\t\t@options[:timeout] = 25\n\t\t\t\t\t@options[:directory] = nil\n\n\t\t\t\t\topts = OptionParser.new do |opt|\n\t\t\t\t\t\topt.banner = \"#{APP_NAME} v#{VERSION}\\nJacob Hammack\\n#{HOME_PAGE}\\n\\n\"\n\t\t\t\t\t\topt.banner << \"Usage: #{APP_NAME} <options>\"\n\t\t\t\t\t\topt.separator('')\n\t\t\t\t\t\topt.separator('File Options')\n\n\t\t\t\t\t\topt.on('-h HASH', '--search-hash HASH', 'Searches a single hash on virustotal.com') do |hash|\n\t\t\t\t\t\t\t@hashes.push(hash)\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-r HASH[,HASH]', '--rescan-hash HASH[,HASH]', 'Requests a rescan of a single hash, or multiple hashes (comma separated), by virustotal.com') do |hash|\n\t\t\t\t\t\t\t@options['rescan'] = true\n\t\t\t\t\t\t\t@hashes.push(hash)\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-f FILE', '--search-hash-file FILE', 'Searches each hash in a file of hashes on virustotal.com') do |file|\n\t\t\t\t\t\t\tif File.exists?(file)\n\t\t\t\t\t\t\t\tputs \"[+] Adding file #{file}\" if @options['verbose']\n\t\t\t\t\t\t\t\t@files_of_hashes.push(file)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tputs \"[!] #{file} does not exist, please check your input!\\n\"\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-u FILE', '--upload-file FILE', 'Uploads a file to virustotal.com for analysis') do |file|\n\t\t\t\t\t\t\tif File.exists?(file)\n\t\t\t\t\t\t\t\tputs \"[+] Adding file #{file}\" if @options['verbose']\n\t\t\t\t\t\t\t\t@uploads.push(file)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tputs \"[!] #{file} does not exist, please check your input!\\n\"\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.separator('')\n\t\t\t\t\t\topt.separator(\"Url Options\")\n\n\t\t\t\t\t\topt.on('-s SITE', '--search-site SITE', 'Searches for a single url on virustotal.com') { |site|\n\t\t\t\t\t\t\t@sites.push(site)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\topt.separator('')\n\t\t\t\t\t\topt.separator('Output Options')\n\n\t\t\t\t\t\topt.on('-j', '--json-output', 'Print results as json to stdout') do\n\t\t\t\t\t\t\t@options['output'] = :json\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-x', '--xml-output', 'Print results as xml to stdout') do\n\t\t\t\t\t\t\t@options['output'] = :xml\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-y', '--yaml-output', 'Print results as yaml to stdout') do\n\t\t\t\t\t\t\t@options['output'] = :yaml\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('--stdout-output', 'Print results as normal text line to stdout, this is default') do\n\t\t\t\t\t\t\t@options['output'] = :stdout\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.separator ''\n\t\t\t\t\t\topt.separator 'Advanced Options'\n\n\t\t\t\t\t\topt.on('-c', '--create-config', 'Creates a skeleton config file to use') do\n\t\t\t\t\t\t\tcreate_config\n\t\t\t\t\t\t\texit\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-d DIRECTORY', '--directory', 'Scans a directory recursively for files and submits the hashes') do |directory|\n\t\t\t\t\t\t\t@options[:directory] = directory\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-p PROXY', '--proxy-server', 'Uses a specified proxy server') do |proxy|\n\t\t\t\t\t\t\t@options['proxy'] = proxy\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('--[no-]verbose', 'Print verbose information') do |v|\n\t\t\t\t\t\t\t@options['verbose'] = v\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.separator ''\n\t\t\t\t\t\topt.separator 'Other Options'\n\n\t\t\t\t\t\topt.on('-v', '--version', 'Shows application version information') do\n\t\t\t\t\t\t\tputs \"#{APP_NAME} - #{VERSION}\"\n\t\t\t\t\t\t\texit\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on_tail('-?', '--help', 'Show this message') { |help|\n\t\t\t\t\t\t\tputs opt.to_s + \"\\n\"\n\t\t\t\t\t\t\texit\n\t\t\t\t\t\t}\n\t\t\t\t\tend\n\n\t\t\t\t\tif ARGV.length != 0\n\t\t\t\t\t\topts.parse!\n\t\t\t\t\telse\n\t\t\t\t\t\tputs opts.to_s + \"\\n\"\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\trescue OptionParser::MissingArgument\n\t\t\t\t\tputs opts.to_s + \"\\n\"\n\t\t\t\t\texit\n\t\t\t\tend\n\t\t\tend", "def parse(args)\n begin \n opt_parser.parse!(args)\n rescue ::OptionParser::InvalidOption => e\n puts help\n exit(1)\n end\n options\n end", "def parse( args )\n opts = OptionParser.new\n opts.banner = 'Usage: webby [options] target [target args]'\n\n opts.separator ''\n\n desired_opts = %[--describe --prereqs --tasks --trace]\n app.standard_rake_options.each do |options|\n next unless desired_opts.include?(options.first)\n opts.on(*options)\n end\n opts.on('-o', '--options [PATTERN]',\n 'Show configuration options (matching optional pattern), then exit.') { |value|\n @command = [:show_options, value]\n }\n\n opts.separator ''\n opts.separator 'autobuild options:'\n\n opts.on('--web-server', 'Start a local web server') {\n cmd_line_options[:use_web_server] = true\n }\n opts.on('--no-web-server', 'Do not start a local web server') {\n cmd_line_options[:use_web_server] = false\n }\n\n opts.separator ''\n opts.separator 'common options:'\n\n opts.on_tail( '-h', '--help', 'show this message' ) do\n @stdout.puts opts\n exit\n end\n opts.on_tail( '--version', 'show version' ) do\n @stdout.puts \"Webby #{::Webby::VERSION}\"\n exit\n end\n\n opts.parse! args\n\n ARGV.replace Array(args.shift)\n args.delete_if do |arg|\n if %r/^[A-Z_]+=/ =~ arg\n ARGV << arg\n next true\n end\n false\n end\n\n args\n end", "def parse(args)\n\t\thelp = nil\n\t\t\n\t\toption = OptionParser.new do |opts|\n\t\t\topts.banner = \"String To Integer\".center(80, '-')\n\t\t\topts.separator \"\"\n\t\t\topts.separator \"Usage:\"\n\t\t\topts.separator \"\tCan be used to convert a string representation of a integer to an integer.\"\n\t\t\topts.separator \"Example\"\n\t\t\topts.separator \"\t ./atoi.rb -s \\'[STRING_REPESENTATION_OF_AN_INTEGER]\\'\"\n\t\t\topts.separator \"\t e.g. ./atoi.rb -s '148'\"\n\t\t\topts.separator \"\t => 148\"\n\t\t\topts.separator \" \"\n\t\t\topts.on(\"-s ASCII_STRING\", \"--ascii_string ASCII_STRING\", String, \"The string representation of a integer; e.g \\'148\\'\", :REQUIRED){ |s| @ascii_string = s.split('') }\n\t\t\topts.on(\"-h\", \"--help\", \"help\"){puts option}\n\t\t\thelp = opts.help\n\t\tend.parse!\n\n\t\tif @ascii_string.nil?; puts help; exit 1; end\n\t\tself\n\tend", "def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n stp = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"stp\", true)\r\n stp.setDisplayName(\"Timeseries Timestep\")\r\n stp.setDescription(\"Timeseries Timestep\")\r\n stp.setDefaultValue(\"Zone Timestep\")\r\n args << stp\r\n \r\n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\r\n env.setDisplayName(\"availableEnvPeriods\")\r\n env.setDescription(\"availableEnvPeriods\")\r\n env.setDefaultValue(\"RUN PERIOD 1\")\r\n args << env\r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n scale = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"scale\", true)\r\n scale.setDisplayName(\"scale factor to apply to the difference\")\r\n scale.setDescription(\"scale factor to apply to the difference\")\r\n scale.setDefaultValue(1)\r\n args << scale \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n \r\n algorithm_download = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"algorithm_download\", true)\r\n algorithm_download.setDisplayName(\"algorithm_download\")\r\n algorithm_download.setDescription(\"algorithm_download\")\r\n algorithm_download.setDefaultValue(false)\r\n args << algorithm_download \r\n \r\n plot_flag = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"plot_flag\", true)\r\n plot_flag.setDisplayName(\"plot_flag timeseries data\")\r\n plot_flag.setDescription(\"plot_flag timeseries data\")\r\n plot_flag.setDefaultValue(true)\r\n args << plot_flag\r\n \r\n plot_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"plot_name\", true)\r\n plot_name.setDisplayName(\"Plot name\")\r\n plot_name.setDescription(\"Plot name\")\r\n plot_name.setDefaultValue(\"\")\r\n args << plot_name\r\n \r\n warning_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"warning_messages\", true)\r\n warning_messages.setDisplayName(\"warning_messages\")\r\n warning_messages.setDescription(\"warning_messages\")\r\n warning_messages.setDefaultValue(false)\r\n args << warning_messages\r\n\r\n return args\r\n end", "def process_arguments\n @args << \"-h\" if(@args.length < 1)\n \n opts_parse = OptionParser.new do |opts|\n opts.on('-f','--file FILE','use the following local file') {|file| @options.file = File.expand_path(file)}\n opts.on('-p','--parse PARSE',\"sets which set of sider files to download #{@@sections.join(\"|\")}\") {|parse| @options.parse = parse}\n opts.on('-d','--download','download the file to be parsed') {@options.download = true}\n opts.on('-o','--output DIR','set the output directory') {|directory| @options.output = File.expand_path(directory)}\n opts.on('-h','--help',\"prints the help\"){puts opts; exit!}\n end\n \n opts_parse.parse!(@args) rescue raise \"There was an error processing command line arguments use -h to see help\"\n end", "def parsed_args\n args = Options.new('binnacle - Simple Test and Infra automation Framework')\n args.verbose = 0\n args.runner = false\n args.result_json = ''\n\n opt_parser = OptionParser.new do |opts|\n opts.banner = 'Usage: binnacle [options] <testfile>'\n\n opts.on('-w', '--wide', 'Do not crop the task line') { args.wide = true }\n opts.on('-v', '--verbose', 'Verbose output') { args.verbose += 1 }\n opts.on('-r', '--runner', 'Run the tasks from a file (Internal use only)') { args.runner = true }\n opts.on('--results-json=FILE', 'Results JSON file') do |json_file|\n args.result_json = json_file\n end\n\n opts.on('-h', '--help', 'Prints this help') do\n puts opts\n exit\n end\n\n opts.on('--version', 'Show Version information') do\n puts \"Binnacle #{Binnacle::VERSION}\"\n exit\n end\n end\n\n opt_parser.parse!(ARGV)\n\n if ARGV.empty?\n warn 'Task file is not specified'\n exit EXIT_INVALID_ARGS\n end\n\n args.task_files = ARGV\n args\nend", "def parse_command_line args\n args.options do |opt|\n opt.on(\"rutema v#{Version::STRING}\")\n opt.on(\"Options:\")\n opt.on(\"--config FILE\", \"-c FILE\",String,\"Loads the configuration from FILE\") { |config_file| @config_file=config_file}\n opt.on(\"--check\",\"Runs just the suite setup test\"){@check=true}\n #opt.on(\"--step\",\"Runs test cases step by step\"){@step=true}\n opt.on(\"--silent\",\"Suppresses console output (only for the default reporters)\") { @silent=true}\n opt.on(\"--bare\",\"No default reporters whatsoever\") { @bare=true}\n #opt.on(\"--color\",\"Adds color to the Console reporter\") { @color=true}\n opt.on(\"-v\", \"--version\",\"Displays the version\") { $stdout.puts(\"rutema v#{Version::STRING}\");exit 0 }\n opt.on(\"--help\", \"-h\", \"-?\", \"This text\") { $stdout.puts opt; exit 0 }\n opt.on(\"--debug\", \"-d\", \"Turn on debug messages\") { $DEBUG=true }\n opt.on(\"You can provide a specification filename in order to run a single test\")\n opt.parse!\n #and now the rest\n unless @config_file\n puts \"No configuration file defined!\\n\"\n $stdout.puts opt \n exit 1\n end\n if !args.empty?\n @test_identifier=args.shift\n end\n end\n end", "def process_arguments\n @e_addr = @options.email\n @r_name = @options.run_names\n @m_name = @options.machine_names\n @action = @options.action\n @snfs = @options.snfs\n end", "def parse\n @opts = OptionParser.new { |opts| process_opts(opts) }\n @opts.parse!(@args)\n\n process_args\n\n @options\n end", "def parse_options(args) # :nodoc:\n option_parser_class = self.class.const_get(\"#{options[:subcommand_option_handling_strategy].to_s.capitalize}CommandOptionParser\")\n OptionParsingResult.new.tap { |parsing_result|\n parsing_result.arguments = args\n parsing_result = @global_option_parser.parse!(parsing_result)\n option_parser_class.new(@accepts).parse!(parsing_result, options[:argument_handling_strategy], options[:autocomplete])\n }\n end", "def parse_arguments\n options = {}\n parser = OptionParser.new do |opts|\n opts.on(\"-d\", \"--dir DIR\", \"absolute or relative path of the directory\") do |arg|\n options[:dir] = arg\n end\n\n opts.on(\"-p\", \"--pattern PATTERN\", \"search pattern - can contain asterisk(*) as wildcard\") do |arg|\n options[:pattern] = arg\n end\n end\n parser.parse!\n [options, parser]\nend", "def parse_args\n options = {}\n optparse = OptionParser.new do|opts|\n # Set a banner\n opts.banner = \"Usage: harness.rb [-c || --config ] FILE [-d || --testdir] DIR\"\n\n options[:testdir] = nil\n opts.on( '-d', '--testdir DIR', 'Execute tests in DIR' ) do|dir|\n options[:testdir] = dir\n end\n options[:config] = nil\n opts.on( '-c', '--config FILE', 'Use configuration FILE' ) do|file|\n options[:config] = file\n end\n\n opts.on( '-h', '--help', 'Display this screen' ) do\n puts opts\n exit\n end\n end\n optparse.parse!\n return options\nend", "def parse_options(args)\n program = Pathname.new(__FILE__).realpath\n header = <<-END_HEADER\n# Running #{program} on #{Time.now}\n# Command-line arguments are: #{args}\n# Command-line to reproduce: #{program} #{args.join(\" \")}\n#\nEND_HEADER\n timestamp = Time.now.strftime(\"%Y%m%d%H%M%S\")\n current_dir = Pathname.pwd\n output_basename = current_dir + \"log\"\n output_basename.mkdir unless output_basename.directory?\n options = OpenStruct.new\n options.log_level = :off\n options.log_destination = STDOUT\n options.db_url = { :adapter => :in_memory }\n options.generate = nil\n options.time = 60\n options.profile_strings = false\n options.output_filename = \"dm-tpcc-#{timestamp}.out\"\n options.data_directory = current_dir + \"data\"\n options.load = false\n options.save_data = false\n\n opts = OptionParser.new do |opts|\n opts.banner = \"Usage: dm-tpcc [options]\"\n opts.separator \"\"\n\n opts.on(\"-g NUM_WAREHOUSES\", \"--generate NUM_WAREHOUSES\", Integer,\n \"Generate data for the number of warehouses.\") do |g| \n options.generate = g \n end\n\n opts.on(\"-s DIRECTORY_NAME\", \"--save DIRECTORY_NAME\",\n \"Save generated data for later use.\") do |s| \n options.data_directory = s unless (s.nil? || s.empty?)\n end\n\n opts.on(\"-S\", \"--save-data\", \"Save generated data for later use.\") do |s| \n options.save_data = s\n end\n\n opts.on(\"-D\", \"--load-data\", \"Load data from saved datasets.\") do |l|\n options.load = l\n end\n\n opts.on(\"--profile-string-algorithms\",\n \"Profile different string generators\") do |sg| \n options.profile_strings = sg \n end\n\n opts.on(\"-d DB_URL\", \"--db-url DB_URL\", String,\n \"Specify a DataMapper DB URL\") do |dburl| \n options.db_url = dburl \n end\n\n opts.on(\"-l LOG_LEVEL\", \"--log-level LOG_LEVEL\", LOG_LEVELS,\n \"Specify a log level.\") do |l| \n options.log_level = l.to_sym \n end\n\n opts.on(\"-L LOG_FILE\", \"--log-file LOG_FILE\", String,\n \"Specify a log file.\") do |f| \n options.log_destination = File.new(f, \"a+\") \n end\n\n opts.on(\"-o FILENAME\", \"--output FILENAME\", String,\n \"Filename to save output to.\") do |outputfile| \n options.output_filename = outputfile\n end\n\n opts.on(\"-t DURATION\", \"--time DURATION\", Integer,\n \"Duration of the test in seconds.\") do |time| \n options.time = time \n end\n\n opts.on(\"--once\", \"Run just one time\") do |once| \n options.once = once \n end\n\n opts.separator \"Common Options:\"\n opts.on_tail(\"-h\", \"--help\", \"Show this message.\") do\n puts opts\n\n print \"\\nLog Levels:\\n\"\n LOG_LEVELS.keys.each { |l| print \"\\t#{l}\\n\" }\n print \"\\nExample Database URLS:\\n\"\n $example_dbs.each { |db| print \"\\t#{db}\\n\" }\n exit\n end\n opts.on_tail(\"--version\", \"Show version\") do\n puts DataMapper::TPCC::VERSION\n exit\n end\n end\n\n opts.parse!(args)\n \n # Process options into global variables (ick)\n $output = File.open(output_basename + options.output_filename, \"w+\")\n $output.print header\n $data_directory = options.data_directory\n $data_directory.mkdir unless $data_directory.directory?\n\n options\nend", "def userargs\n #\n # Portion to interact with user at commandline. Processes users arguments and aligns them within an options hash\n # These options are globally avalilable, and are not mutable. The can be overwritten so be sure to save the contents\n # rather than attempting to read directly from the has itself.\n #\n begin # Catch/Rescue block start\n $options = OpenStruct.new # create a new OpenStruct object\n OptionParser.new do |opt|\n opt.on('-t','--type TYPE','Consume all files of type [\"TXT\",\"GZ\"] in a directory') { |o|\n $options[:type] = o } # consumes all files of given within a given directory\n opt.on('-i','--input FILE/FOLDER','location of file(s) to process') { |o|\n $options[:input] = o } # create files in directory given by user, default if not given\n opt.on('-e','--explode','Explode contents of \"tar.gz\" files to disk') { |o|\n $options[:explode] = o } # create files from compressed file in directory given by user, default if not given\n opt.on('-o','--output{=FOLDERNAME}','Location on disk to store contents generated') { |o|\n $options[:folder] = o } # location (folder) where to store the generated output\n opt.on('-d','--debug','Enables debugging information to be displayed, performance hit') { |o|\n $options[:debug] = o } # enabled debugging output, performance hit\n opt.on('-v','--verbose','Adds additional information to STDOUT, performance hit increases') { |o|\n $options[:verbose] = o } # adds additional debugging information to STDOUT, greater performance hit\n opt.on('-s','--sleep{=TIME}','Adds pause to decrease STDOUT flooding, performance hit increases') { |o|\n $options[:sleep] = o } # adds additional debugging information to STDOUT, greater performance hit\n end.parse! # Stop parsing options from user @ cli\n rescue => someerror # catch error to var\n puts \"[ERROR]:: OptionsParser fault: #{someerror}\"\n end # Catch/Rescue block end\nend", "def arguments\n options = {}\n\n begin\n params = OptionParser.new do |opts|\n opts.banner = 'Usage: ralphttp [OPTIONS]'\n\n opts.on('-c', '--concurrent NUM',\n 'Number of concurrent connections')do |concurrent|\n options[:concurrent] = concurrent\n end\n\n opts.on('-n', '--requests NUM',\n 'Total number of requests to use') do |reqs|\n options[:requests] = reqs\n end\n\n opts.on('-u', '--url URL', 'URL of the page to benchmark') do |url|\n options[:url] = url\n end\n\n opts.on('-a', '--user-agent STRING', 'User Agent to use') do |ua|\n options[:useragent] = ua\n end\n\n opts.on('-d', '--detail', 'Show detailed report') do |d|\n options[:detail] = d\n end\n\n opts.on('-s', '--csv FILE', 'Output CSV data into file') do |c|\n options[:csv] = c\n end\n\n opts.on('-h', '--help', 'Show help') do\n puts opts\n exit\n end\n end\n params.parse!\n options[:url] = url_parse(options[:url]) unless options[:url].nil?\n @params = params\n rescue OptionParser::InvalidOption, OptionParser::MissingArgument\n puts params\n exit\n end # End begin\n\n options\n end", "def parse(args)\n @options = args\n end", "def parse!( args )\n @args = args\n @options.grep!(args)\n end", "def parse_args\n options = { :verbose => false, :status => false, :immediately => false, :action => :attach}\n\n parser = Trollop::Parser.new do \n opt :url, \"\", :long => \"--attach\", :short => \"-a\", :type => String, :required => true\n opt :force\n opt :cloud, \"\", :type => String\n version \"\"\n end\n\n parse do\n options.merge(parser.parse)\n end\n end", "def parse_options(args) # :nodoc:\n args_clone = args.clone\n global_options = {}\n command = nil\n command_options = {}\n remaining_args = nil\n\n global_options,command_name,args = parse_global_options(OptionParserFactory.new(@flags,@switches,@accepts), args)\n @flags.each do |name,flag|\n global_options[name] = flag.default_value unless global_options[name]\n end\n\n command_name ||= @default_command || :help\n command = find_command(command_name)\n if Array(command).empty?\n raise UnknownCommand.new(\"Unknown command '#{command_name}'\")\n elsif command.kind_of? Array\n raise UnknownCommand.new(\"Ambiguous command '#{command_name}'. It matches #{command.sort.join(',')}\")\n end\n\n command_options,args = parse_command_options(OptionParserFactory.new(command.flags,command.switches,@accepts),\n command,\n args)\n\n command.flags.each do |name,flag|\n command_options[name] = flag.default_value unless command_options[name]\n end\n command.switches.each do |name,switch|\n command_options[name] = switch.default_value unless command_options[name]\n end\n\n [global_options,command,command_options,args]\n end", "def run(args)\n ret = DEFAULTS.merge({})\n\n # create option parser\n o = ::OptionParser.new do |o|\n o.banner = \"Usage: #@app [options]\"\n o.separator \" \"\n\n # add command-line options\n o.separator \"Options:\"\n\n o.on('-A', '--allow USER', 'Allow Jabber subscription from USER.') do |v|\n add_allowed(ret, v)\n end\n\n o.on('-c', '--config FILE', 'Use configuration file FILE.') do |v|\n Joggle::ConfigParser.run(v) do |key, val|\n if key == 'engine.allow'\n add_allowed(ret, val)\n elsif key == 'engine.update.range'\n add_update_range(ret, val)\n else\n ret[key] = val\n end\n end\n end\n\n o.on('-D', '--daemon', 'Run as daemon (in background).') do |v|\n ret['cli.daemon'] = true\n end\n\n o.on('--foreground', 'Run in foreground (the default).') do |v|\n ret['cli.daemon'] = false\n end\n\n o.on('-L', '--log-level LEVEL', 'Set log level to LEVEL.') do |v|\n ret['runner.log.level'] = v\n end\n\n o.on('-l', '--log FILE', 'Log to FILE.') do |v|\n ret['runner.log.path'] = v\n end\n\n o.on('-p', '--password PASS', 'Jabber password (INSECURE!).') do |v|\n ret['jabber.pass'] = v\n end\n\n o.on('-s', '--store FILE', 'Use FILE as backing store.') do |v|\n ret['runner.store.path'] = v\n end\n\n o.on('-u', '--username USER', 'Jabber username.') do |v|\n ret['jabber.user'] = v\n end\n\n o.separator ' '\n\n o.on_tail('-v', '--version', 'Print version string.') do\n puts \"Joggle %s, by %s\" % [\n Joggle::VERSION,\n 'Paul Duncan <pabs@pablotron.org>',\n ]\n exit\n end\n\n o.on_tail('-h', '--help', 'Print help information.') do\n puts o\n exit\n end\n end\n\n # parse arguments\n o.parse(args)\n\n # return results\n ret\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \t\"os_object_type\"\t],\n [ \"lib_file_name\", \"STRING\", true, false, \"Lib File Name\", nil, nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"construction_set_name\", \"STRING\", true, false, \"Construction Set Name\", nil, nil, nil, nil, \t nil\t\t\t\t\t],\n \n #Default set for server weather folder.\n [ \"lib_directory\", \"STRING\", true, false, \"Lib Directory\", \"../../lib/btap/resources/constructions\", nil, nil, nil,\t nil\t\t\t\t\t]\n \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def parse_args\n options = {}\n optparse = OptionParser.new do|opts|\n # Set a banner\n opts.banner = \"Usage: harness.rb [options...]\"\n\n options[:tests] = []\n opts.on( '-t', '--tests DIR/FILE', 'Execute tests in DIR or FILE (defaults to \"./tests\")' ) do|dir|\n options[:tests] << dir\n end\n\n options[:type] = 'skip'\n opts.on('--type TYPE', 'Select puppet install type (pe, git, skip) - default \"skip\"') do\n |type|\n unless File.directory?(\"setup/#{type}\") then\n puts \"Sorry, #{type} is not a known setup type!\"\n exit 1\n end\n options[:type] = type\n end\n\n options[:puppet] = 'git://github.com/puppetlabs/puppet.git#HEAD'\n opts.on('-p', '--puppet URI', 'Select puppet git install URI',\n \" #{options[:puppet]}\",\n \" - URI and revision, default HEAD\",\n \" just giving the revision is also supported\"\n ) do |value|\n options[:type] = 'git'\n options[:puppet] = value\n end\n\n options[:facter] = 'git://github.com/puppetlabs/facter.git#HEAD'\n opts.on('-f', '--facter URI', 'Select facter git install URI',\n \" #{options[:facter]}\",\n \" - otherwise, as per the puppet argument\"\n ) do |value|\n options[:type] = 'git'\n options[:facter] = value\n end\n\n options[:config] = nil\n opts.on( '-c', '--config FILE', 'Use configuration FILE' ) do|file|\n options[:config] = file\n end\n\n opts.on( '-d', '--dry-run', \"Just report what would be done on the targets\" ) do |file|\n $dry_run = true\n end\n\n options[:mrpropper] = FALSE\n opts.on( '--mrpropper', 'Clean hosts' ) do\n puts \"Cleaning Hosts of old install\"\n options[:mrpropper] = TRUE\n end\n\n options[:stdout_only] = FALSE\n opts.on('-s', '--stdout-only', 'log output to STDOUT but no files') do\n puts \"Will log to STDOUT, not files...\"\n options[:stdout_only] = TRUE\n end\n\n options[:quiet] = false\n opts.on('-q', '--quiet', 'don\\'t log output to STDOUT') do\n options[:quiet] = true\n end\n\n opts.on( '-h', '--help', 'Display this screen' ) do\n puts opts\n exit\n end\n end\n optparse.parse!\n return options\nend", "def parse_args()\r\n\t\tfor arg in ARGV\r\n\t\t\tif arg == \"-d\"\r\n\t\t\t\t@daemonize = true\r\n\t\t\telsif arg == \"development\" || arg == \"production\"\r\n\t\t\t\t@db_env = arg\r\n\t\t\tend\r\n\t\tend\r\n\t\tputs \"Using DB: #{@db_env}\"\r\n\tend", "def parse(arguments)\n options = {\n port: DEFAULT_PORT\n }\n\n OptionParser.new do |o|\n o.banner = \"Usage: custodian [options]\"\n o.version = Custodian::VERSION\n\n o.on \"-p PORT\", \"--port PORT\", \"Listen on PORT (default #{options[:port]})\" do |port|\n options[:port] = port\n end\n\n o.on \"-s DIR\", \"--samplers DIR\", \"Load samplers from DIR\" do |samplers|\n options[:samplers] = samplers.split(\":\")\n end\n\n o.on \"--daemonize\", \"Daemonize the process\" do\n options[:daemonize] = true\n end\n\n o.on \"--pidfile FILE\", \"Write the process id to FILE\" do |pidfile|\n options[:pidfile] = pidfile\n end\n\n o.on \"--authenticate USERNAME:PASSWORD\", \"Authenticate clients with the given USERNAME and PASSWORD\" do |credentials|\n unless credentials.include? \":\"\n raise OptionParser::InvalidArgument, \"must be a colon-separated string of username and password\"\n end\n\n options[:username], options[:password] = credentials.split(\":\")\n end\n end.parse! arguments\n\n options\n rescue OptionParser::ParseError => e\n error e\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n id = OpenStudio::Measure::OSArgument.makeStringArgument('feature_id', false)\n id.setDisplayName('Feature unique identifier')\n id.setDefaultValue('1')\n args << id\n\n name = OpenStudio::Measure::OSArgument.makeStringArgument('feature_name', false)\n name.setDisplayName('Feature scenario specific name')\n name.setDefaultValue('name')\n args << name\n\n feature_type = OpenStudio::Measure::OSArgument.makeStringArgument('feature_type', false)\n feature_type.setDisplayName('URBANopt Feature Type')\n feature_type.setDefaultValue('Building')\n args << feature_type\n\n feature_location = OpenStudio::Measure::OSArgument.makeStringArgument('feature_location', false)\n feature_location.setDisplayName('URBANopt Feature Location')\n feature_location.setDefaultValue('0')\n args << feature_location\n\n # make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n # reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'BillingPeriod' # match it to utility bill object\n ## Utility report here to report the start and end for each fueltype\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDescription('The frequency at which to report timeseries output data.')\n reporting_frequency.setDefaultValue('Timestep')\n args << reporting_frequency\n\n return args\n end", "def initialize(args)\n\t @all = nil\n\t if args.class == String\n\t @uri = args\n\t query_data\n\t else\n \t\t@uri = args[\"uri\"] and args[\"uri\"][\"value\"]\n \t\t@name = args[\"name\"] and args[\"name\"][\"value\"]\n \t\t@definition = args[\"definition\"] and args[\"definition\"][\"value\"]\n \t\t# @labels = args[:labels]\n \t\t# @descriptions = args[:descriptions]\n \t\t# @scientific_names = args[:scientific_names]\n \tend\n\tend", "def parse\n\n # display the banner\n @banner.display_banner\n\n # if argv is empty\n if @argv.empty?\n ARGV << '-h'\n end\n\n options = OpenStruct.new\n opt_parser = OptionParser.new do|opts|\n\n opts.banner = 'usage: server_manager.rb -opt [ACTION]'\n\n opts.on('-d', '--deploy ¤', [:install], 'manage the deployment :', '¤ install', \"\\n\") do |action|\n return \"deploy_#{action}\" # return point\n end\n\n opts.on('-s', '--server ¤', [:start, :stop, :restart, :status], 'manage the server :', '¤ start', '¤ stop', '¤ restart', '¤ status', \"\\n\") do |action|\n return \"server_#{action}\" # return point\n end\n\n opts.on('-u','--update ¤',[:server, :system_packages, :system_core], 'manage the updates :', '¤ server', '¤ system_packages', '¤ system_core',\"\\n\") do |action|\n return \"update_#{action}\" # return point\n end\n\n opts.on('-a','--archive ¤', [:display, :remove, :remove_all, :import, :export], 'manage the archives :', '¤ display', '¤ remove', '¤ remove_all', '¤ import', '¤ export',\"\\n\") do |action|\n return \"archive_#{action}\" # return point\n end\n\n opts.on('-b','--blacklist ¤', [:display, :add, :remove], 'manage the blacklist :', '¤ display', '¤ add', '¤ remove', \"\\n\") do |action|\n return \"blacklist_#{action}\" # return point\n end\n\n opts.on('-l','--log ¤', [:client, :server, :clear_client, :clear_server], 'manage the logs :', '¤ client', '¤ server', '¤ clear_client', '¤ clear_server', \"\\n\") do |action|\n return \"log_#{action}\" # return point\n end\n\n opts.on('-h', '--help', 'display help') do\n puts opts\n exit\n end\n end\n\n begin\n opt_parser.parse!(@argv)\n\n rescue OptionParser::ParseError => e\n puts \"#{e}\".error\n exit\n end\n\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # lat arg\n lat = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lat\", true)\n lat.setDisplayName(\"Latitude\")\n lat.setDefaultValue(39.7392000000)\n args << lat\n\n # long arg\n lon = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lon\", true)\n lon.setDisplayName(\"Longitude\")\n lon.setDefaultValue(-104.9903000000)\n args << lon\n\n return args\n end", "def parse(args)\n arg_index = 0\n while arg_index < args.size\n arg = args[arg_index]\n\n if arg.start_with? '--'\n # Argument is a long option (eg: --verbose)\n op = arg[2,arg.length]\n value = nil\n\n # Check if the option and value are specified together (\"--op=value\")\n eql_index = op.index '='\n if !eql_index.nil?\n # Split \"op=value\" string and store\n value = op[eql_index+1, op.size]\n op = op[0, eql_index]\n end\n\n # Check if option is accepted\n raise \"Option '--#{op}' not accepted\" if !accepts? op\n\n # Remember that the option was specified\n data = @options[op]\n data.given = true\n\n # Check if given a value that wasn't expected\n if !data.has_value? && !eql_index.nil?\n raise \"Option '--#{op}' does not expect a value\"\n end\n \n # Get associated value\n if data.has_value?\n # If the option was not given as \"op=value\", get the next value.\n # Otherwise, save the value we stored before\n if eql_index.nil?\n # Get index of next value\n arg_index += 1\n # Make sure we actually have a value to save\n if arg_index >= args.size\n raise \"Option '--#{op}' must be followed by a value\"\n end\n # Then save the value\n data.value = args[arg_index]\n else\n data.value = value\n end\n end\n\n elsif arg.start_with? '-'\n # Argument is a short option (eg: -a, -abc)\n op = arg[1,arg.length]\n \n # Make sure each character is accepted\n op.chars.each_with_index do |c,i|\n # Check for errors\n raise \"Option '-#{c}' not accepted\" if !accepts? c\n\n # Remember that the option was specified\n data = @options[c]\n data.given = true\n\n # Check for and save the option's values\n if data.has_value?\n # Get index of next value\n arg_index += 1\n # Make sure we actually have a value to save\n if arg_index >= args.size || i >= op.size\n raise \"Option '-#{c}' must be followed by a value\"\n end\n # Then save the value\n data.value = args[arg_index]\n end\n end\n\n else\n # Argument is a param (ie. not an option)\n @params << arg\n end\n\n # Increment argument index\n arg_index += 1\n end\n end", "def initialize(args = {})\n parse_args(args)\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # url of the city database\n city_db_url = OpenStudio::Measure::OSArgument.makeStringArgument('city_db_url', true)\n city_db_url.setDisplayName('City Database Url')\n city_db_url.setDescription('Url of the City Database')\n # city_db_url.setDefaultValue(\"http://localhost:3000\")\n city_db_url.setDefaultValue('http://insight4.hpc.nrel.gov:8081/')\n args << city_db_url\n\n # project id\n project_id = OpenStudio::Measure::OSArgument.makeStringArgument('project_id', true)\n project_id.setDisplayName('Project ID')\n project_id.setDescription('Project ID.')\n args << project_id\n\n # scenario id\n scenario_id = OpenStudio::Measure::OSArgument.makeStringArgument('scenario_id', true)\n scenario_id.setDisplayName('Scenario ID')\n scenario_id.setDescription('Scenario ID.')\n args << scenario_id\n\n # feature id\n feature_id = OpenStudio::Measure::OSArgument.makeStringArgument('feature_id', true)\n feature_id.setDisplayName('Feature ID')\n feature_id.setDescription('Feature ID.')\n args << feature_id\n\n return args\n end", "def parse(args)\n OptionParser.new do |opts|\n opts.banner = 'Usage: term [options]'\n\n opts.on('-d', '--debug', 'Enable debug') do |v|\n @options[:debug] = v\n end\n end.parse!(args)\n [@options, args]\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \t\"os_object_type\"\t],\n [ \"weather_file_name\", \"STRING\", true, false, \"Weather File Name\", nil, nil, nil, nil, \t nil\t\t\t\t\t],\n #Default set for server weather folder.\n [ \"weather_directory\", \"STRING\", true, false, \"Weather Directory\", \"../../weather\", nil, nil, nil,\t nil\t\t\t\t\t]\n \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def arguments(model = nil)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n chs = OpenStudio::StringVector.new\n chs << 'Last OSM'\n chs << 'Last IDF'\n file_source = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('file_source', chs, true)\n file_source.setDisplayName('Model Source')\n file_source.setDefaultValue('Last OSM')\n args << file_source\n\n chs = OpenStudio::StringVector.new\n chs << 'Timestep'\n chs << 'Hourly'\n reporting_frequency = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('reporting_frequency', chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n variable1_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable1_name', true)\n variable1_name.setDisplayName('Variable 1 Name')\n variable1_name.setDefaultValue('Surface Outside Face Temperature')\n args << variable1_name\n\n variable2_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable2_name', true)\n variable2_name.setDisplayName('Variable 2 Name')\n variable2_name.setDefaultValue('Surface Inside Face Temperature')\n args << variable2_name\n\n variable3_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable3_name', true)\n variable3_name.setDisplayName('Variable 3 Name')\n variable3_name.setDefaultValue('Zone Mean Radiant Temperature')\n args << variable3_name\n\n return args\n end", "def parse(args, prog)\n WhoToWho.log.level = Logger::INFO\n options = OptionParser.new do |opts|\n \n opts.banner = \"Usage: #{prog} [options]\"\n \n opts.on(\"-v\", \"--verbose\", \"Run verbosely\") do |v|\n WhoToWho.log.level = Logger::DEBUG\n WhoToWho.log.debug \"Debug Activate\"\n end\n opts.on( '-f', '--file REQUIRED', :REQUIRED, 'File where is all data') do |f|\n load_file f\n end\n opts.on('-c', '--config FILE', :REQUIRED, 'File where is all config') do |f|\n load_config f\n end\n opts.on('-g', '--gmail', 'Define option if use a Gmail account for SMTP') do |g|\n require_dependency('whotowho/smtp_tls') if g\n end\n opts.on('-s', '--subject SUBJECT', :REQUIRED, 'Define the subject to send by email') do |s|\n @subject = s\n end\n opts.on('-m FILE', '--mail MAIL', :REQUIRED, 'Send a file where the content is with 2 params #{who} and #{towho}') do |c|\n @content = File.open(c).read\n end\n\n @full_print = opts\n\n end.parse!\n test_required\n @test = 0\n end", "def initialize(*args)\n return self if args.empty?\n parsed_args = args.first.is_a?(Hash) ? args.first : parse_string_args(args)\n\n self.executable = parsed_args[:executable]\n self.arguments = parsed_args[:arguments]\n end", "def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # todo - add bool arguments to decide what tables to generate, default all to true.\r\n\r\n return args\r\n end", "def parse_command_line &block\n data = {}\n\n OptionParser.new do |opts|\n opts.banner = \"Usage: #{File.basename($0)} [options]\"\n\n opts.on(\"-c CONFIG\", \"--conf CONFIG\", \"YAML config file\") do |config|\n data[\"config\"] = config\n end\n\n opts.on(\"-p PARAMS\", \"--params PARAMS\", \"Additional default options - key: value as JSON string, override values from config file\") do |params|\n data[\"params\"] = JSON.parse(params)\n end\n\n # process custom args, if given\n block.call(opts) if block_given?\n\n opts.on_tail('-h', '--help', 'display this help and exit') do\n puts opts\n exit\n# return nil\n end\n\n# begin\n opts.parse(ARGV)\n# rescue OptionParser::InvalidOption\n# # do nothing\n# end\n\n end\n\n @args = data\n end", "def get_attribute_group_data(agent_address, service_point, username, password, attribute_group, subnodes, port=1920)\n require 'net/http'\n\n uri = URI(\"http://#{agent_address}:#{port}///#{service_point}/#{service_point}\")\n body = \"<REPORT><SQLTABLE NULLATTROUTPUT=\\\"Y\\\"><TABLENAME>#{attribute_group}</TABLENAME><SUBNODES>#{subnodes.join(\",\")}</SUBNODES></SQLTABLE></REPORT>\"\n\n # warn \"Sending HTTP POST to #{uri} with body #{body}\"\n\n request = Net::HTTP::Post.new(uri.path)\n request.basic_auth(username, password)\n request.body = body\n\n response = Net::HTTP.start(uri.host, uri.port) { |http| http.request(request) }\n if not response.is_a?(Net::HTTPOK)\n $stderr.puts \"Response #{response.code}: #{response.body}\"\n return nil\n end\n\n # warn \"Received #{response.body}\"\n return AttributeGroupData.new_with_xml(response.body)\nend", "def initialize(args={})\n args = {\n :host => \"localhost\",\n :command => \"\",\n :ruser => \"nobody\",\n :luser => ENV[\"USER\"] || \"nobody\",\n :to => 3,\n :nullr => false,\n :ruby_impl => false\n }.merge!(args)\n\n @executable = Rshc.find\n @result = \"\"\n @ruby_impl = @executable.empty? ? true : args[:ruby_impl]\n @host = args[:host]\n @command = args[:command]\n @ruser = args[:ruser]\n @luser = args[:luser]\n @to = args[:to]\n @nullr = args[:nullr]\n end", "def parse_command_line_options!(args)\n OptionParser.new do |opts|\n opts.on('-h', '--help', 'Display this screen') do\n raise UsageError.new(opts)\n end\n end.parse!(args)\n return {}, args\n end", "def arguments\n parser.arguments\n end", "def parse_args(args, kwargs)\n return unless self.class.Args\n command_args = self.class.Args.new(self, *args, **kwargs)\n command_args.validate\n command_args\n end" ]
[ "0.6412463", "0.6116028", "0.60383564", "0.5975493", "0.59547824", "0.58309287", "0.571015", "0.56809366", "0.56716585", "0.5657897", "0.5644503", "0.56317717", "0.5618292", "0.5602395", "0.5582551", "0.55758756", "0.5542489", "0.55292755", "0.552834", "0.55140316", "0.5513628", "0.55035406", "0.5486303", "0.5472661", "0.5472661", "0.5439993", "0.5436932", "0.53932554", "0.5392964", "0.5364783", "0.53558683", "0.53479266", "0.53331274", "0.53329676", "0.5328244", "0.5317464", "0.5301626", "0.5301377", "0.5299083", "0.528314", "0.5275026", "0.52708626", "0.52706087", "0.5269768", "0.5268137", "0.52643895", "0.5262621", "0.5249314", "0.5248002", "0.52455306", "0.5238562", "0.52377844", "0.5236837", "0.52320623", "0.5214942", "0.5206707", "0.51952946", "0.5188935", "0.51861894", "0.51855147", "0.518376", "0.51601636", "0.5155938", "0.5153673", "0.51477385", "0.5143752", "0.5128565", "0.5125291", "0.5124914", "0.51232076", "0.5114849", "0.5110885", "0.51054084", "0.5102703", "0.5091154", "0.50873536", "0.5086515", "0.5084112", "0.5083579", "0.50799453", "0.5074519", "0.5065554", "0.5056247", "0.5045584", "0.5044449", "0.5032303", "0.5031911", "0.5029768", "0.5028409", "0.5027827", "0.50257814", "0.50243807", "0.50227576", "0.50208354", "0.50169194", "0.5014856", "0.5007793", "0.5002318", "0.49958086", "0.49915007" ]
0.86728346
0
GET /produtividades/1 GET /produtividades/1.xml
def show @produtividade = Produtividade.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @produtividade } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @produto = Produto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def show\n @produto = Produto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def show\n @produto = Produto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def show\n\t\t@produt = Produt.find(params[:id])\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml {render :xml => @produt}\n\t\tend\n\tend", "def show\n\t\t# Mapeando Secoes:\n\t\t@secoes = Section.where(\"ativo = 't'\")\n\t\t@departamentos = Departamento.where(\"ativo = 't'\")\n\t\t\n\t\t@produt = Produt.find(params[:id])\n\t\t\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml {render :xml => \"/loja\"}\n\t\tend\n\t\t\n\tend", "def show\n @nossos_servico = NossosServico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def show\n @produto_kit = ProdutoKit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @produto_kit }\n end\n end", "def show\n @proceso = Proceso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @proceso }\n end\n end", "def index\n @pecas = Peca.find :all, :order => :produto_id\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @pecas }\n end\n end", "def show\n @products = CatalogMebeli.find(params[:id]).products\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @product }\n end\n end", "def show\n @precio = Precio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @precio }\n end\n end", "def show\n @estacion = Estacion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @estacion }\n end\n end", "def show\n @lista_precio = ListaPrecio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @lista_precio }\n end\n end", "def index\n @cuentas = Cuenta.all\n\n @cadena = getcuentasxml\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @cadena }\n end\n end", "def index\n @procesos = Proceso.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @procesos }\n end\n end", "def show\n @estagiarios = Estagiario.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @estagiarios }\n end\n end", "def show\n @estagio = Estagio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @estagio }\n end\n end", "def show\n @valor_sistema = ValorSistema.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @valor_sistema }\n end\n end", "def show\n @comunidade = Comunidade.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @comunidade }\n end\n end", "def show\n @campanha_produto = CampanhaProduto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @campanha_produto }\n end\n end", "def show\n @certidao = Certidao.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @certidao }\n end\n end", "def show\n @tipo_proy = TipoProy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipo_proy }\n end\n end", "def show\n @puesto = Puesto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @puesto }\n end\n end", "def show\n @compras_documento = ComprasDocumento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @compras_documento }\n end\n end", "def show\n @estudiante = Estudiante.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @estudiante }\n end\n end", "def show\n @estudiante = Estudiante.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @estudiante }\n end\n end", "def show\n @departamentos = Departamento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @departamentos }\n end\n end", "def show\n @contratosinterventoria = Contratosinterventoria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @contratosinterventoria }\n end\n end", "def show\n @tipos_pagamento = TiposPagamento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipos_pagamento }\n end\n end", "def show\n @lista_precio = ListaPrecio.find(params[:id])\n @producto_listas = @lista_precio.producto_lista_precios.paginate(:page => params[:page],:per_page => 30)\n @cant_productos = @lista_precio.producto_lista_precios.count \n\n respond_to do |format|\n format.html \n format.xml { render :xml => @lista_precio}\n end\n end", "def show\n @poblacionesespecial = Poblacionesespecial.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @poblacionesespecial }\n end\n end", "def show\r\n load_session\r\n\r\n @product = Product.find(params[:id])\r\n @product_desc = @product.product_description\r\n\r\n # Build XML resposne object\r\n xml = Builder::XmlMarkup.new\r\n xml.instruct!\r\n xml.response << @product.to_xml\r\n\r\n respond_to do |format|\r\n format.html # { render :layout => 'home' }\r\n format.xml # { render :xml => @product }\r\n end\r\n end", "def show\n\t\t@departamento = Departamento.find(params[:id])\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml {render :xml => @departamento}\n\t\tend\n\tend", "def show\n @producto_stock = ProductoStock.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @producto_stock }\n end\n end", "def show\n @suministro = Suministro.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @suministro }\n end\n end", "def show\n @partido_politico = PartidoPolitico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @partido_politico }\n end\n end", "def show\n @peso = Peso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @peso }\n end\n end", "def show\n @pagos_detalhe = PagosDetalhe.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @pagos_detalhe }\n end\n end", "def show\n @tservicio = Tservicio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tservicio }\n end\n end", "def show\n @categoria_comida = CategoriaComida.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @categoria_comida }\n end\n end", "def show\n @aplicacion = Aplicacion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @aplicacion }\n end\n end", "def show\n @calidadtiposdocumento = Calidadtiposdocumento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @calidadtiposdocumento }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @departamento }\n end\n end", "def show\n @departamento = Departamento.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @departamento }\n end\n end", "def show\n @pedido = Pedido.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @pedido }\n end\n end", "def show\n @pagamento = Pagamento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @pagamento }\n end\n end", "def show\n @prd_etc = PrdEtc.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @prd_etc }\n end\n end", "def xml(id)\n http.get(\"/nfse/#{id}/xml\") do |response|\n response.headers.fetch(\"Location\") { \"\" }\n end\n end", "def show\n @pieces_commande = PiecesCommande.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @pieces_commande }\n end\n end", "def show\n @tipo_de_documento = TipoDeDocumento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipo_de_documento }\n end\n end", "def show\n @depositocaucion = Depositocaucion.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @depositocaucion }\n end\n end", "def show\n @projeto = Projeto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @projeto }\n end\n end", "def show\n @requisicion = Requisicion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @requisicion }\n end\n end", "def show\n @entidad = Entidad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @entidad }\n end\n end", "def show\n @sprint_diario = SprintDiario.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @sprint_diario }\n end\n end", "def show\n @situacoes_juridica = SituacoesJuridica.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @situacoes_juridica }\n end\n end", "def show\n @parametro = Parametro.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @parametro }\n end\n end", "def show\n @tiposproceso = Tiposproceso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tiposproceso }\n end\n end", "def view\n @product = Product.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @product }\n end\n end", "def show\n @parametro = Parametro.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @parametro }\n end\n end", "def show\n @tabela_preco_produto = TabelaPrecoProduto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tabela_preco_produto }\n end\n end", "def show\n @catalog_product = CatalogProduct.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @catalog_product }\n end\n end", "def show\n @inscripcione = Inscripcione.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @inscripcione }\n end\n end", "def show\n @partecipante = Partecipante.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @partecipante }\n end\n end", "def show\n @actividad = Actividad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @actividad }\n end\n end", "def show\n @proyect = Proyect.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @proyect }\n end\n end", "def index\n @products = Product.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @products }\n end\n end", "def show\n @coleccionista = Coleccionista.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @coleccionista }\n end\n end", "def show\n @tipo_vinculo = TipoVinculo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipo_vinculo }\n end\n end", "def show\n @distribuidora = Distribuidora.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @distribuidora }\n end\n end", "def show\n @colo = Colo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @colo }\n end\n end", "def show\n @promocao = Promocao.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @promocao }\n end\n end", "def show\n @nostro = Nostro.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @nostro }\n end\n end", "def show\n @product = Product.find(params[:id].to_i)\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @product }\n end\n end", "def show\n @categoria_do_recebimento = CategoriaDoRecebimento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @categoria_do_recebimento }\n end\n end", "def show\n @diputado = Diputado.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @diputado }\n end\n end", "def show\n @tipo_articulo = TipoArticulo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipo_articulo }\n end\n end", "def show\n @reputacao_veiculo = ReputacaoVeiculo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @reputacao_veiculo }\n end\n end", "def show\n @convenio = Convenio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @convenio }\n end\n end", "def show\n @estatu = Estatu.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @estatu }\n end\n end", "def show\n @progre = Progre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @progre }\n end\n end", "def show\n @inventario = Inventario.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @inventario }\n end\n end", "def show\n @titulacionesdoctipo = Titulacionesdoctipo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @titulacionesdoctipo }\n end\n end", "def show\n @corporacion_policiaca = CorporacionPoliciaca.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @corporacion_policiaca }\n end\n end", "def show\n @pessoa = Pessoa.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @pessoa }\n end\n end", "def show\n @requisicao = Requisicao.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @requisicao }\n end\n end", "def show\n @provincia = Provincia.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @provincia }\n end\n end", "def show\n @convenio_financiamiento = ConvenioFinanciamiento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @convenio_financiamiento }\n end\n end", "def show\n @sotto_categoria = SottoCategoria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @sotto_categoria }\n end\n end", "def new\n @produto = ProdutoSimples.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def show\n @ponto = Ponto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @ponto }\n end\n end", "def show\n @tipo_pago = TipoPago.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipo_pago }\n end\n end", "def show\n @product = Product.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @product }\n end\n end", "def show\n @estado_pedido = EstadoPedido.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @estado_pedido }\n end\n end", "def index\n @products = Product.all\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @products }\n end\n end", "def show\n @respuestum = Respuestum.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @respuestum }\n end\n end", "def show\n @viviendastipostramite = Viviendastipostramite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @viviendastipostramite }\n end\n end", "def show\n @relatestagiario = Relatestagiario.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @relatestagiario }\n end\n end", "def show\n @descriptor_generico = DescriptorGenerico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @descriptor_generico }\n end\n end", "def show\n @adicional_desconto = AdicionalDesconto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @adicional_desconto }\n end\n end" ]
[ "0.7011869", "0.7011869", "0.7011869", "0.6863754", "0.67091066", "0.665916", "0.66269976", "0.6607207", "0.6559279", "0.65545934", "0.65191364", "0.65031767", "0.64880395", "0.6480338", "0.64791906", "0.64757663", "0.6466996", "0.6466677", "0.6461223", "0.6456405", "0.64547485", "0.6454392", "0.6454199", "0.6439437", "0.6434035", "0.6433297", "0.6426766", "0.6415549", "0.6409161", "0.63997436", "0.6392635", "0.63911873", "0.6387982", "0.6386442", "0.63835156", "0.6383124", "0.63798976", "0.63719404", "0.636196", "0.63611424", "0.63559794", "0.6353537", "0.63478714", "0.63476884", "0.63470536", "0.6341326", "0.63388765", "0.6333685", "0.6333425", "0.6324874", "0.63217664", "0.63124615", "0.63036495", "0.6302739", "0.6302607", "0.63017684", "0.6300019", "0.62952584", "0.6294327", "0.62928694", "0.629185", "0.6275134", "0.6274782", "0.6269904", "0.6267164", "0.6263321", "0.6261194", "0.626057", "0.62602854", "0.6260178", "0.6252305", "0.62508327", "0.6250645", "0.6250582", "0.62484944", "0.6248107", "0.6244179", "0.62409467", "0.6240006", "0.623926", "0.62384593", "0.6236554", "0.62343234", "0.6233996", "0.62326306", "0.623149", "0.6228745", "0.6227597", "0.6225207", "0.6223373", "0.62196225", "0.62183744", "0.6217039", "0.6216225", "0.6213006", "0.6210056", "0.6209677", "0.62086964", "0.6207645", "0.62067807" ]
0.6972938
3
GET /produtividades/new GET /produtividades/new.xml
def new @produtividade = Produtividade.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @produtividade } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @produto = Produto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def new\n @produto = Produto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def new\n @produto = ProdutoSimples.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def new\n @proceso = Proceso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @proceso }\n end\n end", "def new\n # @produto = Produto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @produto }\n end\n end", "def new\n @precio = Precio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @precio }\n end\n end", "def new\n @nossos_servico = NossosServico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def new\n @ponto = Ponto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ponto }\n end\n end", "def new\n @competencia = Competencia.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @competencia }\n end\n end", "def new\n @tiposproceso = Tiposproceso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tiposproceso }\n end\n end", "def new\n\t\t@produt = Produt.new\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.xml {render :xml => @produt}\n\t\tend\n\tend", "def new\n @tipo_proy = TipoProy.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipo_proy }\n end\n end", "def new\n @estacion = Estacion.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @estacion }\n end\n end", "def new\n @pessoa = Pessoa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pessoa }\n end\n end", "def new\n @pessoa = Pessoa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pessoa }\n end\n end", "def new\n @projeto = Projeto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @projeto }\n end\n end", "def new\n @puesto = Puesto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @puesto }\n end\n end", "def new\n @nostro = Nostro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nostro }\n end\n end", "def new\n @entidad = Entidad.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @entidad }\n end\n end", "def new\n @paciente = Paciente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @paciente }\n end\n end", "def new\n @recurso = Recurso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @recurso }\n end\n end", "def new\n @ponto = Ponto.new\n @t = params[:estagiario_id]\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ponto }\n end\n end", "def new\n @solicitud = Solicitud.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @solicitud }\n end\n end", "def new\n @aplicacion = Aplicacion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @aplicacion }\n end\n end", "def new\n @entidade = Entidade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @entidade }\n end\n end", "def new\n @comunidade = Comunidade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @comunidade }\n end\n end", "def new\n @promocao = Promocao.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @promocao }\n end\n end", "def new\n @po = Po.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @po }\n end\n end", "def new\n @peca = Peca.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @peca }\n end\n end", "def new\n @poblacionesespecial = Poblacionesespecial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @poblacionesespecial }\n end\n end", "def new\n @pagamento = Pagamento.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pagamento }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def new\n @provincia = Provincia.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @provincia }\n end\n end", "def new\n @tservicio = Tservicio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tservicio }\n end\n end", "def new\n @adjunto = Adjunto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @adjunto }\n end\n end", "def new\n @spiel = Spiel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @spiel }\n end\n end", "def new\n @prueba = Prueba.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prueba }\n end\n end", "def new\n @tipos_pagamento = TiposPagamento.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipos_pagamento }\n end\n end", "def new\n @lista_precio = ListaPrecio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lista_precio }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nomina }\n end\n end", "def new\n @estagio = Estagio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @estagio }\n end\n end", "def new\n @campanha_produto = CampanhaProduto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @campanha_produto }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @instituto }\n end\n end", "def new\n @progre = Progre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @progre }\n end\n end", "def new\n @lien = Lien.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lien }\n end\n end", "def new\n @contratosinterventoria = Contratosinterventoria.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @contratosinterventoria }\n end\n end", "def new\n @plantilla = Plantilla.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @plantilla }\n end\n end", "def new\n @tiposcontrato = Tiposcontrato.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tiposcontrato }\n end\n end", "def new\n @actividad = Actividad.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @actividad }\n end\n end", "def new\n @catena = Catena.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @catena }\n end\n end", "def new\n @tipo_contrato = TipoContrato.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipo_contrato }\n end\n end", "def new\n @colo = Colo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @colo }\n end\n end", "def new\n @pieces_commande = PiecesCommande.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pieces_commande }\n end\n end", "def new\n @estagiarios = Estagiario.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @estagiarios }\n end\n end", "def new\n @periodista = Periodista.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @periodista }\n end\n end", "def new\n @partido_politico = PartidoPolitico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @partido_politico }\n end\n end", "def new\n @contrato = Contrato.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @contrato }\n end\n end", "def new\n @tipo_articulo = TipoArticulo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipo_articulo }\n end\n end", "def new\n @receita = Receita.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @receita }\n end\n end", "def new\n @partecipante = Partecipante.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @partecipante }\n end\n end", "def new\n @tipo_pago = TipoPago.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipo_pago }\n end\n end", "def new\n @partenaire = Partenaire.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @partenaire }\n end\n end", "def new\n @partenaire = Partenaire.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @partenaire }\n end\n end", "def new\n @tabela_preco_produto = TabelaPrecoProduto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tabela_preco_produto }\n end\n end", "def new\n @promos = Promos.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @promos }\n end\n end", "def new\n @estudiante = Estudiante.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @estudiante }\n end\n end", "def new\n @convenio = Convenio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @convenio }\n end\n end", "def new\n @node = Node.scopied.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @node }\n end\n end", "def new\n @proffesion = Proffesion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @proffesion }\n end\n end", "def new\n @pais = Pais.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pais }\n end\n end", "def new\n @protocolo = Protocolo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @protocolo }\n end\n end", "def new\n @novidade = Novidade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @novidade }\n end\n end", "def new\n @depositocaucion = Depositocaucion.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @depositocaucion }\n end\n end", "def new\n @tipo_nota = TipoNota.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipo_nota }\n end\n end", "def new\n @pagina = Pagina.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pagina }\n end\n end", "def new\n @proyect = Proyect.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @proyect }\n end\n end", "def new\n @pagare = Pagare.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pagare }\n end\n end", "def new\n @tipo_lista = TipoLista.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipo_lista }\n end\n end", "def new\n @prd_etc = PrdEtc.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prd_etc }\n end\n end", "def new\n @vestimenta = Vestimenta.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vestimenta }\n end\n end", "def new\n @suministro = Suministro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @suministro }\n end\n end", "def new\n @premio = Premio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @premio }\n end\n end", "def new\n @catalog = Catalog.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @catalog }\n end\n end", "def new\n @catalog = Catalog.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @catalog }\n end\n end", "def new\n @coleccionista = Coleccionista.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @coleccionista }\n end\n end", "def new\n @partei = Partei.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @partei }\n end\n end", "def new\n @pagos_detalhe = PagosDetalhe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pagos_detalhe }\n end\n end", "def new\n @titulacionesdoctipo = Titulacionesdoctipo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @titulacionesdoctipo }\n end\n end", "def new\n @cuenta = Cuenta.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @cuenta }\n end\n end", "def new\n @cuenta = Cuenta.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @cuenta }\n end\n end", "def new\n @estatu = Estatu.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @estatu }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end", "def new\n @product = Product.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product }\n end\n end" ]
[ "0.77489555", "0.77489555", "0.77235126", "0.7571242", "0.75583035", "0.74109846", "0.7407102", "0.7346539", "0.73421234", "0.7335259", "0.73333687", "0.73301154", "0.7316158", "0.73159915", "0.73159915", "0.73127204", "0.73124444", "0.7309334", "0.73070246", "0.7294046", "0.72938854", "0.7292422", "0.7286733", "0.7284434", "0.7282717", "0.72825843", "0.7276233", "0.7275196", "0.7267394", "0.72525525", "0.72489035", "0.7235341", "0.72320014", "0.72283334", "0.7221508", "0.7215855", "0.7211635", "0.7204944", "0.72038627", "0.7203628", "0.7200128", "0.71985203", "0.7198093", "0.7191213", "0.7189649", "0.71886784", "0.71883845", "0.7184936", "0.7183152", "0.71763504", "0.7175707", "0.71745735", "0.71717936", "0.7170065", "0.7166977", "0.7165572", "0.7165483", "0.7160991", "0.71574014", "0.7156477", "0.71518403", "0.7151247", "0.7151247", "0.715102", "0.71501356", "0.71497405", "0.71480656", "0.71479666", "0.7147005", "0.7141446", "0.71392125", "0.7137728", "0.7137099", "0.7133446", "0.7131782", "0.7128171", "0.71259713", "0.7117561", "0.7113519", "0.7111948", "0.7111347", "0.71111214", "0.7110393", "0.7110393", "0.71044797", "0.71004134", "0.71000564", "0.7093208", "0.7092181", "0.7092181", "0.70894754", "0.70855206", "0.70855206", "0.70855206", "0.70855206", "0.70855206", "0.70855206", "0.70855206", "0.70855206", "0.70855206" ]
0.7659268
3
POST /produtividades POST /produtividades.xml
def create @produtividade = Produtividade.new(params[:produtividade]) respond_to do |format| if @produtividade.save format.html { redirect_to(@produtividade, :notice => 'Produtividade was successfully created.') } format.xml { render :xml => @produtividade, :status => :created, :location => @produtividade } else format.html { render :action => "new" } format.xml { render :xml => @produtividade.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @produto = Produto.new(params[:produto])\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to(@produto, :notice => 'Produto was successfully created.') }\n format.xml { render :xml => @produto, :status => :created, :location => @produto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(params[:produto])\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to(@produto, :notice => 'Produto was successfully created.') }\n format.xml { render :xml => @produto, :status => :created, :location => @produto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(params[:produto])\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to(@produto, :notice => 'Produto salvo com sucesso.') }\n format.xml { render :xml => @produto, :status => :created, :location => @produto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.create(produto_params)\n respond_with @produto\n end", "def create\n @selecciones = Seleccion.where(\"cliente_id = ?\",usuario_actual.id)\n @peso_total = Seleccion.peso_total(usuario_actual.id)\n @precio_total = Seleccion.precio_total(usuario_actual.id)\n @tarjetas = usuario_actual.tdc\n \n #Cobro en el banco\n client = Savon::Client.new(\"http://localhost:3001/servicios/wsdl\")\n tdc = Tarjeta.where(\"id = ? AND cliente_id = ?\",params[:orden][:tarjeta_id],usuario_actual.id)\n total_pagar = params[:orden][:total]\n pago = '<Message>\n <Request>\n <numero_tdc>'+tdc.numero+'</numero_tdc>\n <nombre_tarjetahabiente>'+tdc.tarjetahabiente+'</nombre_tarjetahabiente>\n <fecha_vencimiento>'+tdc.mes_vencimiento+'/'+tdc.ano_vencimiento+'</fecha_vencimiento>\n <codigo_seguridad>'+tdc.codigo+'</codigo_seguridad>\n <tipo_tarjeta>'+tdc.tipo+'</tipo_tarjeta>\n <direccion_cobro>'+tdc.direccion+'</direccion_cobro>\n <total_pagar>'+total_pagar+'</total_pagar>\n <cuenta_receptora>'+cuenta_receptora+'</cuenta_receptora>\n </Request>\n </Message>'\n #response = client.request :verificar_pago, body: { \"value\" => pago } \n #if response.success?\n # data = response.to_hash[:verificar_pago_response][:value][:response].first\n # @respuesta = XmlSimple.xml_in(data)\n #end\n\n #NAMESPACE = 'pagotdc'\n #URL = 'http://localhost:8080/'\n #banco = SOAP::RPC::Driver.new(URL, NAMESPACE)\n #banco.add_method('verificar_pago', 'numero_tdc', 'nombre_tarjetahabiente', 'fecha_vencimiento', 'codigo_seguridad', 'tipo_tarjeta', 'direccion_cobro', 'total_pagar', 'cuenta_receptora')\n #\n \n #respuesta = banco.verificar_pago(tdc.numero, tdc.tarjetahabiente, tdc.mes_vencimiento.to_s+'/'+tdc.ano_vencimiento.to_s, tdc.codigo, tdc.tipo, params[:orden][:total], tdc.direccion)\n \n if true #respuesta.ack.eql?(0)\n params[:orden][:cliente_id] = usuario_actual.id\n params[:orden][:total] = Seleccion.precio_total(usuario_actual.id)\n params[:orden][:fecha_entrega] = \"0000-00-00\"\n @orden = Orden.new(params[:orden])\n \n if @orden.save\n @selecciones = Seleccion.where(\"cliente_id = ?\",usuario_actual.id)\n @selecciones.each do |seleccion|\n p = Producto.find(seleccion.producto_id)\n @venta = Venta.new(:producto_id=>p.id, \n :orden_id=>@orden.id,\n :categoria_id=>p.categoria_id, \n :cantidad=>seleccion.cantidad,\n :costo=>p.precio)\n @venta.save\n end\n \n Seleccion.vaciar_carro(usuario_actual.id)\n respond_to do |format|\n format.html { redirect_to ver_ordenes_path, notice: 'Orden generada correctamente.' }\n end\n else\n respond_to do |format|\n format.html { render action: \"new\" }\n end\n end\n else\n respond_to do |format|\n format.html { render action: \"new\", notice: respuesta.mensaje }\n end\n end\n end", "def create\n @deposits_product = DepositsProduct.new(deposits_product_params)\n\n respond_to do |format|\n if @deposits_product.save\n format.html { redirect_to @deposits_product, notice: 'Deposits product was successfully created.' }\n format.json { render :show, status: :created, location: @deposits_product }\n else\n format.html { render :new }\n format.json { render json: @deposits_product.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @produto = ProdutoSimples.new(params[:produto_simples])\n respond_to do |format|\n if @produto.save\n flash[:notice] = \"Produto criado com sucesso.\"\n format.html { redirect_to(admin_produtos_path) }\n format.xml { render :xml => @produto, :status => :created, :location => @produto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @pedido_produto = PedidoProduto.new(pedido_produto_params)\n @pedido_produto.pedido = @pedido\n\n respond_to do |format|\n if @pedido_produto.save\n format.html { redirect_to pedido_pedido_produtos_path(@pedido), notice: 'Pedido produto was successfully created.' }\n format.json { render :show, status: :created, location: @pedido_produto }\n else\n format.html { render :new }\n format.json { render json: @pedido_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entrada_produto = EntradaProduto.new(entrada_produto_params)\n\n respond_to do |format|\n if @entrada_produto.save\n format.html { redirect_to @entrada_produto, notice: 'Entrada produto was successfully created.' }\n format.json { render :show, status: :created, location: @entrada_produto }\n else\n format.html { render :new }\n format.json { render json: @entrada_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @estagiarios = Estagiario.new(params[:estagiario])\n\n respond_to do |format|\n if @estagiarios.save\n flash[:notice] = 'ESTAGIÁRIO CADASTRADO COM SUCESSO.'\n format.html { redirect_to(@estagiarios) }\n format.xml { render :xml => @estagiarios, :status => :created, :location => @estagiarios }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @estagiarios.errors, :status => :unprocessable_entity }\n end\n end\n end", "def post(resource, params)\n case resource\n when \"pedidos\", \"place_order\", \"new_order\" then url = \"/pedidos\"\n when \"envios\", \"shipping\" then url = \"/envios\"\n else url = \"/#{resource}\"\n end\n\n post_request(url, params)\n end", "def create\n @produto = Produto.new(params[:produto])\n @produto.empresa = session[:usuario].empresa\n \n params[:produto][:preco_compra] = converte_valor_banco params[:produto][:preco_compra]\n params[:produto][:preco_venda] = converte_valor_banco params[:produto][:preco_venda]\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to @produto, notice: 'Produto was successfully created.' }\n format.json { render json: @produto, status: :created, location: @produto }\n else\n format.html { render action: \"new\" }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @departamentos = Departamento.new(params[:departamento])\n\n respond_to do |format|\n if @departamentos.save\n flash[:notice] = 'DEPARTAMENTO CADASTRADO COM SUCESSO.'\n format.html { redirect_to(new_departamento_path) }\n format.xml { render :xml => @departamentos, :status => :created, :location => @departamentos }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @departamentos.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @entidad = Entidad.new(params[:entidad])\n\n respond_to do |format|\n if @entidad.save\n format.html { redirect_to(@entidad, :notice => 'Entidad was successfully created.') }\n format.xml { render :xml => @entidad, :status => :created, :location => @entidad }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @entidad.errors, :status => :unprocessable_entity }\n end\n end\n end", "def entrada_produto_params\n params.require(:entrada_produto).permit(:data, :utilizador, :itemProduto_id, :fornecedor_id)\n end", "def create\n\n\t\t@produt = Produt.new(params[:produt])\n\t\trespond_to do |format|\n\t\t\tif @produt.save\n\t\t\t\tformat.html {redirect_to(@produt, :notice => 'Registro incluído com Sucesso!')}\n\t\t\t\tformat.xml {render :xml => @produt, :status => :created, :location => @produt}\n\t\t\telse\n\t\t\t\tformat.html {render :action => \"new\"}\n\t\t\t\tformat.xml {render :xml => @produt.erros, :status => :unprocessable_entity }\n\t\t\tend\t\t\n\t\tend\n\tend", "def new\n \n @selecciones = Seleccion.where(\"cliente_id = ?\",usuario_actual.id)\n respond_to do |format|\n unless @selecciones.empty?\n @peso_total = Seleccion.peso_total(usuario_actual.id)\n @precio_total = Seleccion.precio_total(usuario_actual.id)\n @tarjetas = usuario_actual.tdc\n @orden = Orden.new(:direccion_entrega=>usuario_actual.direccion)\n t = Time.now\n fecha = t.strftime(\"%Y-%m-%d\")\n client = Savon::Client.new(\"http://192.168.1.121/DistribuidorFIF/webservices/servicio.php?wsdl\")\n preorden = \"<solicitud_pedido>\n <num_orden>001</num_orden>\n <nombre_comercio>Tukiosquito</nombre_comercio>\n <fecha_solicitud>\"+fecha.to_s+\"</fecha_solicitud>\n <nombre_cliente>\"+usuario_actual.nombre+\" \"+usuario_actual.apellido+\"</nombre_cliente>\n <direccion_comercio>\n <avenida>Sucre</avenida>\n <calle>-</calle>\n <edificio_casa>CC Millenium</edificio_casa>\n <local_apt>C1-15</local_apt>\n <parroquia>Leoncio Martinez</parroquia>\n <municipio>Sucre</municipio>\n <ciudad>Caracas</ciudad>\n <estado>Miranda</estado>\n <pais>Venezuela</pais>\n </direccion_comercio>\n <direccion_destino>\n <avenida>Santa Rosa</avenida>\n <calle>Tierras Rojas</calle>\n <edificio_casa>Villa Magica</edificio_casa>\n <local_apt>69</local_apt>\n <parroquia> </parroquia>\n <municipio>Zamora</municipio>\n <ciudad>Cua</ciudad>\n <estado>Miranda</estado>\n <pais>Venezuela</pais>\n </direccion_destino>\"\n @selecciones.each do |seleccion|\n p = Producto.find(seleccion.producto_id)\n preorden = preorden+\"\n <articulo>\n <id>\"+p.id.to_s+\"</id>\n <descripcion>\"+p.descripcion+\"</descripcion>\n <peso>\"+p.peso.to_s+\"</peso>\n <cantidad>\"+seleccion.cantidad.to_s+\"</cantidad>\n <precio>\"+p.precio.to_s+\"</precio>\n </articulo>\"\n end\n preorden = preorden+\"</solicitud_pedido>\"\n response = client.request :ejemplo, body: { \"value\" => preorden } \n if response.success? \n respuesta = response.to_hash[:ejemplo_response][:return]\n datos = XmlSimple.xml_in(respuesta)\n end\n\n @precio_envio = datos[\"num_orden\"][0]\n #@arreglo = XmlSimple.xml_in('')\n #@xml = XmlSimple.xml_out(@arreglo, { 'RootName' => 'solicitud_pedido' })\n #url = 'http://192.168.1.101/Antonio/tukyosquito/proyecto/servicio/servicio.php'\n #cotizacion = SOAP::RPC::Driver.new(url)\n #cotizacion.add_method('obtener','asd')\n #tdc = Tarjeta.where(\"id = ? AND cliente_id = ?\",params[:orden][:tarjeta_id],usuario_actual.id)\n #@respuesta = cotizacion.obtener('123')\n format.html # new.html.erb\n else\n format.html { redirect_to carrito_path, notice: 'No tiene productos agregados al carro de compras para generar una orden.' }\n end\n end\n end", "def create\n @adjunto = Adjunto.new(params[:adjunto])\n\n respond_to do |format|\n if @adjunto.save\n format.html { redirect_to(@adjunto, :notice => 'Adjunto was successfully created.') }\n format.xml { render :xml => @adjunto, :status => :created, :location => @adjunto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @adjunto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(produto_params)\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to @produto, notice: 'Produto was successfully created.' }\n format.json { render :show, status: :created, location: @produto }\n else\n format.html { render :new }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(produto_params)\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to @produto, notice: 'Produto was successfully created.' }\n format.json { render :show, status: :created, location: @produto }\n else\n format.html { render :new }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(produto_params)\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to @produto, notice: 'Produto was successfully created.' }\n format.json { render :show, status: :created, location: @produto }\n else\n format.html { render :new }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entidade = Entidade.new(params[:entidade])\n\n respond_to do |format|\n if @entidade.save\n format.html { redirect_to(@entidade, :notice => 'Entidade cadastrado com sucesso.') }\n format.xml { render :xml => @entidade, :status => :created, :location => @entidade }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @entidade.errors, :status => :unprocessable_entity }\n end\n end\n end", "def post_to_newgistics\n document = Spree::Newgistics::DocumentBuilder.build_product([self])\n response = Spree::Newgistics::HTTPManager.post('/post_products.aspx', document)\n\n if response.status == 200\n errors = Nokogiri::XML(response.body).css('errors').children.any?\n update_column(:posted_to_newgistics, true) unless errors\n end\n\n end", "def create\n @prod_servi = ProdServi.new(prod_servi_params)\n\n respond_to do |format|\n if @prod_servi.save\n format.html { redirect_to @prod_servi, notice: 'Prod servi was successfully created.' }\n format.json { render :show, status: :created, location: @prod_servi }\n else\n format.html { render :new }\n format.json { render json: @prod_servi.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @proceso = Proceso.new(params[:proceso])\n\n respond_to do |format|\n if @proceso.save\n format.html { redirect_to(@proceso, :notice => 'Proceso was successfully created.') }\n format.xml { render :xml => @proceso, :status => :created, :location => @proceso }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @proceso.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(produto_params)\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to @produto, notice: t('.sucesso') }\n format.json { render :show, status: :created, location: @produto }\n else\n format.html { render :new }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(params[:produto])\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to @produto, notice: 'Produto was successfully created.' }\n format.json { render json: @produto, status: :created, location: @produto }\n else\n format.html { render action: \"new\" }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n params[:adm_produto][:perc_comissao] = params[:adm_produto][:perc_comissao].to_f / 100.0 # deixando na forma percentual correta\n @adm_produto = Adm::Produto.new(params[:adm_produto])\n respond_to do |format|\n if @adm_produto.save\n grava_categoria(params[:categorias], @adm_produto)\n logProduto(request.remote_ip, @adm_produto.id, session[:usuario].id, \"Novo produto criado\")\n format.html { redirect_to(:adm_produtos, :notice => 'Produto criado com sucesso') }\n format.xml { render :xml => @adm_produto, :status => :created, :location => @adm_produto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @adm_produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @resultadoconsultum = Resultadoconsultum.new(resultadoconsultum_params)\n\t\n\n\trequire 'nokogiri'\n\t\n\t@doc = Nokogiri::XML(File.open(\"exemplos/emplo.xml\"))\n\n\tcar_tires = @doc.xpath(\"//firstname\")\n\t\n\tdoc = Nokogiri::XML(File.open(\"emplo.xml\"))\n\tdoc.xpath('firstname').each do\n\t\tcar_tires\n\tend\n\n\t \n respond_to do |format|\n if @resultadoconsultum.save\n format.html { redirect_to @resultadoconsultum, notice: car_tires }\n format.json { render :show, status: :created, location: @resultadoconsultum }\n else\n format.html { render :new }\n format.json { render json: @resultadoconsultum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @paciente = Paciente.new(params[:paciente])\n\n respond_to do |format|\n if @paciente.save\n format.html { redirect_to(@paciente, :notice => 'El Paciente se creo exitosamente.') }\n format.xml { render :xml => @paciente, :status => :created, :location => @paciente }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @paciente.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @estado_pedido = EstadoPedido.new(params[:estado_pedido])\n\n respond_to do |format|\n if @estado_pedido.save\n format.html { redirect_to(@estado_pedido, :notice => 'EstadoPedido was successfully created.') }\n format.xml { render :xml => @estado_pedido, :status => :created, :location => @estado_pedido }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @estado_pedido.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @estado_producto = EstadoProducto.new(estado_producto_params)\n\n respond_to do |format|\n if @estado_producto.save\n format.html { redirect_to @estado_producto, notice: 'Estado producto was successfully created.' }\n format.json { render :show, status: :created, location: @estado_producto }\n else\n format.html { render :new }\n format.json { render json: @estado_producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @produto = Produto.new(produto_params)\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to edit_produto_path(@produto), notice: 'Produto was successfully created.' }\n format.json { render :show, status: :created, location: @produto }\n else\n format.html { render :new }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n doc = Nokogiri::XML(request.body.read)\n cvNode = doc.xpath('elwak/checklisten_vorlage')\n cv = ChecklistenVorlage.new({\n objekt_id: cvNode.xpath('objekt_id').text.to_s, \n bezeichner: cvNode.xpath('bezeichner').text.to_s, \n version: cvNode.xpath('version').text.to_s.to_i, \n inaktiv: cvNode.xpath('inaktiv').text.to_s.to_bool \n })\n cv.save\n\n cvNode.xpath('checklisten_eintrags/checklisten_eintrag').each do |ceNode|\n ce = ChecklistenEintrag.new({\n checklisten_vorlage_id: cv.id,\n bezeichner: ceNode.xpath('bezeichner').text.to_s,\n was: ceNode.xpath('was').text.to_s,\n wann: ceNode.xpath('wann').text.to_s,\n typ: ceNode.xpath('typ').text.to_s.to_i,\n position: ceNode.xpath('position').text.to_s.to_i\n })\n ce.save\n end\n\n respond_to do |format|\n format.xml {render :xml => '<?xml version=\"1.0\" encoding=\"UTF-8\"?><success />'}\n end\n end", "def create\n @actividad = Actividad.new(params[:actividad])\n respond_to do |format|\n if @actividad.save \n @actividad.visitadors.each do |v|\n pu = PuntuacionesActividad.new(:actividad_id => @actividad.id, :visitador_id => v.id, :puntuacion => @actividad.puntuacion)\n pu.save\n end\n format.html { redirect_to @actividad, notice: 'Actividad was successfully created.' }\n format.json { render json: @actividad, status: :created, location: @actividad }\n else\n format.html { render action: \"new\" }\n format.json { render json: @actividad.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(xmldoc)\n headers = {'Content-Type' => 'text/xml'}\n check_response( @httpcli.post(@endpoint, xmldoc, headers) )\n end", "def create\n @producto_detalle = ProductoDetalle.new(producto_detalle_params)\n\n respond_to do |format|\n if @producto_detalle.save\n format.html { redirect_to @producto_detalle, notice: 'Producto detalle was successfully created.' }\n format.json { render :show, status: :created, location: @producto_detalle }\n else\n format.html { render :new }\n format.json { render json: @producto_detalle.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @estudiante = Estudiante.new(params[:estudiante])\n\n respond_to do |format|\n if @estudiante.save\n flash[:notice] = 'Creado.'\n format.html { redirect_to(@estudiante) }\n format.xml { render :xml => @estudiante, :status => :created, :location => @estudiante }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @estudiante.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @partenaire = Partenaire.new(params[:partenaire])\n\n respond_to do |format|\n if @partenaire.save\n flash[:notice] = I18n.t(:successfully_added_partner)\n format.html { redirect_to(partenaires_path()) }\n format.xml { render :xml => @partenaire, :status => :created, :location => @partenaire }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @partenaire.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @comunidade = Comunidade.new(params[:comunidade])\n\n respond_to do |format|\n if @comunidade.save\n flash[:notice] = 'Comunidade was successfully created.'\n format.html { redirect_to(@comunidade) }\n format.xml { render :xml => @comunidade, :status => :created, :location => @comunidade }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @comunidade.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @puesto = Puesto.new(params[:puesto])\n\n respond_to do |format|\n if @puesto.save\n flash[:notice] = 'Puesto was successfully created.'\n format.html { redirect_to(@puesto) }\n format.xml { render :xml => @puesto, :status => :created, :location => @puesto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @puesto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @pagina = Pagina.new(pagina_params)\n @pagina.produto = @produto\n\n respond_to do |format|\n if @pagina.save\n format.html { redirect_to edit_produto_pagina_path(@produto, @pagina), notice: 'Pagina was successfully created.' }\n format.json { render :show, status: :created, location: @pagina }\n else\n format.html { render :new }\n format.json { render json: @pagina.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @depositocaucion = Depositocaucion.new(@depositocaucionnuevo)\n respond_to do |format|\n if @depositocaucion.save\n flash[:notice] = 'Depositocaucion was successfully created.'\n format.html { redirect_to(@depositocaucion) }\n format.xml { render :xml => @depositocaucion, :status => :created, :location => @depositocaucion }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @depositocaucion.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @espacio_deportivo = EspacioDeportivo.new(params[:espacio_deportivo])\n\n respond_to do |format|\n if @espacio_deportivo.save\n format.html { redirect_to root_url, :notice => \"Se hizo correctamente la creacion del espacio deportivo\" }\n format.json { render json: @espacio_deportivo, status: :created, location: @espacio_deportivo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @espacio_deportivo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @producte_dapcons_usuari = ProducteDapconsUsuari.new(producte_dapcons_usuari_params)\n\n respond_to do |format|\n if @producte_dapcons_usuari.save\n format.html { redirect_to producte_dapcons_usuaris_path, notice: 'Producte dapcons usuari was successfully created.' }\n format.json { render :show, status: :created, location: @producte_dapcons_usuari }\n else\n format.html { render :new }\n format.json { render json: @producte_dapcons_usuari.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_orcamento\n @produto = Produto.new(produto_params)\n\n respond_to do |format|\n if @produto.save\n format.html { redirect_to edit_produto_path(@produto), notice: '' }\n format.json { render :show, status: :created, location: @produto }\n else\n format.html { render :new }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def produto_params\n params.require(:produto).permit(:categoria_id, :nome, :descricao, :precocompra, :precovenda, :estoque)\n end", "def create\n @saida_produto = SaidaProduto.new(saida_produto_params)\n\n respond_to do |format|\n if @saida_produto.save\n format.html { redirect_to @saida_produto, notice: 'Saida produto was successfully created.' }\n format.json { render :show, status: :created, location: @saida_produto }\n else\n format.html { render :new }\n format.json { render json: @saida_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @productos_por_cliente = ProductosPorCliente.new(productos_por_cliente_params)\n\n respond_to do |format|\n if @productos_por_cliente.save\n format.html { redirect_to @productos_por_cliente, notice: 'Productos por cliente was successfully created.' }\n format.json { render :show, status: :created, location: @productos_por_cliente }\n else\n format.html { render :new }\n format.json { render json: @productos_por_cliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @estudiante = Estudiante.new(params[:estudiante])\n\n respond_to do |format|\n if @estudiante.save\n format.html { redirect_to(@estudiante, :notice => 'Estudiante was successfully created.') }\n format.xml { render :xml => @estudiante, :status => :created, :location => @estudiante }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @estudiante.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @paciente = Paciente.find(params[:paciente_id])\n @visita = Visita.new(params[:visita])\n @visita.paciente = @paciente\n\n respond_to do |format|\n if @visita.save\n format.html { redirect_to(paciente_visitas_url, :notice => 'La Visita se creo exitosamente.') }\n format.xml { render :xml => @visita, :status => :created, :location => @visita }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @visita.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\r\n @doctipo = Doctipo.new(params[:doctipo])\r\n \r\n\r\n respond_to do |format|\r\n if @doctipo.save\r\n \r\n flash[:notice] = 'EL tipo d edocumento fue creado exitosamente.'\r\n format.html { redirect_to(flash[:back] || @doctipo) }\r\n format.xml { render :xml => @doctipo, :status => :created, :location => @doctipo }\r\n\r\n else\r\n format.html { render :action => \"new\" }\r\n format.xml { render :xml => @doctipo.errors, :status => :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @troca_produto = TrocaProduto.new(troca_produto_params)\n\n respond_to do |format|\n if @troca_produto.save\n format.html { redirect_to @troca_produto, notice: \"Troca produto was successfully created.\" }\n format.json { render :show, status: :created, location: @troca_produto }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @troca_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @puestos_entidad = PuestosEntidad.new(params[:puestos_entidad])\n\n respond_to do |format|\n if @puestos_entidad.save\n format.html { redirect_to @puestos_entidad, notice: 'Puestos entidad was successfully created.' }\n format.json { render json: @puestos_entidad, status: :created, location: @puestos_entidad }\n else\n format.html { render action: \"new\" }\n format.json { render json: @puestos_entidad.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @solicitacao = Solicitacao.new(solicitacao_params)\n\n respond_to do |format|\n if @solicitacao.save\n @solicitacao.produto_solicitados.each do |item|\n i = Produto.find(item.produto_id)\n i.quantidade = i.quantidade - item.quantidade\n i.save\n end\n format.html { redirect_to @solicitacao, notice: 'Solicitacao was successfully created.' }\n format.json { render action: 'show', status: :created, location: @solicitacao }\n else\n format.html { render action: 'new' }\n format.json { render json: @solicitacao.errors, status: :unprocessable_entity }\n end\n end\n end", "def produto_params\n params.require(:produto).permit(:nome, :principioativo, :laboratorio, :concentracao, :formafarmaceutica, :tipoproduto_id)\n end", "def create\n @unidades = Unidade.new(params[:unidade])\n respond_to do |format|\n if @unidades.save\n flash[:notice] = 'UNIDADE CADASTRADA COM SUCESSO.'\n format.html { redirect_to(@unidades) }\n format.xml { render :xml => @unidades, :status => :created, :location => @unidades }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @unidades.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @estagio = Estagio.new(params[:estagio])\n\n respond_to do |format|\n if @estagio.save\n flash[:notice] = 'Estagio was successfully created.'\n format.html { redirect_to(@estagio) }\n format.xml { render :xml => @estagio, :status => :created, :location => @estagio }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @estagio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def produto_params\n params.require(:produto).permit(:tipo, :codigo, :descricao, :marca_id, :modelo, :vl_custo, :vl_venda, :unidade, :categoria_pai_id, :categoria_id, :estoque_id, :ean, :ncm, :created_by, :updated_by)\n end", "def create\n @inventario_producto = Inventario::Producto.new(inventario_producto_params)\n\n respond_to do |format|\n if @inventario_producto.save\n format.html { redirect_to @inventario_producto, notice: 'Producto was successfully created.' }\n format.json { render :show, status: :created, location: @inventario_producto }\n else\n format.html { render :new }\n format.json { render json: @inventario_producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @service_order = ServiceOrder.new(service_order_params)\n @products = params[:inputprod]\n @quantity = params[:inputcantidad]\n #@cita_id = Citation.where(:id => params[:citation_id])\n \n respond_to do |format|\n if @service_order.save\n cont =0\n @products.each do |p|\n detalle = ServiceOrderDetail.new(product_id: p, quantity: @quantity[cont], service_order_id:@service_order.id)\n detalle.save\n cont +=1\n end\n \n format.html { redirect_to @service_order, notice: 'Service order was successfully created.' }\n format.json { render :show, status: :created, location: @service_order }\n else\n format.html { render :new }\n format.json { render json: @service_order.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n\t\t@departamento = Departamento.new(params[:departamento])\n\t\trespond_to do |format|\n\t\t\tif @departamento.save\n\t\t\t\tformat.html {redirect_to(@departamento, :notice => 'Registro incluído com Sucesso!')}\n\t\t\t\tformat.xml {render :xml => @departamento, :status => :created, :location => @departamento}\n\t\t\telse\n\t\t\t\tformat.html {render :action => \"new\"}\n\t\t\t\tformat.xml {render :xml => @departamento.erros, :status => :unprocessable_entity }\n\t\t\tend\t\t\n\t\tend\n\tend", "def create\n\n respond_to do |format|\n if @especialidad.save\n format.html { redirect_to @especialidad, notice: 'Servicio creado exitosamente.' }\n format.json { render :show, status: :created, location: @especialidad }\n else\n format.html { render :new }\n format.json { render json: @especialidad.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @competencia = Competencia.new(params[:competencia])\n\n respond_to do |format|\n if @competencia.save\n format.html { redirect_to(@competencia, :notice => 'Competencia ha sido creada satisfactoriamente.') }\n format.xml { render :xml => @competencia, :status => :created, :location => @competencia }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @competencia.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @tiposproceso = Tiposproceso.new(params[:tiposproceso])\n\n respond_to do |format|\n if @tiposproceso.save\n format.html { redirect_to(@tiposproceso, :notice => 'Tiposproceso was successfully created.') }\n format.xml { render :xml => @tiposproceso, :status => :created, :location => @tiposproceso }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @tiposproceso.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @comanda_produto = ComandaProduto.new(comanda_produto_params)\n\n respond_to do |format|\n if @comanda_produto.save\n format.html { redirect_to @comanda_produto, notice: 'Item adicionado com sucesso.' }\n format.json { render :show, status: :created, location: @comanda_produto }\n else\n format.html { render :new }\n format.json { render json: @comanda_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @unidad = Unidad.new(params[:unidad])\n p params[:unidad]\n \n respond_to do |format|\n if @unidad.save\n flash[:notice] = 'Unidad was successfully created.'\n format.html { redirect_to(@unidad) }\n format.xml { render :xml => @unidad, :status => :created, :location => @unidad }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @unidad.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @valor_sistema = ValorSistema.new(params[:valor_sistema])\n\n respond_to do |format|\n if @valor_sistema.save\n flash[:notice] = 'ValorSistema was successfully created.'\n format.html { redirect_to(@valor_sistema) }\n format.xml { render :xml => @valor_sistema, :status => :created, :location => @valor_sistema }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @valor_sistema.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @regiaos = Regiao.new(params[:regiao])\n\n respond_to do |format|\n if @regiaos.save\n flash[:notice] = 'REGIÃO SALVA COM SUCESSO'\n format.html { redirect_to(new_regiao_path)}\n format.xml { render :xml => @regiaos, :status => :created, :location => @regiaos }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @regiaos.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @pedido = Pedido.new(params[:pedido])\n\n respond_to do |format|\n if @pedido.save\n #obtiene una instancia del Itempedido\n @item = @pedido.itempedidos.new(params[:itempedido])\n #obtiene una instancia de autorizacion para guardar un registro\n #del estado del pedido en PENDIENTE\n @autorizacion = @pedido.autorizacions.new(params[:autorizacion])\n if @item.save && @autorizacion.save\n format.html { redirect_to(@pedido, :notice => 'PEDIDO FUE REGISTRADO EXITOSAMENTE') }\n format.xml { render :xml => @pedido, :status => :created, :location => @pedido }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @pedido.errors, :status => :unprocessable_entity }\n end\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @pedido.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @producto_seccion = ProductoSeccion.new(producto_seccion_params)\n\n respond_to do |format|\n if @producto_seccion.save\n format.html { redirect_to @producto_seccion, notice: 'Producto seccion was successfully created.' }\n format.json { render :show, status: :created, location: @producto_seccion }\n else\n format.html { render :new }\n format.json { render json: @producto_seccion.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @objeto = DetallePedido.new(detalle_pedido_params)\n\n respond_to do |format|\n if @objeto.save\n set_redireccion\n format.html { redirect_to @redireccion, notice: 'Detalle pedido was successfully created.' }\n format.json { render :show, status: :created, location: @objeto }\n else\n format.html { render :new }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @campanha_produto = CampanhaProduto.new(params[:campanha_produto])\n\n respond_to do |format|\n if @campanha_produto.save\n flash[:notice] = 'CampanhaProduto was successfully created.'\n format.html { redirect_to(@campanha_produto) }\n format.xml { render :xml => @campanha_produto, :status => :created, :location => @campanha_produto }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @campanha_produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @requisicion = Requisicion.new(params[:requisicion])\n\n respond_to do |format|\n if @requisicion.save\n format.html { redirect_to(@requisicion, :notice => 'Requisicion was successfully created.') }\n format.xml { render :xml => @requisicion, :status => :created, :location => @requisicion }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @requisicion.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n params[:estacionamiento][:id_proveedor]=session['user']['id']\n @estacionamiento = Estacionamiento.new(estacionamiento_params)\n\n respond_to do |format|\n if @estacionamiento.save\n format.html { redirect_to @estacionamiento, notice: 'Estacionamiento was successfully created.' }\n format.json { render :show, status: :created, location: @estacionamiento }\n else\n format.html { render :new }\n format.json { render json: @estacionamiento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @prod_coti = ProdCoti.new(prod_coti_params)\n\n respond_to do |format|\n if @prod_coti.save\n format.html { redirect_to @prod_coti, notice: 'Prod coti was successfully created.' }\n format.json { render :show, status: :created, location: @prod_coti }\n else\n format.html { render :new }\n format.json { render json: @prod_coti.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @producto_padre = ProductoPadre.new(producto_padre_params)\r\n\r\n respond_to do |format|\r\n if @producto_padre.save\r\n format.html { redirect_to producto_padres_path, notice: 'Producto padre creado.' }\r\n format.json { render :show, status: :created, location: @producto_padre }\r\n else\r\n format.html { render :new }\r\n format.json { render json: @producto_padre.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def pedido_produto_params\n params.require(:pedido_produto).permit(:pedido_id, :produto_id, :valor, :quantidade)\n end", "def create\n @tipo_de_documento = TipoDeDocumento.new(params[:tipo_de_documento])\n\n respond_to do |format|\n if @tipo_de_documento.save\n format.html { redirect_to(@tipo_de_documento, :notice => 'Tipo de documento cadastrado com sucesso.') }\n format.xml { render :xml => @tipo_de_documento, :status => :created, :location => @tipo_de_documento }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @tipo_de_documento.errors, :status => :unprocessable_entity }\n end\n end\n end", "def deposits_product_params\n params.require(:deposits_product).permit(:cantidad,:deposit_id,:product_id,:precio)\n end", "def create\n @com_articulo = ComArticulo.new(com_articulo_params)\n\n respond_to do |format|\n if @com_articulo.save\n format.html { redirect_to @com_articulo, notice: 'Producto creado correctamente.' }\n format.json { render :show, status: :created, location: @com_articulo }\n else\n format.html { render :new }\n format.json { render json: @com_articulo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @estatu = Estatu.new(params[:estatu])\n\n respond_to do |format|\n if @estatu.save\n format.html { redirect_to(@estatu, :notice => 'Registro creado correctamente.') }\n format.xml { render :xml => @estatu, :status => :created, :location => @estatu }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @estatu.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @asiento_de_servicio = AsientoDeServicio.new(asiento_de_servicio_params)\n\n respond_to do |format|\n if @asiento_de_servicio.save\n format.html { redirect_to @asiento_de_servicio, notice: 'Asiento de servicio was successfully created.' }\n format.json { render :show, status: :created, location: @asiento_de_servicio }\n else\n format.html { render :new }\n format.json { render json: @asiento_de_servicio.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @product = Product.new(params[:product])\n\n respond_to do |format|\n if @product.save\n format.html { redirect_to(@product, :notice => 'Produto criado com sucesso.') }\n format.xml { render :xml => @product, :status => :created, :location => @product }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @product.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @precio = Precio.new(params[:precio])\n\n respond_to do |format|\n if @precio.save\n format.html { redirect_to(@precio, :notice => 'Precio was successfully created.') }\n format.xml { render :xml => @precio, :status => :created, :location => @precio }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @precio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @producto = Producto.new(producto_params)\n respond_to do |format|\n if @producto.save\n format.html { redirect_to @producto, notice: 'Producto creado exitosamente.' }\n format.json { render :show, status: :created, location: @producto }\n else\n format.html { render :new }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @producto = Producto.new(producto_params)\n respond_to do |format|\n if @producto.save\n format.html { redirect_to @producto, notice: 'Producto creado exitosamente.' }\n format.json { render :show, status: :created, location: @producto }\n else\n format.html { render :new }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pedido = Pedido.new(pedido_params)\n @pedido.pedido_hash = get_pedido_hash\n @pedido.estado_actual = PEDIDO_SOLICITADO\n\n #redirect_to '/pedidos'\n respond_to do |format|\n if @pedido.save\n\n params[:item_cantidad].each do |a, b|\n newitem_pedido = ItemPedido.new\n newitem_pedido.cantidad = b\n newitem_pedido.item_id = a\n item = Item.find(a)\n newitem_pedido.nombre = item.nombre\n newitem_pedido.valor = ItemProveedor.find_by_item_id_and_proveedor_id(item.id,Categorium.find(item.categorium_id).proveedor_id).precio\n newitem_pedido.pedido_id = @pedido.id\n newitem_pedido.estado_actual = ITEM_SOLICITADO\n newitem_pedido.proveedor_id = Categorium.find(item.categorium_id).proveedor_id\n newitem_pedido.disponible = true\n newitem_pedido.save\n\n end\n format.html { redirect_to @pedido, notice: 'Pedido was successfully created.' }\n format.json { render :show, status: :created, location: @pedido }\n else\n format.html { render :new }\n format.json { render json: @pedido.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tipo_proy = TipoProy.new(params[:tipo_proy])\n\n respond_to do |format|\n if @tipo_proy.save\n flash[:notice] = 'TipoProy was successfully created.'\n format.html { redirect_to(@tipo_proy) }\n format.xml { render :xml => @tipo_proy, :status => :created, :location => @tipo_proy }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @tipo_proy.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @anteproyecto_estudiante = AnteproyectoEstudiante.new(anteproyecto_estudiante_params)\n\n respond_to do |format|\n if @anteproyecto_estudiante.save\n format.html { redirect_to @anteproyecto_estudiante, notice: 'Anteproyecto estudiante was successfully created.' }\n format.json { render :show, status: :created, location: @anteproyecto_estudiante }\n else\n format.html { render :new }\n format.json { render json: @anteproyecto_estudiante.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @relacao_produto = RelacaoProduto.new(relacao_produto_params)\n\n respond_to do |format|\n if @relacao_produto.save\n format.html { redirect_to @relacao_produto, notice: 'Relacao produto was successfully created.' }\n format.json { render :show, status: :created, location: @relacao_produto }\n else\n format.html { render :new }\n format.json { render json: @relacao_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @factura = @cliente.facturas.build(params[:factura])\n\n respond_to do |format|\n if @factura.save\n format.html { redirect_to([@cliente, @factura], :notice => t('flash.actions.create.notice', :resource_name => Factura.model_name.human)) }\n format.xml { render :xml => @factura, :status => :created, :location => [@cliente, @factura] }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @factura.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @unidade = Unidade.new(params[:unidade])\n\n respond_to do |format|\n if @unidade.save\n flash[:notice] = 'Unidade cadastrada com sucesso.'\n format.html { redirect_to(@unidade) }\n format.xml { render :xml => @unidade, :status => :created, :location => @unidade }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @unidade.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @produtividade = Produtividade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @produtividade }\n end\n end", "def create\n @partenaire = Partenaire.new(params[:partenaire])\n\n respond_to do |format|\n if @partenaire.save\n flash[:notice] = 'Partenaire was successfully created.'\n format.html { redirect_to(@partenaire) }\n format.xml { render :xml => @partenaire, :status => :created, :location => @partenaire }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @partenaire.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @depoevento = Depoevento.new(params[:depoevento])\n\n respond_to do |format|\n if @depoevento.save\n format.html { redirect_to @depoevento, notice: 'Depoevento was successfully created.' }\n format.json { render json: @depoevento, status: :created, location: @depoevento }\n else\n format.html { render action: \"new\" }\n format.json { render json: @depoevento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @producto_bodega = ProductoBodega.new(producto_bodega_params)\n\n respond_to do |format|\n if @producto_bodega.save\n format.html { redirect_to @producto_bodega, notice: 'Producto bodega was successfully created.' }\n format.json { render :show, status: :created, location: @producto_bodega }\n else\n format.html { render :new }\n format.json { render json: @producto_bodega.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\tPesqSecDep()\n\t\t@cliente = Cliente.new(params[:cliente])\n\t\t\n\t\trespond_to do |format|\n\t\t\tif @cliente.save\n\t\t\t\tformat.html {redirect_to(@cliente, :notice => 'Registro incluído com Sucesso!')}\n\t\t\t\tformat.xml {render :xml => @cliente, :status => :created, :location => @cliente}\n\t\t\telse\n\t\t\t\tformat.html {render :action => \"new\"}\n\t\t\t\tformat.xml {render :xml => @cliente.erros, :status => :unprocessable_entity }\n\t\t\tend\t\t\n\t\tend\n\tend", "def solicitacao_params\n params.require(:solicitacao).permit(:status, :data, :desconto, :pagamento, :pessoa_id, :produto_solicitados_attributes => [:id, :quantidade, :_destroy, :produto_id])\n end", "def create\n @tipo_de_servicio = TipoDeServicio.new(tipo_de_servicio_params)\n\n respond_to do |format|\n if @tipo_de_servicio.save\n format.html { redirect_to @tipo_de_servicio, notice: 'Tipo de servicio was successfully created.' }\n format.json { render :show, status: :created, location: @tipo_de_servicio }\n else\n format.html { render :new }\n format.json { render json: @tipo_de_servicio.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.63159233", "0.63159233", "0.6264138", "0.6236292", "0.614043", "0.61105925", "0.60872656", "0.6045021", "0.6014807", "0.59685445", "0.5956502", "0.5954889", "0.59487337", "0.59463733", "0.5938046", "0.59338456", "0.5927313", "0.5926482", "0.5918086", "0.5918086", "0.5918086", "0.5905608", "0.5898899", "0.5880821", "0.5871649", "0.58487284", "0.58394057", "0.583925", "0.58369946", "0.5836821", "0.5820494", "0.58199334", "0.58137506", "0.5809976", "0.5807549", "0.58035594", "0.5801252", "0.57997173", "0.5796716", "0.5775043", "0.5766775", "0.57468605", "0.5741874", "0.5738218", "0.5736189", "0.57351625", "0.5732501", "0.5731603", "0.57232094", "0.57228726", "0.5717691", "0.57141846", "0.57126665", "0.57053244", "0.5704012", "0.5703693", "0.5698091", "0.56919", "0.56904227", "0.56888556", "0.56867415", "0.5679782", "0.56728977", "0.5672242", "0.5667922", "0.5664355", "0.5654499", "0.56541353", "0.5653605", "0.5646888", "0.5645154", "0.5634476", "0.563258", "0.5631743", "0.5626391", "0.5623777", "0.5622685", "0.5614119", "0.56131643", "0.56085175", "0.5607932", "0.5607633", "0.56073", "0.5604539", "0.5603279", "0.56022954", "0.56022954", "0.56001335", "0.55991095", "0.5594177", "0.5592023", "0.558859", "0.55855775", "0.5585274", "0.5579351", "0.5578228", "0.55782175", "0.5576111", "0.5573499", "0.5572714" ]
0.65412855
0
PUT /produtividades/1 PUT /produtividades/1.xml
def update @produtividade = Produtividade.find(params[:id]) respond_to do |format| if @produtividade.update_attributes(params[:produtividade]) format.html { redirect_to(@produtividade, :notice => 'Produtividade was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @produtividade.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @produto.update(produto_params)\n respond_with @produto\n end", "def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post 'update', opts\n end", "def update\n @produto = Produto.find(params[:id])\n\n respond_to do |format|\n if @produto.update_attributes(params[:produto])\n format.html { redirect_to(@produto, :notice => 'Produto was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @produto = Produto.find(params[:id])\n\n respond_to do |format|\n if @produto.update_attributes(params[:produto])\n format.html { redirect_to(@produto, :notice => 'Produto was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n # @produto = Produto.find(params[:id])\n\n respond_to do |format|\n if @produto.update_attributes(params[:produto])\n format.html { redirect_to(@produto, :notice => 'Produto atualizado!') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @produto_kit = ProdutoKit.find(params[:id])\n\n respond_to do |format|\n if @produto_kit.update_attributes(params[:produto_kit])\n flash[:notice] = 'ProdutoKit was successfully updated.'\n format.html { redirect_to(@produto_kit) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @produto_kit.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @nossos_servico = NossosServico.find(params[:id])\n\n respond_to do |format|\n if @nossos_servico.update_attributes(params[:nossos_servico])\n format.html { redirect_to(@nossos_servico, :notice => 'Nossos servico was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @nossos_servico.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @produto = ProdutoSimples.find(params[:id])\n respond_to do |format|\n if @produto.update_attributes(params[:produto_simples])\n flash[:notice] = \"Produto atualizado com sucesso.\"\n format.html { redirect_to(admin_produtos_path) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @product = Product.find(params[:id])\n\n respond_to do |format|\n if @product.update_attributes(params[:product])\n format.html { redirect_to(@product, :notice => 'Produto alterado com sucesso.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @product.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @orc_suplementacao = OrcSuplementacao.find(params[:id])\n\n respond_to do |format|\n if @orc_suplementacao.update_attributes(params[:orc_suplementacao])\n flash[:notice] = 'SALVO COM SUCESSO.'\n format.html { redirect_to(@orc_suplementacao) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @orc_suplementacao.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @estagio = Estagio.find(params[:id])\n\n respond_to do |format|\n if @estagio.update_attributes(params[:estagio])\n flash[:notice] = 'Estagio was successfully updated.'\n format.html { redirect_to(@estagio) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @estagio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def put(uri, xml)\r\n req = Net::HTTP::Put.new(uri)\r\n req[\"content-type\"] = \"application/xml\"\r\n req.body = xml\r\n request(req)\r\n end", "def update\n @proceso = Proceso.find(params[:id])\n\n respond_to do |format|\n if @proceso.update_attributes(params[:proceso])\n format.html { redirect_to(@proceso, :notice => 'Proceso was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @proceso.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @tiposproceso = Tiposproceso.find(params[:id])\n\n respond_to do |format|\n if @tiposproceso.update_attributes(params[:tiposproceso])\n format.html { redirect_to(@tiposproceso, :notice => 'Tiposproceso was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tiposproceso.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @servicio = Servicio.find(params[:id])\n\n respond_to do |format|\n if @servicio.update_attributes(params[:servicio])\n format.html { redirect_to @servicio, :notice => 'Servicio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @servicio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @tipo_de_documento = TipoDeDocumento.find(params[:id])\n\n respond_to do |format|\n if @tipo_de_documento.update_attributes(params[:tipo_de_documento])\n format.html { redirect_to(@tipo_de_documento, :notice => 'Tipo de documento atualizado com sucesso.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tipo_de_documento.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @producto = Producto.find(params[:id])\n\n respond_to do |format|\n if @producto.update_attributes(params[:producto])\n format.html { redirect_to @producto, notice: 'Producto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @produto.update(produto_params)\n format.html { redirect_to @produto, notice: 'Produto was successfully updated.' }\n format.json { render :show, status: :ok, location: @produto }\n else\n format.html { render :edit }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @produto.update(produto_params)\n format.html { redirect_to @produto, notice: 'Produto was successfully updated.' }\n format.json { render :show, status: :ok, location: @produto }\n else\n format.html { render :edit }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @produto.update(produto_params)\n format.html { redirect_to @produto, notice: 'Produto was successfully updated.' }\n format.json { render :show, status: :ok, location: @produto }\n else\n format.html { render :edit }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @produto.update(produto_params)\n format.html { redirect_to @produto, notice: t('.atualizado') }\n format.json { render :show, status: :ok, location: @produto }\n else\n format.html { render :edit }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @estagiarios = Estagiario.find(params[:id])\n\n respond_to do |format|\n if @estagiarios.update_attributes(params[:estagiario])\n flash[:notice] = 'ESTAGIÁRIO SALVO COM SUCESSO.'\n format.html { redirect_to(@estagiarios) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @estagiarios.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update(id, name= \"Updated Name\")\n xml_req =\n \"<?xml version='1.0' encoding='UTF-8'?>\n <customer>\n <id type='integer'>#{id}</id>\n <name>#{name}</name>\n </customer>\"\n\n request = Net::HTTP::Put.new(\"#{@url}/#{id}.xml\")\n request.add_field \"Content-Type\", \"application/xml\"\n request.body = xml_req\n\n http = Net::HTTP.new(@uri.host, @uri.port)\n response = http.request(request)\n\n # no response body will be returned\n case response\n when Net::HTTPSuccess\n return \"#{response.code} OK\"\n else\n return \"#{response.code} ERROR\"\n end\n end", "def update\n @estudiante = Estudiante.find(params[:id])\n\n respond_to do |format|\n if @estudiante.update_attributes(params[:estudiante])\n flash[:notice] = 'Actualizado.'\n format.html { redirect_to(@estudiante) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @estudiante.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @estoques = Estoque.find(params[:id])\n\n respond_to do |format|\n if @estoques.update_attributes(params[:estoque])\n flash[:notice] = 'ESTOQUE SALVO COM SUCESSO.'\n format.html { redirect_to(@estoques) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @estoques.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @contato_produto = ContatoProduto.find(params[:id])\n\n respond_to do |format|\n if @contato_produto.update_attributes(params[:contato_produto])\n format.html { redirect_to [:admin, @contato_produto], notice: 'Contato produto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @contato_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @calidadtiposdocumento = Calidadtiposdocumento.find(params[:id])\n\n respond_to do |format|\n if @calidadtiposdocumento.update_attributes(params[:calidadtiposdocumento])\n format.html { redirect_to(@calidadtiposdocumento, :notice => 'Calidadtiposdocumento was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @calidadtiposdocumento.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @product = Product.find(params[:id])\n\n respond_to do |format|\n if @product.update_attributes(params[:product])\n flash[:notice] = 'Produto salvo.'\n format.html { redirect_to(@product) }\n format.xml { head :ok }\n else\n default_data\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @product.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @tservicio = Tservicio.find(params[:id])\n\n respond_to do |format|\n if @tservicio.update_attributes(params[:tservicio])\n format.html { redirect_to(@tservicio, :notice => 'Tservicio was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tservicio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @prod_servi.update(prod_servi_params)\n format.html { redirect_to @prod_servi, notice: 'Prod servi was successfully updated.' }\n format.json { render :show, status: :ok, location: @prod_servi }\n else\n format.html { render :edit }\n format.json { render json: @prod_servi.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @voluntario = Voluntario.find(params[:id])\n params[:voluntario].delete :inclusoes\n\n respond_to do |format|\n if @voluntario.update_attributes(params[:voluntario])\n format.html { redirect_to(@voluntario, :notice => 'Voluntário atualizado com sucesso.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @voluntario.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @inventario = Inventario.find(params[:id])\n @foto = @inventario.foto\n \n @service = InventarioService.new(@inventario, @foto)\n respond_to do |format|\n\n if @inventario.update_attributes(params[:inventario],params[:foto_file])\n format.html { redirect_to(@inventario, :notice => 'Inventario was successfully updated.') }\n format.xml { head :ok }\n else\n\t @foto = @service.foto\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @inventario.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @produto_pedido.update(produto_pedido_params)\n format.html { redirect_to @produto_pedido, notice: 'Produto pedido was successfully updated.' }\n format.json { render :show, status: :ok, location: @produto_pedido }\n else\n format.html { render :edit }\n format.json { render json: @produto_pedido.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @produto_pedido.update(produto_pedido_params)\n format.html { redirect_to @produto_pedido, notice: 'Produto pedido was successfully updated.' }\n format.json { render :show, status: :ok, location: @produto_pedido }\n else\n format.html { render :edit }\n format.json { render json: @produto_pedido.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @inventario_producto.update(inventario_producto_params)\n format.html { redirect_to @inventario_producto, notice: 'Producto was successfully updated.' }\n format.json { render :show, status: :ok, location: @inventario_producto }\n else\n format.html { render :edit }\n format.json { render json: @inventario_producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @produto.update(produto_params)\n format.html { redirect_to edit_produto_path(@produto), notice: 'Produto was successfully updated.' }\n format.json { render :show, status: :ok, location: @produto }\n else\n format.html { render :edit }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @valor_sistema = ValorSistema.find(params[:id])\n\n respond_to do |format|\n if @valor_sistema.update_attributes(params[:valor_sistema])\n flash[:notice] = 'ValorSistema was successfully updated.'\n format.html { redirect_to(@valor_sistema) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @valor_sistema.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @product = Product.find(params[:id])\n\n respond_to do |format|\n if @product.update_attributes(params[:product])\n flash[:notice] = 'El producto se ha actualizado.'\n format.html { redirect_to(@product) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @product.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @prod_coti.update(prod_coti_params)\n format.html { redirect_to @prod_coti, notice: 'Prod coti was successfully updated.' }\n format.json { render :show, status: :ok, location: @prod_coti }\n else\n format.html { render :edit }\n format.json { render json: @prod_coti.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @producto = Producto.find(params[:id])\n\n respond_to do |format|\n if @producto.update_attributes(params[:producto])\n format.html { redirect_to @producto, notice: 'El producto ha sido actualizado exitosamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @campanha_produto = CampanhaProduto.find(params[:id])\n\n respond_to do |format|\n if @campanha_produto.update_attributes(params[:campanha_produto])\n flash[:notice] = 'CampanhaProduto was successfully updated.'\n format.html { redirect_to(@campanha_produto) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @campanha_produto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @product = Product.find(params[:id])\n\n respond_to do |format|\n if @product.update_attributes(params[:product])\n save_success\n format.html { redirect_to(@product) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @product.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @suministro = Suministro.find(params[:id])\n\n respond_to do |format|\n if @suministro.update_attributes(params[:suministro])\n format.html { redirect_to(@suministro, :notice => 'Suministro was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @suministro.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @promos = Promos.find(params[:id])\n\n respond_to do |format|\n if @promos.update_attributes(params[:promos])\n flash[:notice] = 'Promos was successfully updated.'\n format.html { redirect_to(@promos) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @promos.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @articulo = Articulo.find(params[:id])\n\n respond_to do |format|\n if @articulo.update_attributes(params[:articulo])\n flash[:notice] = ''\n format.html { redirect_to(articulos_url) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @articulo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @solicitud_servicio = SolicitudServicio.find(params[:id])\n\n respond_to do |format|\n if @solicitud_servicio.update_attributes(params[:solicitud_servicio])\n format.html { redirect_to @solicitud_servicio, notice: 'Solicitud servicio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @solicitud_servicio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @espacio_deportivo = EspacioDeportivo.find(params[:id])\n\n respond_to do |format|\n if @espacio_deportivo.update_attributes(params[:espacio_deportivo])\n format.html { redirect_to root_url, :notice => \"Se actualizo correctamente el espacio deportivo\" }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @espacio_deportivo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @documentotipo = Documentotipo.find(params[:id])\n\n respond_to do |format|\n if @documentotipo.update_attributes(params[:documentotipo])\n format.html { redirect_to @documentotipo, notice: 'Documentotipo was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @documentotipo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @precio = Precio.find(params[:id])\n\n respond_to do |format|\n if @precio.update_attributes(params[:precio])\n format.html { redirect_to(@precio, :notice => 'Precio was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @precio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @productonegocio = Productonegocio.find(params[:id])\n\n respond_to do |format|\n if @productonegocio.update_attributes(params[:productonegocio])\n format.html { redirect_to @productonegocio, notice: 'Productonegocio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @productonegocio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @contratosinterventoria = Contratosinterventoria.find(params[:id])\n\n respond_to do |format|\n if @contratosinterventoria.update_attributes(params[:contratosinterventoria])\n format.html { redirect_to(@contratosinterventoria, :notice => 'Contratosinterventoria was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @contratosinterventoria.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @troca_produto.update(troca_produto_params)\n format.html { redirect_to @troca_produto, notice: \"Troca produto was successfully updated.\" }\n format.json { render :show, status: :ok, location: @troca_produto }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @troca_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @promocao = Promocao.find(params[:id])\n\n respond_to do |format|\n if @promocao.update_attributes(params[:promocao])\n format.html { redirect_to(@promocao, :notice => 'Promoção aletrada com sucesso!') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @promocao.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @puesto = Puesto.find(params[:id])\n\n respond_to do |format|\n if @puesto.update_attributes(params[:puesto])\n flash[:notice] = 'Puesto was successfully updated.'\n format.html { redirect_to(@puesto) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @puesto.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @tipo_proy = TipoProy.find(params[:id])\n\n respond_to do |format|\n if @tipo_proy.update_attributes(params[:tipo_proy])\n flash[:notice] = 'TipoProy was successfully updated.'\n format.html { redirect_to(@tipo_proy) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tipo_proy.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @peso = Peso.find(params[:id])\n\n respond_to do |format|\n if @peso.update_attributes(params[:peso])\n flash[:notice] = 'Peso was successfully updated.'\n format.html { redirect_to(@peso) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @peso.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @producto = Producto.find(params[:id])\n respond_to do |format|\n if @producto.update_attributes(params[:producto])\n format.html { redirect_to @producto, notice: 'Producto actualizado exitosamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\", alert: 'Producto no pudo ser actualizado.' }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @producto.update(producto_params)\n\n format.html { redirect_to \"/publicaciones/pendientes\", notice: 'Producto was successfully updated.' }\n format.json { render :show, status: :ok, location: @producto }\n else\n format.html { render :edit }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entidad = Entidad.find(params[:id])\n\n respond_to do |format|\n if @entidad.update_attributes(params[:entidad])\n format.html { redirect_to(@entidad, :notice => 'Entidad was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @entidad.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @pedido_produto.update(pedido_produto_params)\n format.html { redirect_to pedido_pedido_produtos_path(@pedido), notice: 'Pedido produto was successfully updated.' }\n format.json { render :show, status: :ok, location: @pedido_produto }\n else\n format.html { render :edit }\n format.json { render json: @pedido_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @saida_produto.update(saida_produto_params)\n format.html { redirect_to @saida_produto, notice: 'Saida produto was successfully updated.' }\n format.json { render :show, status: :ok, location: @saida_produto }\n else\n format.html { render :edit }\n format.json { render json: @saida_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @produto = Produto.find(params[:id])\n \n params[:produto][:preco_compra] = converte_valor_banco params[:produto][:preco_compra]\n params[:produto][:preco_venda] = converte_valor_banco params[:produto][:preco_venda]\n\n respond_to do |format|\n if @produto.update_attributes(params[:produto])\n format.html { redirect_to @produto, notice: 'Produto was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @pagetitle = \"Edit product\"\n \n @product = Product.find(params[:id])\n @company = @product.company\n @suppliers = @company.get_suppliers()\n @marcas = @company.get_marcas()\n @modelos = @company.get_modelos()\n @categories = @company.get_categories() \n @unidades = Unidad.all\n\n respond_to do |format|\n if @product.update_attributes(products_params)\n format.html { redirect_to(@product, :notice => 'Product was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @product.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @estudiante = Estudiante.find(params[:id])\n\n respond_to do |format|\n if @estudiante.update_attributes(params[:estudiante])\n format.html { redirect_to(@estudiante, :notice => 'Estudiante was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @estudiante.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @product = Product.find(params[:id])\n\n respond_to do |format|\n if @product.update_attributes(params[:product])\n format.html { redirect_to @product, notice: 'Produto atualizado.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @product.errors, status: :unprocessable_entity }\n end\n end\n end", "def activo_update\n respond_to do |format|\n activo = params[:producto][:activo]\n id = params[:id]\n Producto.where(id: id).update_all(activo: activo )\n msg = { :status => \"ok\", :message => \"Actualizado!\" }\n format.json { render :json => msg }\n end\n end", "def update\n @proyect = Proyect.find(params[:id])\n\n respond_to do |format|\n if @proyect.update_attributes(params[:proyect])\n flash[:notice] = 'Proyect was successfully updated.'\n format.html { redirect_to(@proyect) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @proyect.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @frequencia_orgao = Frequencia::Orgao.find(params[:id])\n\n respond_to do |format|\n if @frequencia_orgao.update_attributes(params[:frequencia_orgao])\n format.html { redirect_to(@frequencia_orgao, :notice => 'Orgão atualizado com sucesso.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @frequencia_orgao.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @consumo = Consumo.find(params[:id])\n\n respond_to do |format|\n if @consumo.update_attributes(params[:consumo])\n format.html { redirect_to @consumo.cliente, :notice => 'Consumo alterado com sucesso.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @consumo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @producto.update(producto_params)\n format.html { redirect_to \"/productos\", notice: 'Producto actualizado con éxito.' }\n format.json { render :show, status: :ok, location: @producto }\n else\n format.html { render :edit }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @competencia = Competencia.find(params[:id])\n\n respond_to do |format|\n if @competencia.update_attributes(params[:competencia])\n format.html { redirect_to(@competencia, :notice => 'Competencia fue actualizada satisfactoriamente.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @competencia.errors, :status => :unprocessable_entity }\n end\n end\n end", "def test_put_expenses_1_xml\n @parameters = {:expense => {:description => 'NewDescription'}}\n if ActiveRecord::VERSION::MAJOR < 4\n Redmine::ApiTest::Base.should_allow_api_authentication(:put,\n '/expenses/1.xml',\n {:expense => {:description => 'NewDescription'}},\n {:success_code => :ok})\n end\n\n assert_no_difference('Expense.count') do\n put '/expenses/1.xml', @parameters, credentials('admin')\n end\n\n expense = Expense.find(1)\n assert_equal \"NewDescription\", expense.description\n end", "def update\n @pedido = Pedido.find(params[:id])\n\n respond_to do |format|\n if @pedido.update_attributes(params[:pedido])\n format.html { redirect_to(@pedido, :notice => 'Pedido was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @pedido.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n\n @empresa_servicio = EmpresaServicio.find(params[:id])\n respond_to do |format|\n if @empresa_servicio.update_attributes(params[:empresa_servicio])\n\n format.html { redirect_to empresa_empresa_servicios_path, notice: \"Los datos del servicio fueron actualizados para la empresa #{@empresa_servicio.empresa.nombre_empresa}\"}\n \n else\n format.html { render action: \"edit\" }\n format.json { render json: @empresa_servicio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @protocolo = Protocolo.find(params[:id])\n\n respond_to do |format|\n if @protocolo.update_attributes(params[:protocolo])\n flash[:notice] = 'CADASTRADO COM SUCESSO.'\n format.html { redirect_to(@protocolo) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @protocolo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @tipo_articulo = TipoArticulo.find(params[:id])\n\n respond_to do |format|\n if @tipo_articulo.update_attributes(params[:tipo_articulo])\n flash[:notice] = 'TipoArticulo was successfully updated.'\n format.html { redirect_to(@tipo_articulo) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tipo_articulo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @producto_seccion.update(producto_seccion_params)\n format.html { redirect_to @producto_seccion, notice: 'Producto seccion was successfully updated.' }\n format.json { render :show, status: :ok, location: @producto_seccion }\n else\n format.html { render :edit }\n format.json { render json: @producto_seccion.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @producto.update(producto_params)\n format.html { redirect_to @producto, notice: 'Producto was successfully updated.' }\n format.json { render :show, status: :ok, location: @producto }\n else\n format.html { render :edit }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sistema = Sistema.find(params[:id])\n\n respond_to do |format|\n if @sistema.update_attributes(params[:sistema])\n format.html { redirect_to @sistema, notice: 'Sistema was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sistema.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @tipo_product = TipoProduct.find(params[:id])\n\n respond_to do |format|\n if @tipo_product.update_attributes(params[:tipo_product])\n format.html { redirect_to @tipo_product, notice: 'Tipo product was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @tipo_product.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entrada_produto.update(entrada_produto_params)\n format.html { redirect_to @entrada_produto, notice: 'Entrada produto was successfully updated.' }\n format.json { render :show, status: :ok, location: @entrada_produto }\n else\n format.html { render :edit }\n format.json { render json: @entrada_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @com_articulo.update(com_articulo_params)\n format.html { redirect_to @com_articulo, notice: 'Producto actualizado correctamente.' }\n format.json { render :show, status: :ok, location: @com_articulo }\n else\n format.html { render :edit }\n format.json { render json: @com_articulo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @prod = Prod.find(params[:id])\n\n respond_to do |format|\n if @prod.update_attributes(params[:prod])\n format.html { redirect_to @prod, :notice => 'Prod was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @prod.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @document.product_id = document_params[:product_id] #入力時に選択した製品のidを、documentの外部 key として記録\n respond_to do |format|\n if @document.update(document_params)\n format.html { redirect_to @document, notice: \"Document was successfully updated.\" }\n format.json { render :show, status: :ok, location: @document }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @certidao = Certidao.find(params[:id])\n\n respond_to do |format|\n if @certidao.update_attributes(params[:certidao])\n flash[:notice] = 'Certidao was successfully updated.'\n format.html { redirect_to(@certidao) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @certidao.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @tipo_vinculo = TipoVinculo.find(params[:id])\n\n respond_to do |format|\n if @tipo_vinculo.update_attributes(params[:tipo_vinculo])\n flash[:notice] = 'TipoVinculo was successfully updated.'\n format.html { redirect_to(@tipo_vinculo) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tipo_vinculo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @producto.update(producto_params)\n format.html { redirect_to @producto, notice: 'Producto actualizado.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @producto_stock = ProductoStock.find(params[:id])\n\n respond_to do |format|\n if @producto_stock.update_attributes(params[:producto_stock])\n format.html { redirect_to(@producto_stock, :notice => 'ProductoStock was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @producto_stock.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @domino = Domino.find(params[:id])\n\n respond_to do |format|\n if @domino.update_attributes(params[:domino])\n flash[:notice] = 'Domino was successfully updated.'\n format.html { redirect_to(@domino) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @domino.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @safra_verdoso = SafraVerdoso.find(params[:id])\n\n respond_to do |format|\n if @safra_verdoso.update_attributes(params[:safra_verdoso])\n format.html { redirect_to \"/safra_produtos/#{@safra_verdoso.safra_produto_id}/descontos\"}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @safra_verdoso.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @departamentos = Departamento.find(params[:id])\n\n respond_to do |format|\n if @departamentos.update_attributes(params[:departamentos])\n flash[:notice] = 'DEPARTAMENTO SALVO COM SUCESSO.'\n format.html { redirect_to(@departamentos) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @departamentos.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @depositocaucion = Depositocaucion.find(params[:id])\n respond_to do |format|\n if @depositocaucion.update_attributes(params[:depositocaucion])\n flash[:notice] = 'Depositocaucion was successfully updated.'\n format.html { redirect_to(@depositocaucion) }\n format.xml { head :ok }\n else \n format.html { render :action => \"edit\" }\n format.xml { render :xml => @depositocaucion.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @peca = Peca.find(params[:id])\n\n respond_to do |format|\n if @peca.update_attributes(params[:peca])\n flash[:notice] = 'Peça atualizada com sucesso.'\n format.html { redirect_to(@peca) }\n format.xml { head :ok }\n else\n flash[:notice] = 'O formulário contém erros. Verifique os campos digitados e tente novamente.'\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @peca.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @producto.update(producto_params)\n format.html { redirect_to @producto, notice: 'Producto modificado exitosamente..' }\n format.json { render :show, status: :ok, location: @producto }\n else\n format.html { render :edit }\n format.json { render json: @producto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @safra_produto = SafraProduto.find(params[:id])\n\n respond_to do |format|\n if @safra_produto.update_attributes(params[:safra_produto])\n format.html { redirect_to \"/safras/#{@safra_produto.safra_id}\"}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @safra_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @requisicion = Requisicion.find(params[:id])\n\n respond_to do |format|\n if @requisicion.update_attributes(params[:requisicion])\n format.html { redirect_to(@requisicion, :notice => 'Requisicion was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @requisicion.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @peticion_servicio_ti = Peticion::ServicioTi.find(params[:id])\n\n respond_to do |format|\n if @peticion_servicio_ti.update_attributes(params[:peticion_servicio_ti])\n format.html { redirect_to edit_peticion_servicio_ti_path(@peticion_servicio_ti), notice: 'Actualizado Correctamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @peticion_servicio_ti.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @produccion = Produccion.find(params[:id])\n\n respond_to do |format|\n if @produccion.update_attributes(params[:produccion])\n format.html { redirect_to @produccion, notice: 'Se ha modificado satisfactoriamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @produccion.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @product = Product.find(params[:id])\n\n respond_to do |format|\n if @product.update_attributes(params[:product])\n flash[:notice] = 'Product was successfully updated.'\n format.html { redirect_to(@product) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @product.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @entidade = Entidade.find(params[:id])\n\n respond_to do |format|\n if @entidade.update_attributes(params[:entidade])\n format.html { redirect_to(@entidade, :notice => 'Entidade atualizado com sucesso.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @entidade.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
[ "0.67078876", "0.664587", "0.6568118", "0.6568118", "0.64782166", "0.6350164", "0.63406724", "0.6331036", "0.6289379", "0.62521005", "0.6245974", "0.6214503", "0.6185831", "0.615584", "0.61452305", "0.6135821", "0.6135462", "0.61248356", "0.61248356", "0.61248356", "0.6102463", "0.6100492", "0.60931295", "0.6079899", "0.6078277", "0.6065896", "0.6064453", "0.6061771", "0.60601526", "0.6059887", "0.6058591", "0.6058322", "0.60559154", "0.60559154", "0.60544676", "0.6043526", "0.60352004", "0.60286576", "0.6023798", "0.6022793", "0.60197216", "0.60196835", "0.6010348", "0.59982806", "0.5994125", "0.59924394", "0.59899586", "0.5989511", "0.5982477", "0.5980906", "0.59799784", "0.5976692", "0.59737283", "0.5972781", "0.5970966", "0.597085", "0.596681", "0.59636897", "0.59609044", "0.5959224", "0.59573585", "0.5954164", "0.59522635", "0.59522194", "0.5950397", "0.5947893", "0.5941409", "0.5941", "0.5940922", "0.5932093", "0.5931732", "0.59282804", "0.59210604", "0.591659", "0.5914396", "0.590983", "0.5907714", "0.5903825", "0.5903023", "0.58999527", "0.5896556", "0.5893821", "0.5890781", "0.58882254", "0.58793736", "0.58793664", "0.5878576", "0.58781993", "0.58735615", "0.5872782", "0.58724195", "0.5870789", "0.58697426", "0.58689135", "0.58645684", "0.58604974", "0.58539855", "0.5852834", "0.585231", "0.5850956" ]
0.64875823
4
DELETE /produtividades/1 DELETE /produtividades/1.xml
def destroy @produtividade = Produtividade.find(params[:id]) @produtividade.destroy respond_to do |format| format.html { redirect_to(produtividades_url) } format.xml { head :ok } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n #@produto = Produto.find(params[:id])\n @produto.destroy\n\n respond_to do |format|\n format.html { redirect_to(produtos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @produto = Produto.find(params[:id])\n @produto.destroy\n\n respond_to do |format|\n format.html { redirect_to(produtos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @produto = Produto.find(params[:id])\n @produto.destroy\n\n respond_to do |format|\n format.html { redirect_to(produtos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @produto = Produto.find(params[:id])\n @produto.destroy\n respond_to do |format|\n format.html { redirect_to(admin_produtos_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n RestClient.delete \"#{REST_API_URI}/contents/#{id}.xml\" \n self\n end", "def destroy\n @proceso = Proceso.find(params[:id])\n @proceso.destroy\n\n respond_to do |format|\n format.html { redirect_to(procesos_url) }\n format.xml { head :ok }\n end\n end", "def netdev_resxml_delete( xml )\n top = netdev_resxml_top( xml )\n par = top.instance_variable_get(:@parent)\n par['delete'] = 'delete'\n end", "def destroy\n @estacion = Estacion.find(params[:id])\n @estacion.destroy\n\n respond_to do |format|\n format.html { redirect_to(estaciones_url) }\n format.xml { head :ok }\n end\n end", "def delete()\n response = send_post_request(@xml_api_delete_path)\n response.is_a?(Net::HTTPSuccess) or response.is_a?(Net::HTTPRedirection)\n end", "def destroy\n @estudiante = Estudiante.find(params[:id])\n @estudiante.destroy\n\n respond_to do |format|\n format.html { redirect_to(estudiantes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @estudiante = Estudiante.find(params[:id])\n @estudiante.destroy\n\n respond_to do |format|\n format.html { redirect_to(estudiantes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @adjunto = Adjunto.find(params[:id])\n @adjunto.destroy\n\n respond_to do |format|\n format.html { redirect_to(adjuntos_url) }\n format.xml { head :ok }\n end\n end", "def delete()\n response = send_post_request(@xml_api_delete_path)\n response.is_a?(Net::HTTPSuccess) or response.is_a?(Net::HTTPRedirection)\n end", "def destroy\n @suministro = Suministro.find(params[:id])\n @suministro.destroy\n\n respond_to do |format|\n format.html { redirect_to(suministros_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @entidad = Entidad.find(params[:id])\n @entidad.destroy\n\n respond_to do |format|\n format.html { redirect_to(entidades_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @relatestagiario = Relatestagiario.find(params[:id])\n @relatestagiario.destroy\n\n respond_to do |format|\n format.html { redirect_to(relatestagiarios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @certidao = Certidao.find(params[:id])\n @certidao.destroy\n\n respond_to do |format|\n format.html { redirect_to(certidaos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @config_xml = ConfigXml.find(params[:id])\n @config_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(config_xmls_url) }\n format.xml { head :ok }\n end\n rescue ActiveRecord::RecordNotFound => e\n prevent_access(e)\n end", "def destroy\n @aplicacion = Aplicacion.find(params[:id])\n @aplicacion.destroy\n\n respond_to do |format|\n format.html { redirect_to(aplicacions_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @campanha_produto = CampanhaProduto.find(params[:id])\n @campanha_produto.destroy\n\n respond_to do |format|\n format.html { redirect_to(campanha_produtos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @domino = Domino.find(params[:id])\n @domino.destroy\n\n respond_to do |format|\n format.html { redirect_to(dominos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tiposproceso = Tiposproceso.find(params[:id])\n @tiposproceso.destroy\n\n respond_to do |format|\n format.html { redirect_to(tiposprocesos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @calidadtiposdocumento = Calidadtiposdocumento.find(params[:id])\n @calidadtiposdocumento.destroy\n\n respond_to do |format|\n format.html { redirect_to(calidadtiposdocumentos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @competencia = Competencia.find(params[:id])\n @competencia.destroy\n\n respond_to do |format|\n format.html { redirect_to(competencias_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @prd_etc = PrdEtc.find(params[:id])\n @prd_etc.destroy\n\n respond_to do |format|\n format.html { redirect_to(prd_etcs_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @elemento = Elemento.find(params[:id])\n @elemento.destroy\n\n respond_to do |format|\n format.html { redirect_to(elementos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tipo_de_documento = TipoDeDocumento.find(params[:id])\n @tipo_de_documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(tipos_de_documento_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @comunidade = Comunidade.find(params[:id])\n @comunidade.destroy\n\n respond_to do |format|\n format.html { redirect_to(comunidades_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @consulta = Consulta.find(params[:id])\n @consulta.destroy\n\n respond_to do |format|\n format.html { redirect_to(consultas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @consulta = Consulta.find(params[:id])\n @consulta.destroy\n\n respond_to do |format|\n format.html { redirect_to(consultas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @recurso = Recurso.find(params[:id])\n @recurso.destroy\n\n respond_to do |format|\n format.html { redirect_to(recursos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tipo_proy = TipoProy.find(params[:id])\n @tipo_proy.destroy\n\n respond_to do |format|\n format.html { redirect_to(tipo_proys_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @direccion = Direccion.find(params[:id])\n @direccion.destroy\n\n respond_to do |format|\n format.html { redirect_to(direccions_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @plantilla = Plantilla.find(params[:id])\n @plantilla.destroy\n\n respond_to do |format|\n format.html { redirect_to(plantillas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @dato = Dato.find(params[:id])\n @dato.destroy\n\n respond_to do |format|\n format.html { redirect_to(datos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @dato = Dato.find(params[:id])\n @dato.destroy\n\n respond_to do |format|\n format.html { redirect_to(datos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @unidad = Unidad.find(params[:id])\n @unidad.destroy\n\n respond_to do |format|\n format.html { redirect_to(unidades_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @valor_sistema = ValorSistema.find(params[:id])\n @valor_sistema.destroy\n\n respond_to do |format|\n format.html { redirect_to(valores_sistema_url) }\n format.xml { head :ok }\n end\n end", "def remove_configuration_product\r\n # node = ProductPackageProduct.find(params[:id].to_i).destroy\r\n # redirect_to :action => \"configuration_products\", :id => node.parent_id\r\n ExampleConfigurationProduct.delete params[:id]\r\n redirect_to :action => \"configuration_products\", :id => params[:id]\r\n end", "def destroy\n @estagio = Estagio.find(params[:id])\n @estagio.destroy\n\n respond_to do |format|\n format.html { redirect_to(estagios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @documento = Documento.find(params[:id])\n @documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(documentos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @distribuidora = Distribuidora.find(params[:id])\n @distribuidora.destroy\n\n respond_to do |format|\n format.html { redirect_to(distribuidoras_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @expedicao = Expedicao.find(params[:id])\n @expedicao.destroy\n\n respond_to do |format|\n format.html { redirect_to(expedicoes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @contrato = Contrato.find(params[:id])\n @contrato.destroy\n\n respond_to do |format|\n format.html { redirect_to(contratos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @iguanasactualizacion = Iguanasactualizacion.find(params[:id])\n @iguanasactualizacion.destroy\n\n respond_to do |format|\n format.html { redirect_to(iguanasactualizaciones_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @cuenta = Cuenta.find(params[:id])\n @cuenta.destroy\n\n respond_to do |format|\n format.html { redirect_to(cuentas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @cuenta = Cuenta.find(params[:id])\n @cuenta.destroy\n\n respond_to do |format|\n format.html { redirect_to(cuentas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @cuenta = Cuenta.find(params[:id])\n @cuenta.destroy\n\n respond_to do |format|\n format.html { redirect_to(cuentas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @configuracion = Configuracion.find(params[:id])\n @configuracion.destroy\n\n respond_to do |format|\n format.html { redirect_to(configuracions_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @documento = Documento.find(params[:id])\n producto = Producto.find(@documento.producto_id)\n @documento.destroy\n\n respond_to do |format|\n format.html { redirect_to producto, notice: 'Documento eliminado exitosamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @doctipo = Doctipo.find(params[:id])\r\n @doctipo.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to(doctipos_url) }\r\n format.xml { head :ok }\r\n end\r\n end", "def destroy\n @convenio = Convenio.find(params[:id])\n @convenio.destroy\n\n respond_to do |format|\n format.html { redirect_to(convenios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @documento = @externo.documentos.find(params[:id])\n @documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(documentos_url(@externo)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @precio = Precio.find(params[:id])\n @precio.destroy\n\n respond_to do |format|\n format.html { redirect_to(precios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @conteudo = Conteudo.find(params[:id])\n @conteudo.destroy\nt=0\n respond_to do |format|\n format.html { redirect_to(exclusao_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @desasignado = Desasignado.find(params[:id])\n @desasignado.destroy\n\n respond_to do |format|\n format.html { redirect_to(desasignados_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @estatu = Estatu.find(params[:id])\n @estatu.destroy\n\n respond_to do |format|\n format.html { redirect_to(estatus_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @dossier = Dossier.find(params[:id])\n @dossier.destroy\n\n respond_to do |format|\n format.html { redirect_to(\"/\") }\n format.xml { head :ok }\n end\n end", "def destroy\n @reputacao_veiculo = ReputacaoVeiculo.find(params[:id])\n @reputacao_veiculo.destroy\n\n respond_to do |format|\n format.html { redirect_to(reputacao_veiculos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @contratosinterventoria = Contratosinterventoria.find(params[:id])\n @contratosinterventoria.destroy\n\n respond_to do |format|\n format.html { redirect_to(contratosinterventorias_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @categoria_comida = CategoriaComida.find(params[:id])\n @categoria_comida.destroy\n\n respond_to do |format|\n format.html { redirect_to(categoria_comidas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @child_dupa2 = ChildDupa2.find(params[:id])\n @child_dupa2.destroy\n\n respond_to do |format|\n format.html { redirect_to(child_dupa2s_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @poblacionesespecial = Poblacionesespecial.find(params[:id])\n @poblacionesespecial.destroy\n\n respond_to do |format|\n format.html { redirect_to(poblacionesespeciales_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @departamentos = Departamento.find(params[:id])\n @departamentos.destroy\n\n respond_to do |format|\n format.html { redirect_to(homes_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @motivo_assistencia = MotivoAssistencia.find(params[:id])\n @motivo_assistencia.destroy\n\n respond_to do |format|\n format.html { redirect_to(motivos_assistencia_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @pieces_commande = PiecesCommande.find(params[:id])\n @pieces_commande.destroy\n\n respond_to do |format|\n format.html { redirect_to(pieces_commandes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tipo_articulo = TipoArticulo.find(params[:id])\n @tipo_articulo.destroy\n\n respond_to do |format|\n format.html { redirect_to(tipo_articulos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @requisicao = Requisicao.find(params[:id])\n @requisicao.destroy\n\n respond_to do |format|\n format.html { redirect_to(requisicoes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @adm_produto = Adm::Produto.find(params[:id])\n @adm_produto.status_id = Status.where([\"codigo = '2'and area_id = ?\", Area.select('id').where([\"codigo = '3'\"]).first]).first.id\n @adm_produto.save\n logProduto(request.remote_ip, @adm_produto.id, session[:usuario].id, \"Produto apagado\")\n respond_to do |format|\n format.html { redirect_to(adm_produtos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tipo_conta = TipoConta.find(params[:id])\n @tipo_conta.destroy\n\n respond_to do |format|\n format.html { redirect_to(tipo_contas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tabela_preco_produto = TabelaPrecoProduto.find(params[:id])\n @tabela_preco_produto.destroy\n\n respond_to do |format|\n format.html { redirect_to(tabela_preco_produtos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @especificacao = Especificacao.find(params[:id])\n @especificacao.destroy\n\n respond_to do |format|\n format.html { redirect_to(especificacaos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @estagiarios = Estagiario.find(params[:id])\n @estagiarios.destroy\n\n respond_to do |format|\n format.html { redirect_to(homes_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ficha_tematica = FichaTematica.find(params[:id])\n @ficha_tematica.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_ficha_tematicas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @nossos_servico = NossosServico.find(params[:id])\n @nossos_servico.destroy\n\n respond_to do |format|\n format.html { redirect_to(nossos_servicos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @inventario = Inventario.find(params[:id])\n @inventario.destroy\n\n respond_to do |format|\n format.html { redirect_to(inventarios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @reclamacao = Reclamacao.find(params[:id])\n @reclamacao.destroy\n\n respond_to do |format|\n format.html { redirect_to(reclamacaos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @reclamo = Reclamo.find(params[:id])\n @reclamo.destroy\n\n respond_to do |format|\n format.html { redirect_to(reclamos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @catena = Catena.find(params[:id])\n @catena.destroy\n\n respond_to do |format|\n format.html { redirect_to(catenas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @documentoclasificacion = Documentoclasificacion.find(params[:id])\n @documentoclasificacion.destroy\n\n respond_to do |format|\n format.html { redirect_to(documentoclasificaciones_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @coleccionista = Coleccionista.find(params[:id])\n @coleccionista.destroy\n\n respond_to do |format|\n format.html { redirect_to(coleccionistas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @solicitudrecurso = Solicitudrecurso.find(params[:id])\n @solicitudrecurso.destroy\n @tramos=Peticion.find_all_by_solicitudrecurso_id(@solicitudrecurso.id) # busco todos los tramos que tenian el id\n @tramos.each {|tramo| tramo.destroy} # los elimino en cascada\n\n respond_to do |format|\n format.html { redirect_to(solicitudrecursos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @articulo = Articulo.find(params[:id])\n @articulo.destroy\n\n respond_to do |format|\n format.html { redirect_to(articulos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n\n @cita = Cita.find(params[:id])\n paciente_id=@cita.paciente_id\n Operation.delete_all \"cita_id = #{@cita.id}\"\n consulta=Consulta.find_by_cita_id(params[:id])\n consulta.update_attributes(:cita_id => nil)\n @cita.destroy\n \n respond_to do |format|\n format.html { redirect_to :controller => \"lab\",:action => \"crea_cita\",:id => paciente_id,:id_cons => consulta.id }\n format.xml { head :ok }\n end\n end", "def delete_data(index_name)\n uri = @client.make_uri(\"/#{index_name}/update/\")\n req = HTTP::Post.new(uri)\n req.content_type = 'text/xml'\n req.body = '<delete><query>*:*</query></delete>'\n response = @client.send_http(req, true, ['200'])\n end", "def destroy\n @viviendastipostramite = Viviendastipostramite.find(params[:id])\n @viviendastipostramite.destroy\n\n respond_to do |format|\n format.html { redirect_to(viviendastipostramites_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @entidade = Entidade.find(params[:id])\n @entidade.destroy\n\n respond_to do |format|\n format.html { redirect_to(entidades_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @receita = Receita.find(params[:id])\n @receita.destroy\n\n respond_to do |format|\n format.html { redirect_to(receitas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @entrada = Entrada.find(params[:id])\n @entrada.destroy\n\n respond_to do |format|\n format.html { redirect_to(mngr_entradas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @inscripcione = Inscripcione.find(params[:id])\n @inscripcione.destroy\n\n respond_to do |format|\n format.html { redirect_to(inscripciones_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @orc_ficha = OrcFicha.find(params[:id])\n @orc_ficha.destroy\n\n respond_to do |format|\n format.html { redirect_to(orc_fichas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @pagamento = Pagamento.find(params[:id])\n @pagamento.destroy\n\n respond_to do |format|\n format.html { redirect_to(pagamentos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\r\n @asignacion = Asignacion.find(params[:id])\r\n @asignacion.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to(asignacions_url) }\r\n format.xml { head :ok }\r\n end\r\n end", "def destroy\n @actividad = Actividad.find(params[:id])\n @actividad.destroy\n\n respond_to do |format|\n format.html { redirect_to(actividads_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @prestamo = Prestamo.find(params[:id])\n @prestamo.destroy\n\n respond_to do |format|\n format.html { redirect_to(prestamos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @peca = Peca.find(params[:id])\n @peca.destroy\n flash[:notice] = 'Peça excluída com sucesso.'\n\n respond_to do |format|\n format.html { redirect_to(pecas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @solicitudrecurso = Solicitudrecurso.find(params[:id])\n @tramos=Peticion.where(\"solicitudrecurso_id = ?\",@solicitudrecurso.id).to_a # busco todos los tramos que tenian el id\n @tramos.each {|tramo| tramo.destroy} # los elimino en cascada\n @solicitudrecurso.destroy\n \n respond_to do |format|\n format.html { redirect_to(solicitudrecursos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @puesto = Puesto.find(params[:id])\n @puesto.destroy\n\n respond_to do |format|\n format.html { redirect_to(puestos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @correspondenciasasignada = Correspondenciasasignada.find(params[:id])\n @correspondenciasasignada.destroy\n\n respond_to do |format|\n format.html { redirect_to(correspondenciasasignadas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @peso = Peso.find(params[:id])\n @peso.destroy\n\n respond_to do |format|\n format.html { redirect_to(pesos_url) }\n format.xml { head :ok }\n end\n end" ]
[ "0.6952404", "0.693134", "0.693134", "0.6847999", "0.68100935", "0.6786605", "0.6731185", "0.67260826", "0.6707294", "0.6671568", "0.66710526", "0.66505945", "0.66400695", "0.6636899", "0.6615354", "0.6615047", "0.6608686", "0.6607667", "0.6606516", "0.6606462", "0.66016257", "0.65977937", "0.659531", "0.65846485", "0.6574756", "0.657007", "0.6561681", "0.6553287", "0.6552807", "0.6552807", "0.6551444", "0.6548625", "0.6540465", "0.6538557", "0.6537334", "0.6537334", "0.65312135", "0.65208983", "0.6494914", "0.64947945", "0.64942366", "0.6493414", "0.6492176", "0.6485301", "0.6484798", "0.648015", "0.648015", "0.648015", "0.6478357", "0.64778674", "0.6475813", "0.6473462", "0.647199", "0.6465652", "0.6464731", "0.64634746", "0.64623785", "0.64595103", "0.64560264", "0.6454949", "0.64533895", "0.6452886", "0.6442026", "0.64403903", "0.643898", "0.64347416", "0.6432977", "0.6431599", "0.64306223", "0.6428594", "0.6428232", "0.6420976", "0.64202213", "0.6420083", "0.6418937", "0.6418657", "0.64177793", "0.64162517", "0.6406352", "0.64053905", "0.6400629", "0.64003646", "0.6398436", "0.63978535", "0.63952047", "0.6394009", "0.6391231", "0.6387065", "0.6383912", "0.6377817", "0.63765323", "0.63752776", "0.6374731", "0.63744587", "0.63740677", "0.63715833", "0.63705033", "0.63658607", "0.6365621", "0.6365276" ]
0.6804053
5
=> Retourne un vrai clone de l'accord
def clone Chord::new self.to_hash end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clone\n super\n end", "def clone() end", "def clone\n end", "def clone\n end", "def clone\n end", "def clone\n super\n end", "def clone; end", "def clone; end", "def clone; end", "def clone\n end", "def clone(*) end", "def clone(*) end", "def clone\n @clone ||= super\n end", "def clone\n dup\n end", "def clone\n @clone = true\n end", "def clone\n self\n end", "def clone\n copy(false)\n end", "def clone\n self.copy\n end", "def clone\n self.copy\n end", "def dup\n Tableau.new @hidden_cards, @cards\n end", "def dup\n clone\n end", "def clone\n self\n end", "def clone_head; end", "def clone\n raise NotImplementedError\n end", "def cloning_tank\n end", "def clone\n\t\t\tCData.new self\n\t\tend", "def _clone\n self.class.new(self)\n end", "def clone\n t = self\n c = super\n c.delete_all\n t.each { |r| c << r.clone }\n c.header = c[header_row_index] if header_row_index\n c\n end", "def clone\n Matrix.rows(@rows)\n end", "def clone\n copy = super\n transaction do\n copy.save!\n\n %w[\n registration_information support information_source advance_directive\n ].each do |assoc|\n copy.send(\"#{assoc}\\=\", send(assoc).clone) if send(assoc)\n end\n\n %w[\n patient_identifiers languages providers medications allergies conditions\n all_results immunizations encounters procedures medical_equipments social_history insurance_providers\n ].each do |assoc|\n send(assoc).each do |item|\n copy.send(assoc) << item.clone\n end\n end\n\n end\n copy\n end", "def dup\n copy(false)\n end", "def deep_clone; end", "def dup\n new_board = ChessBoard.new\n new_board.rows = self.rows.map(&:dup)\n new_board\n end", "def dup\n copy = super\n copy.clear_puzzle\n @puzzle.each_with_index do |entry, index|\n copy[index] = entry\n end\n copy\n end", "def copy\n dup\n end", "def vendored\n clone unless cloned?\n super\n end", "def clone\n self.class.new(@parent, @position)\n end", "def clone\n Marshal.load(Marshal.dump self)\n end", "def dup\n self.class.new(color, board, pos)\n end", "def clone\n self.class.new(setup.map(&:dup))\n end", "def clone\n a_clone = super\n a_clone.send(:instance_variable_set, :@role_symbols, @role_symbols.clone) if @role_symbols\n a_clone\n end", "def clone(*args); end", "def copy\n \n end", "def dup\n Card.new @value, @suit\n end", "def dup\n self.class.new.tap{|obj| obj.initialize_copi self }\n end", "def initialize_copy(orig)\n #This is a stub, used for indexing\n end", "def dup\n copy = super\n @grid = @grid.dup\n copy\n end", "def dup\n clone = super\n clone.name = \"Clone of #{self.name}\"\n clone.institution_default = false\n # The instance requires an ID for MetadataProfileElement validations.\n clone.save!\n self.elements.each { |e| clone.elements << e.dup }\n clone\n end", "def foorth_copy(name)\r\n copy = self.clone\r\n copy.reinitialize(name)\r\n copy\r\n end", "def initialize_copy(original)\n super\n @table = @table.dup\n end", "def dup\n super().extend IndifferentAccess\n end", "def initialize_clone( hooked_array_clone )\n \n super\n \n hooked_array_clone.internal_array = hooked_array_clone.internal_array.clone\n \n end", "def clone_head\n clone.mark_head(true)\n end", "def dup\n end", "def dup\n end", "def initialize_copy(orig)\n super\n @table = @table.dup\n end", "def initialize_copy(orig); end", "def initialize_copy(orig); end", "def initialize_copy(orig); end", "def initialize_copy(orig); end", "def initialize_copy(orig); end", "def copy\n\t\t\treturn self.dup\n\t\tend", "def copyAndActive(name,degats,departAbs, direction, entitySrc)\n newCopy = deep_clone()\n\n puts entitySrc.class\n if entitySrc.is_a?(Entite)\n newCopy.name= name\n newCopy.degats = degats\n newCopy.departAbs = departAbs\n newCopy.deplacer(departAbs[0],departAbs[1])\n newCopy.entitySrc= entitySrc\n newCopy.direction= [direction*5,0]\n\n @@projectilesActifs.push(newCopy)\n# changed()\n# notify_observers(Action::ADD_PROJECTILE, newCopy)\n else\n puts \"c'est pas une entite!\"\n end\n return newCopy\n end", "def copy\n move(:copy)\n end", "def clone\n Inventory.new(@commodities.keys).tap do |inventory|\n @commodities.each_pair do |commodity, id|\n inventory.set_ideal_stock_of(commodity, @ideal_stock[id])\n inventory.set_stock_of(commodity, @stock[id])\n end\n end\n end", "def dup\n new_board = Board.new\n @rows.each_with_index do |row, row_idx|\n row.each_with_index do |pos, col_idx|\n new_pos, new_piece_type, color = [row_idx, col_idx], pos.class, pos.color\n new_board[new_pos] = new_piece_type.new(color, new_board, new_pos) unless pos.is_a?(NullPiece)\n new_board[new_pos] = new_piece_type.instance if pos.is_a?(NullPiece)\n end\n end \n new_board\n end", "def clone\n other = dup\n other.freeze if self.frozen?\n other\n end", "def dup()\n newcards = []\n self.each { |card| newcards << card.dup }\n return Hand.new(newcards)\n end", "def dup\n return Card.new(self.suit, self.rank)\n end", "def clone_with_translation\n new_obj = self.clone_without_translation\n \n self.translations.each do |translation|\n new_obj.translations << translation.clone\n end\n new_obj\n end", "def dup! ; self ; end", "def clone()\n Judge.new(@school.clone, @name.clone)\n end", "def clone(inst_book)\n ch = InstChapter.new\n ch.inst_book_id = inst_book.id\n ch.name = self.name\n ch.short_display_name = self.short_display_name\n ch.position = self.position\n ch.save\n\n inst_chapter_modules.each do |chapter_module|\n inst_chapter_module = chapter_module.clone(inst_book, ch)\n end\n end", "def clone\n Vector.elements(@elements)\n end", "def clone\n ret = self.deep_copy\n ret.register if self.registered\n ret\n end", "def clone\n board_clone = Board.new\n for x in 0..@matrix.length - 1\n for y in 0..@matrix[x].length - 1\n board_clone.matrix[x][y] = @matrix[x][y]\n end\n end\n board_clone.move_number = self.move_number + 1\n board_clone\n end", "def clone\n o = dup\n o.freeze if frozen?\n o\n end", "def dup\n self\n end", "def dup\n self\n end", "def dup\n self\n end", "def clone\n Marshal.load(Marshal.dump(self))\n end", "def clone\n Marshal.load(Marshal.dump(self))\n end", "def clone\n Marshal.load(Marshal.dump(self))\n end", "def clone\n Marshal.load(Marshal.dump(self))\n end", "def clone\n Marshal.load(Marshal.dump(self))\n end", "def clone\n newDelegate = @delegate.clone\n return SparseMatrix.new(newDelegate)\n end", "def clone\n # Do not implement in terms of dup. It breaks rails.\n #\n cls = Rubinius.invoke_primitive :object_class, self\n copy = cls.allocate\n\n Rubinius.invoke_primitive :object_copy_object, copy, self\n Rubinius.invoke_primitive :object_copy_singleton_class, copy, self\n\n Rubinius.privately do\n copy.initialize_copy self\n end\n\n copy.freeze if frozen?\n copy\n end", "def dup\n GameBoard.build(row_size,column_size) {|r,c| self[r,c]}\n end", "def clone\n original_mov = MovMovimiento.find params[:id]\n @mov_movimiento = original_mov.clone\n @mov_movimiento.calcula_consecutivos\n render :new\n end", "def clone_course(course)\n cloned_course = course.dup\n cloned_course.update_attribute(\"name\", course.name + \"-CLONE\")\n cloned_course.save\n\n cloned_course\n end", "def duplicate\n super do |cloned_resource|\n cloned_resource.title = \"Copy #{@resource.title[0...Integral.title_length_maximum - 5]}\"\n cloned_resource.view_count = 0\n cloned_resource.build_active_block_list(content: @resource.active_block_list.content, listable: cloned_resource)\n cloned_resource.tag_list = @resource.tag_list_on(@resource.tag_context)\n cloned_resource.slug = @resource.slug\n cloned_resource.status = :draft\n cloned_resource.published_at = nil\n end\n end", "def clone\n SparseVector.elements(@elements, true, size)\n end", "def dup\n empty_board = Board.new(false)\n pieces.each do |piece|\n temp_color = (piece.color == :red) ? :red : :white\n temp_pos = [piece.pos[0], piece.pos[1]]\n temp_kinged = piece.kinged\n temp_piece = Piece.new(empty_board, temp_color, temp_pos, temp_kinged)\n\n # empty_board.add_piece(Piece.new(empty_board, temp_color, temp_pos, temp_kinged), temp_pos)\n end\n\n empty_board\n # duped_rows = rows.map(&:dup)\n #\n # duped_rows.each_with_index do |row, row_idx|\n # row.each_index do |col_idx|\n # next if duped_rows[row_idx].nil?\n # current_cell = duped_rows[row_idx][col_idx]\n #\n # next if current_cell.nil?\n # duped_rows[row_idx][col_idx] = current_cell.dup\n # end\n # end\n # duped_board = self.class.new(duped_rows, false)\n # duped_board.pieces.each do |piece|\n # piece.board = duped_board\n # end\n # duped_board\n\n end", "def dup_board\n new_board = Board.new(false)\n self.grid.each_with_index do |row, i|\n row.each_with_index do |object, j|\n pos = [i, j]\n if object.nil?\n new_board[pos] = nil\n else\n new_board[pos] = Piece.new(object.color, pos, new_board)\n end\n end\n end\n\n new_board\n end", "def initialize_copy(original_board)\n @rows = original_board.rows.map do |row|\n row.map do |piece|\n if piece.is_a?(NullPiece)\n NullPiece.instance\n else\n new_piece = piece.dup\n new_piece.board = self\n new_piece\n end\n end\n end\n end", "def dup(*) end", "def clone(source)\n copy(source, true)\n end", "def copy(copy)\n\t\t\treturn Alimento.new(copy.nombre,copy.proteinas,copy.carbohidratos,copy.lipidos,copy.gei,copy.terreno)\n\t\tend", "def dup\n result = self.class.new(dimension, geometric_resolution, order)\n result.send(:initialize_copy, self)\n result\n end", "def clone\n other = dup\n other.freeze if frozen?\n other\n end" ]
[ "0.74546385", "0.7397606", "0.73529285", "0.73529285", "0.73529285", "0.7342701", "0.7327746", "0.7327746", "0.7327746", "0.7322227", "0.7093711", "0.7093711", "0.70727116", "0.69959784", "0.6974457", "0.696427", "0.6865983", "0.6811762", "0.6811762", "0.68043834", "0.6770732", "0.67523515", "0.66584206", "0.6634202", "0.65177923", "0.64816576", "0.646421", "0.64409214", "0.63803774", "0.6380008", "0.6364132", "0.6359987", "0.63188905", "0.62843287", "0.62386364", "0.62237006", "0.62231785", "0.61912084", "0.61906374", "0.617436", "0.61734396", "0.61465627", "0.61450446", "0.6133695", "0.6116818", "0.61094373", "0.60838306", "0.6082724", "0.6081711", "0.60736096", "0.60601664", "0.60493827", "0.60464936", "0.6032284", "0.6032284", "0.6029943", "0.602843", "0.602843", "0.602843", "0.602843", "0.602843", "0.60220116", "0.6017412", "0.6013084", "0.60025024", "0.599942", "0.5991098", "0.59833837", "0.5978722", "0.59739417", "0.5953635", "0.59475356", "0.59410477", "0.5936833", "0.593139", "0.59299356", "0.5929801", "0.5925137", "0.5925137", "0.5925137", "0.59207046", "0.59207046", "0.59207046", "0.59207046", "0.59207046", "0.5910006", "0.5901224", "0.58975685", "0.5891574", "0.588439", "0.5882878", "0.5872399", "0.5869125", "0.5868683", "0.58670926", "0.586383", "0.586078", "0.5858804", "0.5857698", "0.58563805" ]
0.64461833
27
GET /webs GET /webs.json
def index # @webs = Web.all[0..100] # @webs = Web.where(urlx: FALSE).where.not(url_ver_date: nil).order("url_ver_date DESC")[0..100] # @webs = Web.where(urlx: FALSE). # where.not(url_ver_date: nil). # order("url_ver_date DESC"). # paginate(:page => params[:page], :per_page => 20) @webs = Web.where(urlx: FALSE). where.not(url_ver_date: nil). order(sort_column + ' ' + sort_direction). paginate(:page => params[:page], :per_page => 50) respond_to do |format| format.html format.js end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @web = Web.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @web }\n end\n end", "def index\n @web_data = WebData.all\n end", "def web_request\n response_string = RestClient.get('http://www.swapi.co/api/people/')\n response_hash = JSON.parse(response_string)\nend", "def show\n @web_page = WebPage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @web_page.to_api_hash }\n end\n end", "def index\n @webfiles = Webfile.all\n end", "def realtime\n render :json=>WebUrl.all.map(&:url).to_json\n end", "def show\n @web_app = WebApp.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @web_app }\n end\n end", "def index\n weathers = Weather.all\n render json: weathers, status: 200\n end", "def show\n @website = Website.find(params[:id])\n\n render json: @website\n end", "def index\n @webtoons = Webtoon.all\n end", "def index \n @source_webs = SourceWeb.websources(params[:project_id]) \n end", "def index\n @urls = Url.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @urls }\n end\n end", "def index\n @webapps = Webapp.all\n end", "def list\n get('/')\n end", "def show\n @webling = Webling.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @webling }\n end\n end", "def index\n @gets = Get.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gets }\n end\n end", "def index\n @webusers = Webuser.all\n end", "def index\n @users = User.all\n binding.pry\n require 'net/http'\n result = Net::HTTP.get('makesys.net', '/')\n p result\n end", "def index\n @watch_sites = WatchSite.includes(:team, :venue).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @watch_sites }\n end\n end", "def getJson(url)\n\t\tencoded_url = URI.encode(\"https://cryptic-mountain-56365.herokuapp.com/api/v1\"+url)\n\t\turi = URI.parse(encoded_url)\n\t\tjson = Net::HTTP.get(uri)\n\tend", "def index\n @websites = Website.all\n end", "def index\n @websites = Website.all\n end", "def index\n @websites = Website.all\n end", "def index\n @urls = Url.get_top(25)\n # render json: @urls\n end", "def swapi_fetch(url)\n JSON.parse(open(url).read)\nend", "def index\n @web_car_galleries = WebCarGallery.all\n\n render json: @web_car_galleries\n end", "def serv_json\n \"http://api.dribbble.com/shots/popular?page=1\"\n end", "def index\n @urls = ShortenedUrl.order(\"updated_at ASC\").all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @urls }\n end\n end", "def index\n @searches = @website.searches.all\n\n respond_to do |format|\n format.html #index.html.erb\n format.json { render json: @searches }\n end\n end", "def heros\n get('/hero/')\n end", "def index\n @whoarewes = Whoarewe.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @whoarewes }\n end\n end", "def index\n @webapps = (params[:category_id]) ? Category.find(params[:category_id]).webapps.validated : Webapp.includes(:category, :comments, :user).validated\n render json: @webapps, :each_serializer => WebappLazySerializer\n end", "def index\n @urls = @site.urls.paginate(:page => params[:page])\n render json: @urls\n end", "def index\n # @wikis = Wiki.all\n @wikis = Wiki.find_all_by_title('Home')\n @allwikis = Wiki.recent.limit(10) \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @wikis }\n end\n end", "def all\n render json: Url.all\n end", "def find_space_webapis(params={}, headers=default_headers)\n @logger.info(\"Finding all Web APIs on the Space\")\n get(\"#{@api_url}/webApis\", params, headers)\n end", "def view_api\n api_string = RestClient.get(\"https://itunes.apple.com/search?term=star+wars&entity=song&attribute=movieTerm\")\n api_hash = JSON.parse(api_string)\n\n end", "def index\n render json: {\n status: :success,\n urls: ShortUrl::top_100\n }\n end", "def index\n @wowolinks = Wowolink.all\n respond_to do |format|\n format.json {\n render :json => @wowolinks, :layout => false\n }\n end\n end", "def index\n @webtiers = Webtier.all\n end", "def get_api_json\n response_string = RestClient.get('http://www.swapi.co/api/people/')\n JSON.parse(response_string)\nend", "def index\n @money = Money.all\n require 'net/http'\n require 'json'\n @url = 'https://api.coinmarketcap.com/v1/ticker/'\n @uri = URI(@url)\n @response = Net::HTTP.get(@uri)\n @lookup_money = JSON.parse(@response)\n end", "def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end", "def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end", "def index\n @servers = Server.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @servers.to_json(:include => { :websites => {:include => :plugins } }) }\n end\n end", "def index\n @heroes = Hero.all\n\n render json: @heroes\n end", "def index\n @loves = Love.all\n render json: @loves\n end", "def index\n @wks = Wk.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @wks }\n end\n end", "def index\n player = Player.all\n render json: players, status: 200\n end", "def index\n @winners = Winner.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @winners }\n end\n end", "def extract_web_entries\n @web_sites = myworkspace.web_sites\n @web_pages = myworkspace.web_pages\n @web_forms = myworkspace.web_forms\n @web_vulns = myworkspace.web_vulns\n end", "def index\n @simple_chores = SimpleChore.all\n respond_to do |format|\n format.html\n format.json { render :json => @simple_chores }\n end\n end", "def make_search(url)\n #make the web request\n data = RestClient.get url\n JSON.parse(data)\nend", "def index\n @websites = Website.find(:all, :order => 'name')\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @websites.to_xml }\n end\n end", "def index\n @site_setups = SiteSetup.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_setups }\n end\n end", "def find_kapp_webapis(kapp_slug, params={}, headers=default_headers)\n @logger.info(\"Finding all Web APIs on the \\\"#{kapp_slug}\\\" Kapp.\")\n get(\"#{@api_url}/kapps/#{kapp_slug}/webApis\", params, headers)\n end", "def index\n @trackers = Tracker.where(public: true)\n\n render json: @trackers\n end", "def get(url); end", "def index\n @weddings = Wedding.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @weddings }\n end\n end", "def index\n respond_to do |format|\n format.html do \n @sites = Site.all\n end\n format.json do\n render json: Site.all\n end\n end\n end", "def index\n @pubs = Pub.all\n\n render json: @pubs\n end", "def index\n @blogs = Blog.all\n\n render json: @blogs\n end", "def index\n @thumbs = Thumb.all\n\n render json: @thumbs\n end", "def rest_get(url)\n JSON.parse(RestClient.get(url))\n end", "def get_webinar(webinar_id:)\n parse(JSON.parse(connection.get(\"webinars/#{webinar_id}\").body))\n end", "def index\n @parsed_sites = ParsedSite.all\n\n render json: @parsed_sites\n end", "def url_list\n urls = current_user.mini_urls\n if urls.count > 0\n render json: {urls: urls}, status: 200\n else\n raise Exceptions::EmptyObjectError.new('No URL found.')\n end\n rescue Exceptions::EmptyObjectError => e\n render json: {error: e}, status: 404\n end", "def index\n @blogs = Blog.all\n render json: @blogs\n end", "def index\n @fhir_base_urls = FhirBaseUrl.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @fhir_base_urls }\n end\n end", "def index\n @teams = Team.all\n render json: @teams\n end", "def show\n render json: @wellist\n end", "def web\n return @web\n end", "def index\n @urls = Url.all\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render xml: @urls}\n format.json { render json: @urls }\n end\n end", "def index\n @lessons = Lesson.all\n\n render 'index.json'\n end", "def list\n get 'projects'\n end", "def fetch_json_from_url(url_of_search)\n Net::HTTP.get(URI.parse(url_of_search))\n end", "def index\n @platforms = Platform.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @platforms }\n end\n end", "def index\n render json: Story.all\n end", "def index\n @url_connectors = UrlConnector.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @url_connectors }\n end\n end", "def websites\n self.dig_for_array(\"webSites\")\n end", "def index\n @sightings = Sighting.all\n render json: @sightings\n end", "def index\n render json: Blog.all\n end", "def index\n @players = Player.all\n render json: @players, status: 200\n end", "def index\n @githubers = Githuber.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @githubers }\n end\n end", "def index\n @stopovers = Stopover.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @stopovers }\n end\n end", "def film_api(url)\n film_response = RestClient.get(url)\n film_hash = JSON.parse(film_response)\nend", "def index\n @tracks = Track.all\n render json: {tracks: @tracks}\n end", "def index\n @lights = Light.all\n\n render json: @lights\n end", "def index\n @releases = @environment.releases.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @releases }\n end\n end", "def index\n @website_settings = WebsiteSetting.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @website_settings }\n end\n end", "def list\n @studios = Studio.all;\n return render json: @studios.to_json, status: 200\n end", "def index\n @specialties = Specialty.all\n\n render json: @specialties\n end", "def index\n @urls = Url.all\n end", "def index\n @urls = Url.all\n end", "def index\n render json: @links\n end", "def index\n @wrestlers = Wrestler.all\n end", "def index\n @teams = Team.all\n render :json => @teams\n end", "def show\n @behatweb = Behatweb.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @behatweb }\n end\n end", "def index\n @subthemes = Subtheme.all\n\n render json: @subthemes\n end", "def test_get_site_list\r\n endpoint = \"/sites\"\r\n uri = URI(\"#{@host}#{endpoint}\")\r\n request = Net::HTTP::Get.new(uri)\r\n request['Accept'] = 'application/json'\r\n \r\n test_start = Time.now\r\n response = Net::HTTP.start(uri.hostname, uri.port) do |http|\r\n http.request(request)\r\n end\r\n test_end = Time.now\r\n\r\n @results << {\r\n :api => 'GET /sites',\r\n :endpoint => endpoint,\r\n :start_time => test_start,\r\n :runtime => (test_end.to_f - test_start.to_f) * 1000.0,\r\n :status => response.code,\r\n :content_type => response['content-type']\r\n }\r\n end", "def index\n @web_display_car_images = WebDisplayCarImage.all\n\n render json:@web_display_car_images\n end" ]
[ "0.68628013", "0.63853025", "0.6382949", "0.6311019", "0.62302643", "0.61907417", "0.6185653", "0.617709", "0.6166561", "0.61606383", "0.61360353", "0.61353517", "0.6105999", "0.60638416", "0.605097", "0.5969948", "0.59571475", "0.5934651", "0.5934212", "0.59248626", "0.5923084", "0.5923084", "0.5923084", "0.59134984", "0.59101236", "0.5907974", "0.5905022", "0.58813184", "0.5872249", "0.5859962", "0.5852869", "0.58447766", "0.584248", "0.5805687", "0.57922816", "0.5779722", "0.5760571", "0.57333344", "0.5732656", "0.57247204", "0.57238156", "0.57158446", "0.5707226", "0.5707226", "0.5689756", "0.5688716", "0.568497", "0.5682684", "0.5682436", "0.56710124", "0.56584734", "0.56569564", "0.5651494", "0.5642666", "0.56385595", "0.5634059", "0.56199706", "0.5613626", "0.5598535", "0.5596256", "0.5596045", "0.558959", "0.55856967", "0.55845785", "0.55843896", "0.55767643", "0.5570979", "0.55659735", "0.5560062", "0.5554349", "0.55528563", "0.5544144", "0.55439544", "0.5532541", "0.5525421", "0.5524566", "0.5521582", "0.5516134", "0.55050844", "0.55013144", "0.55011135", "0.5498195", "0.54975307", "0.5488457", "0.5486798", "0.54867077", "0.54839385", "0.5482536", "0.54809576", "0.54784364", "0.54779756", "0.54758704", "0.54741853", "0.54741853", "0.5469891", "0.54696566", "0.5468891", "0.5468632", "0.5466955", "0.54661244", "0.54654723" ]
0.0
-1
GET /webs/1 GET /webs/1.json
def show respond_to do |format| format.html format.js end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @web = Web.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @web }\n end\n end", "def show\n @web_app = WebApp.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @web_app }\n end\n end", "def show\n @web_page = WebPage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @web_page.to_api_hash }\n end\n end", "def show\n @website = Website.find(params[:id])\n\n render json: @website\n end", "def index\n @web_data = WebData.all\n end", "def show\n @webling = Webling.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @webling }\n end\n end", "def index \n @source_webs = SourceWeb.websources(params[:project_id]) \n end", "def web_request\n response_string = RestClient.get('http://www.swapi.co/api/people/')\n response_hash = JSON.parse(response_string)\nend", "def index\n @webfiles = Webfile.all\n end", "def index\n weathers = Weather.all\n render json: weathers, status: 200\n end", "def index\n @webapps = Webapp.all\n end", "def index\n @webtoons = Webtoon.all\n end", "def show\n @web_image = WebImage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @web_image }\n end\n end", "def realtime\n render :json=>WebUrl.all.map(&:url).to_json\n end", "def index\n @webusers = Webuser.all\n end", "def show\n @behatweb = Behatweb.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @behatweb }\n end\n end", "def new\n @web_app = WebApp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @web_app }\n end\n end", "def set_web\n @web = Web.find(params[:id])\n end", "def serv_json\n \"http://api.dribbble.com/shots/popular?page=1\"\n end", "def index\n @websites = Website.all\n end", "def index\n @websites = Website.all\n end", "def index\n @websites = Website.all\n end", "def index\n @urls = Url.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @urls }\n end\n end", "def show\n @wager = Wager.find(params[:id])\n\n render json: @wager\n end", "def index\n @gets = Get.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gets }\n end\n end", "def destroy\n @web = Web.find(params[:id])\n @web.destroy\n\n respond_to do |format|\n format.html { redirect_to webs_url }\n format.json { head :no_content }\n end\n end", "def swapi_fetch(url)\n JSON.parse(open(url).read)\nend", "def show\n @web_service_log = WebServiceLog.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @web_service_log }\n end\n end", "def index\n # @wikis = Wiki.all\n @wikis = Wiki.find_all_by_title('Home')\n @allwikis = Wiki.recent.limit(10) \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @wikis }\n end\n end", "def index\n @webtiers = Webtier.all\n end", "def index\n @urls = Url.get_top(25)\n # render json: @urls\n end", "def get_default_profile \n get(\"/profiles.json/default\")\nend", "def index\n @money = Money.all\n require 'net/http'\n require 'json'\n @url = 'https://api.coinmarketcap.com/v1/ticker/'\n @uri = URI(@url)\n @response = Net::HTTP.get(@uri)\n @lookup_money = JSON.parse(@response)\n end", "def index\n @users = User.all\n binding.pry\n require 'net/http'\n result = Net::HTTP.get('makesys.net', '/')\n p result\n end", "def getJson(url)\n\t\tencoded_url = URI.encode(\"https://cryptic-mountain-56365.herokuapp.com/api/v1\"+url)\n\t\turi = URI.parse(encoded_url)\n\t\tjson = Net::HTTP.get(uri)\n\tend", "def index\n @web_car_galleries = WebCarGallery.all\n\n render json: @web_car_galleries\n end", "def get_webinar(webinar_id:)\n parse(JSON.parse(connection.get(\"webinars/#{webinar_id}\").body))\n end", "def index\n @whoarewes = Whoarewe.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @whoarewes }\n end\n end", "def get_api_json\n response_string = RestClient.get('http://www.swapi.co/api/people/')\n JSON.parse(response_string)\nend", "def show\n @web_info = WebInfo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @web_info }\n end\n end", "def create\n @web = Web.new(web_params)\n\n respond_to do |format|\n if @web.save\n format.html { redirect_to @web, notice: 'Web was successfully created.' }\n format.json { render :show, status: :created, location: @web }\n else\n format.html { render :new }\n format.json { render json: @web.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @webapps = (params[:category_id]) ? Category.find(params[:category_id]).webapps.validated : Webapp.includes(:category, :comments, :user).validated\n render json: @webapps, :each_serializer => WebappLazySerializer\n end", "def index\n @simple_chores = SimpleChore.all\n respond_to do |format|\n format.html\n format.json { render :json => @simple_chores }\n end\n end", "def index\n @heroes = Hero.all\n\n render json: @heroes\n end", "def index\n @watch_sites = WatchSite.includes(:team, :venue).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @watch_sites }\n end\n end", "def show\n hub = Hub.find(params[:id])\n respond_to do |format|\n format.json { render :json => hub.warehouses }\n end\n end", "def set_web\n @web = Web.find(params[:id]) if params[:id].is_a?(Integer)\n end", "def view_api\n api_string = RestClient.get(\"https://itunes.apple.com/search?term=star+wars&entity=song&attribute=movieTerm\")\n api_hash = JSON.parse(api_string)\n\n end", "def index\n @websites = Website.where(client_id: current_client.uuid) \n end", "def index\n @urls = ShortenedUrl.order(\"updated_at ASC\").all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @urls }\n end\n end", "def index\n @websites = Website.find(:all, :order => 'name')\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @websites.to_xml }\n end\n end", "def index\n @web_service_logs = WebServiceLog.limit(20).order(\"id desc\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @web_service_logs }\n end\n end", "def web\n return @web\n end", "def index\n @shop = Shop.find(1)\n render :json => @shop\n return\n end", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n puts JSON.pretty_generate(result)\n result\nend", "def index\n @thumbs = Thumb.all\n\n render json: @thumbs\n end", "def heros\n get('/hero/')\n end", "def show\n @website = Website.find(params[:id])\n end", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def show\n @strategyweb = Strategyweb.find(params[:id])\n\n respond_to do |format|\n format.html\n# format.json { render json: @strategyweb }\n end\n end", "def index\n @api_v1_todos = Todo.all\n render json: @api_v1_todos\n end", "def index\n @website_settings = WebsiteSetting.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @website_settings }\n end\n end", "def index\n hardware = Hardware.all\n render json: hardware.to_json(:except => [:id])\n end", "def index\n @platforms = Platform.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @platforms }\n end\n end", "def show\n render json: @wellist\n end", "def index\n @wks = Wk.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @wks }\n end\n end", "def index\n @winners = Winner.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @winners }\n end\n end", "def index\n @site_setups = SiteSetup.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_setups }\n end\n end", "def list\n get('/')\n end", "def index\n json_response(@device.browsers)\n end", "def view\n res = @client.get(path)\n @attributes = res.json if res.success?\n end", "def get_json(path)\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n #puts \"🤖 GET #{path}\"\n #puts \"HTTP #{response.code}\"\n #puts JSON.pretty_generate(result)\n result\nend", "def index\n @searches = @website.searches.all\n\n respond_to do |format|\n format.html #index.html.erb\n format.json { render json: @searches }\n end\n end", "def new\n @webling = Webling.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @webling }\n end\n end", "def show\n @heroku = Heroku.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @heroku }\n end\n end", "def index\n player = Player.all\n render json: players, status: 200\n end", "def get_json()\n\n http = Net::HTTP.new(STATUS_URI.host, STATUS_URI.port)\n http.use_ssl = false\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Get.new(\"/api/services.json\")\n\n response = http.request(request)\n JSON.parse(response.body)\nend", "def index\n @releases = @environment.releases.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @releases }\n end\n end", "def index\n @blogs = Blog.all\n\n render json: @blogs\n end", "def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end", "def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end", "def show\n\t\trender json: @url, status: 200\n\tend", "def show\n @webservicetolisten = Webservicetolisten.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @webservicetolisten }\n end\n end", "def index\n info = Aws.get_recipes_from_db\n render :json => info\n end", "def destroy\n @web.destroy\n respond_to do |format|\n format.html { redirect_to webs_url, notice: 'Web was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def index\n @web_display_car_images = WebDisplayCarImage.all\n\n render json:@web_display_car_images\n end", "def index\n @loves = Love.all\n render json: @loves\n end", "def index\n render json: {\n status: :success,\n urls: ShortUrl::top_100\n }\n end", "def index\n @weddings = Wedding.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @weddings }\n end\n end", "def index\n @lights = Light.all\n\n render json: @lights\n end", "def film_api(url)\n film_response = RestClient.get(url)\n film_hash = JSON.parse(film_response)\nend", "def index\n @wms = WmsResult.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @wms }\n end\n end", "def index\n @blogs = Blog.all\n render json: @blogs\n end", "def rest_get(url)\n JSON.parse(RestClient.get(url))\n end", "def index\n @specialties = Specialty.all\n\n render json: @specialties\n end", "def index\n @lessons = Lesson.all\n\n render 'index.json'\n end", "def make_search(url)\n #make the web request\n data = RestClient.get url\n JSON.parse(data)\nend", "def show\n @webpage = Webpage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @webpage }\n end\n end", "def show\n @weather = Weather.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @weather }\n end\n end", "def show\n @weather = Weather.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @weather }\n end\n end" ]
[ "0.7459528", "0.6844274", "0.6693412", "0.6692964", "0.646974", "0.64299685", "0.6338626", "0.6321607", "0.62605476", "0.6235527", "0.6231753", "0.61801666", "0.6178771", "0.61171895", "0.60300744", "0.60118186", "0.59711516", "0.5927276", "0.5914978", "0.590498", "0.590498", "0.590498", "0.58809686", "0.5853889", "0.58425504", "0.5831612", "0.5827569", "0.581989", "0.58052856", "0.57991815", "0.57872987", "0.578635", "0.578174", "0.5761013", "0.57587", "0.57559747", "0.5753447", "0.5752483", "0.5739726", "0.5728785", "0.5719029", "0.5716482", "0.57113194", "0.5708583", "0.5703861", "0.57021993", "0.5700024", "0.56963986", "0.569343", "0.5678828", "0.5665498", "0.5664501", "0.56552166", "0.56354237", "0.5629549", "0.56261194", "0.5622184", "0.56154394", "0.5614546", "0.5614546", "0.5611667", "0.56100845", "0.560922", "0.56014466", "0.56007564", "0.55973965", "0.5597176", "0.55892515", "0.5581701", "0.5579939", "0.5571357", "0.55595785", "0.5553916", "0.55506104", "0.5548151", "0.55411726", "0.5538464", "0.5538353", "0.5536324", "0.55358714", "0.5535827", "0.5535827", "0.5513884", "0.5512098", "0.5506521", "0.5505993", "0.5505258", "0.5505029", "0.5503435", "0.55016243", "0.5500136", "0.5496465", "0.5496317", "0.5490299", "0.5488949", "0.54833525", "0.54802495", "0.5478129", "0.5477933", "0.5473857", "0.5473857" ]
0.0
-1
POST /webs POST /webs.json
def create @web = Web.new(web_params) respond_to do |format| if @web.save format.html { redirect_to @web, notice: 'Web was successfully created.' } format.json { render :show, status: :created, location: @web } else format.html { render :new } format.json { render json: @web.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n params[:url_list].each do |url|\n WebUrl.new(:url => url).save\n end\n render :json=>params[:url_list].to_json\n end", "def create\n @webtoon = Webtoon.new(webtoon_params)\n\n respond_to do |format|\n if @webtoon.save\n format.html { redirect_to @webtoon, notice: 'Webtoon was successfully created.' }\n format.json { render :show, status: :created, location: @webtoon }\n else\n format.html { render :new }\n format.json { render json: @webtoon.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @source_web = SourceWeb.new(source_web_params)\n\n respond_to do |format|\n if @source_web.save\n format.html { redirect_to @source_web, notice: 'Source web was successfully created.' }\n format.json { render :show, status: :created, location: @source_web }\n else\n format.html { render :new }\n format.json { render json: @source_web.errors, status: :unprocessable_entity }\n end\n end\n end", "def web_params\n params.require(:web).permit(:url, :url_ver_sts, :sts_code, :url_ver_date, :tmp_sts, :temp_name, :tmp_date, :slink_sts, :llink_sts, :stext_sts, :ltext_sts, :pge_date, :as_sts, :as_date, :cs_sts, :cs_date, :created_at, :updated_at)\n end", "def create\n @web_app = WebApp.new(params[:web_app])\n\n respond_to do |format|\n if @web_app.save\n format.html { redirect_to @web_app, notice: 'Web app was successfully created.' }\n format.json { render json: @web_app, status: :created, location: @web_app }\n else\n format.html { render action: \"new\" }\n format.json { render json: @web_app.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @web_datas = WebData.new(web_datas_params)\n\n respond_to do |format|\n if @web_datas.save\n format.html { redirect_to @web_datas, notice: 'Web datas was successfully created.' }\n format.json { render :show, status: :created, location: @web_datas }\n else\n format.html { render :new }\n format.json { render json: @web_datas.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @website = Website.new(website_params)\n\n if @website.save\n render json: @website, status: :created, location: @website\n else\n render json: @website.errors, status: :unprocessable_entity\n end\n end", "def create\n \n\t@strategyweb = Strategyweb.new(params[:strategyweb])\n\n respond_to do |format|\n if @strategyweb.save\n format.html { redirect_to @strategyweb, notice: 'Strategyweb was successfully created.' }\n format.json { render json: @strategyweb, status: :created, location: @strategyweb }\n else\n format.html { render action: \"new\" }\n format.json { render json: @strategyweb.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @webscrape = Webscrape.new(webscrape_params)\n\n respond_to do |format|\n if @webscrape.save\n format.html { redirect_to @webscrape, notice: 'Webscrape was successfully created.' }\n format.json { render :show, status: :created, location: @webscrape }\n else\n format.html { render :new }\n format.json { render json: @webscrape.errors, status: :unprocessable_entity }\n end\n end\n end", "def web_request\n response_string = RestClient.get('http://www.swapi.co/api/people/')\n response_hash = JSON.parse(response_string)\nend", "def create\n @website = websites.new(website_params)\n\n respond_to do |format|\n if @website.save\n flash[:notice] = :success\n format.html { redirect_to @website, notice: 'Website was successfully created.' }\n format.json { render :show, status: :created, location: @website }\n else\n format.html { render :new }\n format.json { render json: @website.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @webling = Webling.new(params[:webling])\n\n respond_to do |format|\n if @webling.save\n format.html { redirect_to @webling, notice: 'Webling was successfully created.' }\n format.json { render json: @webling, status: :created, location: @webling }\n else\n format.html { render action: \"new\" }\n format.json { render json: @webling.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @web_app = WebApp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @web_app }\n end\n end", "def create\n @webtier = Webtier.new(webtier_params)\n\n respond_to do |format|\n if @webtier.save\n format.html { redirect_to @webtier, notice: 'webtier was successfully created.' }\n format.json { render :show, status: :created, location: @webtier }\n else\n format.html { render :new }\n format.json { render json: @webtier.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @wod = Wod.new(wod_params)\n\n if @wod.save\n render json: @wod, status: :created\n else\n render json: @wod.errors, status: :unprocessable_entity\n end\n end", "def create\n @web_table = Web::Table.new(web_table_params)\n\n respond_to do |format|\n if @web_table.save\n format.html { redirect_to @web_table, notice: 'Table was successfully created.' }\n format.json { render :show, status: :created, location: @web_table }\n else\n format.html { render :new }\n format.json { render json: @web_table.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @web_data = WebData.all\n end", "def create\n @wager = Wager.new(params[:wager])\n\n if @wager.save\n render json: @wager, status: :created, location: @wager\n else\n render json: @wager.errors, status: :unprocessable_entity\n end\n end", "def create_modified_web_p(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end", "def create(url, data)\n RestClient.post ENV['APIBASE']+url, data, :content_type => :json\nend", "def web(_request, response)\n response.headers[\"Content-Type\"] = \"application/json\"\n json = MultiJson.dump(\n adapter: robot.config.robot.adapter,\n lita_version: Lita::VERSION,\n redis_memory_usage: redis_memory_usage,\n redis_version: redis_version,\n robot_mention_name: robot.mention_name,\n robot_name: robot.name\n )\n response.write(json)\n end", "def create_fake_web\n url = create_url('teste@email.com', 'contato@aondebrasil.com', 'Teste',\n 'Teste' )\n FakeWeb.register_uri(:post, url, body: '{\"subject\" => \"Teste\",'\\\n ' \"from \"=> \"teste@email.com\", \"text\" => \"teste\",'\\\n ' \"action\" => \"send_simple_message\", \"controller\" => \"contact\"}' )\n end", "def create\n @webservice = Webservice.find(params[:webservice_id])\n @rest_api = @webservice.rest_apis.create(rest_api_params)\n redirect_to webservice_path(@webservice)\n end", "def webtoon_params\n params.require(:webtoon).permit(:writer, :webtoon_name, :gerne)\n end", "def post\n Typhoeus.post(@url,\n body: @results_hash.to_json,\n headers: { 'Content-Type' => 'application/json' })\n end", "def new\n @web= Web.new\n end", "def webscrape_params\n params.require(:webscrape).permit(:name)\n end", "def index\n @webtoons = Webtoon.all\n end", "def create\n @webuser = Webuser.new(webuser_params)\n\n respond_to do |format|\n if @webuser.save\n format.html { redirect_to @webuser, notice: 'Webuser was successfully created.' }\n format.json { render action: 'show', status: :created, location: @webuser }\n else\n format.html { render action: 'new' }\n format.json { render json: @webuser.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @webfile = Webfile.new(webfile_params)\n\n respond_to do |format|\n if @webfile.save\n format.html { redirect_to @webfile, notice: 'Webfile was successfully created.' }\n format.json { render :show, status: :created, location: @webfile }\n else\n format.html { render :new }\n format.json { render json: @webfile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @web_info = WebInfo.new(params[:web_info])\n\n respond_to do |format|\n if @web_info.save\n format.html { redirect_to(@web_info, :notice => 'Web info was successfully created.') }\n format.xml { render :xml => @web_info, :status => :created, :location => @web_info }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @web_info.errors, :status => :unprocessable_entity }\n end\n end\n end", "def add_prowl(options)\n uri = URI.parse(\"https://prowl.weks.net/publicapi/add\")\n https = Net::HTTP.new(uri.host, uri.port)\n # We have to use SSL\n https.use_ssl = true\n # Avoid to get warning\n https.verify_mode = OpenSSL::SSL::VERIFY_NONE\n req = Net::HTTP::Post.new(uri.path)\n # Default options for notifications\n options = {:apikey => $configure[:prowl][:apikey], :application => \"Twitter\", :priority => 0}.merge(options)\n req.set_form_data(options)\n https.request(req)\nend", "def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end", "def destroy\n @web.destroy\n respond_to do |format|\n format.html { redirect_to webs_url, notice: 'Web was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def source_web_params\n params.require(:source_web).permit(:url_collection_name, :url_collection, :scheduler_type_id, :project_id)\n end", "def destroy\n @web = Web.find(params[:id])\n @web.destroy\n\n respond_to do |format|\n format.html { redirect_to webs_url }\n format.json { head :no_content }\n end\n end", "def show\n @web = Web.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @web }\n end\n end", "def create\n @behatweb = Behatweb.new(params[:behatweb])\n\n respond_to do |format|\n \n\n if @behatweb.save\n format.html { redirect_to @behatweb, notice: 'Behatweb was successfully created.' }\n format.json { render json: @behatweb, status: :created, location: @behatweb }\n else\n format.html { render action: \"new\" , :layout => 'default'}\n format.json { render json: @behatweb.errors, status: :unprocessable_entity ,action: \"new\"}\n end\n end\n end", "def makes\n make_request :get, '/makes'\n end", "def create\n @website = Website.new(create_params)\n @website.save!\n # create default values\n @website.create_default\n @website.save!\n \n @websites = Website.all\n .order(created_at: :desc)\n respond_to do |format|\n format.js\n end\n end", "def create\n\t\turi = URI.parse(Counter::Application.config.simplyurl)\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\t\n\t\trequest = Net::HTTP::Post.new('/offsets.json')\n\t\tputs params\n\t\tputs params.slice(*['custids','acctids','itemids'])\n\t\t\n\t\t# ok, this join stuff is bogus - it encodes properly, but the other side only sees the last element and loses the array type - it's just string\n\t\t# this way, i 'split' it at the other side to recover my array\n\t\t# it should work without the join/split crap, but it doesn't\n\t\trequest.set_form_data({:custids => ( params['custids'] || []).join(','), :acctids => ( params['acctids'] || []).join(','), :itemids => ( params['itemids'] || []).join(','), :amount => params['amount'], :type => params['type']})\n\t\t\n\t\tputs request.body\n\t\t\n\t\tresponse = http.request(request)\n\t\tputs response.body\n\n respond_to do |format|\n format.html { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n format.json { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n end\n end", "def create\n @webapp = Webapp.new(webapp_params)\n\n respond_to do |format|\n if @webapp.save\n format.html { redirect_to @webapp, notice: 'Webapp was successfully created.' }\n format.json { render :show, status: :created, location: @webapp }\n else\n format.html { render :new }\n format.json { render json: @webapp.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @web_image = WebImage.new(params[:web_image])\n\n respond_to do |format|\n if @web_image.save\n format.html { redirect_to @web_image, notice: 'Web image was successfully created.' }\n format.json { render json: @web_image, status: :created, location: @web_image }\n else\n format.html { render action: \"new\" }\n format.json { render json: @web_image.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @wellist = Wellist.new(wellist_params)\n\n if @wellist.save\n render json: @wellist, status: :created, location: @wellist\n else\n render json: @wellist.errors, status: :unprocessable_entity\n end\n end", "def create\n HTTParty.post(create_url, :options => { :headers => HEADERS })\n end", "def create_web(name, template, options = {}, &blk)\n\t\t\t # create our new web\n\t\t\t new_web = Webs.create_web(@web, name, template, options)\n\t\t\t context_for_new_object(new_web, WebContext, &blk)\n\t\t\tend", "def index\n @webfiles = Webfile.all\n end", "def set_web\n @web = Web.find(params[:id])\n end", "def update\n respond_to do |format|\n if @web.update(web_params)\n format.html { redirect_to @web, notice: 'Web was successfully updated.' }\n format.json { render :show, status: :ok, location: @web }\n else\n format.html { render :edit }\n format.json { render json: @web.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_webinar(user_id:, params:)\n parse(JSON.parse(connection.post(\"users/#{user_id}/webinars\", params.to_json).body))\n end", "def add_kapp_webapi(kapp_slug, body, headers=default_headers)\n raise StandardError.new \"Web API properties is not valid, must be a Hash.\" unless body.is_a? Hash\n @logger.info(\"Adding the \\\"#{body['slug']}\\\" to the \\\"#{kapp_slug}\\\" Kapp.\")\n post(\"#{@api_url}/kapps/#{kapp_slug}/webApis\", body, headers)\n end", "def post_webhook\n HTTParty.post(\n \"https://api.trello.com/1/tokens/#{user.token}/webhooks/?key=#{ENV['TRELLO_KEY']}\",\n query: {\n description: \"Sprint webhook user#{user.id}\",\n callbackURL: \"#{ENV['BASE_URL']}webhooks\",\n idModel: trello_ext_id\n },\n headers: { \"Content-Type\" => \"application/json\" }\n )\n end", "def create\n \n\t@strategyweb = Strategyweb.new(params[:strategyweb])\n @strategyweb.control=\"strategys\"\n @strategyweb.action=\"show\"\n @strategyweb.anreturn=1\n respond_to do |format|\n if @strategyweb.save\n format.html { redirect_to :action=>\"index\", notice: 'Strategyweb was successfully created.' }\n format.json { render json: @strategyweb, status: :created, location: @strategyweb }\n else\n format.html { render action: \"new\" }\n format.json { render json: @strategyweb.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(url, payload = {}, headers = {})\n http :post, \"#{url}.json\", payload.to_json, headers\n end", "def webpage_params\n params.require(:webpage).permit(:name, :type, :publish)\n end", "def create\n flash[:notice] = 'The website was successfully added.' if website.save\n respond_with(website)\n end", "def playlist\n #Posts new playlist to user's profile\n uri = URI.parse(\"#{@userData[\"href\"]}/playlists\")\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true #this helps with the https\n request = Net::HTTP::Post.new(uri)\n request[\"Authorization\"] = \"Bearer #{@data[\"access_token\"]}\"\n request[\"Content-Type\"] = \"application/json\"\n request.body = \"{\\\"name\\\":\\\"#{session[:genre].split.map(&:capitalize).join(' ')} Artists\\\", \\\"description\\\":\\\"This playlist was generated with the WhatGenre App. Check it out on: http://whatgenre.herokuapp.com\\\"}\"\n response = http.request(request)\n @playlistUrl = JSON.parse(response.read_body)[\"href\"]\n topsongs\nend", "def create\n userID = session[:user_id]\n editionID = params[:edition_id]\n price = params[:price]\n\n uri = URI(\"http://107.170.7.58:4567/api/create/sell\")\n parameters = {\"ext\" => \"json\", \"user_id\" => userID, \"edition_id\" => editionID, \"price\" => price, \"start_date\" => Time.now, \"end_date\" => 90.days.from_now}\n response = Net::HTTP.post_form(uri, parameters)\n list = JSON.parse(response.body)\n\n @response = list[0][\"kind\"]\n end", "def index\n @webapps = Webapp.all\n end", "def index\n @webusers = Webuser.all\n end", "def tweet_from_api\n @tweet_api = User.find(2).tweets.create(tweet_params)\n render json: @tweet_api\n end", "def create\n @webservicetolisten = Webservicetolisten.new(params[:webservicetolisten])\n\n respond_to do |format|\n if @webservicetolisten.save\n format.html { redirect_to @webservicetolisten, notice: 'Webservicetolisten was successfully created.' }\n format.json { render json: @webservicetolisten, status: :created, location: @webservicetolisten }\n else\n format.html { render action: \"new\" }\n format.json { render json: @webservicetolisten.errors, status: :unprocessable_entity }\n end\n end\n end", "def createCharities\n\tcharity_list = [\"Direct Relief\", \"Catholic Medical Mission Board\", \"MAP International\", \"United Nations Foundation\", \"The Rotary Foundation of Rotary International\", \"Samaritan's Purse\", \"Institute of International Education\", \"International Rescue Committee\", \"Compassion International\", \"United States Fund for UNICEF\"]\n\tcharity_list.each do |charity|\n\t\tRestClient.post 'http://api.reimaginebanking.com/merchants?key=e0486a76005721ee6d86b140eaea2a40', { \"name\": \"#{charity}\"}.to_json, :content_type => :json, :accept => :json\n\tend\nend", "def post(url, args = {})\r\n make_request(:post, url, args)\r\n end", "def create\n\t\tStripe::WebhookService.new.instrument(params)\n\t\thead :ok\n\t# rescue StandardError\n\t\t# head :unauthorized\n\tend", "def new\n @webling = Webling.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @webling }\n end\n end", "def do_request(homework)\n uri = URI.parse('https://webhook.site/1e9a10c7-54e0-414b-a1a7-3a7dad38c56d')\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')\n req.body = {\n homework_source: homework.source_code,\n student: fullname,\n pr_title: homework.pr_title\n }.to_json\n http.request(req)\n end", "def test_post_sample_traces\n header 'Content-Type', 'application/json'\n\n (0..4).each do |i|\n data = File.read \"sample-traces/#{i}.json\"\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n assert last_response.ok?\n end\n end", "def send(data)\r\n response = self.create_api_web_send_json(data)\r\n return response\r\n end", "def save_webpage\n @webpage = Webpage.find_or_initialize_by(url: webpage_url)\n @webpage.update(\n body: response_body,\n content_type: content_type,\n primary_ip: primary_ip\n )\n end", "def create_api\n\n @url = Url.new(:url => params[:url])\n\n if @url.save\n url_hash = Hash.new\n\n url_hash[:short_url] = root_url.to_s() + \"urls_api/\" + (@url.id).to_s(36)\n url_hash[:url] = @url.url\n\n render :json => url_hash.to_json\n end\n\n end", "def POST; end", "def index\n json = HTTParty.get(\"https://api.typeform.com/v1/form/WaIffL?key=f486f2db8f1249c077a08b582bc3efe0a2617668\").body\n\n @jsontests = JSON.parse(json)\n\n end", "def create\n # Shopify passes the shop domain (aka uid) as an environment variable,\n # not as part of the request body.\n shop_uid = request.env['HTTP_X_SHOPIFY_SHOP_DOMAIN']\n\n Rails.logger.info(\"Shopify webook received for shop '#{shop_uid}'\")\n\n shop = Shop.find_by(shopify_uid: shop_uid)\n\n if shop\n SynchronizeTeamJob.new.async.perform(shop.team.id)\n else\n Rails.logger.info(\"Shop not found '#{shop_uid}'\")\n end\n\n rescue StandardError => e\n # Rescue any error so that we always respond with 200, otherwise Shopify will disable the webhook.\n # Still log and report an error to newrelic, though, so that we know about it.\n ReportError.call(\"Error processing shopify webhook: #{e.message}\")\n ensure\n head :ok\n end", "def create\n response = @page.parse_url\n render json: response\n end", "def create\r\n @web_user_type = WebUserType.new(web_user_type_params)\r\n\r\n respond_to do |format|\r\n if @web_user_type.save\r\n format.html { redirect_to @web_user_type, notice: 'Tipo de utilizadores web criado com sucesso.' }\r\n format.json { render action: 'show', status: :created, location: @web_user_type }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @web_user_type.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create_params\n params.require(:website).permit(:name, :description)\n end", "def index \n @source_webs = SourceWeb.websources(params[:project_id]) \n end", "def write(files, private_gist = false, description = nil)\n response = request(create_url) do |url|\n Net::HTTP::Post.new(url.path).tap {|req|\n req.body = JSON.generate(data(files, private_gist, description))\n }\n end\n\n case response\n when Net::HTTPUnauthorized\n $stderr.puts \"Invalid credentials connecting to #{api_url}\"\n false\n when Net::HTTPCreated, Net::HTTPOK\n JSON.parse(response.body)['html_url']\n else\n raise StandardError, \"#{response.code} #{response.message}\"\n end\n end", "def create\n @session = SessionService.new(current_user).create_from_web! session_params\n\n respond_to do |format|\n format.html { redirect_to @session, notice: 'Session was successfully created.' }\n format.json { render json: @session, status: :created }\n end\n end", "def create(params)\n post_url = url\n LightspeedCall.make('POST') { HTTParty.post(post_url, body: params.to_json, headers: {Authorization: \"Bearer #{LightspeedApi::OauthGrant.token}\", 'Accept' => 'application/json', 'Content-Type' => 'application/json' }) }\n end", "def webapp_params\n params.require(:webapp).permit(:name, :element)\n end", "def create\n @favorite_web_thing = FavoriteWebThing.new(favorite_web_thing_params)\n\n respond_to do |format|\n if @favorite_web_thing.save\n format.html { redirect_to @favorite_web_thing, notice: 'Favorite web thing was successfully created.' }\n format.json { render action: 'show', status: :created, location: @favorite_web_thing }\n else\n format.html { render action: 'new' }\n format.json { render json: @favorite_web_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_twit(twit)\n RestClient.post configuration.base_url + '/twits',\n { twit: twit }.to_json,\n content_type: :json,\n accept: :json\n end", "def http_post(url, data)\n\turi = URI(url)\n\treq = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})\n req.body = data.to_json\n response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(req) }\n return response\nend", "def create\n @progress_web = ProgressWeb.new(progress_web_params)\n @@clonePW=@progress_web\n respond_to do |format|\n if @progress_web.save\n\n format.html { redirect_to @progress_web, notice: 'Progress web was successfully created.' }\n # format.json { render action: 'show', status: :created, location: @progress_web }\n else\n puts \"FAILED\"\n end\n end\n end", "def new\n @strategyweb = Strategyweb.new\n\n respond_to do |format|\n format.html\n format.json { render json: @strategyweb }\n end\n end", "def post(api, params)\n url2json(:POST, \"#{@endpoint}#{api}\", params)\n end", "def index\n @webtiers = Webtier.all\n end", "def create\n @crawled_site = WebCrawlers.new(\"http://wiprodigital.com/\")\n render :show\n end", "def post(*args)\n request :post, *args\n end", "def post_json(url, data)\n JSON.parse(post(url, data, :json, :json))\n end", "def create\n @response = HTTParty.get('http://laxapi.herokuapp.com/api/teams')\n CreateTeamService.new.create_team_objects(@response)\n render :json => {\n :message => \" #{Team.count} teams have been created\",\n status: 200\n }\n end", "def post_request(secureNetId, secureKey, url)\n uri = URI.parse(url) # Parse the URI\n http = Net::HTTP.new(uri.host, uri.port) # New HTTP connection\n http.use_ssl = true # Must use SSL!\n req = Net::HTTP::Post.new(uri.request_uri) # HTTP POST request \n body = {} # Request body hash\n yield body # Build body of request\n req.body = body.to_json # Convert hash to json string\n req[\"Content-Type\"] = 'application/json' # JSON body\n req[\"Origin\"] = 'worldpay.com' # CORS origin\n req.basic_auth secureNetId, secureKey # HTTP basic auth\n res = http.request(req) # Make the call\n return JSON.parse(res.body) # Convert JSON to hashmap\nend", "def create_list(name)\n data = {\n list: {\n name: name\n }\n }\n rest(\"post\", \"lists\", data)\n end", "def send_webhook\n config = Rails.application.config_for(:webhooks)\n\n return unless config.webhooks\n\n config.webhooks.each do |_k, webhook|\n next if webhook.nil?\n\n url = URI(webhook)\n headers = { 'content-type' => 'application/json' }\n payload = {\n 'job_id' => id,\n 'job_type' => kind,\n 'status' => status,\n 'results' => results.count\n }.to_json\n res = Net::HTTP.post(URI(url), payload, headers)\n\n res.code\n end\n end", "def post endpoint, data\n do_request :post, endpoint, data\n end", "def realtime\n render :json=>WebUrl.all.map(&:url).to_json\n end", "def post(url, params = {})\n client.post(url, params).body\n end", "def new_releases\n api_call(\"https://api.spotify.com/\",\"/v1/browse/new-releases\")\n end" ]
[ "0.63210946", "0.5958433", "0.5936645", "0.5894691", "0.5861048", "0.58557266", "0.58455706", "0.5697086", "0.5642276", "0.5636574", "0.5621937", "0.55018014", "0.54857093", "0.5477344", "0.5440458", "0.5398539", "0.5395116", "0.5392223", "0.538897", "0.53792363", "0.5373494", "0.53701645", "0.53468436", "0.5343413", "0.53291625", "0.53283745", "0.53235066", "0.53160787", "0.5302286", "0.5302064", "0.5293738", "0.52780664", "0.52722394", "0.5271395", "0.5270465", "0.52649605", "0.5262855", "0.5262311", "0.52213645", "0.5213538", "0.5211554", "0.51933104", "0.5162581", "0.51471496", "0.5140022", "0.51398546", "0.5135447", "0.5128479", "0.5124143", "0.51115", "0.5099439", "0.5098012", "0.5097957", "0.5083515", "0.50412834", "0.5035476", "0.5033512", "0.50327593", "0.50230396", "0.5022536", "0.5019088", "0.5016558", "0.5005224", "0.50033605", "0.500212", "0.5000043", "0.49986818", "0.49934497", "0.49908453", "0.49886444", "0.49832922", "0.4982183", "0.49725747", "0.49703234", "0.49648973", "0.49545082", "0.49541786", "0.49537042", "0.49534798", "0.49450228", "0.49337423", "0.49328563", "0.49326253", "0.49301967", "0.49223697", "0.49220884", "0.49125636", "0.49033043", "0.49028927", "0.4895105", "0.48936507", "0.4893142", "0.48847365", "0.48784834", "0.48769608", "0.48755193", "0.48751253", "0.48721117", "0.4869042", "0.486632" ]
0.6659848
0
PATCH/PUT /webs/1 PATCH/PUT /webs/1.json
def update respond_to do |format| if @web.update(web_params) format.html { redirect_to @web, notice: 'Web was successfully updated.' } format.json { render :show, status: :ok, location: @web } else format.html { render :edit } format.json { render json: @web.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @web = Web.find(params[:id])\n\n respond_to do |format|\n if @web.update_attributes(params[:web])\n format.html { redirect_to @web, notice: 'Web was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @web.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @web_app = WebApp.find(params[:id])\n\n respond_to do |format|\n if @web_app.update_attributes(params[:web_app])\n format.html { redirect_to @web_app, notice: 'Web app was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @web_app.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def patch!\n request! :patch\n end", "def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end", "def update\n @behatweb = Behatweb.find(params[:id])\n\n respond_to do |format|\n if @behatweb.update_attributes(params[:behatweb])\n format.html { redirect_to @behatweb, notice: 'Behatweb was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @behatweb.errors, status: :unprocessable_entity }\n end\n end\n end", "def put_update(options = {})\n options[:id] ||= @website.id\n options[:website] ||= @attributes\n\n put :update,options\n end", "def update\n respond_to do |format|\n if @webfile.update(webfile_params)\n format.html { redirect_to @webfile, notice: 'Webfile was successfully updated.' }\n format.json { render :show, status: :ok, location: @webfile }\n else\n format.html { render :edit }\n format.json { render json: @webfile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update # PATCH\n raise NotImplementedError\n end", "def update\n @web_info = WebInfo.find(params[:id])\n\n respond_to do |format|\n if @web_info.update_attributes(params[:web_info])\n format.html { redirect_to(web_infos_url) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @web_info.errors, :status => :unprocessable_entity }\n end\n end\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def update\n @webling = Webling.find(params[:id])\n\n respond_to do |format|\n if @webling.update_attributes(params[:webling])\n format.html { redirect_to @webling, notice: 'Webling was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @webling.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @webtoon.update(webtoon_params)\n format.html { redirect_to @webtoon, notice: 'Webtoon was successfully updated.' }\n format.json { render :show, status: :ok, location: @webtoon }\n else\n format.html { render :edit }\n format.json { render json: @webtoon.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(url, payload, headers={})\n RestClient.patch url, payload, headers\n end", "def update\n respond_to do |format|\n if @favorite_web_thing.update(favorite_web_thing_params)\n format.html { redirect_to @favorite_web_thing, notice: 'Favorite web thing was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @favorite_web_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @web_datas.update(web_datas_params)\n format.html { redirect_to @web_datas, notice: 'Web datas was successfully updated.' }\n format.json { render :show, status: :ok, location: @web_datas }\n else\n format.html { render :edit }\n format.json { render json: @web_datas.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @todo = Todo.find(params[:id])\n @todo.update_attributes(params[:todo])\n render :json => @todo\n end", "def update\n respond_to do |format|\n if @web_table.update(web_table_params)\n format.html { redirect_to @web_table, notice: 'Table was successfully updated.' }\n format.json { render :show, status: :ok, location: @web_table }\n else\n format.html { render :edit }\n format.json { render json: @web_table.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def patch(payload)\n post_like payload, Net::HTTP::Patch.new(@uri.path)\n end", "def put!\n request! :put\n end", "def update\n head :ok\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @name = args[:name] if args.key?(:name)\n @starred = args[:starred] if args.key?(:starred)\n @web_properties = args[:web_properties] if args.key?(:web_properties)\n end", "def update\n put :update\n end", "def update\n @go_slim = GoSlim.find(params[:id])\n\n respond_to do |format|\n if @go_slim.update_attributes(params[:go_slim])\n format.html { redirect_to @go_slim, notice: 'Go slim was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @go_slim.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @webtier.update(webtier_params)\n format.html { redirect_to @webtier, notice: 'webtier was successfully updated.' }\n format.json { render :show, status: :ok, location: @webtier }\n else\n format.html { render :edit }\n format.json { render json: @webtier.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @strategyweb = Strategyweb.find(params[:id])\n\n respond_to do |format|\n if @strategyweb.update_attributes(params[:strategyweb])\n format.html { redirect_to :action=>\"index\", notice: 'Strategyweb was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @strategyweb.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @website = Website.find(params[:id])\n\n if @website.update(website_params)\n head :no_content\n else\n render json: @website.errors, status: :unprocessable_entity\n end\n end", "def update\n @strategyweb = Strategyweb.find(params[:id])\n\n respond_to do |format|\n if @strategyweb.update_attributes(params[:strategyweb])\n format.html { redirect_to @strategyweb, notice: 'Strategyweb was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @strategyweb.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @source_web.update(source_web_params)\n format.html { redirect_to @source_web, notice: 'Source web was successfully updated.' }\n format.json { render :show, status: :ok, location: @source_web }\n else\n format.html { render :edit }\n format.json { render json: @source_web.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @web_image = WebImage.find(params[:id])\n\n respond_to do |format|\n if @web_image.update_attributes(params[:web_image])\n format.html { redirect_to @web_image, notice: 'Web image was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @web_image.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if :opr == 'edit'\n update\n else\n @team = Team.find_by_id(params[:id])\n @team.update_attributes({:id => params[:id], :name => params[:name], :status => params[:status]})\n\n if request.xhr?\n render :json => @team\n end\n end\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @internal_web_property_id = args[:internal_web_property_id] if args.key?(:internal_web_property_id)\n @kind = args[:kind] if args.key?(:kind)\n @level = args[:level] if args.key?(:level)\n @name = args[:name] if args.key?(:name)\n @profiles = args[:profiles] if args.key?(:profiles)\n @starred = args[:starred] if args.key?(:starred)\n @website_url = args[:website_url] if args.key?(:website_url)\n end", "def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end", "def update(request)\n end", "def update(request)\n end", "def update_kapp_webapi(kapp_slug, slug, body, headers=default_headers)\n @logger.info(\"Updating the \\\"#{slug}\\\" Web API on the \\\"#{kapp_slug}\\\" Kapp.\")\n put(\"#{@api_url}/kapps/#{kapp_slug}/webApis/#{slug}\", body, headers)\n end", "def update\n team_name = params[:name]\n team_description = params[:description]\n team_id = params[:id]\n\n respond_to do |format|\n if OkrTeam.where(id: team_id).update_all(name: team_name, description: team_description)\n format.json { render json: 'Team is updated successfully!', status: :ok }\n else\n format.json { render json: 'Error!', status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_todo.update(api_v1_todo_params)\n format.json { render json: @api_v1_todo, status: :ok }\n else\n format.json { render json: @api_v1_todo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n streak, success = jsonapi_update.to_a\n\n if success\n render_jsonapi(streak, scope: false)\n else\n render_errors_for(streak)\n end\n end", "def update #saves and redirects, saves changes\n end", "def update\n respond_to do |format|\n if @webuser.update(webuser_params)\n format.html { redirect_to @webuser, notice: 'Webuser was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @webuser.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @webhook = Webhook.find(params[:id])\n\n respond_to do |format|\n if @webhook.update_attributes(params[:webhook])\n format.html { redirect_to @webhook, notice: 'Webhook was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @webhook.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @client_id = args[:client_id] if args.key?(:client_id)\n @kind = args[:kind] if args.key?(:kind)\n @web_property_id = args[:web_property_id] if args.key?(:web_property_id)\n end", "def update\n request_body_Data= '{ \"widget\":\n {\n \"name\" : \"'+params[:name]+'\",\n \"description\" : \"'+params[:description]+'\"\n }}'\n response = RestClient::Request.new({\n method: :put,\n url: ENV['API_URL'] + '/widgets/' + params[:id],\n payload: request_body_Data,\n headers: { Authorization: session[:access_token], content_type: 'application/json'}\n }).execute do |response, request, result|\n case response.code\n when 400\n [ :error, JSON.parse(response) ]\n when 200\n [ :success, JSON.parse(response) ]\n json=JSON.parse(response)\n @widget= Widget.new do |widget|\n widget.id=json[\"data\"][\"widget\"][\"id\"]\n widget.name=json[\"data\"][\"widget\"][\"name\"]\n widget.description=json[\"data\"][\"widget\"][\"description\"]\n widget.kind=json[\"data\"][\"widget\"][\"kind\"]\n widget.userid=json[\"data\"][\"widget\"][\"user\"][\"id\"]\n widget.username=json[\"data\"][\"widget\"][\"user\"][\"name\"]\n widget.owner=json[\"data\"][\"widget\"][\"owner\"]\n end\n else\n fail \"Invalid response #{response.to_str} received.\"\n end\n end\n respond_to do |format|\n if @widget\n format.html { redirect_to @widget, notice: 'Widget was successfully updated.' }\n format.json { render :show, status: :ok, location: @widget }\n else\n format.html { render :edit }\n format.json { render json: @widget.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n # actions\n path = URI(@endpoint).path\n action = URI(@req.request_uri).path.sub(path, '').split('/')\n action -= ['']\n if action.include?('_history')\n @actions = [action[0], '_history']\n else\n @actions = [action[0]]\n end\n\n # search param\n req_query = URI(@req.request_uri).query\n unless req_query.nil?\n @req_params = URI::decode_www_form(req_query).to_h\n end\n\n # requst method\n if @req.request_method == \"GET\" and @actions.include? '_history'\n @req_method = 'vread'\n elsif @req.request_method == \"GET\" and @req_params != nil\n @req_method = 'search-type'\n elsif @req.request_method == \"PUT\"\n @req_method = 'update'\n elsif @req.request_method == \"POST\"\n @req_method = 'create'\n else\n @req_method = 'read'\n end\n\n # interaction\n int1 = Interaction.last type: @actions[0], code: @req_method\n if int1.nil?\n @present = 0\n else\n @present = int1.id\n @intCode = int1.valueCode\n end\n end", "def update\n @todo = Todo.find(params[:id])\n if @todo.update_attributes(todo_params)\n render json: @todo, status: :ok\n else\n render json: @todo.errors, status: 422\n end\n end", "def update\n @specie = Specie.find(params[:id])\n\n respond_to do |format|\n if @specie.update_attributes(params[:specie])\n format.html { redirect_to @specie, notice: 'Specie was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @specie.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_space_webapi(slug, body, headers=default_headers)\n @logger.info(\"Updating the \\\"#{slug}\\\" Web API on the Space.\")\n put(\"#{@api_url}/webApis/#{slug}\", body, headers)\n end", "def update(attrs, path=nil)\n resp = api_client.put(path || url, JSON.dump(attrs))\n refresh(JSON.load(resp.body))\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update\n set_wine_app_description\n set_wine_app_screenshot\n respond_to do |format|\n if @wine_app.update(wine_app_params)\n format.html { redirect_to @wine_app, notice: 'App was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @wine_app.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(url, data, headers = {})\n request(:patch, url, headers, :data => data)\n end", "def rm_update path, data, msg\n\n re = rm_request path, data, 'PUT'\n puts re.body\n chk (re.code!='200'), msg + \"\\n#{re.code} #{re.msg}\\n\\n\"\n return true\n\nend", "def update_radios_for_array(args = {}) \n id = args['id']\n temp_path = \"/radios.json/{arrayId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"radioId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def update\n @web_clip = WebClip.find(params[:id])\n\n respond_to do |format|\n if @web_clip.update_attributes(params[:web_clip])\n format.html { redirect_to(@web_clip, :notice => 'Web clip was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @web_clip.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @webservicetolisten = Webservicetolisten.find(params[:id])\n\n respond_to do |format|\n if @webservicetolisten.update_attributes(params[:webservicetolisten])\n format.html { redirect_to @webservicetolisten, notice: 'Webservicetolisten was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @webservicetolisten.errors, status: :unprocessable_entity }\n end\n end\n end", "def jsonapi_update!(attributes)\n assign_jsonapi_attributes(attributes)\n save!\n end", "def update\n @serving = Serving.find(params[:id])\n\n respond_to do |format|\n if @serving.update_attributes(params[:serving])\n format.html { redirect_to @serving, notice: 'Serving was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @serving.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def update\n respond_to do |format|\n if @rest_api.update(rest_api_params)\n format.html { redirect_to @rest_api, notice: 'Rest api was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @rest_api.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update\n respond_to do |format|\n if @webapp.update(webapp_params)\n format.html { redirect_to @webapp, notice: 'Webapp was successfully updated.' }\n format.json { render :show, status: :ok, location: @webapp }\n else\n format.html { render :edit }\n format.json { render json: @webapp.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def update\n @patch = Patch.find(params[:id])\n\n respond_to do |format|\n if @patch.update_attributes(params[:patch])\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @supermarket = Supermarket.find(params[:id]) \n respond_to do |format|\n if @supermarket.update(supermarket_params)\n format.json { render json: @supermarket, status: :ok }\n end\n end\n end", "def update\n @todo = Todo.find(params[:id])\n if @todo.update(todo_params)\n render json: @todo\n else\n render json: @todo.errors, status: :unprocessable_entity\n end\n end", "def update\n @api_javascript = Api::Javascript.find(params[:id])\n\n respond_to do |format|\n if @api_javascript.update_attributes(params[:api_javascript])\n format.html { redirect_to @api_javascript, notice: 'Javascript was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @api_javascript.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @webextra = Webextra.find(params[:id])\n params[:webextra][:check_mail] = false\n if session[:userid] != nil and session[:userid] != ''\n @valid_staff = Staff.find(:first, :conditions => [\"userid = ? \", session[:userid]])\n end\n @webextra.staff_id = @valid_staff.id\n if params[:story]\n if params[:story][:name] != nil and params[:story][:name].strip != ''\n story = Story.find_by_name(params[:story][:name].strip)\n if story\n\n @webextra.story_id = story.id\n end\n else\n @webextra.story_id = nil\n end\n end\n respond_to do |format|\n if @webextra.update_attributes(params[:webextra])\n\n if params[:video] and params[:video].original_filename\n extension = File.extname(params[:video].original_filename)\n file_name = @webextra.id.to_s + '_' + Time.now.to_i.to_s\n AWS::S3::S3Object.store(sanitize_filename(file_name + extension), params[:video].read, BUCKET, :access => :public_read)\n @webextra.update_attribute('videourl' ,AWS::S3::S3Object.url_for(file_name + extension, BUCKET, :authenticated => false))\n end\n\n format.html { redirect_to(@webextra, :notice => 'Webextra was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @webextra.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @meteor = Meteor.find(params[:id])\n\n respond_to do |format|\n if @meteor.update_attributes(params[:meteor])\n format.html { redirect_to @meteor, notice: 'Meteor was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @meteor.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Company.update(params[\"id\"], params[\"company\"])\n end", "def update\n @jetty = Jetty.find(params[:id])\n\n respond_to do |format|\n if @jetty.update_attributes(params[:jetty])\n format.html { redirect_to @jetty, notice: 'Jetty was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @jetty.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(url, payload)\n url = URI.parse(url)\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n request = Net::HTTP::Patch.new(url.path+'?access_token=verysecret')\n request.content_type = 'application/json'\n request.body = JSON.generate(payload)\n response = http.start {|http| http.request(request) }\n begin\n return JSON.parse(response.body)\n rescue\n # Log as a problematic case with rule number and line\n $problems.write \"#{$index}, #{payload}, #{response.body}\\n\"\n return nil\n end\nend", "def update\n @one = One.find(params[:id])\n\n respond_to do |format|\n if @one.update_attributes(params[:one])\n format.html { redirect_to @one, notice: 'One was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @one.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(*args)\n put(*args)\n end", "def update(*args)\n put(*args)\n end", "def update\n render json: Post.update(params[\"id\"], params[\"post\"])\n end", "def update\n @web_lock = WebLock.find(params[:id])\n\n respond_to do |format|\n if @web_lock.update_attributes(params[:web_lock])\n flash[:notice] = 'WebLock was successfully updated.'\n format.html { redirect_to(@web_lock) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @web_lock.errors, :status => :unprocessable_entity }\n end\n end\n end", "def patch(path, **args); end", "def update\n @api = Api.find(params[:id])\n\n respond_to do |format|\n if @api.update_attributes(params[:api])\n format.html { redirect_to apis_url, notice: 'Api was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @api.errors, status: :unprocessable_entity }\n end\n end\n end", "def rest_patch(base_uri,json_payload,params)\n begin\n @response = RestClient.patch(base_uri,json_payload,params)\n rescue => e\n puts @response.code\n end\n return @response\n end", "def update\n @team = Team.find(params[:id])\n\n if @team.update_attributes(params[:team])\n head :no_content\n else\n render json: @team.errors, status: :unprocessable_entity\n end\n end", "def update\n @moose = Moose.find(params[:id])\n\n respond_to do |format|\n if @moose.update_attributes(params[:moose])\n format.html { redirect_to @moose, notice: 'Moose was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @moose.errors, status: :unprocessable_entity }\n end\n end\n end", "def UpdateView params = {}\n \n APICall(path: 'views.json',method: 'PUT',payload: params.to_json)\n \n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update!(**args)\n @api_version = args[:api_version] if args.key?(:api_version)\n @cancel_requested = args[:cancel_requested] if args.key?(:cancel_requested)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @status_detail = args[:status_detail] if args.key?(:status_detail)\n @target = args[:target] if args.key?(:target)\n @verb = args[:verb] if args.key?(:verb)\n end", "def update\n head :no_content\n end", "def update\n head :no_content\n end", "def rest_update(uri, method: Net::HTTP::Put)\n request = Net::HTTP::Get.new uri\n request.add_field(\"Accept\",\"application/xml\")\n auth_admin(request)\n \n Net::HTTP.start(uri.host, uri.port) do |http|\n response = http.request request\n response.value\n\n doc = REXML::Document.new response.body\n \n doc = strip_class_attributes(yield doc)\n \n request2 = method.new uri\n request2.content_type = 'application/xml'\n auth_admin(request2)\n\n request2.body=doc.to_s\n \n response2 = http.request request2\n response.value\n\n end\n \nend", "def put(*args)\n request :put, *args\n end", "def update\n @monkey = Monkey.find(params[:id])\n\n respond_to do |format|\n if @monkey.update_attributes(params[:monkey])\n format.html { redirect_to @monkey, notice: 'Monkey was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @monkey.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end" ]
[ "0.6730545", "0.6436215", "0.63101006", "0.6219655", "0.61617935", "0.61148036", "0.60678625", "0.6048004", "0.59634805", "0.59534997", "0.5946364", "0.5923348", "0.5905854", "0.5894249", "0.58909994", "0.587048", "0.58527076", "0.5851738", "0.5850731", "0.58336055", "0.5832964", "0.5832868", "0.5828539", "0.58120763", "0.5807427", "0.5792618", "0.5789434", "0.5788095", "0.57878375", "0.5778393", "0.57563305", "0.5748875", "0.5742002", "0.57322663", "0.57234263", "0.57234263", "0.57108694", "0.5693716", "0.56722665", "0.56712717", "0.5653594", "0.56534696", "0.56358445", "0.5629999", "0.56212646", "0.56165546", "0.5595266", "0.55866235", "0.55863756", "0.55792296", "0.55773205", "0.5573122", "0.5572791", "0.5560491", "0.5557542", "0.5553172", "0.5551378", "0.5550649", "0.55504113", "0.55393475", "0.55326223", "0.55299187", "0.55242145", "0.551878", "0.5516431", "0.5516431", "0.55151755", "0.55151755", "0.550258", "0.54957116", "0.5495238", "0.54943484", "0.54873073", "0.54866207", "0.5482241", "0.54805493", "0.547586", "0.5472433", "0.5469061", "0.5469061", "0.5466904", "0.5459805", "0.54579914", "0.54569507", "0.54553306", "0.54524976", "0.54521084", "0.544857", "0.5448071", "0.5448071", "0.5448071", "0.5448071", "0.5448071", "0.5448071", "0.5446727", "0.5446727", "0.5445461", "0.5442438", "0.54412717", "0.54372644" ]
0.64336544
2
DELETE /webs/1 DELETE /webs/1.json
def destroy @web.destroy respond_to do |format| format.html { redirect_to webs_url, notice: 'Web was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @web = Web.find(params[:id])\n @web.destroy\n\n respond_to do |format|\n format.html { redirect_to webs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @web_app = WebApp.find(params[:id])\n @web_app.destroy\n\n respond_to do |format|\n format.html { redirect_to web_apps_url }\n format.json { head :ok }\n end\n end", "def destroy\n @behatweb = Behatweb.find(params[:id])\n @behatweb.destroy\n\n respond_to do |format|\n format.html { redirect_to behatwebs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @web_datas.destroy\n respond_to do |format|\n format.html { redirect_to web_data_url, notice: 'Web datas was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @webtoon.destroy\n respond_to do |format|\n format.html { redirect_to webtoons_url, notice: 'Webtoon was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n delete_from_server single_url\n end", "def delete\n api_client.delete(url)\n end", "def delete\n client.delete(url)\n @deleted = true\nend", "def destroy\n @webling = Webling.find(params[:id])\n @webling.destroy\n\n respond_to do |format|\n format.html { redirect_to weblings_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @webfile.destroy\n respond_to do |format|\n format.html { redirect_to webfiles_url, notice: 'Webfile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @source_web.destroy\n respond_to do |format|\n format.html { redirect_to source_webs_url, notice: 'Source web was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @webtier.destroy\n respond_to do |format|\n format.html { redirect_to webtiers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @webextra = Webextra.find(params[:id])\n @webextra.destroy\n\n respond_to do |format|\n format.html { redirect_to(webextras_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @web_info = WebInfo.find(params[:id])\n @web_info.destroy\n\n respond_to do |format|\n format.html { redirect_to(web_infos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @progress_web.destroy\n respond_to do |format|\n format.html { redirect_to progress_webs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(url, headers = {})\n http :delete, \"#{url}.json\", headers\n end", "def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end", "def destroy\n @website = Website.find(params[:id])\n @website.destroy\n\n head :no_content\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete(url)\n do_request(\"delete\", url)\n end", "def delete\n response = WebPay.client.delete(path)\n response['deleted']\n end", "def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end", "def destroy\n @website = Website.find(params[:id])\n @website.destroy\n\n respond_to do |format|\n format.html { redirect_to(websites_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @website_detail.destroy\n respond_to do |format|\n format.html { redirect_to website_details_url, notice: 'Website detail was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @webpage = Webpage.find(params[:id])\n @webpage.destroy\n\n respond_to do |format|\n format.html { redirect_to(webpages_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @web_image = WebImage.find(params[:id])\n @web_image.destroy\n\n respond_to do |format|\n format.html { redirect_to web_images_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @web_table.destroy\n respond_to do |format|\n format.html { redirect_to web_tables_url, notice: 'Table was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @webuser.destroy\n respond_to do |format|\n format.html { redirect_to webusers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @website = Website.find(params[:id])\n @website.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_websites_url }\n format.xml { head :ok }\n end\n end", "def destroy\n client=Client.find_by_id(params[:id])\n if client != nil\n if client.destroy\n head 204\n end\n else\n head 404\n end\n end", "def delete path\n make_request(path, \"delete\", {})\n end", "def delete\n request(:delete)\n end", "def destroy\n @web_service_log = WebServiceLog.find(params[:id])\n @web_service_log.destroy\n\n respond_to do |format|\n format.html { redirect_to web_service_logs_url }\n format.json { head :ok }\n end\n end", "def destroy\n @webapp.destroy\n respond_to do |format|\n format.html { redirect_to webapps_url, notice: 'Webapp was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @one = One.find(params[:id])\n @one.destroy\n\n respond_to do |format|\n format.html { redirect_to ones_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(url)\n @deleted = true\n end", "def destroy\n @go_slim = GoSlim.find(params[:id])\n @go_slim.destroy\n\n respond_to do |format|\n format.html { redirect_to go_slims_url }\n format.json { head :no_content }\n end\n end", "def delete_space_webapi(slug, headers=default_headers)\n @logger.info(\"Deleting the \\\"#{slug}\\\" Web API on the Space.\")\n delete(\"#{@api_url}/webApis/#{slug}\", headers)\n end", "def destroy\n RestClient.delete \"#{REST_API_URI}/contents/#{id}.xml\" \n self\n end", "def delete endpoint\n do_request :delete, endpoint\n end", "def delete(url, headers={})\n RestClient.delete url, headers\n end", "def destroy\n @thirtyone.destroy\n respond_to do |format|\n format.html { redirect_to thirtyones_url }\n format.json { head :no_content }\n end\n end", "def delete(url)\n call(url: url, action: :delete)\n end", "def destroy\n @v1_chore = Chore.where(id: params[:id])\n if @v1_chore.destroy\n head(:ok)\n else\n head(:unprocessable_entity)\n end\n end", "def delete\n api(\"Delete\")\n end", "def destroy\n @favorite_web_thing.destroy\n respond_to do |format|\n format.html { redirect_to favorite_web_things_url }\n format.json { head :no_content }\n end\n end", "def do_delete(uri = \"\")\n @connection.delete do |req|\n req.url uri\n req.headers['Content-Type'] = 'application/json'\n end\n end", "def delete_demo(id)\n delete_record \"/demos/#{id}\"\n end", "def destroy\n @microsite.destroy\n respond_to do |format|\n format.html { redirect_to microsites_url }\n format.json { head :no_content }\n end\n end", "def delete\n start { |connection| connection.request http :Delete }\n end", "def delete(path)\n RestClient.delete request_base+path\n end", "def delete(_url)\n # do nothing since we can't find the key by url\n end", "def destroy\n @database = Database.find(params[:id])\n path = @database.path\n delete = %x[rm -R #{path}]\n @database.destroy\n\n respond_to do |format|\n format.html { redirect_to databases_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @webscrape.destroy\n respond_to do |format|\n format.html { redirect_to webscrapes_url, notice: 'Webscrape was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(name)\n raise('wrong type: String required') unless name.is_a?(String)\n raise('wrong value: name must be valid') unless !name.nil? && !name.empty?\n\n @client.post({\n 'action' => 'del',\n 'object' => 'htpl',\n 'values' => name,\n }.to_json)\n end", "def destroy\n @url = Url.find(params[:id])\n @url.destroy\n\n respond_to do |format|\n format.html { redirect_to urls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n official = Official.find(params[:id])\n official.destroy\n head 204\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def destroy\n @website = Website.find(params[:id])\n @website.destroy\n @websites = Website.all\n .order(created_at: :desc)\n respond_to do |format|\n format.js\n end\n end", "def delete\n RestClient.delete(url, @header) do |rso, req, res|\n setup(rso, req, res)\n end\n end", "def destroy\n @strategyweb = Strategyweb.find(params[:id])\n @strategyweb.destroy\n\n respond_to do |format|\n format.html { redirect_to strategywebs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @three.destroy\n respond_to do |format|\n format.html { redirect_to threes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @htc.destroy\n respond_to do |format|\n format.html { redirect_to htcs_url }\n format.json { head :no_content }\n end\n end", "def delete_json(url)\n JSON.parse(delete(url, :json, :json))\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n @storage = @client.storages.find(params[:id])\n @storage.destroy\n\n respond_to do |format|\n format.html { redirect_to client_url(@client) }\n format.json { head :no_content }\n end\n end", "def destroy\n @weather = Weather.find(params[:id])\n @weather.destroy\n\n respond_to do |format|\n format.html { redirect_to weathers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @weather = Weather.find(params[:id])\n @weather.destroy\n\n respond_to do |format|\n format.html { redirect_to weathers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @weather = Weather.find(params[:id])\n @weather.destroy\n\n respond_to do |format|\n format.html { redirect_to weathers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n\t\t@website = Website.find(params[:id])\n\t\t@website.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to websites_url }\n\t\t\tformat.xml\t{ head :ok }\n\t\tend\n\tend", "def destroy\n @heroku = Heroku.find(params[:id])\n @heroku.destroy\n\n respond_to do |format|\n format.html { redirect_to herokus_url }\n format.json { head :ok }\n end\n end", "def delete\n execute_request('DELETE') do |uri, headers|\n HTTP.http_client.delete(uri, header: headers)\n end\n end", "def destroy\n @agent_website.destroy\n respond_to do |format|\n format.html { redirect_to agent_websites_url, notice: 'Agent website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @unique_whiteline.destroy\n respond_to do |format|\n format.html { redirect_to unique_whitelines_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @wash = Wash.find(params[:id])\n @wash.destroy\n\n respond_to do |format|\n format.html { redirect_to washes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_todo.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @thirtythree.destroy\n respond_to do |format|\n format.html { redirect_to thirtythrees_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @webservicetolisten = Webservicetolisten.find(params[:id])\n @webservicetolisten.destroy\n\n respond_to do |format|\n format.html { redirect_to webservicetolistens_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exura = Exura.find(params[:id])\n @exura.destroy\n\n respond_to do |format|\n format.html { redirect_to exuras_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mini_url.destroy\n respond_to do |format|\n format.html { redirect_to mini_urls_url, notice: 'Mini url was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to(contact_info_admin_websites_url) }\n format.xml { head :ok }\n end\n add_log(user: current_user, action: \"Deleted website: #{@website.url}\")\n end", "def destroy\n @url = ShortenedUrl.find(params[:id])\n @url.destroy\n\n respond_to do |format|\n format.html { redirect_to shortened_url_index_url }\n format.json { head :no_content }\n end\n end", "def deleteEntityWebsite( entity_id, gen_id)\n params = Hash.new\n params['entity_id'] = entity_id\n params['gen_id'] = gen_id\n return doCurl(\"delete\",\"/entity/website\",params)\n end", "def destroy\n @thirtyeight.destroy\n respond_to do |format|\n format.html { redirect_to thirtyeights_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @web_lock = WebLock.find(params[:id])\n @web_lock.destroy\n\n respond_to do |format|\n format.html { redirect_to(web_locks_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @healthpro.destroy\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @todo3.destroy\n respond_to do |format|\n format.html { redirect_to todo3s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @surah.destroy\n respond_to do |format|\n format.html { redirect_to surahs_url }\n format.json { head :no_content }\n end\n end", "def delete(path)\n request(:delete, path)\n end", "def destroy\n @visit = Visit.find(params[:id])\n @visit.destroy\n\n respond_to do |format|\n format.json { head :no_content }\n end\n end" ]
[ "0.76778334", "0.713998", "0.7040803", "0.7021795", "0.6971132", "0.69428355", "0.69316286", "0.69179", "0.68594915", "0.68535453", "0.68518025", "0.6830644", "0.681978", "0.6812523", "0.68051267", "0.6794138", "0.6793108", "0.6793108", "0.6793108", "0.6793108", "0.67692804", "0.6763383", "0.6755426", "0.67425674", "0.67425674", "0.67425674", "0.67425674", "0.67399985", "0.6729893", "0.67164904", "0.6711596", "0.669768", "0.66967905", "0.6657977", "0.663761", "0.6623641", "0.66101074", "0.65990365", "0.65919435", "0.6583131", "0.6582307", "0.6578405", "0.6572187", "0.6565431", "0.65573907", "0.6557277", "0.653841", "0.652564", "0.65237755", "0.65144885", "0.65081805", "0.65001255", "0.64970595", "0.64965546", "0.6494661", "0.6492503", "0.64920896", "0.6485867", "0.64731467", "0.64720863", "0.64701855", "0.6465927", "0.6465119", "0.64625645", "0.6459656", "0.6454928", "0.6454928", "0.64542305", "0.64482206", "0.6446961", "0.64466846", "0.6444839", "0.6439571", "0.64308375", "0.64287776", "0.6422452", "0.64200026", "0.64200026", "0.64200026", "0.64077127", "0.6406627", "0.6405671", "0.6404206", "0.6397373", "0.6395422", "0.63948095", "0.6388829", "0.63758355", "0.6363029", "0.6362643", "0.6359745", "0.63585466", "0.6356285", "0.6353028", "0.63519657", "0.6346965", "0.6339526", "0.6335383", "0.6334915", "0.63336474" ]
0.7401935
1
Use callbacks to share common setup or constraints between actions.
def set_web @web = Web.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def web_params params.require(:web).permit(:url, :url_ver_sts, :sts_code, :url_ver_date, :tmp_sts, :temp_name, :tmp_date, :slink_sts, :llink_sts, :stext_sts, :ltext_sts, :pge_date, :as_sts, :as_date, :cs_sts, :cs_date, :created_at, :updated_at) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def valid_params_request?; end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def active_code_params\n params[:active_code].permit\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def filtering_params\n params.permit(:email)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def url_whitelist; end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.6980957", "0.6783065", "0.6747844", "0.6741468", "0.67356336", "0.6592548", "0.65036845", "0.64978707", "0.64825076", "0.64795035", "0.64560914", "0.64397955", "0.6379666", "0.6376688", "0.6366702", "0.6319728", "0.6300833", "0.6300629", "0.6294277", "0.6293905", "0.6291174", "0.62905735", "0.6283171", "0.6242344", "0.62403613", "0.6218049", "0.62143815", "0.62104696", "0.61949855", "0.6178671", "0.6176147", "0.6173327", "0.6163395", "0.6153005", "0.6151833", "0.6147288", "0.61224324", "0.6118827", "0.61075264", "0.61054534", "0.6092497", "0.6080082", "0.60710967", "0.60627776", "0.60219413", "0.60175914", "0.60153484", "0.60107356", "0.60081726", "0.60081726", "0.60013986", "0.6000165", "0.59978646", "0.59936947", "0.59925723", "0.5992084", "0.59796256", "0.5967569", "0.5960056", "0.59589803", "0.5958441", "0.5958401", "0.5952607", "0.5952406", "0.5944409", "0.59391016", "0.593842", "0.593842", "0.5933845", "0.59312123", "0.5926475", "0.59248453", "0.59179676", "0.59109294", "0.59101623", "0.5908172", "0.59058356", "0.5899052", "0.5897749", "0.5896101", "0.58942914", "0.58939576", "0.5892063", "0.5887407", "0.588292", "0.58797663", "0.587367", "0.58681566", "0.5868038", "0.5866578", "0.58665025", "0.58655846", "0.58640826", "0.5863465", "0.5862226", "0.586065", "0.58581287", "0.5854443", "0.5854172", "0.58507544", "0.5849934" ]
0.0
-1
Background A Palindrome is a word or phrase which reads the same backward or forward, such as madam or kayak. Implement a Ruby method palindrome? that checks if a given word is a palindrome This method should take one argument (word), a String, and return a Boolean (true of false), telling us if the given word is a palindrome or not You can assume the one argument is a single word It should not be affected by capital letters: palindrome?("racecar") should return true palindrome?("wagon") should return false Resposta:
def palindrome?(word) return word.downcase == word.downcase.reverse end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def palindrome_word?(word)\n # determines whether a single word is a palindrome\n # ignores case\n # returns true or false\n if word.downcase == word.downcase.reverse\n true\n else false\n end\n\nend", "def palindrome_word?(word)\n normalized = word.downcase\n normalized.reverse == normalized\nend", "def is_palindrome?(word)\n if word == word.reverse\n return true\n else\n return false\n end\nend", "def palindrome_word?(word)\n word.downcase === word.downcase.reverse ? true : false\n end", "def palindrome_word? word\n output = word.downcase\n output.reverse == output\nend", "def is_palindrome?(word)\nend", "def palindrome?\n formatted_word = @word.gsub(/[^a-z]/, \"\")\n formatted_word == formatted_word.reverse\n end", "def palindrome?(word)\n word.reverse == word\nend", "def is_palindrome?(word)\n\n\n #\n # raise ArgumentError if !word.is_a?(String)\n # downcased_word = word.downcase.gsub(/\\W/,\"\")\n # return false if downcased_word.length < 2\n # downcased_word == downcased_word.reverse\n\n if word.class == String\n no_white_spaces = word.strip\n if no_white_spaces.to_i == 0 && no_white_spaces.length > 1 && no_white_spaces.length < 20\n no_white_spaces === no_white_spaces.reverse\n else\n return false\n end\n else\n raise ArgumentError\n end\nend", "def palindrome_word?(word)\n word.downcase!\n puts word.downcase!\n reversedword=word.reverse\n if reversedword==word\n return true\n else\n return false\n end\nend", "def palindrome?(word)\n word == word.reverse\nend", "def palindrome?(word)\n lol = (word.gsub(/\\W+/i, \"\")).gsub(/\\d+/i, \"\")\n if lol.downcase == lol.downcase.reverse\n return true;\n else\n return false;\n end\nend", "def palindrome_word?(word)\n return true if word.reverse.upcase == word.upcase\n false\nend", "def palindrome?( string )\n word = string.downcase.gsub(/[^a-z]/, '')\n if word == word.reverse\n return true\n else\n return false\n end\nend", "def isPalindrome(word)\n\nend", "def is_palindrome(word)\n word == word.reverse ? true : false\nend", "def palindrome(word)\n if word.downcase == word.downcase.reverse\n true\n else\n false\n end\nend", "def palindrome(word)\n\treturn word == word.reverse #true\nend", "def palindrome_verify(word)\n if word.reverse == word #Check if string same when reversed \n return \"#{ word } es palindromo.\"\n else # If string is not the same when reversed\n return \"#{ word } no es un palindromo\"\n end\n end", "def palindrome2? word\n word.downcase.reverse == word.downcase \nend", "def palindrome_word? str\n new_str = str.downcase\n if new_str == new_str.reverse\n true\n else\n false\n end\nend", "def is_palindrome?(word)\n if word.class == String\n word = word.downcase\n result = word.reverse == word ? true : false\n else\n puts \"please pass a string as the argument\"\n end\n puts result\nend", "def palindrome?(str)\n # YOUR CODE HERE\n words = str.downcase.gsub(/\\W/, \"\")\n return words == words.reverse\nend", "def palindrome?(word)\n if word == word.reverse\n puts \"The word #{word} is palindrome\"\n elsif\n puts \"The word #{word} is not palindrome\"\n end\n end", "def is_palindrome(word)\n\t# too easy\n # return word == word.reverse\n \tidxReverse = word.length-1\n \tidxForward = 0\n \twhile(idxForward<idxReverse)\n if(word[idxForward] != word[idxReverse])\n return false\n end\n idxReverse -=1\n idxForward +=1\n end\n return true\n \t\nend", "def palindrome_word? word8\n word8.downcase == word8.downcase.reverse\nend", "def is_palindrome(word)\nforwards = \"\"\nbackwards = \"\"\n \n i = 0\n while i < word.length\n char = word[i]\n forwards = forwards + char\n backwards = char + backwards\n\n i += 1\n end\n \n if forwards == backwards\n return \"true\"\n else\n return \"false\"\n end\nend", "def is_palindrome = 'racecar'", "def palindrome_word? word\n if word.length === 1\n return true\n end\n lower = word.downcase\n num = (lower.length/2.0).floor\n num.times do |x|\n if lower[x] == lower[-(x+1)]\n if x == num - 1\n return true\n end\n next\n else\n return false\n end\n end\nend", "def is_palindrome(word)\n palindrome = \"\"\n i = 0\n while i < word.length\n palindrome = word[i] + palindrome #concats backwards into palindrome\n i += 1\n end\n return palindrome == word #compares the newly stored backward word, to the word inputted\nend", "def real_palindrome?(string)\n remove_nonalphanumeric(string) # => nil, nil, \"MadamImAdam\", nil, nil, nil\n palindrome?(string.downcase) # => true, true, true, true, true, false\nend", "def word_check str\n # set str to be lowercase str.downcase\n simple_str = str.downcase.delete(' ')\n\n # check if the str .reverse is the same\n if simple_str == simple_str.reverse\n \"#{str} is a palidrome\"\n else\n \"#{str} is not a palidrome\"\n end\nend", "def palindrome string #func param: string, name: palindrome\n string = string.downcase.scan(/\\w/) #make sure the value is lower case\n string == string.reverse #see if it equals its reverse, and return as boolean statement \nend", "def palindrome_word? (foo)\nfoo.downcase == foo.downcase.reverse\nend", "def is_palindrome(word)\n forward = 0\n backword = word.length - 1\n while forward <= backword\n if word[forward] != word[backword]\n return false\n end\n forward += 1\n backword -= 1\n end\n return true\nend", "def is_palindrome(aString)\n return false if aString == nil\n #positive side = a = 0\n #negative side = y = -1\n temp_word = aString.gsub(/(\\W|\\d)/, \"\").downcase\n\n i = 0\n a = -1\n word = temp_word.chars\n while i < (word.length / 2)\n # check chars are the same\n # if same, move to next set of chars\n # if different, return false \n # when processed all chars and still haven't found a difference, return true\n if word[i] == word[a]\n a -= 1\n i += 1\n else\n return false\n end\n end\n return true\nend", "def real_palindrome?(werd)\n werd.delete(\" \").gsub(/[^A-Za-z0-9 ]/, '').downcase == werd.delete(\" \").gsub(/[^A-Za-z0-9 ]/, '').reverse.downcase\nend", "def palindrome?(word)\n array_of_letters = word.downcase.split(\"\")\n count_front = 0\n count_back = word.length - 1\n # Match the first letter with the last, if they are the same then step through the word\n while count_front < count_back\n if array_of_letters[count_front] == array_of_letters[count_back]\n count_front += 1\n count_back -= 1\n else\n return false\n end\n end\n return true\nend", "def palindrome_r(word)\n if word.length == 1 or word.length == 0\n true\n else\n if word[0] == word[-1]\n palindrome_r(word[1..-2])\n else\n false\n end\n end\nend", "def palindrome?\n string = self.downcase.gsub(/[\\W\\d]+/,\"\")\n string.reverse.eql?(string)\n end", "def palindrome?(string)\n\nend", "def palindrome?(string)\n\nend", "def real_palindrome?(string)\n string.downcase!\n if string == string.reverse\n p true\n else\n p false\n end\nend", "def real_palindrome?(string)\n palindrome?(string.downcase.gsub(/\\W/, ''))\nend", "def is_palindrome?(str)\nend", "def valid_palindrome(s)\n \nend", "def palindrome?(sentence)\n \n a = sentence.downcase.gsub(/ /, \"\") \n if a == a.reverse\n return true\n else \n return false\n end\n \nend", "def real_palindrome?(string)\n string = string.gsub(/\\W/, '').downcase\n string == string.reverse\nend", "def palindrome_check(my_phrase)\n return false if my_phrase.class != String\n\n my_phrase = my_phrase.delete(\" \")\n my_phrase_dup = my_phrase.dup\n return my_phrase == string_reverse(my_phrase_dup)\nend", "def palindrome(words)\n words == words.reverse\nend", "def palindrome?(string)\n s = string.downcase.gsub(/\\W/, \"\")\n return (s == s.reverse)\nend", "def is_palindrome(word)\n reversed = \"\"\n\n i = 0\n while i < word.length\n char = word[i]\n reversed = char + reversed\n\n i += 1\n end\n\n if word == reversed\n return true\n else\t\n\treturn false\n end\nend", "def palindrome?(string)\n\tstring.downcase!\n\tstring.gsub!(/\\W+/, '')\n\tputs string\n\tif string === string.reverse\n\t\tputs \"true\"\n\telse\n\t\tputs \"false\"\n\tend\nend", "def palindrome_word? word\n chicken = word.downcase\n chicken == chicken.reverse\nend", "def real_palindrome?(string)\n string = string.downcase.delete('^a-z0-9')\n palindrome?(string)\nend", "def real_palindrome?(string)\n string = string.downcase.delete('^a-z0-9')\n palindrome?(string)\nend", "def real_palindrome?(string)\n string = string.downcase.delete('^a-z0-9')\n palindrome?(string)\nend", "def real_palindrome?(string)\n string = string.downcase.delete('^a-z0-9')\n palindrome?(string)\nend", "def real_palindrome?(string)\n string = string.downcase.delete('^a-z0-9')\n palindrome?(string)\nend", "def real_palindrome?(string)\n string = string.downcase.delete('^a-z0-9')\n palindrome?(string)\nend", "def palindrome?(string)\n string.delete!(' ')\n string.downcase!\n reversed_string=string.reverse\n reversed_string.eql?(string)\nend", "def palindrome?(str)\n flat_str = str.gsub /[\\W+]/, ''\n reverse_str = flat_str.reverse\n if reverse_str.downcase! == flat_str.downcase!\n return true\n end\n return false\nend", "def palindrome?(sentence)\n dw_sentence = sentence.downcase.delete(' ')\n return dw_sentence == dw_sentence.reverse\nend", "def palindrome?(string)\n string = string.downcase\n string = string.gsub(' ', '')\n if string == string.reverse\n return true\n else\n return false\n end\nend", "def palidrome?(word)\n j = word.length - 1\n half_length = word.length / 2\n\n half_length.times do |i|\n if word[i] != word[j]\n return false\n end\n j -= 1\n end\n\n return true\nend", "def is_palindrome?(string)\n string.reverse == string\nend", "def is_palindrome(word)\n\n i = 0\n reversed = \"\"\n \n while i < word.length\n char = word[i]\n reversed = char + reversed\n i += 1\n end\n \n if word == reversed\n return true\n else \n return false\n end\n \nend", "def palindrome?(str)\n # YOUR CODE HERE\n str = str.gsub(/\\W/, '').downcase\n if str.length == 1\n \treturn true \n elsif str[0] == str[-1..-1]\n \tif str.length == 2\n \t\treturn true\n \telse \t\n\t \ta = str[1...-1]\n\t \treturn palindrome?(a)\n\t end\n else\n \treturn false\n end\nend", "def palindrome?(str)\n # YOUR CODE HERE\n str.downcase.gsub(/\\W/, '').reverse == str.downcase.gsub(/\\W/, '')\nend", "def palindrome (word)\n if word.length == 1 || word.length == 0 #baseline, where it ends\n true\n else\n if word[0] == word[-1]\n palindrome(word[1..-2])\n else\n false\n end\n end\nend", "def palindromo(text)\n if text.downcase == text.downcase.reverse\n \"palindrome\"\n else\n \"no palindrome\"\n end\nend", "def palindrome?(string)\n y = string.downcase.gsub(/\\W/, '')\n y == y.reverse\nend", "def is_palindrome(word)\n palindrome = false\n reversed_str = \"\"\n\n i = 0\n \n while i < word.length\n reversed_str = word[i] + reversed_str\n i += 1\n end\n \n if reversed_str == word\n palindrome = true\n end\n \n return palindrome\nend", "def is_palindrome? string\n string == string.reverse\nend", "def is_palindrome? string\n string == string.reverse\nend", "def palindrome(string)\n word_array = string.split(\"\")\n\n word_array.each_with_index do |letter,index|\n if letter[index] == letter[-index]\n return true\n end\n end\n end", "def palindrome?(sentence)\n word = sentence.downcase.gsub(' ','')\n word == word.reverse\nend", "def is_palindrome(string)\n split_string_array = string.downcase.split(\"\")\n words_array = split_string_array.select{|letter| letter[/[a-z]/]}\n\n reverse_words_array = []\n x = 0\n length = words_array.length\n until words_array[x] == nil\n reverse_words_array << words_array[length -(x+1)]\n x += 1\n end\n\n return reverse_words_array == words_array ? true : false\n\nend", "def is_palindrome(str)\n # check for and handle wonky inputs\n if !str.is_a?(String)\n puts \"Whoops: Input str must be a string.\"\n return\n end\n\n # nix case sensitivity by converting to lowercase\n # represent str as an array of letters\n str_array = str.downcase.split(//)\n\n # compare forwards and backwards\n if str_array == str_array.reverse\n return true\n end\n\n # if all else fails\n return false\n\nend", "def palindrome(str)\n stripped = str.gsub(/[^\\w]/, \"\").downcase\n if stripped === str.reverse\n return true\n else\n return false\n end\nend", "def is_palindrome(word)\n i = 0\n reversed = \"\"\n while i < word.length\n reversed = word[i] + reversed\n i += 1\n end\n return reversed == word\n end", "def palindrome?(str)\n downcased_str = str.downcase\n nospaced_str = downcased_str.gsub(/\\W+/,\"\")\n reversed_str = nospaced_str.reverse\n return nospaced_str == reversed_str\nend", "def palindrome?(string)\r\n string.reverse == string\r\nend", "def palindrome?(string)\r\n string.reverse == string\r\nend", "def palindrome?(string)\r\n string.reverse == string\r\nend", "def palindrome?(string)\n\tputs string\n\tstring.downcase!\n\tstring = string.gsub(/\\W+/, '')\n\tif string === string.reverse\n\t\treturn true\n\telse\n\t\treturn false\n\tend\nend", "def palindrome?(string)\n string.reverse == string\nend", "def palindrome?(string)\n string.reverse == string\nend", "def palindrome?(string)\n string.reverse == string\nend", "def palindrome?(str)\n treated_str = str.gsub(/[^\\w]/,'')\n return treated_str.downcase == treated_str.downcase.reverse\nend", "def palindrome (string)\n\n if string.reverse == string\n return true\n else\n return false\n end\n \nend", "def word_palindrome(word)\n\n index = 0\n end_point = -1\n\n while index < word.length/2\n return false if word[index] != word[end_point-index]\n index+=1\n end\n return true\n\nend", "def palindrome?(string)\n string == string.reverse\nend", "def palindrome?(string)\n if string == string.reverse\n return true\n else \n return false\n end\nend", "def real_palindrome?(str)\n str = str.downcase.delete('^a-z0-9')\n palindrome?(str)\nend", "def real_palindrome?(string)\n new_string = string.downcase.delete('^0-9a-z')\n palindrome?(new_string)\nend", "def palindrome_r(string)\n return true if string.length == 1 || string.length == 0\n string = string.strip.scan(/\\w+/).join.downcase\n return false if string[0] != string[-1]\n palindrome_r(string[1..-2])\nend", "def palindrome_checker2 string\n # remove white space from argument using gsub (what being replaced, replacing with what?)\n lowercase_stripped_string = string.downcase.gsub(\" \", \"\")\n # Create a variable to hold stripped string argument reversed \n lowercase_stripped_string_reversed = lowercase_stripped_string.reverse\n # Compare string argument lowercased to string reversed and lowercased variable\n if lowercase_stripped_string == lowercase_stripped_string_reversed\n \"#{string} is a palindrome\"\n else\n \"#{string} is not a palindrome\" \n end\nend", "def palindrome?(string)\r\n reverse_string = string.reverse\r\n if reverse_string == string\r\n true\r\n else\r\n false\r\n end\r\nend", "def is_palindrome?(string)\n string == string.reverse\nend" ]
[ "0.8780466", "0.87546605", "0.8754099", "0.87351", "0.8728074", "0.87151134", "0.8710223", "0.87019724", "0.8690443", "0.8677623", "0.86329633", "0.86141616", "0.8607497", "0.8575631", "0.8565919", "0.856155", "0.85587114", "0.85578465", "0.8539662", "0.8517202", "0.849367", "0.84779125", "0.8468186", "0.84608483", "0.84543526", "0.8453795", "0.8447357", "0.83937794", "0.83891654", "0.83800244", "0.8367932", "0.8366085", "0.8364417", "0.8343132", "0.83261645", "0.8317321", "0.83145", "0.83033085", "0.8258314", "0.8242362", "0.82422143", "0.82422143", "0.82399666", "0.8223772", "0.821957", "0.8216305", "0.8186693", "0.81836", "0.8175173", "0.81646824", "0.81629306", "0.8162128", "0.8152288", "0.8138907", "0.8135112", "0.8135112", "0.8135112", "0.8135112", "0.8135112", "0.8135112", "0.8128374", "0.81273204", "0.8126106", "0.8120855", "0.8117324", "0.811577", "0.81135964", "0.8099757", "0.8098495", "0.8095632", "0.80880135", "0.808644", "0.8085546", "0.8084431", "0.8084431", "0.8083339", "0.8082682", "0.807817", "0.806842", "0.8068104", "0.8065892", "0.8061962", "0.8060809", "0.8060809", "0.8060809", "0.8058607", "0.8052774", "0.8052774", "0.8052774", "0.804791", "0.8047023", "0.8045209", "0.80434155", "0.80381805", "0.80372894", "0.8034833", "0.8033723", "0.8030222", "0.80299175", "0.8029069" ]
0.85925263
13
GET /records/new GET /records/new.json
def new end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @record = Record.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record }\n end\n end", "def new\n @record = Record.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record }\n end\n end", "def new\n @record = Record.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @record }\n end\n end", "def new\n @record_status = RecordStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record_status }\n end\n end", "def new\n @dummy_record = DummyRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @dummy_record }\n end\n end", "def new\n @status_record = StatusRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @status_record }\n end\n end", "def new\n @recinto = Recinto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recinto }\n end\n end", "def new\n @records_location = RecordsLocation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @records_location }\n end\n end", "def new\n @file_record = FileRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @file_record }\n end\n end", "def new\n @patient = Patient.find(params[:patient_id])\n @record = @patient.records.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @secret_record }\n end\n end", "def new\n @registro_record = RegistroRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @registro_record }\n end\n end", "def new\n @breadcrumb = 'create'\n @time_record = TimeRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @time_record }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @time_record = TimeRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @time_record }\n end\n end", "def new\n @weather_record = WeatherRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weather_record }\n end\n end", "def new\n @patient_history = PatientHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patient_history }\n end\n end", "def new\n @pageType = \"new\"\n @patient = Patient.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patient }\n end\n end", "def new\n @table = Table.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @table }\n end\n end", "def new\n @table = Table.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @table }\n end\n end", "def new\n @liverecord = Liverecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @liverecord }\n end\n end", "def new\n @healthrecord = Healthrecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @healthrecord }\n end\n end", "def new\n @resource = Resource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @resource = Resource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @resource = Resource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @service_record = ServiceRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @service_record }\n end\n end", "def new\n @trail = Trail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trail }\n end\n end", "def new\n @trail = Trail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trail }\n end\n end", "def new\n @document_history = DocumentHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @document_history }\n end\n end", "def new\n @lookup = Lookup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lookup }\n end\n end", "def new\n @database = Database.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @database }\n end\n end", "def new\n @resource = Resource.new\n respond_to do |format|\n format.html {render action: :new} # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @model = Model.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @model }\n end\n end", "def new\n @model = Model.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @model }\n end\n end", "def new\n @model = Model.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @model }\n end\n end", "def new\n @model = Model.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @model }\n end\n end", "def new\n @new_status = NewStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_status }\n end\n end", "def new\n doc_no = (RepairRecord.maximum(:doc_no).to_i || 0) + 1\n @repair_record = current_user.reported_repair_records.new(doc_no: doc_no)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @repair_record }\n end\n end", "def new\n @driver_record = DriverRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @driver_record }\n end\n end", "def new\n @grant_record = GrantRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @grant_record }\n end\n end", "def new\n @query_history = QueryHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @query_history }\n end\n end", "def new\n @t = T.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @t }\n end\n end", "def new\n @database = Database.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json=> @database }\n end\n end", "def new\n @importtodb = Importtodb.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @importtodb }\n end\n end", "def new\n @request = Request.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @request }\n end\n end", "def new\n @request = Request.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @request }\n end\n end", "def new\n @request = Request.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @request }\n end\n end", "def new\n @request = Request.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @request }\n end\n end", "def new\n @request = Request.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @request }\n end\n end", "def new\n @medrecord = Medrecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @medrecord }\n end\n end", "def new\n @group_record = GroupRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @group_record }\n end\n end", "def new\n @dummy_table = DummyTable.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dummy_table }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patient }\n end\n end", "def new\n @person = Person.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n\t\t@person = Person.new\n\t\t# render json: @person #skips the view, and just renders out the json\n\tend", "def new\n @note = Note.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @notes }\n end\n end", "def new\n \n @document = Document.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @document }\n end\n \n end", "def new\n @person = Person.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n @person = Person.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n @person = Person.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n @person = Person.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n @person = Person.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n @person = Person.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n @person = Person.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @person }\n end\n end", "def new\n @entity = Entity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entity }\n end\n end", "def new\n @health_record = HealthRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @health_record }\n end\n end", "def new\n fetch_data\n @payment = Payment.new(:payment_date => Date.today)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @payment }\n end\n end", "def new\n @journal = Journal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json :@journal }\n end\n end", "def new\n @patent = Patent.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patent }\n end\n end", "def new\n @entry = Entry.new\n\n render json: @entry\n end", "def new\n @entry = Entry.new(project_id: @project.id, recorded_for: Date.today)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @newspage = Newspage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newspage }\n end\n end", "def new\n @newapp = Newapp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newapp }\n end\n end", "def new\n @death_record_book = DeathRecordBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @death_record_book }\n end\n end", "def create\n @new_ = New.new(new__params)\n\n respond_to do |format|\n if @new_.save\n format.html { redirect_to @new_, notice: \"New was successfully created.\" }\n format.json { render :show, status: :created, location: @new_ }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @new_.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @get = Get.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @get }\n end\n end", "def new\n @vote_record = VoteRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @vote_record }\n end\n end", "def new\n @collection = Collection.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @collection }\n end\n end", "def new\n @list_record = ListRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @list_record }\n end\n end", "def new\n @record = Umbra::Record.new\n respond_with(@record)\n end", "def new\n @note = Note.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @note }\n end\n end", "def new\n @note = Note.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @note }\n end\n end", "def new\n @note = Note.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @note }\n end\n end", "def new\n @note = Note.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @note }\n end\n end", "def new\n @identity_table = IdentityTable.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @identity_table }\n end\n end", "def new\n @id = Id.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @id }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @entry }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @alley }\n end\n end", "def new\n # Create new news\n @news = News.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @news }\n end\n end", "def new\n @monkey = Monkey.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @monkey }\n end\n end", "def new\n @historical = Historical.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @historical }\n end\n end", "def new\n @recent_transaction = RecentTransaction.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recent_transaction }\n end\n end", "def new\n @player_record = PlayerRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @player_record }\n end\n end", "def new\n @newuser = Newuser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newuser }\n end\n end" ]
[ "0.7878653", "0.78784484", "0.7804585", "0.7370897", "0.73114866", "0.72440517", "0.7236424", "0.71809167", "0.7126915", "0.710027", "0.7074209", "0.7068328", "0.70324624", "0.70223385", "0.6989631", "0.69868344", "0.6939417", "0.68858355", "0.6875809", "0.6875809", "0.6868202", "0.684555", "0.68235815", "0.68235815", "0.68235815", "0.6822378", "0.68172264", "0.68172264", "0.6802299", "0.67997545", "0.67878103", "0.6787601", "0.6759935", "0.6759935", "0.6759935", "0.6759935", "0.67545235", "0.6747813", "0.6745743", "0.6739803", "0.6734139", "0.67320687", "0.6729055", "0.67187935", "0.6710809", "0.6710809", "0.6710809", "0.6710809", "0.6710809", "0.67082226", "0.66875094", "0.6664123", "0.6658093", "0.6656108", "0.6652756", "0.66512084", "0.6649266", "0.66479474", "0.66479474", "0.66479474", "0.66479474", "0.66479474", "0.66479474", "0.66479474", "0.6643847", "0.6642226", "0.66211647", "0.6621135", "0.66172314", "0.66166353", "0.66095483", "0.66089135", "0.66082937", "0.66074055", "0.6597919", "0.6596883", "0.65888816", "0.65765625", "0.6562413", "0.6560509", "0.6557842", "0.6557842", "0.6557842", "0.6557842", "0.65544623", "0.65539336", "0.6553625", "0.6553625", "0.6553625", "0.6553625", "0.6553625", "0.6553625", "0.6553625", "0.6553625", "0.65503174", "0.6550171", "0.65474105", "0.65462965", "0.6537417", "0.653559", "0.65325" ]
0.0
-1
POST /records POST /records.json
def create respond_to do |format| begin model = JSON.parse( params[:model] ) rescue format.html { render action: "new" } format.json { render json: @record.errors, status: :unprocessable_entity } else #@record = Record.where( :email => model["email"] ).first model.delete('authenticity_token') if @record.nil? @record = Record.new(model) @record.save else if @record.score < model["score"] || ( @record.score == model["score"] && @record.time > model["time"] ) @record.update_attributes(model) end end format.html { redirect_to @record, notice: 'Record was successfully created.' } format.json { render json: @record, status: :created, location: @record } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @record = Record.new(record_params)\n \n if @record.save\n render json: @record\n else\n render error: {error: \"Unable to create record\"}, status: :400\n end\n end", "def create\n @record = Record.new(params[:record])\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to @record, :notice => 'Record was successfully created.' }\n format.json { render :json => @record, :status => :created, :location => @record }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @record.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @record = Record.new(params[:record])\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to @record, notice: 'Record was successfully created.' }\n format.json { render json: @record, status: :created, location: @record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create \n @record = current_user.records.new(record_params)\n \n # if the record was saved successfully\n if @record.save\n @record.update_user_json_keys!\n redirect_to records_path\n # else errors\n else\n # reset json\n @saved_json = params[:record][:json]\n render :new\n end\n end", "def create\n @record = Record.new(record_params)\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to @record, notice: 'Record was successfully created.' }\n format.json { render :show, status: :created, location: @record }\n else\n format.html { render :new }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @record = Umbra::Record.new(record_params)\n\n flash[:notice] = t(\"records.create_success\") if @record.save\n respond_with(@record)\n end", "def create\n @record = Record.new(params[:record])\n record_set = RecordSet.find_by_id(params[:record][:record_set_id])\n @record.patient_id = record_set.patient_id\n\n respond_to do |format|\n if @record.save\n format.json { render :json => [ @record.to_jq_record ].to_json }\n format.html { render :json => [ @record.to_jq_record ].to_json }\n else\n format.json { render :json => [ @record.to_jq_record.merge({ :error => \"custom_failure\" }) ].to_json }\n end\n end\n end", "def create\n @record = Record.new(record_params)\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to @record, notice: 'Record was successfully created.' }\n format.json { render action: 'show', status: :created, location: @record }\n else\n format.html { render action: 'new' }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @record = current_user.records.new(record_params)\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to @record, notice: 'Record was successfully created.' }\n format.json { render :show, status: :created, location: @record }\n else\n format.html { render :new }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @record = Record.new(record_params)\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to records_url, notice: '登録しました' }\n format.json { render :show, status: :created, location: @record }\n else\n format.html { render :new }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def push_new_record(record)\n handle_couch_response do\n RestClient.post(local_couch_database_url, record, content_type: :json)\n end\n end", "def batch_create\n @values = record_batch_params.values.reject { |p| p.values.all?(&:blank?) }\n @records = record_class.create(@values)\n\n respond_to do |format|\n if @records.all?(&:valid?)\n format.html { redirect_to url_for(action: 'index'), notice: \"#{record_class.model_name.plural.humanize} were successfully created.\" }\n format.json { render :index, status: :created }\n else\n @records = @records.fill(@records.size..BATCH_SIZE) { record_class.new }\n\n format.html { render :batch_new }\n format.json { render json: @records.map(&:errors), status: :unprocessable_entity }\n end\n end\n end", "def create\n @record = record_class.new(record_params)\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to @record, notice: \"#{record_class.model_name.singular.humanize} was successfully created.\" }\n format.json { render :show, status: :created, location: @record }\n else\n format.html { render :new }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # binding.pry\n @record = Record.create(record_params)\n\n respond_to do |format|\n if @record.save\n # format.html { redirect_to action: \"index\" }\n\n format.html { redirect_to records_url }\n format.js\n # format.html { redirect_to @record, notice: 'Record was successfully created.' }\n # redirect_to action: \"index\"\n\n # redirect_to(@record)\n\n else\n format.html { render :new }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_records\n return error_response unless is_get_records_request?\n as_json\n end", "def create\n @record = current_user.records.build(record_params)\n @record.subscribe(@service)\n respond_to do |format|\n if @record.save\n format.html do\n if current_user.update_second_step!\n #redirect_to social_url, notice: '上のテキストボックスから友達を探してフォローしましょう!!'\n redirect_to api_v1_records_url(access_token: params[:access_token]), notice: '登録しました'\n else\n redirect_to api_v1_records_url(access_token: params[:access_token]), notice: '登録しました'\n end\n end\n format.json { render 'api/v1/records/show' }\n else\n format.html { render action: 'new' }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @test_record = TestRecord.new(test_record_params)\n\n\n\n respond_to do |format|\n if @test_record.save\n format.html { redirect_to @test_record, notice: 'Test record was successfully created.' }\n format.json { render :show, status: :created, location: @test_record }\n else\n format.html { render :new }\n format.json { render json: @test_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @dummy_record = DummyRecord.new(params[:dummy_record])\n\n respond_to do |format|\n if @dummy_record.save\n format.html { redirect_to @dummy_record, :notice => 'Dummy record was successfully created.' }\n format.json { render :json => @dummy_record, :status => :created, :location => @dummy_record }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @dummy_record.errors, :status => :unprocessable_entity }\n end\n end\n end", "def index\n @record_set = RecordSet.find_by_id(params[:record_set_id].to_i)\n can? :read, @record_set\n @records = Record.find_all_by_record_set_id(@record_set.id)\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @records.collect {|r| r.to_jq_record }.to_json }\n end\n end", "def create\n @server_record = ServerRecord.new(server_record_params)\n\n respond_to do |format|\n if @server_record.save\n format.html { redirect_to @server_record, notice: 'Server record was successfully created.' }\n format.json { render :show, status: :created, location: @server_record }\n else\n format.html { render :new }\n format.json { render json: @server_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_data(body)\r\n raise ConfigError, 'no json_records' if body.empty?\r\n # Create REST request header\r\n header = get_header(body.bytesize)\r\n # Post REST request \r\n response = RestClient.post(@uri, body, header)\r\n\r\n return response\r\n end", "def records(opts = {})\n view = opts[:view] || @opts[:view]\n client.view(view, include_docs: true, stream: true).docs.lazy.map do |r|\n @record_class.build(mint_id(r['_id']), r.to_json, 'application/json')\n end\n end", "def create\n records = if file_upload?\n case file_upload_params['records']['file'].content_type\n when 'text/xml' then FileParser::XMLRecordParser.call( file_upload_params['records']['file'].path )\n when 'text/csv' then FileParser::CSVRecordParser.call( file_upload_params['records']['file'].path )\n when 'application/json' then FileParser::JSONRecordParser.call( file_upload_params['records']['file'].path )\n end\n else # non file upload\n form_submission_params['records'].is_a?(Array) ? form_submission_params['records'] : [ form_submission_params['records'] ]\n end\n\n begin\n @report = ReportCreator.new(records).results\n\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @report, status: :ok }\n end\n rescue => exception\n respond_to do |format|\n redirect_to :new, error: \"Invalid Information\", status: :unprocessable_entity\n\n format.json { render status: :unprocessable_entity }\n end\n end\n end", "def save_records\n return error_response unless is_save_records_request?\n if params[:changes]\n params[:changes].each_value do |changed|\n fields = changed.keys\n record = @record_class.find(changed[fields.delete('recid')])\n if record.present?\n fields.each do |field|\n table, column = get_table_and_column field\n obj = if table == @table_name\n record\n elsif record.respond_to?(table.to_sym)\n record.send(\"#{table}\")\n end\n obj.send(\"#{column}=\", changed[field]) if obj and obj.respond_to?(column.to_sym)\n end\n return error_response unless record.save\n end\n end\n end\n succes_response\n end", "def new\n @patient = Patient.find(params[:patient_id])\n @record = @patient.records.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record }\n end\n end", "def create\n @rec = Rec.new(rec_params)\n\n respond_to do |format|\n if @rec.save\n format.html { redirect_to @rec, notice: 'Rec was successfully created.' }\n format.json { render :show, status: :created, location: @rec }\n else\n format.html { render :new }\n format.json { render json: @rec.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_history_record = UserHistoryRecord.new(user_history_record_params)\n\n respond_to do |format|\n if @user_history_record.save\n format.html { redirect_to @user_history_record, notice: 'User history record was successfully created.' }\n format.json { \n response = Hash.new\n response['status'] = \"Successfully uploaded!\"\n response['record'] = @user_history_record\n render json: response\n }\n else\n format.html { render :new }\n format.json { render json: @user_history_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @status_record = StatusRecord.new(params[:status_record])\n\n respond_to do |format|\n if @status_record.save\n format.html { redirect_to @status_record, notice: 'Status record was successfully created.' }\n format.json { render json: @status_record, status: :created, location: @status_record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @status_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @record = Record.new(params[:record])\n respond_to do |format|\n if @record.save\n\tRecord.set_priority @record.list_id\n\tformat.json { render json: @record, status: :created, location: @record }\n else\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def records(opts = {})\n opts = opts.merge(@opts)\n client.list_records(opts).full.lazy.flat_map do |rec|\n @record_class.build(mint_id(rec.header.identifier),\n record_xml(rec))\n\n end\n end", "def create_records(client)\n puts \" --- create records\" if $VERBOSE\n record = {\n kind: 'Article',\n title: 'Sample',\n text: 'Just some random text.'\n }\n result = client.create(record)\n # Make sure the message has the correct fields and values.\n check_result_code(result)\n ref = result[:ref]\n refute_equal(nil, ref, 'create reply record reference can not be nil')\n refute_equal(0, ref, 'create reply record reference can not be 0')\n\n # create a couple more records\n client.create({\n kind: 'Article',\n title: 'Second',\n text: 'More random text.'})\n client.create({\n kind: 'Article',\n title: 'Third',\n text: 'Even more random text.'})\n ref\n end", "def new\n @record = Record.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record }\n end\n end", "def new\n @record = Record.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record }\n end\n end", "def create\n @weather_record = WeatherRecord.new(params[:weather_record])\n\n respond_to do |format|\n if @weather_record.save\n format.html { redirect_to @weather_record, notice: 'Weather record was successfully created.' }\n format.json { render json: @weather_record, status: :created, location: @weather_record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @weather_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hours_record = HoursRecord.new(hours_record_params)\n @hours_record.record_doc.attach(params[:record_doc])\n\n respond_to do |format|\n if @hours_record.save\n format.html { redirect_to @hours_record, notice: 'Hours record was successfully created.' }\n format.json { render :show, status: :created, location: @hours_record }\n else\n format.html { render :new }\n format.json { render json: @hours_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @weather_record = WeatherRecord.new(weather_record_params)\n\n respond_to do |format|\n if @weather_record.save\n format.html { redirect_to @weather_record, notice: 'Weather record was successfully created.' }\n format.json { render :show, status: :created, location: @weather_record }\n else\n format.html { render :new }\n format.json { render json: @weather_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def records(node, path, parameters={})\n result = request(path, parameters) or return []\n result = result.values.first or return []\n result = result[node] or return []\n result = [result] unless Array === result\n result.map { |row| Record.new(node, row) }\n end", "def create\n fail_on_type_mismatch(data_params[:type])\n\n record = queried_record_scope.build\n assign_record_attributes(record, permitted_params_for(:create), data_params)\n\n execute_after_initialize_callbacks(record)\n\n execute_before_create_callbacks(record)\n execute_before_save_callbacks(record)\n\n fail RecordInvalidError.new(record, engaged_field_aliases) if record.errors.any?\n\n record.save!\n\n persist_collection_relationships(record)\n\n execute_after_create_callbacks(record)\n execute_after_save_callbacks(record)\n\n render(\n json: record,\n status: :created,\n fields: query_params[:fields],\n include: query_params[:include]\n )\n end", "def create\n # Create a new record from the params and make it become\n # an external system (e.g. Primo) object if possible\n # in order to kick off callbacks\n @record = user.records.new(record_params).becomes_external_system\n flash[:notice] = t('record.flash.actions.create.notice') if @record.save!\n # Need to specify location due to external system inheritance\n respond_with(@record, location: record_url(@record))\n end", "def create(table, new_record)\n self.post(\"/#{table}/create\", body: {record: new_record})\n end", "def create\n\t\turi = URI.parse(Counter::Application.config.simplyurl)\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\t\n\t\trequest = Net::HTTP::Post.new('/offsets.json')\n\t\tputs params\n\t\tputs params.slice(*['custids','acctids','itemids'])\n\t\t\n\t\t# ok, this join stuff is bogus - it encodes properly, but the other side only sees the last element and loses the array type - it's just string\n\t\t# this way, i 'split' it at the other side to recover my array\n\t\t# it should work without the join/split crap, but it doesn't\n\t\trequest.set_form_data({:custids => ( params['custids'] || []).join(','), :acctids => ( params['acctids'] || []).join(','), :itemids => ( params['itemids'] || []).join(','), :amount => params['amount'], :type => params['type']})\n\t\t\n\t\tputs request.body\n\t\t\n\t\tresponse = http.request(request)\n\t\tputs response.body\n\n respond_to do |format|\n format.html { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n format.json { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n end\n end", "def create_record(record_type, zone_id, name, data, options = {})\n optional_tags= ''\n options.each { |option, value|\n case option\n when :ttl\n optional_tags+= \"<ttl type='integer'>#{value}</ttl>\"\n when :active\n optional_tags+= \"<active>#{value}</active>\"\n when :aux\n optional_tags+= \"<aux>#{value}</aux>\"\n end\n }\n\n request(\n :body => %Q{<?xml version=\"1.0\" encoding=\"UTF-8\"?><record><record_type>#{record_type}</record_type><zone_id type=\"integer\">#{zone_id}</zone_id><name>#{name}</name><data>#{data}</data>#{optional_tags}</record>},\n :expects => 201,\n :method => 'POST',\n :parser => Fog::Parsers::DNS::Slicehost::CreateRecord.new,\n :path => 'records.xml'\n )\n end", "def export\n send_data current_user.records.select(:json).order('updated_at desc').collect(&:json).to_json, filename: 'records.json'\n end", "def create\n @record = Airtable::Record.new({Name: params[:name], Description: params[:description]})\n @table.create(@record)\n render plain: \"success\"\n end", "def new\n @record = Record.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @record }\n end\n end", "def create\n @movie_record = MovieRecord.new(movie_record_params)\n\n respond_to do |format|\n if @movie_record.save\n format.html { redirect_to movie_records_url, notice: 'Movie record was successfully created.' }\n format.json { render :show, status: :created, location: @movie_record }\n else\n format.html { redirect_to movie_records_url }\n format.json { render json: @movie_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n count = unback_count\n if count > 0\n render json: {\n message: \"您还有#{count}次外出没有销假,不能发起新的外出申请!请您首先完成销假。\"\n }, status: :forbidden\n return\n end\n \n @record = @user.records.new(record_params)\n\n respond_to do |format|\n if @record.save\n format.html { redirect_to @record, notice: 'Record was successfully created.' }\n format.json { render :show, status: :created, location: @record }\n else\n format.html { render :new }\n format.json { render json: @record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @number_record = NumberRecord.new(number_record_params)\n\n respond_to do |format|\n if @number_record.save\n format.html { redirect_to number_records_path, notice: 'Number record was successfully created.' }\n format.json { render :show, status: :created, location: @number_record }\n else\n format.html { render :new }\n format.json { render json: @number_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @file_record = FileRecord.new(params[:file_record])\n\n respond_to do |format|\n if @file_record.save\n format.html { redirect_to @file_record, notice: 'File record was successfully created.' }\n format.json { render json: @file_record, status: :created, location: @file_record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @file_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @recordpnytt = Recordpnytt.new(recordpnytt_params)\n\n respond_to do |format|\n if @recordpnytt.save\n format.html { redirect_to @recordpnytt, notice: 'Recordpnytt was successfully created.' }\n format.json { render :show, status: :created, location: @recordpnytt }\n else\n format.html { render :new }\n format.json { render json: @recordpnytt.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @service_record = ServiceRecord.new(service_record_params)\n\n respond_to do |format|\n if @service_record.save\n format.json { render json: @service_record, serializer: ServiceRecordSerializer }\n else\n format.json { render json: @service_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def record\n puts \"****************** in record match, params: #{params}\"\n match_id = params[:match_id]\n match = nil\n begin\n puts \"match find : #{params[:match_id]}\"\n match = Match.find_by(id: match_id)\n rescue Exception => exc\n puts \"match not found: #{params['id']}, #{params['tourney_id']}, #{params['round']}\"\n end\n\n\n if match.present?\n match.player1_score = params[:player1_wins]\n match.player2_score = params[:player2_wins]\n match.ties = params[:ties]\n match.round = params[:round]\n puts \"***************** updating existing match: #{match.inspect}\"\n match.save\n else\n puts \"match not present\"\n end\n respond_to do |format|\n match_hash = match.as_json\n puts \"*********** Getting to end of record service, about to render JSON, #{match_hash}\"\n format.json { render :json => match_hash.to_json }\n # format.json { render :json => {:what => 'ever'} }\n end\n end", "def update_all records\n array = []\n records.each do |id, r|\n params = {}\n r.each do |k, v|\n params[k] = {value: v}\n end\n array.push({\n id: id,\n record: params\n })\n end\n puts \"update #{array.count} records...\"\n while array.present?\n a100 = array.shift(100)\n @api.records.update(@app_id, a100)\n end\n {}\n end", "def record_params\n params.require(:record).permit(:person_id, :event_id, :date)\n\n end", "def record_params\n params.require(:record).permit(:type_of, :rdata, :zone_id, :ttl)\n end", "def create_record(zone_id, type, name, content, options={})\n body = %Q{<?xml version=\"1.0\" encoding=\"UTF-8\"?><record><type>#{type}</type><name>#{name}</name><content>#{content}</content>}\n options.each do |k,v|\n body += %Q{<#{k}>#{v}</#{k}>}\n end\n body += %Q{</record>}\n request(\n :body => body,\n :expects => 202,\n :method => 'POST',\n :parser => Fog::Parsers::DNS::Bluebox::CreateRecord.new,\n :path => \"/api/domains/#{zone_id}/records.xml\"\n )\n end", "def create\n puts game_record_params\n @game_record = GameRecord.new(game_record_params)\n\n respond_to do |format|\n if @game_record.save\n format.html { redirect_to @game_record, notice: 'Game record was successfully created.' }\n format.js { }\n format.json { render :show, status: :created, location: @game_record }\n else\n format.html { render :new }\n format.json { render json: @game_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @records_location = RecordsLocation.new(params[:records_location])\n\n respond_to do |format|\n if @records_location.save\n format.html { redirect_to @records_location, notice: 'Records location was successfully created.' }\n format.json { render json: @records_location, status: :created, location: @records_location }\n else\n format.html { render action: \"new\" }\n format.json { render json: @records_location.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @file_record = FileRecord.new(file_record_params)\n\n respond_to do |format|\n if @file_record.save\n format.html { redirect_to @file_record, notice: 'File record was successfully created.' }\n format.json { render :show, status: :created, location: @file_record }\n else\n format.html { render :new }\n format.json { render json: @file_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def save_record(mid, data)\n url = Configuration::PROPERTIES.get_property :url\n url_get_records = Configuration::PROPERTIES.get_property :url_save_record\n\n url_get_records = url_get_records.gsub '{csk}', URI::encode(@credential[:csk])\n url_get_records = url_get_records.gsub '{aci}', URI::encode(@credential[:aci])\n url_get_records = url_get_records.gsub '{mid}', mid.to_s\n\n params = {\n :fields => Dynamicloud::API::DynamicloudHelper.build_fields_json(data)\n }\n\n response = DynamicService::ServiceCaller.call_service url + url_get_records, params, 'post'\n\n json = JSON.parse(response)\n unless json['status'] == 200\n raise json['message']\n end\n\n data['rid'] = json['rid']\n\n data\n end", "def create\n @regional_data_record = @region.regional_data_records.new(regional_data_record_params)\n\n respond_to do |format|\n if @regional_data_record.save\n format.html { redirect_to [@region, @regional_data_record], notice: 'Regional data record was successfully created.' }\n format.json { render :show, status: :created, location: @regional_data_record }\n else\n format.html { render :new }\n format.json { render json: @regional_data_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @reading_record = ReadingRecord.new(reading_record_params)\n\n respond_to do |format|\n if @reading_record.save\n format.html { redirect_to @reading_record, notice: 'Reading record was successfully created.' }\n format.json { render :show, status: :created, location: @reading_record }\n else\n format.html { render :new }\n format.json { render json: @reading_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def record_params\n params.require(:record).permit()\n end", "def record_params\n params.require(:record).permit()\n end", "def create\n @person_expense_record = PersonExpenseRecord.new(person_expense_record_params)\n\n if @person_expense_record.save\n render json: @person_expense_record, status: :created, location: @person_expense_record\n else\n render json: @person_expense_record.errors, status: :unprocessable_entity\n end\n end", "def create\n record = AssetType.new(params[:record])\n respond_to do |format|\n if record.save \n format.html \n format.json { render json: {} }\n else\n format.html { render action: \"new\" }\n format.json { render json: {} }\n end\n end\n end", "def records(node, path, parameters={})\n result = request(path, parameters).values.first or return []\n result = result[node] or return []\n result = [result] unless Array === result\n result.map { |row| Record.new(node, row) }\n end", "def records(node, path, parameters={})\n result = request(path, parameters).values.first or return []\n result = result[node] or return []\n result = [result] unless Array === result\n result.map { |row| Record.new(node, row) }\n end", "def create\n @driver_record = DriverRecord.new(params[:driver_record])\n respond_to do |format|\n if @driver_record.save\n format.html { redirect_to @driver_record, notice: 'Driver record was successfully created.' }\n format.json { render json: @driver_record, status: :created, location: @driver_record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @driver_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @registro_record = RegistroRecord.new(params[:registro_record])\n\n respond_to do |format|\n if @registro_record.save\n format.html { redirect_to @registro_record, notice: 'Registro record was successfully created.' }\n format.json { render json: @registro_record, status: :created, location: @registro_record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @registro_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def record_params\n params.require(:record).permit(:date_text, :record_type, :product_text, :weight, :count, :user_id, :participant_text, :order_number, :employee_text, :client_text, :created_at, :updated_at)\n end", "def create\n @answer_record = AnswerRecord.new(answer_record_params)\n\n respond_to do |format|\n if @answer_record.save\n format.html { redirect_to @answer_record, notice: 'Answer record was successfully created.' }\n format.json { render :show, status: :created, location: @answer_record }\n else\n format.html { render :new }\n format.json { render json: @answer_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @record_object = RecordObject.new(record_object_params)\n\n respond_to do |format|\n if @record_object.save\n format.html { redirect_to @record_object, notice: 'RecordObject was successfully created.' }\n format.json { render :show, status: :created, location: @record_object }\n else\n format.html { render :new }\n format.json { render json: @record_object.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n\t\t\t\t\t# attributes\n\t\t\t\t\tbegin\n\t\t\t\t\t\tattrs = jsonapi_received_attributes\n\t\t\t\t\t\tif attrs\n\t\t\t\t\t\t\tif @jsonapi_record\n\t\t\t\t\t\t\t\t# update\n\t\t\t\t\t\t\t\t@jsonapi_record.update! attrs\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t# create\n\t\t\t\t\t\t\t\t@jsonapi_record = jsonapi_model_class.new attrs\n\t\t\t\t\t\t\t\t@jsonapi_record.save!\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\trescue NameError => e\n\t\t\t\t\t\tjsonapi_render_errors 500, \"Model class not found.\"\n\t\t\t\t\t\treturn\n\t\t\t\t\trescue \n\t\t\t\t\t\tjsonapi_render_errors 500, @jsonapi_record.to_jsonapi_errors_hash\n\t\t\t\t\t\treturn\n\t\t\t\t\tend\n\n\t\t\t\t\t# relationships\n\t\t\t\t\tjsonapi_received_relationships.each do |relationship|\n\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\t\t# to-one\n\t\t\t\t\t\t\t\tif relationship[:definition][:type] == :to_one\n\t\t\t\t\t\t\t\t\t@jsonapi_record.send :\"#{relationship[:definition][:name]}=\", relationship[:params][:data]\n\t\t\t\t\t\t\t\t\tnext\n\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t# to-many\n\t\t\t\t\t\t\t\t@jsonapi_record.send(relationship[:definition][:name]).send :clear # initialize the relation\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\trelationship[:params][:data].each do |item|\n\t\t\t\t\t\t\t\t\tobject = relationship[:receiver][:class].find_by_id item[:id]\n\t\t\t\t\t\t\t\t\t@jsonapi_record.send(relationship[:definition][:name]).send :<<, object\n\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\trescue \n\t\t\t\t\t\t\t# Should not happen\n\t\t\t\t\t\t\tjsonapi_render_errors 500, \"Relationship could not be created.\"\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\tshow\n\t\t\t\tend", "def create\n @record_status = RecordStatus.new(params[:record_status])\n\n respond_to do |format|\n if @record_status.save\n format.html { redirect_to @record_status, notice: 'Record status was successfully created.' }\n format.json { render json: @record_status, status: :created, location: @record_status }\n else\n format.html { render action: \"new\" }\n format.json { render json: @record_status.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @records = Record.all\n end", "def index\n @records = Record.all\n end", "def index\n @records = Record.all\n end", "def index\n @records = Record.all\n end", "def index\n @records = Record.all\n end", "def create_record_with_http_info(body, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: AccessRecordsApi.create_record ...'\n end\n # verify the required parameter 'body' is set\n if @api_client.config.client_side_validation && body.nil?\n fail ArgumentError, \"Missing the required parameter 'body' when calling AccessRecordsApi.create_record\"\n end\n # resource path\n local_var_path = '/v1/records'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/links+json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] || @api_client.object_to_http_body(body) \n\n return_type = opts[:return_type] || 'InlineResponse2008' \n\n auth_names = opts[:auth_names] || ['oauth2']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type)\n\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: AccessRecordsApi#create_record\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create\n @address_record = AddressRecord.new(address_record_params)\n\n respond_to do |format|\n if @address_record.save\n format.html { redirect_to @address_record, notice: 'Address record was successfully created.' }\n format.json { render :show, status: :created, location: @address_record }\n else\n format.html { render :new }\n format.json { render json: @address_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def records(node, path, parameters={})\n result = request(path, parameters).values.first or return []\n result = result[node] or return []\n result = [result] unless Array === result\n result.map { |row| Record.new(node, row) }\n end", "def create\n @student_record = StudentRecord.new(student_record_params)\n\n respond_to do |format|\n if @student_record.save\n format.html { redirect_to @student_record, notice: 'Student record was successfully created.' }\n format.json { render :show, status: :created, location: @student_record }\n else\n format.html { render :new }\n format.json { render json: @student_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @record = Asset.new(params[:@record])\n respond_to do |format|\n if @record.save\n format.html \n format.json { render json: {} }\n else\n format.html { render action: \"new\" }\n format.json { render json: {} }\n end\n end\n end", "def create\n @player_record = PlayerRecord.new(params[:player_record])\n\n respond_to do |format|\n if @player_record.save\n format.html { redirect_to @player_record, notice: 'Player record was successfully created.' }\n format.json { render json: @player_record, status: :created, location: @player_record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @player_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @medrecord = Medrecord.new(params[:medrecord])\n\n respond_to do |format|\n if @medrecord.save\n format.html { redirect_to @medrecord, notice: 'Medrecord was successfully created.' }\n format.json { render json: @medrecord, status: :created, location: @medrecord }\n else\n format.html { render action: \"new\" }\n format.json { render json: @medrecord.errors, status: :unprocessable_entity }\n end\n end\n end", "def POST; end", "def create\n @daily_record = DailyRecord.new(daily_record_params)\n\n respond_to do |format|\n if @daily_record.save\n format.html { redirect_to @daily_record, notice: 'Daily record was successfully created.' }\n format.json { render :show, status: :created, location: @daily_record }\n else\n format.html { render :new }\n format.json { render json: @daily_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def addRecords(recs); recs.each { |r| addRecord r } end", "def create\n @recording = Recording.new(recording_params)\n respond_to do |format|\n if @recording.save\n format.html { redirect_to @recording, notice: 'Recording was successfully created.' }\n format.json { render :show, status: :created, location: @recording }\n else\n format.html { render :new }\n format.json { render json: @recording.errors, status: :unprocessable_entity }\n end\n end\n end", "def serialize_records\n return nil unless last_response.respond_to?(:records)\n\n last_response.records.map do |remote_record|\n record = self.class.allocate\n record.instantiate(remote_record.to_hash)\n record\n end\n end", "def create\n @account_record = AccountRecord.new(account_record_params)\n\n respond_to do |format|\n if @account_record.save\n format.html { redirect_to @account_record, notice: 'Account record was successfully created.' }\n format.json { render :show, status: :created, location: @account_record }\n else\n format.html { render :new }\n format.json { render json: @account_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pay_record = PayRecord.new(pay_record_params)\n\n respond_to do |format|\n if @pay_record.save\n format.html { redirect_to @pay_record, notice: 'Pay record was successfully created.' }\n format.json { render action: 'show', status: :created, location: @pay_record }\n else\n format.html { render action: 'new' }\n format.json { render json: @pay_record.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_record(http)\n json = %|{\n \"kind\": \"Article\",\n \"title\": \"Sample\",\n \"text\": \"Just some random text.\"\n}|\n resp = http.send_request('PUT', '/v1/Article', json, { 'Content-Type' => 'application/json' })\n # Response should be an OK with a JSON body.\n assert_equal(Net::HTTPOK, resp.class, 'response not an OK')\n reply = Oj.strict_load(resp.body, symbol_keys: true)\n\n # Make sure the message has the correct fields and values.\n assert_equal(0, reply[:code], 'create reply.code should be 0 meaning no error')\n ref = reply[:ref]\n refute_equal(nil, ref, 'create reply record reference can not be nil')\n refute_equal(0, ref, 'create reply record reference can not be 0')\n ref\n end", "def add_vat_record_with_http_info(vat_records, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: VatRecordApi.add_vat_record ...'\n end\n # verify the required parameter 'vat_records' is set\n if @api_client.config.client_side_validation && vat_records.nil?\n fail ArgumentError, \"Missing the required parameter 'vat_records' when calling VatRecordApi.add_vat_record\"\n end\n # resource path\n local_var_path = '/vat_records'\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(vat_records)\n auth_names = ['api_key']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'VatRecord')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: VatRecordApi#add_vat_record\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create\n record = Asset.new(params[:record])\n respond_to do |format|\n if record.save\n format.html \n format.json { render json: {} }\n else\n format.html { render action: \"new\" }\n format.json { render json: {} }\n end\n end\n end", "def create\n @time_record = TimeRecord.new(params[:time_record])\n @time_record.value = (@time_record.ended_at - @time_record.started_at) / 1.hour\n @time_record.recorded_on = @time_record.started_at.to_date\n\n respond_to do |format|\n if @time_record.save\n format.html { redirect_to time_records_path, notice: 'Time record was successfully created.' }\n format.json { render json: @time_record.to_json, status: :created, location: @time_record }\n else\n format.html { render action: \"new\" }\n format.json { render json: @time_record.errors.full_messages, status: :unprocessable_entity }\n end\n end\n end", "def create\n @mailrecord = Mailrecord.new(mailrecord_params)\n\n respond_to do |format|\n if @mailrecord.save\n format.html { redirect_to @mailrecord, notice: 'Mailrecord was successfully created.' }\n format.json { render action: 'show', status: :created, location: @mailrecord }\n else\n format.html { render action: 'new' }\n format.json { render json: @mailrecord.errors, status: :unprocessable_entity }\n end\n end\n end", "def record_params\n params.require(:record).permit(:name, :info, :year, :performer_id)\n end" ]
[ "0.7008424", "0.6489232", "0.63915163", "0.6380105", "0.6365723", "0.633085", "0.6324324", "0.6312938", "0.6291036", "0.6254665", "0.62195176", "0.60934305", "0.60851955", "0.60323256", "0.60116625", "0.5957577", "0.594642", "0.591192", "0.59088993", "0.5867076", "0.5854219", "0.58514225", "0.58330023", "0.5800175", "0.57888657", "0.5780504", "0.577591", "0.5764132", "0.57384014", "0.5720841", "0.5690014", "0.56865627", "0.56850106", "0.5675233", "0.5669811", "0.5654453", "0.5654431", "0.5646462", "0.5643616", "0.56411284", "0.5637018", "0.56296724", "0.56282556", "0.5627378", "0.5616676", "0.56095994", "0.5598893", "0.5598354", "0.5598341", "0.55703604", "0.5570353", "0.5545332", "0.5535092", "0.5533472", "0.55265766", "0.55208004", "0.5518939", "0.551643", "0.5514815", "0.5512816", "0.5505677", "0.54979753", "0.5497349", "0.5497349", "0.5495588", "0.54897267", "0.5483443", "0.5483443", "0.54797095", "0.54757726", "0.5466767", "0.5463056", "0.5460509", "0.5456804", "0.54484725", "0.54478055", "0.54478055", "0.54478055", "0.54478055", "0.54478055", "0.5434043", "0.5431431", "0.5423646", "0.542104", "0.5420772", "0.541936", "0.5411088", "0.5407048", "0.5402813", "0.54013705", "0.5398011", "0.5390346", "0.5387049", "0.53784066", "0.53777146", "0.53753656", "0.5371354", "0.53697246", "0.53640354", "0.5360907" ]
0.5931146
17
Use callbacks to share common setup or constraints between actions.
def set_address @address = Addresslanlng.new end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1