query
stringlengths
7
6.41k
document
stringlengths
12
28.8k
metadata
dict
negatives
listlengths
30
30
negative_scores
listlengths
30
30
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
Gets the gracePeriodInMinutes property value. The number of minutes to wait before restarting the device after an app installation.
def grace_period_in_minutes return @grace_period_in_minutes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def grace_period\n config['grace_period'] || 60\n end", "def grace_period_in_minutes=(value)\n @grace_period_in_minutes = value\n end", "def grace_period\n Integer(ENV[\"BUDDY_CHECK_GRACE_PERIOD\"].presence || \"4\").hours\n end", "def grace_period\n (ENV[\"BUDDY_CHECK_GRACE_PERIOD\"].presence || \"4\").to_i.hours\n end", "def health_check_grace_period\n @group.health_check_grace_period\n end", "def remaining_days_of_grace\n self.expire_on - Date.today - 1\n end", "def date_inside_grace_window(expires_on)\n (expires_on + Rails.configuration.registration_grace_window) - 1.day\n end", "def shutdown_grace_timeout\n @shutdown_grace_timeout || 2\n end", "def lifetime_in_minutes\n return @lifetime_in_minutes\n end", "def restart_notification_snooze_duration_in_minutes\n return @restart_notification_snooze_duration_in_minutes\n end", "def grace_period_expires_date\n read_datetime_from_string('grace_period_expires_date')\n end", "def grace_duration=(grace_duration)\n\n if !grace_duration.nil? && grace_duration < 0\n fail ArgumentError, \"invalid value for 'grace_duration', must be greater than or equal to 0.\"\n end\n\n @grace_duration = grace_duration\n end", "def lock_interval\n get_settings[:lock_interval]\n end", "def last_day_of_standard_grace_window\n (expiry_date + Rails.configuration.grace_window.days) - 1.day\n end", "def timeout_in_minutes\n data[:timeout_in_minutes]\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def lock_timeout\n result = Mimi::DB.execute('select setting from pg_settings where name = ?', :lock_timeout)\n value = result.first['setting'].to_i\n value = value.to_f / 1000 unless value == 0\n value\n end", "def timeout_in\n if admin?\n 1.hour\n else\n 3.days\n end\n end", "def timeout_in\n if admin?\n 1.hour\n else\n 3.days\n end\n end", "def timeout_in\n if admin?\n 1.hour\n else\n 3.days\n end\n end", "def timeout_in\n if self.admin?\n 10.minutes\n else\n 15.minutes\n end\n end", "def password_minutes_of_inactivity_before_lock\n return @password_minutes_of_inactivity_before_lock\n end", "def password_minutes_of_inactivity_before_lock\n return @password_minutes_of_inactivity_before_lock\n end", "def last_day_of_grace_window_with_covid_extension\n (expiry_date + Rails.configuration.covid_grace_window.days) - 1.day\n end", "def monitoring_interval\n data[:monitoring_interval]\n end", "def monitoring_interval\n data[:monitoring_interval]\n end", "def last_day_of_extended_grace_window\n (expiry_date + Rails.configuration.expires_after.years) - 1.day\n end", "def period_length_in_seconds\n @period_length_in_seconds ||= period_length.to_i.minutes.to_i\n end", "def days_remaining_until_password_expire\n @attributes[:days_remaining_until_password_expire]\n end" ]
[ "0.7927201", "0.7733176", "0.75255436", "0.7262469", "0.6507338", "0.62577146", "0.5999537", "0.59116185", "0.5834151", "0.57465625", "0.57101595", "0.5709149", "0.5608274", "0.55790067", "0.5444113", "0.53648925", "0.53648925", "0.53526986", "0.53356713", "0.53356713", "0.53356713", "0.533268", "0.5325971", "0.5325971", "0.5324852", "0.53178984", "0.53178984", "0.53075546", "0.5291337", "0.5273149" ]
0.852647
0
Sets the gracePeriodInMinutes property value. The number of minutes to wait before restarting the device after an app installation.
def grace_period_in_minutes=(value) @grace_period_in_minutes = value end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def grace_period\n config['grace_period'] || 60\n end", "def grace_period_in_minutes\n return @grace_period_in_minutes\n end", "def grace_period\n Integer(ENV[\"BUDDY_CHECK_GRACE_PERIOD\"].presence || \"4\").hours\n end", "def grace_period\n (ENV[\"BUDDY_CHECK_GRACE_PERIOD\"].presence || \"4\").to_i.hours\n end", "def grace_duration=(grace_duration)\n\n if !grace_duration.nil? && grace_duration < 0\n fail ArgumentError, \"invalid value for 'grace_duration', must be greater than or equal to 0.\"\n end\n\n @grace_duration = grace_duration\n end", "def shutdown_grace_timeout\n @shutdown_grace_timeout || 2\n end", "def expire_after_grace!(transaction = nil)\n return unless self.expire_on.nil? # You only set this once subsequent failed transactions shouldn't affect expiration\n self.expire_on = [Date.today, paid_through].max + Freemium.days_grace\n transaction.message = \"now set to expire on #{self.expire_on}\" if transaction\n Freemium.mailer.deliver_expiration_warning(self)\n transaction.save! if transaction\n save!\n end", "def restart_notification_snooze_duration_in_minutes=(value)\n @restart_notification_snooze_duration_in_minutes = value\n end", "def date_inside_grace_window(expires_on)\n (expires_on + Rails.configuration.registration_grace_window) - 1.day\n end", "def health_check_grace_period\n @group.health_check_grace_period\n end", "def remaining_days_of_grace\n self.expire_on - Date.today - 1\n end", "def on_grace_period\n !!(ends_at && ends_at.future?)\n end", "def set_max_wait_time\n q = 'Set the MAX WAIT TIME after executing the RESTART command ' \\\n '(>= 180 secs): '\n until @max_wait && @max_wait.to_i > 179\n @max_wait = Utils.qna(q.cyan, true)\n end\n end", "def grace_period_expires_date\n read_datetime_from_string('grace_period_expires_date')\n end", "def lifetime_in_minutes=(value)\n @lifetime_in_minutes = value\n end", "def signal_restart_graceful\n @signal_operation_queue << :restart_graceful\n interrupt_server_polling_sleep\n nil\n end", "def terminate_at(seconds = 60)\n @terminate_at = seconds\n end", "def setMinutes(minutes)\r\n\t\t\t\t\t@minutes = minutes\r\n\t\t\t\tend", "def implicit_wait=(seconds); end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def restart_notification_snooze_duration_in_minutes\n return @restart_notification_snooze_duration_in_minutes\n end", "def password_minutes_of_inactivity_before_lock=(value)\n @password_minutes_of_inactivity_before_lock = value\n end", "def password_minutes_of_inactivity_before_lock=(value)\n @password_minutes_of_inactivity_before_lock = value\n end", "def lock_interval= value\n put_settings(get_settings.tap {|s| s[:lock_interval] = value})\n end", "def reconnect_interval=(val)\n @j_del.setReconnectInterval(val)\n self\n end", "def retry_interval\n @options[:retry_interval]\n end", "def lock_interval\n get_settings[:lock_interval]\n end", "def automatic_restart=(value)\n @automatic_restart = value\n end", "def start_expiry_period!\n self.update_attribute(:access_token_expires_at, Time.now + Devise.timeout_in)\n end" ]
[ "0.72385937", "0.6891492", "0.63716114", "0.6176589", "0.5830609", "0.54698396", "0.53761536", "0.5191597", "0.51391387", "0.50907636", "0.5034328", "0.49405888", "0.4938738", "0.48332992", "0.4831327", "0.48058861", "0.47441655", "0.47361067", "0.46910712", "0.4637752", "0.4637752", "0.46373147", "0.4588626", "0.4588626", "0.4587147", "0.45451915", "0.4543601", "0.45380136", "0.45349374", "0.45268527" ]
0.7802341
0
Gets the restartNotificationSnoozeDurationInMinutes property value. The number of minutes to snooze the restart notification dialog when the snooze button is selected.
def restart_notification_snooze_duration_in_minutes return @restart_notification_snooze_duration_in_minutes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def restart_notification_snooze_duration_in_minutes=(value)\n @restart_notification_snooze_duration_in_minutes = value\n end", "def minutes\n _nudge[1]\n end", "def countdown_display_before_restart_in_minutes\n return @countdown_display_before_restart_in_minutes\n end", "def getDurationMinutes\r\n\t\t\t\t\treturn @durationMinutes\r\n\t\t\t\tend", "def restart_count\n return @restart_count\n end", "def getMinutes\r\n\t\t\t\t\treturn @minutes\r\n\t\t\t\tend", "def minutes\n (seconds % 3600) / 60\n end", "def in_minutes\n Duration::new(seconds: @seconds).to_minutes\n end", "def grace_period_in_minutes\n return @grace_period_in_minutes\n end", "def durationInMinutes\n @duration/60.0 #Force floating pt.\n end", "def minutes\n (@seconds.abs / 60) % 60 * (@seconds < 0 ? -1 : 1)\n end", "def minutes\n\t\treturn self * 60\n\tend", "def minutes\n\t\treturn self * 60\n\tend", "def lifetime_in_minutes\n return @lifetime_in_minutes\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def get_duration_integer_minutes\n\t\t((end_time - start_time) / 60).to_i\n\tend", "def running_time_in_minutes\n return 0 if self.started_at.nil? and self.stopped_at.nil?\n\n if self.stopped_at.nil?\n # Raid has not yet been stopped, use the current time\n ((Time.now - self.started_at)/60.0).floor\n else\n ((self.stopped_at - self.started_at)/60.0).floor\n end\n end", "def minutes() 60 * seconds end", "def timeout_in_minutes\n data[:timeout_in_minutes]\n end", "def minutes_as_duration\n WorkEntry.minutes_as_duration(self.minutes)\n end", "def countdown_display_before_restart_in_minutes=(value)\n @countdown_display_before_restart_in_minutes = value\n end", "def minutes\n self * SECONDS_IN_MINUTES\n end", "def timeout_in_minutes\n @stack.timeout_in_minutes\n end", "def today_minutes_resting\n self[:min_rest]\n end", "def minutes\n value_parts[1]\n end", "def minutes\n value_parts[1]\n end", "def get_duration\n ((finish - start) / 60 / 60) - (break_length / 60)\n end", "def retry_interval\n @options[:retry_interval]\n end", "def duration_in_seconds\n return @duration_in_seconds\n end" ]
[ "0.80405897", "0.58074635", "0.57878417", "0.57857066", "0.5722918", "0.5672198", "0.56698054", "0.5646157", "0.55132204", "0.5461743", "0.5448392", "0.54086286", "0.54086286", "0.54074484", "0.54024965", "0.54024965", "0.5375624", "0.53550667", "0.535254", "0.53249764", "0.5319535", "0.5300941", "0.5262884", "0.5242884", "0.5232975", "0.5218101", "0.5218101", "0.52081895", "0.5137828", "0.5119624" ]
0.86595196
0
Sets the restartNotificationSnoozeDurationInMinutes property value. The number of minutes to snooze the restart notification dialog when the snooze button is selected.
def restart_notification_snooze_duration_in_minutes=(value) @restart_notification_snooze_duration_in_minutes = value end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def restart_notification_snooze_duration_in_minutes\n return @restart_notification_snooze_duration_in_minutes\n end", "def countdown_display_before_restart_in_minutes=(value)\n @countdown_display_before_restart_in_minutes = value\n end", "def restart_count=(value)\n @restart_count = value\n end", "def setMinutes(minutes)\r\n\t\t\t\t\t@minutes = minutes\r\n\t\t\t\tend", "def automatic_restart=(value)\n @automatic_restart = value\n end", "def grace_period_in_minutes=(value)\n @grace_period_in_minutes = value\n end", "def setDurationMinutes(durationMinutes) \r\n\t\t\t\t\t@durationMinutes = durationMinutes\r\n\t\t\t\tend", "def restart=(restart)\n validator = EnumAttributeValidator.new('String', ['Always', 'WhenNotActive', 'Never', 'NotDefined'])\n unless validator.valid?(restart)\n fail ArgumentError, 'invalid value for \"restart\", must be one of #{validator.allowable_values}.'\n end\n @restart = restart\n end", "def restart( timeout = 5 )\n stop( timeout )\n start\n end", "def password_minutes_of_inactivity_before_screen_timeout=(value)\n @password_minutes_of_inactivity_before_screen_timeout = value\n end", "def password_minutes_of_inactivity_before_screen_timeout=(value)\n @password_minutes_of_inactivity_before_screen_timeout = value\n end", "def vote_to_restart(timer_trigger = false)\n if @restart_vote\n @restart_vote.call\n if timer_trigger\n start_timer\n else\n @restart_vote_count = 0\n end\n end\n true\n end", "def respawn_window\n @options['respawn_window'] ? @options['respawn_window'].to_i : 3600\n end", "def reset_interval\n options[:reset_interval].to_f\n end", "def work_profile_password_minutes_of_inactivity_before_screen_timeout=(value)\n @work_profile_password_minutes_of_inactivity_before_screen_timeout = value\n end", "def restart_autosync\n #Remove current timeout.\n Gtk.timeout_remove(@autosync_timeout) if @autosync_timeout\n @autosync_timeout = nil\n \n #Get various info from db.\n enabled = Knj::Strings.yn_str(Knj::Opts.get(\"autosync_enabled\"), true, false)\n interval = Knj::Opts.get(\"autosync_interval\").to_i\n interval_msecs = interval * 60 * 1000\n \n if !enabled #dont continue if autosync isnt enabled.\n self.status = _(\"Disabled automatic synchronization.\")\n return nil\n end\n \n self.status = sprintf(_(\"Restarted automatic sync. to run every %s minutes.\"), Knj::Locales.number_out(interval, 1))\n \n #Start new timeout.\n @autosync_timeout = Gtk.timeout_add(interval_msecs, &self.method(:gtk_timeout))\n end", "def restart(timeout=nil)\n stop(timeout)\n start!\n end", "def minretrydelay=(retry_delay)\r\n\t\t\t`#{BITS::BITSADMIN} /setminretrydelay {#{@id}} #{retry_delay}`\r\n\t\tend", "def restart\n request('restart')\n end", "def reconnect_interval=(val)\n @j_del.setReconnectInterval(val)\n self\n end", "def retry_interval\n @options[:retry_interval]\n end", "def start_timer\n if @restart_vote && @state != :terminating\n @restart_vote_timer ||= EM::Timer.new(RESTART_VOTE_DELAY) { vote_to_restart(timer_trigger = true) }\n end\n true\n end", "def restart_count\n return @restart_count\n end", "def reconnect_attempts=(val)\n @j_del.setReconnectAttempts(val)\n self\n end", "def restart!\n # Permissions are handled by the script, use: :sudo => false\n run_script! :restart, :sudo => false\n end", "def retry_interval\n @retry_interval ||= options[:retry_interval] || RETRY_INTERVAL\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def passcode_minutes_of_inactivity_before_screen_timeout=(value)\n @passcode_minutes_of_inactivity_before_screen_timeout = value\n end", "def adjust_duration\n # convert minutes into seconds\n self.duration = duration.to_i * 60\n end" ]
[ "0.7709535", "0.54065514", "0.5065944", "0.50300866", "0.48830426", "0.48774555", "0.48566982", "0.48280942", "0.48192656", "0.47637227", "0.47637227", "0.47322124", "0.46878687", "0.46627617", "0.46418434", "0.45728937", "0.45712686", "0.45511588", "0.45501104", "0.45446718", "0.453462", "0.4518573", "0.45174542", "0.4490002", "0.44726196", "0.44701624", "0.44697043", "0.44697043", "0.446461", "0.44460133" ]
0.84445095
0
Optionally produces a unique key to ensure uniqueness of this job. See the Generators module methods for example job_id generators you can use.
def create_job_id application_job_overrides_method!(__method__) # default implementation for framework jobs Generators.generate_uuid(self) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unique_key\n @unique_key ||= section.identifier\n end", "def job_identity(args)\n Digest::SHA1.hexdigest([ Time.now.to_f, rand, self, args ].join)\n end", "def job_key\n Digest::MD5.hexdigest(path)\n end", "def key(name)\n @unique_key = name\n end", "def generate_key; end", "def job_id\n raise NotImplementedError\n end", "def gen_key(record)\n return Digest::SHA2.hexdigest(record.to_s)\n end", "def generate_unique_key\n\n # @TODO:need to update the algo. Right now it's very simple algo\n length = self.url.length\n rand(36**length).to_s(36)\n end", "def job_id=(value)\n @job_id = value.to_s\n end", "def good_job_concurrency_key\n @good_job_concurrency_key || _good_job_concurrency_key\n end", "def create_key\n self.key = Digest::MD5.hexdigest(self.official_id.to_s + self.sent_to_email)\n end", "def new_worker(opts={})\n @mutex.synchronize {\n job_key = opts[:job_key] || gen_key\n unless self[job_key]\n self[job_key] = instantiate_worker(opts[:class]).new(opts[:args])\n return job_key\n else\n raise ::BackgrounDRbDuplicateKeyError\n end \n }\n end", "def job_key; Thread.current[:job_key]; end", "def generate_primary_key\n self[self.class.primary_key] ||= self.class.new_primary_key(10_000)\n end", "def create_unique_key\n begin\n self.unique_key = UrlShort.generate_key\n rescue ActiveRecord::RecordNotUnique\n if (count +=1) < 5\n retry\n else\n raise\n end\n end\n end", "def generate_key(*args)\n @cache_keys[args.join] ||= @key_generator.generate_key(*args)\n end", "def jobid_prefix\n @jobid_prefix\n end", "def next_job_id\n new_id = rand(10*5)\n get_job_status(new_id).nil? ? new_id : next_job_id\n end", "def key\n @key ||= self.project.key + '-' + self.no.to_s\n end", "def uniqueness_generate\n self.uniqueness_options.each do |field, options|\n value = send(field)\n unless value.present?\n value = Uniqueness.generate(options)\n self.send(\"#{field}=\", value)\n end\n end\n end", "def generate_unique_key(now = Time.now)\n u1 = ((now.to_i*1000*1000+now.usec) << 12 | rand(0xfff))\n uid = [u1 >> 32, u1 & 0xffffffff, rand(0xffffffff), rand(0xffffffff)].pack('NNNN')\n uid.unpack('C*').map { |x| \"%02x\" % x }.join\n end", "def rand_key\n return JString.new\n end", "def generate_unique_key\n # not doing uppercase as url is case insensitive\n charset = ::Shortener.key_chars\n (0...::Shortener.unique_key_length).map{ charset[rand(charset.size)] }.join\n end", "def unique_key\n \"redis:bitops:#{SecureRandom.hex(20)}\"\n end", "def job_id\n async && async.job_id\n end", "def __object_unique_id__\n return @args[:data][:Key_name]\n end", "def generate_key\n proposed_key = nil\n\n loop do\n num_part = rand(10**7).to_s.rjust(7, \"0\")\n proposed_key = \"#{IDB_CONFIG[:key_prefix]}-#{num_part}\"\n break unless self.class.find_by(key: proposed_key)\n end\n proposed_key\n end", "def grab_job_uniq\n throw :notimpl\n end", "def prime(job_id)\n redis do |conn|\n conn.lpush(key.primed, job_id)\n end\n end", "def job_id\n @gapi.job_reference.job_id\n end" ]
[ "0.69451106", "0.67873806", "0.6724584", "0.6546879", "0.65102255", "0.6479524", "0.62474793", "0.6236482", "0.621921", "0.620373", "0.61658543", "0.6165188", "0.6146043", "0.61419886", "0.6134388", "0.6120992", "0.60996795", "0.6059127", "0.6036548", "0.6024705", "0.60245883", "0.6008445", "0.5997236", "0.597887", "0.59474486", "0.5942782", "0.59291434", "0.59177876", "0.58889496", "0.5849052" ]
0.69101393
1
Example: 34,592,129,909 => [3,4,5,9,2,1,2,9,9,0,9]
def num_to_array num array = [] div = 100000 while div >= 1 if (num / div) > 0 digit = num / div array << digit num = num - (div * digit) end div = div / 10 end return array end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def digit_list(num)\n arr = []\n divisor = 10**((num.to_s.length) - 1)\n \n while divisor >= 1\n digit = num/divisor\n arr << (num / divisor)\n num -= digit*divisor\n\n divisor = divisor / 10\n end\n \n arr\nend", "def given\n [6,5,3,1,8,7,2,3]\nend", "def cracklepop_numbers(from, to)\n (from..to).to_a.map { |n| cracklepop_number(n) }\nend", "def numbers\n %w[1 2 3 4 5 6 7 8 9 0\n tenth ninth eighth seventh sixth fifth fourth third second first\n ten nine eight seven six five four three two one ]\n end", "def split_number(start)\r\r\n number = []\r\r\n number[0] = start / 1000 / 1000\r\r\n number[1] = start / 1000 % 1000\r\r\n number[2] = start % 1000\r\r\n return number\r\r\n end", "def digit_list(num)\n result = []\n\n until num.zero?\n num, remainder = num.divmod(10)\n result.unshift(remainder)\n end\n result\nend", "def digit_list(num)\n int_array = []\n digit_array = num.to_s.split(//)\n digit_array.each do |numb|\n int_array += [numb.to_i]\n end\n int_array\nend", "def split_number(start)\n number = []\n number[0] = start / 1000 / 1000\n number[1] = start / 1000 % 1000\n number[2] = start % 1000\n return number\n end", "def digitArray(num)\n\tdigs = []\n\twhile num > 9\n\t\tnum, last_digit = num.divmod(10)\n\t\tdigs << last_digit\n\tend\n\tdigs << num\n\tdigs\nend", "def splitNumber(val)\n\tresArr = []\n\twhile(val >= 1)\n\t\tresArr.push(val % 10)\n\t\tval = val / 10\n\tend\n\tresArr\nend", "def list_of_nums(num)\n num.to_s.split('').map! {|n| n.to_i}\nend", "def digit_list(number)\r\n digits = []\r\n loop do\r\n number, remainder = number.divmod(10)\r\n digits.unshift(remainder)\r\n break if number == 0\r\n end\r\n digits\r\nend", "def digit_list(number)\n digits = number.to_s.split('')\n digits = digits.map { |digit| digit.to_i }\n digits\nend", "def digit_list(number)\n return number.abs.to_s.split('').map(&:to_i)\nend", "def digit_list(n)\n list = n.to_s\n list = list.split('')\n list = list.map do |i|\n i.to_i\n end\n return list\nend", "def amicable_numbers(n)\r\n numbers = Array.new\r\n 2.upto(n) do |x|\r\n y = d(x)\r\n if !numbers.include?(y)\r\n numbers.push(x,y) if d(y) == x && y != x\r\n end\r\n end\r\n return numbers\r\nend", "def numUnique2 list\n current_num = list[0]\n unique_numbers = [list[0]]\n\n list.each do |num|\n if num != current_num\n current_num = num\n unique_numbers << num\n end\n end\n return \"**#{unique_numbers.length}**\"\nend", "def series_up(nums) \r\n series = 0 # start the list at the right \r\n list = [] # the list is empty at the start \r\n nums.times do |seq| \r\n n = 0 \r\n nums.times do |nums| # run a loop for the sequence \r\n list[n + series] = n + 1 \r\n n += 1 \r\n end \r\n series += seq + 1 # exponential growth \r\nend \r\n return list \r\nend", "def digit_list(number)\n digits = []\n\n loop do\n number, rem = number.divmod(10)\n digits.unshift(rem)\n\n break if number == 0\n end\n\n digits\nend", "def integer_pigeonhole_sort(numbers)\n sorted = []\n\n numbers.length.times do |i|\n sorted << i\n end\n\n sorted\nend", "def digit_list(num)\n string = num.to_s\n array = string.split('')\n array.map {|num| num.to_i}\nend", "def element_times_index(numbers)\n new_nums = []\n \n i = 0\n while i < numbers.length\n new_nums << numbers[i] * i\n \n i += 1\n end\n \n return new_nums\n end", "def digitize(n)\n number_array =[] #convert n into a string to use split. Map lets us create a new array but we must convert back into int\n number_array = n.to_s.split(\" \").map(&:to_i) # SPLIT divided strings into substrings\n return number_array\n\nend", "def digit_list(num)\n digits = []\n\n loop do\n number, remainder = number.divmod(10)\n digits.unshift(remainder)\n break if number == 0\n end\n\n digits\nend", "def to_a (num)\n arr = []\n for i in Math.log10(num).floor.downto(0) # Range for separating each digit\n arr.push((num/10**i).floor - (num/10**(i+1)).floor * 10 )\n end\n return arr\nend", "def digit_list(num)\n num.to_s.chars.map {|val| val.to_i}\nend", "def wtf_nums()\r\n\tthe_wtf_num = [37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538,\r\n\t\t\t\t\t74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250,\r\n\t\t\t\t\t23067588207539346171171980310421047513778063246676, 89261670696623633820136378418383684178734361726757,\r\n\t\t\t\t\t28112879812849979408065481931592621691275889832738, 44274228917432520321923589422876796487670272189318,\r\n\t\t\t\t\t47451445736001306439091167216856844588711603153276, 70386486105843025439939619828917593665686757934951,\r\n\t\t\t\t\t62176457141856560629502157223196586755079324193331, 64906352462741904929101432445813822663347944758178,\r\n\t\t\t\t\t92575867718337217661963751590579239728245598838407, 58203565325359399008402633568948830189458628227828,\r\n\t\t\t\t\t80181199384826282014278194139940567587151170094390, 35398664372827112653829987240784473053190104293586,\r\n\t\t\t\t\t86515506006295864861532075273371959191420517255829, 71693888707715466499115593487603532921714970056938,\r\n\t\t\t\t\t54370070576826684624621495650076471787294438377604, 53282654108756828443191190634694037855217779295145,\r\n\t\t\t\t\t36123272525000296071075082563815656710885258350721, 45876576172410976447339110607218265236877223636045,\r\n\t\t\t\t\t17423706905851860660448207621209813287860733969412, 81142660418086830619328460811191061556940512689692,\r\n\t\t\t\t\t51934325451728388641918047049293215058642563049483, 62467221648435076201727918039944693004732956340691,\r\n\t\t\t\t\t15732444386908125794514089057706229429197107928209, 55037687525678773091862540744969844508330393682126,\r\n\t\t\t\t\t18336384825330154686196124348767681297534375946515, 80386287592878490201521685554828717201219257766954,\r\n\t\t\t\t\t78182833757993103614740356856449095527097864797581, 16726320100436897842553539920931837441497806860984,\r\n\t\t\t\t\t48403098129077791799088218795327364475675590848030, 87086987551392711854517078544161852424320693150332,\r\n\t\t\t\t\t59959406895756536782107074926966537676326235447210, 69793950679652694742597709739166693763042633987085,\r\n\t\t\t\t\t41052684708299085211399427365734116182760315001271, 65378607361501080857009149939512557028198746004375,\r\n\t\t\t\t\t35829035317434717326932123578154982629742552737307, 94953759765105305946966067683156574377167401875275,\r\n\t\t\t\t\t88902802571733229619176668713819931811048770190271, 25267680276078003013678680992525463401061632866526,\r\n\t\t\t\t\t36270218540497705585629946580636237993140746255962, 24074486908231174977792365466257246923322810917141,\r\n\t\t\t\t\t91430288197103288597806669760892938638285025333403, 34413065578016127815921815005561868836468420090470,\r\n\t\t\t\t\t23053081172816430487623791969842487255036638784583, 11487696932154902810424020138335124462181441773470,\r\n\t\t\t\t\t63783299490636259666498587618221225225512486764533, 67720186971698544312419572409913959008952310058822,\r\n\t\t\t\t\t95548255300263520781532296796249481641953868218774, 76085327132285723110424803456124867697064507995236,\r\n\t\t\t\t\t37774242535411291684276865538926205024910326572967, 23701913275725675285653248258265463092207058596522,\r\n\t\t\t\t\t29798860272258331913126375147341994889534765745501, 18495701454879288984856827726077713721403798879715,\r\n\t\t\t\t\t38298203783031473527721580348144513491373226651381, 34829543829199918180278916522431027392251122869539,\r\n\t\t\t\t\t40957953066405232632538044100059654939159879593635, 29746152185502371307642255121183693803580388584903,\r\n\t\t\t\t\t41698116222072977186158236678424689157993532961922, 62467957194401269043877107275048102390895523597457,\r\n\t\t\t\t\t23189706772547915061505504953922979530901129967519, 86188088225875314529584099251203829009407770775672,\r\n\t\t\t\t\t11306739708304724483816533873502340845647058077308, 82959174767140363198008187129011875491310547126581,\r\n\t\t\t\t\t97623331044818386269515456334926366572897563400500, 42846280183517070527831839425882145521227251250327,\r\n\t\t\t\t\t55121603546981200581762165212827652751691296897789, 32238195734329339946437501907836945765883352399886,\r\n\t\t\t\t\t75506164965184775180738168837861091527357929701337, 62177842752192623401942399639168044983993173312731,\r\n\t\t\t\t\t32924185707147349566916674687634660915035914677504, 99518671430235219628894890102423325116913619626622,\r\n\t\t\t\t\t73267460800591547471830798392868535206946944540724, 76841822524674417161514036427982273348055556214818,\r\n\t\t\t\t\t97142617910342598647204516893989422179826088076852, 87783646182799346313767754307809363333018982642090,\r\n\t\t\t\t\t10848802521674670883215120185883543223812876952786, 71329612474782464538636993009049310363619763878039,\r\n\t\t\t\t\t62184073572399794223406235393808339651327408011116, 66627891981488087797941876876144230030984490851411,\r\n\t\t\t\t\t60661826293682836764744779239180335110989069790714, 85786944089552990653640447425576083659976645795096,\r\n\t\t\t\t\t66024396409905389607120198219976047599490197230297, 64913982680032973156037120041377903785566085089252,\r\n\t\t\t\t\t16730939319872750275468906903707539413042652315011, 94809377245048795150954100921645863754710598436791,\r\n\t\t\t\t\t78639167021187492431995700641917969777599028300699, 15368713711936614952811305876380278410754449733078,\r\n\t\t\t\t\t40789923115535562561142322423255033685442488917353, 44889911501440648020369068063960672322193204149535,\r\n\t\t\t\t\t41503128880339536053299340368006977710650566631954, 81234880673210146739058568557934581403627822703280,\r\n\t\t\t\t\t82616570773948327592232845941706525094512325230608, 22918802058777319719839450180888072429661980811197,\r\n\t\t\t\t\t77158542502016545090413245809786882778948721859617, 72107838435069186155435662884062257473692284509516,\r\n\t\t\t\t\t20849603980134001723930671666823555245252804609722, 53503534226472524250874054075591789781264330331690]\r\n\t# try\r\n\treturn the_wtf_num.inject(0){ |sum, i| sum + i }\r\nend", "def digit_list(number)\n number.to_s.chars.map(&:to_i)\nend", "def digit_list(number)\n number.to_s.chars.map(&:to_i)\nend", "def digit_list(number)\n number.to_s.chars.map(&:to_i)\nend" ]
[ "0.6796014", "0.67468256", "0.66053814", "0.658939", "0.65767604", "0.6517231", "0.6487109", "0.6483543", "0.64770216", "0.6473975", "0.64121974", "0.64044446", "0.6392021", "0.6385052", "0.6381544", "0.6380667", "0.63645804", "0.63514507", "0.63497907", "0.6341346", "0.63396055", "0.6321637", "0.6320431", "0.6317512", "0.63111657", "0.63098216", "0.6309245", "0.62954146", "0.62954146", "0.62954146" ]
0.67473537
1
Creates a new GetDecksResponse
def initialize(response) handle_errors(response) JSON.parse(response.body).each do |key, value| if key == 'decks' # Keep the API response count, it will differ when invalid decks are stripped @decks_count = value.size instance_variable_set( "@#{key}".to_sym, value.map { |deck| ZombieBattleground::Api::Models::Deck.new(deck) } ) else instance_variable_set("@#{key}".to_sym, value) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def response_factory(data)\n\t\t\t\t\t\treturn Response.new(data)\n\t\t\t\t\tend", "def create_response(request)\n response = Response.new\n end", "def initialize(response)\n handle_errors(response)\n\n @deck = ZombieBattleground::Api::Models::Deck.new(JSON.parse(response.body))\n end", "def stub_new_dataset\n deposition_id = rand.to_s[2..8].to_i\n simple = simple_body(deposition_id: deposition_id)\n stub_request(:post, 'https://sandbox.zenodo.org/api/deposit/depositions?access_token=ThisIsAFakeToken')\n .with(headers: { 'Content-Type' => 'application/json' })\n .to_return(status: 200,\n body: simple.merge(state: 'unsubmitted').to_json,\n headers: { 'Content-Type' => 'application/json' })\n [deposition_id, simple[:links][:bucket]]\n end", "def make_stock_card_deck\n self.stock_cards = StockCard.all\n end", "def respond(request_type='', options={})\n opts = {'apiKey' => @api_key, 'trackingId' => @tracking_id}\n options.each do |key, value|\n opts[key.to_s.camelize(:lower)] = value\n end\n\n# puts \"#{__FILE__}:#{__LINE__} [#{__method__}] #{opts.inspect}\"\n\n base_url = (@sandbox ? 'http://sandbox.api.shopping.com/publisher/3.0/rest' : 'http://publisher.usb.api.shopping.com/publisher/3.0/rest')\n target_url = \"#{base_url}/#{request_type}\"\n\n# puts \"#{__FILE__}:#{__LINE__} [#{__method__}] Target URL: #{target_url}\"\n\n response = HTTParty.get(target_url, :query=>opts)\n# puts \"#{__FILE__}:#{__LINE__} [#{__method__}] #{response.inspect}\"\n\n target_key = ''\n response.parsed_response.each_key do |key|\n# puts \"#{__FILE__}:#{__LINE__} [#{__method__}] KEY: #{key}\"\n target_key = key\n end\n\n # now we decide what kind of response object gets returned\n # invoke the correct constructor based on the value of target_key\n response_class = SDC.const_get(\"#{target_key}\")\n# puts \"#{__FILE__}:#{__LINE__} [#{__method__}] FOO: #{response_class.class.name}\"\n# puts \"#{__FILE__}:#{__LINE__} [#{__method__}] FOO: #{response_class.new(response)}\"\n\n\n response_class.new(response)\n end", "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 show\n @response = Response.new\n @responses = @ticket.responses\n end", "def request_get(token)\n url = \"https://api.spotify.com/v1/browse/new-releases?limit=2\"\n\n options = {\n headers: {\n \"Content-Type\": 'application/json',\n \"Accept\": 'application/json',\n \"Authorization\": \"Bearer #{token}\"\n }\n }\n\n return my_request = HTTParty.get(url, options)\nend", "def response(arguments = {})\n Response.new(self, arguments)\n end", "def response(url)\n space_fix_encoder = AssignFast::SpaceFixEncoder.new\n Faraday.get(url) do |req|\n req.options.params_encoder = space_fix_encoder\n req.headers['Accept'] = 'application/json'\n end\n end", "def create(options)\n API::request(:post, 'close_offering_requests', options)\n end", "def get(url, query = {})\n query[:format] ||= @format\n OEmbed::Response.create_for(raw(url, query), self, url, query[:format].to_s)\n end", "def stock_dividends_with_http_info(symbol, from, to, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: DefaultApi.stock_dividends ...'\n end\n # verify the required parameter 'symbol' is set\n if @api_client.config.client_side_validation && symbol.nil?\n fail ArgumentError, \"Missing the required parameter 'symbol' when calling DefaultApi.stock_dividends\"\n end\n # verify the required parameter 'from' is set\n if @api_client.config.client_side_validation && from.nil?\n fail ArgumentError, \"Missing the required parameter 'from' when calling DefaultApi.stock_dividends\"\n end\n # verify the required parameter 'to' is set\n if @api_client.config.client_side_validation && to.nil?\n fail ArgumentError, \"Missing the required parameter 'to' when calling DefaultApi.stock_dividends\"\n end\n # resource path\n local_var_path = '/stock/dividend'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'symbol'] = symbol\n query_params[:'from'] = from\n query_params[:'to'] = to\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[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<Dividends>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['api_key']\n\n new_options = opts.merge(\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(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: DefaultApi#stock_dividends\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_deck\r\n session[:deck] || Deck.new(:title => \"untitled deck\")\r\n end", "def create\n @deck = Deck.new_from_api\n\n respond_to do |format|\n if @deck.save\n format.html { redirect_to @deck, notice: 'Deck was successfully created.' }\n format.json { render :show, status: :created, location: @deck }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @deck.errors, status: :unprocessable_entity }\n end\n end\n end", "def initialize(data)\n @response = data\n @id = data[\"id\"]\n @name = data[\"name\"]\n @market = data[\"market\"]\n @alias = data[\"alias\"]\n @reference = data[\"reference\"]\n @efficiency = data[\"efficiency\"]\n @first_downs = data[\"first_downs\"]\n @interceptions = data[\"interceptions\"]\n @touchdowns = data[\"touchdowns\"]\n @possession_time = data.dig('summary', \"possession_time\")\n @avg_gain = data.dig('summary', \"avg_gain\")\n @safeties = data.dig('summary', \"safeties\")\n @turnovers = data.dig('summary', \"turnovers\")\n @play_count = data.dig('summary', \"play_count\")\n @rush_plays = data.dig('summary', \"rush_plays\")\n @total_yards = data.dig('summary', \"total_yards\")\n @lost_fumbles = data.dig('summary', \"lost_fumbles\")\n @penalty_yards = data.dig('summary', \"penalty_yards\")\n @return_yards = data.dig('summary', \"return_yards\")\n end", "def new\n @card = @deck.cards.new\n @decks = Deck.all(:order => 'title')\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @card }\n end\n end", "def index\n uri = URI(\"http://107.170.7.58:4567/api/department\")\n parameters = {\"ext\" => \"json\", \"count\" => \"1000\"}\n response = Net::HTTP.post_form(uri, parameters)\n\n list = JSON.parse(response.body)\n @departments = Array.new\n list.each do |department|\n @departments.push Department.new(department['data'])\n end\n\n page = params[:page]\n offset = page.to_s+\"0\"\n @prevPage = page.to_i-1\n @nextPage = page.to_i+1\n\n if params[:department]\n department = params[:department]\n @departmentName = @departments[department.to_i-1].name\n\n parameters = {\"ext\" => \"json\", \"count\" => \"10\", \"offset\" => offset, \"department_id\" => department}\n else\n parameters = {\"ext\" => \"json\", \"count\" => \"10\", \"offset\" => offset}\n end\n\n uri = URI(\"http://107.170.7.58:4567/api/sell\")\n response = Net::HTTP.post_form(uri, parameters)\n\n list = JSON.parse(response.body)\n\n @sells = Array.new\n @books = Array.new\n list.each do |listing|\n if listing[\"kind\"].eql? \"sell\"\n @sells.push Sell.new(listing[\"data\"])\n else if listing[\"kind\"].eql? \"book\"\n @books[listing[\"data\"][\"id\"]] = Edition.new(listing[\"data\"])\n end\n end\n end\n end", "def new\n @deck = Deck.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @deck }\n end\n end", "def new\n @deck = Deck.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @deck }\n end\n end", "def response\n @response ||= self.class.get(@events_url, @options)\n end", "def make_eds_response(data, params = nil)\n docs = eds_documents(data)\n params ||= {}\n options = { documents: docs, blacklight_config: blacklight_config }\n blacklight_config.response_model.new(data, params, options)\n end", "def empty_response\n rates = Rates.new([], [], [])\n ParsedEntries.new(\"\", \"\", \"\", \"\", [], rates, [])\n end", "def index\n @decks = current_user.decks\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @decks }\n end\n end", "def get(options = {})\n @response_xml = options[:cache_file] ? File.read(options[:cache_file]) : http_get(options)\n response = Response.parse(response_xml, options) do | inner_response, elements |\n parse_reports(inner_response, elements)\n end\n response.response_items.first # there is is only one\n end", "def show\n @item_response = Hash.new \n @item_response[:item] = Array.new \n\n temp_item = Hash.new\n temp_item[:title] = @item.title\n temp_item[:description] = @item.description\n temp_item[:price] = @item.price\n temp_item[:status] = @item.status\n unless @item.status.eql?('banned')\n temp_item[:published_date] = @item.published_date\n temp_item[:Seller_Name] = Seller.find(@item.seller_id).name\n end\n @item_response[:item] << temp_item\n \n render json: {response: @item_response, count: @item_response[:item].count }, status: :ok\n end", "def index\n @decks = Deck.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @decks }\n end\n end", "def index\n @decks = Deck.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @decks }\n end\n end", "def to_response\n []\n end" ]
[ "0.5612215", "0.5533734", "0.5371256", "0.52257246", "0.5163544", "0.515944", "0.51577", "0.5107998", "0.5074359", "0.50703037", "0.50401974", "0.50234216", "0.5021981", "0.4982436", "0.49554443", "0.49522188", "0.49125293", "0.49082685", "0.48954833", "0.4892001", "0.4892001", "0.48678428", "0.4851912", "0.4846921", "0.48399127", "0.48196232", "0.4814806", "0.48088458", "0.48088458", "0.4797934" ]
0.5753592
0
Validator for decks in decks
def decks_contains_valid_decks @decks.each do |deck| next if deck.is_a?(ZombieBattleground::Api::Models::Deck) && deck.valid? && deck.errors.size.zero? errors.add(:decks, 'decks must be an array of Deck') end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_invalid_decks\n @decks.select! do |deck|\n deck.is_a?(ZombieBattleground::Api::Models::Deck) &&\n deck.valid? &&\n deck.errors.size.zero?\n end\n end", "def decks_is_an_array_of_deck\n unless @decks.is_a?(Array)\n errors.add(:decks, 'Decks must be an array')\n return\n end\n\n if remove_invalid\n remove_invalid_decks\n else\n decks_contains_valid_decks\n end\n end", "def validate\n # valid if list of headers identical to list of drills and data items combined\n # except that there may be dummy units, algorithm columns\n headers.each do |header|\n if !(definition.drill.keys+definition.data.keys+['units','algorithm','default']).include?(header)\n raise \"Header missing from itemdef: #{header}, itemdef has: #{(definition.drill.keys+definition.data.keys+['units','algorithm','default']).join(',')}\"\n end\n end\n (definition.drill.keys+definition.data.keys+['units']).each do |key|\n raise \"Header missing from data table: #{key}\" if !headers.include?(key)\n end\n end", "def validate_empty\n if self.units.count > 0\n errors.add(:units, \"must not exist in order for a unit to be deleted\")\n throw(:abort)\n elsif self.collections.count > 0\n errors.add(:collections, \"must not exist in order for a unit to be deleted\")\n throw(:abort)\n end\n end", "def deck_is_a_deck\n return if @deck.is_a?(ZombieBattleground::Api::Models::Deck) &&\n @deck.valid? &&\n @deck.errors.size.zero?\n\n errors.add(:deck, 'deck must be a Deck')\n end", "def valid_sets; end", "def validate_suppliers!\n data.each do |supplier_name, config|\n REQUIRED_FIELDS.each do |field|\n result = config[field]\n raise MissingFieldError.new(supplier_name, field) if (result.nil? || result.to_s.empty?)\n end\n \n validate_workers!(supplier_name, config[\"workers\"])\n end\n end", "def valid?(set); end", "def validate!\n if identifier.to_s.empty?\n raise ValidationError.new(\"identifier is required\")\n else\n [image_changes.created,\n image_changes.updated,\n unit_changes.created,\n unit_changes.updated].each do |collection|\n collection.each(&:validate!)\n end\n\n true\n end\n end", "def validate_records\n have_enough_items_to_trade?\n end", "def has_invalid_items?\n unless @offer[:items].empty? || @offer[:items].select { |item_name|\n !Inventory.items_and_values.include?(item_name)}.empty?\n add_error(:offer, :items, \"There is an invalid item in the list\")\n error = true\n end\n unless @for[:items].empty? || @for[:items].select { |item_name|\n !Inventory.items_and_values.include?(item_name)}.empty?\n add_error(:for, :items, \"There is an invalid item in the list\")\n error = true\n end\n\n error ||= false\n end", "def validate!\n # Require that at least one field exist.\n if fields.length == 0\n raise SkyDB::Query::ValidationError.new(\"At least one selection field is required for #{self.inspect}.\")\n end\n\n fields.each do |field|\n field.validate!\n end\n\n groups.each do |group|\n group.validate!\n end\n end", "def validate_items\n not(empty_item_list? or has_invalid_items? ||\n has_different_point_values?) ? true : false\n end", "def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:vessel_code => self.vessel_code}],self)\n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_vessel\n\t end\nend", "def satisfied?\n self.enrollments.group_by(&:quarter).map do |quarter, enrollments|\n units = enrollments.map(&:units).reduce(:+)\n unless MIN_UNITS <= units and MAX_UNITS >= units\n self.errors << quarter.to_s.bold + \" has \" + units.to_s.bold.red + \" units!\"\n end\n end\n self.errors.empty?\n end", "def check_items_balances\n details.select(&:marked_for_destruction?)\n .all?(&:valid_for_destruction?)\n end", "def require_quantities\n \tunless self.dishes.count > 0\n \t\terrors.add(:order, \"must have dishes\")\n \tend\n end", "def valid?\n validate_survivors and validate_items && validate_records\n end", "def valid_input?(id_list)\n return false if id_list.empty?\n id_list.each do |id, quan|\n return false unless Product.where(\"id =?\", id).first\n return false if (quan.nil? || quan <=0)\n end\n end", "def cards_validation\n if cards.any?(&:invalid?)\n errors[:base] << 'Wallet has an invalid card'\n end\n end", "def validate_items\n [buyer_items, seller_items].each do |items|\n fail InvalidItemsError unless items.kind_of?(Enumerable)\n end\n end", "def validate( list )\n # reuse the highline lambda to santize input\n return true if (@allow_empty_list && list.nil?)\n list = highline_question_type.call( list ) if !list.is_a? Array\n return false if !list.is_a?(Array)\n return false if (!@allow_empty_list && list.empty? )\n list.each{ |item|\n return false if !validate_item( item )\n }\n true\n end", "def validate_item( x )\n fail 'not implemented!'\n end", "def validate_buried\n if buried\n if units.where.not(buried: true).count > 0\n errors.add(:base, \"This unit cannot be deleted, as it contains at \"\\\n \"least one child unit.\")\n throw(:abort)\n elsif collections.where.not(buried: true).count > 0\n errors.add(:base, \"This unit cannot be deleted, as it contains at \"\\\n \"least one collection.\")\n throw(:abort)\n end\n end\n end", "def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:pack_material_product_code => self.pack_material_product_code},{:id => self.id}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_pack_material_product\n\t end\nend", "def validate \n #\tfirst check whether combo fields have been selected\n is_valid = true\n if is_valid\n is_valid = ModelHelper::Validations.validate_combos([{:qc_test_id => self.qc_test_id}],self) \n end\n # #now check whether fk combos combine to form valid foreign keys\n # if is_valid\n # is_valid = set_qc_test\n # end\n # if is_valid\n # is_valid = ModelHelper::Validations.validate_combos([{:qc_inspection_type_code => self.qc_inspection_type_code}],self) \n # end\n # #now check whether fk combos combine to form valid foreign keys\n # if is_valid\n # is_valid = set_qc_inspection_type\n # end\n end", "def validate\n if self.line_item_problem_type.form_tag == 'wrong_dvd' && self.wrong_copy_id.nil?\n errors.add_to_base(\"Barcode number is required\")\n end\n end", "def valid?\n @errors << :title if [email protected]_a?(String) || @title.empty?\n @errors << :author if [email protected]_a?(String) || @author.empty?\n @errors << :release_date unless @release_date.is_a?(Date)\n @errors << :publisher if [email protected]_a?(String) || @publisher.empty?\n @errors << :isbn unless @isbn.is_a?(Integer) && @isbn < 10**10 && @isbn >= 10**9\n \n @errors.empty?\n end", "def valid_group(cards)\n puts validate(cards)\nend", "def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:commodity_code => self.commodity_code},{:rmt_variety_code => self.rmt_variety_code}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_rmt_variety\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:season_code => self.season_code},{:id => self.id}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_season\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend" ]
[ "0.6536624", "0.6467546", "0.6031117", "0.5980525", "0.57976454", "0.5779107", "0.57296395", "0.57295007", "0.5706486", "0.56935155", "0.56799835", "0.5678328", "0.56366324", "0.5572912", "0.553737", "0.55199265", "0.5515637", "0.5477121", "0.544545", "0.54299545", "0.5417221", "0.5416207", "0.541012", "0.5397859", "0.5390762", "0.53883183", "0.5386715", "0.53828675", "0.53794235", "0.53764737" ]
0.80109626
0
Removes invalid vards from deck
def remove_invalid_decks @decks.select! do |deck| deck.is_a?(ZombieBattleground::Api::Models::Deck) && deck.valid? && deck.errors.size.zero? end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_invalid_codes(guess)\n @valid_codes.filter! { |code| code.check_code(guess) == [@black_pegs, @white_pegs] }\n puts \"#{@valid_codes.count} possible codes left\"\n end", "def find_unseen\n unseen.replace(full_deck)\n (my_hand + op_hand + my_lands.values +\n op_lands.values + discards.values).flatten.each do |c|\n i = unseen.index(c) or next\n unseen.delete_at(i)\n end\n end", "def clean_bad_data\n self.character_achievements.select{|ca| ca.achievement }.group_by{|ca| ca.achievement.armory_id }.each{|aid, cas|\n if cas.size > 1\n cas[1,1000].each{|c| c.destroy }\n end\n }\n end", "def discard_and_replace(number = 1)\n number = faceup.count if number > faceup.count\n gamefield.slice(0, number).each_with_index do |card, i|\n card.faceup_position = nil\n card.facedown_position = nil\n return false unless card.save\n end\n gamefield.each do |card|\n card.faceup_position = card.faceup_position - number\n return false unless card.save\n end\n deal number\n end", "def prepare_deck\n (1..104).each do |i|\n v = [1, 2, 3, 5, 7]\n if i == 55\n @deck[i] = v[4]\n elsif (i % 11 == 0.0) && i != 55\n @deck[i] = v[3]\n elsif (i % 10 == 0.0) && i != 55\n @deck[i] = v[2]\n elsif (i % 5 == 0.0) && i != 55\n @deck[i] = v[1]\n else\n @deck[i] = v[0]\n end\n end\n end", "def reset_discard_pile(deck)\n @cards = []\n @cards << deck.take_card\n while @cards[0].color == 'Wild' || @cards[0].number.is_a?(String)\n deck.cards.unshift(@cards.pop)\n @cards << deck.take_card\n end\n @cards\n end", "def make_discards(player, list_of_allies, list_of_axis)\n complete_squads = player.player_hand.completes\n\n # We need to make sure that we don't make attacks with squadrons that have already been used\n complete_squads = player.remove_used_squads(complete_squads, list_of_allies, list_of_axis)\n end", "def discardHiddenTreasure(t)\n \n end", "def non_trump_cards\n @cards.select {|c| c.suit != @trump_suit}\n end", "def remove_card_from_deck (card)\n\t\t@deck -= [card]\n\tend", "def reset_unused!\n @cards += @used\n @used = []\n end", "def remove_cards\n\t\[email protected]!(0,2)\n\tend", "def remove_invalid_combs(board, hi, combs_pre)\n board_view = board_row_from_i(board, hi)\n r = combs_pre.select{ |c| validate_comb(board_view, c) }\n r\nend", "def undistinguished_vars\n @undistinguished ||= vars.vars.reject(&:distinguished?)\n end", "def available_cards(correct_card_ids)\n # Exclude cards that have already been successfully answered\n self.cards.reject do |card|\n puts \"correct_card_ids = #{correct_card_ids}\"\n correct_card_ids.include?(card.id)\n end\n end", "def clear_damage_values\n mrts_conditional_drops_clear_damage_values\n @element = 0\n end", "def scrubbed\n end", "def discardHiddenTreasures(t)\n \n t.each do |x|\n @currentPlayer.discardHiddenTreasure(x)\n @dealer.giveTreasureBack(x)\n \n end\n \n end", "def reshuffle\n discard.each do |modifier|\n deck.push modifier\n end\n @discard = []\n shuffle\n end", "def subtractSet(chosenCards)\n @cardsOnTable.each { |c|\n if c = chosenCards[0]\n @cardsOnTable.delete_at(0)\n elsif c = chosencards[1]\n @cardsOnTable.delete_at(1)\n elsif c = chosenCards[2]\n @cardsOnTable.delete_at(2)\n end\n }\n end", "def deal_a_card(from_the_deck)\n #delete any empty hashes from the deck array otherwise there will be an error because it will be picking a nil result\n if from_the_deck.include?({})\n from_the_deck.delete({})\n end\n \n deck_chosen_from = from_the_deck.sample\n key_chosen_from_deck = deck_chosen_from.keys.sample\n value_chosen_from_deck = deck_chosen_from[key_chosen_from_deck].sample\n \n remove_from_deck(deck_chosen_from, key_chosen_from_deck, value_chosen_from_deck)\n\n #delete any hash key with an empty array value otherwise there will be an error because it will be picking a nil result\n if deck_chosen_from[key_chosen_from_deck].empty?\n deck_chosen_from.delete(key_chosen_from_deck)\n end\n\n picked_card = [key_chosen_from_deck, value_chosen_from_deck]\nend", "def discard_bad_plates\n show do \n title \"Discard Plates\"\n \n discard_plate_ids = operations.select { |op| op.temporary[:delete] }.map { |op| op.input(\"Plate\").item.id }\n note \"Discard the following plates with 0 colonies: #{discard_plate_ids}\"\n end\n end", "def createDeck\n deck = []\n for suit in @@cardSuits\n for symbol in @@symbolVals.keys\n if symbol != \"AA\"\n deck << Card.new(symbol, suit)\n end\n end\n end\n\n return deck\n end", "def remove_cards_forAI(cardToRemove1, cardToRemove2, cardToRemove3)\n\t\[email protected](cardToRemove1)\n\t\[email protected](cardToRemove2)\n\t\[email protected](cardToRemove3)\n\tend", "def clean!\n time = Time.now\n \n instance_variables.select do |i|\n condition = false\n match = i.to_s.match(/\\A@exchange[^\\d]+\\d{4}_\\d{1,3}_?\\d{0,2}_(\\d{4})_(\\d{1,3})_?(\\d{1,2})?/)\n \n if match\n condition = match[1].to_i != time.year || match[2].to_i != time.yday\n condition = match[3].to_i != time.hour if match[3]\n end\n \n condition\n end.each do |i|\n remove_instance_variable i\n end\n end", "def discard_characters_for(player)\n player.characters.each do |c|\n self.discard_pile << c\n end\n end", "def summon_removal\n # remove all expired pets\n @pets.clone.each {|p| @pets.delete(p) if p.terminate}\n # remove all expired monsters\n @monsters.clone.each {|m| @monsters.delete(m) if m.terminate}\n end", "def convert_deck(arr_of_cards)\n arr_of_cards.each do |card|\n # Remove the \"Your Cards:\" from the first element\n if arr_of_cards.index(card) == 0\n card.slice!(0, 12)\n end\n end\n end", "def deal_card(deck,card_values)\n suites = deck.map {|k,v| k}\n suite_choice = suites[rand(0..3)]\n value = card_values[rand(0..12)]\n value_index = card_values.index(value)\n while deck[suite_choice].values_at(value_index).count(TAKEN_MARKER) == 1\n\n suite_choice = suites[rand(0..3)]\n value_index = card_values[rand(0..12)]\n end\n deck[suite_choice][value_index] = TAKEN_MARKER\n\n deck[suite_choice][value_index] = TAKEN_MARKER\nend", "def discardHiddenTreasure(t)\n @hiddenTreasures.delete(t)\n if (@pendingBadConsequence != nil) and [email protected]\n @pendingBadConsequence.substractHiddenTreasure(t)\n end\n dieIfNoTreasures\n \n end" ]
[ "0.61292017", "0.6067254", "0.60121524", "0.5808344", "0.5545818", "0.5521131", "0.5516175", "0.55056226", "0.5500904", "0.5476033", "0.54756474", "0.5460172", "0.5446137", "0.5412514", "0.5403982", "0.53832686", "0.53735137", "0.5367933", "0.5349089", "0.5344778", "0.5327373", "0.53034514", "0.52923447", "0.5279193", "0.52710164", "0.52578425", "0.5248851", "0.5247276", "0.52412474", "0.52411807" ]
0.6802469
0
Mock a crappy remote API call that could toss an exception on some upstream error. It also mocks a return value of ':pending' when it's not complete and returns ':happy' when it's complete.
def crappy_api_call $count += 1 # First two calls fail raise "OH SNAP" if $count < 3 # Next few calls say pending return :pending if $count < 5 # Then finally done return :happy end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_WAPI_do_request_rest_client_error_417\n\n\n stub_request(:get, \"https://start/hey\").\n with(:headers => {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip, deflate', 'Authorization' => 'Bearer sweet!'}).\n to_return(:status => 417, :body => \"\", :headers => {})\n\n a = Hash['api_prefix' => \"https://start\",\n 'key' => 'key',\n 'secret' => 'secret',\n 'token_server' => 'nowhere.edu',\n 'token' => 'sweet!'\n ]\n h = WAPI.new(a);\n\n r = h.do_request(\"/hey\")\n\n assert_equal(r.meta_status, 666, \"didn't get wrapped exception\")\n\n end", "def test_no_retry_with_mismatched_error\n call_count = 0\n client_stub = make_client_stub\n\n make_request_proc = lambda do |args|\n call_count += 1\n raise FakeFaradayError.new(GRPC::Core::StatusCodes::INTERNAL)\n end\n \n options = Gapic::CallOptions.new(\n retry_policy: { retry_codes: [GRPC::Core::StatusCodes::UNAVAILABLE] }\n )\n\n client_stub.stub :base_make_http_request, make_request_proc do\n ex = assert_raises Gapic::Rest::Error do\n client_stub.make_get_request uri: \"/foo\", options: options\n end\n\n refute_nil ex.cause\n assert_kind_of FakeFaradayError, ex.cause\n assert_equal GRPC::Core::StatusCodes::INTERNAL, ex.cause.grpc_code\n end\n assert_equal 1, call_count\n end", "def test_retries_then_raises_unexpected_exception\n client_stub = make_client_stub\n\n call_count = 0\n make_request_proc = lambda do |args|\n call_count += 1\n raise RuntimeError if call_count == 3\n raise FakeFaradayError.new(GRPC::Core::StatusCodes::UNAVAILABLE)\n end\n\n sleep_proc = ->(count) { }\n\n options = Gapic::CallOptions.new(\n timeout: 1,\n retry_policy: {\n retry_codes: [GRPC::Core::StatusCodes::UNAVAILABLE], \n }\n )\n\n Kernel.stub :sleep, sleep_proc do\n client_stub.stub :base_make_http_request, make_request_proc do\n ex = assert_raises RuntimeError do\n client_stub.make_get_request uri: \"/foo\", options: options\n end\n end\n end\n\n assert_equal 3, call_count\n end", "def test_get_request_error_417\n\n stub_request(:get, \"https://start/hey\").\n with(:headers => {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip, deflate', 'Authorization' => 'Bearer sweet!'}).\n to_return(:status => 417, :body => \"\", :headers => {})\n\n a = Hash['api_prefix' => \"https://start\",\n 'key' => 'key',\n 'secret' => 'secret',\n 'token_server' => 'nowhere.edu',\n 'token' => 'sweet!'\n ]\n h = WAPI.new(a);\n\n r = h.get_request(\"/hey\")\n\n assert_equal(r.meta_status, 666, \"didn't get wrapped exception\")\n exp = r.result\n assert_equal(exp.http_code, 417, \"got incorrect wrapped exception\")\n\n end", "def stub_coin_market_cap_success_call_service\n \tlist_response = File.read('test/fixtures/api_responses/coin_market_cap_success.json')\n json_response = JSON.parse(list_response)\n json_response.stubs(:code).returns(200)\n CoinMarketCap.stubs(:call_service).returns(json_response)\n end", "def test_times_outs\n client_stub = make_client_stub\n to_attempt = 5\n time_delay = 60\n\n call_count = 0\n make_request_proc = lambda do |args|\n call_count += 1\n raise FakeFaradayError.new(GRPC::Core::StatusCodes::UNAVAILABLE)\n end\n\n time_now = 1\n time_proc = ->(_) do\n time_now += time_delay\n end\n\n # Default delay and multiplier are 1 and 1.3\n # The number of expects here is `to_attempt-1`, spelt out for visibility\n sleep_mock = Minitest::Mock.new\n sleep_mock.expect :sleep, nil, [1]\n sleep_mock.expect :sleep, nil, [1 * 1.3]\n sleep_mock.expect :sleep, nil, [1 * 1.3 * 1.3]\n sleep_mock.expect :sleep, nil, [1 * 1.3 * 1.3 * 1.3]\n sleep_proc = ->(count) { sleep_mock.sleep count }\n\n options = Gapic::CallOptions.new(\n timeout: time_delay * to_attempt + 0.1, # `+0.1` means that timeout stays positive on last cycle \n retry_policy: {\n retry_codes: [GRPC::Core::StatusCodes::UNAVAILABLE], \n }\n )\n\n Kernel.stub :sleep, sleep_proc do\n ::Process.stub :clock_gettime, time_proc do\n client_stub.stub :base_make_http_request, make_request_proc do\n ex = assert_raises ::Gapic::Rest::Error do\n client_stub.make_get_request uri: \"/foo\", options: options\n end\n\n refute_nil ex.cause\n assert_kind_of FakeFaradayError, ex.cause\n\n # Note that this is not a DEADLINE_EXCEEDED\n # Our fake never throws ::Faraday::TimeoutError so the error gets wrapped as is.\n # This mirrors the gRPC test\n assert_equal GRPC::Core::StatusCodes::UNAVAILABLE, ex.cause.grpc_code\n end\n end\n end\n\n assert_equal to_attempt, call_count\n sleep_mock.verify\n end", "def test_no_retry_without_codes\n call_count = 0\n client_stub = make_client_stub\n\n make_request_proc = lambda do |args|\n call_count += 1\n raise FakeFaradayError.new(GRPC::Core::StatusCodes::INTERNAL)\n end\n\n options = Gapic::CallOptions.new # no codes\n client_stub.stub :base_make_http_request, make_request_proc do\n ex = assert_raises Gapic::Rest::Error do\n client_stub.make_get_request uri: \"/foo\", options: options\n end\n\n refute_nil ex.cause\n assert_kind_of FakeFaradayError, ex.cause\n assert_equal GRPC::Core::StatusCodes::INTERNAL, ex.cause.grpc_code\n end\n\n assert_equal 1, call_count\n end", "def test_errors_from_handled_requests_are_noticed\n desc = basic_grpc_desc\n def desc.trace_with_newrelic?; true; end # force a true response from this method\n def desc.process_distributed_tracing_headers(ac); end # noop this DT method (tested elsewhere)\n def desc.metadata_for_call(call); NewRelic::EMPTY_HASH; end # canned. test metadata_for_call elsewhere\n raised_error = RuntimeError.new\n new_transaction_called = false\n NewRelic::Agent::Transaction.stub(:start_new_transaction, proc { new_transaction_called = true; transaction }) do\n received_error = nil\n notice_stub = proc { |e| received_error = e }\n NewRelic::Agent.stub(:notice_error, notice_stub) do\n assert_raises(RuntimeError) do\n result = desc.handle_with_tracing(nil, nil, method, nil) { raise raised_error }\n end\n\n assert_equal raised_error, received_error\n assert new_transaction_called\n end\n end\n end", "def stub_http_start_with_good_01_response()\n Net::HTTP.stub(:start, method(:http_start_stub_good_01)) do\n yield()\n end # Net::HTTP.stub(:start)\n end", "def test_should_handle_retry_by_status_code\n error = proc { raise Google::Cloud::Error, 'something bad happened' }\n @fire_cloud_client.stub :get_workspace_bucket, error do\n # should only retry once\n forbidden_mock = Minitest::Mock.new\n status = 403\n forbidden_mock.expect :status_code, status\n forbidden_mock.expect :nil?, false\n 3.times do\n forbidden_mock.expect :==, false, [Integer] # will check against 502..504\n end\n @fire_cloud_client.stub :extract_status_code, forbidden_mock do\n assert_raise RuntimeError do\n @fire_cloud_client.execute_gcloud_method(:get_workspace_file, 0, 'foo', 'bar.txt')\n forbidden_mock.verify\n end\n end\n # test with 502 should cause retry cascade\n status = 502\n bad_gateway_mock = Minitest::Mock.new\n 6.times do # 6 is for 5 total requests and then 6th iteration that terminates retry loop\n bad_gateway_mock.expect :status_code, status\n bad_gateway_mock.expect :nil?, false\n bad_gateway_mock.expect :==, true, [status]\n end\n @fire_cloud_client.stub :extract_status_code, bad_gateway_mock do\n assert_raise RuntimeError do\n @fire_cloud_client.execute_gcloud_method(:get_workspace_file, 0, 'foo', 'bar.txt')\n bad_gateway_mock.verify\n end\n end\n end\n end", "def test_doesnt_propagate_errors_in_instrumentation\n NewRelic::Agent::CrossAppTracing.stubs( :start_trace ).\n raises( StandardError, \"something bad happened\" )\n\n res = Curl::Easy.http_get( default_url )\n\n assert_kind_of Curl::Easy, res\n end", "def mock_faraday_error(status_code)\n mocked_error_class = if (500..599).include?(status_code) && Faraday::VERSION.to_f >= 16.0\n Faraday::ServerError\n else\n Faraday::ClientError\n end\n\n ::Faraday::Connection.any_instance.stubs(:get).\n raises(mocked_error_class.new(nil, { status: status_code}))\n end", "def test_status_green_on_502\n Excon.stub({method: :get}, {body: '<doctype', status: 502})\n\n authorize 'user', 'password'\n assert_output( /502 override/,'') { get '/status' }\n last_response.body.must_equal 'green'\n end", "def stub_message_fail\n @response_fail = File.open(File.join('fixtures', 'astros-fail.json'), 'r').read\n stub_request(:get, /api.open-notify.org\\/astros.json/).to_return(:body => @response_fail, :status => 200, :headers => {'Content-Type'=>'application/json'})\nend", "def mock_undetermined_vehicle_compliance\n allow(ComplianceCheckerApi).to receive(:vehicle_compliance)\n .and_raise(BaseApi::Error422Exception.new(422, '', {}))\n end", "def fake_a_broken_uri(uri)\n stub_request(:get, uri).to_return(body: \"Oopsies\")\nend", "def test_json_parser_error\n Excon.stub({method: :get}, {body: '<doctype', status: 200})\n\n authorize 'user', 'password'\n assert_output( /JSON::ParserError/,'') { get '/status' }\n last_response.body.must_equal 'green'\n end", "def mock_success\n head :ok\n end", "def test_WAPI_do_request_unauthorized\n\n stub_request(:get, \"https://start/hey\").\n with(:headers => {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip, deflate', 'Authorization' => 'Bearer sweet!'}).\n to_return(:status => 401, :body => \"unauthorized\", :headers => {})\n\n a = Hash['api_prefix' => \"https://start\",\n 'key' => 'key',\n 'secret' => 'secret',\n 'token_server' => 'nowhere.edu',\n 'token' => 'sweet!'\n ]\n h = WAPI.new(a);\n\n r = h.do_request(\"/hey\")\n logger.info \"tWdou: #{__LINE__}: r: \"+r.inspect\n\n assert_equal(r.meta_status, 666, \"didn't get wrapped exception\")\n\n exp = r.result\n assert_equal(exp.http_code, 401, \"didn't catch unauthorized in do_request\")\n\n end", "def work()\n # FIXME : .rel[...].get doesn't update $client.rate_limit...\n\n rate_limit = $client.rate_limit\n dbgp \"#{rate_limit.remaining} API calls left.\"\n\n # A little buffer in case we use a feature from octokit\n # which doesn't update rate_limit on `$client`.\n if rate_limit.remaining < 5 then\n reset = rate_limit.resets_in + 10\n puts \"💤 zleepy timez (back in #{reset} seconds)\"\n sleep(reset)\n end\n\n begin\n yield\n rescue Octokit::BadGateway, Octokit::InternalServerError => e\n puts \"Uuuh... github is having a bad time :( #{e.response_status}\"\n pp \"=====\"\n pp \"=====\"\n pp e.response_body\n pp \"=====\"\n pp e.response_headers\n pp \"=====\"\n pp \"=====\"\n sleep 10\n retry\n end\nend", "def mock_check_barcode_request(barcode, status_code)\n if status_code == '404'\n stub_request(:get, \"#{ENV.fetch('PATRON_MICROSERVICE_URL_V01', nil)}?barcode=\" + barcode)\n .to_return(status: 404, body: {\n \"message\" => \"Failed to retrieve patron record by barcode\",\n \"statusCode\" => 404\n }\n .to_json, headers: { 'Content-Type' => 'application/json' })\n return\n end\n\n if status_code == '409'\n stub_request(:get, \"#{ENV.fetch('PATRON_MICROSERVICE_URL_V01', nil)}?barcode=\" + barcode)\n .to_return(status: 409, body: {\n \"message\" => \"Multiple patron records found\",\n \"statusCode\" => 409\n }\n .to_json, headers: { 'Content-Type' => 'application/json' })\n return\n end\n\n if status_code == '500'\n stub_request(:get, \"#{ENV.fetch('PATRON_MICROSERVICE_URL_V01', nil)}?barcode=\" + barcode)\n .to_return(status: 500, body: {\n \"message\" => \"Server error\",\n \"statusCode\" => 500\n }\n .to_json, headers: { 'Content-Type' => 'application/json' })\n return\n end\n\n # return a successful 200 \"single unique user found\" response\n stub_request(:get, \"#{ENV.fetch('PATRON_MICROSERVICE_URL_V01', nil)}?barcode=\" + barcode)\n .to_return(status: 200,\n body: SIERRA_USER.to_json,\n headers: { 'Content-Type' => 'application/json' })\n end", "def status_test_result_running_request\n stub_request(:get, \"http://www.webpagetest.org/testStatus.php?f=json&test=#{OTHER_TEST_ID}\").\n with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Faraday v0.8.8'}).\n to_return(:status => 200, :headers => {}, :body => test_running_response(OTHER_TEST_ID).to_json)\n end", "def __proxied_call(**args)\n error = catch(:verbalize_error) do\n value = perform(**args)\n return Success.new(value)\n end\n\n Failure.new(error)\n end", "def test_status_green_on_empty\n Excon.stub({method: :get}, {body: '', status: 200})\n\n authorize 'user', 'password'\n assert_output( /status=200/,'') { get '/status' }\n last_response.body.must_equal 'green'\n end", "def status_test_result_completed_request\n stub_request(:get, \"http://www.webpagetest.org/testStatus.php?f=json&test=#{OTHER_TEST_ID}\").\n with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Faraday v0.8.8'}).\n to_return(:status => 200, :headers => {}, :body => test_completed_response(OTHER_TEST_ID).to_json)\n end", "def test_email_client_secondary_success_only\n MailgunClient.stubs(:send_email).returns(bad_req_code)\n SendgridClient.stubs(:send_email).returns(ok_code)\n\n input_val = EmailObject.new\n response = ClientResponse.new input_val\n response.set_ok\n\n assert_equal response, EmailClient.send_email(input_val)\n end", "def raises_upon_errored_playbook\n expect(Ansible::Runner).to receive(:run).and_return(response_bad)\n expect { yield }.to raise_error(MiqException::Error)\nend", "def mock_send_request_to_patron_creator_service\n stub_request(:post, ENV.fetch('PATRON_MICROSERVICE_URL_V02', nil))\n .to_return(\n {\n status: 201,\n body: {\n 'status' => 'success'\n }.to_json,\n headers: {}\n },\n {\n status: 500,\n body: {\n 'status' => 'failure'\n }.to_json, headers: {}\n }\n )\n end", "def check_github_response\n Retriable.retriable(retry_options) do\n yield\n end\n rescue MovedPermanentlyError => e\n fail_with_message(e, \"The repository has moved, update your configuration\")\n rescue Octokit::Forbidden => e\n fail_with_message(e, \"Exceeded retry limit\")\n rescue Octokit::Unauthorized => e\n fail_with_message(e, \"Error: wrong GitHub token\")\n end", "def test_that_it_raises_an_api_error_if_ng_status_is_returned\n not_exist_user_id = 'NOT_EXSIT_USER'\n res_body = load_test_data 'error_404_not_found.json'\n url = \"#{HOST}/users/#{not_exist_user_id}\"\n add_stub_request :get, url, res_body: res_body, res_status: 404\n\n proc_404_error = proc do\n @client.user not_exist_user_id\n end\n assert_404_error proc_404_error\n end" ]
[ "0.6178254", "0.6141393", "0.60216916", "0.59456843", "0.5910256", "0.5890731", "0.5865106", "0.58541054", "0.5812357", "0.57681704", "0.57539564", "0.57478607", "0.57234883", "0.57191676", "0.56989217", "0.56568074", "0.56478715", "0.56476104", "0.5606398", "0.55973184", "0.5580324", "0.5564777", "0.5517927", "0.5506444", "0.5474862", "0.5443437", "0.54322463", "0.54181176", "0.5375391", "0.53753257" ]
0.67977315
0
Open the bookmarks and return an REXML::Document. If the cache option is provided, the document is loaded from the localpath specified.
def open require 'rexml/document' xml = if cache && File.exist?(cache) File.read(cache) else request :all end File.open(cache, 'wb') { |io| io.write(xml) } if cache REXML::Document.new(xml) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def open(path)\n document = parse(File.read(path))\n document.path = path\n document\n end", "def get_html\n print \"Getting doc...\"\n if File.size?(@cache)\n html = File.read(@cache)\n else\n html = open(URL).read\n IO.write(@cache, html)\n end\n puts \"done.\"\n html\n end", "def sdmx_doc(cache, url=ECB_ALL_RATES_URL)\n rates_source = !!cache ? cache : url\n Nokogiri::XML(open(rates_source))\n end", "def open_document\n @document = Nokogiri::XML(open(@feed_uri).read)\n end", "def parse(cache)\n raise ParserException, \"No HTML document found\" if\n cache.assets[:documents].empty?\n # TODO: limited to a single document only\n raise ParserException, \"More than one HTML document found, this is not supported (yet)\" if\n cache.assets[:documents].size > 1\n \n @cache = cache\n @document = @cache.assets[:documents][0]\n log.debug \"-- Parsing #{@document}\"\n @doc = Nokogiri::HTML.parse(IO.read(File.join(@cache.path, @document)), nil, 'UTF-8')\n \n @uid = @cache.name\n parse_title\n parse_toc\n self\n end", "def load_bookmarks\n if File.exist? File.expand_path(\"~/Dropbox/test.txt\")\n return YAML.load_stream(open(File.expand_path(\"~/Dropbox/test.txt\"))).documents \n else\n puts \"Add: ./dl.rb url\"\n puts \"Get: ./dl.rb tagname\"\n return open(File.expand_path(\"~/Dropbox/test.txt\"), \"w\")\n end\nend", "def get_file_doc(prptfile, filename)\n Zip::ZipFile.open(prptfile, Zip::ZipFile::CREATE) do |zipfile|\n return REXML::Document.new zipfile.read(filename)\n end\nend", "def get_content_as_dom()\n if @state == RedXmlResource::STATE_LAZY\n @document = @doc_service.find_document(@doc_name)\n @state = RedXmlResource::STATE_LOADED\n end\n return @document\n end", "def load_xml_document file_name\n xml_file = File.new file_name, \"r\"\n return Document.new xml_file\n end", "def get_document(depth: nil, pierce: nil)\n {\n method: \"DOM.getDocument\",\n params: { depth: depth, pierce: pierce }.compact\n }\n end", "def doc(path, options = {})\n require 'nokogiri'\n\n File.open(path) do |f|\n yield Nokogiri::XML(f)\n end\n end", "def moddify_document(path)\n doc = nil\n File.open(path,'r+') do | file|\n xml_string = file.read\n doc = process_xml(xml_string) if valid_xml?(xml_string)\n end\n doc\nend", "def load_document(url, filters = {})\n html = load_html(url, filters)\n ProxyFetcher::Document.parse(html)\n end", "def read_cache\n @html = File.read(@cache_file) if cache_exist?\n parse_html unless @html.nil?\n end", "def sitemap_doc\n return doc if doc && !gzip?\n\n begin\n @sitemap_doc ||= Nokogiri::XML::Document.parse(unzipped_body, @url.to_s, content_charset)\n rescue\n end\n end", "def open(id, rev = nil)\n begin\n unless Colonel.config.rugged_backend.nil?\n repo = Rugged::Repository.bare(File.join(Colonel.config.storage_path, id), backend: Colonel.config.rugged_backend)\n else\n repo = Rugged::Repository.bare(File.join(Colonel.config.storage_path, id))\n end\n rescue Rugged::OSError\n return nil\n end\n\n Document.new(nil, id: id, repo: repo, type: self)\n end", "def doc\n @doc ||= Nokogiri::HTML(open(self.url))\n end", "def initialize_file_based_cache\n Dir.mkdir(\"cache\")\n @document_cache = ActiveSupport::Cache::FileStore.new(\"cache\")\n @file_based_cache = true\n end", "def new_document(content, opts = {})\n RetrievalLite::Document.new(content, opts)\n end", "def get_document_bookmarks(request)\n data, _status_code, _headers = get_document_bookmarks_with_http_info(request)\n request_token if _status_code == 401\n data\n end", "def open_uri(*args, &blk)\n OpenURI::DbCache::Page.fetch(*args, &blk)\n end", "def create_doc(path)\n doc = File.read(path)\n @current_xml_document = doc\n Hpricot.XML(doc)\n end", "def load_doc(path)\n page = HTTParty.get(path)\n \n Nokogiri::HTML(page)\nend", "def cache_open(url)\n Cachy.cache(url, hash_key: true) { open(url).read }\nend", "def as_xml_document(remove_stylesheets = false) \n # pulling this in instead of calling fro it from the file store everytime we need it\n data = current_data\n data = data.gsub(/\\<\\?xml\\-stylesheet.*\\?\\>/,'') if remove_stylesheets\n data ? REXML::Document.new(data) : nil\n end", "def load_html\n file = @local_source + @url.sub(@host, '')\n if (@url != @host) && !@local_source.nil? && File.exists?(file)\n f = File.open(file)\n @doc = Nokogiri::XML(f)\n f.close\n else\n html = Flatfish::Url.open_url(@url)\n @doc = Nokogiri::HTML(html)\n end\n end", "def read(document=section)\n @downloader.read(\n document: document,\n origin: origin_for(document)\n )\n end", "def load_document(id)\n cached = cache && id.is_a?(String) && cache[id]\n if cache\n if cached\n ActiveSupport::Notifications.instrument('couch_potato.load.cached') do\n cached\n end\n else\n cache[id] = load_document_without_caching(id)\n cache[id]\n end\n else\n load_document_without_caching(id)\n end\n end", "def downloads\n @downloads ||= DocumentDownloads.new(self)\n end", "def read_cache\n @cache_file = select_cache_file\n begin\n\topen(@cache_file, \"rb\") { |f| load_local_cache(f) } || {}\n rescue StandardError => ex\n\t{}\n end\n end" ]
[ "0.5680514", "0.55620104", "0.54649127", "0.54545224", "0.5450304", "0.5341162", "0.5259545", "0.5218658", "0.5166951", "0.5152344", "0.51081336", "0.50645673", "0.50215924", "0.499534", "0.49784198", "0.49608606", "0.4945149", "0.49401587", "0.49323162", "0.49273184", "0.4921945", "0.48802957", "0.4795255", "0.47935385", "0.478112", "0.47409216", "0.47292516", "0.4715568", "0.4710571", "0.47102362" ]
0.72416097
0
Determine if any bookmarks have been updated since the time specified.
def updated_since?(time) time < last_updated_at end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stale?(time = Time.now)\n updated_at < time\n end", "def has_beeen_updated_recently?( update_time )\n now = Time.now.utc\n ( (! update_time.nil?) && (update_time.year == now.year) && (update_time.month == now.month) && (update_time.day == now.day) &&\n (update_time.hour == now.hour) && (update_time.min == now.min) && ((now.sec - update_time.sec).abs < 7) )\n end", "def updates_since? last_update\r\n return true unless self.updated_since(last_update).blank?\r\n return true unless self.problems.updated_since(last_update).blank?\r\n false\r\n end", "def fresh_at?(time)\n time >= updated_at\n end", "def content_changed_since?(last_updated)\n stale?(:last_modified => last_updated)\n end", "def changed_since_publication?\n return true unless on_flickr?\n\n last_updated > published_at + 1.second\n end", "def stale?\n updated_at < 2.weeks.ago || json == '{}'\n end", "def has_changed?\n updated_at > 8.hours.ago\n end", "def movies_stale?\n Time.new - self.movies.last.updated_at >= 900\n end", "def contact_info_updated_since(t)\n return false if sdb_update_at.nil?\n t < sdb_update_at\n end", "def stale?\n updated_at < 2.hours.ago\n end", "def modified_since?( time )\n mtime > time\n end", "def has_played_since_last_update?\n @front_page = get_page(bungie_net_front_page_url)\n last_played = (@front_page/\"div.spotlight div \").inner_html.split(\"&nbsp; | &nbsp;\")[1].gsub(\"Last Played \", \"\").to_date\n return last_played > self.updated_at.to_date\n end", "def outdated?\n (Time.now - self.time_of_last_ok) > threshold_for_oldest_ok\n end", "def stale?\n (last_updated_at || Time.at(0)) < 5.minutes.ago\n end", "def gets_updated?\n for p in all_periods\n return true if p.keep_updated?\n end\n return false\n end", "def stale?\n unlocked? and item.has_attribute?(:updated_at) and updated_at < item.updated_at\n end", "def isDataUpToDate?\n DailyNews.first.updated_at.to_s.slice(5..6).eql? Time.now.to_s.slice(8..9)\n end", "def stale?\n forecasts.empty? || (Time.now - data_file.mtime) > 14_400\n end", "def any_updates?\n change_history.size > 1\n end", "def any_updates?\n change_history.size > 1\n end", "def fresh_by_time?\n return false unless env.key?(IF_MODIFIED_SINCE) && !last_modified.nil?\n Time.parse(last_modified) <= Time.parse(env.fetch(IF_MODIFIED_SINCE))\n end", "def is_stale?\n frequency = dispatchable.frequency.name\n created_at < time_for_interval(frequency)\n end", "def up_to_date_for?(timestamp)\n keys.sort.last >= timestamp\n end", "def stale?\n @stale ||= Time.now.to_i - timestamp.to_i > MaximumAge\n end", "def up_to_date?\n lu = latest_stored_update\n\n if !lu && !@prev_latest_update\n # They match if both nil\n true\n elsif lu && @prev_latest_update && (lu - @prev_latest_update).abs < 2\n # Consider them a match if they are within 2 seconds of one another,\n # accounting for the difference between Rails and DB times\n true\n elsif @prev_latest_update.nil?\n # The remembered value was nil, so let the caller know this\n self.prev_latest_update = lu\n nil\n else\n # There was no match\n self.prev_latest_update = lu\n false\n end\n end", "def updated?\n !ignore? && !removed? && mtime != File.mtime(path)\n end", "def need_update?\n return true unless @lastread\n @lastread < File::stat(@path).mtime\n end", "def updated\n watchers.find_all(&:updated?)\n end", "def stale?\n if config.cache.is_a?(Proc)\n proc_timestamp != mem_timestamp\n else\n file_timestamp != mem_timestamp\n end\n end" ]
[ "0.70125854", "0.6957735", "0.68587834", "0.685865", "0.6844506", "0.6724337", "0.6705332", "0.6684811", "0.6628862", "0.6596946", "0.6590277", "0.653508", "0.6528973", "0.6457132", "0.6413472", "0.6410814", "0.6402752", "0.63746107", "0.6356492", "0.6343933", "0.6343933", "0.63326395", "0.6316552", "0.62589824", "0.6256015", "0.62278134", "0.62240934", "0.6224039", "0.619349", "0.616603" ]
0.741279
0
Yield each bookmark to the block that requires synchronization. The :since option may be specified to indicate the time of the most recently updated bookmark. Only bookmarks whose time is more recent than the time specified are yielded.
def synchronize(options={}) if since = options[:since] since.utc return false unless updated_since?(since) else since = Time.at(0) since.utc end open.elements.each('posts/post') do |el| attributes = el.attributes time = Time.iso8601(attributes['time']) next if time <= since yield :href => attributes['href'], :hash => attributes['hash'], :description => attributes['description'], :extended => attributes['extended'], :time => time, :shared => (attributes['shared'] != 'no'), :tags => attributes['tag'].split(' ') end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bookmark_query(q,&blk)\n response = query(q)\n bookmark = response[\"bookmark\"]\n docs = response[\"docs\"]\n\n until !docs || docs.empty?\n yield docs\n q[\"bookmark\"] = bookmark\n response = query(q)\n bookmark = response[\"bookmark\"]\n docs = response[\"docs\"]\n end\n\n docs\n end", "def index\n bookmarks_loader(Time.now, current_user.id) \n bookmark = @bookmarks.first\n if bookmark\n session[:first_link_time] = bookmark.updated_at \n end \n bookmark = @bookmarks.last\n if bookmark\n session[:last_link_time] = bookmark.updated_at\n end \n end", "def listsinceblock(hash)\n @api.request 'listsinceblock', hash\n end", "def timeline\n\t\t\t\tbookmarks_loader(Time.now, doorkeeper_token.resource_owner_id) \n\t\t\t\tbookmarks_formatter\t\t\t\t\n\t\t\tend", "def bookmarkaby ( options = {}, &block )\n bb = BookmarkBuilder.new( self, options )\n yield bb\n concat_with_or_without_binding( bb.to_html, block.binding ) if bb.bookmarks?\n end", "def lock_changes\n begin\n @lock_count += 1\n yield\n ensure\n @lock_count -= 1\n end\n end", "def block(from_id, to_id, scope = Amico.default_scope_key)\n return if from_id == to_id\n\n Amico.redis.multi do\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.following_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.following_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.followers_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.followers_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zadd(\"#{Amico.namespace}:#{Amico.blocked_key}:#{scope}:#{from_id}\", Time.now.to_i, to_id)\n Amico.redis.zadd(\"#{Amico.namespace}:#{Amico.blocked_by_key}:#{scope}:#{to_id}\", Time.now.to_i, from_id)\n end\n end", "def loadmore\n bookmarks_loader(session[:last_link_time], current_user.id)\n bookmark = @bookmarks.last\n if bookmark\n session[:last_link_time] = bookmark.updated_at \n end \n end", "def each(&block)\n @lock.synchronize do\n @links.each(&block)\n end\n end", "def bookmarks(user)\n user = Access::Validate.user(user, false)\n Bookmark\n .where('(bookmarks.creator_id = ? OR bookmarks.updater_id = ?)', user.id, user.id)\n .order('bookmarks.updated_at DESC')\n end", "def watch\n loop { (yield @journal.current_entry while @journal.move_next) if @journal.wait(100_000) }\n end", "def delete_unmarked_entries(&block)\n deleted_ids = []\n # First remove the entry from the hash table.\n @entries_by_id.delete_if do |id, e|\n if e[MARKED] == 0\n yield(id) if block_given?\n deleted_ids << id\n true\n else\n false\n end\n end\n # Then delete the entry itself.\n @entries.delete_if { |e| e[MARKED] == 0 }\n write_index\n\n deleted_ids\n end", "def each(uri = nil, &block) # :yield: cookie\n # if uri\n # ...\n # else\n # synchronize {\n # ...\n # }\n # end\n # self\n end", "def each(&block)\n max_id = nil\n\n 100.times do\n tweets = tweets_before(max_id)\n break if tweets.empty?\n\n tweets.each(&block) if block_given?\n\n max_id = tweets.map { |tweet| tweet['id'] }.min - 1 # Don't fetch the same tweet again\n end\n end", "def lock_for_update(name=nil)\n if locked_for_update?(name)\n logger.debug { \"we are locked for update, yield to the block\" }\n yield\n else\n zk_with_lock(:mode => :exclusive, :name => name) { yield }\n end\n end", "def bookmark_time\n @ole.BookmarkTime\n end", "def block_and_forth_forever(&block)\nend", "def block_and_forth_forever(&block)\nend", "def block_and_forth_forever(&block)\nend", "def each(&_block)\n iterator = BlockIterator.new(self)\n\n until iterator.current_hash == Block::GENESIS_PREV_HASH\n block = iterator.next\n yield(block)\n end\n end", "def bookmarks\n\t\toptions = { list: true }\n\t\tresponse = self.server.run_with_json_template( :bookmarks, **options )\n\t\treturn response.map {|bk| Hglib::Repo::Bookmark.new(self, **bk) }\n\tend", "def loadmore\n\t\t\t\ttime = Time.at(params[:time].to_i).to_datetime\n\t\t\t\tbookmarks_loader(time, doorkeeper_token.resource_owner_id) \n\t\t\t\tbookmarks_formatter\n\t\t\tend", "def bookmark_by(u)\r\n Bookmark.bookmark_by(u, self)\r\n end", "def synchronize # :yields:\n lock\n yield\n ensure\n unlock\n end", "def render_bookmarks(bookmarks, title, feed_uri, user, except=[])\n # Figure out a current value for the Last-Modified header.\n if bookmarks.empty?\n last_modified = nil\n else\n # Last-Modified is the most recent timestamp in the bookmark list.\n most_recent_bookmark = bookmarks.max do |b1,b2|\n b1.timestamp <=> b2.timestamp\n end\n last_modified = most_recent_bookmark.timestamp\n end\n \n # If the bookmark list has been modified since it was last requested...\n render_not_modified_or(last_modified) do\n respond_to do |format|\n # If the client requested XML, serialize the ActiveRecord\n # objects to XML. Include references to the tags in the\n # serialization.\n format.xml { render :xml => \n bookmarks.to_xml(:except => except + [:id, :user_id],\n :include => [:tags]) }\n # If the client requested Atom, turn the ActiveRecord objects\n # into an Atom feed.\n format.atom { render :xml => atom_feed_for(bookmarks, title, \n feed_uri, user) }\n end\n end\n end", "def in_lock consistency_spec\n locker = Locker.new Snapscatter.parse_spec(consistency_spec)\n locker.lock\n begin\n yield\n ensure\n locker.unlock\n end\n end", "def blocks(limit: 1000, sort: :asc)\n history(limit: limit, sort: sort).map { |i| i[:block] }\n end", "def each # :nodoc:\n begin\n time, all = @rdmon.wait_snapshot\n stats = all[@addr] or next\n stats.queued >= @queued_min or next\n stats.active >= @active_min or next\n body = sprintf(@fmt, time.iso8601, @addr, stats.active, stats.queued)\n body = \"#{body.size.to_s(16)}\\r\\n#{body}\\r\\n\" if @chunk\n yield body\n end while true\n yield \"0\\r\\n\\r\\n\" if @chunk\n end", "def sync(&block)\n # Lock usage:\n # 1. @stop.mutex->@is_synching.mutex\n # 2. insert_to_backlog()\n # 3. stop_synching?()\n\n @stop.use do |stop, stop_mutex|\n @is_synching.use do |is_synching, is_synching_mutex|\n if is_synching then\n return\n else\n @stop.set_wo_lock(false)\n @is_synching.set_wo_lock(true)\n end\n end\n end\n\n last_timestamp = (@checkpoint.nil? ? nil : @checkpoint.commit_ts)\n cursor = init_sync(@checkpoint)\n\n yield :finished_dumping, 0 if block_given?\n\n loop do\n return if stop_synching?\n doc_batch = []\n ns_set_snapshot = get_ns_set_snapshot\n doc_count = 0 # count for the current batch\n cursor_exception_occured = false\n\n loop do\n begin\n doc = cursor.next_document\n rescue => e\n @logger.error \"#{@name}: #{get_full_exception_msg(e)}\"\n cursor_exception_occured = true\n yield :excep, doc_count if block_given?\n break\n end\n\n if doc.nil? then\n break\n else\n if insert_to_backlog(doc) then\n # Do nothing\n elsif filter_entry?(ns_set_snapshot, doc[\"ns\"]) then\n @logger.debug \"#{@name}: skipped oplog: #{doc}\"\n else\n doc_batch << doc\n doc_count += 1\n end\n\n last_timestamp = doc[\"ts\"]\n end\n\n return if stop_synching?\n break if doc_count > OPLOG_BATCH_SIZE\n end\n\n update_solr(doc_batch, true) unless doc_batch.empty?\n\n yield :sync, doc_count if block_given?\n\n sleep @update_interval unless @update_interval.zero?\n\n # Setting of cursor was deferred until here to do work with Solr while\n # waiting for connection to Mongo to recover.\n if cursor_exception_occured then\n if last_timestamp.nil? then\n cursor = retry_until_ok do\n timestamp = get_last_oplog_timestamp\n get_oplog_cursor(timestamp)\n end\n else\n cursor = retry_until_ok { get_oplog_cursor_w_check(last_timestamp) }\n end\n\n if cursor.nil? then\n if @auto_dump then\n cursor = perform_full_dump\n else\n raise StaleCursorException, STALE_CURSOR_MSG\n end\n end\n\n yield :cursor_reset, doc_count if block_given?\n end\n end\n end", "def index\n @bookmarks = Bookmark.where(owner: current_user)\n end" ]
[ "0.5677542", "0.5362584", "0.5287357", "0.5209643", "0.5123315", "0.50758433", "0.49724126", "0.49338025", "0.49207413", "0.48885435", "0.4852993", "0.47811237", "0.47484133", "0.4718143", "0.4698666", "0.46631137", "0.46602684", "0.46602684", "0.46602684", "0.46580476", "0.4653106", "0.46193504", "0.46134466", "0.46089986", "0.46025783", "0.45895875", "0.45572627", "0.45488644", "0.4539659", "0.45351037" ]
0.5633354
1
Initializes all keys to `UNSET_VALUE`
def initialize super keys.each do |key| set(key, self.class::UNSET_VALUE) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clear\n keys.each do |k|\n Jeapie.instance_variable_set(\"@#{k}\", nil)\n end\n end", "def reset_initial_values\n @initial_values.clear if @initial_values\n @missing_initial_values.clear if @missing_initial_values\n end", "def reset!\n @significant_keys = nil\n @orders = Hash.new{|h,k| h[k] = Hash.new{|h2, k2| h2[k2] = []}}\n @key_count = Hash.new(0)\n @cache = {}\n end", "def clear\n @data = {}\n @next_keys = {}\n end", "def reset\n @ret_val = 999\n @keys = []\n @keys_to_check = []\n @keys_used = []\n @unsigned_keys = []\n @algs = []\n @last_nsec3_hashed = nil\n @nsec3param = nil\n @first_nsec3 = nil\n @count = 0\n @last_nsec = nil\n @first_nsec = nil\n @warned_about_nsec3param = false\n @zone_name = \"\"\n @soa = nil\n @config = nil\n @key_tracker = nil\n @key_cache = nil\n @unknown_nsecs = {}\n @empty_nonterminals = []\n end", "def clear\n with(keys: EMPTY_ARRAY)\n end", "def reset!\n self.user_values = {}\n\n # @inputs have to be nil, not an empty hash. otherwise\n # the memoized inputs will not pick up the changes.\n @inputs = nil\n end", "def reset\n @value = nil\n @count = 0\n end", "def reset\n\t\tself.clear\n\t\tme = self\n\t\t@default_values.each {|n,v| me[n] = v.is_a?(Class) ? nil : v}\n\tend", "def clear!\n @key_registry = {}\n self\n end", "def clear\n all_keys = keys\n return 0 if all_keys.empty?\n\n # Delete all keys\n del(*all_keys)\n end", "def reset\n @map[@map.keys[0]].reset\n @map[@map.keys[1]].reset\n end", "def clear\n @index = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }\n end", "def reset!\n keys.each do |key|\n instance_variable_set(:\"@#{key}\", GogoKit::Default.send(key))\n end\n self\n end", "def reset\n keys.each do |key|\n instance_variable_set(:\"@#{key}\", defaults[key])\n self\n end\n end", "def initialize\n @_values = {}\n end", "def clear_assigned_keys\n @assigned_keys = {}\n end", "def reset!\n @defaults.each { |key, value| instance_variable_set(key, value) }\n end", "def reset!\n @defaults.each { |key, value| instance_variable_set(key, value) }\n end", "def reset\n\t\t\t\tself.clear\n\t\t\t\tme = self\n\t\t\t\t@default_values.each { |n, v| me[n] = v.is_a?(Class) ? nil : v }\n\t\t\tend", "def initialize\n super {|hash, key| hash[key] = 0}\n end", "def clear\n @lock.synchronize do\n @values.clear\n @references_to_keys_map.clear\n end\n end", "def reset! key = nil\n if key.nil?\n @values.clear\n else\n key = ::Kernel.String(key).to_sym\n @values.delete key\n end\n self\n end", "def reset!\n Unleashed::Configurable.keys.each do |key|\n instance_variable_set(:\"@#{key}\", Unleashed::Default.options[key])\n end\n\n self\n end", "def clear!\n @key_files = []\n @known_identities = nil\n self\n end", "def clear\n @val = 0\n self\n end", "def reset\n @value = nil\n end", "def reset!\n @defaults.each do |k, v|\n instance_variable_set(k, v)\n end\n end", "def hash_set_up\n Hash.new { |hash, key| hash[key] = Array.new(1) { 0 } }\n end", "def clear\n @values.clear\n end" ]
[ "0.69660556", "0.6755322", "0.67488617", "0.6719314", "0.66499686", "0.66154104", "0.6439547", "0.64275587", "0.64091766", "0.63930345", "0.6391282", "0.6360693", "0.6350334", "0.63373464", "0.6332697", "0.6281231", "0.6239432", "0.6217614", "0.6217614", "0.621136", "0.61982644", "0.6192366", "0.6145772", "0.613051", "0.6116607", "0.61120486", "0.6109144", "0.60894907", "0.60265964", "0.60210407" ]
0.8348679
0
Returns a configuration line/stanza for the specified key and value. The returned line should include linefeed `\\n` if not empty. The default implementations returns "=\\n".
def config_for(key, value) "#{key}=#{value && value}\n" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def first_line(value)\n config_value = AppConfig.config[value]\n if config_value.kind_of? Mash\n config_value = config_value.to_hash\n end\n str = [config_value.inspect].flatten.first.split(\"\\n\").first\n if str.length > VALUE_LENGTH\n str = str[0..(VALUE_LENGTH - 4)] + '...'\n end\n str\n end", "def to_cookiestxt_line(linefeed = \"\\n\")\n [\n @domain,\n @for_domain ? True : False,\n @path,\n @secure ? True : False,\n @expires.to_i.to_s,\n @name,\n @value\n ].join(\"\\t\") << linefeed\n end", "def write_basic_line(io, line_key, line_value, validators)\n return if !line_value || line_value.empty?\n line_value.strip!\n valid = validate_line_value(line_value, validators)\n if valid || !@raise_on_invalid_data\n io.puts \"#{line_key}: #{line_value}\"\n elsif validators && !validators.empty? && @raise_on_invalid_data\n raise InvalidDataError, \"Invalid value: `#{line_value}` given for key `#{line_key}`\"\n end\n end", "def optional_newline\n \"\\n\"\n end", "def formatted_value_string(value)\n return value unless value.to_s.include?(\"\\n\") || value.to_s.include?(\"\\302\")\n\n # replaces all of \\n with a break line, but make sure it is escaped before marking as safe\n value = ERB::Util.html_escape(value)\n value.gsub!(\"\\n\", '<br>')\n value.html_safe # rubocop:disable Rails/OutputSafety\n end", "def get_key_val_override(line)\n\t\toverride_in_line = nil\n\t\tunless line.include?(\"=\")\n\t\t#not a key=value type of line.\n\t\t\treturn nil\n\t\tend\n\t\t\n\t\tif line.index(\"=\") == 0\n\t\t#= is the first character. not valid.\n\t\t\traise 'Invalid config file at line: ' << line\n\t\tend\n\t\t\n\t\tsplit_index = line.index(\"=\")\n\t\t\n\t\t#get key and value based on position of =\n\t\tkey = line[0..split_index - 1]\n\t\tvalue = line[split_index + 1..line.length]\n\t\tkey.strip!\n\t\tvalue.strip!\n\t\t\n\t\t#determine if key has an override.\n\t\tif key.include?(OVERRIDE_START) and key.include?(OVERRIDE_END)\n\t\t\toverride_start_index = key.index(OVERRIDE_START)\n\t\t\toverride_end_index = key.index(OVERRIDE_END)\n\t\t\toverride_in_line = key[override_start_index + 1..override_end_index - 1]\n\t\t\tkey = key[0..override_start_index - 1]\n\t\t\t\n\t\t\tkey.strip!\n\t\t\toverride_in_line.strip!\n\t\t\t\n\t\t\tif key.empty? or override_in_line.empty?\n\t\t\t#either key is empty or the data within <> is empty\n\t\t\t\traise 'Invalid config file at line: ' << line\n\t\t\tend\n\t\tend\n\t\t\n\t\t#return the tuple with key, value, override data\n\t\t{:key => key, :value => value, :override_in_line => override_in_line}\n\tend", "def val_for key\n split(\"\\n\").val_for(key)\n end", "def format(key, value)\n \"#{key}#{key_value_separator}#{format_value(value)}\"\n end", "def item_value(subsetting, subsetting_value)\n (subsetting || '') + (@key_val_separator || '') + (subsetting_value || '')\n end", "def config_value_for(key)\n cmd = executable_command config_value_str(key)\n value = `#{cmd}`.strip\n value = nil if value == ''\n value\n end", "def line_ending=(value)\n @line_ending = value || \"\\r\\n\"\n end", "def config_for(key, val)\n case val\n when TrueClass, FalseClass then key.to_s.tr('_', '-') if val\n when String, Fixnum then \"#{key.to_s.tr('_', '-')}=#{val}\"\n when Array then val.map { |v| config_for(key, v) }.join(\"\\n\")\n when Hash then config_for(key, val.keys.select { |k| val[k] })\n else raise(Exceptions::ValidationFailed,\n \"Invalid: '#{key}' => '#{val}'\")\n end\n end", "def default_line_separator\n @def_line_sep ||= infer_line_separator\n end", "def strip_lines(value)\n value.to_s.gsub(/\\n\\s*/, ' ')\n end", "def val_for key\n split(\"\\n\").grep(\n key.is_a?(Regexp) ? key : /(^|^[^\\w]*\\s+)#{Regexp.escape(key)}\\b/\n ).map {|l|\n l.sub(/^[^\\w]*\\s+/, '').\n sub(key.is_a?(Regexp) ? key : /^#{Regexp.escape(key)}\\b\\s*[:=]?/, '').\n sub(/[;,]\\s*$/, '').\n strip\n }.first || ''\n end", "def format_custom_property_value(node)\n value = node.resolved_value.sub(/\\n[ \\t\\r\\f\\n]*\\Z/, ' ')\n if node.style == :compact || node.style == :compressed || !value.include?(\"\\n\")\n # Folding not involving newlines was done in the parser. We can safely\n # fold newlines here because tokens like strings can't contain literal\n # newlines, so we know any adjacent whitespace is tokenized as whitespace.\n return node.resolved_value.gsub(/[ \\t\\r\\f]*\\n[ \\t\\r\\f\\n]*/, ' ')\n end\n\n # Find the smallest amount of indentation in the custom property and use\n # that as the base indentation level.\n lines = value.split(\"\\n\")\n indented_lines = lines[1..-1]\n min_indentation = indented_lines.\n map {|line| line[/^[ \\t]*/]}.\n reject {|line| line.empty?}.\n min_by {|line| line.length}\n\n # Limit the base indentation to the same indentation level as the node name\n # so that if *every* line is indented relative to the property name that's\n # preserved.\n if node.name_source_range\n base_indentation = min_indentation[0...node.name_source_range.start_pos.offset - 1]\n end\n\n lines.first + \"\\n\" + indented_lines.join(\"\\n\").gsub(/^#{base_indentation}/, ' ' * @tabs)\n end", "def convert_linebreaks(value)\n value.gsub(/(?:\\n\\r?|\\r\\n?)/, '<br/>').html_safe\n end", "def to_rb\n configuration.map { |k,v| \"#{k}(#{v.inspect})\" }.join(\"\\n\")\n end", "def format_with_quotes(key, value)\n value = remove_open_quotes(value)\n # Remove leading and trailing single quotes so we don't quote twice\n # if this key is flagged to be wrapped or it contains a special character\n # and it's not a full text field, such as About You\n if !value.nil? && !KEYS_TO_EXCLUDE_FROM_QUOTES.include?(key) && (KEYS_TO_WRAP_IN_QUOTES.include?(key) || /(\\[|\\]|\\(|\\)|: )/ === value)\n return \"'#{value.chomp(\"'\").reverse.chomp(\"'\").reverse}'\"\n else\n return value\n end\n end", "def to_line(record)\n str = \"\"\n str = \"# Puppet Name: #{record[:name]}\\n\" if record[:name]\n if record[:environment] and record[:environment] != :absent and record[:environment] != [:absent]\n record[:environment].each do |env|\n str += env + \"\\n\"\n end\n end\n\n if record[:special]\n str += \"@#{record[:special]} #{record[:command]}\"\n else\n str += join(record)\n end\n str\n end", "def compiled_string_at(line_no)\n line_str = \"\"\n\n value_arr.each do |num|\n if dash_lines.keys.include?(line_no)\n line_str << dash_or_blank_fill(line_no, num)\n else\n line_str << bars(line_no, num)\n end\n\n line_str << \" \"\n end\n\n line_str\n end", "def to_s\n \"\\\"#{@key}\\\": #{@value}\"\n end", "def append_cmd\n sprintf 'echo \"%s%s\" >> %s', key_set_string, @config[:value], @file\n end", "def line_break\n append '(?:\\n|(?:\\r\\n))'\n end", "def k8s_config_map(path)\n \"|\\n\" +\n ERB.new(File.read(Pathname(@_curr_file).dirname + path)).result(binding).split(\"\\n\").map do |line|\n \" \" + line + \"\\n\"\n end.join('')\n end", "def ssh_config\n ENTRIES.inject([]) { |out, keyvalue|\n host, keywords = keyvalue\n out << [\n 'Host ' + host,\n keywords.inject([]) do |subout, subkeyvalue|\n key, value = subkeyvalue\n subout << \"#{INDENT}#{key.to_s}#{SEPARATOR}#{value.to_s}\"\n end\n ]\n }.join(\"\\n\")\nend", "def escape_ini_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 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 node_text( value, block = nil )\n @seq_map = false\n\t\t\tvalx = value.dup\n unless block\n block =\n if options(:UseBlock)\n '|'\n elsif not options(:UseFold) and valx =~ /\\n[ \\t]/ and not valx =~ /#{YAML::ESCAPE_CHAR}/\n '|'\n else\n '>'\n end \n\n indt = $&.to_i if block =~ /\\d+/\n if valx =~ /(\\A\\n*[ \\t#]|^---\\s+)/\n indt = options(:Indent) unless indt.to_i > 0\n block += indt.to_s\n end\n\n block +=\n if valx =~ /\\n\\Z\\n/\n \"+\"\n elsif valx =~ /\\Z\\n/\n \"\"\n else\n \"-\"\n end\n end\n block += \"\\n\"\n if block[0] == ?\"\n esc_skip = ( \"\\t\\n\" unless valx =~ /^[ \\t]/ ) || \"\"\n valx = fold( YAML::escape( valx, esc_skip ) + \"\\\"\" ).chomp\n self << '\"' + indent_text( valx, indt, false )\n else\n if block[0] == ?> \n valx = fold( valx ) \n end\n #p [block, indt]\n self << block + indent_text( valx, indt )\n end\n\t\tend", "def getLine (key)\n lines = \n {\n \"N\": [\"Times Square\", \"34th\", \"28th\", \"23rd\", \"Union Square\", \"8th\"],\n \"L\": [\"8th\", \"6th\", \"Union Square\", \"3rd\", \"1st\"],\n \"6\": [\"Grand Central\", \"33rd\", \"28th\", \"23rd\", \"Union Square\", \"Astor Place\"]\n }\n return lines[key]\nend" ]
[ "0.6334932", "0.595716", "0.55967873", "0.5538644", "0.5380671", "0.5348368", "0.5344652", "0.5301884", "0.52344185", "0.5225823", "0.51633716", "0.513886", "0.5133486", "0.512706", "0.5108123", "0.5065678", "0.50303304", "0.50193423", "0.50114393", "0.49856082", "0.49671972", "0.4933405", "0.4930286", "0.4918874", "0.49036446", "0.48831964", "0.48362857", "0.480645", "0.4790564", "0.47574666" ]
0.6606757
0
This gets a game cliche from a list of cliches in a text file
def get_game_cliche #initialize variable chosen_line = nil #Get the cliche File.foreach("game_cliches.txt").each_with_index do |line, number| chosen_line = line if rand < 1.0/(number+1) end return chosen_line.chomp end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def from_file(file)\n file_lines_array = File.readlines(file)\n file_characters_array = []\n file_lines_array.each do |line|\n file_characters_array << line\n end\n file_characters_array.map! do |character|\n character = @dictionary[character]\n end\n morse_code = file_characters_array.join(\"\")\n puts morse_code\n end", "def readfile(file=\"SCC.txt\")\n\tg = Graph.new\n\tFile.open(file, \"r\") do |infile|\n\t\twhile (line = infile.gets)\n\t\t\tverts = line.split\n\t\t\tg.add_edge(verts[0], verts[1])\n\t\tend\n\tend\n\treturn g\nend", "def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend", "def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend", "def get_game_genre\n\t\t#initialize variable\n\t\tchosen_line = nil\n\t\t\n\t\t#Get the cliche\n\t\tFile.foreach(\"game_genres.txt\").each_with_index do |line, number|\n\t\t\tchosen_line = line if rand < 1.0/(number+1)\n\t\tend\n\t\t\n\n\treturn chosen_line.chomp\n\tend", "def read_generator\n file = File.open(\"./lib/deck_of_cards.txt\")\n file_data = file.readlines.map(&:chomp)\n file.close\n file_data\n end", "def cards\n # Open and iterate on file contents to create individual cards, closes automatically\n File.open(filename, 'r') do |file|\n file.readlines.map do |line|\n question, answer, category = line.chomp.split(',')\n Card.new(question, answer, category.to_sym)\n end\n end\n end", "def concordance(infile_name)\n @hash.clear\n line_number = 1\n File.readlines(infile_name).each do |line|\n words = wordify line\n word_number = 1\n words.each do |word|\n @hash[word] = [] if @hash[word].nil?\n @hash[word] << ConcordanceTuple.new(line_number, word_number)\n word_number += 1\n end\n line_number += 1\n end\n end", "def import\n print 'Import filename: '\n $stdout.flush\n file = gets.chomp\n fd = File.new(file, \"r\")\n itecky = file.rindex('.')\n raise 'missing dot in filename' if itecky == nil\n fname = file[0,itecky]\n fname.upcase!\n puts\n fd.each do\n |row|\n if row.strip.length == 0 or row[0,1] == '*' or row[0,1] == '#'\n next\n end\n row.chomp!\n items = row.split # deleni row na polozky oddelene mezerou\n nitems = items.length # pocet polozek\n raise \"only one word on the line\\n[#{row}]\" if nitems == 1\n if nitems == 2 # slovicka bez oddelovaci carky\n en = items[0]\n cz = items[1]\n else # slovicka a fraze s oddelovaci carkou\n i = row.index(' - ') # oddelovac anglickeho a ceskeho vyrazu\n raise \"missing ' - ' between English and Czech phrases\\n[#{row}]\" if i == nil\n en = row[0,i+1].strip # prvni cast radku - anglicka\n cz = row[i+3..-1].strip # druha cast radku - ceska\n end\n flag = false\n for iw in 0 ... $words.length do\n if $words[iw].fname == fname and\n ($words[iw].english == en or $words[iw].czech == cz) then\n flag = true\n break\n end\n end\n if flag == true then next end\n $words << Word.new(fname,0,0,en,cz)\n w = konverze($words.last.english + ' | ' + $words.last.czech)\n puts w\n end\n puts\n $stdout.flush\nend", "def candyList\n\t\t['sweet1.png','sweet2.png','sweet3.png','sweet4.png','sweet5.png','sweet6.png','sweet7.png','sweet8.png']\n\tend", "def initialize(file)\n @data = []\n @breakdown = []\n File.open(file).each do |l|\n l.strip!\n @data.push l\n # Split the data points into the component elements\n first, second = l.chars.each_slice(l.length / 2).map(&:join)\n puts \"#{first} - #{second}\" if @@debug\n # Store the elements for later\n @breakdown.push [first, second]\n end\n end", "def main\n c=[]\n File.open(CLUSTERS,'r').each {|line| c << line.chomp.split(\"\\t\") unless (line.include?(\"Cr\") || line.include?(\"Ct\"))}\n gtf=positions\n process(c,gtf)\n printlabels(gtf)\nend", "def identify_craft_in campaign_name\n dir = File.join(self.path, \"saves\", campaign_name, \"Ships\")\n Dir.chdir(dir)\n {\n :vab => Dir.glob(\"VAB/*.craft\").map{|craft| craft.gsub(\"VAB/\", \"\")}, \n :sph => Dir.glob(\"SPH/*.craft\").map{|craft| craft.gsub(\"SPH/\", \"\")}\n }\n end", "def load_words\n File.read(\"../scrabble word cheat/words.txt\").split(\"\\n\")\nend", "def load_from_file(filename,clean)\n\t\tbegin\n\t\t\t@clusters = []\n\t\t\t@items = []\n\t\t\t\n\t\t\traise IOError.new(\"#{filename} not found\") if not File.exists?(filename)\n\t\t\t\n\t\t\tIO.foreach(filename) do |line|\n\t\t\t\tlabel, items = *line.split(\":\",2).map { |x| x.strip }\n\t\t\t\titems = items.split(\" \").map { |x| (x.respond_to?(:to_sym) and not x.to_sym.nil?) ? x.to_sym : x }\n\t\t\t\titems = items - @items if clean\n\t\t\t\tif items.size > 0\n\t\t\t\t\titems.reject! { |x| @items.include?(x) }\n\t\t\t\t\tcluster = Cluster.new(items,label)\n\t\t\t\t\t@items = @items | cluster.items\n\t\t\t\t\[email protected] cluster\n\t\t\t\tend\n\t\t\tend\n\t\trescue IOError\n\t\t\traise $!\n\t\tend\n\tend", "def define_word_CEDICT(word)\n @cedict = 'cedict.txt'\n @word_matches = File.readlines(@cedict).grep(/#{word}/)\n\n @best_match = []\n\n @word_matches.each do |x|\n # CEDICT lists simplified and traditional characters, space delimited\n # 学 = \"學 学 [xue2] /to learn/to study/science/-ology/\"\n @match = x.split\n\n if @match[0] == word || @match[1] == word\n @best_match << x\n end\n end\n\n return @best_match\n end", "def load(filename)\n data = Array.new\n f = File.new(filename, \"r\")\n while (line = f.gets())\n nums = line.split(\" \")\n w = Array.new\n p = Array.new\n cnt = 0\n for i in (0..nums.at(1).to_i-1)\n #w.push(bin_round(nums.at(3+2*i).to_i, $roundbits)) #pro aprox alg.\n w.push(nums.at(3+2*i).to_i)\n p.push(nums.at(4+2*i).to_i)\n cnt += 1\n end\n data.push(Batoh.new(w, p, nums.at(2).to_i, Array.new(cnt, 0))) #inverzni pro DP\n end\n #pp data.to_s\n return data\nend", "def generate_words\n ret = []\n\n File.open('enable.txt').each do |line|\n new_line = line\n # We don't care for the new line character in the game of hangman.\n new_line = new_line.delete(\"\\n\")\n ret << new_line\n end\n\n return ret\nend", "def new_game\n dictonary = File.new('dictonary.txt', 'r')\n cleaned_dictonary = dictonary.readlines(chomp: true).select { |word| word.length >= 5 && word.length <= 12 }\n dictonary.close\n word = cleaned_dictonary.sample\n set_up_game(word, '_' * word.length)\n end", "def pick_word\n @dictionary = File.readlines('dictionary.txt').map(&:chomp)\n @computer_word = @dictionary.sample\n end", "def file_to_string_array\n card_list = []\n # File.open(\"./lib/two_cards.txt\").each do |line|\n File.open(@filename).each do |line|\n card_list << line\n end\n card_list.each do |card|\n card.slice!(\"\\n\")\n end\n #puts \"#{@card_list}\"\n #@card_list\n end", "def initialize file\n word_set = Set.new\n\n File.open(file, \"r\") do |f|\n f.each_line do |raw_line|\n line = raw_line.strip.upcase\n\n if HangmanGame.acceptable_word? line\n word_set.add line\n end\n end\n end\n\n @words = word_set.to_a.freeze\n\n Random.srand\n end", "def setUpGame\r\n #creates an array to that will be used to hold the words for the text file. \r\n $word_list = []\r\n #The \"file\" class in Ruby calls the \".open\" method which looks inside the specified file, the \".each\" method iterates over each line of the file and is piped (\"|\") to a variable called word \r\n File.open(CONST_WORD_LIST).each do |word|\r\n #The word variable is overwritten each time a new line is read, so each line is being stored into the \"word_list\" array \r\n #is_number? takes in each word and if it returns true, the word is added to the list. \r\n if is_number?(word) then $word_list << word end\r\n if word.chars.count { |char| word.count(char) > 1 } > 1 #each word has its characters inputted and unqiue characters are counted, the count is outputted and checked if it is more than 1 \r\n $word_list.delete(word)\r\n end\r\n puts $word_list\r\n end\r\n #puts $word_list\r\nend", "def load_categories(file)\n categories = IO.readlines(file)\n\n categories.each do |cat|\n cat.strip!\n end\n\n return categories\nend", "def read_content(file)\n\t\tcontent = []\n\t\tfile.each do |f|\n\t\t\tif File.file?(f)\n\t\t\t\tFile.open(f, \"r\") do |f|\n\t\t\t\t\tword = \"\"\n\t\t\t\t\tf.each_line do |line|\n\t\t\t\t\t\tword += \"#{line}\"\n\t\t\t\t\tend\n\t\t\t\t\tcontent += [word]\n\t\t\t\tend\n\t\t\tend\t\t\t\n\t\tend\n\t\treturn calculate_content(content)\n\tend", "def readFile\r\n\t\tfile = File.open(fileName, \"r\")\r\n\r\n\t\t#Array for partial matches\t\t\r\n\t\t@dictionary = Array.new\r\n\t\tfile.each do |line|\r\n\t\t\tif line != \"\\n\"\r\n\t\t\t\t@dictionary << line.split(/[:;\\n]/)\r\n\t\t\tend\r\n\t\tend\r\n\t\tstartStrategies\r\n\tend", "def read(file)\n\t\tnline = 0\t\t\t# entero que cuenta el numero de lineas en el archivo\n\t\tcomment = false \t# booleano que indica si se ha encontrado o no un comentario\n\t\tfile.each_line do |line|\n\t\t\tnline +=1\t\t# Para cada linea se imcrementa el contador en 1\n\t\t\tncolumn = 1\t\t# En cada nueva linea se inicializa el contador de columnas del archivo en 1 \n\n\t\t\t# Se chequea que la linea a leer no sea vacia\n\t\t\twhile line != \"\"\t\t\t\t\n\t\t\t\t# Para cada linea, se evaluan distintas expresiones regulares para la creacion del token\n\t\t\t\tcase line\n\n\t\t\t\t# Caso inicio/fin de comentario ( {-,-} )\n\t\t\t\twhen /^(\\{\\-|\\-\\})/\n\t\t\t\t\tword = line[/^(\\{\\-|\\-\\})/]\n\t\t\t\t\tif word == \"\\{\\-\"\n\t\t\t\t\t\tcomment = true \t\t# se encontro el inicio de comentario\n\t\t\t\t\t\t@comment << Token.new(nil,nil,nline,ncolumn)\n\t\t\t\t\telsif word == \"\\-\\}\"\n\t\t\t\t\t\tcomment = false \t# se cerro el comentario\n\t\t\t\t\t\[email protected]\n\t\t\t\t\tend\n\t\t\t\t\t# Para este caso no se crea token, simplemente se corta la linea para continuar \n\t\t\t\t\t# con la evaluacion de los siguientes caracteres/palabras\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso true,false,read,write\n\t\t\t\twhen /^(true|false|read|write)/\n\t\t\t\t\tword = line[/^(true|false|read|write)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que la palabra no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"true\" \n\t\t\t\t\t\t\t@tokens << Token.new(:TRUE,true,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"false\" \n\t\t\t\t\t\t\t@tokens << Token.new(:FALSE,false,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"read\"\n\t\t\t\t\t\t\t@tokens << Token.new(:READ,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"write\"\n\t\t\t\t\t\t\t@tokens << Token.new(:WRITE,word,nline,ncolumn)\n\t\t\t\t\t \tend\n\t\t\t\t\t end\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\t ncolumn += word.size()\n\t\t\t\t\t \n\t\t\t\t# Caso cualquier palabra que no sea true,false,read,write (identificadores)\n\t\t\t\twhen /^[a-zA-Z_][a-zA-Z0-9_]*/\n\t\t\t\t\tword = line[/^[a-zA-Z_][a-zA-Z0-9_]*/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el identificador no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\t@tokens << Token.new(:IDENTIFIER,word,nline,ncolumn)\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso para los numeros\n\t\t\t\twhen /^[0-9][0-9]*/\n\t\t\t\t\tword = line[/^[0-9][0-9]*/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el numero no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\t\t@tokens << Token.new(:NUMBER,word.to_i,nline,ncolumn)\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso operadores booleanos (/\\,\\/,^)\n\t\t\t\twhen /^(\\\\\\/|\\/\\\\|\\^)/\n\t\t\t\t\tword = line[/^(\\\\\\/|\\/\\\\|\\^)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el operador no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"\\^\" \n\t\t\t\t\t\t\t @tokens << Token.new(:NOT,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\\\\\/\" \n\t\t\t\t\t\t\t@tokens << Token.new(:OR,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\/\\\\\" \n\t\t\t\t\t\t\t@tokens << Token.new(:AND,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\t\t\t\t\t\n\t\t\t\t# Caso lienzos (<|>,<\\>,<->,< >,#)\n\t\t\t\twhen /^(<(\\||\\\\|\\/|\\-|\\_|\\s)>|#)/\n\t\t\t\t\tword = line[/^(<(\\||\\\\|\\/|\\-|\\_|\\s)>|#)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el lienzo no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"#\" then \n\t\t\t\t\t\t\t@tokens << Token.new(:EMPTY_CANVAS,[\"\"],nline,ncolumn)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t@tokens << Token.new(:CANVAS,[word[1]],nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso <=,>=,/=,>,<,=\n\t\t\t\twhen /^(>=|<=|\\/=|>|<|=)/\n\t\t\t\t\tword = line[/^(>=|<=|\\/=|>|<|=)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el operador no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \">=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MORE_EQUAL,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"<=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LESS_EQUAL,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\/=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:INEQUAL,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \">\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MORE,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"<\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LESS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:EQUAL,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso !,%,@\n\t\t\t\twhen /^[!%@]/\n\t\t\t\t\tword = line[/^[!%@]/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"!\"\n\t\t\t\t\t\t\t@tokens << Token.new(:EXCLAMATION_MARK,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"%\"\n\t\t\t\t\t\t\t@tokens << Token.new(:PERCENT,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"@\"\n\t\t\t\t\t\t\t@tokens << Token.new(:AT,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso operadores aritmeticos (+,-,*,/)\n\t\t\t\twhen /^(\\+|-|\\*|\\/)/\n\t\t\t\t\tword = line[/^(\\+|-|\\*|\\/)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"\\+\"\n\t\t\t\t\t\t\t@tokens << Token.new(:PLUS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"-\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MINUS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\*\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MULTIPLY,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\/\"\n\t\t\t\t\t\t\t@tokens << Token.new(:DIVISION,word,nline,ncolumn)\n\t\t\t\t\t\t\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso :,|,$,',&,~,;\n\t\t\t\twhen /^[:|$'&~]/\n\t\t\t\t\tword = line[/^[:|$'&~]/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \":\"\n\t\t\t\t\t\t\t@tokens << Token.new(:COLON,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"|\"\n\t\t\t\t\t\t\t@tokens << Token.new(:PIPE,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"$\"\n\t\t\t\t\t\t\t@tokens << Token.new(:DOLLAR,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"'\"\n\t\t\t\t\t\t\t@tokens << Token.new(:APOSTROPHE,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"&\"\n\t\t\t\t\t\t\t@tokens << Token.new(:AMPERSAND,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"~\"\n\t\t\t\t\t\t\t@tokens << Token.new(:VIRGUILE,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso {,},[,],(,),?,;,..\n\t\t\t\twhen /^(\\{|\\}|\\[|\\]|\\(|\\)|\\?|;|\\.\\.)/\n\t\t\t\t\tword = line[/^(\\{|\\}|\\[|\\]|\\(|\\)|\\?|;|\\.\\.)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"{\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LCURLY,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"}\"\n\t\t\t\t\t\t\t@tokens << Token.new(:RCURLY,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"[\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LBRACKET,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"]\"\n\t\t\t\t\t\t\t@tokens << Token.new(:RBRACKET,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"(\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LPARENTHESIS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \")\"\n\t\t\t\t\t\t\t@tokens << Token.new(:RPARENTHESIS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"?\"\n\t\t\t\t\t\t\t@tokens << Token.new(:INTERROGATION_MARK,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \";\"\n\t\t\t\t\t\t\t@tokens << Token.new(:SEMI_COLON,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\.\\.\"\n\t\t\t\t\t\t\t@tokens << Token.new(:DOUBLE_DOT,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso espacio en blanco\n\t\t\t\twhen /^\\s/\n\t\t\t\t\tline = line.partition(/^\\s/).last\n\t\t\t\t\t# El tamaño de la columna se incrementa en 1, porque este es el tamaño correspondiente a 1 espacio\n\t\t\t\t\tncolumn += 1\n\n\t\t\t\t# Caso simbolo no aceptado por el lenguaje\n\t\t\t\telse\n\t\t\t\t\tword = line[/^[^\\s\\w]/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\t@invalids << InvalidWord.new(word,nline,ncolumn)\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Cierra case\n\t\t\t\tend\n\t\t\t# Cierra while\n\t\t\tend\n\t\t# Cierra do\n\t\tend\t\n\t# Cierra procedimiento read\n\tend", "def getWord()\n\tFile.open(\"./corncob_lowercase.txt\"){|f|\n\t\tline=nil\n\t\trand(1..58110).times{line=f.gets}\n\t\tputs line\n\t\treturn line.chomp()\n\t}\nend", "def create_list\n car_set = @car_make\n File.open(@file).each do |word|\n car_set.add(word.to_s.strip)\n end\n end", "def get_rand_circuit(name=\"circvit\")\n \n name=name.upcase.scan(/[A-Z]/).join.scan(/[^U]/).join.split(//)\n \n \n family= %w{will belief desire}\n family=family.shuffle\n \n fill = Magick::HatchFill.new(\"Transparent\", \"LightGreen\")\n \n i = Magick::ImageList.new \n i.new_image(333, 333, fill){ self.background_color = \"Transparent\" }\n gc = Magick::Draw.new\n \n \n gc.gravity(Magick::CenterGravity)\n gc.stroke(\"#33cc33\")\n gc.fill(\"#222222\")\n gc.stroke_width(20)\n gc.circle(167, 167, 167, 20)\n gc.stroke(\"#3333cc\")\n gc.fill(\"transparent\")\n gc.stroke_width(2)\n gc.circle(167, 167, 167, 25)\n gc.circle(167, 167, 167, 15)\n gc.circle(167, 167, 167, 22)\n gc.circle(167, 167, 167, 17)\n gc.draw(i)\n\n (0..name.length-1).each do |n|\n i.new_image(333, 333){ self.background_color = \"Transparent\" }\n gc = Magick::Draw.new \n gc.stroke(\"transparent\")\n gc.fill(\"transparent\")\n \n gc.pointsize = (52 + (rand(23)) )\n \n gc.gravity(Magick::CenterGravity)\n f=rand(3)\n gc.font= \"#{Rails.root}/app/assets/fonts/akho#{family[f]}.ttf\" \n gc.text((-rand(72) + rand(72)), (-rand(72) + rand(72)), name[n]).rotate(rand(360))\n gc.fill('red')\n gc.text((-rand(72) + rand(72)), (-rand(72) + rand(72)), name[n]).rotate(rand(360))\n gc.draw(i)\n \n end\n \n \n @Circuit=i.flatten_images\n @Circuit.format = 'png'\n \n \n @circuit_file = \"#{Rails.root}/tmp/circuit-#{name.join}-#{Time.now.to_i}-#{Process.pid}.png\"\n \n \n @Circuit.write('png:'+ @circuit_file)\n \n \n \n \n\n @data_uri = Base64.encode64(@Circuit.to_blob).gsub(/\\n/, \"\") \n @image_tag = '<img alt=\"preview\" src=\"data:image/png;base64,%s\">' % @data_uri\n \n end" ]
[ "0.60776716", "0.58314663", "0.5727392", "0.5727392", "0.56803805", "0.55513674", "0.5522171", "0.55120814", "0.53398526", "0.5279201", "0.52735335", "0.52666813", "0.52592844", "0.52514553", "0.52434874", "0.51947075", "0.516467", "0.5110767", "0.5105512", "0.50975233", "0.50879365", "0.5086082", "0.50765514", "0.5058335", "0.50501716", "0.50430745", "0.50413615", "0.50383943", "0.5019041", "0.50179666" ]
0.7069886
0
This gets a business model from a list in a text file
def get_business_model #initialize variable chosen_line = nil #Get the cliche File.foreach("business_models.txt").each_with_index do |line, number| chosen_line = line if rand < 1.0/(number+1) end return chosen_line.chomp end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_from_file(filename = \"listsave\")\n\t\tIO.readlines(filename).each do |line|\n\t\t\tadd_task(Task.new(line.chomp))\n\t\tend\n\tend", "def read_models\n File.readlines(\"car-models.txt\").each do |line|\n @modles_hash[line[0,1]] = line.partition('=').last.chomp\n end\n # puts \"@modles_hash: #{@modles_hash.inspect}\"\n # return @modles_hash\n end", "def read_file(master_list, fileName, sepRegex, reorder)\n\tFile.foreach(\"codetest_files/input_files/\"+fileName) do |x|\n\t\tnewS = x.gsub(/\\n/, \"\").split(sepRegex)\n\t\tnewO = {\n\t\t\t\"LastName\": newS[0],\n\t\t\t\"FirstName\": newS[1],\n\t\t\t\"Gender\": newS[reorder[0]][0] == \"M\" ? \"Male\" : \"Female\",\n\t\t\t\"DOB\": newS[reorder[1]].gsub(/-/, \"/\"),\n\t\t\t\"FavoriteColor\": newS[reorder[2]]\n\t\t}\n\t\t# pushing object into master array\n\t\tmaster_list << newO\n\tend\n\tmaster_list\nend", "def get_model_class(file); end", "def read_collection\n @@book_class = []\n lines = File.readlines('collection.txt')\n lines.each do| line |\n line_parts = line.split('/')\n @id = id+1\n title = line_parts[0].chomp\n author = line_parts[1].chomp\n @due_date = due_date = nil.to_i\n @@book_class << Book.new(id, title, author, due_date) #class implementation\n end\n end", "def file_2_list(f,lc=true)\n puts \"Loading records from file: #{f}\" if @verbose\n begin\n list=Array.new\n file = File.open(f, \"r\")\n file.each_line do |line|\n line=line.chomp.strip\n next if line.nil?\n next if line.empty?\n next if line =~ /^\\s*#/\n line=line.downcase if lc==true\n list.push(line.chomp.strip)\n end\n file.close\n return list\n rescue => ee\n puts \"Exception on method #{__method__} for file #{f}: #{ee}\" if @verbose\n return nil\n end\n end", "def create_list\n car_set = @car_make\n File.open(@file).each do |word|\n car_set.add(word.to_s.strip)\n end\n end", "def get_loaded_model(model_path, file); end", "def file_2_list(f,lc=true)\n\t\tputs \"Loading records from file: #{f}\" if @verbose\n\t\tbegin\n\t\t\tlist=Array.new\n\t\t\tfile = File.open(f, \"r\")\n\t\t\tfile.each_line do |line|\n\t\t\t\tline=line.chomp.strip\n\t\t\t\tnext if line.nil?\n\t\t\t\tnext if line.empty?\n\t\t\t\tnext if line =~ /^\\s*#/\n\t\t\t\tline=line.downcase if lc==true\n\t\t\t\tlist.push(line.chomp.strip)\n\t\t\tend\n\t\t\tfile.close\n\t\t\treturn list\n\t\trescue => ee\n\t\t\tputs \"Exception on method #{__method__} for file #{f}: #{ee}\" if @verbose\n\t\t\treturn nil\n\t\tend\n\tend", "def load_db\n basic_foods = {} # store BasicFood objects\n recipes = {} # store Recipe objects\n File.readlines('FoodDB.txt').each do |line|\n line = line.chomp.split(\",\")\n if line[1] == \"b\"\n basic_food = BasicFood.new(line[0], line[2])\n basic_foods[basic_food.name] = basic_food\n elsif line[1] == \"r\"\n recipe = Recipe.new(line[0], line[2..line.size])\n recipes[recipe.name] = recipe\n end\n end\n [basic_foods, recipes]\n end", "def rehydrate_model_from(filename)\n log(\"Reading saved #{method2str} model from #{filename}.\")\n File.open(filename, \"r\") do |file|\n @model = JSON.parse(file.read)\n end \n end", "def read_aperm\n @@book_class = []\n lines = File.readlines('aperm.txt')\n lines.each do| line |\n line_parts = line.split('/')\n @id = line_parts[0].to_i\n title = line_parts[1]\n author = line_parts[2]\n @due_date = line_parts[3].to_i\n @@book_class << Book.new(id, title, author, due_date) #class implementation\n end #do\n # print_all\n end", "def parse\r\n raise \"directory #{@config[:model_dir]} not exists\" unless File.directory? @config[:model_dir]\r\n Dir[\"#{@config[:model_dir]}/*.rb\"].each do |file|\r\n crt_model = Model.new\r\n model_attrs_ = Hash.new\r\n in_public = true\r\n File.open(file, 'r:utf-8').each do |line|\r\n line.chomp!\r\n\r\n # erd_tag and attr\r\n if /^[\\#\\s]*erd_tag\\:?\\s*(?<tag_>[\\w\\.]+)/ =~ line\r\n crt_model.tag = tag_ \r\n crt_model.attrs = @config[:tags][tag_]\r\n end\r\n\r\n # catch class definition\r\n if /^\\s*class\\s+(?<name_>\\w+)/ =~ line\r\n crt_model.name = name_.underscore \r\n self.parse_erd crt_model, line\r\n if /^\\s*class\\s+\\w+\\s+\\<\\s+(?<parent_>\\w+)/ =~ line\r\n crt_model.parent = parent_.underscore if parent_\r\n end\r\n end\r\n \r\n # catch functions\r\n in_public = true if /public\\:/ =~ line\r\n in_public = false if /private\\:/ =~ line\r\n\r\n if /^\\s*def\\s+(?<func_>[^#]+)\\s*/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = func_, 'function'\r\n self.parse_erd field_, line # parse erd attr and label\r\n # arbitrage link\r\n if /\\-\\>\\s*(?<name_>\\w+)(\\{(?<attrs_>.+)\\})?/ =~ line\r\n attrs = {}\r\n attrs = YAML.load(attrs_) if attrs_\r\n field_.edge = [name_, '', attrs]\r\n end\r\n crt_model.fields << field_ \r\n end\r\n\r\n # catch field\r\n if /^\\s*field\\s+\\:(?<name_>\\w+)\\s*\\,.*\\:?type\\:?\\s*(?<type_>[A-Za-z_0-9\\:]+)/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = name_, type_\r\n self.parse_erd field_, line # parse erd attr and label\r\n # arbitrage link\r\n if /\\-\\>\\s*(?<name_>\\w+)(\\{(?<attrs_>.+)\\})?/ =~ line\r\n attrs = {}\r\n attrs = YAML.load(attrs_) if attrs_\r\n field_.edge = [name_, '', attrs]\r\n end\r\n crt_model.fields << field_ \r\n end\r\n\r\n # catch relations\r\n if /^\\s*(?<rel_>embeds_many|embeds_one|has_many|has_one|belongs_to|embedded_in)\\s+\\:(?<name_>\\w+)\\s*(\\,.*\\:?as\\:?\\s*(?<as_>\\w+))?/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = rel_, name_\r\n field_.name = \"#{rel_} (as #{as_})\" if as_\r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n #if %w[belongs_to embedded_in embeds_one has_one].include? rel_\r\n field_.edge = [name_, '', {label: rel_, arrowhead: 'normal'}]\r\n #end\r\n end\r\n \r\n # common extension field\r\n if /^\\s*symbolize\\s+\\:(?<name>\\w+)\\s*\\,.*\\:?in\\:?.*(?<in_>\\[.+\\])/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = name_, \"symbolized in #{in_}\"\r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n end\r\n\r\n if /^\\s*state_machine\\s+\\:(?<state_>\\w+)/ =~ line\r\n field_ = Fields.new\r\n field_.name = state_ == \"initial\" ? \"state\" : state_\r\n field_.type = \"state_machine\"\r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n end\r\n\r\n if /\\s*as_enum\\s+\\:(?<name_>\\w+)\\s*\\,\\s*(?<enum_>[^#]+)/ =~ line\r\n field_ = Fields.new\r\n field_.name = name_\r\n field_.type = \"[ENUM] \" + enum_ \r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n end\r\n\r\n end # open and parse one file\r\n\r\n # assign attributes at the last moment\r\n crt_model.attrs.merge! model_attrs_\r\n\r\n # if config.include/tag, default to exclude_it = true\r\n if @config[:include].size > 0 or @config[:tag].size > 0\r\n include_it = false\r\n else\r\n include_it = true\r\n end\r\n\r\n # if in the include list, include it\r\n include_it = true if @config[:include] and @config[:include].include? crt_model.name\r\n @config[:tag].each do |t|\r\n include_it = true if t == crt_model.tag or /^#{t}(\\..+)?/.match(crt_model.tag)\r\n end\r\n\r\n include_it = false if @config[:exclude].include? crt_model.name\r\n @models[crt_model.name] = crt_model if include_it\r\n end # open directory\r\n self\r\n end", "def parse_file\n File.open(\"FoodDB.txt\", \"r\") do |f|\n f.each_line do |line|\n line.chomp!\n command = line.split(\",\")\n name = command[0]\n type = command[1]\n info = command[2]\n #switches on type\n case type\n when \"b\"\n addFood(name, info)\n when \"r\"\n length = command.length-1\n ingredients = command[2..length]\n addRecipe(name,ingredients)\n end\n end\n end\n end", "def load_hpo_file(file)\n\tstorage = []\n\tid = nil\n\tname = nil\n\talt_id = []\n\tsyn = []\n\tis_a = []\n\tFile.open(file).each do |line|\n\t\tline.chomp!\n\t\ttag, info = line.split(': ')\n\t\tif tag == 'id' || tag == 'name' || tag == 'is_a' || tag == 'synonym' || tag == 'alt_id'\n\t\t\tif tag == 'id'\n\t\t\t\tstorage << [id, alt_id.join('|'), name, syn.join('|')].concat(is_a) if !name.nil? #if !temp[1].include?(\"obsolete\") \n\t\t\t\tid = info\n\t\t\t\tname = nil\n\t\t\t\talt_id = []\n\t\t\t\tsyn = []\n\t\t\t\tis_a = []\n\t\t\tend\n\t\t\tif tag == 'alt_id'\n\t\t\t\talt_id << info\n\t\t\telsif tag == 'is_a'\n\t\t\t\tis_a.concat(info.split(' ! '))\n\t\t\telsif tag == 'synonym'\n\t\t\t\tsyn << info.split('\"')[1]\n\t\t\telse\n\t\t\t\tname = info\n\t\t\tend\n\t\tend\n\tend\n\tstorage << [id, alt_id.join('|'), name, syn.join('|')].concat(is_a)\n\treturn storage\nend", "def load_model(model_class)\n begin\n file_content = File.read(model_class.db_filename)\n json_data = JSON.parse(file_content)\n rescue Errno::ENOENT\n # The file does not exists\n json_data = []\n end\n json_data.each do |data_hash|\n new_object = model_class.from_hash(data_hash)\n new_object.save\n end\nend", "def load_model(model_class)\n begin\n file_content = File.read(model_class.db_filename)\n json_data = JSON.parse(file_content)\n rescue Errno::ENOENT\n # The file does not exists\n json_data = []\n end\n json_data.each do |data_hash|\n new_object = model_class.from_hash(data_hash)\n new_object.save\n end\nend", "def _parse_file_using_import(file, layout, model)\n attributes = {}\n count = 0\n value_sets = []\n column_names = model.columns.map{ |column| column.name }\n not_nces_fields = column_names.select { |name| name[/id/] }\n field_names = column_names - not_nces_fields\n options = { :validate => false }\n mstate_index = field_names.index(\"MSTATE\")\n while (line = file.gets) do\n next if line.strip == ''\n values = []\n layout.each do |label, start_pos, end_pos, length, data_type, description|\n data_str = line[(start_pos-1)..(end_pos-1)].strip.gsub(/[^[:print:]]/, '')\n data_value = case data_type\n when 'N'\n data_str.to_i\n when 'D'\n data_str.to_f\n else\n data_str\n end\n values << data_value\n end\n if @states_and_provinces\n if @states_and_provinces.include?(values[mstate_index])\n value_sets << values\n end\n else\n value_sets << values\n end\n if value_sets.length >= 10\n records = model.import(field_names, value_sets, options)\n value_sets = values = []\n end\n count += 1\n if count % 500 == 0\n print '.'\n STDOUT.flush\n end\n end\n if value_sets.length > 0\n model.import(field_names, value_sets, options)\n end\n puts \"\\n#{count} records processed from #{file.path}\"\n end", "def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend", "def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend", "def find_mos_models description\n models = {}\n description.downcase.each_line{|l|\n if l =~ /(^ *)([m]\\S*) (\\([^\\)]*\\)) +(\\S+) +(.*)$/\n parms, = parse_parameters $5\n models[$4] ||= []\n models[$4] << {'l'=> parm_eval(parms['l']),\n 'w'=> parm_eval2(parms['w'], parms[NUMBER_OF_FINGERS])}\n end\n }\n models.each_value{|v| v.uniq!}\n end", "def update_model(wbs)\n f = File.new(\"#{wbs.railsbase}/app/models/#{singular_name}.rb\",'r+')\n fa = f.readlines\n new_array = prepare_model_changes(fa, wbs)\n f.rewind\n new_array.each {|line| f.puts(line)}\n end", "def load_model file\n self.clear_model\n\n xml_file = File.new file\n doc = Document.new xml_file\n\n doc.elements.each(\"model/entities/entity\") do |element|\n\n id = element.elements[1].text.to_i\n name = element.elements[2].text\n type = element.elements[3].text\n definition = element.elements[4].text\n x = element.elements[5].text.to_i\n y = element.elements[6].text.to_i\n\n if id.to_i > @max_id\n @max_id = id.to_i\n end\n\n ent = self.add_entity name, type, definition, x, y\n ent.id = id\n end\n\n doc.elements.each(\"model/connections/connection\") do |element|\n name = element.elements[1].text\n definition = element.elements[2].text\n source_entity_id = element.elements[3].text.to_i\n target_entity_id = element.elements[4].text.to_i\n source_point_type = element.elements[5].text\n target_point_type = element.elements[6].text\n source_point_x = element.elements[7].text.to_i\n source_point_y = element.elements[8].text.to_i\n target_point_x = element.elements[9].text.to_i\n target_point_y = element.elements[10].text.to_i\n label_x = element.elements[11].text.to_i\n label_y = element.elements[12].text.to_i\n\n source_entity = self.get_entity source_entity_id\n target_entity = self.get_entity target_entity_id\n source_point = Point2D::Double.new source_point_x, source_point_y\n target_point = Point2D::Double.new target_point_x, target_point_y\n\n con = self.add_connection_specific_endpoints source_entity,\n target_entity,\n source_point,\n target_point,\n source_point_type,\n target_point_type,\n name,\n definition\n\n con.label.set_location label_x, label_y\n end\n @panel.repaint\n end", "def get_model(basic_data)\n [ content(basic_data, './model'),\n content(basic_data, './trim')\n ].join(' ').strip\n end", "def import_ori(file_path)\n string = IO.read(file_path)\n array = string.split(\"\\n\")\n array.shift\n return array\n end", "def import(libfile, lib)\r\n\t#open the text file containing the booklist from the library\r\n\tf = File.open(libfile)\r\n\t#parse the incoming lines into arrays of data\r\n\twhile line = f.gets do\r\n\t\tparsed_line = line.split('*')\r\n\t\tadd_book(parsed_line, lib)\r\n\tend\r\n\tf.close\r\nend", "def parse\n # TODO: Try to convert lsynth parts, maybe flag parts that are troublesome for manual editing,\n # look up to see if I've stored a conversion from ldraw ID to Bricklink ID,\n # convert Ldraw color IDs to BL color IDs, etc.\n parts = {}\n temp_parts = []\n\n @lines.each_with_index do |line, i|\n # This will stop getting parts for the base model once a submodel is reached\n break if line.match(/0 FILE/) && i > 15\n\n @submodels << line.match(/\\w+\\.ldr/).to_s.downcase if line.match(/^1/) && line.match(/\\.ldr$/)\n @lsynthed_parts << line.gsub('0 SYNTH BEGIN', '').split if line =~ /^0 SYNTH BEGIN/\n next unless line.match(/^1/) && line.match(/.dat$/)\n\n part = line.match(/\\w+\\.dat/).to_s.gsub!('.dat', '')\n next if lsynth_part?(part)\n\n color = line.match(/^1\\s\\d+/).to_s.gsub!('1 ', '')\n bl_part = get_bl_part_number(part)\n temp_parts << [bl_part, color, part]\n end\n\n # Now go through all submodels to determine the parts belonging to the submodels\n temp_parts = handle_submodels(temp_parts)\n\n # Not yet functional\n # handle_lsynthed_parts(temp_parts)\n\n temp_parts.each do |info|\n if parts.key?(\"#{info[0]}_#{info[1]}\")\n parts[\"#{info[0]}_#{info[1]}\"]['quantity'] += 1\n else\n parts[\"#{info[0]}_#{info[1]}\"] = {}\n parts[\"#{info[0]}_#{info[1]}\"]['quantity'] = 1\n parts[\"#{info[0]}_#{info[1]}\"]['ldraw_part_num'] = info[2]\n end\n end\n\n parts\n end", "def parse_file(f)\n\tentities = []\n\twhile (e = parse_entity(f))\n\t\tentities.push(e)\n\tend\n\treturn entities\nend", "def readfile\n features=[]\n feature=''\n data_range=''\n price=''\n \n File.open(\"./public/test.txt\", \"r\").each_line do |line|\n feature = line.scan(/([a-zA-z ]+ \\– [0-9]+)/).to_s.strip()\n date_range= line.scan(/([0-9\\/]+ \\– [0-9]+\\/[0-9]+)/).to_s\n price = line.scan(/( [0-9]+\\.[0-9]+)/).to_s.strip()\n this_feature={\n \"feature\" => feature,\n \"date_range\" => date_range,\n \"price\" => price\n \n }\n features << this_feature\n \n \n end\n\n return features\n end", "def load_models\n url = Configuration::PROPERTIES.get_property :url\n url_get_records = Configuration::PROPERTIES.get_property :url_get_models\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\n response = DynamicService::ServiceCaller.call_service url + url_get_records, {}, 'get'\n\n json = JSON.parse(response)\n unless json['status'] == 200\n raise json['message']\n end\n\n models = []\n array = json['models']\n array.each do |item|\n model = Dynamicloud::API::Model::RecordModel.new item['id'].to_i\n model.name = item['name']\n model.description = item['description']\n\n models.push model\n end\n\n models\n end" ]
[ "0.5695746", "0.5681048", "0.5620122", "0.5601672", "0.55808204", "0.55757797", "0.5550483", "0.5545499", "0.5530213", "0.54000396", "0.53902805", "0.53765845", "0.5367506", "0.53501093", "0.5347121", "0.53337157", "0.53337157", "0.5333076", "0.5310881", "0.5310881", "0.5276545", "0.5272617", "0.5267418", "0.5245766", "0.52253383", "0.5187939", "0.51798207", "0.5163715", "0.51426864", "0.51352" ]
0.6435022
0
This gets a game genre from a list in a text file
def get_game_genre #initialize variable chosen_line = nil #Get the cliche File.foreach("game_genres.txt").each_with_index do |line, number| chosen_line = line if rand < 1.0/(number+1) end return chosen_line.chomp end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_genre_list()\n File.open('./genre_list')\nend", "def load_genre(file_name)\n\t\tindata = []\n\t\tCSV.foreach(\"#{file_name}\", col_sep: \"|\") do |row|\n\t\t\tgenre_for_movie = [row[5].to_i,row[6].to_i,row[7].to_i,row[8].to_i,row[9].to_i,row[10].to_i,row[11].to_i,row[12].to_i,row[13].to_i,row[14].to_i,row[15].to_i,row[16].to_i,row[17].to_i,row[18].to_i,row[19].to_i,row[20].to_i,row[21].to_i,row[22].to_i,row[23].to_i ]\n\t\t\tindata.push({\"movie_id\"=>row[0].to_i,\"genres\"=>genre_for_movie})\n\t\tend\n\t\treturn indata\n\tend", "def list_genre\n genre = gets.chomp\n Genre.all.each do |a|\n if a.name == genre\n a.songs.collect { |s| puts \"#{s.artist.name} - #{s.name} - #{s.genre.name}\" }\n end\n end\n end", "def read_genre()\n\tcount = $genre_names.length\n\ti = 0\n\tputs 'Genre: '\n\twhile i < count\n\t\tputs \"#{i} \" + $genre_names[i]\n\t\ti += 1\n\tend\n\tselectedGenre = read_integer_in_range('Please select your album genre.', 0, count - 1)\n\tselectedGenre\nend", "def genre\n fetch('game.genre')\n end", "def list_genres\n\n puts \"1. Action\"\n puts \"2. Adventure\"\n puts \"3. Fighting Games\"\n puts \"4. First-Person Shooters\"\n puts \"5. Flight/Flying\"\n puts \"6. Party\"\n puts \"7. Platformer\"\n puts \"8. Puzzle\"\n puts \"9. Racing\"\n puts \"10. Real-Time Strategy (RTS)\"\n puts \"11. Role-Playing\"\n puts \"12. Simulation\"\n puts \"13. Sports\"\n puts \"14. Stategy\"\n puts \"15. Third-Person Shooter\"\n puts \"16. Turn-Based Strategy\"\n puts \"17. Wargames\"\n puts \"18. Wrestling\"\n puts \"Choose a genre (number)\"\n @input = gets.strip\n end", "def genres\n details.css(\"div.subtext a[href^='/genre/']\").map { |genre| genre.text } rescue []\n end", "def genres\n to_array search_by_itemprop 'genre'\n end", "def genres\n document[\"genre\"].collect {|gender| gender[\"$\"]} rescue nil\n end", "def genre_list\n {\"1\" => 'シーバス', \"2\" => 'バス', \"3\" => \"青物\",\n \"4\" => \"フラットフィッシュ\", \"6\" => \"アジ\"}\n end", "def genres\n MusicImporter.new(path).print_genres\n end", "def genres\n search_by_text('жанры').split(', ')\n end", "def list_songs_by_genre\n puts \"Please enter the name of a genre:\"\n input = gets.chomp\n if genre = Genre.find_by_name(input)\n sort_by_name = genre.songs.sort_by do |genre|\n genre.name\n end\n sort_by_name.each.with_index(1) do |genre, i|\n puts \"#{i}. #{genre.artist.name} - #{genre.name}\"\n end\n end\n end", "def store_genre\n genres = RSpotify::Recommendations.available_genre_seeds\n genre = @prompt.select('Which genre would you like to add to your list?', genres, filter: true)\n genre_details = {\n 'name' => genre.capitalize,\n 'type' => 'genre'\n }\n @mylist << genre_details\n update_file\n end", "def genres\n document.search(\"h5[text()='Genre:'] ~ a[@href*=/Sections/Genres/']\").map { |link| link.innerHTML.strip.imdb_unescape_html } rescue []\n end", "def genres\n songs.map {|song| song.genre }\n end", "def genres\n songs.map {|song| song.genre}\n end", "def genres\n\t\[email protected] {|g| g.genre}\n\tend", "def genres\n songs.map do |song| song.genre end\n end", "def genres\n @songs.collect {|s| s.genre}\n end", "def lookup_genre(s)\n \tg = genre_list()\n \tg[s]\n end", "def genres\r\n self.songs.collect do |song|\r\n song.genre\r\n end\r\n end", "def genres(string)\n return [] if string.blank?\n\n genres = []\n\n # Split fields\n string.split(/[,;]/).each do |genre|\n ##\n # Start with a single empty genre string. Split the genre by spaces\n # and process each component. If a component does not have a slash,\n # concatenate it to all genre strings present in +temp+. If it does\n # have a slash present, duplicate all genre strings, and concatenate\n # the first component (before the slash) to the first half, and the\n # last component to the last half. +temp+ now has an array of genre\n # combinations.\n #\n # 'Traditional Heavy/Power Metal' => ['Traditional Heavy', 'Traditional Power']\n # 'Traditional/Classical Heavy/Power Metal' => [\n # 'Traditional Heavy', 'Traditional Power',\n # 'Classical Heavy', 'Classical Power']\n #\n temp = [\"\"]\n\n genre.downcase.split.reject { |g| GENRE_SUFFIXES.include? g }.each do |g|\n if g.include? \"/\"\n # Duplicate all WIP genres\n temp2 = temp.dup\n\n # Assign first and last components to temp and temp2 respectively\n split = g.split \"/\"\n temp.map! { |t| t.empty? ? split.first.capitalize : \"#{t.capitalize} #{split.first.capitalize}\" }\n temp2.map! { |t| t.empty? ? split.last.capitalize : \"#{t.capitalize} #{split.last.capitalize}\" }\n\n # Add both genre trees\n temp += temp2\n else\n temp.map! { |t| t.empty? ? g.capitalize : \"#{t.capitalize} #{g.capitalize}\" }\n end\n end\n genres += temp\n end\n genres.uniq\n end", "def bookGenre\n\t\tarr =[]\n\t\tcurrent_user.reads.each do |f|\n\t\t\tarr.push(Book.find_by_id(f.book_id).genre)\n\t\tend\n\t\th = Hash.new(0)\n\t\t\tarr.each do |word|\n\t\t\th[word] += 1\n\t\tend\n\t\tgenre = h.sort_by{|word,count| count}\n\t\tgenre = genre.reverse # Hash highest the genre picked the most\n\n\t\tarr2 =[]\n\t\tgenre.each do |key,value|\n\t\t\tarr2.push(key)\n\t\tend\n\t\tif(arr2.size > 1)\n\t\t\t@popGenre = arr2.at(0)\n\t\telse\n\t\t\t@popGenre = \"Adventure\"\n\t\tend\n\tend", "def genre; end", "def genre; end", "def genres\n songs.map{|song|song.genre}.uniq\n end", "def genres\n songs.collect{|song| song.genre}.uniq\n end", "def get_genre_list\n @genre_names = Genre.select('name')\n end", "def genres\n self.songs.collect do |song|\n song.genre\n end\n end" ]
[ "0.692953", "0.67731315", "0.6715894", "0.6458827", "0.6436415", "0.6399445", "0.63710093", "0.62383497", "0.6196342", "0.6195388", "0.61871946", "0.6115621", "0.6111598", "0.60685605", "0.6032322", "0.60173255", "0.5997231", "0.5992747", "0.59678346", "0.5966975", "0.587621", "0.5866576", "0.5839669", "0.58282965", "0.5818604", "0.5818604", "0.5806597", "0.5804598", "0.5794781", "0.5765711" ]
0.7423634
0
The top left of checkerboard should always be filled with [r] You should assume the size input is always an integer You should not assume the size input is always positive number Input size of <= 0 will return an empty string
def checkerboard(size) for i in 1..size do i % 2 == 0 ? checker=0 : checker=1 for j in 1..size do if checker == 1 print "[r]" checker = 0 else print "[b]" checker = 1 end end puts "\n" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def checkerboard(size)\n return \"\" if size <= 0\n completed_board = \"\"\n\n first_line = size.times do |n|\n if n.odd?\n completed_board << \"[r]\"\n else\n completed_board << \"[b]\"\n end\n end\n\n # binding.pry\nend", "def board(empty_square_char = '.')\n board_str = \" ABCDEFGH\\n\"\n (@board.size-1).downto(0).each do |rank_index|\n line = \"#{rank_index+1} \"\n @board[rank_index].each do |cell|\n line << (cell.nil? ? empty_square_char : cell)\n end\n board_str << line+\"\\n\"\n end\n board_str\n end", "def checker_board(size)\n # We can change \"X\" to \"||\" and \" \" to \" \" and it'll output a square shape\n pattern_1 = \"||\"\n pattern_2 = \" \"\n new_pattern_1 = \"\"\n new_pattern_2 = \"\"\n\n numbers = (1..size).to_a.reverse\n numbers.each do |number|\n if number.even?\n new_pattern_1 << pattern_1\n new_pattern_2 << pattern_2\n elsif number.odd?\n new_pattern_1 << pattern_2\n new_pattern_2 << pattern_1\n end # I don't know if this is bad practice, having one subfuction end and another one start right after\n end\n numbers.each do |number|\n if number.even?\n puts new_pattern_1\n else # We can use else, since there's only two conditons\n puts new_pattern_2\n end\n end\nend", "def populate_board\n rows_of_pieces = (size - 2) / 2\n make_pieces([0, 1], 'red', rows_of_pieces, 1)\n make_pieces([size - 1, 0], 'black', rows_of_pieces, -1)\n end", "def create_empty_board(position)\n 9.times { |i| position[i] = \" \"}\nend", "def create_board(size)\n return (0...size).map{|b| (0...size).map{|bb| 0}}\n end", "def empty_board\n { 1 => \" \", 2 => \" \", 3 => \" \", 4 => \" \", 5 => \" \", 6 => \" \", 7 => \" \", 8 => \" \", 9 => \" \"}\nend", "def board\n string = \"\"\n @array.each do |element|\n if (1..9).include?(element)\n string << element.to_s\n else\n string << \"-\"\n end\n end\n string\n end", "def display_board(board)\n filled_board = []\n board = board.each_slice(3).to_a\n board.each do |a|\n filled_board << a.join(\" | \")\n end\n for row in (0..filled_board.length-1)\n if row > 0\n print \"-----------\\n\"\n end\n print \" \" + filled_board[row] + \" \\n\"\n end\n nil\nend", "def to_s( )\n\t\t\tboard = \" +#{'---+' * 8}\\n\"\n\t\t\twhite = false\n\t\t\t(1..8).to_a.reverse.each do |rank|\n\t\t\t\tboard << \"#{rank} | \"\n\t\t\t\tboard << (\"a\"..\"h\").map do |file|\n\t\t\t\t\twhite = !white\n\t\t\t\t\t@squares[\"#{file}#{rank}\"] || (white ? \" \" : \".\")\n\t\t\t\tend.join(\" | \")\n\t\t\t\twhite = !white\n\t\t\t\tboard << \" |\\n\"\n\t\t\t\tboard << \" +#{'---+' * 8}\\n\"\n\t\t\tend\n\t\t\tboard << \" #{('a'..'h').to_a.join(' ')}\\n\"\n\t\t\tboard\n\t\tend", "def print_board\n 6.times do |y|\n y = 5 - y # To print from top to bottom\n 7.times do |x|\n if @board[[x, y]] == nil\n x == 6 ? (puts \"( )\") : (print \"( )\")\n else\n # Prints only the 3 first letters of each color to keep board alignment\n x == 6 ? (puts \"(#{@board[[x, y]].color[0, 3]})\") : (print \"(#{@board[[x, y]].color[0, 3]})\")\n end\n end\n end\n end", "def initializeBoard()\n\n # TO DO: COMPLETE THIS METHOD\n maxMid = @size / 2\n minMid = @size / 2 - 1\n for i in 0..size-1\n for j in 0..size-1\n if i == maxMid && j == maxMid\n @board[i][j] = \"B\"\n elsif i == minMid && j == minMid\n @board[i][j] = \"B\"\n elsif (i == minMid || i == maxMid) && (j == maxMid || j == minMid)\n @board[i][j] = \"W\"\n else\n @board[i][j] = \"-\";\n end\n end\n end\n end", "def show_board(spaces)\nputs \"\\n\n\n _______ _______ _______ \n | 1 | 2 | 3 |\n | \" + spaces[0] + \" | \" + spaces[1] + \" | \" + spaces[2] + \" |\n |_______|_______|_______|\n | 4 | 5 | 6 |\n | \" + spaces[3] + \" | \" + spaces[4] + \" | \" + spaces[5] + \" |\n |_______|_______|_______|\n | 7 | 8 | 9 |\n | \" + spaces[6] + \" | \" + spaces[7] + \" | \" + spaces[8] + \" |\n |_______|_______|_______| \\n\\n\\n\"\n\nend", "def show_board(spaces)\n\nputs \"\\n\n\n _______ _______ _______ \n | 1 | 2 | 3 |\n | \" + spaces[0] + \" | \" + spaces[1] + \" | \" + spaces[2] + \" |\n |_______|_______|_______|\n | 4 | 5 | 6 |\n | \" + spaces[3] + \" | \" + spaces[4] + \" | \" + spaces[5] + \" |\n |_______|_______|_______|\n | 7 | 8 | 9 |\n | \" + spaces[6] + \" | \" + spaces[7] + \" | \" + spaces[8] + \" |\n |_______|_______|_______| \\n\\n\\n\"\n\nend", "def show_board(spaces)\n\nputs \"\\n\n\n _______ _______ _______ \n | 1 | 2 | 3 |\n | \" + spaces[0] + \" | \" + spaces[1] + \" | \" + spaces[2] + \" |\n |_______|_______|_______|\n | 4 | 5 | 6 |\n | \" + spaces[3] + \" | \" + spaces[4] + \" | \" + spaces[5] + \" |\n |_______|_______|_______|\n | 7 | 8 | 9 |\n | \" + spaces[6] + \" | \" + spaces[7] + \" | \" + spaces[8] + \" |\n |_______|_______|_______| \\n\\n\\n\"\n\nend", "def fill_board(size)\n board = []\n board_rows = []\n size.times {|i| board_rows << i}\n size.times {board << board_rows}\n @board = board\n end", "def build_square size\n #starting positions\n x,y = size/2,0\n\n # build square\n (1..size**2).inject(Array.new(size){[]}) do |arr,i|\n\n # store current number in square\n arr[y][x] = i\n\n # move up and left\n x = (x+1)%size\n y = (y-1)%size\n\n # undo move and move down if space is taken\n if arr[y][x]\n y = (y+2)%size\n x = (x-1)%size\n end\n arr\n end\n end", "def checker_board(size)\n pattern_1 = \"X X X \"\n pattern_2 = \" X X X\"\n\n numbers = (1..size).to_a.reverse\n numbers.each do |number|\n if number.even?\n puts pattern_2\n elsif number.odd?\n puts pattern_1\n end\n end\nend", "def game_board_string(id)\n gs = game_state(id)\n result = ''\n (gs.rows - 1).downto(0) { |i|\n row_matrix = gs.row i\n for j in 0..gs.columns - 1\n if row_matrix[j].nil?\n result += '-'\n else\n result += row_matrix[j].value\n end\n end\n }\n return result\n end", "def display_board(board=[])\n if board.empty?\n 9.times do\n board << \" \"\n end\n end\n #row one\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n #row two\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n #row three\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \" \nend", "def check_valid (size)\n #checks length of string correct according to n x m\n if @arg.length != size\n puts \"String length incorrect\"\n end\n #checks if outer wall is all 1's\n string=''\n @col_nums.times do\n string+='1'\n end\n if !@arg[0..@col_nums-1].eql? string\n puts \"Invalid maze (outer wall)\"\n end\n (0..@row_nums*@col_nums-1).step(@col_nums) do |i|\n if @arg[i] != \"1\" || @arg[i-1] != \"1\"\n puts \"Invalid maze (outer wall)\"\n break\n end\n end\n #cell centers should be 0's\n #takes values of cell centers and uses coordinates for make_cell method\n (@col_nums..@row_nums*@col_nums-1).step(@col_nums*2) do |i|\n (1..@col_nums-2).step(2) do |j|\n if @arg[i+j]!=\"0\"\n puts \"Invalid maze (cell center)\"\n break\n else\n make_cell(i+j)\n end\n end\n end\n #cell corners should be 1's\n (0..@row_nums*@col_nums-1).step(@col_nums*2) do |i|\n (0..@col_nums-2).step(2) do |j|\n if @arg[i+j]!=\"1\"\n puts \"Invalid maze (cell corner)\"\n break\n end\n end\n end\n end", "def initialize(size)\n @board_size = size\n @board = []\n @board_size.times { @board << Array.new(@board_size, EMPTY_SYMBOL) }\n end", "def board\n output = \"\"\n [*0..80].each do |i|\n output << @board[i].ljust(4)\n output << \"\\n\" if (i+1) % 9 == 0\n end\n output\n end", "def construct_board\n board_dimensions = []\n puts \"Select board width between 1 and 500\".colorize(:green)\n board_width = gets.chomp\n puts \"Select board height between 1 and 500\".colorize(:green)\n board_height = gets.chomp\n puts sep = \"------------------------------------------------------\".colorize(:yellow)\n validate_width_is_number = board_width.to_i\n validate_height_is_number = board_height.to_i\n if validate_width_is_number <= 0 || validate_height_is_number > 500 && validate_height_is_number <= 0 || validate_height_is_number > 500\n puts \"Selection must be a number and between 1 and 500\".colorize(:red)\n return construct_board\n else \n validated_width = validate_width_is_number\n validated_height = validate_height_is_number\n board_size = validated_width.to_i * validated_height.to_i \n puts \"You have selected a board width of #{validated_width} and a board height of #{validated_height}.\".colorize(:green)\n puts \"Constructing a board with #{board_size} tiles.\".colorize(:green)\n if validated_width == validated_height\n board_dimensions.push(validated_width, validated_height)\n puts sep\n else\n puts \"Sorry, the board's width and height must be equal to each other. Try again\".colorize(:red)\n puts sep\n return construct_board\n end\n end\n return board_dimensions\nend", "def to_s\n board_str = \"\"\n square_index = 0\n new_line_counter = 1\n @array.each_with_index do |v, i|\n board_str << v.to_s #if (0..2).include?(i)\n if new_line_counter % 9 == 0\n board_str << \"\\n\"\n elsif new_line_counter % 3 == 0\n board_str << \" \"\n else\n board_str << \" \"\n end\n new_line_counter += 1\n end\n if @array.include?(0) == true\n board_str\n else\n self.fancy_display\n end\n end", "def to_s()\n\t\tstr = \"\\n \"\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' '\n\t\tend\n\t\tstr << \"\\n\";\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' ';\n\t\t\tstr << @board[i].join(' ') + \"\\n\";\n\t\tend\n\t\treturn str;\n\tend", "def to_s()\n\t\tstr = \"\\n \"\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' '\n\t\tend\n\t\tstr << \"\\n\";\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' ';\n\t\t\tstr << @board[i].join(' ') + \"\\n\";\n\t\tend\n\t\treturn str;\n\tend", "def board_size()\n p \"What board size would you want? odd numbers besides 1 are valid choices; 3 is a normal 3 by 3 board and 5 would make a 5 by 5 board.\"\n choice = gets.chomp\n if choice.to_i.odd? == true && choice.to_i > 1 && choice.to_i < 10\n choice.to_i\n else\n \tp \"wrong size choice\"\n board_size()\n end\nend", "def initializeBoard()\n #\n # TO DO: complete this method\n #\n for j in 0...@size\n for i in 0...@size\n @board[j][i]=EMPTY\n end\n end\n center = (@size/2)-1\n @board[center][center] = BLACK\n @board[center+1][center+1] = BLACK\n @board[center+1][center] = WHITE\n @board[center][center+1] = WHITE\n\n\n\n\n end", "def display_board\n cell_one = \" \"\n cell_two = \" \"\n cell_three = \" \"\n cell_four = \" \"\n cell_five = \" \"\n cell_six = \" \"\n cell_seven = \" \"\n cell_eight = \" \"\n cell_nine = \" \"\n divider = \"|\"\n row = \"-----------\"\n puts cell_one + divider + cell_two + divider + cell_three\n puts row\n puts cell_four + divider + cell_five + divider + cell_six\n puts row\n puts cell_seven + divider + cell_eight + divider + cell_nine\nend" ]
[ "0.7710083", "0.67398125", "0.66570306", "0.64006877", "0.63859284", "0.63433677", "0.6326673", "0.63063467", "0.6300146", "0.62883115", "0.62721723", "0.6269958", "0.62586683", "0.6236139", "0.6236139", "0.62247515", "0.62210417", "0.6220166", "0.6217392", "0.6162387", "0.61510426", "0.61438626", "0.6131827", "0.6105714", "0.61041003", "0.6098388", "0.6098388", "0.6080526", "0.60618836", "0.6032293" ]
0.7139748
1
The number of alarms. Returns an Integer.
def count @alarms.objects.find { |o| o.name == "count" }.val end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def count\n @monkeys.count\n end", "def aps_notification_count_for_application(application_name)\n redis.llen(aps_application_queue_key(application_name)).to_i\n end", "def num_missed_calls\n missed_contacts.count\n end", "def get_at_words_count\n @redis.llen(\"store:ats\").to_i\n end", "def notification_count\n @notifications.size\n end", "def unread_notification_count\n unread_notifications.count\n end", "def count\n self.at('/RETS/COUNT')['Records'].to_i\n end", "def returned_count\n if acknowledged?\n reply.number_returned\n else\n 0\n end\n end", "def get_size\n @monitors.length\n end", "def aps_applications_count\n redis.smembers(:aps_applications).size\n end", "def number_of_events_in_my_calendars\n self.events.length\n end", "def get_ata_words_count\n @redis.llen(\"store:atas\").to_i\n end", "def remediated_device_count\n return @remediated_device_count\n end", "def num_allies\n @allies.size\n end", "def at_job_count\n\n @non_cron_jobs.values.select { |j| j.class == AtJob }.size\n end", "def count\n @count\n end", "def number_of_meals\n meals.count\n end", "def size\n each_advisory_path.count\n end", "def num_of_tickets()\n result = films()\n @number_of_tickets = result.count\n end", "def num_answered_calls\n answered_contacts.count\n end", "def count_measures\n measures = 0\n \n self.measure_ids.each do |measure|\n measures += 1 if !measure.empty?\n end\n \n return measures\n end", "def cron_job_count\n\n @cron_jobs.size\n end", "def num_lights\n\t\t\[email protected]\n\t\tend", "def count\n run.count\n end", "def app_hang_count\n return @app_hang_count\n end", "def getDayOffCount\n\t\tdayCount = 0\n\t\tunless Setting.plugin_redmine_wktime['wk_schedule_weekend'].blank?\n\t\t\tdayCount = Setting.plugin_redmine_wktime['wk_schedule_weekend'].length\n\t\tend\n\t\tdayCount\n\tend", "def number_of_manifestations_launched(login=nil)\n count_by_frbr(login, :launches, :how_many_manifestations?) \n end", "def recording_count(bbb_id)\n bbb_server.get_recordings(meetingID: bbb_id)[:recordings].length\n end", "def count\n @count\n end", "def count\n @count\n end" ]
[ "0.6462344", "0.628732", "0.5995112", "0.5980965", "0.5917086", "0.5846684", "0.5811305", "0.5753843", "0.5741786", "0.5738726", "0.5713813", "0.5709746", "0.56947064", "0.56912374", "0.56524205", "0.5648412", "0.56226647", "0.5620281", "0.5602073", "0.5579684", "0.55703425", "0.5553837", "0.5532829", "0.5511789", "0.55019623", "0.55003697", "0.54958826", "0.54930896", "0.54910886", "0.54910886" ]
0.7122949
0
Query alarms. options A Hash of options: :start A DateTime instance describing the earliest time to query history for. :end A DateTime instance describing the latest time to query history for.
def query options from = options.fetch :start to = options.fetch :end query = @alarms.objects.find { |o| o.name == "query" } filter = OBIX::Builder.new do obj do abstime name: "start", val: from.iso8601 abstime name: "end", val: to.iso8601 end end.object alarms = query.invoke filter alarms.objects.find { |o| o.name == "data" } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def query options\n from = options.fetch :start\n to = options.fetch :end\n\n query = @history.objects.find { |o| o.name == \"query\" }\n\n filter = OBIX::Builder.new do\n obj do\n abstime name: \"start\", val: from.iso8601\n abstime name: \"end\", val: to.iso8601\n end\n end.object\n\n history = query.invoke filter\n\n history.objects.find { |o| o.name == \"data\" }\n end", "def query(options)\n run_command('query', options)\n end", "def query\n begin\n response = resource[\"/query/#{app}\"].post(:days => options[:days], :url => options[:url], :mode => options[:mode])\n rescue RestClient::InternalServerError\n display \"An error has occurred.\"\n end\n display response.to_s\n end", "def query(options={})\n from = parse_date(options[:from]).strftime('%Y-%m-%d')\n to = parse_date(options[:to]).strftime('%Y-%m-%d')\n\n response = Client.instance.request(:data,\n 'start-date' => from,\n 'end-date' => to,\n 'ids' => \"ga:#{@profile_id}\",\n 'metrics' => @metrics.join(','),\n 'dimensions' => @dimensions.join(','))\n \n\n headers = column_headers(response['columnHeaders'])\n group(response['rows'], headers)\n end", "def find_events_in_range(start_min, start_max,options = {})\n options[:max_results] ||= 25\n options[:order_by] ||= 'lastmodified' # other option is 'starttime'\n formatted_start_min = start_min.strftime(\"%Y-%m-%dT%H:%M:%S\")\n formatted_start_max = start_max.strftime(\"%Y-%m-%dT%H:%M:%S\")\n query = \"?start-min=#{formatted_start_min}&start-max=#{formatted_start_max}&recurrence-expansion-start=#{formatted_start_min}&recurrence-expansion-end=#{formatted_start_max}\"\n query = \"#{query}&orderby=#{options[:order_by]}&max-results=#{options[:max_results]}\"\n event_lookup(query)\n end", "def query_range(options)\n run_command('query_range', options)\n end", "def query_scheduled_messages(options = nil)\n require_relative 'scheduledmessage'\n @api.cursor(ScheduledMessage, get_base_api_path() + \"/scheduled\", options)\n end", "def search_time_sheet_activities(options={})\n cur_date = options[:start]\n method = 'search.messages'\n entries = []\n cnt = 0\n max_cnt = 15\n\n loop do\n fdate = cur_date.strftime('%Y-%m-%d')\n printf \"\\n>>> gathering activities for #{fdate}\"\n \n query = \"in:engineering from:me on:#{fdate}\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n break unless(cnt > max_cnt or cur_date < options[:stop])\n \n cur_date += (60*60*24)\n cnt += 1\n end\n\n entries = entries.sort_by { |h| h[:ts] }\n end", "def find_future_events(options={})\n formatted_start_min = encode_time(Time.now)\n query = \"?timeMin=#{formatted_start_min}#{parse_options(options)}\"\n event_lookup(query)\n end", "def alarms(tracker_id, options = {})\n get_json(path_user_version(\"/devices/tracker/#{tracker_id}/alarms\", options))\n end", "def all(options = {})\n constraints = [\n (\"SystemModstamp < #{options[:before].utc.iso8601}\" if options[:before]),\n (\"SystemModstamp >= #{options[:after].utc.iso8601}\" if options[:after]),\n *options[:conditions],\n ]\n\n DB.client.query(query(*constraints)).map do |record|\n instance_type.new(@record_type, record, @mapping)\n end\n end", "def query(metric_name, options={})\n key = build_key(metric_name)\n parse_time_range(options)\n key << assemble_for(options)\n if options[:id]\n key = \"dnid:#{options[:id]}\"\n real_key = DulyNoted.redis.get key\n if options[:meta_fields]\n options[:meta_fields].collect! { |x| x.to_s }\n result = {}\n options[:meta_fields].each do |field|\n result[field] = DulyNoted.redis.hget real_key, field\n end\n results = [result]\n else\n results = [DulyNoted.redis.hgetall(real_key)]\n end\n else\n keys = find_keys(key)\n grab_results = Proc.new do |metric|\n if options[:meta_fields]\n options[:meta_fields].collect! { |x| x.to_s }\n result = {}\n options[:meta_fields].each do |field|\n result[field] = DulyNoted.redis.hget metric, field\n end\n result\n else\n DulyNoted.redis.hgetall metric\n end\n end\n results = []\n if options[:time_start] && options[:time_end]\n keys.each do |key|\n results += DulyNoted.redis.zrangebyscore(key, options[:time_start].to_f, options[:time_end].to_f).collect(&grab_results)\n end\n else\n keys.each do |key|\n results += DulyNoted.redis.zrange(key, 0, -1).collect(&grab_results)\n end\n end\n end\n return results\n end", "def query(options) # :nodoc:\n @next_token = options[:next_token]\n query_expression = build_conditions(options[:query_expression])\n # add sort_options to the query_expression\n if options[:sort_option]\n sort_by, sort_order = sort_options(options[:sort_option])\n sort_query_expression = \"['#{sort_by}' starts-with '']\"\n sort_by_expression = \" sort '#{sort_by}' #{sort_order}\"\n # make query_expression to be a string (it may be null)\n query_expression = query_expression.to_s\n # quote from Amazon:\n # The sort attribute must be present in at least one of the predicates of the query expression.\n if query_expression.blank?\n query_expression = sort_query_expression\n elsif !query_attributes(query_expression).include?(sort_by)\n query_expression += \" intersection #{sort_query_expression}\"\n end\n query_expression += sort_by_expression\n end\n # request items\n query_result = self.connection.query(domain, query_expression, options[:max_number_of_items], @next_token)\n @next_token = query_result[:next_token]\n items = query_result[:items].map do |name|\n new_item = self.new('id' => name)\n new_item.mark_as_old\n reload_if_exists(record) if options[:auto_load]\n new_item\n end\n items\n end", "def find_events_in_range(start_min, start_max, options = {})\n formatted_start_min = encode_time(start_min)\n formatted_start_max = encode_time(start_max)\n query = \"?timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}#{parse_options(options)}\"\n event_lookup(query)\n end", "def search_time_sheet_activities(options={})\n cur_date = options[:start]\n method = 'search.messages'\n entries = []\n cnt = 0\n max_cnt = 15\n channels = (ENV['SLACK_CHANNELS'] and ENV['SLACK_CHANNELS'].split(/,/)) or ['engineering']\n\n loop do\n channels.each do |channel|\n\n fdate = cur_date.strftime('%Y-%m-%d')\n printf \"\\n>>> gathering activities for #{fdate}\"\n \n query = \"in:#{channel} from:me on:#{fdate}\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n break if(cnt > max_cnt)\n cnt += 1\n end\n cur_date += (60*60*24)\n break if(cur_date > options[:stop])\n end\n\n entries = entries.sort_by { |h| h[:ts] }\n end", "def get_query_metadata_for_account(account_id,\r\n from: nil,\r\n to: nil,\r\n min_start_time: nil,\r\n max_start_time: nil)\r\n # Prepare query url.\r\n _query_builder = config.get_base_uri(Server::VOICEDEFAULT)\r\n _query_builder << '/api/v2/accounts/{accountId}/recordings'\r\n _query_builder = APIHelper.append_url_with_template_parameters(\r\n _query_builder,\r\n 'accountId' => { 'value' => account_id, 'encode' => true }\r\n )\r\n _query_builder = APIHelper.append_url_with_query_parameters(\r\n _query_builder,\r\n 'from' => from,\r\n 'to' => to,\r\n 'minStartTime' => min_start_time,\r\n 'maxStartTime' => max_start_time\r\n )\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json'\r\n }\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = config.http_client.get(\r\n _query_url,\r\n headers: _headers\r\n )\r\n VoiceBasicAuth.apply(config, _request)\r\n _response = execute_request(_request)\r\n\r\n # Validate response against endpoint and global error codes.\r\n if _response.status_code == 400\r\n raise ApiErrorResponseException.new(\r\n 'Something\\'s not quite right... Your request is invalid. Please' \\\r\n ' fix it before trying again.',\r\n _response\r\n )\r\n elsif _response.status_code == 401\r\n raise APIException.new(\r\n 'Your credentials are invalid. Please use your Bandwidth dashboard' \\\r\n ' credentials to authenticate to the API.',\r\n _response\r\n )\r\n elsif _response.status_code == 403\r\n raise ApiErrorResponseException.new(\r\n 'User unauthorized to perform this action.',\r\n _response\r\n )\r\n elsif _response.status_code == 404\r\n raise ApiErrorResponseException.new(\r\n 'The resource specified cannot be found or does not belong to you.',\r\n _response\r\n )\r\n elsif _response.status_code == 415\r\n raise ApiErrorResponseException.new(\r\n 'We don\\'t support that media type. If a request body is required,' \\\r\n ' please send it to us as `application/json`.',\r\n _response\r\n )\r\n elsif _response.status_code == 429\r\n raise ApiErrorResponseException.new(\r\n 'You\\'re sending requests to this endpoint too frequently. Please' \\\r\n ' slow your request rate down and try again.',\r\n _response\r\n )\r\n elsif _response.status_code == 500\r\n raise ApiErrorResponseException.new(\r\n 'Something unexpected happened. Please try again.',\r\n _response\r\n )\r\n end\r\n validate_response(_response)\r\n\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_response.raw_body)\r\n ApiResponse.new(\r\n _response,\r\n data: decoded.map { |element| RecordingMetadataResponse.from_hash(element) }\r\n )\r\n end", "def parse_options(options) # :nodoc\n options[:max_results] ||= 25\n options[:order_by] ||= 'startTime' # other option is 'updated'\n options[:expand_recurring_events] ||= true\n query_string = \"&orderBy=#{options[:order_by]}\"\n query_string << \"&maxResults=#{options[:max_results]}\"\n query_string << \"&singleEvents=#{options[:expand_recurring_events]}\"\n query_string << \"&q=#{options[:query]}\" unless options[:query].nil?\n query_string\n end", "def run_alarm(opts)\n sources = Sources.instance\n storage = Storage.instance\n devices = Devices.instance\n rng = Rng.new\n io = IO.instance\n player = Player.instance\n\n run_use_cli_opts(opts)\n source = run_prepare(opts, sources, devices, rng, io)\n run_download(source, storage.method, storage)\n run_play(source, devices, player, storage)\n end", "def search_time_sheet_events(options={})\n days = {}\n method = 'search.messages'\n max_cnt = 15\n cnt = 0\n cur_date = options[:start]\n total_hours = 0.0\n\n loop do\n entries = []\n fdate = cur_date.strftime('%Y-%m-%d')\n printf \"\\n>>> processing #{fdate}\"\n \n query = \"in:engineering from:me on:#{fdate} biab\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {state: :off, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n query = \"in:engineering from:me on:#{fdate} brb\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {state: :off, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n \n query = \"in:engineering from:me on:#{fdate} back\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {state: :on, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n \n query = \"in:engineering from:me on:#{fdate} good\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n state = (x['text'] =~ /evening|night/) ? :off : :on\n {state: state, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n entries = entries.sort_by { |h| h[:ts] }\n days[fdate] = {entries: entries}\n\n start_entry = nil\n last_entry = nil\n seconds = 60*15\n total_time_for_day = 0.0\n start = nil\n entries.each do |entry|\n begin\n printf \".\"\n entry[:diff] = 0\n\n if(entry[:state] == :off)\n stop = Time.at((entry[:ts].to_f / seconds).round * seconds)\n start = nil\n entry[:ts] = stop\n next unless start_entry\n\n diff = entry[:ts] - start_entry[:ts]\n start_entry[:diff] = (diff/(60*60))\n\n total_time_for_day += start_entry[:diff]\n start_entry = nil\n else\n time = Time.at((entry[:ts].to_f / seconds).round * seconds)\n entry[:ts] = time\n\n start_entry = entry if start_entry.nil?\n end\n rescue Exception => e\n puts \"Problem with entry: #{entry.inspect}\nstart_entry: #{start_entry.inspect}\n\"\n raise e\n end\n last_entry = entry\n end\n\n if(start_entry)\n today = Time.now.strftime(\"%Y%m%d\")\n process_day = start_entry[:ts].strftime(\"%Y%m%d\")\n\n if(today == process_day)\n time = Time.at((Time.now.to_f / seconds).round * seconds)\n\n diff_work = time - start_entry[:ts]\n start_entry[:diff] = diff_work/(60*60)\n total_time_for_day += start_entry[:diff]\n \n entries << {state: :pending, ts: time, text: \"still working\"}\n\n else\n entries << {state: :off, ts: last_entry[:ts], text: \"good day/evening (you never checked out?)\"}\n end\n end\n\n if entries.length > 0\n entries[entries.length-1][:diff] = 0.0 \n days[fdate][:hours] = total_time_for_day\n total_hours += days[fdate][:hours]\n printf \"=> #{days[fdate][:hours]} for day; #{total_hours} for range\"\n end\n\n break unless(cnt > max_cnt or cur_date < options[:stop])\n\n # go to next day\n cur_date += (60*60*24)\n cnt += 1\n end\n\n days[:hours] = total_hours\n report = {report: days}\n puts \"\\n>>> DONE!\"\n report\n end", "def list(from = nil, to = Time.now, limit = 100, cursor = nil)\n raise ArgumentError unless from && to\n wf_event_id?(cursor) if cursor\n\n from = parse_time(from, true)\n to = parse_time(to, true)\n\n wf_ms_ts?(from)\n wf_ms_ts?(to)\n\n body = { earliestStartTimeEpochMillis: from,\n latestStartTimeEpochMillis: to,\n cursor: cursor,\n limit: limit }\n\n api.get('', body.cleanse)\n end", "def index\n @logs ||= Log.where(device_id: selected_device).order(created_at: :desc)\n unless params[:start_time].blank?\n start_date = DateTime.parse(\"#{params[:start_time]} 00:00:00\")\n @logs = @logs.where(\"created_at >= :start_time\", {start_time: start_date})\n end\n\n unless params[:end_time].blank?\n end_date = DateTime.parse(\"#{params[:end_time]} 23:59:59\")\n @logs = @logs.where(\"created_at <= :end_time\", {end_time: end_date})\n end\n end", "def collect_alarms(opts = {})\n data, _status_code, _headers = collect_alarms_with_http_info(opts)\n return data\n end", "def by_star(start_time, end_time, options = {}, &block)\n start_time = parse(start_time) \n end_time = parse(end_time)\n\n\n raise ParseError, \"End time is before start time, searching like this will return no results.\" if end_time < start_time\n field = options.delete(:field)\n ensure_valid_options(options)\n\n scoping = { :conditions => conditions_for_range(start_time, end_time, field) }.merge(options)\n result = scoped(scoping)\n result = result.scoped(block.call) if block_given?\n result\n end", "def query\n opinions = Decidim::Opinions::Opinion.where(component: @components)\n opinions = opinions.where(\"created_at >= ?\", @start_at) if @start_at.present?\n opinions = opinions.where(\"created_at <= ?\", @end_at) if @end_at.present?\n opinions\n end", "def add_query(symbol, start_date, end_date, &callback)\n start_date = Date.parse(start_date) unless start_date.is_a?(Date)\n end_date = Date.parse(end_date) unless end_date.is_a?(Date)\n\n @hydra.queue(make_request(symbol, start_date, end_date, callback))\n\n true\n end", "def query_events(params)\n events = Event.all\n\n #Allows the input and output parameters like time and date.\n if params[:date].present?\n date = params[:date].to_date\n events = events.where('date >= ?', date)\n else \n events = Event.where('date >= ?', Date.today)\n end\n\n if params[:food].present?\n if params[:food] != 'Any'\n events = events.where(food_type: params[:food])\n end\n end\n\n #allows for the selection of vegetarian options\n if params[:restrictions] == 'Vegetarian'\n events = events.where(vegetarian: true)\n end\n #allows for selection of vegan options\n if params[:restrictions] == 'Vegan'\n events = events.where(vegan: true)\n end\n\n if params[:time].present?\n \t#allows you to select the times\n events = events.where('time >= ?', params[:time])\n end\n\n events\n end", "def future(opts={}, now = Time.now.utc)\n all({:start.gte => now}.merge(opts))\n end", "def query_scheduled\n send(\"QUERY_GETALLSCHEDULED\")\n response = recv\n \n recording_count = response.shift.to_i\n recordings = []\n\n while recording_count > 0\n recording_array = response.slice!(0, Recording::RECORDINGS_ELEMENTS.length)\n recordings << Recording.new(recording_array, { :protocol_version => @protocol_version })\n recording_count -= 1\n end\n\n recordings = recordings.sort_by { |r| r.startts }\n recordings.reverse!\n end", "def alarms(tracker_id)\n get_call(\"user/#{user_id}/devices/tracker/#{tracker_id}/alarms.json\")\n end", "def search(options = {})\n self.date = options[:date] || date\n self.hd = options[:hd] || hd\n response = HTTParty.get(DEFAULT_URL, query: attributes)\n handle_response(response)\n end" ]
[ "0.7354929", "0.5985333", "0.58743316", "0.58070326", "0.5764716", "0.5755746", "0.5753159", "0.5711461", "0.56931704", "0.5642877", "0.5606174", "0.5584435", "0.54797727", "0.54386693", "0.54228055", "0.54051065", "0.53797007", "0.53651226", "0.5352223", "0.534723", "0.5345414", "0.5293993", "0.527068", "0.52704585", "0.5252477", "0.5246936", "0.5245493", "0.52379984", "0.52368253", "0.52328265" ]
0.8652422
0
returns the measure record associated with the device
def measure_for_device(device_id, measure_id) device = Device.where(:name => device_id) # use first on device to get record from association, then # use first again on measures to get measure record device.first.measures.where(:name => measure_id).first if device.any? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def measure\n Measure.new(1, self)\n end", "def get_cell_measures(cell)\n query_cell_info '/cell/getMeasures', cell\n end", "def get_patient_result(patient_id)\n qm = QualityMeasure.new(@measure_id, @sub_id)\n measure = Builder.new(get_db, qm.definition, @parameter_values)\n records = get_db.collection('records')\n result = records.map_reduce(measure.map_function, \"function(key, values){return values;}\",\n :out => {:inline => true}, \n :raw => true, \n :finalize => measure.finalize_function,\n :query => {:medical_record_number => patient_id, :test_id => @parameter_values['test_id']})\n raise result['err'] if result['ok']!=1\n result['results'][0]['value']\n end", "def measurement_values\n return @measurement_values unless @measurement_values.nil? \n return nil unless self.id\n \n @measurement_values = MetricMeasurementValues.new({:metric_id => self.id})\n return @measurement_values\n end", "def resourceType\n 'DeviceMetric'\n end", "def measures\n @dimensions.describe\n end", "def measures(cube_unique_name)\n @measures = {} if @measures.nil?\n\n @measures[cube_unique_name] ||= cube(cube_unique_name).get_measures.map do |measure|\n {\n :unique_name => measure.get_unique_name,\n :name => measure.get_caption\n }\n end\n end", "def metric_devices\n return @metric_devices\n end", "def measurements\n return @values['measurements'] if @values.key?('measurements')\n @values['measurements'] = {}\n @values['measurements']\n end", "def find_measure(instance_name)\n @items.find { |i| i.name == instance_name }\n end", "def reported_result(measure)\n (reported_results || {})[measure.key] || {}\n end", "def get_metric start, stop, step\n\t\[email protected]_metric self, start, stop, step\n\tend", "def meters \n metrics(Meter)\n end", "def usage_measures\n request = get '/1/reporting/measures'\n convert_to_mashes request\n end", "def measurements\n []\n end", "def measurements\n @measurements ||= []\n end", "def metric\n provider.find_metric(metric_key)\n end", "def get_measures\n # Collect time sig events and scan for last event time\n time_sigs = []\n max_pos = 0\n @tracks.each do |t|\n t.each do |e|\n time_sigs << e if e.kind_of?(MIDI::TimeSig)\n max_pos = e.time_from_start if e.time_from_start > max_pos\n end\n end\n time_sigs.sort { |x,y| x.time_from_start <=> y.time_from_start }\n\n # Add a \"fake\" time sig event at the very last position of the sequence,\n # just to make sure the whole sequence is calculated.\n t = MIDI::TimeSig.new(4, 2, 24, 8, 0)\n t.time_from_start = max_pos\n time_sigs << t\n\n # Default to 4/4\n measure_length = @ppqn * 4\n oldnumer, olddenom, oldbeats = 4, 2, 24\n\n measures = MIDI::Measures.new(max_pos, @ppqn)\n curr_pos = 0\n curr_meas_no = 1\n time_sigs.each do |te|\n meas_count = (te.time_from_start - curr_pos) / measure_length\n meas_count += 1 if (te.time_from_start - curr_pos) % measure_length > 0\n 1.upto(meas_count) do |i|\n measures << MIDI::Measure.new(curr_meas_no, curr_pos, measure_length,\n oldnumer, olddenom, oldbeats)\n curr_meas_no += 1\n curr_pos += measure_length\n end\n oldnumer, olddenom, oldbeats = te.numerator, te.denominator, te.metronome_ticks\n measure_length = te.measure_duration(@ppqn)\n end\n measures\n end", "def medical_record_number\n return medical_identifiers.first.medical_record_number if medical_identifiers.size == 1\n end", "def list_measures\n exec_req_and_parse_response \"/measure/list\"\n end", "def measures(client, var, options={})\n\t\t\t\tif options[:measures]\n\t\t\t\t\t\toptions[:measures] \n\t\t\t\telse\n\t\t\t\t\t[\"probe\",\"marker\",\"value\"]\n\t\t\t\tend\n\t\t\t\t# measure_properties(measures,var,options)\n\t\t\tend", "def set_measure\n @measure = Measure.find(params[:id])\n end", "def set_measure\n @measure = Measure.find(params[:id])\n end", "def set_measure\n @measure = Measure.find(params[:id])\n end", "def variables_card\n metric_card.metric_variables_card\nend", "def data\n measurements.collect do |measurement|\n {\n id: measurement.id, key: measurement.seconds,\n value: measurement.ppm, area: measurement.area,\n deleted: measurement.excluded\n }\n end\n end", "def format_measure(v)\n v\n end", "def measures\n return [] if !measure_ids\n self.bundle.measures.in(:hqmf_id => measure_ids).order_by([[:hqmf_id, :asc],[:sub_id, :asc]])\n end", "def show\n skippable_fields = [:map_fns, :record_ids, :measure_attributes]\n @measure = Measure.by_user(current_user).without(*skippable_fields).find(params[:id])\n if stale? last_modified: @measure.updated_at.try(:utc), etag: @measure.cache_key\n @measure_json = MultiJson.encode(@measure.as_json(except: skippable_fields))\n respond_with @measure do |format|\n format.json { render json: @measure_json }\n end\n end\n end", "def map_record_into_measure_groups(patient_id)\n qm = QualityMeasure.new(@measure_id, @sub_id)\n measure = Builder.new(get_db, qm.definition, @parameter_values)\n records = get_db.collection('records')\n records.map_reduce(measure.map_function, \"function(key, values){return values;}\",\n :out => {:reduce => 'patient_cache'}, \n :finalize => measure.finalize_function,\n :query => {:medical_record_number => patient_id, :test_id => @parameter_values['test_id']})\n apply_manual_exclusions\n end" ]
[ "0.6254628", "0.62511176", "0.6113168", "0.6065451", "0.6030521", "0.6027722", "0.5988547", "0.5962184", "0.5931976", "0.59317654", "0.59277445", "0.5884901", "0.5878865", "0.58713424", "0.5865355", "0.586038", "0.5829321", "0.58077085", "0.5791861", "0.57839763", "0.5758343", "0.57511026", "0.57511026", "0.57511026", "0.5723697", "0.5698178", "0.56158406", "0.5603718", "0.56026655", "0.5555681" ]
0.77113473
0
write a function to search target in nums. If target exists, then return its index, otherwise return 1. Template 1 is the most basic and elementary form of Binary Search. It is the standard Binary Search Template that most high schools or universities use when they first teach students computer science. Template 1 is used to search for an element or condition which can be determined by accessing a single index in the array. Approach 1: Algorithm Initialise left and right pointers: left = 0, right = n 1. While left <= right: Compare middle element of the array nums[pivot] to the target value target. If the middle element is the target target = nums[pivot] : return pivot. If the target is not yet found: If target < nums[pivot], continue the search on the left right = pivot 1. Else continue the search on the right left = pivot + 1. Complexity Analysis Time complexity: O(log N). Space complexity: O(1) since it's a constant space solution.
def search(nums, target) left = 0 right = nums.length - 1 while left <= right pivot = left + (right - left) / 2 return pivot if nums[pivot] == target if target < nums[pivot] right = pivot - 1 else left = pivot + 1 end end -1 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def search_target(nums, target)\n return -1 if nums.empty? || !target\n start_ind = 0\n last_ind = nums.size - 1\n mid = (start_ind + last_ind) / 2\n\n #having condition as start_ind + 1 < last_ind will be helpful in find first/last position in function\n #also avoid infinite loop when the array only has two elements\n while start_ind + 1 < last_ind do \n mid = start_ind + (last_ind - start_ind) / 2\n if (nums[mid] == target)\n last_ind = mid\n elsif nums[mid] > target\n last_ind = mid\n else\n start_ind = mid\n end\n end\n\n #find first position\n #if we wanna find the last position, check last_ind first\n if nums[start_ind] == target\n return start_ind\n end\n\n if nums[last_ind] == target\n return last_ind\n end\n\n return -1\nend", "def search(nums, target)\n left = 0\n right = nums.length - 1\n len = nums.length\n\n if nums[left] > nums[right] # no need if we're already sorted\n while right - left > 1\n mid = (right + left)/2\n\n # Check which side seam is on\n if nums[left] > nums[mid]\n # left side\n right = mid\n else\n left = mid\n #right side\n end\n end\n else\n right = 0\n end\n\n start = right\n\n left = 0\n right = nums.length\n\n while left < right\n return (start + left) % len if t_index(nums, left, start, len) == target\n return (start + right) % len if t_index(nums, right, start, len) == target\n\n mid = (left + right) / 2\n return (start + mid) % len if t_index(nums, mid, start, len) == target\n\n if target < t_index(nums, mid, start, len)\n right = mid - 1\n else\n left = mid + 1\n end\n end\n\n -1\nend", "def find_target(nums, target)\n return -1 if nums.empty? || !target\n start_ind = 0\n last_ind = nums.size - 1\n\n while (start_ind + 1 < last_ind) do\n mid = start_ind + (last_ind - start_ind) / 2\n\n if nums[mid] == target\n return mid\n end\n\n if nums[start_ind] < nums[mid]\n if nums[start_ind] <= target && target <= nums[mid]\n last_ind = mid\n else\n start_ind = mid\n end\n else\n if nums[mid] <= target && target <= nums[last_ind]\n start_ind = mid\n else\n last_ind = mid\n end\n end\n end\n\n return start_ind if nums[start_ind] == target\n return last_ind if nums[last_ind] == target\n return -1\nend", "def search(nums, target)\n return -1 if nums.length == 0\n\n left = 0\n right = nums.length\n\n while left < right\n mid = (left + right) / 2\n if nums[mid] == target\n return mid\n elsif nums[mid] < target\n left = mid + 1\n else\n right = mid\n end\n end\n\n # Post-processing:\n # End Condition: left == right\n if (left != nums.length) && (nums[left] == target)\n left\n else\n -1\n end\nend", "def search(nums, target)\n nums.each_with_index do |num, index|\n return index if num == target\n end\n -1\nend", "def first_pos(nums, target)\n start_ind = 0\n last_ind = nums.size #will return the size if not found such element\n\n while start_ind + 1 < last_ind do\n mid = start_ind + (last_ind - start_ind) / 2\n if nums[mid] < target\n start_ind = mid\n else\n last_ind = mid\n end\n end\n\n if nums[start_ind] >= target\n return start_ind\n end\n\n return last_ind\nend", "def binary_search(arr, target)\n new_arr = arr\n return nil if arr.empty? \n middle = (arr.length - 1) / 2\n if arr[middle] > target\n binary_search(arr[0...middle], target)\n elsif arr[middle] < target \n if binary_search(arr[middle+1..-1], target).nil?\n return nil\n else\n binary_search(arr[middle+1..-1], target) + middle + 1\n end \n elsif target == arr[middle]\n return new_arr.index(arr[middle])\n else\n return nil\n end\nend", "def binary_search(arr, target, idx_puls = 0)\n mid = arr.length / 2\n return mid + idx_puls if arr[mid] == target\n return nil if arr.length == 1\n\n if arr[mid] < target\n binary_search(arr[(mid + 1)..-1], target, mid + 1)\n else\n binary_search(arr[0...mid], target, idx_puls)\n end\n\nend", "def sortAndSearch(arr, target)\n arr = arr.sort_by(&:to_i)\n\n startIndex = 0;\n endIndex = arr.size-1\n\n if (target < arr[startIndex] || target > arr[endIndex])\n return 'target is not in array'\n elsif (target === arr[startIndex])\n return startIndex\n elsif (target === arr[endIndex])\n return endIndex\n end\n\n while (startIndex < endIndex - 1)\n midIndex = (startIndex + endIndex) / 2\n\n if (arr[midIndex] === target)\n return midIndex\n elsif (target < arr[midIndex])\n endIndex = midIndex\n elsif (target > arr[midIndex])\n startIndex = midIndex\n end\n end\n\n return 'target is not in array'\nend", "def search_range(nums, target)\n left = search(target, nums, :left)\n return [-1, -1] if left == nums.size || target != nums[left]\n [left, search(target + 1, nums, :right) - 1]\nend", "def search_insert (nums, target)\n\ti, j, m = 0, nums.length - 1, 0\n\twhile i <= j\n\t\tm = (i + j) / 2\n\t\tif nums[m] == target then return m\n\t\telsif nums[m] < target then i = m + 1\n\t\telse j = m - 1 end\n\tend\n\treturn i\nend", "def search(arr, target)\n left = 0\n right = arr.length - 1\n\n while left <= right\n mid = (left + right ) / 2\n\n return mid if arr[mid] == target\n\n if arr[mid] < target\n left = mid + 1\n else\n right = mid - 1\n end\n end\n\n return -1\nend", "def search_range(nums, target)\r\n left = 0\r\n right = nums.size - 1\r\n beginning = -1\r\n ending = -1\r\n\r\n while left + 1 < right\r\n mid = left + (right - left) / 2\r\n if nums[mid] < target\r\n left = mid + 1\r\n else\r\n right = mid\r\n end\r\n end\r\n if nums[left] == target\r\n beginning = left\r\n elsif nums[right] == target\r\n beginning = right\r\n end\r\n\r\n right = nums.size - 1\r\n while left + 1 < right\r\n mid = left + (right - left) / 2 + 1\r\n if nums[mid] > target\r\n right = mid - 1\r\n else\r\n left = mid\r\n end\r\n end\r\n if nums[right] == target\r\n ending = right\r\n elsif nums[left] == target\r\n ending = left\r\n end\r\n\r\n return [beginning, ending]\r\nend", "def binary_search(arr, target)\n return nil if !arr.include?(target)\n middle_ele = arr[arr.length / 2]\n middle_idx = arr.length / 2\n if target == middle_ele\n return middle_idx\n elsif target > middle_ele\n binary_search(arr[middle_idx+1..-1], target) + arr[0..middle_idx].length\n else\n binary_search(arr[0...middle_idx], target)\n end\nend", "def binary_search(arr, target)\n return nil if arr.empty?\n probe_index = arr.size / 2\n probe_ele = arr[probe_index]\n\n case probe_ele <=> target\n when 1\n left_arr = arr.take(probe_index) \n return binary_search(left_arr,target)\n when 0 \n return probe_index\n when -1\n compensated_index = (probe_index + 1)\n right_arr = arr.drop(compensated_index)\n return nil if binary_search(right_arr,target).nil?\n return binary_search(right_arr,target) + compensated_index\n end\nend", "def binary_search(array, target)\n temp = array.sort\n middle = temp.length / 2\n first = 0\n last = temp.length - 1\n while first < last\n if temp[middle] == target\n return middle\n elsif temp[middle] < target\n first = middle + 1\n middle = (first + last) / 2\n else\n last = middle - 1\n middle = (first + last) / 2\n end\n end\n return -1\nend", "def bsearch(nums, target)\n # nil if not found; can't find anything in an empty array\n return nil if nums.empty?\n \n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n # search in left\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index # found it!\n when 1\n # search in the right; don't forget that the right subarray starts\n # at `probe_index + 1`, so we need to offset by that amount.\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n sub_answer.nil? ? nil : (probe_index + 1) + sub_answer\n end\n \n # Note that the array size is always decreasing through each\n # recursive call, so we'll either find the item, or eventually end\n # up with an empty array.\n end", "def bsearch(nums, target)\n # nil if not found; can't find anything in an empty array\n return nil if nums.empty?\n \n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n # search in left\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index # found it!\n when 1\n # search in the right; don't forget that the right subarray starts\n # at `probe_index + 1`, so we need to offset by that amount.\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n sub_answer.nil? ? nil : (probe_index + 1) + sub_answer\n end\n \n # Note that the array size is always decreasing through each\n # recursive call, so we'll either find the item, or eventually end\n # up with an empty array.\n end", "def find_a_number_in_sorted_array(target_num, array, start_index, end_index)\n \n if end_index < start_index or start_index > end_index\n return nil\n end\n \n middle_index = ((start_index + end_index)/2).floor\n found_target_index = nil \n \n if target_num < array[middle_index]\n found_target_index = find_a_number_in_sorted_array(target_num, array, start_index, middle_index - 1)\n elsif target_num > array[middle_index]\n found_target_index = find_a_number_in_sorted_array(target_num, array, middle_index + 1, end_index)\n else\n found_target_index = middle_index\n end\n \n return found_target_index\nend", "def bsearch(arr, target)\n return nil if arr.empty?\n mid_idx = arr.length / 2\n pivot = arr[mid_idx]\n return mid_idx if pivot == target\n if pivot > target\n bsearch(arr[0...mid_idx], target)\n else\n result = bsearch(arr[mid_idx + 1..-1], target)\n if result == nil\n nil\n else\n mid_idx + 1 + result\n end\n end\nend", "def binary_search(array, target) \n return nil if array.length == 0\n mid = array.length / 2\n return mid if array[mid] == target\n left = array[0...mid]\n right = array[mid + 1..-1]\n if array[mid] > target #[]\n binary_search(left, target)\n else\n result = binary_search(right, target)\n return result.nil? ? nil : result + mid + 1\n end\n \nend", "def find_start nums, target, left, right\n if left + 1 >= right\n return left if nums[left] == target\n return right if nums[right] == target\n return -1\n end\n\n mid = left + (right - left) / 2\n\n if nums[mid] >= target\n right = mid\n else\n left = mid\n end\n\n find_start nums, target, left, right\nend", "def search_insert(nums, target)\n return 0 if nums.length == 0 \n if nums.include?(target)\n nums.each_with_index do |val ,index| \n if val == target\n return index\n end\n end\n else\n if target > nums[-1] \n return (nums.length - 1) + 1\n elsif target < nums[0]\n return 0\n elsif target.between?(nums[0],nums[-1])\n i = 0 \n j = 1\n while i < nums.length - 1 do \n if target.between?(nums[i],nums[j])\n return i + 1\n end\n i += 1\n j += 1\n end\n end\n end\nend", "def binary_search(arr, target)\n if arr.length == 1\n return nil if arr[0] != target\n end\n mid = arr.length / 2\n if target == arr[mid]\n return mid\n elsif target > arr[mid]\n if binary_search(arr[mid..arr.length], target) == nil\n return nil\n else\n return binary_search(arr[mid..arr.length], target) + arr.length / 2\n end\n else\n binary_search(arr[0..mid-1], target)\n end\nend", "def search_insert(nums, target)\n @start_index = 0\n @end_index = nums.length - 1\n if target > nums.last\n return nums.length\n elsif target < nums.first\n return 0\n else\n while @start_index <= @end_index\n @mid_index = (@end_index + @start_index) / 2\n if nums[@mid_index] == target\n return @mid_index\n elsif nums[@mid_index] < target\n @start_index += 1\n else\n @end_index -= 1\n end\n \n end\n return nums.bsearch_index{|e| e > target}\n end\nend", "def search_insert(nums, target)\n idx = nums.index(target)\n return idx unless idx.nil?\n first = nums.first\n last = nums.last\n return nums.size if target > last\n return 0 if target < first\n target.downto(first).to_a.each do |e|\n idx = nums.index(e)\n return idx + 1 unless idx.nil?\n end\n return 'Not found'\nend", "def binary_search(array, target)\n return nil if array.length == 1 && array[0] != target\n mid = array.length / 2\n\n if target == array[mid]\n return mid\n elsif target < array[mid]\n return binary_search(array[0...mid], target)\n else\n found = binary_search(array[mid+1..-1], target)\n return found.nil? ? nil : mid + 1 + found\n end\nend", "def search_insert(nums, target)\n start_ind = 0\n last_ind = nums.size \n\n while start_ind + 1 < last_ind do\n mid = start_ind + (last_ind - start_ind) / 2\n if nums[mid] == target\n return mid\n end\n\n if nums[mid] < target\n start_ind = mid\n else\n last_ind = mid\n end\n end\n\n if nums[start_ind] >= target\n return start_ind\n end\n\n return last_ind\nend", "def binary_search(array, target)\n return nil if array.empty?\n midpoint = array.length / 2\n case target <=> array[midpoint]\n when 0\n midpoint\n when 1\n right_idx = binary_search(array[(midpoint + 1)..-1], target)\n if right_idx\n right_idx + 1 + midpoint\n else\n nil\n end\n when -1\n binary_search(array[0...midpoint], target)\n end\nend", "def binary_search(target, array)\r\n\t#Your code here\r\n\tindex = array.length / 2\r\n\tlo = 0\r\n\thi = array.length - 1\r\n\twhile array[index] != target && array.include?(target)\r\n\t\tif array[index] > target\r\n\t\t\thi = index - 1\r\n\t\t index = (lo + hi) / 2\r\n\t\telsif array[index] < target\r\n\t\t\tlo = index + 1\r\n\t\t\tindex = (lo + hi) / 2\r\n\t\tend\r\n\tend\r\n\tif array[index] == target\r\n\t\treturn index\r\n\telse\r\n\t\treturn -1\r\n\tend \r\nend" ]
[ "0.86517495", "0.8379405", "0.81462884", "0.8144708", "0.794463", "0.78020096", "0.7797183", "0.77851063", "0.7719615", "0.77196014", "0.7711477", "0.7692617", "0.7687563", "0.76829803", "0.7676202", "0.76682353", "0.7660379", "0.7660379", "0.7649494", "0.76413953", "0.762154", "0.7617419", "0.7615616", "0.7601422", "0.75818425", "0.7577275", "0.7564444", "0.75369376", "0.7499334", "0.748712" ]
0.86788327
0
Adds a handler to the reactor. A handler is a callable taking a single argument, the message.
def add_handler(handler) @handlers << handler end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_message_handler(&block)\n @message_handlers << block\n end", "def add_handler(name, handler)\n subscribe(name)\n subscriptions[name].handlers << handler\n end", "def handler\n @handlers.push(proc do |msg|\n yield msg\n end)\n end", "def add_handler(new_handler)\n @handlers.push(new_handler)\n end", "def add_handler(handler)\n h, options = *(handler.is_a?(Array) ? handler : [handler, {}])\n name = coerce_handler(h)\n global_opts = { output: @output, config: @config }\n opts = global_opts.merge(options)\n ready_handler = name.new(opts)\n @ready_handlers << ready_handler\n end", "def add_handler(opts={})\n end", "def add_handler(type, callable=nil, &b)\n callable = callable(callable, b)\n regex = regex_for(type)\n sync do\n id = @handler_serial+=1\n handlers << [id, regex, callable]\n id\n end\n end", "def register(handler)\n conf = @config\n bot = self\n isaac = @bot\n\n @bot.register{|type, msg|\n begin\n $log.debug \"Received message: #{type} #{msg}\"\n handler.dispatch(type, msg, bot.clone_state(msg)) # TODO: send a binding?\n rescue Exception => e\n $log.warn e.to_s\n $log.debug e.backtrace.join(\"\\n\")\n end\n }\n end", "def on_message_call handler\n @@handler_symbol = handler\n end", "def register_inbound_handler(handler)\n\t\t@inbound_handlers << handler\n\tend", "def handle(handler, *guards, &block)\n client.register_handler handler, *guards, &block\n end", "def on_message(&handler)\n @on_message_handler = handler\n end", "def add_handler(opts={})\n return if not payload_instance\n return if not handler_enabled?\n payload_instance.add_handler(opts)\n end", "def set_message_handler &block\n @message_handler = block\n end", "def register_handler(handler)\n handler.handled_events.each do |event_type|\n (event_handlers[event_type] ||= []) << handler\n Twitch::Bot::Logger.debug \"Registered #{handler} for #{event_type}\"\n end\n end", "def __set_handler(handler)\n @__handler = handler\n end", "def setup_method_handler(method_handler)\n @handler = method_handler\n end", "def set_message_handler(&block); end", "def handler(name, handler)\n # Construct an instance, if the handler is a class and needs to be initialized.\n handler = handler.new\n\n # Make sure it quacks like a handler.\n unless handler.respond_to?(:generate) && handler.respond_to?(:parse)\n raise ArgumentError, \"Media type handlers must respond to #generate and #parse\"\n end\n\n # Register that thing!\n @handlers[name.to_s] = handler\n end", "def make_handlers(*args)\r\n make :handler, *args\r\n end", "def message_handler(&message_proc)\n @message_proc = message_proc\n end", "def add_response_handler(&block)\n Listener.new(&block).tap do |listener|\n listener.stopback{ listener.succeed }\n add_to_listener_pool(listener)\n end\n end", "def register(*args, &block)\n h = Unobservable.handler_for(*args, &block)\n @handlers << h\n return h\n end", "def attach handler\n raise ArgumentError, \"Handler must provide an 'on_attach' method\" unless handler.respond_to? :on_attach\n handler.on_attach self\n end", "def handle(name, r_type, expr, &block)\n @handlers.push({name: name, methods: r_type, expr: expr, handler: block})\n end", "def new_handler\n handler.new(event)\n end", "def define_handler(*extensions, &block)\n @handlers += extensions.map { |ext| [ext, block] }\n end", "def with_handler(handler = current_handler)\n begin\n if handler != current_handler\n old_handler = current_handler\n set_current_handler handler\n end\n\n handlers[current_handler].tap do |h|\n return yield h if block_given?\n end\n ensure\n set_current_handler old_handler if old_handler\n end\n end", "def <<(command_handler)\n command_handler.commands.each do |command|\n @commands[command] = command_handler\n end\n end", "def register_handler\n @register_handler ||= Justdi::RegisterHandler\n end" ]
[ "0.7231306", "0.70802605", "0.6918257", "0.67517906", "0.6619087", "0.6497206", "0.6444436", "0.64262986", "0.63075036", "0.6248153", "0.621285", "0.6183933", "0.617584", "0.61286837", "0.5891722", "0.5729914", "0.5725149", "0.5690471", "0.56413794", "0.5638347", "0.5552255", "0.5513339", "0.55046207", "0.5499442", "0.54946107", "0.5435877", "0.53842777", "0.5375725", "0.5343435", "0.5329399" ]
0.7232581
0
GET /recovery_passwords GET /recovery_passwords.json
def index @recovery_passwords = RecoveryPassword.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @passwords = current_user.passwords\n end", "def password\n respond_to do |format|\n format.html\n format.json { render json: { :password => get_password } }\n end\n end", "def forgot_password\n user = validate_user(params['forgot_username'])\n\n devices = get_mfa_devices(user.id)\n\n status = user ? :ok : :not_found\n\n render json: devices, status: status\n end", "def new_user_password\n client = Client.where(recovery_token: params[:recovery_token]).first\n\n if(client)\n render \"home/change_password_template\", layout: \"application\"\n else\n render \"home/change_password_template_error\"\n end\n\n end", "def index\n @xmt_mgr_passwords = Xmt::Password.all\n end", "def recover_password\n person = Person.find_by_email(params[:email])\n\n if person\n UserMailer.recovery(:key => CryptoHelper.encrypt(\"#{person.id}:#{person.salt}\"),\n :email => person.email,\n :username => person.username,\n :domain => APP_CONFIG.server_domain).deliver\n render_json :messages => \"Recovery mail sent to specified address.\", :status => :ok and return\n else\n render_json :messages => \"Record not found.\", :status => :not_found and return\n end\n\n end", "def index\n @passwords = Password.all;\n end", "def password_rest\n UserMailer.password_rest\n end", "def passwords_file\n dir['passwords']\n end", "def form_passwords(form) # Implement this in Form class\r\n { \r\n :passwords => [ \r\n form['password'],\r\n form['confirm_password']\r\n ]\r\n }\r\n end", "def set_recovery_password\n @recovery_password = RecoveryPassword.find(params[:id])\n end", "def zone_passwords(zone_name)\n parameters = \"zone=#{zone_name}\"\n request(:get, \"/api/zone/passwords?#{parameters}\")\n end", "def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end", "def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end", "def password_recovery(email, subject = \"CakeMail Password Recovery\", text = \"Your password is: \")\n session.request(\"CakeMail::API::ClassUser\", \"PasswordRecovery\", { :email => email, :subject => subject, :text => text })\n end", "def recover_password(new_password)\n url = \"user/#{user_sys_name}/#{user_id}/recovery/?\"\n request = { newPassword: new_password }\n response = Uas::Query.execute(url, request: request, method: :put)\n case response[:code]\n when 200 then true\n else false\n end\n end", "def recover_password\n raise Webapp::UserSessionExistsError if user_session\n if request.get?\n @handle_or_user_name = \"\" \n \n elsif request.post?\n @handle_or_user_name = params[:handle_or_email]\n raise Webapp::BadParametersError if @handle_or_user_name.nil? || @handle_or_user_name.empty?\n user = User.find_by_handle_or_email(@handle_or_user_name)\n #Should create a PasswordRecovery\n password_recovery = PasswordRecovery.create_password_recovery(user.id)\n #Should send an email\n UserMailer.deliver_recover_password_instructions(user)\n #TODO: Check why the message does not apears correctly in Web GUI\n #message = sprintf(t(:recover_password_instructions_sent),\n flash_notice(:recover_password_instructions_sent,user.email)\n redirect_to root_url\n #should flash a message and redirect to root_url\n \n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n \n rescue Webapp::UserSessionExistsError\n logger.error \"Attempt to recover a password within a user session. Client IP: \"+request.remote_ip\n flash_error(:user_session_exists)\n redirect_to root_url\n rescue Webapp::BadParametersError, ActiveRecord::RecordNotFound\n logger.error(\"Attempt to recover a password but email or user name was not provided or not found Email or Name was #{@email_or_user_name}. Client IP:\"+request.remote_ip)\n flash_error(:invalid_login_name_or_email)\n redirect_to recover_password_url\n end", "def recover_password\n begin\n @user = User.find_by_email(params[:user][:email])\n UserMailer.send_password_recovery_mail(@user,\n edit_password_path(@user.authentication_token),\n request.host_with_port) \n flash[:notice] = \"We have sent the password to your email.\"\n rescue Exception => e\n flash[:notice] = \"We have sent the password to your email.\"\n end\n redirect_to root_path\n end", "def password_recovery\n session[:user_id] = nil\n id = params[:uhash].slice(0, params[:uhash].length-40)\n @user = User.find_by_id(id)\n if not @user or (@user.id.to_s + Digest::SHA1.hexdigest(\"YA\" + @user.email + \"YA\") != params[:uhash])\n return render :text => \"Link is not valid or expired\"\n end\n r = Recovery.find_by_user_id(@user[:id])\n if not r or r[:recover_hash] != params[:hash] or (Time.now - r.updated_at) > 1.day\n return render :text => \"Link is not valid or expired\"\n end\n r.destroy\n session[:user_id] = @user.id\n session[:recovery] = true\n redirect_to schedule_url\n end", "def pw_admin\n @user = User.find(params[:id])\n new_password = Devise.friendly_token(50)\n user.reset_password(new_password, new_password)\n user.send_rest_password_instructions\n end", "def password\n if !@password_insync && resource[:api_admin] == :true\n update_admin_pass_with_rake\n end\n return resource[:password] if @password_insync\n return nil\n end", "def get_password(type, key, password = nil)\n if ['db', 'user', 'service'].include?(type)\n secret node['openstack']['secret'][\"#{type}_passwords_data_bag\"], key, password\n else\n ::Chef::Log.error(\"Unsupported type for get_password: #{type}\")\n end\n end", "def get_password(type, key)\n unless [:db, :user, :service, :token].include?(type)\n Chef::Log.error \"Unsupported type for get_password: #{type}\"\n return\n end\n\n if node[:garcon][:use_databags]\n if type == :token\n secret node[:garcon][:secret][:secrets_data_bag], key\n else\n secret node[:garcon][:secret][\"#{type}_passwords_data_bag\"], key\n end\n else\n node[:garcon][:secret][key][type]\n end\n end", "def password_recovery_instructions\n PharmacistMailer.password_recovery_instructions\n end", "def password\n Password.find(password_id)\n end", "def guess_http_password(attempt)\n HTTParty.get(\n \"http://localhost:3001/bank/vault\",\n headers: {\n \"Authorization\" => \"Token token=#{attempt}\"\n }\n ).success?\n end", "def update\n begin\n _params = update_password_params\n if _params[:password].length < Devise.password_length.min\n render json: {errors: [\"Too short password.\"]}, status: :bad_request\n return\n elsif _params[:password].length > Devise.password_length.max\n render json: {errors: [\"Too long password.\"]}, status: :bad_request\n return\n end\n user = User.reset_password_by_token(_params)\n render json: user, status: :ok\n rescue => e\n logger.error(\"Password update failed. #{e.message}\")\n render json: {errors: [\"Password update failed.\"]}, status: :internal_server_error\n return\n end\n end", "def password_recovery_fail\n PharmacistMailer.password_recovery_fail\n end", "def password\n conf['api']['password']\n end", "def password_reset(token)\n get(\"/v1/password_resets/#{token}\")\n end" ]
[ "0.6642948", "0.65952843", "0.6493781", "0.62614274", "0.62520427", "0.62235296", "0.6222507", "0.6112147", "0.605353", "0.6041732", "0.6038329", "0.60291475", "0.59056455", "0.59056455", "0.58997273", "0.5888444", "0.58786786", "0.58556145", "0.5850409", "0.5814593", "0.58043265", "0.5801536", "0.5771085", "0.5765638", "0.57579064", "0.5743724", "0.57374966", "0.572397", "0.57152677", "0.57011557" ]
0.70308644
0
POST /recovery_passwords POST /recovery_passwords.json
def create @recovery_password = RecoveryPassword.new(recovery_password_params) respond_to do |format| if @recovery_password.save format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido creado.' } format.json { render :show, status: :created, location: @recovery_password } else format.html { render :new } format.json { render json: @recovery_password.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n puts 'Recovery password!!!!!!!!!!!!!!!!!!!!!!'\n self.resource = resource_class.send_reset_password_instructions(resource_params)\n\n if successfully_sent?(resource)\n render status: 200, json: nil\n else\n render status: 400, json: { message: 'Invalid email!' }\n # binding.pry\n end\n end", "def new_user_password\n client = Client.where(recovery_token: params[:recovery_token]).first\n\n if(client)\n render \"home/change_password_template\", layout: \"application\"\n else\n render \"home/change_password_template_error\"\n end\n\n end", "def pass_recovery\n @user = TempUser.find_by(username: params[:username])\n @user = User.find_by(username: params[:username]) if !@user\n if @user.present?\n @new_password = SecureRandom.hex(5)\n @user.update(username: params[:username], password: @new_password, password_confirmation: @new_password)\n EmailNotification.send_recovery_email(@user,@new_password)\n render json: { status: 'New password has been sent to your email' }, status: :ok\n else\n render json: { status: 'Invalid username' }, status: :not_found\n end\n end", "def recovery_password_params\n params.require(:recovery_password).permit(:recovery_password_id, :state, :user_id, :token, :progress)\n end", "def create\n @user = @current_tenant.users.find_by_email(params[:email])\n new_password = rand(10000000000000).floor.to_s(36)\n @user.password = new_password\n if @user.save\n UserMailer.forget_password(@user).deliver\n else\n @response[:success] = false\n @status = :unprocessable_entity\n end\n\n render json: @response, status: @status\n end", "def auth_password_healthcheck(payload)\n do_http_request(\n method: 'POST',\n url: AUTH_URL + '/healthcheck/oauth/token',\n headers: {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Accept' => 'application/json',\n 'X-Header' => ''\n },\n payload: payload,\n typeconsistent: true\n )\n end", "def create\n resource = resource_class.send_reset_password_instructions(resource_params)\n\n if successfully_sent?(resource)\n render json: {\n msg: 'Вам были отправлены инструкции по восстановлению пароля'\n }\n else\n render json: {\n msg: resource.errors.full_messages.first,\n errors: resource.errors\n }, status: 403\n end\n end", "def set_recovery_password\n @recovery_password = RecoveryPassword.find(params[:id])\n end", "def create\n @xmt_mgr_password = Xmt::Password.new(xmt_mgr_password_params)\n\n respond_to do |format|\n if @xmt_mgr_password.save\n format.html { redirect_to @xmt_mgr_password, notice: 'Password was successfully created.' }\n format.json { render :show, status: :created, location: @xmt_mgr_password }\n else\n format.html { render :new }\n format.json { render json: @xmt_mgr_password.errors, status: :unprocessable_entity }\n end\n end\n end", "def test_password_invalid_format\n data = { 'email' => '[email protected]', 'password' => 'open123' }\n post '/users', data.to_json\n assert last_response.status.eql?(400)\n end", "def pw_admin\n @user = User.find(params[:id])\n new_password = Devise.friendly_token(50)\n user.reset_password(new_password, new_password)\n user.send_rest_password_instructions\n end", "def reset_password\n if verify_token(params['reset_device_id'], params['reset_otp_token'])\n status = :ok\n response = set_password(session[:user_id], params['new_password'])\n else\n status = :unauthorized\n response = 'Invalid token'\n end\n\n render json: response, status: status\n end", "def recover_password(new_password)\n url = \"user/#{user_sys_name}/#{user_id}/recovery/?\"\n request = { newPassword: new_password }\n response = Uas::Query.execute(url, request: request, method: :put)\n case response[:code]\n when 200 then true\n else false\n end\n end", "def password_reset_request\n end", "def send_pass\n username = params[:user][:account_name]\n email = params[:user][:email]\n resp = LinkedData::Client::HTTP.post(\"/users/create_reset_password_token\", {username: username, email: email})\n\n if resp.nil?\n redirect_to login_index_path, notice: \"Please check your email for a message with reset instructions\"\n else\n flash[:notice] = resp.errors.first + \". Please try again.\"\n redirect_to \"/lost_pass\"\n end\n end", "def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end", "def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end", "def password_recovery_fail\n PharmacistMailer.password_recovery_fail\n end", "def recover_password\n raise Webapp::UserSessionExistsError if user_session\n if request.get?\n @handle_or_user_name = \"\" \n \n elsif request.post?\n @handle_or_user_name = params[:handle_or_email]\n raise Webapp::BadParametersError if @handle_or_user_name.nil? || @handle_or_user_name.empty?\n user = User.find_by_handle_or_email(@handle_or_user_name)\n #Should create a PasswordRecovery\n password_recovery = PasswordRecovery.create_password_recovery(user.id)\n #Should send an email\n UserMailer.deliver_recover_password_instructions(user)\n #TODO: Check why the message does not apears correctly in Web GUI\n #message = sprintf(t(:recover_password_instructions_sent),\n flash_notice(:recover_password_instructions_sent,user.email)\n redirect_to root_url\n #should flash a message and redirect to root_url\n \n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n \n rescue Webapp::UserSessionExistsError\n logger.error \"Attempt to recover a password within a user session. Client IP: \"+request.remote_ip\n flash_error(:user_session_exists)\n redirect_to root_url\n rescue Webapp::BadParametersError, ActiveRecord::RecordNotFound\n logger.error(\"Attempt to recover a password but email or user name was not provided or not found Email or Name was #{@email_or_user_name}. Client IP:\"+request.remote_ip)\n flash_error(:invalid_login_name_or_email)\n redirect_to recover_password_url\n end", "def form_passwords(form) # Implement this in Form class\r\n { \r\n :passwords => [ \r\n form['password'],\r\n form['confirm_password']\r\n ]\r\n }\r\n end", "def new_reset_password\n end", "def request_new_password(name)\n values = {\n name: name\n }\n @client.make_request :post,\n auth_path('request_new_password'),\n values\n end", "def forgot_password\n user = validate_user(params['forgot_username'])\n\n devices = get_mfa_devices(user.id)\n\n status = user ? :ok : :not_found\n\n render json: devices, status: status\n end", "def password_rest\n UserMailer.password_rest\n end", "def create\n auth_key = self.class.klass.auth_key\n auth_password = self.class.klass.auth_password\n valid_key = self.class.klass.valid_key\n current_authable = self.class.klass.send(:find_by!, auth_key => reset_password_params[auth_key])\n current_authable.reset_password(reset_password_params[auth_password], reset_password_params[valid_key])\n render json: { meesage: \"reset password successful\"}, status: 200\n rescue UserError => e\n render json: { error: e.message }, status: e.status\n end", "def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n p[:password_unset] = 0 \n update_attributes(p)\n end", "def password\n respond_to do |format|\n format.html\n format.json { render json: { :password => get_password } }\n end\n end", "def create_new_password\n pass = generate_password\n set_password(pass)\n pass\n end", "def password_recovery_success\n PharmacistMailer.password_recovery_success\n end", "def password_recovery_instructions\n PharmacistMailer.password_recovery_instructions\n end" ]
[ "0.6374773", "0.62566763", "0.62361735", "0.62082964", "0.61124355", "0.6088549", "0.6035341", "0.60332566", "0.60098505", "0.5997153", "0.59957033", "0.59919095", "0.5968382", "0.59658456", "0.59611714", "0.59586763", "0.59586763", "0.5920181", "0.59013224", "0.5885759", "0.58809954", "0.58797616", "0.5876884", "0.5875616", "0.5871806", "0.58671063", "0.5846309", "0.5831486", "0.58193415", "0.5815538" ]
0.66673905
0
DELETE /recovery_passwords/1 DELETE /recovery_passwords/1.json
def destroy @recovery_password.destroy respond_to do |format| format.html { redirect_to recovery_passwords_url, notice: 'Recovery password ha sido eliminado.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @password.destroy\n respond_to do |format|\n format.html { redirect_to passwords_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @xmt_mgr_password.destroy\n respond_to do |format|\n format.html { redirect_to xmt_mgr_passwords_url, notice: 'Password was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @secure_password.destroy\n respond_to do |format|\n format.html { redirect_to dashboard_index_path, notice: 'Secure password was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @password_setting.destroy\n respond_to do |format|\n format.html { redirect_to password_settings_url }\n format.json { head :no_content }\n end\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @password = Password.find(params[:id])\n @password.destroy\n\n respond_to do |format|\n format.html { redirect_to(passwords_url) }\n format.xml { head :ok }\n end\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 destroy\n @pass = Passbook::Pass.where(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first\n head :not_found and return if @pass.nil?\n head :unauthorized and return if request.env['HTTP_AUTHORIZATION'] != \"ApplePass #{@pass.authentication_token}\"\n\n @registration = @pass.registrations.where(device_library_identifier: params[:device_library_identifier]).first\n head :not_found and return if @registration.nil?\n\n @registration.destroy\n\n head :ok\n end", "def destroy\n @password_tier.destroy\n respond_to do |format|\n format.html { redirect_to password_tiers_url, notice: 'PasswordTier was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @secret.destroy\n respond_to do |format|\n format.html { redirect_to secrets_url, notice: 'El secreto se eliminó correctamente.' }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n # @credential.destroy\n # respond_to do |format|\n # format.html { redirect_to credentials_url, notice: 'Credential was successfully destroyed.' }\n # format.json { head :no_content }\n # end\n end", "def destroy\n if params[:admin_password] == ENV[\"ADMIN_PASSWORD\"]\n @keg.destroy\n respond_to do |format|\n format.html { redirect_to Keg, notice: \"Le fût a été supprimé.\"}\n format.json { head :no_content }\n end\n end\n end", "def delete_user_for_tenant(args = {}) \n delete(\"/tenants.json/#{args[:tenantId]}/users/#{args[:userId]}\", args)\nend", "def destroy\n @recovery.destroy\n respond_to do |format|\n format.html { redirect_to recoveries_url, notice: 'Recovery was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @secret_key.destroy\n respond_to do |format|\n format.html { redirect_to secret_keys_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @credential_key.destroy\n respond_to do |format|\n format.html { redirect_to credential_keys_url, notice: 'Credential key was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def webhelper_delete_all_signing_keys(username, password, base_url = @base_url)\r\n private_resource = RestClient::Resource.new base_url + \"/api/v1/keys\", {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.get :accept => :json\r\n json = JSON.parse(response)\r\n\r\n puts \"\"\r\n # delete ios signing_keys\r\n puts \"+ Delete iOS signing-key: \"\r\n json['keys']['ios']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n # delete android signing_keys\r\n puts \"+ Delete Android signing-key: \"\r\n json['keys']['android']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n # delete blackberry signing_keys\r\n puts \"+ Delete BlackBerry signing-key: \"\r\n json['keys']['blackberry']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n end", "def destroy\n @credential.destroy\n respond_to do |format|\n format.html { redirect_to credentials_url, notice: 'Credential was successfully destroyed.' }\n format.json { head :no_content }\n end\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 remove\n get_credentials\n begin\n response = resource[\"/remove/#{app}\"].post(:apikey => @credentials[1])\n rescue RestClient::InternalServerError\n display \"An error has occurred.\"\n end\n display response.to_s\n end", "def destroy\n \n keystone.delete_tenant(keystone.get_tenant(params[:id])[:id])\n\n respond_to do |format|\n format.html { redirect_to tenants_url }\n format.json { head :ok }\n end\n end", "def destroy\n @passwordrepository.destroy\n respond_to do |format|\n format.html { redirect_to passwordrepositories_url, notice: 'Passwordrepository was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def http_delete(opts={})\n ret=http_delete_low(opts)\n if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then\n\tauthdefault\n\tret=http_delete_low(opts)\n\treturn ret\n else\n\treturn ret\n end\n end", "def destroy\n @swift_api_key.destroy\n respond_to do |format|\n format.html { redirect_to swift_api_keys_url, notice: 'Swift api key was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @login_key = LoginKey.find(params[:id])\n @login_key.destroy\n\n respond_to do |format|\n format.html { redirect_to login_keys_url }\n format.json { head :no_content }\n end\n end", "def delete(path)\n RestClient.delete request_base+path\n end", "def destroy\n @keystore.destroy\n respond_to do |format|\n format.html { redirect_to keystores_url, notice: 'Keystore was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def deleteLogin( login_id)\n params = Hash.new\n params['login_id'] = login_id\n return doCurl(\"delete\",\"/login\",params)\n end", "def destroy\n debug(\"#{self.class}::destroy\")\n\n #Retrieval of key\n if ((defined? $key) && !(($key.nil?) || ($key.empty?)))\n Puppet.debug('INFO: key already provided as a command parameter ' + $key)\n\n elsif (!($name.to_s.empty?) )\n\n #Retrieve key\n uriAttributeMap1 = {}\n uriAttributeMap1[:name] = $name\n resourceType = \"storage-service-levels\"\n $key = self.retrieveKeyOfObjectType('/api/1.0/slo/storage-service-levels', resourceType, uriAttributeMap1)\n\n end\n\n\n apiUri = '/api/1.0/slo/storage-service-levels/'+$key\n resourceType = \"storageservicelevel\"\n\n if(transport.http_delete_request(apiUri ,resourceType))\n if(resource[:name] != null)\n puts \"#{resourceType} : #{resource[:name]} successfully deleted\"\n\t\t\telse\n\t\t\t puts \" #{resourceType} successfully deleted\"\n\t\t\tend\n else\n if(resource[:name] != null)\n puts \" #{resourceType} : #{resource[:name]} deletion failed\"\n\t\t else\n\t\t\t puts \" #{resourceType} deletion failed\"\n\t\t end\n end\n\nend" ]
[ "0.69135994", "0.65709585", "0.6546936", "0.6473401", "0.63672", "0.6350938", "0.63128436", "0.6280077", "0.6279821", "0.62780744", "0.6257426", "0.62523204", "0.6236595", "0.6233573", "0.61981446", "0.6159638", "0.61543375", "0.61443245", "0.6133967", "0.6116662", "0.60867435", "0.6082456", "0.6075214", "0.6072639", "0.6056436", "0.6052998", "0.60352355", "0.6033643", "0.60070413", "0.6006934" ]
0.69258785
0
== Constraints Chef libraries are evaluated before the recipe that places the chef_gem that it needs is put into place. This places two constraints on this library: 1) A 'require' must be done in a method 2) This class cannot use 'Subclass < Superclass' As Net::LDAP is a class it cannot be included as a module
def initialize require 'rubygems' require 'net-ldap' require 'cicphash' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def conscientious_require; end", "def load_cloudflare_cookbook_gems\n return if defined? @@cloudflare_cookbook_gems_loaded\n chef_gem 'cloudflare' do\n action :install\n version '2.0.1'\n end\n require 'resolv'\n require 'cloudflare'\n @@cloudflare_cookbook_gems_loaded = true\nend", "def require_gems; end", "def require(*args)\n super\n case args\n when [\"stripe\"]\n # so we don't have to shell out to uname\n ::Stripe.class_variable_set(:@@uname, 'Linux Codecademy codex-adapter x86_64 GNU/Linux')\n\n # gem hard-codes their own bundled ca file, which we need to override\n ::Stripe.class_variable_set(:@@ssl_bundle_path, '/etc/ssl/certs/ca-certificates.crt')\n when [\"twilio-ruby\"]\n Twilio::REST::Client::DEFAULTS[:ssl_ca_file] = '/etc/ssl/certs/ca-certificates.crt'\n end\n end", "def install_bootloader\n raise RuntimeError, \"Not implemented in base class\"\n end", "def hook_require!\n hook_instance_require!\n hook_singleton_require!\n end", "def require_with_grace(r) require r; rescue LoadError; block_given? ? yield : abort(\"#{$!.message}\\n\\n try executing: gem install '#{r}'\") end", "def pleaserun_setup\n chef_gem 'pleaserun' do\n compile_time true\n version '>= 0.0.30'\n end\n\n require 'pleaserun/namespace'\n require 'pleaserun/platform/base'\n\n target_platform = platform\n target_platform_version = platform_version || target_version\n\n if target_platform.nil? || target_platform.empty?\n require 'pleaserun/detector'\n if target_platform_version.nil?\n target_platform, target_platform_version = PleaseRun::Detector.detect\n else\n target_platform = PleaseRun::Detector.detect\n end\n Chef::Log.info \"[dropwizard_pleaserun] autodetected #{target_platform} \" \\\n \"/ #{target_platform_version}\"\n end\n\n Chef::Log.info \"[dropwizard_pleaserun] platform: #{target_platform} / \" \\\n \"version: #{target_platform_version}\"\n\n require \"pleaserun/platform/#{target_platform}\"\n platform_klass = load_platform(target_platform)\n\n pr = platform_klass.new(target_platform_version.to_s)\n pr.name = app_name\n pr.user = user unless user.nil?\n pr.group = group unless group.nil?\n pr.description = description unless description.nil?\n pr.umask = umask unless umask.nil?\n pr.runas = runas unless runas.nil?\n pr.chroot = chroot unless chroot.nil?\n pr.chdir = chdir unless chdir.nil?\n pr.nice = nice unless nice.nil?\n pr.prestart = prestart unless prestart.nil?\n pr.program = program\n pr.args = args unless args.empty?\n pr.log_directory = log_directory unless log_directory.nil?\n\n pr\nend", "def require_chef_vault!\n @require_chef_vault ||=\n begin\n error_message = \"Knife bootstrap requires version 2.6.0 or higher of the chef-vault gem to configure vault items\"\n require \"chef-vault\"\n if Gem::Version.new(ChefVault::VERSION) < Gem::Version.new(\"2.6.0\")\n raise error_message\n end\n\n true\n rescue LoadError\n raise error_message\n end\n end", "def required_if_used(*args)\n unless @required_gems\n [:included, :extended, :inherited].each do |method_name|\n define_method(method_name) do |klass|\n super if defined?(super)\n @required_gems.each { |gem| require gem.to_s }\n end\n end\n end\n @required_gems ||= []\n @required_gems |= args\n end", "def initialize\n super\n require 'ipaddr'\n require 'socket'\n require 'openssl'\n require 'digest'\n require 'securerandom'\n end", "def initialize\n super\n\t \n require 'base64'\n require 'digest'\n require 'json'\n require 'net/http'\n require 'net/https'\n require 'openssl'\n require 'rexml/document'\n require 'securerandom'\n require 'socket'\n require 'uri'\n require_relative 'omslog'\n require_relative 'oms_configuration'\n require_relative 'oms_common'\n end", "def initialize(name, run_context = nil)\n super\n @provider = Chef::Provider::Package::Rubygems\n end", "def add_poolparty_base_requirements\n heartbeat\n haproxy\n ruby\n poolparty_base_packages\n realize_plugins!(true) # Force realizing of the plugins\n end", "def platform_require\n fail NotImplementedError,\n 'Abstract method must returns `Gem::Requirement`'\n end", "def hook_require!\n @hooking_require = true\n\n # There are two independent require methods. Joy!\n ::Kernel.module_eval do\n class << self\n orig_public_require = Kernel.public_method(:require)\n define_method(:require) do |path, *args|\n ::Bumbler::Hooks.handle_require(path) do\n orig_public_require.call(path, *args)\n end\n end\n end\n\n orig_instance_require = self.instance_method(:require)\n define_method(:require) do |path, *args|\n ::Bumbler::Hooks.handle_require(path) do\n orig_instance_require.bind(self).call(path, *args)\n end\n end\n end\n\n @hooking_require = nil\n end", "def init\n clone_appd_cookbook\n chef_gem \"install berkshelf\"\n end", "def install_dependencies\n recipe_eval do\n run_context.include_recipe 'chef-sugar::default'\n run_context.include_recipe 'build-essential::default'\n\n case node.platform_family\n when 'debian'\n package 'curl'\n package 'git-core'\n package 'libxml2-dev'\n package 'libxslt-dev'\n package 'zlib1g-dev'\n package 'ncurses-dev'\n package 'libssl-dev'\n when 'freebsd'\n package 'textproc/libxml2'\n package 'textproc/libxslt'\n package 'devel/ncurses'\n when 'mac_os_x'\n run_context.include_recipe 'homebrew::default'\n package 'libxml2'\n package 'libxslt'\n package 'openssl'\n when 'rhel'\n package 'curl'\n package 'bzip2'\n package 'file'\n package 'git'\n package 'libxml2-devel'\n package 'libxslt-devel'\n package 'ncurses-devel'\n package 'zlib-devel'\n package 'openssl-devel'\n end\n end\n end", "def require!\n yield if block_given?\n require @require_path\n rescue LoadError => exception\n @error = exception\n @satisfied = false\n else\n @error = nil\n @satisfied = true\n end", "def require!\n super do\n gem @gem_name, @version if @version\n end\n end", "def install!\n include_recipe 'zypper'\n super\n end", "def setup_class_dsl(tool_class)\n return if tool_class.name.nil? || tool_class.is_a?(DSL::Tool)\n class << tool_class\n alias_method :super_include, :include\n end\n tool_class.extend(DSL::Tool)\n end", "def do_requires()\n require 'rack'\n require './lib/my_thin.rb'\n require './android_translation_helper.rb'\nend", "def bootstrap_require\n def RC.required(feature)\n config = RC.configuration[feature]\n if config\n config.each do |config|\n next unless config.apply_to_feature?\n config.call\n end\n end\n super(feature) if defined?(super)\n end\n end", "def required_rock_packages\n raise \"#{self.class} needs to overwrite required_rock_packages\"\n end", "def require_dependency_with_check(dependency)\n begin\n require dependency\n rescue LoadError => e\n puts \"You need to install #{dependency} before we can proceed\"\n end\nend", "def install_chef_gem(nr)\n # let chef_gem install the gem for us\n at_compile_time do\n chef_gem nr.gem_name do\n %w(options version source).each do |attr|\n value = new_resource.send(attr.to_sym)\n send(attr.to_sym, value) unless value.nil?\n end\n end\n end\n end", "def load_classifier()\n auth_info = {\n 'ca_certificate_path' => Puppet[:localcacert],\n 'certificate_path' => Puppet[:hostcert],\n 'private_key_path' => Puppet[:hostprivkey],\n }\n unless @classifier\n load_classifier_config\n @classifier = PuppetClassify.new(@classifier_url, auth_info)\n end\nend", "def load_minimal_gems\r\n end", "def install\n # Switch this to use Module#prepend at some point when I stop caring about Ruby 1.9.\n ::Berkshelf::Berksfile.class_exec do\n old_sources = instance_method(:sources)\n define_method(:sources) do\n original_sources = begin\n old_sources.bind(self).call\n rescue ::Berkshelf::NoAPISourcesDefined\n # We don't care, there will be a source\n []\n end\n # Make sure we never add two halite sources.\n original_sources.reject {|s| s.is_a?(::Halite::Berkshelf::Source) } + [::Halite::Berkshelf::Source.new(self)]\n end\n end\n\n # Inject support for the :halite location type\n ::Berkshelf::Downloader.class_exec do\n old_try_download = instance_method(:try_download)\n define_method(:try_download) do |source, name, version|\n remote_cookbook = source.cookbook(name, version)\n if remote_cookbook && remote_cookbook.location_type == :halite\n tmp_dir = Dir.mktmpdir\n Halite.convert(remote_cookbook.location_path, tmp_dir)\n tmp_dir\n else\n old_try_download.bind(self).call(source, name, version)\n end\n end\n end\n\n end" ]
[ "0.6480207", "0.64590555", "0.62435687", "0.6108768", "0.6097916", "0.6090847", "0.6049699", "0.6030041", "0.60176545", "0.6016308", "0.5910933", "0.5820359", "0.57835615", "0.57699853", "0.5769488", "0.5702365", "0.5679358", "0.56678206", "0.56448567", "0.5639703", "0.55822486", "0.55593985", "0.5543125", "0.55209076", "0.55100465", "0.5483127", "0.54654026", "0.54618347", "0.54580754", "0.54530054" ]
0.66525275
0
== Bind This method should not be used directly. It is used to bind to the directory server. The databag_name is the name of the databag that is used for looking up connection credentials. It returns a connected ruby Net::LDAP object
def bind( host, port, credentials, databag_name, use_tls ) # :yields: host, port, credentials, databag_name, use_tls credentials = credentials.kind_of?(Hash) ? credentials.to_hash : credentials.to_s unless databag_name.kind_of?(String) or databag_name.kind_of?(Symbol) raise "Invalid databag_name: #{databag_name}" end if credentials.kind_of?(String) and credentials.length > 0 # Pull named credentials from the databag require 'chef/data_bag_item' require 'chef/encrypted_data_bag_item' secret = Chef::EncryptedDataBagItem.load_secret credentials = Chef::EncryptedDataBagItem.load( databag_name.to_s, credentials, secret ).to_hash end unless credentials.kind_of?(Hash) and credentials.key?('bind_dn') and credentials.key?('password') raise "Invalid credentials: #{credentials}" end args = { host: host, port: port, auth: { method: :simple, username: credentials['bind_dn'], password: credentials['password'] } } args[:encryption] = :simple_tls if use_tls @ldap = Net::LDAP.new args raise "Unable to bind: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message == 'Success' @ldap end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bind\n conn = Net::LDAP.new :host => @config[:server],\n :port => @config[:port],\n :base => @config[:base]\n if @config[:encryption]\n conn.encryption @config[:encryption]\n end\n \n raise \"Anonymous Bind is disabled\" if @config[:password] == \"\" && !(@config[:anonymous_bind])\n \n conn.auth \"#{@config[:username]}@#{@config[:domain]}\", @config[:password]\n \n begin\n Timeout::timeout(10){\n if conn.bind\n return conn\n else\n raise 'Query User Rejected'\n end\n }\n rescue Timeout::Error\n raise 'Unable to connect to LDAP Server'\n rescue Errno::ECONNRESET\n if @config[:allow_fallback]\n @config[:port] = @config[:allow_fallback]\n @config[:encryption] = false\n return Adauth::Connection.new(@config).bind\n end\n end\n end", "def bind(login, password)\n cfg = Rails.application.secrets.ldap\n host = cfg['host']\n port = cfg['port']\n ssl = cfg['ssl'].to_sym\n # base = cfg['base']\n users = cfg['users']\n # groups = cfg['groups']\n\n options = {\n host: host,\n port: port,\n encryption: ssl,\n }\n\n ldap = Net::LDAP.new(options)\n ldap.auth(\"cn=#{login},#{users}\", password)\n return LDAP::User.find(login) if ldap.bind\n false\n end", "def bind_connection(credentials)\n Net::LDAP.new(credentials)\n rescue\n raise(ConnectionError, 'Failure connecting to LDAP host')\n end", "def bind( user_dn, password )\n\t\tuser_dn = user_dn.dn if user_dn.respond_to?( :dn )\n\n\t\tself.log.info \"Binding with connection %p as: %s\" % [ self.conn, user_dn ]\n\t\tself.conn.bind( user_dn.to_s, password )\n\t\t@bound_user = user_dn.to_s\n\tend", "def connect\n @conn ||= Net::LDAP.new\n @conn.host = @host\n @conn.port = @port\n @conn.auth \"#{@login_dn},#{@base_dn}\", @password\n\n if @conn.bind\n return true\n else\n return false\n end\n end", "def ldap_connect\n ldap = Net::LDAP.new(host: host, port: Net::LDAP::DefaultPort)\n ldap\n end", "def ldap_connect(domain,binddn=BINDUSER,bindpw=BINDPASS)\n binddn = binddn + \"@\" + domain\n ldap = Net::LDAP.new(:host => domain,\n :port => 389,\n :auth => {\n :method => :simple,\n :username => binddn,\n :password => bindpw,\n })\n return ldap\n end", "def connect!\n com::unboundid::ldap::sdk::LDAPConnection.new(\n self.host, self.port, self.bind_dn, self.password) \n end", "def open(host, user = nil, password = nil)\n @ldap = Net::LDAP.new\n @ldap.host = host\n @ldap.port = 389\n @ldap.auth(user, password)\n @ldap.bind\n end", "def authenticate_dn(dn, password)\n\t\tif dn.present? && password.present?\n\t\t\tinitialize_ldap_con(dn, password).bind\n\t\tend\n\tend", "def new_net_ldap\n params = {\n :host => host,\n :auth => authentication_information,\n :port => 636,\n :encryption => { :method => :simple_tls }\n }\n @net_ldap = Net::LDAP.new(params)\n @net_ldap.bind || raise(BindFailedException)\n @net_ldap\n rescue Net::LDAP::Error => e\n raise(BindFailedException)\n end", "def client\n Net::LDAP.new({\n host: Settings.ldap.host,\n port: Settings.ldap.port,\n encryption: { method: :simple_tls },\n auth: {\n method: :simple,\n username: Settings.ldap.application_bind,\n password: Settings.ldap.application_password\n }\n })\n end", "def connection\n return @connection if @connection\n load_ldap_library\n @connection = if ldap_library == 'net/ldap'\n Net::LDAP.new(:host=>server, :port=>(port), :encryption=>(:simple_tls if use_ssl))\n else\n (use_ssl ? LDAP::SSLConn : LDAP::Conn).new(server, port)\n end\n end", "def bound_as( user_dn, password )\n\t\traise LocalJumpError, \"no block given\" unless block_given?\n\t\tprevious_bind_dn = @bound_user\n\t\tself.with_duplicate_conn do\n\t\t\tself.bind( user_dn, password )\n\t\t\tyield\n\t\tend\n\tensure\n\t\t@bound_user = previous_bind_dn\n\tend", "def bind_to_directory\n\t\tbinddn = self.options.binddn or\n\t\t\traise ArgumentError, \"no binddn in the options hash?!\"\n\t\tself.log.debug \"Attempting to bind to the directory as %s\" % [ binddn ]\n\n\t\tpass = self.prompt.ask( \"password: \" ) {|q| q.echo = '*' }\n\t\tuser = Treequel::Branch.new( self.directory, binddn )\n\n\t\tself.directory.bind_as( user, pass )\n\t\tself.log.debug \" bound as %s\" % [ user ]\n\n\t\treturn true\n\tend", "def connect_to_ldap\r\n begin\r\n @ldap = Net::LDAP.new(:host => @ldap_host,\r\n :port => @ldap_port,\r\n :auth => { :method => :simple,\r\n :username => @ldap_username,\r\n :password => @ldap_password } )\r\n @logger.info \"Connecting to LDAP: '#{@ldap_host}' on port #{@ldap_port}\"\r\n @logger.info \"Binding to LDAP as: #{@ldap_username}\"\r\n \r\n success = @ldap.bind()\r\n if (success)\r\n @logger.info \"LDAP authorization succeeded\"\r\n return true\r\n else\r\n @logger.error \"LDAP authorization failed: #{@ldap.get_operation_result.message}\"\r\n return false\r\n end\r\n rescue Net::LDAP::LdapError => error\r\n @logger.error(\"Error connecting to LDAP: #{error}\")\r\n return false\r\n end\r\n end", "def ldap\n @attributes[:ldap]\n end", "def net_ldap\n @net_ldap ||= new_net_ldap\n end", "def ldap_server\n get_attribute_from_auth_source('host')\n end", "def initialize_ldap_con(username, password, hosts)\n result = nil\n\n hosts.each do |host|\n ldap = Net::LDAP.new({\n :host => host,\n :port => 389,\n :auth => {\n :method => :simple,\n :username => username,\n :password => password\n }\n })\n\n # If the bind succeeded, return the active connection. Else try the next host\n result = ldap if ldap.get_operation_result.code == 0\n end\n\n return result\n end", "def bind_by_username\n username_attribute = options[:ldap][:username_attribute] || default_username_attribute\n\n @ldap.bind_as(:base => @options[:ldap][:base], :password => @password, :filter => user_filter)\n end", "def authenticate_with_active_directory(username, password)\n auth_ldap = ADMapper::Connection.current_connection.dup.bind_as(\n :filter => Net::LDAP::Filter.eq( \"sAMAccountName\", username ),\n :base => ADMapper::Connection.treebase,\n :password => password\n )\n \n end", "def ldap?(auth, username, password)\n require 'net/ldap'\n\n raise 'Missing ldap base' unless auth[:base]\n\n @ldap = Net::LDAP.new auth\n\n raise format('Ldap connexion fail %s', ldap.inspect) unless ldap.bind\n\n dn = ldap_search(auth[:base], filer_strip(auth[:filter], username))\n ldap.authenticate(dn, password)\n session[:user] = username if ldap.bind\n !session[:user].nil?\n end", "def authenticate(dn, password)\n if @conn.bind(:username => \"#{dn},#{@base_dn}\", :password => password)\n @conn.bind \"#{@login_dn},#{@base_dn}\", @password\n return true\n else\n return false\n end\n end", "def bind_by_username_with_preauthentication\n raise CASServer::AuthenticatorError, \"A password must be specified in the configuration for the authenticator user!\" unless\n @options[:ldap][:auth_password]\n\n @ldap.authenticate(@options[:ldap][:auth_user], @options[:ldap][:auth_password])\n\n @ldap.bind_as(:base => @options[:ldap][:base], :password => @password, :filter => user_filter)\n end", "def valid?(auth)\n # how to connect to the ldap server: ldap, ldaps, ldap + starttls\n if @config.ldaps\n enc = { method: :simple_tls }\n elsif @config.starttls\n enc = { method: :start_tls }\n enc[:tls_options] = @config.tls_options if @config.tls_options\n else\n enc = nil # just straight ldap\n end\n conn = Net::LDAP.new(host: @config.hostname, port: @config.port,\n base: @config.basedn,\n encryption: enc)\n\n $stdout.puts \"Net::LDAP.new => #{conn.inspect}\" if @config.debug\n\n if @config.auth\n $stdout.puts \"doing auth for #{@config.rootdn.inspect}\" if @config.debug\n conn.auth @config.rootdn, @config.passdn\n # conn.get_operation_result.message has the reson for a failure\n return false unless conn.bind\n end\n\n filter = Net::LDAP::Filter.eq(@config.username_ldap_attribute,\n auth.username)\n\n $stdout.puts \"Net::LDAP::Filter.eq => #{filter.inspect}\" if @config.debug\n\n # find the user and rebind as them to test the password\n # return conn.bind_as(:filter => filter, :password => auth.password)\n $stdout.puts \"doing bind_as password.size: #{auth.password.size}...\" if @config.debug\n ret = conn.bind_as(filter: filter, password: auth.password)\n $stdout.puts \"bind_as => #{ret.inspect}\" if @config.debug\n ret\n end", "def connection\n unless @connection\n raise Puppet::Error, \"Could not set up LDAP Connection: Missing ruby/ldap libraries\" unless Puppet.features.ldap?\n begin\n conn = Puppet::Util::Ldap::Connection.instance\n conn.start\n @connection = conn.connection\n rescue => detail\n puts detail.backtrace if Puppet[:trace]\n raise Puppet::Error, \"Could not connect to LDAP: #{detail}\"\n end\n end\n\n @connection\n end", "def bind_default_ldap_server(size_limit, domain=nil)\n vprint_status(\"Initializing LDAP connection.\")\n\n # If domain is still null the API may be able to handle it...\n init_result = wldap32.ldap_sslinitA(domain, 389, 0)\n session_handle = init_result['return']\n if session_handle == 0\n raise \"Unable to initialize ldap server: #{init_result[\"ErrorMessage\"]}\"\n end\n\n vprint_status(\"LDAP Handle: #{session_handle}\")\n\n vprint_status(\"Setting Sizelimit Option\")\n wldap32.ldap_set_option(session_handle, LDAP_OPT_SIZELIMIT, size_limit)\n\n vprint_status(\"Binding to LDAP server\")\n bind_result = wldap32.ldap_bind_sA(session_handle, nil, nil, LDAP_AUTH_NEGOTIATE)\n\n bind = bind_result['return']\n unless bind == 0\n wldap32.ldap_unbind(session_handle)\n raise \"Unable to bind to ldap server: #{ERROR_CODE_TO_CONSTANT[bind]}\"\n end\n\n if (block_given?)\n begin\n yield session_handle\n ensure\n vprint_status(\"Unbinding from LDAP service\")\n wldap32.ldap_unbind(session_handle)\n end\n else\n return session_handle\n end\n\n return session_handle\n end", "def start\n case ssl\n when :tls\n @connection = LDAP::SSLConn.new(host, port, true)\n when true\n @connection = LDAP::SSLConn.new(host, port)\n else\n @connection = LDAP::Conn.new(host, port)\n end\n @connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)\n @connection.set_option(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON)\n @connection.simple_bind(user, password)\n rescue => detail\n raise Puppet::Error, \"Could not connect to LDAP: #{detail}\"\n end", "def login(user, pass)\n conn = LDAP::Conn.new($ldap_conf[:server], $ldap_conf[:port])\n conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)\n conn.start_tls\n\n begin\n if conn.bind('uid=' + user + ',' + $ldap_conf[:people_dn], pass)\n get_uidNumber conn, user\n else\n False\n end\n rescue Exception => e\n nil\n end\nend" ]
[ "0.6913362", "0.63650143", "0.6115088", "0.6058074", "0.6005063", "0.6000602", "0.5991074", "0.59695226", "0.5956265", "0.5793615", "0.5700936", "0.5565955", "0.5537644", "0.5522277", "0.5521801", "0.5499361", "0.5465693", "0.5459872", "0.53915536", "0.5391111", "0.53690284", "0.5332073", "0.5296467", "0.52696913", "0.51822764", "0.5179506", "0.51708615", "0.5142381", "0.5118283", "0.5100353" ]
0.7768266
0
== Search This method is used to search the directory server. It accepts the connection resource object described above along with the basedn to be searched. Optionally it also accepts an LDAP filter and scope. The default filter is objectClass= and the default scope is 'base' It returns a list of entries.
def search( c, basedn, *constraints ) # :yields: connection_info, basedn, filter, scope self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap raise "Must specify base dn for search" unless basedn ( filter, scope, attributes ) = constraints filter = filter.nil? ? Net::LDAP::Filter.eq( 'objectClass', '*' ) : filter case scope when 'base' scope = Net::LDAP::SearchScope_BaseObject when 'one' scope = Net::LDAP::SearchScope_SingleLevel else scope = Net::LDAP::SearchScope_WholeSubtree end scope = scope.nil? ? Net::LDAP::SearchScope_BaseObject : scope attributes = attributes.nil? ? [ '*' ] : attributes entries = @ldap.search( base: basedn, filter: filter, scope: scope, attributes: attributes ) raise "Error while searching: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/ return entries end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def query_ldap(session_handle, base, scope, filter, fields)\n vprint_status(\"Searching LDAP directory\")\n search = wldap32.ldap_search_sA(session_handle, base, scope, filter, nil, 0, 4)\n vprint_status(\"search: #{search}\")\n\n if search['return'] == LDAP_SIZELIMIT_EXCEEDED\n print_error(\"LDAP_SIZELIMIT_EXCEEDED, parsing what we retrieved, try increasing the MAX_SEARCH value [0:LDAP_NO_LIMIT]\")\n elsif search['return'] != Error::SUCCESS\n print_error(\"No results\")\n wldap32.ldap_msgfree(search['res'])\n return\n end\n\n search_count = wldap32.ldap_count_entries(session_handle, search['res'])['return']\n\n if search_count == 0\n print_error(\"No entries retrieved\")\n wldap32.ldap_msgfree(search['res'])\n return\n end\n\n print_status(\"Entries retrieved: #{search_count}\")\n\n pEntries = []\n entry_results = []\n\n if datastore['MAX_SEARCH'] == 0\n max_search = search_count\n else\n max_search = [datastore['MAX_SEARCH'], search_count].min\n end\n\n 0.upto(max_search - 1) do |i|\n\n if(i==0)\n pEntries[0] = wldap32.ldap_first_entry(session_handle, search['res'])['return']\n end\n\n if(pEntries[i] == 0)\n print_error(\"Failed to get entry\")\n wldap32.ldap_msgfree(search['res'])\n return\n end\n\n vprint_status(\"Entry #{i}: 0x#{pEntries[i].to_s(16)}\")\n\n entry = get_entry(pEntries[i])\n\n # Entries are a linked list...\n if client.arch == ARCH_X64\n pEntries[i+1] = entry[4]\n else\n pEntries[i+1] = entry[3]\n end\n\n ber = get_ber(entry)\n\n field_results = []\n fields.each do |field|\n vprint_status(\"Field: #{field}\")\n\n values = get_values_from_ber(ber, field)\n\n values_result = \"\"\n values_result = values.join(',') if values\n vprint_status(\"Values #{values}\")\n\n field_results << {:type => 'unknown', :value => values_result}\n end\n\n entry_results << field_results\n end\n\n return {\n :fields => fields,\n :results => entry_results\n }\n end", "def search( base, scope=:subtree, filter='(objectClass=*)', options={} )\n\t\tcollectclass = nil\n\n\t\t# If the base argument is an object whose class knows how to create instances of itself\n\t\t# from an LDAP::Entry, use it instead of Treequel::Branch to wrap results\n\t\tif options.key?( :results_class )\n\t\t\tcollectclass = options.delete( :results_class )\n\t\telse\n\t\t\tcollectclass = base.class.respond_to?( :new_from_entry ) ?\n\t\t\t\tbase.class :\n\t\t\t\tself.results_class\n\t\tend\n\n\t\t# Format the arguments in the way #search_ext2 expects them\n\t\tbase_dn, scope, filter, searchopts =\n\t\t\tself.normalize_search_parameters( base, scope, filter, options )\n\n\t\t# Unwrap the search options from the hash in the correct order\n\t\tself.log.debug do\n\t\t\tattrlist = SEARCH_PARAMETER_ORDER.inject([]) do |list, param|\n\t\t\t\tlist << \"%s: %p\" % [ param, searchopts[param] ]\n\t\t\tend\n\t\t\t\"searching with base: %p, scope: %p, filter: %p, %s\" %\n\t\t\t\t[ base_dn, scope, filter, attrlist.join(', ') ]\n\t\tend\n\t\tparameters = searchopts.values_at( *SEARCH_PARAMETER_ORDER )\n\n\t\t# Wrap each result in the class derived from the 'base' argument\n\t\tself.log.debug \"Searching via search_ext2 with arguments: %p\" % [[\n\t\t\tbase_dn, scope, filter, *parameters\n\t\t]]\n\n\t\tresults = []\n\t\tself.conn.search_ext2( base_dn, scope, filter, *parameters ).each do |entry|\n\t\t\tbranch = collectclass.new_from_entry( entry, self )\n\t\t\tbranch.include_operational_attrs = true if\n\t\t\t\tbase.respond_to?( :include_operational_attrs? ) &&\n\t\t\t\tbase.include_operational_attrs?\n\n\t\t\tif block_given?\n\t\t\t\tresults << yield( branch )\n\t\t\telse\n\t\t\t\tresults << branch\n\t\t\tend\n\t\tend\n\n\t\treturn results\n\trescue RuntimeError => err\n\t\tconn = self.conn\n\n\t\t# The LDAP library raises a plain RuntimeError with an incorrect message if the\n\t\t# connection goes away, so it's caught here to rewrap it\n\t\tcase err.message\n\t\twhen /no result returned by search/i\n\t\t\traise LDAP::ResultError.new( LDAP.err2string(conn.err) )\n\t\telse\n\t\t\traise\n\t\tend\n\tend", "def search(args = nil)\n args ||= {}\n\n # filtering, scoping, search base\n # filter: https://tools.ietf.org/html/rfc4511#section-4.5.1.7\n # base: https://tools.ietf.org/html/rfc4511#section-4.5.1.1\n # scope: https://tools.ietf.org/html/rfc4511#section-4.5.1.2\n filter = args[:filter] || Net::LDAP::Filter.eq(\"objectClass\", \"*\")\n base = args[:base]\n scope = args[:scope] || Net::LDAP::SearchScope_WholeSubtree\n\n # attr handling\n # attrs: https://tools.ietf.org/html/rfc4511#section-4.5.1.8\n # attrs_only: https://tools.ietf.org/html/rfc4511#section-4.5.1.6\n attrs = Array(args[:attributes])\n attrs_only = args[:attributes_only] == true\n\n # references\n # refs: https://tools.ietf.org/html/rfc4511#section-4.5.3\n # deref: https://tools.ietf.org/html/rfc4511#section-4.5.1.3\n refs = args[:return_referrals] == true\n deref = args[:deref] || Net::LDAP::DerefAliases_Never\n\n # limiting, paging, sorting\n # size: https://tools.ietf.org/html/rfc4511#section-4.5.1.4\n # time: https://tools.ietf.org/html/rfc4511#section-4.5.1.5\n size = args[:size].to_i\n time = args[:time].to_i\n paged = args[:paged_searches_supported]\n sort = args.fetch(:sort_controls, false)\n\n # arg validation\n raise ArgumentError, \"search base is required\" unless base\n raise ArgumentError, \"invalid search-size\" unless size >= 0\n raise ArgumentError, \"invalid search scope\" unless Net::LDAP::SearchScopes.include?(scope)\n raise ArgumentError, \"invalid alias dereferencing value\" unless Net::LDAP::DerefAliasesArray.include?(deref)\n\n # arg transforms\n filter = Net::LDAP::Filter.construct(filter) if filter.is_a?(String)\n ber_attrs = attrs.map { |attr| attr.to_s.to_ber }\n ber_sort = encode_sort_controls(sort)\n\n # An interesting value for the size limit would be close to A/D's\n # built-in page limit of 1000 records, but openLDAP newer than version\n # 2.2.0 chokes on anything bigger than 126. You get a silent error that\n # is easily visible by running slapd in debug mode. Go figure.\n #\n # Changed this around 06Sep06 to support a caller-specified search-size\n # limit. Because we ALWAYS do paged searches, we have to work around the\n # problem that it's not legal to specify a \"normal\" sizelimit (in the\n # body of the search request) that is larger than the page size we're\n # requesting. Unfortunately, I have the feeling that this will break\n # with LDAP servers that don't support paged searches!!!\n #\n # (Because we pass zero as the sizelimit on search rounds when the\n # remaining limit is larger than our max page size of 126. In these\n # cases, I think the caller's search limit will be ignored!)\n #\n # CONFIRMED: This code doesn't work on LDAPs that don't support paged\n # searches when the size limit is larger than 126. We're going to have\n # to do a root-DSE record search and not do a paged search if the LDAP\n # doesn't support it. Yuck.\n rfc2696_cookie = [126, \"\"]\n result_pdu = nil\n n_results = 0\n\n message_id = next_msgid\n\n instrument \"search.net_ldap_connection\",\n message_id: message_id,\n filter: filter,\n base: base,\n scope: scope,\n size: size,\n time: time,\n sort: sort,\n referrals: refs,\n deref: deref,\n attributes: attrs do |payload|\n loop do\n # should collect this into a private helper to clarify the structure\n query_limit = 0\n if size > 0\n if paged\n query_limit = (((size - n_results) < 126) ? (size -\n n_results) : 0)\n else\n query_limit = size\n end\n end\n\n request = [\n base.to_ber,\n scope.to_ber_enumerated,\n deref.to_ber_enumerated,\n query_limit.to_ber, # size limit\n time.to_ber,\n attrs_only.to_ber,\n filter.to_ber,\n ber_attrs.to_ber_sequence\n ].to_ber_appsequence(Net::LDAP::PDU::SearchRequest)\n\n # rfc2696_cookie sometimes contains binary data from Microsoft Active Directory\n # this breaks when calling to_ber. (Can't force binary data to UTF-8)\n # we have to disable paging (even though server supports it) to get around this...\n\n controls = []\n controls <<\n [\n Net::LDAP::LDAPControls::PAGED_RESULTS.to_ber,\n # Criticality MUST be false to interoperate with normal LDAPs.\n false.to_ber,\n rfc2696_cookie.map{ |v| v.to_ber}.to_ber_sequence.to_s.to_ber\n ].to_ber_sequence if paged\n controls << ber_sort if ber_sort\n controls = controls.empty? ? nil : controls.to_ber_contextspecific(0)\n\n write(request, controls, message_id)\n\n result_pdu = nil\n controls = []\n\n while pdu = queued_read(message_id)\n case pdu.app_tag\n when Net::LDAP::PDU::SearchReturnedData\n n_results += 1\n yield pdu.search_entry if block_given?\n when Net::LDAP::PDU::SearchResultReferral\n if refs\n if block_given?\n se = Net::LDAP::Entry.new\n se[:search_referrals] = (pdu.search_referrals || [])\n yield se\n end\n end\n when Net::LDAP::PDU::SearchResult\n result_pdu = pdu\n controls = pdu.result_controls\n if refs && pdu.result_code == Net::LDAP::ResultCodeReferral\n if block_given?\n se = Net::LDAP::Entry.new\n se[:search_referrals] = (pdu.search_referrals || [])\n yield se\n end\n end\n break\n else\n raise Net::LDAP::ResponseTypeInvalidError, \"invalid response-type in search: #{pdu.app_tag}\"\n end\n end\n\n # count number of pages of results\n payload[:page_count] ||= 0\n payload[:page_count] += 1\n\n # When we get here, we have seen a type-5 response. If there is no\n # error AND there is an RFC-2696 cookie, then query again for the next\n # page of results. If not, we're done. Don't screw this up or we'll\n # break every search we do.\n #\n # Noticed 02Sep06, look at the read_ber call in this loop, shouldn't\n # that have a parameter of AsnSyntax? Does this just accidentally\n # work? According to RFC-2696, the value expected in this position is\n # of type OCTET STRING, covered in the default syntax supported by\n # read_ber, so I guess we're ok.\n more_pages = false\n if result_pdu.result_code == Net::LDAP::ResultCodeSuccess and controls\n controls.each do |c|\n if c.oid == Net::LDAP::LDAPControls::PAGED_RESULTS\n # just in case some bogus server sends us more than 1 of these.\n more_pages = false\n if c.value and c.value.length > 0\n cookie = c.value.read_ber[1]\n if cookie and cookie.length > 0\n rfc2696_cookie[1] = cookie\n more_pages = true\n end\n end\n end\n end\n end\n\n break unless more_pages\n end # loop\n\n # track total result count\n payload[:result_count] = n_results\n\n result_pdu || OpenStruct.new(:status => :failure, :result_code => Net::LDAP::ResultCodeOperationsError, :message => \"Invalid search\")\n end # instrument\n ensure\n\n # clean up message queue for this search\n messages = message_queue.delete(message_id)\n\n # in the exceptional case some messages were *not* consumed from the queue,\n # instrument the event but do not fail.\n if !messages.nil? && !messages.empty?\n instrument \"search_messages_unread.net_ldap_connection\",\n message_id: message_id, messages: messages\n end\n end", "def search(basedn, scope, deref, filter)\n #raise LDAP::ResultError::UnwillingToPerform, \"Bad base DN\" unless basedn == BASEDN\n #raise LDAP::ResultError::UnwillingToPerform, \"Bad filter\" unless filter[0..1] == [:eq, \"uid\"]\n uid = filter[3]\n @@pool.borrow do |sql|\n q = \"select login_id,passwd from #{TABLE} where login='#{sql.quote(uid)}'\"\n puts \"SQL Query #{sql.object_id}: #{q}\" if $debug\n res = sql.query(q)\n res.each do |login_id,passwd|\n @@cache.add(login_id, passwd)\n send_SearchResultEntry(\"id=#{login_id},#{BASEDN}\", {\n \"maildir\"=>[\"/netapp/#{uid}/\"],\n })\n end\n end\n end", "def search( scope=:subtree, filter='(objectClass=*)', parameters={}, &block )\n\t\treturn self.directory.search( self, scope, filter, parameters, &block )\n\tend", "def search(options)\n options[:base] = @base_name\n options[:attributes] ||= %w{ou cn dn sAMAccountName member}\n options[:ignore_server_caps] ||= true\n\n @connection.search(options)\n end", "def lookup(terms = {})\n # Format the CWID if that's what we're getting.\n if terms[:cwid]\n terms = format(terms.values.first)\n else\n terms = terms.values.first\n end\n\n # Make the request to the LDAP server\n req = self.connection.get do |r|\n r.url self.configuration.search_path + terms\n end\n\n # Return nil if there's a nil directory return\n if req.body['directory'].nil?\n return []\n end\n\n # Return nil if there aren't any results\n if req.body['directory'] && (req.body['directory'].empty? || req.body['directory'].nil?)\n return []\n\n # Otherwise, create a new Person out of it\n else\n results = []\n\n if req.body['directory']['person'].is_a?(Hash)\n results << Person.new(req.body['directory']['person'])\n else\n req.body['directory']['person'].each do |r|\n results << Person.new(r)\n end\n end\n\n return results\n end\n end", "def search(base, filter = nil, attributes = nil)\n rows = []\n \n timeout_status = nil\n search_status = nil\n begin\n timeout_status = Timeout::timeout(60) do\n @ds.search(:base => base, :filter => filter, :attributes => attributes) do |entry|\n if ((!entry.nil?) && (entry[:cn] != []))\n rows << entry\n end \n end\n \n search_status = @ds.get_operation_result\n end\n rescue Timeout::Error => te\n ret = {\n :status => 0,\n :message => \"Connection to LDAP timed out\",\n :values => nil\n }\n return ret\n rescue Exception => e\n pp [\"exception\", e]\n end\n \n if (search_status.code == 0)\n ret = {\n :status => 1,\n :message => \"Success\",\n :values => rows\n }\n else\n ret = {\n :status => 0,\n :message => \"Net-LDAP Error #{search_status.code}: #{search_status.message}\",\n :values => nil\n }\n end\n \n return ret\n end", "def get_entry( c, dn ) # :yields: connection_info, distinguished_name\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n \n entry = @ldap.search( \n base: dn, \n filter: Net::LDAP::Filter.eq( 'objectClass', '*' ),\n scope: Net::LDAP::SearchScope_BaseObject,\n attributes: [ '*' ]\n )\n \n raise \"Error while searching: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/\n return entry ? entry.first : entry\n end", "def ldap_search(attr,query)\n\t\tload \"#{$pwd}/plugins/config/ldap_config.rb\"\n\t\n\t\t# ldap_return auth (below) is a function from auth_ldap.rb that returns a\n\t\t# hash with the username and password to bind to LDAP with.\n\t\tldap_config = return_ldap_config\n\n\t\thost = 'ldap.oit.pdx.edu'\n\t\tport = 636\n \t\tauth = { :method => :simple, :username => ldap_config['username'], :password => ldap_config['pass'] }\n\t\tbase = 'dc=pdx,dc=edu'\n\t\n\t\tresult = Hash.new(Array.new)\n\t\tNet::LDAP.open(:host => host, :port => port, :auth => auth, :encryption => :simple_tls, :base => base) do |ldap|\n\t\t\t\n\t\t\t# Perform the search, then return a hash with LDAP attributes corresponding\n\t\t\t# to hash keys, and LDAP values corresponding to hash values.\n\t\t\tfilter = Net::LDAP::Filter.eq(attr,query)\n\t\t\tif (ldap.bind)\n\t\t\t\tldap.search(:filter => filter) do |entry|\n\t\t\t\t\tentry.each do |attribute, values|\n\t\t\t\t\t\tvalues.each do |value|\n\t\t\t\t\t\t\tresult[\"#{attribute}\"] += [\"#{value}\"]\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tresult = false\n\t\t\tend\n\t\tend\n\n\t\treturn result\n\tend", "def search(sfilter = nil)\n sfilter ||= filter\n\n result = []\n connect do |conn|\n conn.search2(base, 1, sfilter) do |entry|\n result << entry2provider(entry)\n end\n end\n return(result.empty? ? nil : result)\n end", "def search(query = '', type: 'account', domain: nil, **options)\n options[:limit] ||= Zimbra::Directory::SEARCH_LIMIT\n DirectoryService.search(query, type.to_sym, domain, options)\n end", "def /(*args)\n search(:base => dn.send(:/, *args), :scope => :base, :limit => true)\n end", "def search(options, &block)\n if options[:base].kind_of?(Hash)\n options = options.merge(:base => dn/options[:base])\n end\n namespace.search({:base => dn}.merge(options), &block)\n end", "def ldapsearch(filter)\n raise ArgumentError.new(\"You must pass a block to ldapsearch\") unless block_given?\n\n found = false\n count = 0\n\n begin\n connection.search(search_base, 2, filter, search_attributes) do |entry|\n found = true\n yield entry\n end\n rescue SystemExit,NoMemoryError\n raise\n rescue Exception => detail\n if count == 0\n # Try reconnecting to ldap if we get an exception and we haven't yet retried.\n count += 1\n @connection = nil\n Puppet.warning \"Retrying LDAP connection\"\n retry\n else\n error = Puppet::Error.new(\"LDAP Search failed\")\n error.set_backtrace(detail.backtrace)\n raise error\n end\n end\n\n found\n end", "def get_users(host, base='dc=griddynamics,dc=net', scope=LDAP::LDAP_SCOPE_SUBTREE, filter='(objectclass=person)')\n\n puts \"Getting users from #{host} with base #{base} with filter #{filter}\"\n\n attrs = ['uid', 'mail', 'sn', 'givenName' ,'cn', 'sshPublicKey']\n\n conn = LDAP::Conn.new(host)\n\n puts \"Connection received: #{conn.inspect}\"\n\n conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)\n\n puts conn.bind('','')\n\n conn.perror(\"bind\")\n\n begin\n users = Hash.new\n\n conn.search(base, scope, filter, attrs) { |entry|\n groups = []\n entry.dn.split(',').each { |dn|\n tmp = dn.split('=')\n if tmp[0] == 'ou'\n groups << tmp[1]\n end\n }\n\n if groups.include?('people') and groups.include?('griddynamics') and not groups.include?('deleted')\n users[entry.vals('uid')[0].dup] = {\n :email => entry.vals('mail')[0].dup,\n :name => entry.vals('givenName')[0].dup,\n :last_name => entry.vals('sn')[0].dup,\n :full_name => entry.vals('cn')[0].dup,\n :ssh_public_key => entry.vals('sshPublicKey').nil? ? nil : entry.vals('sshPublicKey')[0].dup,\n :groups => groups.dup\n }\n end\n }\n return users\n rescue LDAP::ResultError\n conn.perror(\"search\")\n exit\n end\n conn.perror(\"search\")\n conn.unbind\nend", "def search(options, &block)\n instrument \"search.github_ldap\", options.dup do |payload|\n result =\n if options[:base]\n @connection.search(options, &block)\n else\n search_domains.each_with_object([]) do |base, result|\n rs = @connection.search(options.merge(:base => base), &block)\n result.concat Array(rs) unless rs == false\n end\n end\n\n return [] if result == false\n Array(result)\n end\n end", "def ldapSearchLookup(key) \n answer = []\n filter = Net::LDAP::Filter.from_rfc4515(key)\n conf = Config[:ldap] \n treebase = conf[:base]\n Hiera.debug(\"Searching #{key} in LDAP backend, base #{treebase}.\")\n searchresult = @connection.search(:filter => filter)\n\n for i in 0..searchresult.length-1 do\n answer[i] = {}\n searchresult[i].each do |attribute, values|\n Hiera.debug( \" #{attribute}:\")\n answer[i][attribute.to_s] = values\n values.each do |value|\n Hiera.debug( \" ---->#{value}:\")\n end\n end\n end\n return answer\n end", "def search( options={} )\n\t\tds = @storage.each_key\n\t\tself.log.debug \"Starting search with %p\" % [ ds ]\n\n\t\tds = self.omit_related_resources( ds, options )\n\t\tds = self.apply_search_criteria( ds, options )\n\t\tds = self.apply_search_order( ds, options )\n\t\tds = self.apply_search_direction( ds, options )\n\t\tds = self.apply_search_limit( ds, options )\n\n\t\treturn ds.to_a\n\tend", "def search(*args)\n search_provider.search(*args)\n end", "def get_entry(domain,search_key,search_value,return_attrs = [])\n @domain = domain\n @search_key = search_key\n @search_value = search_value\n @return_attrs = return_attrs\n @treebase = @domain.gsub(/\\./, ',dc=')\n @treebase = @treebase.insert(0, 'dc=')\n ldap = ldap_connect(@domain)\n filter = Net::LDAP::Filter.eq(@search_key,@search_value)\n results = ldap.search(:base => @treebase, :filter => filter, :attributes => @return_attrs)\n if (results.nil? || results.length == 0)\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end", "def scoped_search(scope, *args, &block)\n # extract the original query\n query = args[1] || \"*:*\"\n\n # prepend the environment to the query based on scope\n case scope\n when /domain/i,/dc/i\n args[1] = \"domain:#{node[:domain]} AND (#{query})\"\n when /environment/, /env/i\n args[1] = \"chef_environment:#{node[:chef_environment]} AND (#{query})\"\n else\n rasie ArgumentError \"restricted search does not know how to handle scope: #{scope} \"\n end\n\n # call the original search method\n search(*args, &block)\n end", "def search_options_for(filter:, attributes:)\n {}.tap do |opts|\n group_base = APP_CONFIG[\"ldap\"][\"group_base\"]\n opts[:base] = group_base if group_base.present?\n opts[:filter] = Net::LDAP::Filter.construct(filter)\n opts[:attributes] = attributes\n end\n end", "def find(dn = self.dn, options = {})\n # Some misguided attempts to emulate active record.\n case dn\n when :all then search({:limit => false}.merge(options))\n when :first then first(options)\n when Array then dn.map {|d| fetch(d, options)}\n else fetch(dn, options)\n end\n end", "def search(search_options)\n Array(global_catalog_connection.search(search_options.merge(options)))\n end", "def find(source = @source)\n scope = 0\n filter = \"(objectClass=*)\"\n if source.respond_to?(:search2_ext)\n source.search2(\n to_s,\n scope,\n filter\n )\n elsif source.respond_to?(:search)\n Array(source.search(\n :base => to_s,\n :scope => scope,\n :filter => filter,\n :limit => 1\n ))\n else\n raise RuntimeError, \"missing or invalid source for LDAP search\", caller\n end.first\n end", "def search(domain, offset=0, limit=false, order=false, context={}, count=false)\n rpc_execute('search', domain, offset, limit, order, context, count)\n end", "def search(args)\n args = validate_search_args!(args)\n\n response = remote_call(:search, args)\n\n if response.respond_to?(:records)\n serialize_records(response.records)\n else\n response\n end\n end", "def search_for_login(connection=nil)\n connection ||= self\n @login_ldap_entry ||= begin\n DeviseLdapAuthenticatable::Logger.send(\"LDAP search for login: #{@attribute}=#{@login}\")\n filter = Net::LDAP::Filter.eq(@attribute.to_s, @login.to_s)\n ldap_entry = nil\n match_count = 0\n connection.open do |ldap|\n ldap.search(:filter => filter) {|entry| ldap_entry = entry; match_count+=1}\n end\n DeviseLdapAuthenticatable::Logger.send(\"LDAP search yielded #{match_count} matches\")\n ldap_entry\n end\n end", "def execute()\n begin\n\n # If we are successful in authenticating using the active directory\n # server and credentials specified by the task info values.\n if @ldap.bind\n # Build a filter to search by\n filter = Net::LDAP::Filter.eq( \"objectclass\", \"computer\" )\n # Add the search value (attribute) to the filter for the search\n unless @parameters['search_value'].nil?\n filter = filter & Net::LDAP::Filter.eq(@search_by, @parameters['search_value'])\n end\n\n # Search operation - return result is set to true so that an array is\n # returned (to determine if search matches more than one entry)\n user_entries = @ldap.search(\n :base => @info_values['base'],\n :filter => filter,\n :size => 2,\n :return_result => true\n )\n\n # Raise an exception if there was a problem with the call\n unless @ldap.get_operation_result.code == 0\n @error_message = \"Message: #{@ldap.get_operation_result.message}, Error Code: \"\\\n\t\t\t\t\"#{@ldap.get_operation_result.code}\"\n raise \"Message: #{@ldap.get_operation_result.message}, Error Code: \"\\\n\t\t\t\t\t\t\"#{@ldap.get_operation_result.code}\" if @error_handling == \"Raise Error\"\n end\n\n # Raise exception if search did not return 1 entry\n if user_entries.length < 1\n @error_message = \"User not found when searching by #{@search_by} \"\\\n \"for: #{@parameters['search_value']}\" if @error_message.nil?\n raise \"User not found when searching by #{@search_by} for: #{@parameters['search_value']}\" if @error_handling == \"Raise Error\"\n elsif user_entries.length > 1\n @error_message = \"Search matched more than one entry when searching by #{@search_by} \"\\\n \"for: #{@parameters['search_value']}\" if @error_message.nil?\n raise \"Search matched more than one entry when searching by #{@search_by} for: \"\\\n\t\t\t\t\t\t\"#{@parameters['search_value']}\" if @error_handling == \"Raise Error\"\n end\n \n # Determine the computers distinguished name\n user_dn = user_entries.first.dn\n\n puts \"Computer DN: #{user_dn}\" if @debug_logging_enabled\n \n # For each of the group names\n groups = @group_names.inject({}) do |hash, group_name|\n # Initialize the group name\n hash[group_name] = nil\n # Build a filter to retrieve the group entries\n filter = Net::LDAP::Filter.eq( \"objectclass\", \"group\" ) & Net::LDAP::Filter.eq( \"cn\", group_name )\n # Search for each of the groups\n @ldap.search(\n :base => \"#{@info_values['base']}\",\n :filter => filter,\n :return_result => false\n ) {|entry| hash[group_name] = entry }\n # Return the hash to be used with the remaining inject calls\n hash\n end\n\n # If debug logging is enabled\n if @debug_logging_enabled\n # Log the retrieved group information\n puts \"Retrieved Groups:\" \n groups.each do |name, group|\n puts \" #{name}: #{group.dn}\"\n end\n end\n\n # Attempt to retrieve the names of any groups that did were not retrieved\n missing_group_names = groups.keys.select {|name| groups[name].nil?}\n\n # If we were unable to locate\n if missing_group_names.length > 0\n @error_message = \"The following groups did not exist on the configured Active Directory server: \"\\\n\t\t\t\t\t\t\"#{missing_group_names.join(', ')}\"\n # Raise an exception that lists what groups were missing\n raise \"The following groups did not exist on the configured Active Directory server: \"\\\n\t\t\t\t\t\t\"#{missing_group_names.join(', ')}\" if @error_handling == \"Raise Error\"\n # If there were not any missing groups\n else\n # TODO - add_attributes returns true or false, so the result of\n # get_operation_result should be examined if add_attributes was not\n # successful and an error message should be raised.\n\n # Add the user as a member to each of the groups\n groups.each {|name, entry| \n @ldap.add_attribute(entry.dn, :member, user_dn)\n #puts \"Added: #{entry.dn}, #{user_dn}\"\n }\n \n end\n # If authentication of the ldap session failed\n else\n @error_message = \"Directory authentication failed for #{@info_values['host']}: \"\\\n\t\t\t\t\t\"#{@ldap.get_operation_result}\" if @error_message.nil?\n # Raise an error\n raise \"Directory authentication failed for #{@info_values['host']}: \"\\\n \"#{@ldap.get_operation_result}\" if @error_handling == \"Raise Error\"\n end\n rescue Exception => error\n @error_message = error.inspect if @error_message.nil?\n raise error if @error_handling == \"Raise Error\"\n end\n\n # Build, log, and return the results\n results = <<-RESULTS\n <results>\n <result name=\"Handler Error Message\">#{escape(@error_message)}</result>\n </results>\n RESULTS\n puts(\"Results: \\n#{results}\") if @debug_logging_enabled\n\t return results\n end" ]
[ "0.70574045", "0.6846109", "0.6770961", "0.65752316", "0.6574974", "0.645856", "0.6366931", "0.62826765", "0.6233852", "0.6118379", "0.60482985", "0.6020928", "0.5801382", "0.56704265", "0.5670218", "0.56624055", "0.5576212", "0.5559215", "0.5526331", "0.55008805", "0.5485458", "0.5424206", "0.5424003", "0.541686", "0.54073745", "0.5404407", "0.538748", "0.53843033", "0.5379917", "0.5373955" ]
0.830434
0
== Get Entry This method accepts a connection resource object. It is intended to be used with Chef::Resource::LdapEntry objects that will also have a .dn method indicating Distinguished Name to be retrieved. It returns a single entry.
def get_entry( c, dn ) # :yields: connection_info, distinguished_name self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap entry = @ldap.search( base: dn, filter: Net::LDAP::Filter.eq( 'objectClass', '*' ), scope: Net::LDAP::SearchScope_BaseObject, attributes: [ '*' ] ) raise "Error while searching: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/ return entry ? entry.first : entry end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def lookup_entry\n\t\tself.log.debug \"Looking up entry for %s\" % [ self.dn ]\n\t\tentry = nil\n\n\t\tif self.include_operational_attrs?\n\t\t\tself.log.debug \" including operational attributes.\"\n\t\t\tentry = self.directory.get_extended_entry( self )\n\t\telse\n\t\t\tself.log.debug \" not including operational attributes.\"\n\t\t\tentry = self.directory.get_entry( self )\n\t\tend\n\n\t\tentry.delete( 'dn' ) if entry\n\t\tself.log.debug \" entry is: %p\" % [ entry ]\n\t\treturn entry\n\tend", "def get_entry( branch )\n\t\tself.log.debug \"Looking up entry for %p\" % [ branch.dn ]\n\t\treturn self.conn.search_ext2( branch.dn, SCOPE[:base], '(objectClass=*)' ).first\n\trescue LDAP::ResultError => err\n\t\tself.log.info \" search for %p failed: %s\" % [ branch.dn, err.message ]\n\t\treturn nil\n\tend", "def entry\n\t\t@entry ||= self.lookup_entry\n\tend", "def get_extended_entry( branch )\n\t\tself.log.debug \"Looking up entry (with operational attributes) for %p\" % [ branch.dn ]\n\t\treturn self.conn.search_ext2( branch.dn, SCOPE[:base], '(objectClass=*)', %w[* +] ).first\n\trescue LDAP::ResultError => err\n\t\tself.log.info \" search for %p failed: %s\" % [ branch.dn, err.message ]\n\t\treturn nil\n\tend", "def get_entry(domain,search_key,search_value,return_attrs = [])\n @domain = domain\n @search_key = search_key\n @search_value = search_value\n @return_attrs = return_attrs\n @treebase = @domain.gsub(/\\./, ',dc=')\n @treebase = @treebase.insert(0, 'dc=')\n ldap = ldap_connect(@domain)\n filter = Net::LDAP::Filter.eq(@search_key,@search_value)\n results = ldap.search(:base => @treebase, :filter => filter, :attributes => @return_attrs)\n if (results.nil? || results.length == 0)\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end", "def entry\n @entry.object\n end", "def entry\n return nil unless @item and self.type == :query\n @item['entry']\n end", "def get_entry(path, commit = @commit)\n entry_hash = get_entry_hash(path, commit)\n if entry_hash.nil?\n entry = nil\n else\n entry = @repo.lookup(entry_hash[:oid])\n end\n entry\n end", "def get_entry(entry)\n selected_entry = find_entry(entry)\n raise Errno::ENOENT, entry if selected_entry.nil?\n\n selected_entry\n end", "def read_entry(key, options)\n query = Google::Cloud::Datastore::Key.new @datastore_kind_name, key\n entities = dataset.lookup query\n return nil unless entities.any?\n entity = entities.first\n entry = deserialize_entry( entity[:_value], entity[:_format] )\n return entry\n end", "def get_entry(entry); end", "def lookup_entry\n\t\tif entryhash = super\n\t\t\tself.apply_applicable_mixins( self.dn, entryhash )\n\t\tend\n\n\t\treturn entryhash\n\tend", "def get_entry\n raise NotImplementedError\n end", "def read_entry(key, options) # :nodoc:\n entry = with { |c| c.get(key, options) }\n # NB Backwards data compatibility, to be removed at some point\n entry.is_a?(ActiveSupport::Cache::Entry) ? entry.value : entry\n rescue Dalli::DalliError => e\n log_dalli_error(e)\n instrument_error(e) if instrument_errors?\n raise if raise_errors?\n nil\n end", "def fetch(username, realm)\n return nil unless has_entry?(username, realm)\n ir = internal_record(username, realm)\n return ir['entry'].dup\n end", "def fetch(username, realm)\n return nil unless has_entry?(username, realm)\n ir = internal_record(username, realm)\n return ir['entry'].dup\n end", "def entry\n Entry.new\n end", "def read_entry(key, options) # :nodoc:\n @data.get(key, options)\n rescue ::Couchbase::Error::Base => e\n logger.error(\"#{e.class}: #{e.message}\") if logger\n raise if @raise_errors\n nil\n end", "def fetch(dn = self.dn, options = {}) #:nodoc:\n find_one(dn, options)\n end", "def get(entry_id, version=-1)\n\t\t\tkparams = {}\n\t\t\t# Entry id\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\t# Desired version of the data\n\t\t\tclient.add_param(kparams, 'version', version);\n\t\t\tclient.queue_service_action_call('baseentry', 'get', 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 fetch(username)\n return nil unless has_entry?(username)\n ir = internal_record(username)\n return ir['entry'].dup\n end", "def get_related (entry, type)\n related_entry_key = entry.related[type] unless entry.related.nil?\n self.entries[related_entry_key]\n end", "def fetch(username)\n return nil unless has_entry?(username)\n ir = internal_record(username)\n return ir['entry'].dup\n end", "def find_entry(name)\n Entry.where(name: name, address_book_id: self.id).first\n end", "def read_entry(key, options) # :nodoc:\n deserialize_entry(@data.where(key: key).get(:value))\n rescue Sequel::Error => e\n logger.error(\"Sequel::Error (#{e}): #{e.message}\") if logger\n nil\n end", "def get_dn(domain,dn,return_attrs = [])\n scope = Net::LDAP::SearchScope_BaseObject\n ldap = ldap_connect(domain)\n results = ldap.search(:base => dn, :scope => scope, :attributes => return_attrs)\n if (results.nil? || results.length == 0)\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end", "def find_entry\n ms = model_scope\n result = nil\n if params[:id]\n # Requests that retrieve existing records (e.g. show, edit, update, destroy) set an 'id' param\n # The +find+ method raises ActiveRecord::RecordNotFound if no database item has this primary key\n result = ms.find(params[:id])\n elsif params[ms.primary_key]\n # Primary key is a single value provided in the params hash\n # This modification allows the create action to succeed even if the item already exists\n # The +where...first+ methods returns the item from the database or nil if not found\n result = ms.where(ms.primary_key => params[ms.primary_key]).first\n elsif ms.primary_key.instance_of? CompositePrimaryKeys::CompositeKeys\n # primary key is composed of multiple values\n if (ms.primary_key - params.keys).empty?\n # param values are present for all the primary keys\n pk_values = ms.primary_key.map{|k| params[k]}\n result = ms.find(pk_values)\n end\n end\n result\n end", "def ledger_entry(ledger_entry_id)\n API::request(:get, \"ledger_entries/#{ledger_entry_id}\")\n end", "def get_atom_entry(url)\n res = get(url, \"Accept\" => \"application/atom+xml\")\n\n # XXX handle other HTTP codes\n if res.code != \"200\"\n raise Atom::HTTPException, \"failed to fetch entry: expected 200 OK, got #{res.code}\"\n end\n\n # be picky for atom:entrys\n res.validate_content_type( [ \"application/atom+xml\" ] )\n\n Atom::Entry.parse(res.body, url)\n end", "def retrieve_ldap_node(dn)\n node = RubyLdapom::LdapNode.new(self, dn, false)\n node.load_attributes\n end" ]
[ "0.69192225", "0.6838741", "0.6255633", "0.62506276", "0.6213904", "0.61219466", "0.6081091", "0.6077004", "0.6066452", "0.60608196", "0.594333", "0.5859642", "0.58492595", "0.58359665", "0.5781691", "0.5781691", "0.5737232", "0.5667582", "0.566263", "0.56159306", "0.5518761", "0.5518751", "0.5517276", "0.5447974", "0.53721625", "0.5364211", "0.53152406", "0.5300923", "0.52258205", "0.5217422" ]
0.78271013
0
== Add Entry This method accepts a connection resource object, a distinguished name, and the attributes for the entry to be added.
def add_entry( c, dn, attrs ) # :yields: connection_info, distinguished_name, attributes self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap # Ensure no duplicates by casting as a case insensitive, case preserving hash attrs = CICPHash.new.merge(attrs) # Ensure relativedn is included in the attribute list relativedn = dn.split(/,(?!([\w -]+=[\w -]+,?){1,}\")/).first attrs.merge!(Hash[*relativedn.split('=', 2).flatten]) @ldap.add dn: dn, attributes: attrs raise "Unable to add record: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message == 'Success' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_entry entry\n @data << entry\n end", "def add_subscription_entry(name, entry)\n\t\tend", "def add(entry)\n @entries[entry.tag] = entry\n end", "def add(dn, attributes)\n attributes = normalize_attributes(attributes)\n log_dispatch(:add, dn, attributes)\n adapter.add(dn, attributes)\n end", "def add(account) \n entry = Keybox::HostAccountEntry.new(account, account)\n\n if @options.use_password_hash_for_url then\n begin \n account_uri = URI.parse(account) \n if not account_uri.scheme.nil? then\n entry = Keybox::URLAccountEntry.new(account,account)\n end\n rescue ::URI::InvalidURIError\n # just ignore it, we're fine with the Host\n # Account Entry\n end\n\n end\n new_entry = gather_info(entry)\n hsay \"Adding #{new_entry.title} to database.\", :information\n @db << new_entry\n end", "def add_entry(name, phone, email)\n new_entry = Entry.new(name, phone, email)\n entries << new_entry\n end", "def add_entry(name)\n Library.create(name: name)\n end", "def add_data_entry(entry)\n @repository << entry\n return nil\n end", "def add entry\n existing_entry = @entries[entry.msgid]\n if existing_entry\n entry = existing_entry.merge(entry)\n end\n @entries[entry.msgid] = entry\n end", "def add_entry(opts)\n raise ArgumentError, \"Expected Hash or Keepassx::Entry, got #{opts.class}\" unless valid_entry?(opts)\n\n if opts.is_a?(Keepassx::Entry)\n # Add entry\n @entries << opts\n\n # Increment counter\n header.entries_count += 1\n\n # Return entry\n opts\n\n elsif opts.is_a?(Hash)\n opts = deep_copy(opts)\n opts = build_entry_options(opts)\n\n # Create entry\n entry = create_entry(opts)\n\n # Increment counter\n header.entries_count += 1\n\n # Return entry\n entry\n end\n end", "def <<(entry)\n @entries << entry if entry.kind_of?(Inaho::Entry)\n end", "def add_connection(resource, connection)\n @data['powerConnections'] << {\n 'connectionUri' => resource['uri'],\n 'deviceConnection' => connection,\n 'sourceConnection' => connection\n }\n end", "def add_entry(located_entry)\n path = insert_entry(located_entry)\n set_new_value(path, located_entry)\n end", "def add(entry)\n _check_open!\n ::Dnet.route_add(@handle, entry)\n end", "def << (entry)\n @entries << entry\n end", "def add(name, resource, attributes = {})\n resources[name] = resource\n resource.update_attributes(attributes) if attributes.any?\n resource\n end", "def add(entry)\n entries << entry\n end", "def create_entry(options = {title: '', description: '', principal_balance: 0, interest_income_balance: 0, from_installment: nil })\n\n\t\t\taccounting_entry = accounting_entries.build()\n accounting_entry.title = options[:title]\n accounting_entry.entry_date = Date.current\n accounting_entry.principal_balance = options[:principal_balance]\n accounting_entry.interest_income_balance = options[:interest_income_balance]\n accounting_entry.description = options[:description]\n accounting_entry.from_installment =options[:from_installment]\n accounting_entry.save\n accounting_entry\n\n\tend", "def add(resource)\n get_resource(resource.type).add(resource.value)\n end", "def add(options = {})\n entry = Entry.new(\n ip_address: options[:ip_address],\n hostname: options[:hostname],\n aliases: options[:aliases],\n comment: options[:comment],\n priority: options[:priority],\n )\n\n @entries << entry\n remove_existing_hostnames(entry) if options[:unique]\n end", "def add_connection(connection)\n self.connections[connection.id] = connection\n end", "def add_entry( entry )\n case entry\n when Credit\n credits << entry\n when Debit\n debits << entry\n else\n raise ArgumentError, \"Transaction is unable to handle an Unknown type: #{entry}\"\n end\n end", "def add\n ensure_client\n required_attributes = %w[deviceVolumeName isShareable storageSystemUri]\n required_attributes.each { |k| raise IncompleteResource, \"Missing required attribute: '#{k}'\" unless @data.key?(k) || @data.key?(k.to_sym) }\n @data['name'] ||= @data['deviceVolumeName']\n response = @client.rest_post(\"#{BASE_URI}/from-existing\", { 'body' => @data }, @api_version)\n set_all(client.response_handler(response))\n self\n end", "def add(requestor, dn, attributes)\n log(\"#{requestor[:name]} #{requestor[:ip]} added #{dn}\")\n ret = {\n :status => 1,\n :message => \"Success\",\n :values => \"\"\n }\n @ds.add(:dn => dn, :attributes => attributes)\n ret = @ds.get_operation_result\n return ret\n end", "def insert_entry(params)\n Entry.create(params)\n end", "def new_entry(entry)\n BatchEntries.create(\n batch_registries_id: @current_batch_registry.id,\n payload: entry.to_json,\n complete: false,\n error: false,\n current_status: 'registered'\n )\n end", "def add_entry_of(habit_id, entry)\n entries.insert(\n timestamp: entry.timestamp,\n type: entry.type,\n habit_id: habit_id\n )\n end", "def xattr_add_entry(name, value)\n raise ArgumentError, 'value is not a String' unless value.is_a?(String)\n\n C.archive_entry_xattr_add_entry(entry, name, Utils.get_memory_ptr(value), value.bytesize)\n end", "def add_entry(symbol, *options)\r\n @list[0].add_entry(symbol, *options)\r\n end", "def add_entry(entry)\n self.notes = \"#{entry}\\n#{notes}\".truncate_bytes(MAX_LENGTH)\n end" ]
[ "0.61634195", "0.6126714", "0.6046693", "0.60178816", "0.58524925", "0.568015", "0.56614065", "0.5592205", "0.5586353", "0.5576164", "0.55708426", "0.55561775", "0.5537293", "0.5488622", "0.5487179", "0.54644245", "0.54437673", "0.5431659", "0.54093915", "0.54081136", "0.5394243", "0.5335649", "0.533192", "0.53185534", "0.52872497", "0.52623206", "0.52533054", "0.5252948", "0.52488714", "0.5231823" ]
0.76255393
0
== Modify Entry Accepts a connection resource object as the first argument, followed by an Array of ldap operations. It is intended to be used with Chef::Resource::LdapEntry objects that will also have a .dn method that returns the DN of the entry to be modified. Each ldap operation in the ldap operations list is an Array object with the following items: 1. LDAP operation ( e.g. :add, :delete, :replace ) 2. Attribute name ( String or Symbol ) 3. Attribute Values ( String or Symbol, or Array of Strings or Symbols ) So an example of an operations list to be passed to this method might look like this: [ [ :add, 'attr1', 'value1' ], [ :replace, :attr2, [ :attr2a, 'attr2b', :attr2c ] ], [ :delete, 'attr3' ], [ :delete, :attr4, 'value4' ] ] Note that none of the values passed can be Integers. They must be STRINGS ONLY! This is a limitation of the ruby netldap library.
def modify_entry( c, dn, ops ) # :yields: connection_info, distinguished_name, operations entry = self.get_entry( c, dn ) @ldap.modify dn: dn, operations: ops raise "Unable to modify record: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|Attribute or Value Exists)/ end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_entry(entry, ldap_attrs, user_attrs, ldap_key, user_key)\n if user_attrs.has_key?(user_key)\n if ldap_attrs.has_key?(ldap_key)\n if user_attrs[user_key] != ldap_attrs[ldap_key].first\n entry << LDAP.mod(LDAP::LDAP_MOD_REPLACE, ldap_key, user_attrs[user_key].is_a?(String) ? [ user_attrs[user_key] ] : user_attrs[user_key] )\n end\n else\n entry << LDAP.mod(LDAP::LDAP_MOD_ADD, ldap_key, user_attrs[user_key].is_a?(String) ? [ user_attrs[user_key] ] : user_attrs[user_key] )\n end\n else\n if ldap_attrs.has_key?(ldap_key)\n entry << LDAP.mod(LDAP::LDAP_MOD_DELETE, ldap_key, [ ])\n end\n end\n end", "def modify(ldap)\n puts \"Enter firstname\"\n firstname = gets.chomp\n puts \"Enter attribute to modify\"\n attribute = gets.chomp\n puts \"Enter new value\"\n value = gets.chomp\n \n dn = \"cn=#{firstname},ou=people,dc=example,dc=com\"\n ops = [\n [:replace, attribute.to_sym, value ]\n ]\n ldap.modify :dn => dn, :operations => ops\n puts \"****** modify result ******\"\n puts ldap.get_operation_result\n end", "def update_object(method,domain,object,attribute,value)\n @ldap = ldap_connect(domain,ADMINUSER,ADMINPASS)\n begin\n if (method == 'add')\n @ldap.add_attribute(object,attribute,value)\n elsif (method == 'replace')\n @ldap.replace_attribute(object.to_s,attribute,value)\n end\n rescue Exception => e\n puts\n puts \" Error: #{e.message}\"\n puts \" Error: #{e.backtrace.inspect}\"\n puts \" Error: #{@ldap.get_operation_result.error_message}\"\n puts \" Error: #{@ldap.get_operation_result.code}: #{@ldap.get_operation_result.message}\"\n puts\n abort\n else\n puts \" Result: #{@ldap.get_operation_result.code}: #{@ldap.get_operation_result.message}\"\n end\n end", "def modify(requestor, dn, ops)\n ops.each do |op|\n #pp [\"op\", op]\n #log(\"#{requestor[:name]} #{requestor[:ip]} operation #{op[0]} #{op[1]} \\\"#{op[2].join(', ')}\\\" for #{dn}\")\n end\n ret = {\n :status => 1,\n :message => \"Success\",\n :values => \"\"\n }\n @ds.modify(:dn => dn, :operations => ops)\n ret = @ds.get_operation_result\n return ret\n end", "def modify( branch, mods )\n\t\tif mods.first.respond_to?( :mod_op )\n\t\t\tself.log.debug \"Modifying %s with LDAP mod objects: %p\" % [ branch.dn, mods ]\n\t\t\tself.conn.modify( branch.dn, mods )\n\t\telse\n\t\t\tnormattrs = normalize_attributes( mods )\n\t\t\tself.log.debug \"Modifying %s with: %p\" % [ branch.dn, normattrs ]\n\t\t\tself.conn.modify( branch.dn, normattrs )\n\t\tend\n\tend", "def add_entry( c, dn, attrs ) # :yields: connection_info, distinguished_name, attributes\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n \n # Ensure no duplicates by casting as a case insensitive, case preserving hash\n attrs = CICPHash.new.merge(attrs)\n # Ensure relativedn is included in the attribute list\n relativedn = dn.split(/,(?!([\\w -]+=[\\w -]+,?){1,}\\\")/).first\n attrs.merge!(Hash[*relativedn.split('=', 2).flatten])\n @ldap.add dn: dn, attributes: attrs\n raise \"Unable to add record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message == 'Success'\n end", "def modify(dn, attributes)\n if attributes.kind_of?(Hash)\n attributes = normalize_attributes(attributes)\n else\n attributes = attributes.map do |(action, key, values)|\n [action, Ldaptic.encode(key), values.respond_to?(:before_type_cast) ? values.before_type_cast : [values].flatten.compact]\n end\n end\n log_dispatch(:modify, dn, attributes)\n adapter.modify(dn, attributes) unless attributes.empty?\n end", "def diff_with_entry( attribute, values )\n\t\tmods = []\n\t\tattribute = attribute.to_s\n\t\tentry = self.entry || {}\n\t\tentry_values = entry.key?( attribute ) ? entry[attribute] : []\n\n\t\t# Workaround for the fact that Time has a #to_ary, causing it to become an\n\t\t# Array of integers when cast via Array().\n\t\tvalues = [ values ] if values.is_a?( Time )\n\n\t\tvalues = Array( values ).compact.\n\t\t\tcollect {|val| self.get_converted_attribute(attribute, val) }\n\t\tself.log.debug \" comparing %s values to entry: %p vs. %p\" %\n\t\t\t[ attribute, values, entry_values ]\n\n\t\t# If the attributes on the server are the same as the local ones,\n\t\t# it's a NOOP.\n\t\tif values.sort == entry_values.sort\n\t\t\tself.log.debug \" no change.\"\n\t\t\treturn nil\n\n\t\t# If the directory doesn't have this attribute, but the local\n\t\t# object does, it's an ADD\n\t\telsif entry_values.empty?\n\t\t\tself.log.debug \" ADD %s: %p\" % [ attribute, values ]\n\t\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_ADD, attribute, values )\n\n\t\t# ...or if the local value doesn't have anything for this attribute\n\t\t# but the directory does, it's a DEL\n\t\telsif values.empty?\n\t\t\tself.log.debug \" DELETE %s\" % [ attribute ]\n\t\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_DELETE, attribute )\n\n\t\t# ...otherwise it's a REPLACE\n\t\telse\n\t\t\tself.log.debug \" REPLACE %s: %p with %p\" %\n\t\t\t\t[ attribute, entry_values, values ]\n\t\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_REPLACE, attribute, values )\n\t\tend\n\n\tend", "def modify_master_entry(master_entry, change_to_platform)\n print \"LdapHandler::modify_master_entry\\n\"\n master_entry.each { |x|\n printf(\"updating %s\\n\", x.dn) \n #operations = [[:replace, :puppetVar, [\"platform=#{change_to_platform}\"]]]\n #@ldap.modify(:dn => x.dn, :operations => operations)\n #print \"\", @ldap.get_operation_result.message, \"\\n\"\n }\n end", "def modify(args)\n modify_dn = args[:dn] or raise \"Unable to modify empty DN\"\n ops = self.class.modify_ops args[:operations]\n\n message_id = next_msgid\n request = [\n modify_dn.to_ber,\n ops.to_ber_sequence\n ].to_ber_appsequence(Net::LDAP::PDU::ModifyRequest)\n\n write(request, nil, message_id)\n pdu = queued_read(message_id)\n\n if !pdu || pdu.app_tag != Net::LDAP::PDU::ModifyResponse\n raise Net::LDAP::ResponseMissingOrInvalidError, \"response missing or invalid\"\n end\n\n pdu\n end", "def update(name, is, should)\n if should[:ensure] == :absent\n Puppet.info \"Removing #{dn(name)} from ldap\"\n delete(name)\n return\n end\n\n # We're creating a new entry\n if is.empty? or is[:ensure] == :absent\n Puppet.info \"Creating #{dn(name)} in ldap\"\n # Remove any :absent params and :ensure, then convert the names to ldap names.\n attrs = ldap_convert(should)\n create(name, attrs)\n return\n end\n\n # We're modifying an existing entry. Yuck.\n\n mods = []\n # For each attribute we're deleting that is present, create a\n # modify instance for deletion.\n [is.keys, should.keys].flatten.uniq.each do |property|\n # They're equal, so do nothing.\n next if is[property] == should[property]\n\n attributes = ldap_convert(should)\n\n prop_name = ldap_name(property).to_s\n\n # We're creating it.\n if is[property] == :absent or is[property].nil?\n mods << LDAP::Mod.new(LDAP::LDAP_MOD_ADD, prop_name, attributes[prop_name])\n next\n end\n\n # We're deleting it\n if should[property] == :absent or should[property].nil?\n mods << LDAP::Mod.new(LDAP::LDAP_MOD_DELETE, prop_name, [])\n next\n end\n\n # We're replacing an existing value\n mods << LDAP::Mod.new(LDAP::LDAP_MOD_REPLACE, prop_name, attributes[prop_name])\n end\n\n modify(name, mods)\n end", "def update!(**args)\n @collection_overrides = args[:collection_overrides] if args.key?(:collection_overrides)\n @credential = args[:credential] if args.key?(:credential)\n @custom_certificate_authority_roots = args[:custom_certificate_authority_roots] if args.key?(:custom_certificate_authority_roots)\n @description = args[:description] if args.key?(:description)\n @descriptor_url = args[:descriptor_url] if args.key?(:descriptor_url)\n @id = args[:id] if args.key?(:id)\n @insert_time = args[:insert_time] if args.key?(:insert_time)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @operation = args[:operation] if args.key?(:operation)\n @options = args[:options] if args.key?(:options)\n @self_link = args[:self_link] if args.key?(:self_link)\n end", "def edit(entry)\n return \"Node hostname cannot be empty!\" if entry['hostname'].empty?\n load\n doc = REXML::Element.new(\"NODE\")\n doc.add_attributes(entry)\n if entry['oldname'].empty?\n # adding a new node\n @@nds.each{|n|\n return \"'#{n['hostname']}' already exists!\" if n['hostname'] == entry['hostname'] && n['testbed'] == entry['testbed']\n }\n result = OMF::Services.inventory.addNode(doc.to_s)\n return AM_ERROR if !XPath.match(result, \"ADD_NODE/OK\" )\n else\n # update an existing entry\n @@nds.collect! {|n|\n if n['hostname'] == entry['oldname']\n n = entry\n n.delete('oldname')\n end\n n\n }\n end\n saveDnsmasqConfig\n return \"OK\"\n end", "def cmd_modify argv\n setup argv\n json = @hash['json']\n e = @hash['element']\n response = @api.modify(json, e)\n msg response\n return response\n end", "def domain_update(args)\n if args.key?(:chg) && args[:chg].key?(:registrant)\n raise ArgumentError, 'You need to do a trade or recover operation to change the registrant'\n end\n has_contacts = args.key?(:add) && args[:add].key?(:contacts) || args.key?(:add) && args[:add].key?(:contacts)\n has_ns = args.key?(:add) && args[:add].key?(:ns) || args.key?(:add) && args[:add].key?(:ns)\n has_other = args.key?(:add) && args[:add].key?(:status) || args.key?(:add) && args[:add].key?(:status) || args.key?(:chg) && args[:chg].key?(:authInfo)\n if [has_contacts, has_ns, has_other].count { |v| v } > 1\n raise ArgumentError, \"You can't update all that at one time\"\n end\n [:add, :rem].each do |ar|\n if args.key?(ar) && args[ar].key?(:ns) && args[ar][:ns].first.is_a?(String)\n args[ar][:ns] = args[ar][:ns].map { |ns| { :hostName => ns } }\n end\n end\n super\n end", "def attributes=(should)\n connect unless @connection\n case @resource[:entry_management]\n when :inclusive\n Puppet.debug(\"Replacing entire #{@resource[:name]} entry\")\n data = should\n data['objectclass'] = @resource[:objectclass]\n @connection.delete(:dn => @resource[:name])\n @connection.add(:dn => @resource[:name], :attributes => data)\n when :minimal\n attributes_to_update.each do |k, v|\n Puppet.debug(\"Updating #{k} with #{v} for entry #{@resource[:name]}\")\n @connection.modify(:dn => @resource[:name], :operations => [[ :replace, k.to_sym, v ]])\n end\n end\n end", "def modify(name, mods)\n connect { |connection| connection.modify dn(name), mods }\n end", "def update!(**args)\n @description = args[:description] if args.key?(:description)\n @permissions = args[:permissions] if args.key?(:permissions)\n @action = args[:action] if args.key?(:action)\n @in = args[:in] if args.key?(:in)\n @not_in = args[:not_in] if args.key?(:not_in)\n @conditions = args[:conditions] if args.key?(:conditions)\n @log_config = args[:log_config] if args.key?(:log_config)\n end", "def ldap_mod_replace( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_REPLACE, attribute.to_s, values.flatten )\n\tend", "def ldap_mod_replace( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_REPLACE, attribute.to_s, values.flatten )\n\tend", "def update\n @ldap_entry = LdapEntry.find(params[:id])\n\n respond_to do |format|\n if @ldap_entry.update_attributes(ldap_entry_params)\n format.html { redirect_to ldap_entries_path, notice: 'Ldap entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ldap_entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @entry = args[:entry] if args.key?(:entry)\n end", "def update!(**args)\n @entrys = args[:entrys] unless args[:entrys].nil?\n @kind = args[:kind] unless args[:kind].nil?\n end", "def delete_entry( c, dn ) # :yields: connection_info, distinguished_name\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n @ldap.delete dn: dn\n raise \"Unable to remove record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/\n end", "def update!(**args)\n @operations = args[:operations] if args.key?(:operations)\n @service_config_id = args[:service_config_id] if args.key?(:service_config_id)\n end", "def update_ldap_info(ldap_info)\n ldap_info.each do |key, value|\n if self.respond_to?(:\"#{key}=\")\n self.send :\"#{key}=\", value\n end\n end\n generate_attributes_from_ldap_info\n end", "def ldappassword\n\n$HOST = ''\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\nbase = 'dc=, dc='\nldapadmin = 'cn=, dc=, dc='\nldapadminpass = ''\nscope = LDAP::LDAP_SCOPE_SUBTREE\nattrs = ['sn', 'cn']\n\n#hash the password for ldap change\ne_password = \"{SHA}\" + Base64.encode64(Digest::SHA1.digest(@newpasswd)).chomp\n\nconn = LDAP::Conn.new($HOST, $PORT)\nreset = [\n LDAP.mod(LDAP::LDAP_MOD_REPLACE, \"userPassword\", [e_password]),\n]\n\n conn.bind(ldapadmin,ldapadminpass)\n begin\n conn.search(base, scope, \"uid=#{@authex.username}\", attrs) { |entry|\n $USERDN = entry.dn\n }\n rescue LDAP::ResultError\n conn.perror(\"search\")\n exit\n end\n\n begin\n conn.modify(\"#{$USERDN}\", reset)\n puts $USERDN\n rescue LDAP::ResultError => msg\n puts \"Can't change password: \" + msg\n exit 0\n rescue LDAP::Error => errcode\n puts \"Can't change password: \" + LDAP.err2string(errcode)\n exit 0\n end\n\n\n\nend", "def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n @kind = args[:kind] if args.key?(:kind)\n end", "def modify_attribute(action, key, *values)\n key = Ldaptic.encode(key)\n values.flatten!.map! {|v| Ldaptic.encode(v)}\n @original_attributes[key] ||= []\n virgin = @original_attributes[key].dup\n original = Ldaptic::AttributeSet.new(self, key, @original_attributes[key])\n original.__send__(action, values)\n begin\n namespace.modify(dn, [[action, key, values]])\n rescue\n @original_attributes[key] = virgin\n raise $!\n end\n if @attributes[key]\n read_attribute(key).__send__(action, values)\n end\n self\n end", "def update!(**args)\n @operations = args[:operations] unless args[:operations].nil?\n end" ]
[ "0.6744574", "0.6497927", "0.60004467", "0.595042", "0.59479856", "0.59115237", "0.57591045", "0.5537294", "0.5492222", "0.5431266", "0.5388358", "0.5270078", "0.5257175", "0.5213396", "0.5180569", "0.51710707", "0.5163162", "0.515719", "0.50943655", "0.50943655", "0.50694454", "0.50682765", "0.506156", "0.5055153", "0.5046399", "0.50186914", "0.50001484", "0.49764377", "0.49484053", "0.49482363" ]
0.79542965
0
== Delete Entry Expects a connection resource object, along with a .dn method that returns the Distinguished Name of the entry to be deleted.
def delete_entry( c, dn ) # :yields: connection_info, distinguished_name self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap @ldap.delete dn: dn raise "Unable to remove record: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/ end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete(dn)\n @conn.delete :dn => dn\n end", "def delete(dn)\n log_dispatch(:delete, dn)\n adapter.delete(dn)\n end", "def delete_entry(entry)\n @address_book.entries.delete(entry)\n puts \"#{entry.name} has been deleted\"\n end", "def destroy\n begin\n self.class.delete(dn)\n @new_entry = true\n rescue Error\n raise DeleteError.new(_(\"Failed to delete LDAP entry: %s\") % dn)\n end\n end", "def delete_entry(aliaz)\n\n end", "def delete(name)\n connect { |connection| connection.delete dn(name) }\n end", "def delete_entry(params)\n dd = DBDeleter.new(params)\n dd.delete\n end", "def delete(requestor, dn)\n log(\"#{requestor[:name]} #{requestor[:ip]} deleted #{dn}\")\n \n ret = {\n :status => 1,\n :message => \"Success\",\n :values => \"\"\n }\n @ds.delete(:dn => dn)\n ret = @ds.get_operation_result\n return ret\n end", "def delete(args)\n dn = args[:dn] or raise \"Unable to delete empty DN\"\n controls = args.include?(:control_codes) ? args[:control_codes].to_ber_control : nil #use nil so we can compact later\n message_id = next_msgid\n request = dn.to_s.to_ber_application_string(Net::LDAP::PDU::DeleteRequest)\n\n write(request, controls, message_id)\n pdu = queued_read(message_id)\n\n if !pdu || pdu.app_tag != Net::LDAP::PDU::DeleteResponse\n raise Net::LDAP::ResponseMissingOrInvalidError, \"response missing or invalid\"\n end\n\n pdu\n end", "def delete_entry(key, **options); end", "def destroy\n dns_entry_response = RestClient.delete('https://api.cloudflare.com/client/v4/zones/:zone_identifier/dns_records/:identifier',:content_type => :json, :accept => :json, :'x-auth-key' => session[:key] :'x-auth-email' => session[:email])\n @dns_entry.destroy\n respond_to do |format|\n format.html { redirect_to dns_entries_url, notice: \"Dns entry was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def delete_entry(key, options)\n dataset.delete Google::Cloud::Datastore::Key.new @datastore_kind_name, key\n end", "def delete_entry(cache_id:, request:)\n {\n method: \"CacheStorage.deleteEntry\",\n params: { cacheId: cache_id, request: request }.compact\n }\n end", "def delete(entry_id)\n\t\t\tkparams = {}\n\t\t\t# Data entry id to delete\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\tclient.queue_service_action_call('data', 'delete', 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 destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n redirect_to(entries_url)\n end", "def delete_entry\n\t\t#delete product from cards\n\t\t\[email protected](\"delete from cards where card_no=?\")\n\t\t\tstatement.execute(@card_no)\n\t\t#delete product from inline_products\n\t\t\[email protected](\"delete from inline_products where card_no=?\")\n\t\t\tstatement1.execute(@card_no)\n\tend", "def delete(host)\n\t\tputs \"Remove entry from the local host repository: #{host} \"\n\t\thost=host.strip.downcase\n\t\tif @known_hosts.key?(host)\n\t\t\t@known_hosts.delete(host)\n\t\t\tputs \"Entry cleared.\"\n\t\t\treturn host\n\t\telse\n\t\t\tputs \"Entry not fund. Skip: #{host}\"\n\t\tend\n\trescue => ee\n\t\tputs \"Exception on method #{__method__}: #{ee}\"\n\tend", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n head :no_content\n end", "def delete_entry(key, **options)\n failsafe(:delete_entry, returning: false) do\n with { |c| c.del key }\n end\n end", "def delete(account)\n matches = @db.find(account)\n count = 0\n matches.each do |match|\n hsay \"-\" * 40, :separator_bar\n hsay match, :normal\n hsay \"-\" * 40, :separator_bar\n\n if hagree \"Delete this entry (y/n) ?\" then\n @db.delete(match)\n count += 1\n end\n end\n hsay \"#{count} records matching '#{account}' deleted.\", :information\n end", "def delete_domain!(name)\n sdb_query({:Action => 'DeleteDomain', 'DomainName' => name})\n end", "def destroy\n @account_entry = AccountEntry.find(params[:id])\n @account_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(account_entries_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ldap_entry = LdapEntry.find(params[:id])\n @ldap_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to ldap_entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n flash[:success] = \"Entry deleted\"\n redirect_to request.referrer || root_url\n end", "def delete_entry(key, options) # :nodoc:\n @data.where(key: key).delete\n rescue Sequel::Error => e\n logger.error(\"Sequel::Error (#{e}): #{e.message}\") if logger\n false\n end", "def destroy\n @entry ||= Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n debugger\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end", "def delete_account\n @connection.request({\n :method => 'DELETE'\n })\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url, :notice => \"Entry has been deleted\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_entries_url }\n format.json { head :no_content }\n end\n end" ]
[ "0.7283597", "0.68367934", "0.68008673", "0.67022884", "0.6545504", "0.6452004", "0.63261557", "0.6283859", "0.5983127", "0.59383315", "0.5937805", "0.59077823", "0.5865994", "0.58384407", "0.5783325", "0.5737294", "0.5722508", "0.5717711", "0.570386", "0.56989276", "0.56645185", "0.56571215", "0.5579299", "0.55746925", "0.55657315", "0.5562984", "0.5556856", "0.55539024", "0.5540061", "0.55373514" ]
0.79056066
0
Just an idea, instead of localeStorage, saving the current project in Redis in a hash. Not implemented.
def cache(user) "#{user.id}_project" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def current_locale\n Thread.current[:\"localite:locale\"] || base\n end", "def translations_hash; end", "def current\n locale = I18n.locale\n @current ||=\n Rails.cache.fetch(\"languages/current/#{locale}\") do\n l = Language.find_by_group(locale)\n l ||= Language.english\n end\n end", "def switch_to(text_domain, locale)\n @store[text_domain] ||= {}\n @store[text_domain][locale] ||= {}\n @store[text_domain][locale][\"\"] = false # ignore gettext meta key when translating\n @current = @store[text_domain][locale]\n end", "def store_translations(locale, data, options = {})\n locale = locale.to_sym\n translations[locale] ||= {}\n data = data.deep_symbolize_keys\n translations[locale].deep_merge!(data)\n end", "def project\n strong_memoize(:project) do\n projects.first\n end\n end", "def git_cache\n self[KEY]\n end", "def track_locale\n I18n.locale = session[:current_locale] || I18n.default_locale\n end", "def api_hash locale=Locale.first\n \t{\n \t code: self.code, \n \t name: self.name(locale.name),\n note: self.note(locale.name),\n question: self.question(locale.name)\n }\n end", "def store_translations(locale, data)\n flatten_data(locale => data).each do |key, value|\n self[key] = value\n end\n end", "def current_locale(reload = false)\n return @locale if @locale && !reload\n @locale = locales.find(:id => 'current')\n end", "def store_language\n self.language ||= I18n.locale.to_s\n end", "def key\n @key ||= self.project.key + '-' + self.no.to_s\n 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 cache_key\n [super, user.try(:cache_key)].compact.join('/')\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 wiki_key\n # This assumes the project is Wikipedia, which is true for all wikis with the articlequality\n # or the language is nil, which is the case for Wikidata.\n @wiki_key ||= \"#{@wiki.language || @wiki.project}wiki\"\n end", "def locale_backend; end", "def project_name\n locales_CEW.websiteName\n end", "def cookie_key_name\n live_editing? ? \"steam-locale-#{site.handle}\" : 'steam-locale'\n end", "def path\n current_localization.path\n end", "def cache_key; @cache.to_sym; end", "def old_redis_key\n @old_redis_key ||= \"sphinx/integration/recent_rt:current\"\n end", "def store=(possible_store)\n @store = if possible_store.is_a?(Hash)\n Lolita::I18n::Redis_Store.new(possible_store)\n else\n possible_store\n end\n @store\n end", "def find_main_translations\n find_main_cached.translations.inject({}) { |memo, tr| memo[\"#{tr.namespace}/#{tr.tr_key}\"] = tr; memo }\n end", "def local_store\n @stores[\"sc-chi\"]\n end", "def remember(locale)\n cookies[:locale] = locale\n I18n.locale = locale\n end", "def translation\r\n translation_for(Mongoid::Globalize.locale)\r\n end", "def user_languages_hash\n result = Hash.new\n\n I18n.available_locales.each do |locale|\n result[t(\"languages.#{locale.to_s}\")] = locale.to_s\n end\n \n return result\n end", "def store_translations(locale, data, options = {})\n super\n ActiveRecord::Base.transaction do\n store_item(locale, data)\n end if store_items? && valid_locale?(locale)\n end" ]
[ "0.5913796", "0.58742917", "0.57955784", "0.5696557", "0.56920224", "0.56034577", "0.5578434", "0.5498196", "0.54722613", "0.54700357", "0.5460152", "0.5426229", "0.53552544", "0.5337919", "0.5317755", "0.5310304", "0.5302839", "0.5284406", "0.5281995", "0.5275137", "0.52645075", "0.5264381", "0.5251599", "0.5242304", "0.52336925", "0.52141577", "0.52055055", "0.5204621", "0.5193236", "0.51854044" ]
0.5911733
1
turn a href into an absolute path
def make_path(base, href) return href if href[0] == '/' base + href end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def expand_path(href)\n return href if href.match(/^https*:\\/\\//) # if starts with protocol complete link\n return @request_href unless href.match(/[a-zA-Z0-9]+/) # rejects href=\"#\" and allows non-unique exception handling.\n return @request_href if href.match(/#[a-zA-Z0-9]*$/)\n\n if href[0, 1] != \"/\"\n return @request_href + href if @request_href[-1, 1] == \"/\"\n return @request_href + \"/\" + href\n else\n # relative path from domain.\n base_url = @request_href.match(BASEURLREG).to_a.first\n return base_url + href unless base_url[-1, 1] == \"/\"\n return base_url.chop + href\n end\n end", "def url_from_href(href) #:nodoc:\n scheme, host, path = $1, $2, $3 if URL_PARTS.match href\n\n scheme = uri.scheme if scheme.nil? or scheme.empty? and uri.respond_to? :scheme\n\n host = uri.host if host.nil? or host.empty? and uri.respond_to? :host\n\n path = (\n (/\\/$/.match(uri.path)) ?\n '%s%s' % [uri.path,path] :\n '%s/%s' % [File.dirname(uri.path),path]\n ) unless /^\\//.match path\n\n '%s://%s%s' % [scheme, host, path]\n end", "def to_absolute(link)\n return nil if link.nil?\n\n # remove anchor\n link = link.to_s.gsub(/#.*$/,'')\n if Gem::Requirement.new('< 2.5').satisfied_by?(Gem::Version.new(RUBY_VERSION))\n link = URI.encode(URI.decode(link))\n end\n\n relative = URI(link)\n absolute = base ? base.merge(relative) : @url.merge(relative)\n\n absolute.path = '/' if absolute.path.empty?\n\n return absolute\n end", "def normalise_href(href)\n # ignore links which are external, or to in-page anchors\n return nil if href[0] == \"#\" || [\"/\", \"http\", \"mail\", \"/ima\"].include?(href[0, 4])\n\n # Remove any trailing anchors, or \"/\" and leading \"./\" \n target = href.sub(/\\#.*/, \"\").sub(/\\/$/, \"\").sub(/\\.*/, \"\").sub(/\\/*/, \"\")\n\n # Ignore links which don't point to html files\n /html$/.match?(target) ? target : nil\nend", "def to_absolute(link)\n # remove anchor\n link = URI.encode(link.to_s.gsub(/#[a-zA-Z0-9_-]*$/,''))\n\n relative = URI(link)\n absolute = @url.merge(relative)\n\n absolute.path = '/' if absolute.path.empty?\n\n return absolute\n end", "def absolute_url(href)\n Addressable::URI.join(self.class::DOMAIN, href).to_s\n end", "def relativize(href, path, absolute_base, root_dir)\n # href = actual href string on page\n # path = actual current location / file path of current page\n # absolute_base = the base url for the site\n\n href_url = URI.join(URI.encode(absolute_base), URI.encode(href))\n path_url = URI.join(absolute_base, URI.encode(path))\n relative_url = path_url.route_to(href_url).to_s\n url_out = test_index(relative_url, href_url, absolute_base, root_dir)\n if href.match(/^#/)\n url_out = href\n end\n url_out\nend", "def to_absolute(link, url)\n return nil if link.nil?\n url = URI(url.to_s) unless url.is_a?(URI)\n\n # remove anchor\n link = URI.encode(link.to_s.gsub(/#[a-zA-Z0-9_-]*$/,''))\n\n relative = URI(link)\n absolute = url.merge(relative)\n\n absolute.path = '/' if absolute.path.nil? or absolute.path.empty?\n\n return absolute\n end", "def to_absolute(page, link)\n # remove anchor\n link = URI.encode(link.to_s.gsub(/#[a-zA-Z0-9_-]*$/,''))\n\n relative = URI(link)\n absolute = page.url.merge(relative)\n\n absolute.path = '/' if absolute.path.empty?\n\n return absolute\n end", "def relative_link(link)\n # REMEMBER TO ADD ROUTES TO HANDLE THESE LINKS\n link.gsub!(@base, \"\").gsub!(\".html\", \"\").gsub!(\"-\", \"_\")\n end", "def to_absolute(link)\n # remove fragment\n link = link.split('#').first if link.index('#')\n url = URI(URI.encode(link))\n raise URI::InvalidURIError unless url.path\n url = @url.merge(url) if url.relative?\n url.path = '/' if url.path.empty?\n url\n end", "def convert_a(el, indent)\n\t\tif @options[:cdn_prefix]\n\t\t\tel.attr['href'] = cdn_url(el.attr['href'])\n\t\tend\n\t\t# any hrefs not starting with proto: or / or # are relative and \n\t\t# will be prefixed\n\t\tif el.attr['href'] && el.attr['href'] !~ /(^[\\w]*:|^\\/|^\\#)/\n\t\t\tel.attr['href'] = File.join(@options[:asset_prefix], el.attr['href'])\n\t\tend\n\t\tsuper\n\tend", "def link_path\n File.join(\"/f/#{@page_name}\", name) # /foo/bar_files/file.jpg\n end", "def as_href(from_path)\n RDoc::Markup::ToHtml.gen_relative_url from_path, path\n end", "def clean_url(href)\n # TODO: A better way would be to split by / then take the last section, strip off the anchor then cgi escape\n URI.unescape(href.strip).gsub(\" \", \"%20\")\n end", "def site_url(href)\n path_resolver = (@path_resolver ||= PathResolver.new)\n base_dir = path_resolver.posixify(@document.base_dir)\n site_root = path_resolver.posixify(@document.attr('site-root', base_dir))\n unless path_resolver.is_root? site_root\n raise ::ArgumentError, %(site-root must be an absolute path: #{site_root})\n end\n base_dir_to_root = nil\n if (base_dir != site_root) && (base_dir.start_with? site_root)\n comp, root = path_resolver.partition_path(base_dir.slice(site_root.length + 1, base_dir.length))\n base_dir_to_root = '../' * comp.length\n end\n path_resolver.web_path(href, base_dir_to_root)\n end", "def href\n dir = ::File.dirname(file.path)\n ext = ::File.extname(file.path)\n\n if dir != '.'\n ::File.join(dir, name.chomp(ext)) #file.path) \n else\n if name == settings.index #|| 'Home'\n 'index.html'\n else\n name.chomp(ext) #file.path\n end\n end\n end", "def url(href)\n a href, :href => href\n end", "def get_path_for(path)\n if path.respond_to?(:href)\n path = path.href\n elsif path =~ /^[^\\/]/\n if link = link_for_rel(path)\n path = link.href\n end\n end\n path\n end", "def absolutize_url(url)\n # file_path = File.expand_path(File.join(working_directory, url))\n # full_path = File.expand_path(File.join(path, url))\n # full_path.gsub(File.expand_path(path), '')\n ('/' + url.split('./').last).gsub(%r(/+), '/')\n end", "def makeAbsolute(link, currURL)\n\t\tif not ( link =~ /http/ )\n\t\t\t# relative link: create absolute link\n\n\t\t\t# .edu/pigs/index.html should be treated as .edu/pigs\n\t\t\tdirectory = /(.*#{Regexp.escape(\"/\")})\\w+#{Regexp.escape(\".\")}\\w+$/.match(currURL)\n\t\t\tif directory\n\t\t\t\tcurrURL = directory[1]\n\t\t\tend\n\n\t\t\t# remove any trailing forward slash\n\t\t\tif currURL[-1] == \"/\"\n\t\t\t\tcurrURL = currURL[0..-2]\n\t\t\tend\n\n\t\t\t# if the link starts with \"/\", don't just append\n\t\t\tif ( link =~ /^#{Regexp.escape(\"/\")}/ )\n\t\t\t\tdomain = URI.parse(currURL).host\n\t\t\t\tlink = \"http://\" + domain + link\n\t\t\telse\n\t\t\t\t# is ../ the start?\n\t\t\t\tif ( link =~ /^..#{Regexp.escape(\"/\")}/ )\n\t\t\t\t\t# make sure you can actually go back a directory: look for bowdoin.edu/***/ at least\n\t\t\t\t\tif ( currURL =~ /.*bowdoin.edu#{Regexp.escape(\"/\")}.*#{Regexp.escape(\"/\")}?/ )\n\t\t\t\t\t\t# remove first instance of ../\n\t\t\t\t\t\tadjustedLink = link[3..-1]\n\t\t\t\t\t\tshortened = /.*#{Regexp.escape(\"/\")}/.match(currURL)\n\t\t\t\t\t\t# remove / at end (guaranteed if the regex matches)\n\t\t\t\t\t\tshortened = shortened[0][0..-2]\n\n\t\t\t\t\t\t# another instance of ../?\n\t\t\t\t\t\tif ( adjustedLink =~ /^..#{Regexp.escape(\"/\")}/ )\n\t\t\t\t\t\t\t# recurse on shortened URL\n\t\t\t\t\t\t\tresult = makeAbsolute(adjustedLink, shortened)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tresult = shortened + \"/\" + adjustedLink\n\t\t\t\t\t\t\treturn result\n\t\t\t\t\t\tend\t\t\t\t\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\t# normal relative link - add to end\n\t\t\t\t\tending = /.*#{Regexp.escape(\"/\")}([^#{Regexp.escape(\"/\")}]*)$/.match(currURL)\n\t\t\t\t\tif ending\n\t\t\t\t\t\ttoMatch = ending[1]\n\t\t\t\t\t\tif ( link =~ /^#{toMatch}/ )\n\t\t\t\t\t\t\tputs \"Repeats, avoiding \" + link\n\t\t\t\t\t\t\treturn currURL\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\treturn currURL + \"/\" + link\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\treturn link\n\t\tend\n\tend", "def absolutify url, cd \n url = url.to_s\n # deal w/ bad URLs, already absolute, etc\n begin\n u = URI.parse(url)\n rescue\n # GIGO, no need for alarm\n return url\n end\n\n return url if u.absolute? # http://example.com/about\n c = URI.parse(cd)\n return c.scheme + \"://\" + c.host + url if url.index('/') == 0 # /about\n return cd + url if url.match(/^[a-zA-Z]+/) # about*\n\n # only relative from here on in; ../about, ./about, ../../about\n u_dirs = u.path.split('/')\n c_dirs = c.path.split('/')\n\n # move up the directory until there are no more relative paths\n u.path.split('/').each do |x|\n break unless (x == '' || x == '..' || x == '.')\n u_dirs.shift\n c_dirs.pop unless x == '.'\n end\n return c.scheme + \"://\" + c.host + c_dirs.join('/') + '/' + u_dirs.join('/')\n end", "def to_url(host)\n uri = URI.parse(href)\n if uri.absolute?\n if uri.host != URI.parse(host).host\n Grell.logger.debug \"GRELL does not follow links to external hosts: #{href}\"\n nil\n else\n href # Absolute link to our own host\n end\n else\n if uri.path.nil?\n Grell.logger.debug \"GRELL does not follow links without a path: #{uri}\"\n nil\n end\n if uri.path.start_with?('/')\n host + href # convert to full URL\n else # links like href=\"google.com\" the browser would go to http://google.com like \"http://#{link}\"\n Grell.logger.debug \"GRELL Bad formatted link: #{href}, assuming external\"\n nil\n end\n end\n rescue URI::InvalidURIError # Invalid links propagating till we navigate to them\n href\n end", "def link_path\n File.join('/_attachment', @page_name, name)\n end", "def absolute_url_for(uri, str)\n # TODO: use URI.parse() for better handling?\n return str if str =~ /^[|[:alpha:]]+:\\/\\//\n File.join(((uri.path.empty?) ? uri.to_s : File.dirname(uri.to_s)), \n str)\n end", "def absolutify_url(uri)\n if uri =~ /^\\w*\\:/i\n normalize_url(uri)\n else\n Addressable::URI.join(@url, uri).normalize.to_s\n end\n rescue URI::InvalidURIError, Addressable::URI::InvalidURIError => e\n add_fatal_error \"Link parsing exception: #{e.message}\" and nil\n end", "def fix_link_path(absolute_path, link)\r\n\t\tabsolute_path += \"/\" if !absolute_path.end_with?(\"/\") && !link.start_with?(\"/\")\r\n\t\tabsolute_path + link\r\n\tend", "def absolutify_url(url)\n url =~ /^\\w*\\:/i ? url : File.join(@url,url)\n end", "def href\n @href ||= build_href(path, collection: self.collection?)\n end", "def build_href(path, collection: false)\n if propstat_relative_path\n request.path_for path, collection: collection\n else\n request.url_for path, collection: collection\n end\n end" ]
[ "0.74313325", "0.7259466", "0.7234768", "0.7195484", "0.71680987", "0.71527714", "0.7023498", "0.6959961", "0.6959891", "0.6949252", "0.69085574", "0.6827566", "0.6731841", "0.67244583", "0.671601", "0.6713233", "0.67031634", "0.66990775", "0.66528964", "0.6634661", "0.6624634", "0.65588886", "0.6506714", "0.6500628", "0.6492348", "0.647526", "0.6429499", "0.6426743", "0.6413162", "0.64031446" ]
0.7278829
1
reduce any '../', './', and '//' in a path or uri
def reduce_path(path) if path =~ /^(https?:\/\/.+)(\/.*)/ prefix = $1 path = $2 relative = false else prefix = nil relative = path[0] != '/' end while path.sub!(/\/*[^\/]+\/+\.\./, ''); end while path.sub!(/\/+\.\/+/, '/'); end path = path[2..-1] if path[0..1] == './' while path.sub!(/\/\//, '/'); end path = path[1..-1] if relative and path[0] == '/' path = prefix + path if prefix path end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def uri(path)\n s = File::expand_path(path).gsub(DIR, \"\").gsub(File::SEPARATOR, '/')\n return s == '' ? '/' : s\n end", "def normalize_path(url); end", "def normalize_path(url); end", "def normalize_uri(*strs)\n new_str = strs * \"/\"\n\n new_str = new_str.gsub!(\"//\", \"/\") while new_str.index(\"//\")\n\n # Makes sure there's a starting slash\n unless new_str[0,1] == '/'\n new_str = '/' + new_str\n end\n\n new_str\n end", "def normalize_uri(*strs)\n new_str = strs * '/'\n new_str = new_str.gsub!('//', '/') while new_str.index('//')\n new_str\n end", "def fullpath(uri)\n return File.join(DIR, uri.gsub('/', File::SEPARATOR))\n end", "def humanish(uri)\n uri.path.split('/').last.gsub('.git', '')\n end", "def normalize_path(path); end", "def normalize_path(path); end", "def get_path(uri)\n name = uri.gsub(\"http://\", \"\")\n dir_list = name.split(\"/\")\n return dir_list\n end", "def uri_normalize(uri)\n \treturn 'http://' + uri unless uri =~ /http:\\/\\//\n \turi\n\tend", "def uri_normalize(uri)\n \treturn 'http://' + uri unless uri =~ /http:\\/\\//\n \turi\n\tend", "def host_and_path(uri)\n uri = URI.parse(uri) unless uri.is_a? URI\n host = uri.host\n path = uri.path.gsub(/\\/$/, '')\n path = path.empty? ? '/' : uri.path\n URI.parse(\"#{host}#{path}\")\n end", "def uri_path(str)\n str.gsub(%r{[^/]+}n) { uri_segment($&) }\n end", "def conform_uri(uri_string)\n uri_string.gsub(/^(?!\\/)(.*)/, '/\\1').gsub(/[\\/]+$/, '')\n end", "def path_without_name_and_ref(path); end", "def normalize_path(path)\n path.sub(%r{^/}, '').tr('', '')\n end", "def normalize_path(path)\n path = \"/#{path}\"\n path.squeeze!('/')\n path.sub!(%r{/+\\Z}, '')\n path = '/' if path == ''\n path\n end", "def url_for(str)\n return str if str =~ /^[|[:alpha:]]+:\\/\\//\n File.join((uri.path.empty?) ? uri.to_s : File.dirname(uri.to_s), str)\n end", "def relativize_path(path)\n path.to_s.gsub(/^\\/?#{Regexp.escape(root_path.to_s)}\\/?/, '')\n end", "def normalize_url(path)\n @known_pairs ||= {}\n @public_directories_regex ||= Regexp.new(Bones.public_directories.join('|'))\n \n if v = @known_pairs[path]\n return v\n else\n value = case\n when path =~ /^(\\w{3,}:\\/\\/|mailto)/\n # don't do anything to this type of URL\n return path\n when path =~ @public_directories_regex\n path\n when File.directory?('pages' / path)\n path\n else\n # don't add .html if there's already an extension\n path =~ /\\..+/ ? path : path + '.html'\n end\n \n @known_pairs[path] = options.base / value\n end \n end", "def normalize_path(path)\n path = \"/#{path}\"\n path.squeeze!('/')\n path.sub!(%r{/+\\Z}, '')\n path = '/' if path == ''\n path\n end", "def remove_leading_slash(path); end", "def get_file_uri_path(uri)\n uri.sub(%r{\\Afile://}, '')\n end", "def unescape_path(path); end", "def file_uri_from_path(path)\n path = path.to_s if path.is_a?(Pathname)\n path = path.tr('\\\\', '/') if windows?\n path = URI::DEFAULT_PARSER.escape(path)\n return path.start_with?('/') ? \"file://\" + path : path unless windows?\n return \"file:///\" + path.tr(\"\\\\\", \"/\") if path =~ %r{^[a-zA-Z]:[/\\\\]}\n return \"file:\" + path.tr(\"\\\\\", \"/\") if path =~ %r{\\\\\\\\[^\\\\]+\\\\[^\\\\/]+}\n path.tr(\"\\\\\", \"/\")\n end", "def simplify_path(path)\n return '' if path.empty?\n\n start_with_slash = path[0] == '/'\n stack = []\n stack << '' if start_with_slash\n tokens = path.split('/')\n tokens.each do |token|\n case token\n when '..'\n stack.pop if stack[-1] != ''\n\n when '.', ''\n next\n else\n stack.push token\n end\n end\n\n return '/' if stack.length == 1 && stack[0] == ''\n\n stack.join('/')\nend", "def absolute_url_for(uri, str)\n # TODO: use URI.parse() for better handling?\n return str if str =~ /^[|[:alpha:]]+:\\/\\//\n File.join(((uri.path.empty?) ? uri.to_s : File.dirname(uri.to_s)), \n str)\n end", "def extract_path(input)\n input_s = input.to_s\n if /^(\\w+):/.match(input_s)\n input_s.gsub(/^\\w+:[^\\/]*\\/\\/[^\\/]+(\\/[^\\?]+)(?:\\?.*)?$/, '\\1')\n else\n input_s.gsub(/(?:\\?.*)$/, '')\n end\n end", "def reg_url2; /(.+)\\//; end" ]
[ "0.7050252", "0.6911172", "0.6911172", "0.68011254", "0.677133", "0.67306715", "0.6601699", "0.65985906", "0.65985906", "0.6590226", "0.6532023", "0.6532023", "0.6453584", "0.64493656", "0.6447845", "0.6432042", "0.64209706", "0.63909125", "0.6367975", "0.6360824", "0.63547516", "0.6311897", "0.62633437", "0.6253081", "0.6232644", "0.6210744", "0.6206922", "0.62049615", "0.6193031", "0.6192998" ]
0.7364567
0
Create an empty page with necessary assets for project +p+
def create_empty_page(p) cli.say 'Creating project page' FileUtils.mkdir_p(browse_file(p, '.')) %w[favicon-32.png style.css].each do |i| FileUtils.cp(template_file(i), browse_file(p, i)) end write_file(p, 'about.html') do build_from_template('about.html', citation: MiGA::MiGA.CITATION) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_project_page(p)\n # Redirect page\n write_file(p, '../index.html') { build_from_template('redirect.html') }\n\n # Summaries\n summaries = Dir[\"#{p.path}/*.tsv\"].map do |i|\n b = File.basename(i, '.tsv')\n generate_summary_page(i, p)\n \"<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>\"\n end.join('')\n\n # Project index page\n data = {\n project_active: 'active',\n information: format_metadata(p),\n summaries: summaries.empty? ? 'None' : \"<ul>#{summaries}</ul>\",\n results: format_results(p)\n }\n write_file(p, 'index.html') { build_from_template('index.html', data) }\n end", "def create(p)\n puts \"Creating page #{p}\"\n Dir.mkdir p unless File.exists? p\n Content.new(\"#{@dir}\", @extension).page p\n end", "def create\r\n html=params[:page][:html]\r\n @page = Page.new(params[:page])\r\n respond_to do |format|\r\n if @page.save\r\n format.html { redirect_to @page, notice: 'Page was successfully created.' }\r\n format.json { render json: @page, status: :created, location: @page }\r\n target = \"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\"\r\n if !File.directory?(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}/images\")\r\n end\r\n File.open(target, \"w+\") do |f|\r\n f.write(html)\r\n end\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @page.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def setup\n @page = pages(:homepage)\n end", "def create_base_project\n puts \"creating base project\"\n directory \"templates\", \"#{app_path}\"\n end", "def generate\n # Ensure site is a directory\n FileUtils.mkdir_p site_path\n\n # If there is more than one language, then we need to create\n # multiple files, one for each language.\n if languages.size >= 1\n\n # Enter the most dastardly loop. \n # Create a View::Document with sections only containing the \n # specified language. \n languages.map do |language|\n document_views = documents.map do |document|\n document.sections = document.sections.map do |section|\n section.examples = section.examples.select {|ex| ex.language.blank? || ex.language == language }\n section\n end\n\n Views::Document.new document\n end\n\n # Use Mustache to create the file\n page = Page.new\n page.title = title\n page.logo = File.basename logo if logo\n page.documents = document_views\n\n File.open(\"#{site_path}/#{language.underscore}.html\", \"w\") do |file|\n file.puts page.render\n end\n end\n\n # copy the default language to the index and were done!\n FileUtils.cp \"#{site_path}/#{default.underscore}.html\", \"#{site_path}/index.html\"\n\n # There are no languages specified, so we can just create one page\n # using a collection of Document::View.\n else \n document_views = documents.map do |document|\n Views::Document.new document\n end\n\n page = Page.new\n page.title = title\n page.logo = File.basename logo if logo\n page.documents = document_views\n\n File.open(\"#{site_path}/index.html\", \"w\") do |file|\n file.puts page.render\n end\n end\n\n # Copy the logo if specified\n FileUtils.cp \"#{logo}\", \"#{site_path}/#{File.basename(logo)}\" if logo\n\n # Copy all the stylesheets into the static directory and that's it!\n resources_path = File.expand_path \"../resources\", __FILE__\n\n FileUtils.cp \"#{resources_path}/style.css\", \"#{site_path}/style.css\"\n FileUtils.cp \"#{resources_path}/syntax.css\", \"#{site_path}/syntax.css\"\n end", "def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end", "def create_default_template_file\n unless self.description.redirection_required?\n self.localizations.each do |page_localization|\n file_path = File.join(Rails.root, \"app\", \"views\" , \"pages\" , \"#{self.view}.#{page_localization.locale.slug}.html.haml\" )\n unless File.exists?(file_path)\n file = File.new(file_path, \"w\")\n\n page_localization.contents.each do |content|\n file.puts(\"= @page.easy_contents(:#{content.section_name})\")\n end\n file.close\n end\n end\n end\n end", "def generate_page file\n setup\n\n template_file = @template_dir + 'page.rhtml'\n\n out_file = @outputdir + file.path\n debug_msg \" working on %s (%s)\" % [file.full_name, out_file]\n rel_prefix = @outputdir.relative_path_from out_file.dirname\n search_index_rel_prefix = rel_prefix\n search_index_rel_prefix += @asset_rel_path if @file_output\n\n current = file\n asset_rel_prefix = rel_prefix + @asset_rel_path\n\n @title = \"#{file.page_name} - #{@options.title}\"\n\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io|\n here = binding\n # suppress 1.9.3 warning\n here.local_variable_set(:current, current)\n here.local_variable_set(:asset_rel_prefix, asset_rel_prefix)\n here\n end\n end", "def generate_main_page_with(specs)\n main_page = Amy::Model::Main.new\n specs['resources'].each_pair { |resource, options|\n main_page.add_resource( { 'resource' => resource, 'title' => options['title'] } )\n }\n main_page.links = specs['links'] || []\n main_page.version = specs['api_version']\n main_page.base_url = specs['base_url']\n @generator.do(\"#{Amy::BASE_DIR}/views/main.erb.html\", main_page)\n end", "def webpage\n render(:webpage, layout:false) and return\n end", "def create\n flash[:notice] = 'The page was successfully created.' if page.save\n respond_with(page, location: project_page_path(page.project, page))\n end", "def new\n @project = Project.new\n\n render :layout => \"empty\"\n end", "def create_test_page(options = {})\n no_part = options.delete(:no_part)\n page = super(options)\n unless no_part\n part = PagePart.new part_params(:name => 'body', :content => 'test')\n page.parts << part\n page.save\n part.save\n end\n page\n end", "def create_project\n empty_directory(project)\n end", "def new\n @page = @site.pages.new\n @page.parts << PagePart.new(:name => \"body\")\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @page }\n end\n end", "def first_mandate\n # renders static page\n end", "def testem_page\n testem_fields(\n \"#{Prawn::DATADIR}/images/reports/CEM2030-2012_Page_01.pdf\"\n # \"#{Rails.root}/app/assets/images/reports/testem_fields.pdf\"\n # \"#{Rails.root}/app/assets/pdfs/testem.png\"\n )\n start_new_page\n end", "def init\n @title_page = 'Pine app'\n erb :welcome, layout: :template\nend", "def default_page\n\t\t\t\tDir.chdir File.join(self.source, @site_name)\n\t\t\t\tFile.open Settings::PAGES_TEMPLATE + '/page.md', 'r' do |file|\n\n\t\t\t\t\tfront_matter = {\n\t\t\t\t\t\t'title' => 'Home Page',\n\t\t\t\t\t\t'date' => Time.now.strftime(\"%Y-%m-%d\"),\n\t\t\t\t\t\t'author' => 'Your Name',\n\t\t\t\t\t\t'template' => 'page'\n\t\t\t\t\t}\n\n\t\t\t\t\tcontents = Liquid::Template.parse(file.read).render front_matter \n\t\t\t\t\tFile.open(File.join(\"pages\", \"index.md\"), \"w\") do |f|\n\t\t\t\t\t\tf.write contents\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tFileUtils.mkdir_p(File.join(self.source, @site_name, \"media/images\", \"index\"))\n\t\t\tend", "def create_project(tx)\n Installer.copy(tx, \"#{@service_dir}/pieces/public\", get_path(:web))\n true\n end", "def add_template_pages; end", "def build\r\n self.ehtml, self.ecss, self.ejs = self.theme.page_layout.build_content() \r\n return self.ehtml, self.ecss, self.ejs\r\n end", "def create\r\n @project = current_user.projects.new(project_params)\r\n new_page = @project.pages.new({ name: generate_new_page_name})\r\n @project.startpage = new_page\r\n @project.date_created = Time.now\r\n @project.last_modified = Time.now\r\n respond_to do |format|\r\n if @project.save\r\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\r\n format.json { render action: 'show', status: :created, location: @project }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @project.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end", "def create_page\n segments = self.slug.split('/').find_all { |segment| segment != '' }\n max_segments = segments.size\n\n while segment = segments.pop do\n _options = self.page_options(slug: segment, translated: false)\n file_path = File.join(pages_path, segments, segment)\n\n # the content type option is never deleted for the first segment (the requested template)\n _options.delete(:content_type) unless segments.size == (max_segments - 1)\n\n template 'template.liquid.tt', \"#{file_path}.liquid\", _options\n\n self.other_locales.each do |locale|\n _options[:translated] = true\n template 'template.liquid.tt', \"#{file_path}.#{locale}.liquid\", _options\n end\n end\n end", "def load_index_page\n @page ||= Language.current_root_page\n render template: \"alchemy/welcome\", layout: false if signup_required?\n end", "def files_to_page\n insert_to_page('div', html)\n insert_to_page('script', js, false)\n insert_to_page('style', style, false)\n end", "def create_base_project\n raise GeneratorArgumentsError if app_path.nil?\n puts \"creating base project\"\n directory \"templates\", \"#{app_path}\"\n end", "def create_page\n @outfile.puts <<'EOF'\n<!DOCTYPE html>\n<html>\n <head>\n <title>Fun Fun Fun</title>\n <meta charset=\"utf-8\">\nEOF\n\n include_stylesheets\n include_javascript\n add_data(@batch)\n @outfile.puts <<'EOF'\n </head>\n <body>\n <svg class=\"chart\">\n </svg>\n </body>\n</html>\nEOF\n end" ]
[ "0.702871", "0.67735654", "0.6353886", "0.6273523", "0.6258971", "0.6180119", "0.613617", "0.6118454", "0.6103431", "0.6102516", "0.6098231", "0.6093809", "0.6092664", "0.60811114", "0.60627323", "0.6057448", "0.6052244", "0.60504496", "0.6045839", "0.6034876", "0.59940636", "0.5942914", "0.5938164", "0.59338003", "0.59038603", "0.5897831", "0.5892447", "0.58901954", "0.58868366", "0.58585703" ]
0.8454481
0
Create landing page for project +p+
def generate_project_page(p) # Redirect page write_file(p, '../index.html') { build_from_template('redirect.html') } # Summaries summaries = Dir["#{p.path}/*.tsv"].map do |i| b = File.basename(i, '.tsv') generate_summary_page(i, p) "<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>" end.join('') # Project index page data = { project_active: 'active', information: format_metadata(p), summaries: summaries.empty? ? 'None' : "<ul>#{summaries}</ul>", results: format_results(p) } write_file(p, 'index.html') { build_from_template('index.html', data) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_empty_page(p)\n cli.say 'Creating project page'\n FileUtils.mkdir_p(browse_file(p, '.'))\n %w[favicon-32.png style.css].each do |i|\n FileUtils.cp(template_file(i), browse_file(p, i))\n end\n write_file(p, 'about.html') do\n build_from_template('about.html', citation: MiGA::MiGA.CITATION)\n end\n end", "def index\n @main_page = \"Pessoal\"\n @page_title = \"Projetos\"\n @projects = Project.all\n @current_projects = Project.current_projects\n end", "def index\n\t @title = \"Miradi Data Server\"\n\t \"<html>Welcome to the Miradi Data Server!<br/>\" +\n\t\t\"<form action='projects' method='post' accept-charset='utf8'>\" + \n\t\t\"Project Name: <input type='text' name='name'></input>\" +\n\t\t\"<input type='submit' value='Create Project'></input>\" + \n\t\t\"</form>\"\n\tend", "def create\r\n @project = current_user.projects.new(project_params)\r\n new_page = @project.pages.new({ name: generate_new_page_name})\r\n @project.startpage = new_page\r\n @project.date_created = Time.now\r\n @project.last_modified = Time.now\r\n respond_to do |format|\r\n if @project.save\r\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\r\n format.json { render action: 'show', status: :created, location: @project }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @project.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def home\n error_404 unless (@page = Page.where(:link_url => '/').first).present?\n \n call_back\n \n @test = @profile\n @test2 = @current_patner.nil?\n \n # Member.project; Project.hoster\n \n if !Project.all.empty?\n @projects = Project.all\n end\n end", "def create_landing\r\n\r\n end", "def new\n @brigade_project = BrigadeProject.new\n general_static_response(@brigade_project)\n end", "def index\n #respond(\"<pre>\" + request.env.inspect + \"</pre>\")\n @title = \"Welcome to Pastr!\"\n end", "def new\r\n session[:from_page] = params[:from_page]\r\n session[:from_event] = params[:from_event]\r\n\r\n @project = Project.new\r\n @project.build_project_image\r\n @project.project_web_links.build\r\n @funders = Funder.all\r\n\r\n respond_to do |format|\r\n format.html {render :layout => 'backend'} # new.html.erb\r\n format.xml { render :xml => @project }\r\n end\r\n end", "def new\n @project = Project.new\n @title = \"New Project\"\n end", "def new\n @project = Project.new\n\n render :layout => \"empty\"\n end", "def create\n @project = Project.new(project_params)\n if @project.save\n redirect_to \"/charity_lp/landingpage\", notice: 'Research Form was successfully created.'\n # format.json { render :show, status: :created, location: @project }\n else\n render 'new'\n\n # format.html {redirect_to \"/projects/new\", notice: 'Errors in submition, please ensure all fields are filled in correctly' }\n # format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end", "def new\n\t\t@project = Project.new({:project_state_type_id => ProjectStateType.find_by_code('preparation').id})\n\t\tputs @project.inspect\n\t\tmake_breadcrumbs\n\t\t\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.json { render json: @project }\n\t\tend\n\tend", "def first_mandate\n # renders static page\n end", "def new_project\n @request = Request.new(data_type: :project)\n @request.build_contact\n @request.build_project\n @request.build_general_information\n\n render 'new'\n end", "def home\n @projects = Project.all.where('published = true')\n @header = \"Published Projects\"\n end", "def load_index_page\n @page ||= Language.current_root_page\n render template: \"alchemy/welcome\", layout: false if signup_required?\n end", "def show\n @page_title = \"Voluntips | Projekt: \" + @project.title\n set_show_keywords\n end", "def show\n @project = Project.find params[:id]\n @page_title = \"Project #{@project.name}\"\n end", "def home\n\t\t# Home Page\n\tend", "def new\n \t@pagenav = Page.find_all_by_published('true')\n @project = Project.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project }\n end\n end", "def index\n redirect_to index_project_path\n end", "def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end", "def new\n redirect_to project_path id: new_project_from_hash('transient' => true,\n 'name' => 'Untitled Project',\n 'default_workspace' => {\n 'name' => 'Untitled Workspace'\n }).id\n end", "def url_for_page( project, opts )\n setup_project_urls( project )\n if (opts[:page_name])\n raise \"No bulletin provided!\" if (! opts[:bulletin])\n url_for :controller => 'content', :action => 'page',\n :project_name => project.name, \n :bulletin_title => opts[:bulletin].title,\n :page_name => opts[:page_name],\n :layout => opts[:layout]\n \n end\n end", "def create\n flash[:notice] = 'The page was successfully created.' if page.save\n respond_with(page, location: project_page_path(page.project, page))\n end", "def create\n @urlroot = Designax::Application.config.urlroot\n if params[:pk] == \"new\" and params[:name] == \"project_name\"\n project_name = params[:value]\n @project = Project.new()\n @project.project_name = project_name\n else\n @project = Project.new(params[:project])\n end\n\n respond_to do |format|\n if @project.save\n redirect_url = @urlroot + \"/projects\"\n response_url = { \"url\" => redirect_url }\n format.json { render json: response_url, status: 200 }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n add_breadcrumb \"Nouveau\"\n @project = Project.new\n end", "def show\n # turn ruby database into json\n # route to the project 3 page with this json\n # id = 1\n end", "def front\n @title = \"a community for DIY environmental investigation\"\n render :template => \"home/home-2\"\n end" ]
[ "0.7371354", "0.6664608", "0.6611665", "0.6508865", "0.6410716", "0.63955003", "0.6310804", "0.6294235", "0.6290953", "0.6285155", "0.6269014", "0.6267971", "0.62649435", "0.6193769", "0.6182318", "0.6173127", "0.6159468", "0.61482817", "0.61232287", "0.61231667", "0.6119241", "0.61133945", "0.6076119", "0.6061125", "0.6037977", "0.6023587", "0.60214686", "0.6019947", "0.60066587", "0.5999332" ]
0.77630687
0
Create page for the summary +path+ in project +p+
def generate_summary_page(path, p) b = File.basename(path, '.tsv') table = '<table class="table table-hover table-responsive">' File.open(path, 'r') do |fh| fh.each do |ln| r = ln.chomp.split("\t") if $. == 1 table += '<thead><tr>' + r.map { |i| "<th scope=col>#{format_name(i)}</th>" }.join(' ') + '</tr></thead><tbody>' else table += "<tr><th scope=row>#{r.shift}</th>" + r.map { |i| "<td>#{i}</td>" }.join(' ') + "</tr>" end end end table += '</tbody></table>' write_file(p, "s-#{b}.html") do build_from_template( 'summary.html', file: "#{b}.tsv", name: format_name(b), table: table ) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_project_page(p)\n # Redirect page\n write_file(p, '../index.html') { build_from_template('redirect.html') }\n\n # Summaries\n summaries = Dir[\"#{p.path}/*.tsv\"].map do |i|\n b = File.basename(i, '.tsv')\n generate_summary_page(i, p)\n \"<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>\"\n end.join('')\n\n # Project index page\n data = {\n project_active: 'active',\n information: format_metadata(p),\n summaries: summaries.empty? ? 'None' : \"<ul>#{summaries}</ul>\",\n results: format_results(p)\n }\n write_file(p, 'index.html') { build_from_template('index.html', data) }\n end", "def create_empty_page(p)\n cli.say 'Creating project page'\n FileUtils.mkdir_p(browse_file(p, '.'))\n %w[favicon-32.png style.css].each do |i|\n FileUtils.cp(template_file(i), browse_file(p, i))\n end\n write_file(p, 'about.html') do\n build_from_template('about.html', citation: MiGA::MiGA.CITATION)\n end\n end", "def create(p)\n puts \"Creating page #{p}\"\n Dir.mkdir p unless File.exists? p\n Content.new(\"#{@dir}\", @extension).page p\n end", "def create_summary\r\n puts \"Creating a summary...\"\r\n #@lists.disp_summary\r\n create_html_summary\r\n file = File.open('test.html','w')\r\n file << @html\r\n file.close\r\n end", "def write_page(page, path = '')\n self.output_resource_op page\n\n # Note: we assume the current locale is the default one\n page.translated_in.each do |locale|\n default_locale = locale.to_sym == self.mounting_point.default_locale.to_sym\n\n # we do not need the localized version of the filepath\n filepath = page.fullpath.dasherize\n\n Locomotive::Mounter.with_locale(locale) do\n # we assume the filepath is already localized\n self.write_page_to_fs(page, filepath, default_locale ? nil : locale)\n end\n end\n\n self.output_resource_op_status page\n\n # also write the nested pages\n (page.children || []).each do |child|\n self.write_page(child, page.depth == 0 ? '' : page.slug)\n end\n end", "def generate_dataset_page(p, d)\n data = {\n unmiga_name: d.name.unmiga_name,\n information: format_metadata(d),\n results: format_results(d)\n }\n write_file(p, \"d_#{d.name}.html\") do\n build_from_template('dataset.html', data)\n end\n end", "def write_page(path, format, data, commit = {})\n write(merge_path_elements(nil, path, format), data, commit)\n end", "def projectinfo_for(p)\n res = sitemap.find_resource_by_page_id(\"projectinfo/#{project_slug(p)}\")\n if res\n return res.render\n end\n end", "def build_page(path, silent: false)\n page = sitemap[path]\n out_fname = File.join(BUILD_DIR, path)\n puts \"Rendering #{out_fname}...\" unless silent\n\n # Check page data for info on how to build this path\n if page['template'].present?\n ctx = TemplateContext.new(@config)\n ctx.page = page\n # Check if we have a layout defined, use it\n layout = ctx.page.key?('layout') ? ctx.page['layout'] : config['layout']\n\n # Make sure to render the template inside the layout render so code in the\n # erb layout and template are executed in a sensible order.\n content =\n if layout.present?\n ctx.render(layout) { ctx.render(ctx.page['template']) }\n else\n ctx.render(ctx.page['template'])\n end\n elsif page['json'].present?\n content = page['json'].to_json\n elsif page['file'].present?\n content = File.read(page['file'])\n else\n raise(\n ArgumentError,\n \"Page '#{path}' missing one of required attributes: 'template', 'json', 'file'.\"\n )\n end\n\n # If page data includes a digest flag, add sha1 digest to output filename\n if page['digest'] == true\n ext = VizBuilder.fullextname(path)\n fname = File.basename(path, ext)\n dir = File.dirname(path)\n digest = Digest::SHA1.hexdigest(content)\n digest_fname = \"#{fname}-#{digest}#{ext}\"\n page['digest_path'] = \"#{dir}/#{digest_fname}\"\n out_fname = File.join(BUILD_DIR, dir, digest_fname)\n end\n\n FileUtils.mkdir_p(File.dirname(out_fname))\n File.write(out_fname, content)\n content\n end", "def new_page_info\n args = Webby.site.args\n\n # TODO: maybe even get rid of this method altogether\n raise \"Usage: webby #{args.rake.first} 'path'\" if args.raw.empty?\n\n [args.page, args.title, args.dir]\n end", "def process_pages\n bindings = {\n :name => @definition.get_name,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:view)\n @definition.resources.each do |methods|\n methods[1].each do |resource|\n bindings.merge!(:resource => resource)\n filename = \"#{resource.slug}.html\"\n page.save_template(filename, bindings)\n end\n end\n end", "def make_page(file_path, collection: \"posts\", category: nil, tags: nil)\n PageWithoutAFile.new(@site, __dir__, \"\", file_path).tap do |file|\n file.content = feed_template\n file.data.merge!(\n \"layout\" => nil,\n \"sitemap\" => false,\n \"xsl\" => file_exists?(\"feed.xslt.xml\"),\n \"collection\" => collection,\n \"category\" => category,\n \"tags\" => tags\n )\n file.output\n end\n end", "def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end", "def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def summary\n resource = pointer[\"resource\"]\n content, id = self.get_page_content\n line_limit = @ruhoh.db.config(resource)['summary_lines']\n line_count = 0\n line_breakpoint = content.lines.count\n\n content.lines.each_with_index do |line, i|\n if line =~ /^\\s*$/ # line with only whitespace\n if line_count >= line_limit\n line_breakpoint = i\n break\n end\n else\n line_count += 1\n end\n end\n\n summary = content.lines.to_a[0, line_breakpoint].join\n\n # The summary may be missing some key items needed to render properly.\n # So search the rest of the content and add it to the summary.\n content.lines.with_index(line_breakpoint) do |line, i|\n # Add lines containing destination urls.\n if line =~ /^\\[[^\\]]+\\]:/\n summary << \"\\n#{line}\"\n end\n end\n\n summary = master.render(summary)\n Ruhoh::Converter.convert(summary, id)\n end", "def parse_project(p)\n @builder.outline(\"text\" => p[\"name\"], \"type\" => \"link\", \"url\" => p[\"url\"], \"created\" => p[\"created\"]) do\n p[\"tasks\"].each { |t| parse_task(t) }\n end\n end", "def index\n @descriptive_pages = DescriptivePage.where(Project_id: session[:current_project_id])\n @project = Project.find_by(id: session[:current_project_id])\n end", "def details_page\n @details_page ||= seed_url ? Project.fetch_details(seed_url) : Project.fetch_details(url)\n end" ]
[ "0.7484316", "0.6507673", "0.6498785", "0.63521224", "0.60548556", "0.59551257", "0.584933", "0.5718473", "0.5688941", "0.5640451", "0.5592488", "0.5543848", "0.5512932", "0.55012167", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.5489683", "0.54802626", "0.5470567", "0.54619", "0.5454729" ]
0.7636214
0
Create page for dataset +d+ within project +p+
def generate_dataset_page(p, d) data = { unmiga_name: d.name.unmiga_name, information: format_metadata(d), results: format_results(d) } write_file(p, "d_#{d.name}.html") do build_from_template('dataset.html', data) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_datasets_index(p)\n cli.say 'Creating index pages'\n data = format_dataset_index(p)\n data.each do |k, v|\n write_file(p, \"#{k}_datasets.html\") do\n v[:list] = 'None' if v[:list] == ''\n build_from_template(\n 'datasets.html',\n v.merge(:\"#{k}_datasets_active\" => 'active')\n )\n end\n end\n end", "def generate_project_page(p)\n # Redirect page\n write_file(p, '../index.html') { build_from_template('redirect.html') }\n\n # Summaries\n summaries = Dir[\"#{p.path}/*.tsv\"].map do |i|\n b = File.basename(i, '.tsv')\n generate_summary_page(i, p)\n \"<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>\"\n end.join('')\n\n # Project index page\n data = {\n project_active: 'active',\n information: format_metadata(p),\n summaries: summaries.empty? ? 'None' : \"<ul>#{summaries}</ul>\",\n results: format_results(p)\n }\n write_file(p, 'index.html') { build_from_template('index.html', data) }\n end", "def show\r\n @new_page = Page.new({project: @project, name: generate_new_page_name})\r\n @new_data_source = DataSource.new({project: @project})\r\n @pages_list = @project.pages.map {|i| [i.id, i.name]}\r\n @data_sources = @project.data_sources.includes(:data_source_type)\r\n end", "def showData\n $page = $page +\n \"<dl>\\n\" +\n \" <dt>name\\n\" +\n \" <dd>\" + $name + \"\\n\" +\n \" <dt>organization\\n\" +\n \" <dd>\" + $organization + \"\\n\" +\n \" <dt>email\\n\" +\n \" <dd>\" + $email + \"\\n\" +\n \" <dt>source\\n\" +\n \" <dd>\" + $source + \"\\n\" +\n \" <dt>use\\n\" +\n \" <dd>\" + $use + \"\\n\" +\n \" <dt>notification\\n\" +\n \" <dd>\" + $notification + \"\\n\" +\n \"</dl>\\n\"\nend", "def create(p)\n puts \"Creating page #{p}\"\n Dir.mkdir p unless File.exists? p\n Content.new(\"#{@dir}\", @extension).page p\n end", "def initialize(site, base, index_files, dir, data, name, title, template, extension, defaults = {})\n @site = site\n @base = base\n\n # @dir is the directory where we want to output the page\n # @name is the name of the page to generate\n #\n # the value of these variables changes according to whether we\n # want to generate named folders or not\n if data[name] == nil\n puts \"error (datapage_gen). empty value for field '#{name}' in record #{data}\"\n else\n filename = sanitize_filename(data[name]).to_s\n\n @dir = dir + (index_files ? \"/\" + filename + \"/\" : \"\")\n @name = (index_files ? \"index\" : filename) + \".\" + extension.to_s\n\n self.process(@name)\n self.read_yaml(File.join(base, '_layouts'), template + \".html\")\n\n # original method to set page title to data[name]\n # self.data['title'] = data[name]\n\n if title\n self.data['title'] = data[title]\n elsif data['publiccode'] && data['publiccode']['name']\n self.data['title'] = data['publiccode']['name'] + ' - ' + defaults['title_suffix']\n else\n self.data['title'] = data[name]\n end\n\n self.data.merge!(defaults)\n # add all the information defined in _data for the current record to the\n # current page (so that we can access it with liquid tags)\n self.data.merge!(data)\n end\n end", "def showData\n $page = $page +\n \"<dl>\\n\" +\n \" <dt>events\\n\" +\n \" <dd>\" + $events + \"\\n\" +\n \"</dl>\\n\"\nend", "def generate(site)\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n index_files = site.config['page_gen-dirs'] == true\n\n # data contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n data = site.config['page_gen']\n if data\n data.each do |data_spec|\n index_files_for_this_data = data_spec['index_files'] != nil ? data_spec['index_files'] : index_files\n template = data_spec['template'] || data_spec['data']\n name = data_spec['name']\n title = data_spec['title']\n dir = data_spec['dir'] || data_spec['data']\n extension = data_spec['extension'] || \"html\"\n\n if site.layouts.key? template\n # records is the list of records defined in _data.yml\n # for which we want to generate different pages\n records = nil\n data_spec['data'].split('.').each do |level|\n if records.nil?\n records = site.data[level]\n else\n records = records[level]\n end\n end\n\n # apply filtering conditions:\n # - filter requires the name of a boolean field\n # - filter_condition evals a ruby expression\n records = records.select { |r| r[data_spec['filter']] } if data_spec['filter']\n records = records.select { |record| eval(data_spec['filter_condition']) } if data_spec['filter_condition']\n\n records.each do |record|\n site.pages << DataPage.new(site, site.source, index_files_for_this_data, dir, record, name, title, template, extension, data_spec['defaults'])\n end\n else\n puts \"error (datapage_gen). could not find template #{template}\" if not site.layouts.key? template\n end\n end\n end\n end", "def create\n @dataset = Dataset.new(params[:dataset])\n prep_dataset_form\n @dataset.save!\n publish_press_item(\"New dataset added: #{@dataset.title}\")\n\n respond_to do |wants|\n flash[:notice] = 'Dataset was successfully created.'\n wants.html { redirect_to(@dataset) }\n wants.xml { render :xml => @dataset, :status => :created, :location => @dataset }\n end\n end", "def testem_page\n testem_fields(\n \"#{Prawn::DATADIR}/images/reports/CEM2030-2012_Page_01.pdf\"\n # \"#{Rails.root}/app/assets/images/reports/testem_fields.pdf\"\n # \"#{Rails.root}/app/assets/pdfs/testem.png\"\n )\n start_new_page\n end", "def generate(site)\n\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n\n index_files = site.config['page_gen-dirs'] == true\n\n # data contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n data = site.config['page_gen']\n types = site.config['data_types']\n if data\n data.each do |data_spec|\n # template = data_spec['template'] || data_spec['data']\n name = data_spec['name']\n # dir = data_spec['dir'] || data_spec['data']\n # Added 2 lines: Set context and type for JSON-LD \n context = data_spec['context'] || \"http://schema.org/\"\n # type = data_spec['type'] || \"Thing\"\n extension = data_spec['extension'] || \"html\"\n\n # records is the list of records defined in _data.yml\n # for which we want to generate different pages\n records = nil\n data_spec['data'].split('.').each do |level|\n if records.nil?\n records = site.data[level]\n else\n records = records[level]\n end\n end\n records.each do |record|\n # Added 3 lines: Add context and type for JSON-LD to each record\n collection = record[\"collection\"]\n dir = types[collection][\"dir\"] || collection\n template = types[collection][\"template\"]\n type = types[collection][\"type\"]\n record[\"@context\"] = context\n record[\"data\"][\"@type\"] = type\n record[\"data\"][\"name\"] = record[\"name\"]\n site.pages << DataPage.new(site, site.source, index_files, dir, record, name, template, extension)\n end\n end\n end\n end", "def generate(site)\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n puts \"debug\"\n index_files = site.config['page_gen-dirs']\n index_files = true if index_files.nil?\n\n # config contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n config = site.config['data_gen']\n\n # default configuration: get all data files, use the 'data_page.html' template,\n # output to /data\n path = nil\n template = 'data_page'\n dir = 'data'\n \n \n if config\n path = config['path'] || path\n template = config['template'] || template\n dir = config['dir'] || dir\n end\n\n if site.layouts.key? template\n data_files = path.nil? ? site.data : site.data[path]\n\n data_files.each do |name, record|\n site.pages << DataPage.new(site, site.source, index_files, dir, record, name, template, \"html\")\n end\n else\n puts \"DataPageGenerator error. could not find template #{template}\"\n end\n end", "def flowchart\r\n @project = Project.find(params[:project_id])\r\n @foundpages = Page.find(:all, :conditions => { :project_id => @project.id })\r\n render 'flowchart'\r\n end", "def set_page_data\n @page_title = \"Dragos | My Portfolio\"\n @seo_keywords = \"Dragos Portfolio\"\n end", "def create_page\n @outfile.puts <<'EOF'\n<!DOCTYPE html>\n<html>\n <head>\n <title>Fun Fun Fun</title>\n <meta charset=\"utf-8\">\nEOF\n\n include_stylesheets\n include_javascript\n add_data(@batch)\n @outfile.puts <<'EOF'\n </head>\n <body>\n <svg class=\"chart\">\n </svg>\n </body>\n</html>\nEOF\n end", "def index\n @descriptive_pages = DescriptivePage.where(Project_id: session[:current_project_id])\n @project = Project.find_by(id: session[:current_project_id])\n end", "def create\n @descriptive_page = DescriptivePage.new(descriptive_page_params)\n @descriptive_page.Project_id = session[:current_project_id]\n\n respond_to do |format|\n if @descriptive_page.save\n format.html { redirect_to @descriptive_page, notice: 'Descriptive page was successfully created.' }\n format.json { render :show, status: :created, location: @descriptive_page }\n else\n format.html { render :new }\n format.json { render json: @descriptive_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @page_title = \"VDW Datasets\"\n @datasets = Dataset.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @datasets }\n format.pdf\n end\n end", "def pages; end", "def get_development_application(page, da_container)\n\n #Get detail page of da\n\n detail_page = get_da_detail_page(page, da_container)\n\n \n\n #Get da summary\n\n da_summary = get_da_summary(page, da_container, detail_page)\n\n \n\n #Create a record that includes da_summary and detail_page to save to the database\n\n record = da_summary\n\n record['page_content'] = detail_page.body.to_s.force_encoding('utf-8')\n\n \n\n #Save record to database\n\n save_record_to_database(record)\n\nend", "def get_development_application(page, da_container)\n\n #Get detail page of da\n\n detail_page = get_da_detail_page(page, da_container)\n\n \n\n #Get da summary\n\n da_summary = get_da_summary(page, da_container, detail_page)\n\n \n\n #Create a record that includes da_summary and detail_page to save to the database\n\n record = da_summary\n\n record['page_content'] = detail_page.body.to_s.force_encoding('utf-8')\n\n \n\n #Save record to database\n\n save_record_to_database(record)\n\nend", "def create_page_content(page_id, data)\n create_content(Voog::API::Contents::ParentKind::Page, page_id, data)\n end", "def create_empty_page(p)\n cli.say 'Creating project page'\n FileUtils.mkdir_p(browse_file(p, '.'))\n %w[favicon-32.png style.css].each do |i|\n FileUtils.cp(template_file(i), browse_file(p, i))\n end\n write_file(p, 'about.html') do\n build_from_template('about.html', citation: MiGA::MiGA.CITATION)\n end\n end", "def index\n params[:page_title] = 'Listado de datasets de Open Data - Datos Democráticos'\n params[:page_description] = 'Listado de datasets de Open Data. Datos abiertos de instituciones principalmente gubernamentales (Open Gov).'\n\n @sel_category = params[:category]\n\n @page = (params.has_key?(:page) ? params[:page].to_i : 0)\n limit = 10\n\n @data_collections = DataCollection.all\n if not @sel_category.nil?\n @data_collections = @data_collections.joins('INNER JOIN data_collection_categories ON data_collection_categories.data_collection_id = data_collections.id').where('data_collection_categories.category_id = ?', @sel_category)\n end\n count = @data_collections.count\n\n @data_collections = @data_collections.limit(limit).offset(limit * @page)\n\n @total_pages = (count / limit).ceil\n @has_next_page = (limit * (@page + 1) < count)\n\n @categories = Category.all\n end", "def fit_pdi_page(x, y, optlist)\n @p.fit_pdi_page(self, x, y, optlist)\n end", "def new\n @project = Project.new\n @datasets = Dataset.all\n\n respond_to do |format|\n format.html\n format.xml { render xml: @project } # new.html.erb\n end\n end", "def index\n @datasets = Dataset.select_without_data.order(:name).page(params[:page])\n end", "def create_pages(page)\n skip_count = 0\n page[:content].split( SEP_PAGES ).each_with_index do |content,i|\n if content =~ PTN_METADATA\n page[:title] = $1;page[:tag] = $2\n page[:created_at] = str2time( $3 ) if !$3.blank?\n h = {};$4.split('|').each{|e| pair = e.split('=') ; h[pair[0].to_sym] = pair[1] }\n h[:public_flag] = false if !h[:public_flag] || h[:public_flag] != \"true\"\n h[:page_type] = 'N' if !h[:page_type]\n page.merge!(h)\n #$lgr.info page.inspect\n content.gsub! PTN_METADATA , \"\"\n end\n page[:content] = content\n extract_data Page.create!(page)\n end.length\n end", "def page; end", "def page; end" ]
[ "0.68037844", "0.64201796", "0.6405191", "0.6208129", "0.5913871", "0.5708373", "0.56997925", "0.5664465", "0.56394017", "0.5603932", "0.554942", "0.55379516", "0.55356014", "0.553241", "0.54918236", "0.5452057", "0.54436624", "0.54004836", "0.5386109", "0.5359547", "0.5359547", "0.5353955", "0.5346942", "0.5341443", "0.5312532", "0.53000295", "0.5295668", "0.5270518", "0.5270405", "0.5270405" ]
0.86693054
0
Create pages for reference and query dataset indexes
def generate_datasets_index(p) cli.say 'Creating index pages' data = format_dataset_index(p) data.each do |k, v| write_file(p, "#{k}_datasets.html") do v[:list] = 'None' if v[:list] == '' build_from_template( 'datasets.html', v.merge(:"#{k}_datasets_active" => 'active') ) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_indexes\n @first_page = first_page\n generate_index('index')\n generate_index('indexes')\n end", "def index_pages\n debug_msg \" generating pages search index\"\n\n pages = @files.select do |file|\n file.text?\n end\n\n pages.each do |page|\n debug_msg \" #{page.page_name}\"\n record = page.search_record\n @index[:searchIndex] << search_string(record.shift)\n @index[:longSearchIndex] << ''\n record.shift\n @index[:info] << record\n end\n end", "def process_index\n bindings = {\n :url => @definition.get_url,\n :name => @definition.get_name,\n :resources => @definition.resources,\n :description => @definition.get_description,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:index)\n page.save_template('index.html', bindings)\n end", "def generate_indexes\n @posts = DB[:posts].all\n index_layout = File.read \"#{root}/_layouts/index.html\"\n @output = Liquid::Template.parse(index_layout).render('site'=>self)\n path = \"#{root}/_site/index.html\"\n File.open(path, 'w'){ |f| f.write(@output) }\n end", "def build_index\n\n\t\t# Names the file based on date and time for uniqueness and ability to find which one you want later\n\t\tt = Time.now\n\t\t@file_time = t.strftime(\"%Y.%b.%d_%H.%M.%S\")\n\t\t@filename = \"quilt_pages/#{@needed_rows}x#{@needed_columns}_#{@file_time}.html\"\n\n\t\t# Store the quilt page template in a variable\n\t\tquilt_template = File.read \"templates/quilt_template.erb\"\n\t\t# Start a new ERB\n\t\terb_template = ERB.new quilt_template\n\t\t# Pull it all together and put info into one variable\n\t\tquilt_page = erb_template.result(binding)\n\n\t\t# Makes the directory for the quilt pages if there isn't one\n\t\tDir.mkdir(\"quilt_pages\") unless Dir.exists? \"quilt_pages\"\n\n\t\t# Opens the file and saves (actually writes) the quilt info\n\t\tFile.open(@filename, 'w') do |file|\n\t\t\tfile.puts quilt_page\n\t\tend\n\n\t\tsystem(\"open #{@filename}\")\n\tend", "def pages; end", "def create_sub_index(data, folder_num)\n create_partials data[:sub_file], data\n data[:header] = read_file(get_header_path(data[:sub_file]))\n data[:footer] = read_file(get_footer_path(data[:sub_file]))\n data[:stylesheetloc] = sub_file_stylesheet_locs\n system \"mkdir page#{folder_num}\"\n write_data data, 'data'\n system \"erb _templates/_index.html.erb > page#{folder_num}/index.html\"\n end", "def construct_index\n end", "def pages\n end", "def build_index\n reset @store.all_files.sort, @store.all_classes_and_modules.sort\n\n index_classes\n index_methods\n index_pages\n\n { :index => @index }\n end", "def index\n params[:page_title] = 'Listado de datasets de Open Data - Datos Democráticos'\n params[:page_description] = 'Listado de datasets de Open Data. Datos abiertos de instituciones principalmente gubernamentales (Open Gov).'\n\n @sel_category = params[:category]\n\n @page = (params.has_key?(:page) ? params[:page].to_i : 0)\n limit = 10\n\n @data_collections = DataCollection.all\n if not @sel_category.nil?\n @data_collections = @data_collections.joins('INNER JOIN data_collection_categories ON data_collection_categories.data_collection_id = data_collections.id').where('data_collection_categories.category_id = ?', @sel_category)\n end\n count = @data_collections.count\n\n @data_collections = @data_collections.limit(limit).offset(limit * @page)\n\n @total_pages = (count / limit).ceil\n @has_next_page = (limit * (@page + 1) < count)\n\n @categories = Category.all\n end", "def gen_main_index\n template = RDoc::TemplatePage.new @template::INDEX\n\n open 'index.html', 'w' do |f|\n classes = @classes.sort.map { |klass| klass.value_hash }\n\n values = {\n 'main_page' => @main_page,\n 'initial_page' => main_url,\n 'style_url' => style_url('', @options.css),\n 'title' => CGI.escapeHTML(@options.title),\n 'charset' => @options.charset,\n 'classes' => classes,\n }\n\n values['inline_source'] = @options.inline_source\n\n template.write_html_on f, values\n end\n end", "def generate(site)\n puts 'Indexing pages...'\n \n # gather pages and posts\n items = site.pages.dup.concat(site.posts)\n\n # only process files that will be converted to .html and only non excluded files \n items = items.find_all {|i| i.output_ext == '.html' && ! @excludes.any? {|s| (i.absolute_url =~ Regexp.new(s)) != nil } } \n items.reject! {|i| i.data['exclude_from_search'] } \n \n # only process items that are changed since last regeneration\n items = items.find_all {|i| @last_indexed.nil? || File.mtime(i.full_path_to_source) > @last_indexed }\n\n # dont process index pages\n items.reject! {|i| i.is_a?(Jekyll::Page) && i.index? }\n\t\t\t \n while not @index.running?\n # wait for the indextank index to get ready\n sleep 0.5\n end\n \n items.each do |item| \n page_text = extract_text(site,item)\n\n @index.document(item.absolute_url).add({ \n :text => page_text,\n :title => item.data['title'] || item.name \n })\n puts 'Indexed ' << item.absolute_url\n end\n \n @last_indexed = Time.now\n write_last_indexed()\n \n puts 'Indexing done'\n end", "def index\n if params[:visit_id]\n @visit = Visit.find(params[:visit_id])\n @search = @visit.image_datasets.search(params[:search])\n @image_datasets = @search.relation.page(params[:page]).per(50).all\n @total_count = @image_datasets.count\n @page_title = \"All Image Datasets for Visit #{@visit.rmr}\"\n else\n # @image_datasets = ImageDataset.find_all_by_visit_id(params[:visit_id])# .paginate(:page => params[:page], :per_page => PER_PAGE)\n # @visit = Visit.find(params[:visit_id])\n # @total_count = @image_datasets.count\n # @page_title = \"All Image Datasets for Visit #{@visit.rmr}\"\n # else\n @search = ImageDataset.search(params[:search])\n \n # Set pagination and reporting options depending on the requested format\n # (ie Don't paginate datasets on CSV download.)\n if params[:format]\n @image_datasets = @search.relation\n \n # Eventually, we'll be able to set exactly what we want included in the \n # report from the web interface. For now, we'll do it programatically \n # here in the controller.\n light_include_options = :image_dataset_quality_checks\n heavy_include_options = {\n :image_dataset_quality_checks => {:except => [:id]},\n :visit => {:methods => :age_at_visit, :only => [:scanner_source, :date], :include => {\n :enrollments => {:only => [:enumber], :include => { \n :participant => { :methods => :genetic_status, :only => [:gender, :wrapnum, :ed_years] }\n }}\n }}\n }\n else\n @image_datasets = @search.relation.page(params[:page])\n end\n \n # @total_count = all_images.size # I'm not sure where this method is coming from, but it's breaking in ActiveResource\n @total_count = ImageDataset.count\n @page_title = \"All Image Datasets\"\n end\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :text => @image_datasets.to_xml(:except => [:dicom_taghash])}\n format.csv { render :csv => ImageDataset.csv_download(@image_datasets, heavy_include_options) }\n end\n end", "def create_indexes\n indexes = %w{ Page(page_id) Trait(eol_pk) Trait(resource_pk) Term(uri) Term(name)\n Resource(resource_id) MetaData(eol_pk)}\n indexes.each do |index|\n begin\n query(\"CREATE INDEX ON :#{index};\")\n rescue Neography::NeographyError => e\n if e.to_s =~ /already created/\n puts \"Already have an index on #{index}, skipping.\"\n else\n raise e\n end\n end\n end\n end", "def index\n get_own_documents\n if @page > @pages_amount && @pages_amount != 0\n @page = @pages_amount\n get_own_documents\n end\n render_js_or_html_index\n end", "def process_pages\n bindings = {\n :name => @definition.get_name,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:view)\n @definition.resources.each do |methods|\n methods[1].each do |resource|\n bindings.merge!(:resource => resource)\n filename = \"#{resource.slug}.html\"\n page.save_template(filename, bindings)\n end\n end\n end", "def define_index_links(query)\n @links ||= []\n\n # Add some extra links to the index user is sent to if they click on an\n # undefined location.\n if query.flavor == :at_where\n @links << [:list_observations_location_define.l,\n { controller: :location, action: :create_location,\n where: query.params[:user_where] }]\n @links << [:list_observations_location_merge.l,\n { controller: :location, action: :list_merge_options,\n where: query.params[:user_where] }]\n @links << [:list_observations_location_all.l,\n { controller: :location, action: :list_locations }]\n end\n\n @links << [\n :show_object.t(type: :map),\n add_query_param(\n { controller: :observations, action: :map },\n query\n )\n ]\n\n @links << coerced_query_link(query, Location)\n @links << coerced_query_link(query, Name)\n @links << coerced_query_link(query, Image)\n\n @links << [\n :list_observations_add_to_list.t,\n add_query_param(\n { controller: :species_list, action: :add_remove_observations },\n query\n )\n ]\n\n @links << [\n :list_observations_download_as_csv.t,\n add_query_param(\n { controller: :observations, action: :download },\n query\n )\n ]\n @links\n end", "def index\n authorize IndexPage\n @index_pages = IndexPage.\n where(institution: current_institution).\n order(:name)\n end", "def index\n @datasets = Dataset.where(publication_state: [Databank::PublicationState::RELEASED, Databank::PublicationState::Embargo::FILE, Databank::PublicationState::TempSuppress::FILE, Databank::PublicationState::PermSuppress::FILE]).where(is_test: false) # used for json response\n\n @my_datasets_count = 0\n\n @search = nil\n search_get_facets = nil\n\n per_page = if params.has_key?(:per_page)\n params[:per_page].to_i\n else\n 25\n end\n\n if current_user&.role\n\n case current_user.role\n when \"admin\"\n\n search_get_facets = Dataset.search do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n without(:depositor, \"error\")\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"subjects\")\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"depositors\")\n any_of do\n params[\"depositors\"].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?(\"visibility_codes\")\n any_of do\n params[\"visibility_codes\"].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n keywords(params[:q])\n\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are only for admins\n\n search_get_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:depositor).rows.each do |outer_row|\n has_this_row = false\n\n @search.facet(:depositor).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:depositor).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n when \"depositor\"\n\n current_netid = current_user.email.split(\"@\").first\n\n search_get_my_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n any_of do\n with :depositor_email, current_user.email\n with :internal_view_netids, current_netid\n with :internal_editor_netids, current_netid\n end\n with(:is_most_recent_version, true)\n with :is_test, false\n any_of do\n with :publication_state, Databank::PublicationState::DRAFT\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n keywords(params[:q])\n facet(:visibility_code)\n end\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_test, false)\n any_of do\n with :depositor_email, current_user.email\n with :internal_view_netids, current_netid\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n all_of do\n with :depositor_email, current_user.email\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n end\n end\n end\n\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with :is_test, false\n any_of do\n with :depositor_email, current_user.email\n with :internal_view_netids, current_netid\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n\n if params.has_key?(\"depositors\")\n any_of do\n params[\"depositors\"].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?(\"editor\")\n any_of do\n with :internal_editor_netids, params[\"editor\"]\n with :depositor_netid, params[\"editor\"]\n end\n end\n\n if params.has_key?(\"subjects\")\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?(\"visibility_codes\")\n any_of do\n params[\"visibility_codes\"].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n end\n\n keywords(params[:q])\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n\n # this gets all categories for facets, even if current results do not have any instances\n\n search_get_my_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n else\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_test, false)\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n if params.has_key?(\"depositors\")\n any_of do\n params[\"depositors\"].each do |depositor|\n with :depositor, depositor\n end\n end\n end\n\n if params.has_key?(\"subjects\")\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords(params[:q])\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n end\n\n else\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n end\n\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:creator_names)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?(\"subjects\") && !params[\"subjects\"].nil?\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords(params[:q])\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are in all searchers\n\n search_get_facets.facet(:subject_text).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:subject_text).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:subject_text).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:publication_year).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:publication_year).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:publication_year).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:license_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:license_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:license_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:funder_codes).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:funder_codes).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:funder_codes).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n @report = Dataset.citation_report(@search, request.original_url, current_user)\n\n send_data @report, filename: \"report.txt\" if params.has_key?(\"download\") && params[\"download\"] == \"now\"\n end", "def indexInfo()\n # Let the user know what we're doing\n puts \"Checking and indexing info pages.\"\n\n # Build a list of all valid units\n cacheAllUnits()\n\n # First, the units that are new or changed\n batch = { dbUpdates: [], idxData: \"[\", idxDataSize: 0 }\n Unit.left_join(:info_index, unit_id: :id, page_slug: nil, freshdesk_id: nil).\n select(Sequel[:units][:id], :name, :page_slug, :freshdesk_id, :index_digest).each { |row|\n indexUnit(row, batch)\n }\n\n # Then the pages that are new or changed\n Page.left_join(:info_index, unit_id: :unit_id, page_slug: :slug).\n select(Sequel[:pages][:unit_id], :name, :title, :slug, :attrs, :index_digest).each { |row|\n indexPage(row, batch)\n }\n\n # Delete excess units and pages\n DB.fetch(\"SELECT unit_id FROM info_index WHERE page_slug IS NULL AND freshdesk_id IS NULL \" +\n \"AND NOT EXISTS (SELECT * FROM units WHERE info_index.unit_id = units.id)\").each { |row|\n deleteIndexUnit(row[:unit_id], batch)\n }\n DB.fetch(\"SELECT unit_id, page_slug FROM info_index WHERE page_slug IS NOT NULL \" +\n \"AND NOT EXISTS (SELECT * FROM pages WHERE info_index.unit_id = pages.unit_id \" +\n \" AND info_index.page_slug = pages.slug)\").each { |row|\n deleteIndexPage(row[:unit_id], row[:page_slug], batch)\n }\n\n # Flush the last batch\n flushInfoBatch(batch, true)\nend", "def create_main_index(data)\n create_partials data[:sub_file], data\n data[:header] = read_file(get_header_path(data[:sub_file]))\n data[:footer] = read_file(get_footer_path(data[:sub_file]))\n data[:stylesheetloc] = main_file_stylesheet_locs\n write_data data, 'data'\n system 'erb _templates/_index.html.erb > index.html'\n end", "def index\r\n build_index unless @index\r\n @index\r\n end", "def index\n\n @datasets = Dataset.where(publication_state: [Databank::PublicationState::RELEASED, Databank::PublicationState::Embargo::FILE, Databank::PublicationState::TempSuppress::FILE, Databank::PublicationState::PermSuppress::FILE]).where(is_test: false) #used for json response\n\n @my_datasets_count = 0\n\n @search = nil\n search_get_facets = nil\n\n if params.has_key?(:per_page)\n per_page = params[:per_page].to_i\n else\n per_page = 25\n end\n\n if current_user&.role\n\n case current_user.role\n when \"admin\"\n\n search_get_facets = Dataset.search do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n end\n\n @search = Dataset.search do\n\n without(:depositor, 'error')\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('depositors')\n any_of do\n params['depositors'].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?('visibility_codes')\n any_of do\n params['visibility_codes'].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n keywords (params[:q])\n\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are only for admins\n\n search_get_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:depositor).rows.each do |outer_row|\n has_this_row = false\n\n @search.facet(:depositor).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:depositor).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n\n when \"depositor\"\n\n current_netid = current_user.email.split(\"@\").first\n\n search_get_my_facets = Dataset.search do\n all_of do\n without(:depositor, 'error')\n any_of do\n with :depositor_email, current_user.email\n with :internal_editor_netids, current_netid\n end\n with(:is_most_recent_version, true)\n with :is_test, false\n any_of do\n with :publication_state, Databank::PublicationState::DRAFT\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n keywords(params[:q])\n facet(:visibility_code)\n\n end\n\n search_get_facets = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with(:is_test, false)\n any_of do\n with :depositor_email, current_user.email\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n all_of do\n with :depositor_email, current_user.email\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n end\n all_of do\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n end\n end\n end\n\n keywords (params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n end\n\n @search = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with :is_test, false\n any_of do\n with :depositor_email, current_user.email\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n\n if params.has_key?('depositors')\n any_of do\n params['depositors'].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?('visibility_codes')\n any_of do\n params['visibility_codes'].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n end\n\n keywords (params[:q])\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n\n # this gets all categories for facets, even if current results do not have any instances\n\n search_get_my_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n else\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n\n keywords (params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n\n all_of do\n\n without(:depositor, 'error')\n with(:is_test, false)\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n if params.has_key?('depositors')\n any_of do\n params['depositors'].each do |depositor|\n with :depositor, depositor\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords (params[:q])\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n end\n\n else\n\n search_get_facets = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n end\n\n keywords (params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:creator_names)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords (params[:q])\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are in all searchers\n\n search_get_facets.facet(:subject_text).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:subject_text).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:subject_text).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:publication_year).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:publication_year).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:publication_year).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:license_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:license_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:license_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:funder_codes).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:funder_codes).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:funder_codes).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n @report = Indexable.citation_report(@search, request.original_url, current_user)\n\n if params.has_key?('download') && params['download'] == 'now'\n send_data @report, :filename => 'report.txt'\n end\n\n end", "def build_indices\n @files, @classes = RDoc::Generator::Context.build_indices(@toplevels,\n @options)\n end", "def build_indices\n @files, @classes = RDoc::Generator::Context.build_indices(@toplevels,\n @options)\n end", "def pages=(_arg0); end", "def initialize(site, base, index_files, dir, data, name, title, template, extension, defaults = {})\n @site = site\n @base = base\n\n # @dir is the directory where we want to output the page\n # @name is the name of the page to generate\n #\n # the value of these variables changes according to whether we\n # want to generate named folders or not\n if data[name] == nil\n puts \"error (datapage_gen). empty value for field '#{name}' in record #{data}\"\n else\n filename = sanitize_filename(data[name]).to_s\n\n @dir = dir + (index_files ? \"/\" + filename + \"/\" : \"\")\n @name = (index_files ? \"index\" : filename) + \".\" + extension.to_s\n\n self.process(@name)\n self.read_yaml(File.join(base, '_layouts'), template + \".html\")\n\n # original method to set page title to data[name]\n # self.data['title'] = data[name]\n\n if title\n self.data['title'] = data[title]\n elsif data['publiccode'] && data['publiccode']['name']\n self.data['title'] = data['publiccode']['name'] + ' - ' + defaults['title_suffix']\n else\n self.data['title'] = data[name]\n end\n\n self.data.merge!(defaults)\n # add all the information defined in _data for the current record to the\n # current page (so that we can access it with liquid tags)\n self.data.merge!(data)\n end\n end", "def build_docs\n object_map.each do |index, objects|\n objects.each do |object|\n template_context = {\n #:meta => Site\n index => object\n }\n content = converter.render(template_map[index], template_context)\n filename = converter.filename_for(object)\n write_output_file(filename, content)\n end\n end\n end", "def generate_index\n page = {}\n page[:title] = nil\n page[:body] = \"\"\n \n @posts.keys.sort.reverse.each_with_index do |date, i|\n if i >= @config[:front_page_entries]\n break\n else\n post = @posts[date]\n \n # Don't post the whole thing on the front page.\n unless post[:excerpt].nil?\n post[:body] = ''\n end\n\n page[:body] << generate_post(@posts[date])\n end\n end\n\n File.open(File.join(@site_path, 'index.html'), 'w') do |f|\n f << generate_page(page)\n end\n end" ]
[ "0.7581115", "0.7085274", "0.69342494", "0.66503674", "0.6550457", "0.6513609", "0.6435873", "0.63384014", "0.63214314", "0.628524", "0.6247826", "0.62302375", "0.6215779", "0.6195686", "0.6191556", "0.61650985", "0.6163107", "0.6147718", "0.61047316", "0.60825545", "0.6070926", "0.60394925", "0.60330474", "0.6025197", "0.60031056", "0.60031056", "0.59985137", "0.5989121", "0.5986344", "0.59775454" ]
0.73654836
1
Format +obj+ metadata as a table
def format_metadata(obj) '<table class="table table-sm table-responsive">' + obj.metadata.data.map do |k, v| case k when /^run_/, :plugins, :user next when :web_assembly_gz v = "<a href='#{v}'>#{v[0..50]}...</a>" when :datasets v = v.size end "<tr><td class='text-right pr-4'><b>#{format_name(k)}</b></td>" \ "<td>#{v}</td></tr>" end.compact.join('') + '</table>' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def table_row(obj, out_mode, depth)\n row = []\n variables = out_mode == :full ? obj.class::FIELDS_FULL : obj.class::FIELDS_SUMMARY\n variables.each do |var|\n val = obj.instance_variable_get(\"@#{var}\")\n val = val[0..32] if out_mode == :summary # Shorten data for summary - BRUTE FORCE - should be neater\n row << val\n end\n if depth == :deep\n # Deep! So check the connection, do a search and attach the new column/row\n row << deep_data(obj)\n end\n row\n end", "def color_table(*obj)\n colors = obj.map do |vals|\n attr = {}\n vals = vals.strip.split(\"\\n\").map do |val|\n val.gsub(/RGB|HEX|CMYK|Pantone/i, '').strip\n end\n\n attr[:name] = vals.shift\n\n vals.each do |val|\n next if val.empty?\n case val\n when /#[0-9a-fA-F]{3,6}/ then attr[:hex] = val\n when /(\\d+\\D+){3}\\d+/ then attr[:cmyk] = val\n when /(\\d+\\D+){2}\\d+/ then attr[:rgb] = val\n else attr[:pantone] = val\n end\n end\n\n attr\n end\n\n format_color_table colors\n end", "def prettify(obj)\n # Most look best with pretty_inspect\n str = obj.pretty_inspect\n # Mashes need to be first converted to Hashes then pretty_inspect\n if obj.kind_of? Mash\n str = obj.to_hash.pretty_inspect\n end\n # For Arrays, pretty_inspect displays one value per line which\n # uses up too much real estate\n if obj.kind_of? Array\n str = obj.inspect\n end\n # Manually format Hashes so keys and values each display in columns\n if obj.kind_of? Hash\n key_length = 0\n obj.keys.each do |key|\n key_length = key.length if key.length > key_length\n end\n buf = []\n obj.each do |key,value|\n buf << sprintf(\"%-#{key_length}.#{key_length}s => %s\", key, value)\n end\n str = buf.join(\"\\n\")\n end\n str\n end", "def EXCEL_TABLE(objects, *arguments)\n DebugTable.new(objects, arguments, :tsv)\n end", "def dump_table(io, table_obj)\n create_data = table_obj.data.clone\n create_data.delete(:name)\n create_data[:return_sql] = true\n\n # Get SQL for creating table and add it to IO.\n sqls = @export_db.tables.create(table_obj.name, **create_data)\n sqls.each do |sql|\n io.write(\"#{sql};\\n\")\n end\n\n\n # Try to find a primary column in the table.\n prim_col = nil\n table_obj.columns do |col|\n if col.primarykey?\n prim_col = col\n break\n end\n end\n\n\n debug \"Dumping data for table: #{table_obj.name}\"\n\n # Set up rows and way to fill rows.\n rows = []\n\n\n @db.select(table_obj.name, nil, unbuffered: true) do |row|\n rows << row\n @rows_count += 1\n\n if rows.length >= 1000\n update_status\n dump_insert_multi(io, table_obj, rows)\n end\n end\n\n\n # Dump the last rows if any.\n dump_insert_multi(io, table_obj, rows) unless rows.empty?\n end", "def TXT_TABLE(objects, *arguments)\n DebugTable.new(objects, arguments, :txt)\n end", "def object_csv(hash, namespaces)\n namespace = hash.dig(\"metadata\", \"namespace\")\n team, repo = namespace_team_repo(namespace, namespaces)\n\n [\n hash.fetch(\"kind\"),\n hash.fetch(\"apiVersion\"),\n hash.dig(\"metadata\", \"name\"),\n namespace,\n team,\n repo\n ].join(\", \")\nend", "def format_list\n config = TABLE[@vobject][:columns]\n CLIHelper::ShowTable.new do\n column :DATACENTER,\n 'Object datacenter',\n :size => config[:DATACENTER] || 15 do |d|\n d[:datacenter]\n end\n\n column :IMID, 'identifier for ...', :size=>config[:IMID] || 4 do |d|\n d[:import_id]\n end\n\n column :REF, 'ref', :left, :adjust, :size=>config[:REF] || 15 do |d|\n d[:ref] || d[:cluster_ref]\n end\n\n column :NAME, 'Name', :left, :expand,\n :size=>config[:NAME] || 20 do |d|\n d[:name] || d[:simple_name]\n end\n\n column :CLUSTERS, 'CLUSTERS', :left,\n :size=>config[:CLUSTERS] || 10 do |d|\n d = d[:clusters] if d[:clusters]\n d[:one_ids] || d[:cluster].to_s\n end\n\n column :PATH, 'PATH', :left, :expand,\n :size=>config[:PATH] || 10 do |d|\n d[:path]\n end\n\n default(*config.keys)\n end\n end", "def format_object(obj)\n if obj.kind_of? Exception\n return \"Caught #{obj.class}: #{obj.message}\\n\\t\" +\n (obj.backtrace.nil? ? [] : obj.backtrace[0...@depth]).join(\"\\n\\t\")\n elsif obj.kind_of? String\n return obj\n else # inspect the object\n return \"#{obj.class}: #{obj.inspect}\"\n end\n end", "def dump_table(io, table_obj)\n #Get SQL for creating table and add it to IO.\n sqls = @args[:db].tables.create(table_obj.name, table_obj.data, :return_sql => true)\n sqls.each do |sql|\n io.write(\"#{sql};\\n\")\n end\n \n \n #Try to find a primary column in the table.\n prim_col = nil\n table_obj.columns do |col|\n if col.primarykey?\n prim_col = col\n break\n end\n end\n \n \n #Set up rows and way to fill rows.\n rows = []\n block_data = proc do |row|\n rows << row\n @rows_count += 1\n \n if rows.length >= 1000\n self.update_status\n self.dump_insert_multi(io, table_obj, rows)\n end\n end\n \n \n #If a primary column is found then use IDQuery. Otherwise use cloned unbuffered query.\n args = {:idquery => prim_col.name.to_sym} if prim_col\n \n \n #Clone the connecting with array-results and execute query.\n @args[:db].clone_conn(:result => \"array\") do |db|\n db.select(table_obj.name, nil, args, &block_data)\n end\n \n \n #Dump the last rows if any.\n self.dump_insert_multi(io, table_obj, rows) if !rows.empty?\n end", "def show(obj)\n y(obj.send(\"column_names\"))\nend", "def show(obj)\n y(obj.send(\"column_names\"))\nend", "def schema(obj)\n y(obj.send(\"column_names\"))\nend", "def generate_tabular_report(filename, ostream)\n file = File.read(filename)\n data_hash = JSON.parse(file)\n rpt_data = transform(data_hash)\n rpt_data.keys.each do |name|\n ostream.puts\n ostream.puts name\n tbl = create_resources_table(rpt_data[name]['resources'])\n tbl.each do |r|\n ostream.puts r.join(\"\\t\")\n end\n end\nend", "def inspect\n to_table.render :ascii\n end", "def print_table_t(objects, *method_names)\n terminal_width = `tput cols`.to_i\n cols = objects.count + 1 # Label column\n col_width = (terminal_width / cols) - 1 # Column spacing\n\n Array(method_names).map do |method_name|\n cells = objects.map { |o| o.send(method_name).inspect }\n cells.unshift(method_name)\n\n puts cells.map { |cell| cell.to_s.ljust(col_width) }.join \" \"\n end\n nil\nend", "def table_specific_items(objects)\n @tableheadings, @tablecolumncount = objects[0].table_headings\n @tablerow = tablerow_array(objects)\n @tablerowcount = @tablerow.count\n end", "def <<(obj)\n if obj.is_a?(String) || obj.is_a?(Integer)\n td = Table::Row::Data.new(obj.to_s)\n super(td)\n else\n expect(obj, [Data, Header])\n end\n super(obj)\n end", "def to_table\n headers = fields.map { |field| field.label.downcase }\n body = fields.map { |field| field.to_s.downcase }\n\n [headers, body]\n end", "def logs_table(obj, args = {})\n html = args[:out] || $stdout\n\n html << \"<table class=\\\"list hayabusa_log_table\\\">\"\n html << \"<thead>\"\n html << \"<tr>\"\n html << \"<th>ID</th>\"\n html << \"<th>Message</th>\"\n html << \"<th style=\\\"width: 130px;\\\">Date &amp; time</th>\"\n html << \"<th>Tag</th>\"\n html << \"<th>Objects</th>\" if args[:ob_use]\n html << \"<th>IP</th>\" if args[:show_ip]\n html << \"</tr>\"\n html << \"</thead>\"\n html << \"<tbody>\"\n\n count = 0\n @ob.list(:Log_link, {\"object_class\" => obj.class.name, \"object_id\" => obj.id, \"limit\" => 500, \"orderby\" => [[\"id\", \"desc\"]]}) do |link|\n count += 1\n log = link.log\n\n msg_lines = log.text.split(\"\\n\")\n first_line = msg_lines[0].to_s\n\n classes = [\"hayabusa_log\", \"hayabusa_log_#{log.id}\"]\n classes << \"hayabusa_log_multiple_lines\" if msg_lines.length > 1\n\n html << \"<tr class=\\\"#{classes.join(\" \")}\\\">\"\n html << \"<td>#{log.id}</td>\"\n html << \"<td>#{first_line.html}</td>\"\n html << \"<td>#{log.date_saved_str}</td>\"\n html << \"<td>#{log.tag.html}</td>\"\n\n if args[:ob_use]\n begin\n html << \"<td>#{log.objects_html(args[:ob_use])}</td>\"\n rescue => e\n html << \"<td>#{e.message.html}</td>\"\n end\n end\n\n html << \"<td>#{log.ip}</td>\" if args[:show_ip]\n html << \"</tr>\"\n end\n\n if count <= 0\n html << \"<tr>\"\n html << \"<td colspan=\\\"2\\\" class=\\\"error\\\">No logs were found for that object.</td>\"\n html << \"</tr>\"\n end\n\n html << \"</tbody>\"\n html << \"</table>\"\n\n return nil\n end", "def table_data(objects, *arguments)\n rows = [[*arguments]]\n\n rows += flatten_uniq(objects).map do |obj|\n arguments.map do |argument|\n begin\n obj = obj.query if obj.respond_to?(:query)\n if argument.respond_to?(:call)\n obj.instance_eval(&argument)\n else\n obj.instance_eval(argument.to_s)\n end\n rescue => e\n 'error'\n end\n end\n end\n\n rows\n end", "def get_table(object)\n raise NotImplementedError, \"Subclasses must implement private method get_table\"\n end", "def to_table\n @doc.make_table(data, table_options)\n end", "def format_result(obj)\n formatted_str = \"\\n\\nSearch Results: \\n\\n\"\n obj.each do |key, value|\n unless key == \"_id\"\n\t key_str = key.capitalize\n\t if value.kind_of?(Array)\n\t\t \tformatted_str << key_str << \": \"\n\t\t \tvalue.each do |var|\n\t\t \t\tformatted_str << var.to_s << ((var == value.last) ? \"\" : \",\")\n\t\t \tend\n\t\t \tformatted_str << \"\\n\"\n\t elsif value.is_a?(Hash)\n\t\t formatted_str << key_str << \": \" << \"\\n\"\n\t\t value.each do |var_key, var_value|\n\t\t formatted_str << \"\\t\" << var_key << \":\" << var_value << \"\\n\"\n\t\t end\n\t else\n\t\t formatted_str << key_str << \": \" << value.to_s << \"\\n\"\n\t end\n\t end\n end\n formatted_str\n end", "def to_table\n mortadella = Mortadella::Horizontal.new headers: %w[NAME LOCATION]\n @tags.keys.sort.each do |tag_name|\n mortadella << [tag_name, @tags[tag_name].to_sentence]\n end\n mortadella.table\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 export_table export_obj\n @export_obj = export_obj\n\n ExportMetadata.record(:table => @export_obj.table_name,\n :database => @export_obj.source_schema,\n :export_to => load_to,\n :export_id => @export_obj.id,\n :filepath => filepath,\n :store_in => @export_obj.s3_path,\n :incremental_col => @export_obj.incremental_column) do |metadata|\n\n prepare metadata\n\n if (@export_obj.export_type? == :new && load_to == \"mysql\") || load_to == \"mysql\"\n on_failure_state_trans(metadata, \"new\") # If failed, go back to new\n on_export_success(metadata)\n initial_export metadata\n elsif @export_obj.export_type? == :incremental || load_to == \"vertica\"\n on_failure_state_trans(metadata, \"failed\") # Set state trans on failure\n on_export_success(metadata)\n incremental_export_into_outfile metadata\n end\n\n end # metadata\n end", "def convert_to_csv(obj_array)\n CSV.generate(headers: true) do |csv|\n csv << obj_array.first.keys\n\n obj_array.each do |object|\n csv << object.values\n end\n end\n end", "def print_object(issues)\n if issues.nil?\n raise \"nil issue\"\n end\n if !issues.is_a? Array\n issues = [issues]\n end\n\n count = issues.length\n if issues.empty?\n return \"0 rows returned\"\n end\n\n table = Terminal::Table.new do |t|\n if @set_width\n width, height = HighLine::SystemExtensions.terminal_size\n t.style = {:width => width}\n end\n header = []\n sorted_fields = sort_fields(filter_fields(issues.first.keys))\n sorted_fields.each do |key|\n h = key.to_s.capitalize\n h = h.blue if @color\n header << h\n end\n\n t << header\n t << :separator\n\n issues.each do |hash|\n row = []\n sorted_fields.each do |key|\n row << format_field(hash, key)\n end\n t << row\n end\n end.to_s + \"#{count} rows returned\"\n end", "def model_headerleft(obj, options=Hash.new)\n begin\n display = obj.class::DISPLAY_ATTRIBUTES\n rescue NameError\n end\n display = options[:only].map {|key| key.to_s} if options[:only]\n display = obj.attributes.map {|key,value| key} if display == nil\n display.delete_if {|key| options[:except].include?(key.to_sym)} if options[:except]\n retval = \"\"\n display.each do |field|\n # Process the value\n value = obj.send(field.to_sym)\n if field[-3..-1] == \"_id\"\n begin\n klass = field[0..-4]\n helper_method_ref = klass + \"_headerleft\"\n alt_obj = obj.send(klass.to_sym)\n value = obj.send(klass.to_sym).name\n\n begin\n value = self.send(helper_method_ref.to_sym, alt_obj)\n rescue NameError\n end\n rescue NoMethodError\n end\n end\n\n if value.kind_of?(Array)\n response_ary = []\n value.each do |val|\n helper_method_ref = val.class.to_s.underscore+\"_headerleft\"\n begin\n response_ary << self.send(helper_method_ref.to_sym, val)\n rescue NameError\n response_ary << val.name\n end\n end\n value = response_ary.join \", \"\n end\n\n if value.kind_of?(Time) || value.kind_of?(Date)\n if value > Date.new(1950,1,1)\n # When a date is too long ago, time_ago_in_words falls apart. In early 2008, this was a date in 1901. I'm cutting off any possibility of problems for the next 50 years by going with 1950 instead.\n value = \"#{time_ago_in_words(value)} ago (#{value.to_date.to_s(:long)})\"\n else\n value = value.to_date.to_s(:long)\n end\n end\n if value.kind_of?(String) && (value[0..6] == \"http://\" || value[0..7] == \"https://\")\n value = link_to(value, value)\n end\n\n retval += field_fmt(field.humanize, value, field) + \"\\n\"\n end\n retval\n end" ]
[ "0.63745046", "0.6241079", "0.62046194", "0.5997506", "0.5989809", "0.59521073", "0.5918139", "0.58749056", "0.58509296", "0.5800575", "0.578684", "0.578684", "0.5783817", "0.5769742", "0.57531536", "0.574793", "0.57232594", "0.5713948", "0.5704228", "0.56967455", "0.5633141", "0.5614438", "0.5573691", "0.5537945", "0.5522724", "0.55076814", "0.5488932", "0.548793", "0.54848534", "0.5482798" ]
0.7606932
0
Format +obj+ results as cards
def format_results(obj) o = '' obj.each_result do |key, res| links = format_result_links(res) stats = format_result_stats(res) next unless links || stats name = format_name(key) url_doc = 'http://manual.microbial-genomes.org/part5/workflow#' + key.to_s.tr('_', '-') o += <<~CARD <div class="col-md-6 mb-4"> <h3>#{name}</h3> <div class='border-left p-3'> #{stats} #{links} </div> <div class='border-top p-2 bg-light'> <a target=_blank href="#{url_doc}" class='p-2'>Learn more</a> </div> </div> CARD end "<div class='row'>#{o}</div>" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def format_result(obj)\n formatted_str = \"\\n\\nSearch Results: \\n\\n\"\n obj.each do |key, value|\n unless key == \"_id\"\n\t key_str = key.capitalize\n\t if value.kind_of?(Array)\n\t\t \tformatted_str << key_str << \": \"\n\t\t \tvalue.each do |var|\n\t\t \t\tformatted_str << var.to_s << ((var == value.last) ? \"\" : \",\")\n\t\t \tend\n\t\t \tformatted_str << \"\\n\"\n\t elsif value.is_a?(Hash)\n\t\t formatted_str << key_str << \": \" << \"\\n\"\n\t\t value.each do |var_key, var_value|\n\t\t formatted_str << \"\\t\" << var_key << \":\" << var_value << \"\\n\"\n\t\t end\n\t else\n\t\t formatted_str << key_str << \": \" << value.to_s << \"\\n\"\n\t end\n\t end\n end\n formatted_str\n end", "def render(obj)\n # We can't use a case statement here becuase \"when Hash\" doesn't work for\n # ActiveSupport::OrderedHash - respond_to?(:values) is a more reliable\n # indicator of hash-like behavior.\n if NilClass === obj\n print(\"null\")\n \n elsif TrueClass === obj\n print(\"true\")\n \n elsif FalseClass === obj\n print(\"false\")\n \n elsif String === obj\n print(escape_json_string(obj))\n \n elsif Symbol === obj\n print(\"\\\"#{obj}\\\"\")\n \n elsif Numeric === obj\n print(obj.to_s)\n \n elsif Time === obj\n print(obj.to_s)\n \n elsif obj.respond_to?(:keys)\n print(\"{\")\n indent_out\n last_key = obj.keys.last\n obj.each do |(key, val)|\n render(key)\n case val\n when Hash, Array\n indent_out\n print(\":\\n#{indent}\")\n render(val)\n indent_in\n else\n print(\": \")\n render(val)\n end\n print(\",\\n#{indent}\") unless key == last_key\n end\n indent_in\n print(\"}\")\n \n elsif Array === obj\n print(\"[\")\n indent_out\n last_index = obj.size - 1\n obj.each_with_index do |elem, index|\n render(elem)\n print(\",\\n#{indent}\") unless index == last_index\n end\n indent_in\n print(\"]\")\n \n else\n raise \"unrenderable object: #{obj.inspect}\"\n end\n end", "def print_cards\n str_arr = @cards.map { |card| card.to_s }\n cards_str = str_arr.join(\", \")\n \"#{@name}'s cards: #{cards_str}\"\n end", "def SplitJsonObj(jsonObj, sortedBy)\n\tjsonObj.each do |color|\n\t\tputs \"\\n---\" + color[sortedBy] + \"---\\n\"\n\t\tputs color[\"cards\"]\n\tend\nend", "def prettify(obj)\n # Most look best with pretty_inspect\n str = obj.pretty_inspect\n # Mashes need to be first converted to Hashes then pretty_inspect\n if obj.kind_of? Mash\n str = obj.to_hash.pretty_inspect\n end\n # For Arrays, pretty_inspect displays one value per line which\n # uses up too much real estate\n if obj.kind_of? Array\n str = obj.inspect\n end\n # Manually format Hashes so keys and values each display in columns\n if obj.kind_of? Hash\n key_length = 0\n obj.keys.each do |key|\n key_length = key.length if key.length > key_length\n end\n buf = []\n obj.each do |key,value|\n buf << sprintf(\"%-#{key_length}.#{key_length}s => %s\", key, value)\n end\n str = buf.join(\"\\n\")\n end\n str\n end", "def display_object\n\tputs \"Name: #{name}\"\n\tpretty_price = format(\"%0.2f\", price)\n\tputs \"Price: $#{pretty_price}\"\n\tputs \"Size: #{size}\"\n end", "def to_hcard(options = {}, &block)\n result = []\n clasess = ['fn']\n clasess << 'org' if org == fn\n if url?\n clasess << 'url'\n result << \"<a class='#{clasess.join(' ')}' href='#{url}'>#{fn}</a>\"\n else\n result << \"<span class='#{clasess.join(' ')}'>#{fn}</span>\"\n end\n result << \"(<span class='nickname'>#{nickname}</span>)\" if nickname?\n result << \"<abbr class='bday' title='#{bday.to_s}'>#{I18n.l(bday, :format => :long)}</abbr>\" if bday?\n result << \"<span class='title'>#{title}</span>\" if title?\n result << \"<span class='role'>#{role}</span>\" if role?\n result << \"<span class='org'>#{org}</span>\" if org.present? && org != fn\n vcard_adrs.each do |adr|\n result << adr.to_hcard\n end\n result << \"<abbr class='geo' title='#{geo}'>Location</abbr>\" if geo.present?\n # result << \"<span class='geo'><abbr class='latitude' title='#{latitude}'>N 48° 81.6667</abbr><abbr class='longitude' title='2.366667'>E 2° 36.6667</abbr></span>\" if geo.present?\n vcard_tels.each do |tel|\n result << tel.to_hcard\n end\n vcard_emails.each do |email|\n result << email.to_hcard\n end\n # result.compact!\n result << agent.to_hcard if agent_id? # TODO add agent class?\n main_tag_name = options.fetch(:main_tag_name, 'div')\n (\"<#{main_tag_name} class='vcard'>\" << result.join(' ') << \"</#{main_tag_name}>\").html_safe \n end", "def display\n\t\t@deck_of_cards.each.with_index do |card, i|\n\t\t\tputs \"#{i}=> #{card.display}\"\n\t\tend\n\tend", "def cards\n\t\[email protected] do |card|\n\t\t\tputs card.card\n\t\tend\n\tend", "def to_s\n result = \"\"\n count = 0\n for card in @cards\n result << \"#{card} \"\n count += 1\n if count > 12 \n count = 0\n result << \"\\n\"\n end\n end \n return result\n end", "def display_stream_object(obj, current_user_id)\n separator = \"\\n\"\n dbl_separator = \"\\n\\n\"\n meth = __method__\n if obj.is_a?(Tw::Tweet) then\n lastTweet = obj\n self.renderer.display([obj], @options.format(), separator: separator, current_user_id: current_user_id)\n elsif obj.is_a?(Tw::DMTweet) then\n self.renderer.display([obj], @options.format(), separator: separator, current_user_id: current_user_id)\n elsif obj.is_a?(Tw::Stream::Message) then\n self.renderer.display_stream_message(obj, @options.format, separator: separator)\n elsif obj.is_a?(Hash) && obj.size > 0 then\n if obj[:friends] then\n self.renderer.display_stream_message(obj, @options.format, separator: separator)\n else\n # Unknown data\n self.renderer.display_stream_message(obj, @options.format(), separator: separator)\n end\n else\n # do_nothing()\n end\n end", "def to_s\n result = \"\"\n self.each { |card | result << \"#{card} \" } \n return result\n end", "def to_s\n\t\tstr = \"\"\n\t\[email protected] do |card|\n\t\t\tstr += \"#{card} \"\n\t\tend\t\n\t\tstr.strip\t\n\tend", "def cards\n object.game_cards.map do |gc|\n { id: gc.card.id, word: gc.card.word, identity: gc.identity }\n end\n end", "def result_to_string(object)\n if object.is_a?(String) then\n return object\n else\n if defined?(awesome_inspect)\n return object.awesome_inspect({:plain=>true, :index=>false})\n elsif defined?(pretty_inspect)\n return object.pretty_inspect.chomp # Remove new line that PrettyInspect adds at the end https://www.ruby-forum.com/topic/113429\n else\n return object.inspect\n end\n end\n end", "def cards\n # all_cards = {}\n object.stock_cards.map do |stock|\n {id: stock.id, user_id: stock.user_id, company: stock.company, buy_price: stock.buy_price, sell_price: stock.sell_price}\n end\n end", "def printCard\n \"#{@color[0]}#{@fillType[0]}#{@shapeType[0]}#{@numberOfSymbols[0]}\"\n end", "def display_deck\n @deck_array.each do |x|\n x.display_card\n end\n end", "def pretty(object)\n PP.pp(object, out)\n end", "def format(object, opts = {})\n object.ai(opts.merge(html: true))\n end", "def to_s\n cards.map(&:to_s).join(' ')\n end", "def cards_print(cards)\n print_this = cards.each {|x, y| print x.to_s, ', '}\n end", "def print_objects\n @header_object.each_pair do |key,val|\n puts \"#{key}: #{val[0]} #{val[1]} #{val[2]}\"\n end\n end", "def outf(obj, ios=nil, &block)\n fmt = $cfg['tool.outformat']\n ios = $stdout if ios.nil?\n case fmt\n when /yaml/i\n ios.puts Hash.transform_keys_to_strings(obj).to_yaml\n when /pp/\n pp obj\n when /json/i\n ios.puts obj.to_json\n else # aka best.\n # sometime ‘best’ is only know by the caller, so block.\n if block_given? then\n yield obj, ios\n else\n if obj.kind_of?(Array) then\n obj.each {|i| ios.puts i.to_s}\n else\n ios.puts obj.to_s\n end\n end\n end\n end", "def display\n print(\"Card: #{@id} \")\n print(\"Number: #{@number} \")\n print(\"Color: #{@color} \")\n print(\"Shape: #{@shape} \")\n puts(\"Shade: #{@shade}\")\n end", "def display_search_results(objects)\n objects.limit(results_limit).reduce(String.new) do |string, object|\n string << (tag.tr display_search_results_row(object))\n end\n end", "def inspect_in_object(obj, opts)\n val = obj.send(name)\n str =\n begin\n val.inspect_with_options(opts)\n rescue NoMethodError\n val.inspect\n end\n (f=@format) ? (f % str) : str\n end", "def print_object(issues)\n if issues.nil?\n raise \"nil issue\"\n end\n if !issues.is_a? Array\n issues = [issues]\n end\n\n count = issues.length\n if issues.empty?\n return \"0 rows returned\"\n end\n\n table = Terminal::Table.new do |t|\n if @set_width\n width, height = HighLine::SystemExtensions.terminal_size\n t.style = {:width => width}\n end\n header = []\n sorted_fields = sort_fields(filter_fields(issues.first.keys))\n sorted_fields.each do |key|\n h = key.to_s.capitalize\n h = h.blue if @color\n header << h\n end\n\n t << header\n t << :separator\n\n issues.each do |hash|\n row = []\n sorted_fields.each do |key|\n row << format_field(hash, key)\n end\n t << row\n end\n end.to_s + \"#{count} rows returned\"\n end", "def printCardArray()\n\t\tprint @cards\n\tend", "def to_s\n @cards.map(&:to_s).join(' ')\n end" ]
[ "0.64820445", "0.6226193", "0.5886291", "0.5849091", "0.58358157", "0.5789512", "0.5777686", "0.5776829", "0.5770966", "0.5745876", "0.5724106", "0.57017106", "0.56891537", "0.56819046", "0.5678904", "0.56606877", "0.56455904", "0.5630276", "0.56124246", "0.56106174", "0.5596629", "0.55927134", "0.5546957", "0.5537878", "0.550494", "0.54980767", "0.5492414", "0.5489384", "0.54847026", "0.54820544" ]
0.77843404
0
Write +file+ within the browse folder of project +p+ using the passed block output as content
def write_file(p, file) File.open(browse_file(p, file), 'w') { |fh| fh.print yield } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write(block)\n @filemgr.write(block, @contents)\n end", "def output(file, &block)\n @outfile = File.expand_path(file)\n @block = block\n self\n end", "def write_to(file_name, &block)\n file = File.new(file_name, \"w\")\n file.write \"---\\n\"\n yield(file) if block_given?\n file.write \"---\"\n file.close\nend", "def write_content\n File.open(absolute_path,'w') do |file|\n file << content if content\n end\n # TODO git functionality\n end", "def write()\n template = ERB.new(File.read(File.join(@@support_location, \"template.erb\")))\n file_contents = template.result(self.binding())\n File.write(output_name, file_contents)\n end", "def to_pwdump_file(path, &block)\n exporter = Metasploit::Credential::Exporter::Pwdump.new(workspace: workspace)\n\n output_file = File.open(path, 'w') do |file|\n file << exporter.rendered_output\n end\n output_file.path\n end", "def open_output_file(&block)\r\n outfile = options[:outfile]\r\n if outfile\r\n File.open(outfile, 'w') { |f| block.call(f) }\r\n else\r\n block.call(STDOUT)\r\n end\r\n end", "def write_to_output filename, content = nil # :yields: file\n self.create_output_file(filename) do |output_path|\n File.open(output_path, 'w') do |f|\n if content\n f.write(content)\n else\n yield f\n end\n end\n end\n end", "def save_content(title, content)\n File.open(\"pages/#{title}.txt\", \"w\") do |file|\n file.print(content)\n end\nend", "def write_output_file(output_file, body)\n File.open(output_file, 'w:UTF-8') do |file|\n file.puts $HTML_header\n file.puts body\n file.puts $HTML_footer\n end\nend", "def create_output_file(content)\n\t\t\tf = File.new(@params[:output_file], 'w')\n\t\t\tf << content\n\t\t\tf.close\n\t\tend", "def write(path, options={}, &block)\n content = options[:content]\n if block\n content = []\n yield content\n content = content.join(\"\\n\")\n end\n exec! \"cat > '#{path}' <<EOF\\n#{content}\\nEOF\", options\n end", "def write\n path = \"#{site.root}/_site/#{output_file}\"\n File.open(path, 'w') do |f|\n f.write(@output)\n end\n end", "def browse_file(p, file)\n File.join(p.path, 'browse', file)\n end", "def write(out=nil)\n out ||= project.path(:output, path)\n FileUtils.mkdir_p File.dirname(out)\n\n if tilt?\n File.open(out, 'w') { |f| f.write to_html({}, :build => true) }\n else\n FileUtils.cp file, out\n end\n end", "def create_HTML_file(loc_name, content, out_dir)\n File.open(\"#{out_dir}/#{loc_name}.html\", 'w') do |f|\n f.write(HEADER_TEXT)\n f.write(\"<h1>Lonely Planet: #{loc_name}</h1>\")\n f.write(NAV_TITLE)\n f.write($navigation_html)\n f.write(BLOCK_TITLE)\n f.write(\"<h1><li class='first'><a href='#'>#{loc_name}</a></li></h1>\")\n f.write(MAIN_BLOCK)\n f.write(content)\n f.write(CLOSE_HTML)\n end\nend", "def log_and_stream(output)\n write_file output, @filename if @filename\n @block.call(output)\n end", "def write\n filename = \"#{@directory}/label.html\"\n File.open(filename, 'w') do |fp|\n fp.puts(self.to_s)\n end\n puts \"Wrote #{filename}\"\n end", "def save_content(title, content)\n\tFile.open(\"pages/#{title}.txt\" , \"w\") do |file|\n\t file.print(content)\n end \t\t\nend", "def write_file(path, content=path)\n path = File.join(temporary_directory, path)\n FileUtils.mkdir_p File.dirname(path)\n open(path, 'w'){|f| f.print content}\n end", "def generate (path)\n File.open(path, \"w\") do |f|\n @output.each do |line|\n f.puts line\n end\n end \n end", "def write\n make_parent_directory\n generate_file\n end", "def file_write(file, content)\n \n instructions = \"echo #{content.inspect} >> #{file}\"\n r = @ssh ? @ssh.exec!(instructions) : `#{instructions}`\n puts 'r: ' + r.inspect if @debug\n \n @results[:file_write] = r\n\n end", "def write\n File.open(@file, 'a') do |w| \n w.write(\"\\n\"+ @name + \" \" + @path)\n end\n end", "def write_file!\n file = File.new( path, \"w\")\n \n file.write(@source)\n file.close\n end", "def write(file)\n self.files.each { |l| file.puts l }\n end", "def write_page(path, format, data, commit = {})\n write(merge_path_elements(nil, path, format), data, commit)\n end", "def output\n super(@file_format => @file_path)\n end", "def sprint_write_file(type, content, file = nil)\n file = sprint_temp_file(type) if file.nil?\n log(\"#{self.class} writing file #{file}\", :info)\n File.open(file,'w'){ |f| f.write(content) }\n return type, file\n end", "def write(path)\n File.open(path, 'w') do |file|\n file.puts '# This Puppetfile is managed by Bolt. Do not edit.'\n modules.each { |mod| file.puts mod.to_spec }\n end\n rescue SystemCallError => e\n raise Bolt::FileError.new(\n \"#{e.message}: unable to write Puppetfile.\",\n path\n )\n end" ]
[ "0.66409993", "0.6551999", "0.6197935", "0.61722183", "0.61622196", "0.6113944", "0.6112693", "0.6066088", "0.60583067", "0.59728247", "0.5966772", "0.59273505", "0.59130883", "0.59073776", "0.58719283", "0.5867446", "0.58516586", "0.58434427", "0.5830314", "0.58273727", "0.58120763", "0.5805977", "0.5803251", "0.5793743", "0.5758577", "0.5758478", "0.5739494", "0.5728034", "0.5723559", "0.5719327" ]
0.7643977
0
Use a +template+ file to generate content with a hash of +data+ over the layout page if +layout+ is true
def build_from_template(template, data = {}, layout = true) cont = File.read(template_file(template)).miga_variables(data) return cont unless layout build_from_template( 'layout.html', data.merge(content: cont, project_name: cli.load_project.name), false ) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mustache(template, args={}, layout=true)\n args = args.update(:site => site, :site_tags => tags, :current_user => current_user)\n layout_class = UserApp::Views::Layout\n layout_class.template = design.layout\n view_class = UserApp::Views.const_get(template.to_s.classify)\n view_class.template = design.send(template)\n view_initialized = view_class.new(args)\n view_rendered = view_initialized.render\n if layout\n if view_initialized.respond_to?(:title)\n args.update(:page_title => view_initialized.title)\n end\n layout_class.new(args).render(:yield => view_rendered)\n else\n view_rendered\n end\n end", "def render_layout(output, layout, info); end", "def layout_template_file(program:)\n template_file(\n template_name: program.layout_template_name,\n extension: :LAYOUT_EXT\n )\n end", "def render_template(view, template, layout_name, locals); end", "def layout\n return @layout if @layout\n return if no_layout?\n\n @layout = site.layouts[data.layout].tap do |layout|\n unless layout\n Bridgetown.logger.warn \"Generated Page:\", \"Layout '#{data.layout}' \" \\\n \"requested via #{relative_path} does not exist.\"\n end\n end\n end", "def create_layout(content, attributes, identifier)\n # Get filenames\n base_path = 'layouts' + identifier[0..-2]\n meta_filename = base_path + '.yaml'\n content_filename = base_path + '.html'\n\n # Notify\n Nanoc3::NotificationCenter.post(:file_created, meta_filename)\n Nanoc3::NotificationCenter.post(:file_created, content_filename)\n\n # Create files\n FileUtils.mkdir_p(File.dirname(meta_filename))\n File.open(meta_filename, 'w') { |io| io.write(YAML.dump(attributes.stringify_keys)) }\n File.open(content_filename, 'w') { |io| io.write(content) }\n end", "def layout(name=:layout, &b)\n template(name, &b)\n end", "def render_layout(output, layout, info)\n payload[\"content\"] = output\n payload[\"layout\"] = Utils.deep_merge_hashes(layout.data, payload[\"layout\"] || {})\n\n render_liquid(\n layout.content,\n payload,\n info,\n layout.path\n )\n end", "def render\n template_body = Tilt.new(@template).render(self)\n if @layout\n layout = Dir[File.join(File.dirname(@template), @layout) + '*'].first\n raise \"#{Guinness::EMOJI} Guinness : Unable to locate layout at: '#{@layout}'\" unless layout\n @body = Tilt.new(layout).render(self) { template_body }\n end\n @body || template_body\n end", "def render\n layout = File.read \"#{site.root}/_layouts/#{@layout}.html\"\n @output = Liquid::Template.parse(layout).render('post'=>self) \n end", "def render(template_name, context=Context.new, layout=true)\n #context = Context.new(context) if context.is_a?(Hash)\n context = hook_context(context)\n while true\n template = get_template(template_name, context) # context is passed only for preprocessor\n _buf = context._buf\n output = template.render(context)\n context._buf = _buf\n unless context._layout.nil?\n layout = context._layout\n context._layout = nil\n end\n layout = @layout if layout == true or layout.nil?\n break unless layout\n template_name = layout\n layout = false\n context.instance_variable_set('@_content', output)\n end\n return output\n end", "def inject_into_layout\n application_layout_path_prefix = 'app/views/layouts/application.html'\n\n api_key = ask 'What is your kit ID (leave blank to specify later):'\n api_key = '- YOUR KIT ID HERE -' if api_key.blank?\n\n layout_templates = { slim: { content: \" = typekit '#{api_key}'\", after: \"head\\n\" }}\n layout_templates[:erb] = { content: \" <%#{layout_templates[:slim][:content].lstrip} %>\", after: \"<head>\\n\" }\n\n layout_templates.each_pair do |lang,options|\n path = ::File.join(destination_root, \"#{application_layout_path_prefix}.#{lang}\")\n if ::File.exists?(path)\n inject_into_file path, after: options[:after] do\n \"#{options[:content]}\\n\"\n end\n end\n end\n end", "def inside_layout(layout, &block)\n binding = block.binding if BINDING_REQUIRED\n\n layout = Dir.entries('app/views/layouts').detect { |a| /#{layout}/.match(a) }\n @template.instance_variable_set('@content_for_layout', capture(&block))\n concat(\n @template.render(:file => \"#{RAILS_ROOT}/app/views/layouts/#{layout}\", :user_full_path => true),\n binding\n )\n end", "def template_for(file); end", "def render(data = {}, &block)\n output = content(data, &block)\n output = layout.render(get_data(data)) { output } unless layout.nil?\n output\n end", "def generate_layout\n if options.sass?\n directory 'app'\n gem 'compass', '>=0.10.5'\n gem 'compass-960-plugin', '>=0.10.0'\n directory 'config'\n else\n copy_file \"stylesheet.css\", \"public/stylesheets/#{file_name}.css\" if options.stylesheet?\n copy_file \"handheld.css\", \"public/stylesheets/handheld.css\" if options.stylesheet?\n end\n copy_file \"modernizr-1.5.min.js\", \"public/javascripts/modernizr-1.5.min.js\"\n copy_file \"jquery-1.4.2.min.js\", \"public/javascripts/jquery-1.4.2.min.js\"\n copy_file \"dd_belatedpng.js\", \"public/javascripts/dd_belatedpng.js\"\n\n template \"layout.html.erb\", \"app/views/layouts/#{file_name}.html.erb\"\n copy_file 'layout_helper.rb', 'app/helpers/layout_helper.rb'\n end", "def layout_contents\n @layout = <<-LAYOUT\n blueprint-deploy:\n layout: #{spec_bp_name} # name of the layout file we use\n blueprint : #{spec_bp_name} # name of the default blueprint\n servers:\n - server1:\n name: util\n applications:\n - app1:\n - app2:\n - server2:\n name: review\n applications:\n - app1:\n - app3:\n LAYOUT\n @layout\n end", "def process_layout(config, widget_name)\n layout = nil\n layout_path = File.join(widget_name, 'layouts', \"#{config['layout']}.html\")\n [\n File.join(@ruhoh.paths.theme, \"widgets\", layout_path),\n File.join(@path, layout_path),\n File.join(@system_path, layout_path)\n ].each do |path|\n layout = path and break if File.exist?(path)\n end\n\n return '' unless layout\n content = File.open(layout, 'r:UTF-8') { |f| f.read }\n Mustache.render(content, {'config' => config})\n end", "def do_layout(payload, layouts)\n end", "def lookup_layout\n return \"{{{content}}}\" if metadata.key?('layout') && !metadata['layout']\n\n name = metadata['layout'] || 'page'\n name = name + '.mustache' unless name.end_with?('.mustache')\n\n path = ::File.join('_layouts', name)\n dir = ::File.join(wiki.path, ::File.dirname(file.path))\n\n layout_file = lookup_path(path, dir)\n\n if layout_file\n IO.read(layout_file)\n else\n default_layout\n end\n end", "def layout_render(content)\n\t\t\treturn content unless @layout\n\n\t\t\tlayout_files = find_layouts(@layout)\n\t\t\treturn content if layout_files.empty?\n\n\t\t\tlayout_files.each_with_object(content.dup) do |layout_file, result|\n\t\t\t\tlayout = compile_file(layout_file)\n\t\t\t\tresult.replace layout.render(@scope, @locals) { result }\n\t\t\tend\n\t\tend", "def dynamic_layout\n # ALL THIS SUCKS, I KNOW..\n \n # No layout for AJAX calls\n @layout = if request.xhr? \n nil\n # dialog param = lightview popup\n elsif params[:dialog]\n 'dialog'\n # uses user 'role' name for layout ... bad\n elsif current_user && !current_user.role.nil?\n current_user.role.downcase\n # no user, check for 'about' action\n elsif controller_name == 'about'\n 'about'\n # none of the above, use Rails default\n else\n 'home'\n end\n return nil unless @layout\n \n Rails.logger.debug \"Dyamic layout = #{@layout}\"\n # Layouts further divided by site subdomain: www vs vault\n if current_subdomain == 'vault'\n # Then public vs logged in...ugh\n if current_user\n @layout = 'vault/private/' + @layout\n else\n @layout = 'vault/public/' + @layout\n end\n end\n @layout\n end", "def render_with_layout(template, locals = {}, additional_js = [], additional_css = [])\n script_tags = \"\"\n css_tags = \"\"\n additional_js.each { |fileName| script_tags << \"<script src='/js/#{fileName}'></script>\" }\n additional_css.each do |fileName|\n css_tags << \"<link rel='stylesheet' type='text/css' href='/css/#{fileName}'/>\"\n end\n erb :base, :locals => locals.merge({ :template => template, :user => @user,\n :script_tags => script_tags, :css_tags => css_tags })\n end", "def generate\n layouts = params[:layout_info]\n FileOperation.delete_existing_file\n layouts.count.times do |layout|\n generate_layout(layouts[layout])\n $global_path = params[:layout_info][layout][:className]\n generate_layouts_in_files params[:css_info]\n end\n render json: { url: download_api_layout_index_path }\n end", "def parse(template, output, b = binding())\n # Generate the requested page\n template = File.read(template)\n erb = Erubis::Eruby.new(template)\n @content = erb.result(b)\n \n # Generate the layout\n layout = File.read(\"templates/layout.html.erb\")\n erb_layout = Erubis::Eruby.new(layout)\n \n FileUtils.mkdir_p(File.dirname(output))\n File.open(output, \"w+\") do |f|\n f.puts erb_layout.result(b)\n end\n end", "def create_default_template_file\n unless self.description.redirection_required?\n self.localizations.each do |page_localization|\n file_path = File.join(Rails.root, \"app\", \"views\" , \"pages\" , \"#{self.view}.#{page_localization.locale.slug}.html.haml\" )\n unless File.exists?(file_path)\n file = File.new(file_path, \"w\")\n\n page_localization.contents.each do |content|\n file.puts(\"= @page.easy_contents(:#{content.section_name})\")\n end\n file.close\n end\n end\n end\n end", "def generate_template(datestamp, entrytext, starred, uuid)\n ERB.new <<-XMLTEMPLATE\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n <plist version=\"1.0\">\n <dict>\n <key>Creation Date</key>\n <date><%= datestamp %></date>\n <key>Entry Text</key>\n <string><%= entrytext %></string>\n <key>Starred</key>\n <<%= starred %>/>\n <key>Tags</key>\n <array>\n <string>daily logs</string>\n </array>\n <key>UUID</key>\n <string><%= uuid %></string>\n </dict>\n </plist>\n XMLTEMPLATE\n end", "def initialize(content_template, data, layout)\n @content_template = erb_template(content_template)\n @layout = erb_template(layout)\n @data = data\n end", "def template\n File.read(File.expand_path('../../../../templates/activity.md.mustache', __FILE__))\n end", "def generate(page_setup = {})\n Zip::File.open(@template_path) do |template_zip|\n buffer = Zip::OutputStream.write_buffer do |out|\n template_zip.each do |entry|\n out.put_next_entry entry.name\n if @replaceable_files[entry.name] && entry.name == Document.doc_xml_file\n source = entry.get_input_stream.read\n # the source has only 1 sectPr and we change the doc dimensions based on the page setup\n source = replace_dimensions(source, page_setup)\n # Change only the body of document. TODO: Improve this...\n source = source.sub(/(<w:body>)((.|\\n)*?)(<w:sectPr)/, \"\\\\1#{@replaceable_files[entry.name]}\\\\4\")\n out.write(source)\n elsif @replaceable_files[entry.name] && entry.name == Document.header_xml_file\n source = entry.get_input_stream.read\n # Change only the body of document. TODO: Improve this...\n\n Rails.logger.info(\"header before:#{source}\")\n source = source.sub(/<w:tbl>.*<\\/w:tbl>/, \"#{@replaceable_files[entry.name]}\")\n Rails.logger.info(\"header after:#{source}\")\n\n out.write(source)\n # elsif @replaceable_files[entry.name] && entry.name == Document.footer_xml_file\n # source = entry.get_input_stream.read\n # Change only the body of document. TODO: Improve this...\n # Rails.logger.info(\"footer before:#{source}\")\n # source = source.sub(/<w:tbl>.*<\\/w:tbl>/, \"#{@replaceable_files[entry.name]}\")\n # Rails.logger.info(\"footer after:#{source}\")\n # out.write(source)\n\n elsif @replaceable_files[entry.name]\n out.write(@replaceable_files[entry.name])\n Rails.logger.info(\"footer: #{entry.get_input_stream.read}\") if entry.name == Document.footer_xml_file\n elsif entry.name == Document.content_types_xml_file\n raw_file = entry.get_input_stream.read\n content_types = @image_files.empty? ? raw_file : inject_image_content_types(raw_file)\n\n out.write(content_types)\n else\n out.write(template_zip.read(entry.name))\n end\n end\n unless @image_files.empty?\n #stream the image files into the media folder using open-uri\n @image_files.each do |hash|\n out.put_next_entry(\"word/media/#{hash[:filename]}\")\n URI.open(hash[:url], 'rb') do |f|\n out.write(f.read)\n end\n end\n end\n # add the header rels as its not already in the template docx\n out.put_next_entry(Document.header_relations_xml_file)\n out.write(@replaceable_files[Document.header_relations_xml_file])\n # add the footer rels as its not already in the template docx\n out.put_next_entry(Document.footer_relations_xml_file)\n out.write(@replaceable_files[Document.footer_relations_xml_file])\n\n # test creating for the blank header and footer to see if it fixes the error on open\n #\n # out.put_next_entry('word/_rels/header2.xml.rels')\n # out.write(@replaceable_files[Document.header_relations_xml_file])\n # add the footer rels as its not already in the template docx\n # out.put_next_entry('word/_rels/footer2.xml.rels')\n # out.write(@replaceable_files[Document.footer_relations_xml_file])\n\n end\n buffer.string\n end\n end" ]
[ "0.6997361", "0.67198944", "0.67088735", "0.6704546", "0.66211927", "0.6575901", "0.647485", "0.639517", "0.6370739", "0.6320471", "0.629727", "0.62776285", "0.62680995", "0.623344", "0.62254375", "0.62193334", "0.6199515", "0.6190676", "0.6162726", "0.61603975", "0.61348367", "0.6125117", "0.60581225", "0.60519505", "0.6034666", "0.6003229", "0.5978579", "0.59647626", "0.5953351", "0.59379715" ]
0.73471045
0
Path to the template browse file
def template_file(file) File.join( MiGA::MiGA.root_path, 'lib', 'miga', 'cli', 'action', 'browse', file ) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def template_path\n File.expand_path('../templates', __FILE__)\n end", "def template_path\n File.expand_path(File.join(File.dirname(__FILE__), \"template.rb\"))\n end", "def full_path\n \"templates/#{filename}\"\n end", "def template_path\n \"#{template_dir}/#{template_name}\"\n end", "def template_path\n File.join path, 'templates'\n end", "def pathTemplates\n \"./templates/\"\nend", "def template_path\n @options[:template_path]\n end", "def template_path(template)\n File.join(@root, 'templates', self.class::FILES[template])\n end", "def templates_path\n File.join(root, TEMPLATES)\n end", "def path(file)\n File.join File.dirname(__FILE__), '../../templates/', file\n end", "def template_path(extension)\n File.expand_path('../../../views/renderers/' + @dirname + '/' + @placeholder + '.' + extension, __FILE__)\n end", "def full_template_path\n template_root.join(\"#{@template}.erb\").to_s.squeeze(\"/\")\n end", "def template_path\n File.join(File.dirname(__FILE__), 'templates', 'type', \"#{@format}.erb\")\n end", "def template_path(filename)\n File.join(PatienceDiff::TEMPLATE_PATH, filename)\n end", "def templates_path\n @templates_path\n end", "def template_path\n File.expand_path(File.join('..', '..', '..', 'templates', \"#{template_name}.erb\"), __FILE__)\n end", "def template_path\n return File.join(File.dirname(__FILE__), \"../../../templates\", platform)\n end", "def template_path() 'demo/admin/billing.erb' end", "def file_path( target )\n File.join(template_theme.website.path, self.path, template_theme.file_name(target))\n end", "def template_path()\n 'demo/auth/signup.erb'\n end", "def template_path\n exact_path = File.join(root, request.path)\n with_erb = File.join(root, \"#{request.path}.html.erb\")\n with_index = File.join(root, File.dirname(request.path), 'index.html.erb')\n\n [ exact_path, with_erb, with_index ].find { |f| File.file?(f) }\n end", "def template_file\n File.join(Asciimeme.template_dir, \"#{meme_name}.erb\")\n end", "def template_path\n @default_options.fetch(:template_path, nil)\n end", "def file_path\n 'index.html'\n end", "def scaffold_path(template_name)\n File.join(scaffold_template_dir, template_name+'.rhtml')\n end", "def template_base_path\n @template_base_path ||= Inkblot.vendor_path('templates')\n end", "def templates_path\n File.join(File.dirname(__FILE__), '..', 'templates')\n end", "def template_path\n @template_path ||= @env[:templates_path] || default_settings[:templates_path]\n Pathname.new @template_path\n end", "def template_load_path\n @template_load_path ||= File.expand_path(File.dirname(self.filename))\n end", "def render_file_path(template)\n template.gsub(%r{.templates/.*?erb}, File.basename(template)).gsub('.erb', '')\n end" ]
[ "0.7515096", "0.7345798", "0.72823894", "0.7268778", "0.72396916", "0.7000569", "0.6968479", "0.6914573", "0.69109267", "0.6904416", "0.6890691", "0.68772614", "0.6826309", "0.6808136", "0.6794476", "0.67501146", "0.6747688", "0.6718692", "0.66853267", "0.6671208", "0.66488403", "0.6615804", "0.65964144", "0.6585768", "0.65806246", "0.65720546", "0.6565497", "0.6552496", "0.6548049", "0.65430415" ]
0.7424156
1
Path to the browse file in the project
def browse_file(p, file) File.join(p.path, 'browse', file) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def path\n project\n end", "def code_browse path\n dr = ruby_renderer\n view(path, :close_key => 'q', :title => $0) do |t|\n t.renderer dr\n t.bind_key([?\\\\,?\\\\,?o],'choose file') { \n str = choose_file \"**/*\"\n if str and str != \"\"\n t.add_content str\n t.buffer_last\n else\n alert \"nothing chosen\"\n end\n }\n end\n end", "def path\n @file\n end", "def browse_path\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"\" ] if browse_everything_controller2_debug_verbose\n rv = params[:path] || ''\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"browse_path rv=#{rv}\",\n \"\" ] if browse_everything_controller2_debug_verbose\n rv\n end", "def path\n end", "def path\n @file\n end", "def path\n File.join(self.drive.path, self.relative_path)\n end", "def path\n @path ||= @project.dir.path\n end", "def file_path\n 'index.html'\n end", "def path\n @file.path\n end", "def relativeWebPath()\n return File.join('/', @@tracksDir, \"#{self.fileName}#{self.fileType}\")\n end", "def file\n File.join(root, FILENAME)\n end", "def path\n file.url\n end", "def path\n File.join(self.folder, self.filename)\n end", "def fullpath\n File.expand_path( @file )\n end", "def current_file_path\n current_file.to_path\n end", "def template_file(file)\n File.join(\n MiGA::MiGA.root_path,\n 'lib', 'miga', 'cli', 'action', 'browse', file\n )\n end", "def path\n @path ||= File.join(folder,\".xHF#{name}\")\n end", "def path\n ::File.join(@folder, @file)\n end", "def get_project_path\n return File.absolute_path File.join(root_dir, src)\n end", "def path\n @file.path\n end", "def path\n File.join @proj_path_base, @proj_filename\n end", "def path\n File.join(@base, @name)\n end", "def path\n File.join Dubya.root_path, 'vendor/wiki'\n end", "def project_path\n \"#{Dir.home}/viewcumber/\"\nend", "def path()\n return ::File.join(@root, @name)\n end", "def relative_path; end", "def relative_path; end", "def relative_path; end", "def relative_path; end" ]
[ "0.66099113", "0.63447005", "0.6344689", "0.63362616", "0.63069445", "0.62917894", "0.6266471", "0.62566894", "0.62329155", "0.62251616", "0.62099624", "0.6183693", "0.6176807", "0.61586636", "0.6128603", "0.6115792", "0.6110082", "0.61082464", "0.6090519", "0.60740787", "0.60677415", "0.60659975", "0.6059082", "0.6051804", "0.60380876", "0.60300386", "0.6024", "0.6024", "0.6024", "0.6024" ]
0.7663598
0
determine the future value of an investment of present_value with given interest rate over time periods number of periods (years) that the interest is cumulated rate the annual rate of return present_value the value at the start of the period compound_frequency number of compounds / period(year)
def future_value(rate,periods,present_value,compound_frequency = 1) compound_frequency = resolve_compound_frequency!(compound_frequency) if compound_frequency == :continuous return continuous_compound_fv(rate,periods,present_value) end future_value = present_value * (1+rate/compound_frequency)** (periods * compound_frequency) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def present_value(rate,periods,future_value)\n present_value = future_value / (1+rate)**periods\n end", "def compound_return(periods,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n n = periods.to_d\n rate = ((fv / pv)**(1/n))-1\n end", "def future_given_present(present_value, interest, term)\n (present_value.to_f * (1 + interest.to_f) ** term).round(4)\n end", "def present_given_future(future_value, interest, term)\n (future_value.to_f / (1 +interest.to_f) ** term).round(4)\n end", "def anticipated_fixed_payment(present_value, rate, term)\n\t\t((present_value.to_f) / ((1 - (1 - rate.to_f ) ** term ) / rate.to_f )).round(4)\n end", "def annuity_given_future(future_value, interest, term)\n (future_value.to_f * (interest.to_f / ((1 + interest) ** term)-1)).round(4)\n end", "def anticipated_interest(rate, periods)\n\t\t (1 - (( 1 / ( rate.to_f + 1 )) ** (1.0 / periods)))\n\t\tend", "def nominal_due_given_efective(effective_rate, periods)\n\t\t\t((((1 + (effective_rate.to_f/100))**(1/periods.to_f)-1)*periods.to_f)*100).round(4)\n end", "def annuity_given_present(present_value, interest, term)\n interest = interest.to_f\n (present_value.to_f * ((interest * (1+interest) ** term) / (((1 + interest) ** term) -1))).round(4)\n end", "def investment_horizon(rate,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n periods = Math.log(fv/pv) / Math.log(1+rate)\n end", "def calculate_loan(rate, n_periods, total_loan_amount)\n fixed_payment = (rate /\n (1 - ((1 + rate)**(n_periods * - 1)))) * total_loan_amount\n\n fixed_payment.to_f\nend", "def future_given_annuity(annuity, interest, term)\n (annuity * (((1 + interest.to_f) ** term) -1) / interest.to_f ).round(4)\n end", "def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend", "def effective_annual_rate(rate,compound_frequency)\n compound_frequency = resolve_compound_frequency!(compound_frequency)\n if compound_frequency == :continuous\n return continuous_effective_annual_rate(rate)\n end\n m= compound_frequency\n e_rate = (1 + rate/m)**m -1\n end", "def expression_value\n return @expression_value if defined?(@expression_value)\n\n subexpr_value =\n (1 + periodic_interest_rate) ** total_number_of_payments\n @expression_value =\n (periodic_interest_rate * subexpr_value) / (subexpr_value - 1)\n end", "def calculate_payment\n x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods)\n y = ((1 + @periodic_rate)**@periods) - 1\n (x / y).round(2)\n end", "def net_present_value\n lambda do |x|\n relative_payments.reduce(0) do |sum, relative_payment|\n sum + relative_payment.amount * (1 + x)**-relative_payment.offset\n end\n end\n end", "def compound_interest(rate, count = 1, period = 12)\n Money.new(cents * ((1 + rate / 100.0 / period) ** count - 1))\n end", "def installment_value(interest_rate, financing_time_months, loan_value)\n @installment_calculator.calculate(interest_rate, financing_time_months, loan_value)\n end", "def nominal_anticipated_given_efective(effective_rate, periods)\n nominalRate = (1+(effective_rate.to_f/100))**(1/periods.to_f)-1\n toAnticipated = nominalRate / (1+nominalRate)\n (toAnticipated * periods.to_f * 100).round(4)\n end", "def calculate_interest principle, days_since\n (principle * APR / 365 * days_since).round(2)\n end", "def calculate_years(principal, interest, tax, desired)\n i = 0\n return i if principal == desired\n \n while principal < desired\n principal += (principal * interest) - (principal * interest * tax)\n i += 1\n end\n \n i\nend", "def calculate(loan_value, financing_time_months, interest_rate, loan_date = Date.today)\n balance = loan_value\n installment = installment_value(interest_rate, financing_time_months, loan_value)\n installment_date = loan_date.next_month\n iof = 0\n\n financing_time_months.step(1, -1) do |_|\n amortization = installment - interest_part(balance, interest_rate)\n\n days = past_days(loan_date, installment_date)\n\n iof += amortization*(@iof_day*(minimal_days(days)))\n iof += amortization*@iof_additional\n\n balance -= amortization\n installment_date = installment_date.next_month\n end\n\n loan_iof(iof, loan_value)\n end", "def rates_prediction\r\n final_array = []\r\n today = today_rate\r\n weekly_change = weekly_percentage_change_array\r\n\r\n first = ((weekly_change[0] / 100) * today) + today\r\n final_array << first\r\n\r\n if @time > 1\r\n i = 0\r\n while i < weekly_change[1].length\r\n rate = ((weekly_change[1][i] / 100) * final_array[i]) + final_array[i]\r\n final_array << rate\r\n i += 1\r\n end\r\n end\r\n final_array\r\n end", "def annual_ror(initial_value, final_value, years)\n if years <= 0\n 0\n elsif initial_value == 0\n # BigDecimal::INFINITY\n Float::INFINITY\n else\n 100.to_d * if final_value < 0 # fudge if final value is less than zero\n (((initial_value.to_d - final_value.to_d) / initial_value.to_d) ** (1 / years.to_d)) * -1\n else\n ((final_value.to_d / initial_value.to_d) ** (1 / years.to_d)) - 1\n end\n end\n end", "def net_present_value_derivative\n lambda do |x|\n relative_payments.reduce(0) do |sum, relative_payment|\n sum + relative_payment.amount * -relative_payment.offset * (1 + x)**(-relative_payment.offset - 1)\n end\n end\n end", "def calculate_years(principal, interest, tax, desired)\n total = principal\n years = 0\n loop do\n break if total >= desired\n total_interest = total*interest\n total += total_interest\n total -= total_interest*tax\n years += 1\n end\n years\nend", "def calculate_interest(principal, roi, time)\n rate = roi.to_f / 100\n amount = principal.to_f * (1 + rate * time.to_f)\n\n amount\nend", "def grow_one_year(starting_balance, growth_rate)\n starting_balance * (1.0 + growth_rate)\nend", "def calculate_interest(current_period, previous_period=0)\n previous_balance = @txns[previous_period][:balance]\n period_of_interest = current_period - previous_period\n @interest += (previous_balance * daily_interest * period_of_interest).round(2)\n end" ]
[ "0.7779788", "0.75517434", "0.7306679", "0.6672953", "0.65825135", "0.63988066", "0.6284648", "0.6245956", "0.6159949", "0.61575097", "0.60779995", "0.60768104", "0.6067823", "0.6065797", "0.60527045", "0.59514064", "0.5936478", "0.5902118", "0.5874436", "0.58550656", "0.5800216", "0.57959485", "0.5781822", "0.56942713", "0.56749696", "0.56540984", "0.56426233", "0.563002", "0.562688", "0.5606239" ]
0.80783045
0
determine the present value required to acheive a future value with given interest rate over time periods number of periods (years) that the interest is cumulated rate the annual rate of return future_value the value at the end of the period
def present_value(rate,periods,future_value) present_value = future_value / (1+rate)**periods end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def future_given_present(present_value, interest, term)\n (present_value.to_f * (1 + interest.to_f) ** term).round(4)\n end", "def compound_return(periods,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n n = periods.to_d\n rate = ((fv / pv)**(1/n))-1\n end", "def future_value(rate,periods,present_value,compound_frequency = 1)\n compound_frequency = resolve_compound_frequency!(compound_frequency)\n if compound_frequency == :continuous\n return continuous_compound_fv(rate,periods,present_value)\n end\n future_value = present_value * (1+rate/compound_frequency)** (periods * compound_frequency)\n end", "def present_given_future(future_value, interest, term)\n (future_value.to_f / (1 +interest.to_f) ** term).round(4)\n end", "def annuity_given_future(future_value, interest, term)\n (future_value.to_f * (interest.to_f / ((1 + interest) ** term)-1)).round(4)\n end", "def future_given_annuity(annuity, interest, term)\n (annuity * (((1 + interest.to_f) ** term) -1) / interest.to_f ).round(4)\n end", "def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend", "def anticipated_interest(rate, periods)\n\t\t (1 - (( 1 / ( rate.to_f + 1 )) ** (1.0 / periods)))\n\t\tend", "def investment_horizon(rate,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n periods = Math.log(fv/pv) / Math.log(1+rate)\n end", "def anticipated_fixed_payment(present_value, rate, term)\n\t\t((present_value.to_f) / ((1 - (1 - rate.to_f ) ** term ) / rate.to_f )).round(4)\n end", "def calculate_years(principal, interest, tax, desired)\n i = 0\n return i if principal == desired\n \n while principal < desired\n principal += (principal * interest) - (principal * interest * tax)\n i += 1\n end\n \n i\nend", "def annual_ror(initial_value, final_value, years)\n if years <= 0\n 0\n elsif initial_value == 0\n # BigDecimal::INFINITY\n Float::INFINITY\n else\n 100.to_d * if final_value < 0 # fudge if final value is less than zero\n (((initial_value.to_d - final_value.to_d) / initial_value.to_d) ** (1 / years.to_d)) * -1\n else\n ((final_value.to_d / initial_value.to_d) ** (1 / years.to_d)) - 1\n end\n end\n end", "def annuity_given_present(present_value, interest, term)\n interest = interest.to_f\n (present_value.to_f * ((interest * (1+interest) ** term) / (((1 + interest) ** term) -1))).round(4)\n end", "def calculate_years(principal, interest, tax, desired)\n total = principal\n years = 0\n loop do\n break if total >= desired\n total_interest = total*interest\n total += total_interest\n total -= total_interest*tax\n years += 1\n end\n years\nend", "def expression_value\n return @expression_value if defined?(@expression_value)\n\n subexpr_value =\n (1 + periodic_interest_rate) ** total_number_of_payments\n @expression_value =\n (periodic_interest_rate * subexpr_value) / (subexpr_value - 1)\n end", "def net_present_value\n lambda do |x|\n relative_payments.reduce(0) do |sum, relative_payment|\n sum + relative_payment.amount * (1 + x)**-relative_payment.offset\n end\n end\n end", "def nominal_due_given_efective(effective_rate, periods)\n\t\t\t((((1 + (effective_rate.to_f/100))**(1/periods.to_f)-1)*periods.to_f)*100).round(4)\n end", "def calculate_interest principle, days_since\n (principle * APR / 365 * days_since).round(2)\n end", "def required_annual_savings\n needed_amount_less_savings / years_to_retirement\n end", "def grow_one_year(starting_balance, growth_rate)\n starting_balance * (1.0 + growth_rate)\nend", "def call(year)\n previous_year = Population.previous_known(year)\n\n return previous_year.population if previous_year.year == year # year entered is known\n\n next_year = Population.next_known(year)\n\n # there is no next year - unable to calculate\n return nil if next_year.nil? \n\n # calculate the percentage that year is between next and previous years\n mod_percentage = (year - previous_year.year).to_f / (next_year.year - previous_year.year).to_f\n delta_population = next_year.population - previous_year.population\n\n (delta_population * mod_percentage).to_i + previous_year.population\n end", "def installment_value(interest_rate, financing_time_months, loan_value)\n @installment_calculator.calculate(interest_rate, financing_time_months, loan_value)\n end", "def rates_prediction\r\n final_array = []\r\n today = today_rate\r\n weekly_change = weekly_percentage_change_array\r\n\r\n first = ((weekly_change[0] / 100) * today) + today\r\n final_array << first\r\n\r\n if @time > 1\r\n i = 0\r\n while i < weekly_change[1].length\r\n rate = ((weekly_change[1][i] / 100) * final_array[i]) + final_array[i]\r\n final_array << rate\r\n i += 1\r\n end\r\n end\r\n final_array\r\n end", "def calculate_loan(rate, n_periods, total_loan_amount)\n fixed_payment = (rate /\n (1 - ((1 + rate)**(n_periods * - 1)))) * total_loan_amount\n\n fixed_payment.to_f\nend", "def calculate_interest(principal, roi, time)\n rate = roi.to_f / 100\n amount = principal.to_f * (1 + rate * time.to_f)\n\n amount\nend", "def calculate_interest(current_period, previous_period=0)\n previous_balance = @txns[previous_period][:balance]\n period_of_interest = current_period - previous_period\n @interest += (previous_balance * daily_interest * period_of_interest).round(2)\n end", "def total_amount_owed(principal, interest_rate_percentage, number_of_years)\n annual_percentage_rate = interest_rate_percentage / 100\n principal * (1 + annual_percentage_rate * number_of_years)\nend", "def daily_interest\n @apr / 100.0 / 365\n end", "def calculate(loan_value, financing_time_months, interest_rate, loan_date = Date.today)\n balance = loan_value\n installment = installment_value(interest_rate, financing_time_months, loan_value)\n installment_date = loan_date.next_month\n iof = 0\n\n financing_time_months.step(1, -1) do |_|\n amortization = installment - interest_part(balance, interest_rate)\n\n days = past_days(loan_date, installment_date)\n\n iof += amortization*(@iof_day*(minimal_days(days)))\n iof += amortization*@iof_additional\n\n balance -= amortization\n installment_date = installment_date.next_month\n end\n\n loan_iof(iof, loan_value)\n end", "def nominal_anticipated_given_efective(effective_rate, periods)\n nominalRate = (1+(effective_rate.to_f/100))**(1/periods.to_f)-1\n toAnticipated = nominalRate / (1+nominalRate)\n (toAnticipated * periods.to_f * 100).round(4)\n end" ]
[ "0.74859816", "0.7460934", "0.73605585", "0.70097977", "0.69373226", "0.67010456", "0.65248215", "0.65005285", "0.64793396", "0.6350233", "0.62822175", "0.62789625", "0.62492776", "0.6179234", "0.61650795", "0.6115266", "0.6107985", "0.6103223", "0.60859317", "0.60255533", "0.6011521", "0.59799707", "0.59727925", "0.59215283", "0.59044385", "0.5855717", "0.58168334", "0.5790984", "0.5721664", "0.57119286" ]
0.7800808
0
determine the rate of return over a period periods number of periods (years) that the interest is cumulated present_value the value at the start of the period future_value the value at the end of the period
def compound_return(periods,present_value,future_value) pv = present_value.to_d fv = future_value.to_d n = periods.to_d rate = ((fv / pv)**(1/n))-1 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def present_value(rate,periods,future_value)\n present_value = future_value / (1+rate)**periods\n end", "def future_value(rate,periods,present_value,compound_frequency = 1)\n compound_frequency = resolve_compound_frequency!(compound_frequency)\n if compound_frequency == :continuous\n return continuous_compound_fv(rate,periods,present_value)\n end\n future_value = present_value * (1+rate/compound_frequency)** (periods * compound_frequency)\n end", "def investment_horizon(rate,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n periods = Math.log(fv/pv) / Math.log(1+rate)\n end", "def future_given_present(present_value, interest, term)\n (present_value.to_f * (1 + interest.to_f) ** term).round(4)\n end", "def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend", "def anticipated_interest(rate, periods)\n\t\t (1 - (( 1 / ( rate.to_f + 1 )) ** (1.0 / periods)))\n\t\tend", "def nominal_due_given_efective(effective_rate, periods)\n\t\t\t((((1 + (effective_rate.to_f/100))**(1/periods.to_f)-1)*periods.to_f)*100).round(4)\n end", "def calculate_years(principal, interest, tax, desired)\n i = 0\n return i if principal == desired\n \n while principal < desired\n principal += (principal * interest) - (principal * interest * tax)\n i += 1\n end\n \n i\nend", "def anticipated_fixed_payment(present_value, rate, term)\n\t\t((present_value.to_f) / ((1 - (1 - rate.to_f ) ** term ) / rate.to_f )).round(4)\n end", "def annual_ror(initial_value, final_value, years)\n if years <= 0\n 0\n elsif initial_value == 0\n # BigDecimal::INFINITY\n Float::INFINITY\n else\n 100.to_d * if final_value < 0 # fudge if final value is less than zero\n (((initial_value.to_d - final_value.to_d) / initial_value.to_d) ** (1 / years.to_d)) * -1\n else\n ((final_value.to_d / initial_value.to_d) ** (1 / years.to_d)) - 1\n end\n end\n end", "def calculate_interest principle, days_since\n (principle * APR / 365 * days_since).round(2)\n end", "def calculate_payment\n x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods)\n y = ((1 + @periodic_rate)**@periods) - 1\n (x / y).round(2)\n end", "def present_given_future(future_value, interest, term)\n (future_value.to_f / (1 +interest.to_f) ** term).round(4)\n end", "def calculate_years(principal, interest, tax, desired)\n total = principal\n years = 0\n loop do\n break if total >= desired\n total_interest = total*interest\n total += total_interest\n total -= total_interest*tax\n years += 1\n end\n years\nend", "def required_annual_savings\n needed_amount_less_savings / years_to_retirement\n end", "def total_amount_owed(principal, interest_rate_percentage, number_of_years)\n annual_percentage_rate = interest_rate_percentage / 100\n principal * (1 + annual_percentage_rate * number_of_years)\nend", "def calculate_loan(rate, n_periods, total_loan_amount)\n fixed_payment = (rate /\n (1 - ((1 + rate)**(n_periods * - 1)))) * total_loan_amount\n\n fixed_payment.to_f\nend", "def daily_interest\n @apr / 100.0 / 365\n end", "def net_present_value\n lambda do |x|\n relative_payments.reduce(0) do |sum, relative_payment|\n sum + relative_payment.amount * (1 + x)**-relative_payment.offset\n end\n end\n end", "def nominal_anticipated_given_efective(effective_rate, periods)\n nominalRate = (1+(effective_rate.to_f/100))**(1/periods.to_f)-1\n toAnticipated = nominalRate / (1+nominalRate)\n (toAnticipated * periods.to_f * 100).round(4)\n end", "def rates_prediction\r\n final_array = []\r\n today = today_rate\r\n weekly_change = weekly_percentage_change_array\r\n\r\n first = ((weekly_change[0] / 100) * today) + today\r\n final_array << first\r\n\r\n if @time > 1\r\n i = 0\r\n while i < weekly_change[1].length\r\n rate = ((weekly_change[1][i] / 100) * final_array[i]) + final_array[i]\r\n final_array << rate\r\n i += 1\r\n end\r\n end\r\n final_array\r\n end", "def nb_year(p0, percent, aug, p)\n years = 0\n while p >= p0 do\n p0 += (percent/100.0 * p0) + aug\n years += 1\n end\n p years\nend", "def years_until_retirement\n @retirement_age.to_i - @current_age.to_i\n end", "def annuity_given_future(future_value, interest, term)\n (future_value.to_f * (interest.to_f / ((1 + interest) ** term)-1)).round(4)\n end", "def nb_year(p0, percent, aug, p)\n year_count = 0\n until p0 >= p do\n p0 += (p0 * (percent/100.to_f)) + aug\n year_count += 1\n # binding.pry\n end\n year_count\n # binding.pry\nend", "def mortgage_calc principle, annual_interest, years\n n = years * 12\n r = (annual_interest / 100)/ 12 #since this is usually expressed as a percentage\n return (principle * r * (1 + r)**n / ((1 + r)**n - 1)).round(2)\nend", "def grow_one_year(starting_balance, growth_rate)\n starting_balance * (1.0 + growth_rate)\nend", "def call(year)\n previous_year = Population.previous_known(year)\n\n return previous_year.population if previous_year.year == year # year entered is known\n\n next_year = Population.next_known(year)\n\n # there is no next year - unable to calculate\n return nil if next_year.nil? \n\n # calculate the percentage that year is between next and previous years\n mod_percentage = (year - previous_year.year).to_f / (next_year.year - previous_year.year).to_f\n delta_population = next_year.population - previous_year.population\n\n (delta_population * mod_percentage).to_i + previous_year.population\n end", "def withdrawal_rate\n (youngest_person_retirement_age - 15.0) / 1000.0\n end", "def compound_interest(rate, count = 1, period = 12)\n Money.new(cents * ((1 + rate / 100.0 / period) ** count - 1))\n end" ]
[ "0.78171325", "0.69233257", "0.68300253", "0.6731517", "0.6698266", "0.6611931", "0.6558443", "0.64138514", "0.6395259", "0.635134", "0.6257746", "0.62558013", "0.62553144", "0.623989", "0.62014925", "0.6158807", "0.6115589", "0.6073032", "0.6028322", "0.6027582", "0.5992313", "0.5905765", "0.5905208", "0.59027576", "0.5892498", "0.5870332", "0.5868521", "0.58194965", "0.5801096", "0.57637244" ]
0.79168487
0
determine the investment horizon (length of time) required to create a future value given a present value and interest rate present_value the value at the start of the period future_value the value at the end of the period rate the annual rate of return
def investment_horizon(rate,present_value,future_value) pv = present_value.to_d fv = future_value.to_d periods = Math.log(fv/pv) / Math.log(1+rate) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def present_value(rate,periods,future_value)\n present_value = future_value / (1+rate)**periods\n end", "def future_given_present(present_value, interest, term)\n (present_value.to_f * (1 + interest.to_f) ** term).round(4)\n end", "def present_given_future(future_value, interest, term)\n (future_value.to_f / (1 +interest.to_f) ** term).round(4)\n end", "def compound_return(periods,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n n = periods.to_d\n rate = ((fv / pv)**(1/n))-1\n end", "def future_value(rate,periods,present_value,compound_frequency = 1)\n compound_frequency = resolve_compound_frequency!(compound_frequency)\n if compound_frequency == :continuous\n return continuous_compound_fv(rate,periods,present_value)\n end\n future_value = present_value * (1+rate/compound_frequency)** (periods * compound_frequency)\n end", "def annuity_given_future(future_value, interest, term)\n (future_value.to_f * (interest.to_f / ((1 + interest) ** term)-1)).round(4)\n end", "def anticipated_fixed_payment(present_value, rate, term)\n\t\t((present_value.to_f) / ((1 - (1 - rate.to_f ) ** term ) / rate.to_f )).round(4)\n end", "def annuity_given_present(present_value, interest, term)\n interest = interest.to_f\n (present_value.to_f * ((interest * (1+interest) ** term) / (((1 + interest) ** term) -1))).round(4)\n end", "def earned_schedule\n ev = project.earned_value(self) #Current Earned Value\n pv_line = planned_value_by_week #Planned value by week to see in what week EV is the same as PV.\n\n week = pv_line.first[0] #PVt week\n next_week = pv_line.first[0] #PVt+1 week\n\n previous_value = 0 #Temp PVt value for loop\n previous_key = pv_line.first[0] #Temp PVt week for loop \n\n pv_line.each do |key, value|\n # puts \"#{previous_value} >= #{ev} < #{value}\"\n if( ev >= previous_value.round && ev < value.round) #Each key is a week, in what week does the EV equal to PV?\n # puts \"#{previous_value} >= #{ev} < #{value}\"\n # puts \"Yes!\"\n week = previous_key\n next_week = key\n elsif( ev == previous_value.round && ev == value.round) #THIS elseif is here when both are equal until the end of the project, e.g. when the project is finished.\n # puts \"Yes! Equal\"\n week = key\n next_week = key\n end\n previous_key = key\n previous_value = value.round\n end\n\n pv_t = pv_line[week] #PVt value\n pv_t_next = pv_line[next_week] #PVt+1 value\n\n num_of_weeks = pv_line.keys[0..pv_line.keys.index(week)].size - 1 #Get num of weeks until \"week\", t is number of weeks.\n \n if (pv_line[next_week] - pv_line[week]) == 0 #Prevent from divide by zero, when values are equal.\n num_of_weeks #This means that the line is flat. So use the previous value because (EV >= PVt and EV < PVt+1).\n else\n num_of_weeks + ((ev - pv_line[week]).to_f / (pv_line[next_week] - pv_line[week]))\n end\n end", "def anticipated_interest(rate, periods)\n\t\t (1 - (( 1 / ( rate.to_f + 1 )) ** (1.0 / periods)))\n\t\tend", "def net_present_value\n lambda do |x|\n relative_payments.reduce(0) do |sum, relative_payment|\n sum + relative_payment.amount * (1 + x)**-relative_payment.offset\n end\n end\n end", "def calculate(loan_value, financing_time_months, interest_rate, loan_date = Date.today)\n balance = loan_value\n installment = installment_value(interest_rate, financing_time_months, loan_value)\n installment_date = loan_date.next_month\n iof = 0\n\n financing_time_months.step(1, -1) do |_|\n amortization = installment - interest_part(balance, interest_rate)\n\n days = past_days(loan_date, installment_date)\n\n iof += amortization*(@iof_day*(minimal_days(days)))\n iof += amortization*@iof_additional\n\n balance -= amortization\n installment_date = installment_date.next_month\n end\n\n loan_iof(iof, loan_value)\n end", "def nominal_due_given_efective(effective_rate, periods)\n\t\t\t((((1 + (effective_rate.to_f/100))**(1/periods.to_f)-1)*periods.to_f)*100).round(4)\n end", "def expression_value\n return @expression_value if defined?(@expression_value)\n\n subexpr_value =\n (1 + periodic_interest_rate) ** total_number_of_payments\n @expression_value =\n (periodic_interest_rate * subexpr_value) / (subexpr_value - 1)\n end", "def future_given_annuity(annuity, interest, term)\n (annuity * (((1 + interest.to_f) ** term) -1) / interest.to_f ).round(4)\n end", "def present_value\n # Payoff amount = 0, we’re assuming a fully amortizing loan\n payoff_amount = 0\n end", "def installment_value(interest_rate, financing_time_months, loan_value)\n @installment_calculator.calculate(interest_rate, financing_time_months, loan_value)\n end", "def set_estimate_from_effort\n estimated_effort = self.story_points #custom_value.value\n unless estimated_effort.blank?\n self.estimated_hours = case estimated_effort.to_i\n when 1 then 4\n when 2 then 8\n when 3 then 12\n when 5 then 20\n when 8 then 32\n end\n end\n end", "def calculate_interest principle, days_since\n (principle * APR / 365 * days_since).round(2)\n end", "def current_age_approximate\n nil\n end", "def forecast_finish_date(basis_hours)\n if complete_ev(basis_hours) == 100.0\n @ev.keys.max\n elsif today_spi(basis_hours) == 0.0\n @pv.keys.max\n else\n if @issue_max_date < @basis_date\n rest_days = (@pv[@pv.keys.max] - @ev[@ev.keys.max]) / today_spi(basis_hours) / basis_hours\n @basis_date + rest_days\n else\n rest_days = @pv.count { |key, _value| key > @basis_date }\n @pv.keys.max - (rest_days - (rest_days / today_spi(basis_hours)))\n end\n end\n end", "def nominal_anticipated_given_efective(effective_rate, periods)\n nominalRate = (1+(effective_rate.to_f/100))**(1/periods.to_f)-1\n toAnticipated = nominalRate / (1+nominalRate)\n (toAnticipated * periods.to_f * 100).round(4)\n end", "def calculate_interest(principal, roi, time)\n rate = roi.to_f / 100\n amount = principal.to_f * (1 + rate * time.to_f)\n\n amount\nend", "def estimate_embargo_period( issued, embargo_release )\n period = Date.parse( embargo_release ) - Date.parse( issued )\n case period.to_i\n when 0\n return ''\n when 1..186\n return GenericWork::EMBARGO_VALUE_6_MONTH\n when 187..366\n return GenericWork::EMBARGO_VALUE_1_YEAR\n when 367..731\n return GenericWork::EMBARGO_VALUE_2_YEAR\n when 732..1825\n return GenericWork::EMBARGO_VALUE_5_YEAR\n else\n return GenericWork::EMBARGO_VALUE_FOREVER\n end\n end", "def pv\n factor = (1.0 + monthly_rate)**duration\n second_factor = (factor - 1) * (1 + monthly_rate * ptype) / monthly_rate\n\n -(future_value + (payment.to_f * second_factor)) / factor\n end", "def registro_inicio(vaca,num_horas)\n estim_reg = Time.now.advance(:hours => -num_horas.to_i).localtime\n estimate_time = estim_reg.change(:min => 0)\n return estimate_time \n end", "def needed_exp\n return next_exp - now_exp\n end", "def calculate_years(principal, interest, tax, desired)\n i = 0\n return i if principal == desired\n \n while principal < desired\n principal += (principal * interest) - (principal * interest * tax)\n i += 1\n end\n \n i\nend", "def calculate_interest(current_period, previous_period=0)\n previous_balance = @txns[previous_period][:balance]\n period_of_interest = current_period - previous_period\n @interest += (previous_balance * daily_interest * period_of_interest).round(2)\n end", "def required_annual_savings\n needed_amount_less_savings / years_to_retirement\n end" ]
[ "0.73584276", "0.7230214", "0.6933694", "0.66302454", "0.6504473", "0.61318266", "0.5859032", "0.5783148", "0.5606104", "0.55674577", "0.556436", "0.5499632", "0.54799885", "0.54791063", "0.5467902", "0.54229295", "0.5418428", "0.5403856", "0.5395165", "0.5387388", "0.528683", "0.52741015", "0.52691734", "0.5198442", "0.51516557", "0.5121989", "0.5091097", "0.5064475", "0.5061778", "0.5040751" ]
0.78798425
0
determine the effective annual rate for a given simple interest rate compounded over a given number of periods rate simple annual rate compound_per_period compound / period
def effective_annual_rate(rate,compound_frequency) compound_frequency = resolve_compound_frequency!(compound_frequency) if compound_frequency == :continuous return continuous_effective_annual_rate(rate) end m= compound_frequency e_rate = (1 + rate/m)**m -1 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def anticipated_interest(rate, periods)\n\t\t (1 - (( 1 / ( rate.to_f + 1 )) ** (1.0 / periods)))\n\t\tend", "def compound_interest(rate, count = 1, period = 12)\n Money.new(cents * ((1 + rate / 100.0 / period) ** count - 1))\n end", "def calculate_loan(rate, n_periods, total_loan_amount)\n fixed_payment = (rate /\n (1 - ((1 + rate)**(n_periods * - 1)))) * total_loan_amount\n\n fixed_payment.to_f\nend", "def nominal_anticipated_given_efective(effective_rate, periods)\n nominalRate = (1+(effective_rate.to_f/100))**(1/periods.to_f)-1\n toAnticipated = nominalRate / (1+nominalRate)\n (toAnticipated * periods.to_f * 100).round(4)\n end", "def simple_interest(rate, count = 1, period = 12)\n Money.new(rate / 100 / period * cents * count)\n end", "def total_amount_owed(principal, interest_rate_percentage, number_of_years)\n annual_percentage_rate = interest_rate_percentage / 100\n principal * (1 + annual_percentage_rate * number_of_years)\nend", "def compound_return(periods,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n n = periods.to_d\n rate = ((fv / pv)**(1/n))-1\n end", "def nominal_due_given_efective(effective_rate, periods)\n\t\t\t((((1 + (effective_rate.to_f/100))**(1/periods.to_f)-1)*periods.to_f)*100).round(4)\n end", "def pmt(interest_rate,payments,principal)\n numerator =interest_rate*principal*(1 + interest_rate)**payments\n denominator= (1+ interest_rate)**payments - 1\n return numerator/denominator.to_f\nend", "def apply_rate(amount, interchange_base = 0.0, interchange_percent = 0.0)\n FeeService.apply_raw_rate(amount, @base + interchange_base, @percent + interchange_percent)\n end", "def calculate_payment\n x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods)\n y = ((1 + @periodic_rate)**@periods) - 1\n (x / y).round(2)\n end", "def yearly_rate(*args)\n if paid?\n if yearly?\n rate(*args) / duration_parts[0] #number of years\n else\n rate(*args) / duration_in_months * 12\n end\n else\n nil\n end\n end", "def interest_part(balance, interest_rate)\n balance*(interest_rate/100)\n end", "def interest(rate)\n raise ArgumentError.new \"The rate must be a positive number\" if rate < 0\n interest = @balance * rate/100\n @balance += interest\n return interest\n end", "def compound_interest\n\tp \"What is the principal amount?\"#\n\tprincipal = gets.chomp.to_i\n\tp \"What is the rate?\"\n\trate = gets.chomp.to_f\n\tp \"What is the number of years?\"\n\tterm = gets.chomp.to_i\n\tp \"What is the number of time the interest in compounded per year?\"\n\tcompounded = gets.chomp.to_i\n\t\n\tnew_rate = ((rate / compounded)/100) + 1\n\ttotal = principal\n\t(term * compounded).times do\n\t\ttotal = total * new_rate\n\tend\n\t\n\tp \"$#{principal} invested at #{rate}% for #{term} years compounded #{compounded} times per year is #{total.round(2)}\"\n\t\nend", "def annual_salary\n hourly_rate * 1950\n end", "def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend", "def rate\n Rate.new(self.interest/100, :apr, duration: self.tenure * 12)\n end", "def efective_given_nominal_anticipated(nominal_rate, term)\n (((1/((1-((nominal_rate.to_f/100)/term))**term))-1)*100).round(4)\n end", "def interest\n return (@capital / 100) * @rate\n end", "def calculate_interest principle, days_since\n (principle * APR / 365 * days_since).round(2)\n end", "def debt_rate\n ten_year_treasury + bps(200)\n end", "def calculate_interest(principal, roi, time)\n rate = roi.to_f / 100\n amount = principal.to_f * (1 + rate * time.to_f)\n\n amount\nend", "def calculateInterest\n\t\tinterest = 0\n\t\[email protected] do |trans|\n\t\t\tinterest += -1 * ((31 - trans[0]) * trans[-1] * @APR / 365)\n\t\tend\n\t\tinterest < 0 ? 0 : interest.round(2)\n\tend", "def update_rates\n currencies(true).each_pair do |currency, data|\n rate = data[:middle_rate_for_commercial_transactions]\n add_rate(\"EUR\", currency, rate) if known_currencies.include?(currency)\n end\n rates\n end", "def future_value(rate,periods,present_value,compound_frequency = 1)\n compound_frequency = resolve_compound_frequency!(compound_frequency)\n if compound_frequency == :continuous\n return continuous_compound_fv(rate,periods,present_value)\n end\n future_value = present_value * (1+rate/compound_frequency)** (periods * compound_frequency)\n end", "def annual_ror(initial_value, final_value, years)\n if years <= 0\n 0\n elsif initial_value == 0\n # BigDecimal::INFINITY\n Float::INFINITY\n else\n 100.to_d * if final_value < 0 # fudge if final value is less than zero\n (((initial_value.to_d - final_value.to_d) / initial_value.to_d) ** (1 / years.to_d)) * -1\n else\n ((final_value.to_d / initial_value.to_d) ** (1 / years.to_d)) - 1\n end\n end\n end", "def withdrawal_rate\n (youngest_person_retirement_age - 15.0) / 1000.0\n end", "def profit_day_rate(cal)\n day_rate = avg_rate_card_amount_cents.round(2)\n mins_tracked = Timing.minute_duration_submitted_for_period_and_client(id, cal.start_date, cal.end_date)\n days_tracked = (hours = mins_tracked.to_s.to_d / account.account_setting.working_day_duration_minutes).round(2)\n invoiced_amount = Invoice.amount_cents_invoiced_for_period_and_client(id, cal.start_date, cal.end_date).round(2)\n total_project_potential = (days_tracked * avg_rate_card_amount_cents.round).round(2)\n\n if invoiced_amount == 0 && days_tracked != 0\n 0\n elsif invoiced_amount != 0 && days_tracked == 0\n invoiced_amount\n elsif invoiced_amount == 0\n day_rate\n else\n ((invoiced_amount / total_project_potential) * day_rate).round(2)\n end\n end", "def efective_given_nominal_due(nominal_rate, term)\n ((((1+((nominal_rate.to_f/100)/term))**term)-1).round(6))*100\n end" ]
[ "0.6941773", "0.6785467", "0.6609534", "0.65379953", "0.6418716", "0.6287261", "0.627252", "0.6134057", "0.6099594", "0.60314786", "0.6006965", "0.59807014", "0.59512377", "0.5846905", "0.58282346", "0.5824809", "0.58177525", "0.5814894", "0.57970273", "0.5775244", "0.5764877", "0.57511556", "0.5696544", "0.568939", "0.5684052", "0.56806034", "0.5675443", "0.5661221", "0.5660324", "0.563824" ]
0.757776
0
Migrating this to `authorizerhomerooms`
def authorized_homerooms if EnvironmentVariable.is_true('ENABLE_HOMEROOM_AUTHORIZATION_V2') authorizer.homerooms else authorizer.allowed_homerooms_DEPRECATED(acknowledge_deprecation: true) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def authorized_by(authorizer)\n authorizer.to_s.camelize.constantize # get authorizer loaded\n alias_method :old_users, :users\n alias_method :old_method_missing, :method_missing\n include TransitiveAuthorization::Authorizee::InstanceMethods\n self.cattr_accessor :transitive_authorizer\n self.transitive_authorizer = authorizer\n end", "def authorization(*args, &block); end", "def authorizations\n @@authorized_actions ||= {}\n @@authorized_actions\n end", "def authorization; end", "def authorized(&block)\n authorizer.authorized(&block)\n end", "def authorized(&block)\n authorizer.authorized(&block)\n end", "def authorize\n end", "def authorize\n end", "def authorizes(*authorizees)\n TransitiveAuthorization::AuthorizedUser.transitive_authorized_user.class_eval do\n alias_method :old_authorizables_for, :authorizables_for\n alias_method :old_has_role?, :has_role?\n alias_method :old_roles_for, :roles_for\n alias_method :old_method_missing, :method_missing\n include TransitiveAuthorization::Authorizer::InstanceMethods\n self.cattr_accessor :transitive_authorizees\n self.transitive_authorizees ||= Array.new\n self.transitive_authorizees << authorizees\n end\n end", "def documentation_authorizer\n @documentation_authorizer ||= Documentation.config.authorizer.new(controller)\n end", "def authorize \n self.make 'authorization' \n end", "def all_authorisor\n -> enforcer, policies, ctx {\n Fn.compose.( finally_fn.(enforcer),\n Fn.fmap_compose.(policies)\n ).(Success(ctx))\n }.curry\n end", "def apply_authorities(env)\n DogBiscuits.config.authorities_add_new.each do |authority_name|\n term = authority_name.to_s.singularize.to_sym\n next unless env.attributes.key? term\n env.attributes[term].each do |attr|\n add_new(authority_name.to_s, attr)\n end\n end\n end", "def create_authorizer\n auth = {}\n [\n # ACCOUNT\n :can_create_account?,\n :can_view_account?,\n :can_renew_account?,\n :can_close_account?,\n # RESOURCE\n :can_create_resource?,\n :can_view_resource?,\n :can_release_resource?,\n :can_modify_resource?,\n # LEASE\n :can_create_lease?,\n :can_view_lease?,\n :can_modify_lease?,\n :can_release_lease?,\n ].each do |m| auth[m] = true end\n OMF::SFA::AM::DefaultAuthorizer.new(auth)\n end", "def create_authorizer\n auth = {}\n [\n # ACCOUNT\n :can_create_account?,\n :can_view_account?,\n :can_renew_account?,\n :can_close_account?,\n # RESOURCE\n :can_create_resource?,\n :can_view_resource?,\n :can_release_resource?,\n :can_modify_resource?,\n # LEASE\n :can_create_lease?,\n :can_view_lease?,\n :can_modify_lease?,\n :can_release_lease?,\n ].each do |m| auth[m] = true end\n OMF::SFA::AM::DefaultAuthorizer.new(auth)\n end", "def normalize_author(hsh)\n str = hsh['author']\n tokens = repair_and_tokenize_author_text(str)\n authors = []\n current_auth = []\n begin_auth = 1\n tokens.each {|tok|\n if tok =~ /^(&|and)$/i\n if !current_auth.empty?\n auth = normalize_author_name(current_auth)\n authors << auth\n end\n current_auth = []\n begin_auth = 1\n next\n end\n if begin_auth > 0\n current_auth << tok\n begin_auth = 0\n next\n end\n if tok =~ /,$/\n current_auth << tok\n if !current_auth.empty?\n auth = normalize_author_name(current_auth)\n authors << auth\n current_auth = []\n begin_auth = 1\n end\n else\n current_auth << tok\n end\n }\n if !current_auth.empty?\n auth = normalize_author_name(current_auth)\n authors << auth unless auth.strip == \"-\"\n end\n hsh['authors'] = authors\n hsh\n end", "def authorizer\n current_ability\n end", "def ach_authorizations(entity_id)\n API::request(:get, \"entities/#{entity_id}/ach_authorizations\")\n end", "def authorize_leader!\n raise CanCan::AccessDenied if current_user.managed_chapters.count.zero?\n end", "def author_hash; end", "def authorize_resource(*args); end", "def resolved_author; end", "def authorize(verb); send_or_default(\"authorize_#{verb}\",true) ; end", "def show\n authorize @orden\n end", "def host_authorization; end", "def host_authorization; end", "def index\n @authorizations = Authorization.all\n end", "def index\n @authorizations = Authorization.all\n end", "def index\n authorize Order\n super\n end", "def normalize_author(hsh)\n str = hsh['author']\n tokens = repair_and_tokenize_author_text(str)\n authors = []\n current_auth = []\n begin_auth = 1\n tokens.each {|tok|\n if tok =~ /^(&|and)$/i\n if !current_auth.empty?\n auth = normalize_author_name(current_auth)\n authors << auth\n end\n current_auth = []\n begin_auth = 1\n next\n end\n if begin_auth > 0\n current_auth << tok\n begin_auth = 0\n next\n end\n if tok =~ /,$/\n current_auth << tok\n if !current_auth.empty?\n auth = normalize_author_name(current_auth)\n authors << auth\n current_auth = []\n begin_auth = 1\n end\n else\n current_auth << tok\n end\n }\n if !current_auth.empty?\n auth = normalize_author_name(current_auth)\n authors << auth.strip unless auth.strip == \"-\" || auth.strip.blank?\n end\n hsh['authors'] = authors if !authors.empty?\n normalize('author',hsh)\n hsh\n end" ]
[ "0.6965431", "0.63082737", "0.62287205", "0.61290187", "0.59146535", "0.59146535", "0.5896997", "0.5896997", "0.58728963", "0.5806797", "0.5795525", "0.57881975", "0.57546115", "0.5666361", "0.5666361", "0.5648755", "0.563015", "0.5618461", "0.559866", "0.55767435", "0.55689144", "0.5547122", "0.55168605", "0.5514433", "0.55123913", "0.55123913", "0.55042624", "0.55042624", "0.54859656", "0.5483117" ]
0.7283598
0
Query for students through homeroom, but scoped within studentlevel authorization check. This is essentially doublewrapping the authorizaiton checks; the homeroom authorization check should separately only allow access when the educator can access all students in the homeroom.
def authorized_students(homeroom) authorized do homeroom.students .active .includes(:event_notes, :interventions, :homeroom) .to_a end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def school_students(query={})\n self.simple_client.get(\"/api/v1/schools/my/students?#{query.to_query}\")\n end", "def query_student(hQuery)\n result = []\n\n hQuery[:status] = :active unless hQuery.key?(:status)\n\n @data[:students].each do |hValue|\n elem = hValue\n hQuery.each do |query_key, query_value|\n elem = nil if not_in_query?(hQuery, hValue, query_key, query_value)\n end\n result << elem if elem\n end\n result\n end", "def students\n filters = []\n filters.push(\"{SCHOOL_TFPID} = '#{goddamn_school}'\") if goddamn_school\n Student.some(\n shard: self.goddamn_city,\n sort: [\"Name\", :asc],\n filterByFormula: \"AND(#{filters.join(',')})\"\n )\n end", "def index\n if current_user.admin? or current_user.editor? #checks if user is admin, if so displays all of the students in database.\n @students = Student.all\n if params[:search]\n @students = Student.search(params[:search]).order(\"created_at DESC\")\n else\n @students = Student.all.order('created_at DESC')\n end\n elsif user_signed_in?\n @students = Student.all.where(:user_id => current_user.id) #Only displays the the users student. \n end\n\n\n authorize @students\n end", "def my_students(query={})\n self.simple_client.get(\"/api/v1/students?#{query.to_query}\")\n end", "def show\n @user = User.shod(params[:id])\n @student = @user.student\n @employee = User.where(role: 'Employee').take\n authorize! :read, @user\n end", "def students\n if current_user.is_admin?\n @students= User.find(:all, :conditions => \"is_teacher = '0' and is_admin = '0'\")\n respond_to do |format|\n format.xml { render :xml => @students }\n end\n else\n respond_to do |format|\n format.xml { render :text => \"error\" }\n end\n end\n end", "def authorized_homerooms\n if EnvironmentVariable.is_true('ENABLE_HOMEROOM_AUTHORIZATION_V2')\n authorizer.homerooms\n else\n authorizer.allowed_homerooms_DEPRECATED(acknowledge_deprecation: true)\n end\n end", "def set_hs_students_from_housing\n high_school_students_from_housing = CeqrData::ScaHousingPipelineByBoro.version(\n data_package.table_for(\"sca_housing_pipeline_by_boro\")\n ).high_school_students_from_new_housing_by_boro(project.borough)\n\n hs_students = high_school_students_from_housing.map{|s| s[:hs_students]}\n\n self.hs_students_from_housing = hs_students.first\nend", "def show\n authorize @institute\n @admins = User.where(role:3,institute_id: @institute.id)\n @students = User.where(role:1,institute_id: @institute.id)\n end", "def index\n \n parent_user = User.find( params[:parent_id] )\n\n\t# check that the issuer of the request has both the username and ID of the parent, prevent attack\n if params[:parent_login].gsub(/ /,'') != parent_user.login.gsub(/ /,'')\n \tlog_attack \"Student index() for parent \" + params[:parent_id] + \" : \" + params[:parent_login] + \" - parent_user.login = \" + parent_user.login \t\n respond_to do |format|\n format.xml { render :xml => errorRsp( \"Security error\") }\n end\n \treturn\n end\n \n \n if params[:parent_id] != nil\n @students = Student.find_all_by_parent_id(params[:parent_id], \n :conditions => { :status => [ \"active\" ] } )\n end\n \n \n if params[:admin_list] != nil\n @students = Student.find_all_by_status( [ \"active\", \"suspended\" ] )\n end\n \n respond_to do |format|\n format.xml { render :xml => @students }\n end\n end", "def index\n if logged_as_teacher?\n @sidequest= Sidequest.new\n @sidequests = Sidequest.where(teacher_id: session[:user_id])\n end\n if logged_as_student?\n student = Student.find(session[:user_id])\n progres = student.progre\n @sidequests = Sidequest.where(level: progres.lvl, finished: false)\n end\n end", "def index\n if current_user.roles == 'admin' or current_user.roles == 'editor' #checks if user is admin, if so displays all of the students in database.\n @emergency_contacts = EmergencyContact.all\n elsif user_signed_in?\n @emergency_contacts = EmergencyContact.all.where(:user_id => current_user.id) #Only displays the the users student. \n else\n @emergency_contacts = EmergencyContact.all\n end\n authorize @emergency_contacts\n end", "def index\n if user_signed_in?\n if current_user.role != 2\n redirect_to root_path\n else\n @institute_user = InstituteUser.find_by user_id: current_user.id\n @institute = Institute.find(@institute_user.institute_id)\n #@students = Student.all\n\n @query = Student.where(\"institute_id = ?\", @institute.id).ransack(params[:q])\n @institute_students = @query.result \n end\n else\n redirect_to root_path\n end\n end", "def index\n @studies = Study.find_studies_with_details(current_user.superadmin? ? nil : current_user&.id)\n @study_statistics_by_id = Study.get_study_statistics(studies: @studies)\n authorize! :read, StudyCompletion\n end", "def hals\n @course = Course.find(params[:id])\n # don't show any private hals\n @hals = @course.hals.not_private\n end", "def is_authorized_for_student(student)\n return true if self.districtwide_access?\n\n return false if self.restricted_to_sped_students && !(student.program_assigned.in? ['Sp Ed', 'SEIP'])\n return false if self.restricted_to_english_language_learners && student.limited_english_proficiency == 'Fluent'\n return false if self.school.present? && self.school != student.school\n\n return true if self.schoolwide_access? || self.admin? # Schoolwide admin\n return true if self.has_access_to_grade_levels? && student.grade.in?(self.grade_level_access) # Grade level access\n return true if student.in?(self.students) # Homeroom level access\n false\n end", "def show\n @teacher = Teacher.find(params[:id])\n @students = @teacher.students.order('full_name ASC')\n @students_at_school = Student.where(school_id: @teacher.school_id).order('full_name ASC')\n @students_not_in_roster = Student.where(school_id: @teacher.school_id).where.not(id: @teacher.students).order('full_name ASC')\n\n #Whenever this page is visited, it updates the roster for the admin.\n if @teacher.admin\n\n #https://stackoverflow.com/questions/3343861/how-do-i-check-to-see-if-my-array-includes-an-object\n @students_at_school.each do |student|\n unless @students.include?(student)\n @teacher.students << Student.find(student.id)\n end\n end\n \n @students = @students_at_school\n @students_not_in_roster = []\n else\n # add student case\n if params[:add_student] && (params[:add_student_id] != nil)\n @teacher.students << Student.find(params[:add_student_id])\n redirect_to @teacher\n # remove student case\n elsif params[:remove_student] && (params[:remove_student_id] != nil)\n @teacher.students.delete(Student.find(params[:remove_student_id]))\n redirect_to @teacher\n end\n end\n end", "def index\n authorize Student\n if User.find_by_email(current_user.email).provider == 'facebook' and Student.find_by_email(current_user.email).education == 'DUMMY'\n redirect_to edit_student_path(Student.find_by_email(current_user.email)), notice: 'Please fill out details first !'\n end\n\n @students = Student.all\n # authorize Student\n end", "def restrict_to_student\n # Get the instructor the message is headed to\n instructor = Instructor.find_by_id params[:user_id]\n\n # Get all instructors that this student has been taught by.\n #\n # SELECT * FROM users JOIN courses ON courses.instructor_id = users.id JOIN histories ON\n # histories.course_id = courses.id WHERE users.type = 'Instructor' AND histories.student_id = id\n #\n # This translates to selecting all instructors that have taught a course that is associated\n # with a history that belongs to the student.\n instructors = Instructor.joins(courses: :histories).where(histories: {user: @auth_user})\n\n # Redirect if the target instructor is not in the list of instructors\n redirect_to messages_path unless instructors.include? instructor\n end", "def index\n @students = params[:query].present? ? Student.find_by_query(params[:query]) : Student.all_students\n end", "def index\n @admin_students = Admin::Student.all\n if @admin_classroom.present?\n @admin_students = @admin_classroom.students\n end\n \n end", "def student_and_homeroom_grade_levels_now(school_id)\n return [] if @educator.homeroom.nil?\n homeroom_grade = @educator.homeroom.grade\n student_grades = @educator.homeroom.students\n .where(school_id: school_id)\n .active\n .map(&:grade)\n\n ([homeroom_grade] + student_grades).uniq\n end", "def students # Want: student id and student names on Users Table\n return User.joins(:sections).where(:sections => {:id => self.id}).all\n end", "def is_authorized_for_student?(student)\n begin\n return true if @educator.districtwide_access?\n\n return false if @educator.restricted_to_sped_students && !(student.program_assigned.in? ['Sp Ed', 'SEIP'])\n return false if @educator.restricted_to_english_language_learners && student.limited_english_proficiency == 'Fluent'\n return false if @educator.school_id.present? && student.school_id.present? && @educator.school_id != student.school_id\n\n return true if @educator.schoolwide_access? || @educator.admin? # Schoolwide admin\n return true if @educator.has_access_to_grade_levels? && student.grade.in?(@educator.grade_level_access) # Grade level access\n return true if student.in?(@educator.students) # Homeroom level access\n return true if student.in?(@educator.section_students) # Section level access\n rescue ActiveModel::MissingAttributeError => err\n # We can't do authorization checks on models with `#select` that are missing\n # fields. If this happens, it's probably because the developer is trying to\n # to optimize a query. The authorization layer could only recover by making more\n # queries, so instead we raise and force the developer to figure out how to resolve.\n #\n # See `Authorizer.student_fields_for_authorization` and `Authorizer.educator_field_for_authorization`\n # to see what fields are required on each model.\n raise err\n end\n false\n end", "def students\n Rollcall::Student.find_all_by_school_id schools\n end", "def students_for_grade_level_next_year_json\n params.require(:workspace_id)\n params.require(:school_id)\n params.require(:grade_level_next_year)\n school_id = params[:school_id].to_i\n grade_level_next_year = params[:grade_level_next_year]\n\n # Check authorization by grade level, differently than normal.\n students = queries.authorized_students_for_next_year(school_id, grade_level_next_year)\n students_json = ClassListQueries.students_as_json(students)\n\n # educator names\n educators_json = Educator.where(school_id: school_id).as_json(only: [:id, :full_name])\n\n render json: {\n students: students_json,\n educators: educators_json,\n current_educator_id: current_educator.id\n }\n end", "def index\n @q = current_user.houses.ransack(params[:q])\n @houses = @q.result(distinct: true).page params[:page]\n #@houses = current_user.houses.all.page params[:page]\n authorize @houses\n end", "def authorized_students_for_next_year(school_id, grade_level_next_year)\n grade_level_now = GradeLevels.new.previous(grade_level_next_year)\n return [] unless is_authorized_for_grade_level_now?(school_id, grade_level_now)\n\n # Query for those students (outside normal authorization rules)\n Student.active.where({\n school_id: school_id,\n grade: grade_level_now\n })\n end", "def students \n sk = Sektion.where(:teacher_id => self.id).map(&:id)\n sids = StudentRoster.where(:sektion_id => sk).map(&:student_id).uniq\n return Student.where(:id => sids)\n end" ]
[ "0.63462687", "0.6304662", "0.61484975", "0.57862616", "0.56988627", "0.5667931", "0.56361127", "0.5581746", "0.5519501", "0.5499715", "0.54860336", "0.5476777", "0.5427626", "0.5418739", "0.5410691", "0.53927666", "0.5379627", "0.53769565", "0.53667456", "0.533562", "0.53337866", "0.5325641", "0.5319898", "0.52909327", "0.528019", "0.52778226", "0.52691007", "0.5268825", "0.5232666", "0.5208139" ]
0.77949256
0
Serializes a Student into a hash with other fields joined in (that are used to perform filtering and slicing in the UI). This may be slow if you're doing it for many students without eager includes.
def fat_student_hash(student) HashWithIndifferentAccess.new(student.as_json({ except: [ :primary_phone, :primary_email, :student_address ] }).merge({ has_photo: student.has_photo, discipline_incidents_count: student.most_recent_school_year_discipline_incidents_count, absences_count: student.most_recent_school_year_absences_count, tardies_count: student.most_recent_school_year_tardies_count, homeroom_name: student.try(:homeroom).try(:name), event_notes_without_restricted: student.event_notes_without_restricted, interventions: student.interventions, sped_data: sped_data(student) })) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def serialize_students(student_ids, section)\n students = Student\n .active\n .where(id: student_ids)\n .includes(:student_section_assignments)\n\n students.map do |student|\n grade_numeric = student.student_section_assignments.find_by_section_id(section.id).grade_numeric\n student.as_json(methods: [\n :has_photo,\n :event_notes_without_restricted,\n :most_recent_school_year_discipline_incidents_count,\n :most_recent_school_year_absences_count,\n :most_recent_school_year_tardies_count\n ]).merge({\n grade_numeric: grade_numeric\n })\n end\n end", "def student_hash_for_slicing(student)\n student.as_json.merge({\n student_risk_level: student.student_risk_level.as_json,\n discipline_incidents_count: student.most_recent_school_year.discipline_incidents.count,\n absences_count: student.most_recent_school_year.absences.count,\n tardies_count: student.most_recent_school_year.tardies.count,\n homeroom_name: student.try(:homeroom).try(:name)\n })\n end", "def fat_student_hash(student)\n HashWithIndifferentAccess.new(student_hash_for_slicing(student).merge({\n event_notes_without_restricted: student.event_notes_without_restricted,\n interventions: student.interventions,\n sped_data: student.sped_data,\n }))\n end", "def fat_student_hash(student)\n HashWithIndifferentAccess.new(student_hash_for_slicing(student).merge({\n interventions: student.interventions,\n student_risk_level: student.student_risk_level.decorate.as_json_with_explanation,\n }))\n end", "def compute_student_hashes(authorized_student_ids)\n # Students table first\n authorized_students = Student.where(id: authorized_student_ids).includes(:homeroom)\n students_json = authorized_students.as_json({\n except: [\n :primary_phone,\n :primary_email,\n :student_address\n ]\n })\n\n # Optimized computation for aggregates\n aggregates = {\n discipline_incidents_count: DisciplineIncident.where(student_id: authorized_student_ids).where('occurred_at >= ?', first_day_of_school).group(:student_id).count,\n absences_count: Absence.where(student_id: authorized_student_ids).where('occurred_at >= ?', first_day_of_school).group(:student_id).count,\n tardies_count: Tardy.where(student_id: authorized_student_ids).where('occurred_at >= ?', first_day_of_school).group(:student_id).count\n }\n\n # Merge\n authorized_students.each_with_index.map do |student, index|\n HashWithIndifferentAccess.new(students_json[index].merge({\n discipline_incidents_count: aggregates[:discipline_incidents_count].fetch(student.id, 0),\n absences_count: aggregates[:absences_count].fetch(student.id, 0),\n tardies_count: aggregates[:tardies_count].fetch(student.id, 0),\n homeroom_name: student.try(:homeroom).try(:name)\n }))\n end\n end", "def get_student_section_columns_hash(students)\n students.inject({}) do |map, student|\n map[student[:student_id]] = section_columns_hash(student[:sections])\n map\n end\n end", "def flat_row_hash(student, all_service_types)\n student_fields = student.as_json.except(*[\n 'created_at',\n 'updated_at',\n 'student_address',\n 'hispanic_latino',\n 'race'\n ])\n\n additional_student_fields = {\n student_risk_level: student.student_risk_level.level,\n discipline_incidents_count: student.most_recent_school_year.discipline_incidents.count,\n absences_count: student.most_recent_school_year.absences.count,\n tardies_count: student.most_recent_school_year.tardies.count,\n homeroom_name: student.try(:homeroom).try(:name)\n }\n\n # unroll all service types\n student_service_type_ids = student.services.active.map(&:service_type_id)\n service_fields = all_service_types.reduce({}) do |hash, service_type|\n service = student.services.active.find {|service| service.service_type_id == service_type.id }\n value = if service.nil? then '' else service.date_started.strftime(\"%Y-%m-%d\") end\n hash[\"#{service_type.name} (active_service_date_started)\"] = value\n hash\n end\n\n # Unroll all event note types.\n # This will include the presence of restricted notes, but only the date and\n # no content.\n all_event_note_types = EventNoteType.all\n event_note_type_ids = student.event_notes.map(&:event_note_type_id)\n event_note_fields = all_event_note_types.reduce({}) do |hash, event_note_type|\n event_note = student.event_notes.find {|event_note| event_note.event_note_type_id == event_note_type.id }\n value = if event_note.nil? then '' else event_note.recorded_at.strftime(\"%Y-%m-%d\") end\n hash[\"#{event_note_type.name} (last_event_note_recorded_at)\"] = value\n hash\n end\n\n student_fields\n .merge(additional_student_fields)\n .merge(service_fields)\n .merge(event_note_fields)\n .stringify_keys!\n end", "def profile\n student = Student.find(params[:id])\n chart_data = StudentProfileChart.new(student).chart_data\n @serialized_data = {\n current_educator: current_educator,\n student: student.serialized_data,\n notes: student.student_notes.map { |note| serialize_student_note(note) },\n feed: student_feed(student),\n chart_data: chart_data,\n intervention_types_index: intervention_types_index,\n educators_index: educators_index,\n attendance_data: {\n discipline_incidents: student.most_recent_school_year.discipline_incidents,\n tardies: student.most_recent_school_year.tardies,\n absences: student.most_recent_school_year.absences\n }\n }\n end", "def merge_mutable_fields_for_slicing(student_hashes)\n student_ids = student_hashes.map {|student_hash| student_hash[:id] }\n mutable_fields = mutable_fields_for_slicing(student_ids)\n\n student_hashes.map do |student_hash|\n for_student = {\n event_notes: mutable_fields[:all_event_notes].select {|event_note| event_note.student_id == student_hash[:id] },\n active_services: mutable_fields[:all_active_services].select {|service| service.student_id == student_hash[:id] },\n summer_services: mutable_fields[:all_summer_services].select {|service| service.student_id == student_hash[:id] },\n interventions: mutable_fields[:all_interventions].select {|intervention| intervention.student_id == student_hash[:id] }\n }\n student_hash.merge({\n event_notes: for_student[:event_notes].map {|x| EventNoteSerializer.safe(x).serialize_for_school_overview },\n active_services: for_student[:active_services].map {|x| ServiceSerializer.new(x).serialize_service },\n summer_services: for_student[:summer_services].map {|x| ServiceSerializer.new(x).serialize_service },\n interventions: for_student[:interventions].map {|x| DeprecatedInterventionSerializer.new(x).serialize_intervention },\n })\n end\n end", "def hash_builder(student)\n student_hash = { id: student.id, name: student.first_name + ' ' + student.s_last_name,\n other_interventions: student.num_other_programs,\n tutor: student.vol_name, first_attempt_average: @acumen_one,\n second_attempt_average: @acumen_two,\n hug_gain: (@acumen_two - @acumen_one).round(2),\n last_year_dra_gains: @last_year_dra_gains,\n fall_dra: @student_record[:fall_dra], winter_dra: @student_record[:winter_dra],\n mid_year_dra_gain: @student_record[:mid_year_dra_gain],\n spring_dra: @student_record[:spring_dra], end_year_dra_gain: @student_record[:end_year_dra_gain],\n fall_rit: @student_record[:fall_rit], winter_rit: @student_record[:winter_rit],\n mid_year_rit_gain: @student_record[:mid_year_rit_gain],\n spring_rit: @student_record[:spring_rit], end_year_rit_gain: @student_record[:end_year_rit_gain],\n fall_rank: @student_record[:fall_rank], winter_rank: @student_record[:winter_rank],\n mid_year_rank_gain: @student_record[:mid_year_rank_gain],\n spring_rank: @student_record[:spring_rank], end_year_rank_gain: @student_record[:end_year_rank_gain],\n fall_lexile: @student_record[:fall_lexile], winter_lexile: @student_record[:winter_lexile],\n spring_lexile: @student_record[:spring_lexile] }\n student_hash\n end", "def students_by_section\n class_map = Hash.new{ |h,k| h[k] = [] }\n self.followers.includes([:section, :student_user]).each do |f|\n class_map[f.section] << f.student_user\n end\n class_map\n end", "def student_feed(student, restricted_notes: false)\n {\n event_notes: student.event_notes\n .select {|note| note.is_restricted == restricted_notes}\n .map {|event_note| EventNoteSerializer.new(event_note).serialize_event_note },\n services: {\n active: student.services.active.map {|service| ServiceSerializer.new(service).serialize_service },\n discontinued: student.services.discontinued.map {|service| ServiceSerializer.new(service).serialize_service }\n },\n deprecated: {\n interventions: student.interventions.map { |intervention| DeprecatedInterventionSerializer.new(intervention).serialize_intervention }\n }\n }\n end", "def to_jaxb_json_hash\n _h = {}\n if !students.nil?\n _ha = Array.new\n students.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['students'] = _ha\n end\n return _h\n end", "def student_list\n Student::all.map do |s|\n s.attributes.except 'id', 'created_at', 'updated_at'\n end\n end", "def student_feed(student, restricted_notes: false)\n {\n event_notes: student.event_notes\n .select {|note| note.is_restricted == restricted_notes}\n .map {|event_note| EventNoteSerializer.dangerously_include_restricted_note_text(event_note).serialize_event_note },\n transition_notes: student.transition_notes\n .select {|note| note.is_restricted == restricted_notes},\n services: {\n active: student.services.active.map {|service| ServiceSerializer.new(service).serialize_service },\n discontinued: student.services.discontinued.map {|service| ServiceSerializer.new(service).serialize_service }\n },\n deprecated: {\n interventions: student.interventions.map { |intervention| DeprecatedInterventionSerializer.new(intervention).serialize_intervention }\n }\n }\n end", "def collect_students(section = nil, student_attr = nil)\n @students ||= (\n student_list = data.collect{|row| row[0].to_s.sub(/COMMA\\s*/,', ').strip}\n students = student_list.collect do |student|\n s = section.rollbook_entries.detect{|rbe| rbe.student.send(student_attr) == student}\n s && s.id\n end\n students)\n end", "def sample_students_json\n raise Exceptions::EducatorNotAuthorized unless current_educator.can_set_districtwide_access?\n\n seed = params.fetch(:seed, '42').to_i\n n = params.fetch(:n, '40').to_i\n authorized_sample_students = authorized do\n Student.active.sample(n, random: Random.new(seed))\n end\n sample_students_json = authorized_sample_students.as_json({\n only: [:id, :grade, :first_name, :last_name],\n include: {\n school: {\n only: [:id, :name, :school_type]\n }\n }\n })\n render json: {\n sample_students: sample_students_json\n }\n end", "def student_feed(student)\n {\n v1_notes: student.student_notes.map { |note| serialize_student_note(note) },\n v1_interventions: student.interventions.map { |intervention| serialize_intervention(intervention) },\n event_notes: student.event_notes,\n v2_services: if Rails.env.development? then v2_services_fixture else [] end\n }\n end", "def add_student_attributes(student_hash)\n @twitter = student_hash[:twitter]\n @linkedin = student_hash[:linkedin]\n @github = student_hash[:github]\n @blog = student_hash[:blog]\n @profile_quote = student_hash[:profile_quote]\n @bio = student_hash[:bio]\n @profile_url = student_hash[:profile_url]\n\n end", "def students # Want: student id and student names on Users Table\n return User.joins(:sections).where(:sections => {:id => self.id}).all\n end", "def index\n @course = params[:course_id]\n @students = Student.left_join_enrolls @course\n puts @students.as_json\n end", "def students_with_low_grades_json(time_now, time_threshold, grade_threshold)\n all_assignments = assignments(time_now, time_threshold, grade_threshold)\n by_student = all_assignments.group_by(&:student)\n json = by_student.map do |student, assignments|\n {\n student: student.as_json(:only => [:id, :email, :first_name, :last_name, :grade, :house]),\n assignments: assignments.map {|assignment| serialize_assignment(assignment) }\n }\n end\n json.as_json\n end", "def set_student\n @student = Student.includes(:scores, :nutritions).find(params[:id])\n end", "def student\n\n\t\tif(params[:student_user_id].eql?('null') || params[:classroom_id].eql?('null') )\n\t\t\trender json: {status: \"error\", error: \"invalid-student-user-or-classroom\"}\n\t\telse\n\t\t\tstudent = StudentUser.joins(:classrooms)\n\t\t\t\t.joins(\"inner join teacher_users t on classrooms.teacher_user_id = t.id\")\n\t\t\t\t.where(\"t.id = ?\", @current_teacher_user.id)\n\t\t\t\t.where(\"classrooms.id = ?\", params[:classroom_id])\n\t\t\t\t.where(\"student_users.id = ?\" , params[:student_user_id])\n\t\t\t\t.first\n\n\t\t\tif(!student.nil?)\n\t\t\t\tstudent = student.as_json\n\t\t\t\tstudent.delete(\"salt\")\n\t\t student.delete(\"password_digest\")\n\t\t student.delete(\"oauth_expires_at\")\n\t\t student.delete(\"oauth_token\")\n\t\t student.delete(\"updated_at\")\n\t\t student.delete(\"create_at\")\n\n\t\t\t\trender json: {status: \"success\", student: student}\n\t\t\t\n\t\t\telse\n\n\t\t\t\trender json: {status: \"error\", error: \"invalid-student-user-or-classroom\"}\n\n\t\t\tend\n\t\tend\n\t\t\n\t\t\n\tend", "def set_student\n @student = Student.includes(:person=>[ {photos: :person}, {passports: :person}]).where(id:params[:id]).take\n if @student != nil\n @p_address = Address.where(:person_id => @student.person.id).order(\"addresses.id DESC\").limit(1).where(:a_type=>1).take\n @r_address = Address.where(:person_id => @student.person.id).order(\"addresses.id DESC\").limit(1).where(:a_type=>2).take\n @f_address = Address.where(:person_id => @student.person.id).order(\"addresses.id DESC\").limit(1).where(:a_type=>3).take\n end\n end", "def sped_data(student)\n {\n sped_level: sped_level(student),\n sped_tooltip_message: sped_tooltip_message(student),\n sped_bubble_class: sped_bubble_class(student)\n }\n end", "def construct_table_rows(students, grade_entry_form)\n result = {}\n students.each do |student|\n result[student.id] = construct_table_row(student, grade_entry_form)\n end\n\n result\n end", "def index\n puts render json: @user.students, each_serializer: UserSerializer\n end", "def student_params\n params.fetch(:student, {}).permit(\n :last_name,\n :first_name,\n :birthdate,\n :email,\n :level_id,\n :accommodations,\n :school,\n :school_grade,\n :highest_math_class,\n :waiver_submitted)\n end", "def students\n @course = Course.find(params[:id])\n\t\t@students = @course.students\n\t\t@other_students = Student.find(:all, :conditions => [\"id not in (select student_id from courses_students where course_id=?)\", @course.id])\n\n respond_to do |format|\n format.html # students.html.erb\n format.json { render :json => @students }\n end\n end" ]
[ "0.74007237", "0.7180264", "0.7028448", "0.69895357", "0.6417459", "0.63001305", "0.6236654", "0.62192965", "0.6130004", "0.60334575", "0.5991246", "0.59414005", "0.59389347", "0.59350747", "0.5875466", "0.5874363", "0.5831538", "0.57497793", "0.5737095", "0.56373227", "0.56134474", "0.5577197", "0.55398154", "0.5537411", "0.5473963", "0.54303396", "0.5396487", "0.535877", "0.5356221", "0.53441495" ]
0.7238609
1
SpEd Data as defined by Somerville Schools
def sped_data(student) { sped_level: sped_level(student), sped_tooltip_message: sped_tooltip_message(student), sped_bubble_class: sped_bubble_class(student) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sld; end", "def sp\n\t\t# --Stallция Preφιcς--\n\t\ts = ['S', 'Z', 'C', 'S']\n\t\tt = ['t', 'zt', 'ct', 'st']\n\t\ta = ['a', 'å', 'ä', 'ą']\n\t\tl = ['l', 'll', 'л', 'лл', 'lъ', 'llъ', 'лъ', 'ллъ',]\n\t\tc = ['c', 'z', 's', 'c', 'z', 'ц']\n\t\ti = ['i', '', 'и']\n\t\tja = ['a', 'ja', 'ya', 'ia', 'иa','я', 'ѧ']\n\t\tpp = ['P', 'П', 'Ψ', 'Ξ']\n\t\tr = ['r', 'р']\n\t\te = ['e', 'ϵ', 'ε']\n\t\tfi = ['f', 'ff', 'ф', 'φ', 'ѳ', 'þ', 'ξ']\n\t\tjota = ['i', 'и', 'ι', 'ї', 'ј']\n\t\tis = ['s', 'z', 'c', 'σ', 'ς',\n\t\t\t\t'ss', 'sz', 'sσ', 'sς', 'zs', 'cs', 'σs',\n\t\t\t\t'zz', 'zc', 'zσ', 'zς', 'cz', 'σz',\n\t\t\t\t'cc', 'cσ', 'cς', 'sc', 'σc',\n\t\t\t\t'σσ', 'σς', 'ςς',\n\t\t\t\t'ssz', 'ssσ', 'ssς', 'zss', 'css', 'σss',\n\t\t\t\t'scz']\n\t\tsparray = [s, t, a, l, c, i, ja, [\"\\n\"], pp, r, e, fi, jota, is]\n\t\tcilibles = []\n\t\tfor i in sparray\n\t\t\tcilibles.push(i[rand(i.length)])\n\t\tend\n\t\t@spreffis = cilibles.join\n\t\t@spinitial = cilibles[0] + cilibles[8]\n\tend", "def summer_olympics_sport; end", "def stderrs; end", "def summer_paralympics_sport; end", "def idols_data\n\n\t\t[[ \"Last name\", \"First name\", \"Description\" ]] + [[ @view_context.number_to_currency(1), 2, 3] ] +\n\t\[email protected] { |idol| [idol.last_name, idol.first_name, idol.talents.first.description] }\n\n\tend", "def schubert; end", "def sid_column\n end", "def ssmed_params\n params.require(:ssmed).permit(\n :ssmedprint, :ssmedcomment, :election_year_id, :county, :current_step\n )\n end", "def spanish_citizen_number; end", "def the_stans(data)\nend", "def schumann; end", "def pcode4\n school.sierra_code\n end", "def sv\n field_fetch('SV').sub(/;/,'')\n end", "def sid\n data['sid']\n end", "def ob_sssr\n @ob.get_sssr.to_a\n end", "def sld\n self.domain.sld\n end", "def parse_sqft\n end", "def parse_sqft\n end", "def to_escp\n @data\n end", "def winter_olympics_sport; end", "def site_data; end", "def sospa(location)\n string = location[1..-1]\n col = location[0].to_i\n row = (string.length.to_f / col).floor\n remainder = string.length % col\n address = [[nil]*col]*(row+1)\n\n sizes = [row+1] * remainder + [row] * (col - remainder)\n pos = 0\n sizes.each_with_index { |size, i|\n size.times { |index| address[col * index + i] = string[pos + index] }\n pos += size\n }\n\n address = CGI::unescape(address.join).gsub('^', '0')\n rescue\n raise location\n end", "def data\n # STUB\n end", "def spa\n return @spa\n end", "def national_sport; end", "def spanish_foreign_citizen_number; end", "def sn\n end", "def evalue;\t\[email protected];\t\tend", "def primary_school; end" ]
[ "0.57599723", "0.5654223", "0.5592384", "0.55232763", "0.5443806", "0.5325148", "0.5241047", "0.52281827", "0.52018094", "0.5200175", "0.5169785", "0.5169777", "0.51659054", "0.5161655", "0.515208", "0.5147694", "0.5135845", "0.5131139", "0.5131139", "0.51245856", "0.511807", "0.5085833", "0.50699806", "0.506589", "0.5058614", "0.505292", "0.5027107", "0.50060385", "0.49992824", "0.49928224" ]
0.640719
0
GET /featured_clients GET /featured_clients.json
def index @featured_clients = FeaturedClient.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_featured_client\n @featured_client = FeaturedClient.find(params[:id])\n end", "def index\n @clients = current_user.clients\n render json: @clients\n end", "def show\n render json: @client\n end", "def get_featured\n render json: Event.where(is_featured: true), status: :ok\n end", "def show\n @clients = get_clients\n @client = Client.find(params[:id])\n\n respond_to do |format|\n #format.html # show.html.erb\n format.json { render json: @client }\n format.js\n end\n end", "def show\n @client = Client.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def show\n @client = Client.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def show\n @client = Client.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def show\n @client = Client.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def show\n @client = Client.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def show\n @client = Client.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def show\n @client = Client.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def show\r\n @client = Client.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @client }\r\n end\r\n end", "def create\n @featured_client = FeaturedClient.new(featured_client_params)\n\n respond_to do |format|\n if @featured_client.save\n format.html { redirect_to @featured_client, notice: 'Featured client was successfully created.' }\n format.json { render :show, status: :created, location: @featured_client }\n else\n format.html { render :new }\n format.json { render json: @featured_client.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @clients = Client.all\n render json: @clients\n end", "def index\n @clients = Client.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clients }\n end\n end", "def index\n @clients = Client.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clients }\n end\n\n end", "def show\n client = Client.retrieve_by_id(params[:id])\n\n render json: client, serializer: SingleClientSerializer\n end", "def index\n sanitized_params = parse_params(client_where_params)\n clients = Client.find_all(sanitized_params)\n render json: clients\n end", "def index\n render json: Client.all\n end", "def show\n @client = clients.find(params[:id])\n end", "def find_client\n cliente = get_cliente(params[:id])\n\n respond_to do |format|\n format.json {render json: {client: cliente}}\n end\n end", "def show\n @clientsOffers = ClientsOffers.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clientsOffers }\n end\n end", "def recent\n if current_user.is_admin?\n @clients = Client.all\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @clients }\n end\n end", "def update\n respond_to do |format|\n if @featured_client.update(featured_client_params)\n format.html { redirect_to @featured_client, notice: 'Featured client was successfully updated.' }\n format.json { render :show, status: :ok, location: @featured_client }\n else\n format.html { render :edit }\n format.json { render json: @featured_client.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @clients = Client.all\n @uuid = params[:uuid]\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clients }\n end\n end", "def show\n\t\t@client = Client.find(params[:id])\n\t\tif @client.status != 0\n\t\t\trender :json => @client, status: 200\n\t\telse\n\t\t\trender :json => @client.status, status: 400\n\t\tend\n\tend", "def list_clients(json_payload={})\n conn = @client.get do |req|\n req.url \"/api/v2/client/list?\"\n req.headers[\"Authorization\"] = @token\n req.params = json_payload\n end\n conn.body\n end", "def get_clients\n @clients\n end", "def get_clients\n @clients\n end" ]
[ "0.6933652", "0.683633", "0.67539525", "0.6728703", "0.66623473", "0.6645311", "0.6645311", "0.6645311", "0.6645311", "0.6645311", "0.6645311", "0.6645311", "0.6604498", "0.65847147", "0.6570766", "0.656262", "0.6558943", "0.6556442", "0.6501677", "0.64970773", "0.6423044", "0.6401207", "0.6362379", "0.63543266", "0.6352246", "0.63308823", "0.63179797", "0.62598413", "0.62346554", "0.62346554" ]
0.78416455
0
POST /featured_clients POST /featured_clients.json
def create @featured_client = FeaturedClient.new(featured_client_params) respond_to do |format| if @featured_client.save format.html { redirect_to @featured_client, notice: 'Featured client was successfully created.' } format.json { render :show, status: :created, location: @featured_client } else format.html { render :new } format.json { render json: @featured_client.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_featured_client\n @featured_client = FeaturedClient.find(params[:id])\n end", "def update_features(client_id)\n response = self.class.put(\"https://app.klipfolio.com/api/1.0/clients/#{client_id}/features\", basic_auth: @auth, headers: { \"Content-Type\" => \"application/json\" },\n body: {\n features:[{\"name\":\"public_dashboards\",\"enabled\":true},\n {\"name\":\"published_dashboards\",\"enabled\":true},\n {\"name\":\"downloadable_reports\",\"enabled\":true},\n {\"name\":\"scheduled_emails\",\"enabled\":true}]\n }.to_json)\n puts response.body\n puts \"Client's features were updated.\" if response.success?\n end", "def index\n @featured_clients = FeaturedClient.all\n end", "def update\n respond_to do |format|\n if @featured_client.update(featured_client_params)\n format.html { redirect_to @featured_client, notice: 'Featured client was successfully updated.' }\n format.json { render :show, status: :ok, location: @featured_client }\n else\n format.html { render :edit }\n format.json { render json: @featured_client.errors, status: :unprocessable_entity }\n end\n end\n end", "def featured_client_params\n params.require(:featured_client).permit(:image, :website_name, :testimonial)\n end", "def create\n @client = current_user.clients.build(client_params)\n\n if @client.save\n render :create, status: :created\n CareeerMailer.trial_end(current_user.email, @client).deliver_later\n CareeerMailer.welcome(current_user.email, @client).deliver_later\n else\n render json: @client.errors, status: :unprocessable_entity\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to clients_url, notice: 'El cliente se creó correctamente' }\n format.json { render :index, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = current_user.clients.build(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = current_user.clients.build(client_params)\n \n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(params[:client])\n @client.campaign_id = session[:campaign_id]\n @groups = Group.all.map {|g| [g.name, g.id]}\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, :notice => 'Client was successfully created.' }\n format.json { render :json => @client, :status => :created, :location => @client }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @client.errors, :status => :unprocessable_entity }\n end\n end\n end", "def destroy\n @featured_client.destroy\n respond_to do |format|\n format.html { redirect_to featured_clients_url, notice: 'Featured client was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to clients_path, notice: 'Client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @clients = get_clients\n @client = Client.new(params[:client])\n\n respond_to do |format|\n if @client.save\n @clients = get_clients\n newVisitOnCreate(@client)\n #format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render json: @client, status: :created, location: @client }\n format.js\n else\n #format.html { render action: \"index\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n format.js\n end\n end\n end", "def create\n @client = Client.new(params[:client])\n\n respond_to do |format|\n if @client.save \n format.html { redirect_to @client, :notice => 'Klijent je uspjesno kreiran.' }\n format.json { render :json => @client, :status => :created, :location => @client }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @client.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(params[:client])\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to clients_path, notice: 'Client was successfully created.' }\n format.json { render json: @client, status: :created, location: @client }\n else\n format.html { render action: \"new\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n\n format.js\n\n format.html { redirect_to root_path, notice: 'Vous avez bien été ajouté à notre newsletter' }\n\n format.json { render :show, status: :created, location: @client }\n\n else\n\n format.html { render :new }\n\n format.json { render json: @client.errors, status: :unprocessable_entity }\n\n end\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: \"Client was successfully created.\" }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n authorize @client\n respond_to do |format|\n if @client.save\n format.html { redirect_back_or_default clients_url, t('Record has been saved') }\n format.json { render :show, status: :created, location: @client }\n format.js { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n format.js { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(params[:client])\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render json: @client, status: :created, location: @client }\n else\n format.html { render action: \"new\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(params[:client])\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render json: @client, status: :created, location: @client }\n else\n format.html { render action: \"new\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(params[:client])\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render json: @client, status: :created, location: @client }\n else\n format.html { render action: \"new\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(params[:client])\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Client was successfully created.' }\n format.json { render json: @client, status: :created, location: @client }\n format.js\n else\n format.html { render action: \"new\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n format.js\n end\n end\n end", "def create\n #newParams = client_params.as_json\n flash[:notice] = \"Cliente creado\"\n @client = current_freelance.clients.create(client_params)\n\n #@client = current_freelance.clients\n #@client.name = params[:name]\n #@client.surname = params[:surname]\n #@client.username = params[:username]\n #@client.password = params[:password]\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to clients_path, notice: 'Client was successfully created.' }\n #format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to @client, notice: 'Cliente cadastrado com sucesso!' }\n format.json { render :show, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @featured = Featured.new(featured_params)\n @featured.user = current_user\n respond_to do |format|\n if @featured.save\n format.html { redirect_to @featured, notice: 'Featured was successfully created.' }\n format.json { render :show, status: :created, location: @featured }\n else\n format.html { render :new }\n format.json { render json: @featured.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.67577773", "0.6596986", "0.6583391", "0.6533749", "0.6523827", "0.6325813", "0.6287912", "0.6286387", "0.62818676", "0.62335885", "0.6210315", "0.62056553", "0.62049633", "0.6194312", "0.6185106", "0.61788565", "0.61700845", "0.6154021", "0.6149242", "0.6149242", "0.6149242", "0.6148748", "0.6143141", "0.6113137", "0.6113137", "0.6113137", "0.6102692", "0.60985816", "0.60902274", "0.6089652" ]
0.7798717
0
PATCH/PUT /featured_clients/1 PATCH/PUT /featured_clients/1.json
def update respond_to do |format| if @featured_client.update(featured_client_params) format.html { redirect_to @featured_client, notice: 'Featured client was successfully updated.' } format.json { render :show, status: :ok, location: @featured_client } else format.html { render :edit } format.json { render json: @featured_client.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_features(client_id)\n response = self.class.put(\"https://app.klipfolio.com/api/1.0/clients/#{client_id}/features\", basic_auth: @auth, headers: { \"Content-Type\" => \"application/json\" },\n body: {\n features:[{\"name\":\"public_dashboards\",\"enabled\":true},\n {\"name\":\"published_dashboards\",\"enabled\":true},\n {\"name\":\"downloadable_reports\",\"enabled\":true},\n {\"name\":\"scheduled_emails\",\"enabled\":true}]\n }.to_json)\n puts response.body\n puts \"Client's features were updated.\" if response.success?\n end", "def update\n @client.update(client_params)\n render json: @client\n end", "def set_featured_client\n @featured_client = FeaturedClient.find(params[:id])\n end", "def update\n authorize! :update, Client\n load_client\n build_client\n save_client or render :edit\n end", "def update\n @clients = get_clients\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n @clients = get_clients\n #format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { head :no_content }\n format.js\n else\n #format.html { render action: \"index\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n format.js\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to clients_path, notice: 'Client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to clients_path, notice: 'Client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_client\n\t\t@client = Client.find(params[:id])\n\n\t \trespond_to do |format|\n\t\t if @client.update_attributes(client_update_params)\n\t\t format.html { redirect_to(@client, :notice => 'Entry was successfully updated.') }\n\t\t format.json { respond_with_bip(@client) }\n\t\t else\n\t\t format.html { render :action => \"edit\" }\n\t\t format.json { respond_with_bip(@client) }\n\t\t end\n\n \t end\n\tend", "def update\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to @client, :notice => 'Klijent je uspjesno izmjenjen.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @client.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to @client, :notice => 'El cliente se ha actualizado correctamente.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @client.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n\n if @client.update(client_params)\n format.html { redirect_to clients_path, notice: 'Client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n params[:client][:contact_ids] ||= []\n @client = Client.find(params[:id])\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\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\n authorize @client\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_back_or_default clients_url, t('Record has been saved') }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n authorize! :update, @client\n\n respond_to do |format|\n if @client.update_attributes(client_params)\n format.html { redirect_to @client, :notice => 'Client was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @client.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n if @client.update(client_params)\n head(:ok)\n else\n render json: @client.errors.full_messages, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n succeess_redirect_path = URI(request.referer).path.gsub 'edit', ''\n if @client.update(client_params)\n format.html { redirect_to succeess_redirect_path, notice: 'Client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { redirect_to URI(request.referer).path }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: 'client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: 'client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n params[:client][:version] = ENV[\"VERSION\"]\r\n params[:client][:username] = current_user.username\r\n @client = Client.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @client.update_attributes(client_params)\r\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: \"edit\" }\r\n format.json { render json: @client.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: \"Client was successfully updated.\" }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n \n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to clients_url, notice: 'La información del cliente se actualizó correctamente.' }\n format.json { render :index, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client.update(client_params)\n format.html { redirect_to @client, notice: 'Client was successfully updated.' }\n format.json { render :show, status: :ok, location: @client }\n else\n format.html { render :edit }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.7180061", "0.71587324", "0.67126924", "0.6706564", "0.6624684", "0.66181684", "0.66181684", "0.657036", "0.6560939", "0.6560939", "0.6537225", "0.6521621", "0.6474115", "0.64677155", "0.64466053", "0.64425135", "0.64348674", "0.6433545", "0.64225364", "0.64199555", "0.64164215", "0.64164215", "0.6408945", "0.6405561", "0.6400949", "0.6400565", "0.63983315", "0.63983315", "0.63983315", "0.63983315" ]
0.7571402
0
DELETE /featured_clients/1 DELETE /featured_clients/1.json
def destroy @featured_client.destroy respond_to do |format| format.html { redirect_to featured_clients_url, notice: 'Featured client was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @client.destroy\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :ok }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :ok }\n end\n end", "def destroy\r\n @client = Client.find(params[:id])\r\n @client.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to clients_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @client.destroy\n respond_to do |format|\n format.html { redirect_to clients_url, notice: 'Данные по клиенту удалены.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n authorize! :update, @client\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :ok }\n end\n end", "def destroy\n @my_studio_client = MyStudio::Client.find(params[:id])\n @my_studio_client.destroy\n\n respond_to do |format|\n format.html { redirect_to my_studio_clients_url }\n format.json { head :ok }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n @uuid = params[:uuid]\n respond_to do |format|\n format.html { redirect_to :controller => 'ads', :action => 'admin_dash', :id => 1, :uuid => @uuid }\n format.json { head :no_content }\n end\n end", "def destroy\n @client.destroy\n respond_to do |format|\n format.html { redirect_to clients_url, notice: 'Client a été supprimer.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_client = ApiClient.find(params[:id])\n @api_client.destroy\n\n respond_to do |format|\n format.html { redirect_to api_clients_url }\n format.json { head :no_content }\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(client_id)\n id = client_id.to_s\n Client.collection.filter(:id => id).delete\n AuthRequest.collection.filter(:client_id => id).delete\n AccessGrant.collection.filter(:client_id => id).delete\n AccessToken.collection.filter(:client_id => id).delete\n end", "def destroy\n @qa_client = QaClient.find(params[:id])\n @qa_client.destroy\n\n respond_to do |format|\n format.html { redirect_to qa_clients_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n \n if @client.deleted_at.blank?\n @client.destroy\n else\n @client.revive\n end\n \n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :ok }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n \n respond_to do |format|\n format.html { redirect_to clients_url }\n format.xml { head :ok }\n end\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n @clients = get_clients\n @client = Client.new\n\n respond_to do |format|\n #format.html { redirect_to clients_url }\n format.json { head :no_content }\n format.js\n end\n end", "def destroy\n @otg_client.destroy\n respond_to do |format|\n format.html { redirect_to otg_clients_url, notice: 'Otg client was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @client.destroy\n respond_to do |format|\n format.html { redirect_to clients_url, notice: 'El Cliente fue Eliminado Exitosamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize @client\n @client.destroy\n respond_to do |format|\n format.html { redirect_back_or_default clients_url, t('Record has been deleted') }\n format.json { head :no_content }\n end\n end" ]
[ "0.75142395", "0.745067", "0.745067", "0.745067", "0.745067", "0.745067", "0.745067", "0.745067", "0.745067", "0.745067", "0.744217", "0.7420447", "0.7420447", "0.7416775", "0.7321803", "0.73160225", "0.7283156", "0.7262876", "0.7257515", "0.7226291", "0.72083664", "0.71967685", "0.71831965", "0.7175605", "0.7167847", "0.71629816", "0.7150093", "0.7143115", "0.7134274", "0.71249956" ]
0.79933196
0
Convert value to bit array to_multi_bit( '0b101010', 6 ) => [1,0,1,0,1,0] to_multi_bit( '0b101010', 10 ) => [1,0,1,0,1,0,0,0,0,0] to_multi_bit( '0b101010', 3 ) => [1,0,1] to_multi_bit( '0b01010' ) => [1,0,1,0] minimum array size for val to_multi_bit( '' ) => [0] null string is equivalent to 0
def to_multi_bit( val, array_size=-1 ) array_size = Integer(array_size) unless array_size.kind_of?(Integer) if val == '' then val = '0' end begin val = Integer(val).to_s(2) rescue => e raise ParameterError, "#{__method__} contains invalid string for number" end arr = val.scan(/./).map{ |b| b.to_i(2) } return arr if array_size < 0 return _fit_array_length( arr, array_size ) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_bit_array\n BitMapping.number_to_bit_array(number)\n end", "def input_to_bitstring( value )\r\n value\r\n end", "def number_to_bit_array(number, minimum_binary_places = 0)\n assert_non_negative(number)\n array = []\n while number > 0\n array << (number & 1)\n number >>= 1\n end\n array.reverse!\n zero_pad_count = minimum_binary_places - array.size\n zero_pad_count.times { array.unshift(0) }\n array\n end", "def set_bits\n bits = []\n 0.upto(63) {|i| bits << i if set?(i)}\n bits\n end", "def boolean_to_binary(array)\nend", "def from_bits(bin_num)\n base10_value = 0\n @bit_vals.each_with_index do |val,i|\n base10_value += val if bin_num[i] == '1'\n end\n base10_value\n end", "def bitarray(n) \n b=Array::new \n i=0 \n v=n\n while v > 0\n b[i] = (0x1 & v)\n v = v/2\n i = i + 1\n end\n return b\n end", "def stringy(num, bit = 1)\n bin_arr = []\n num.times { |n| n.even? ? bin_arr << (0 + bit) : bin_arr << (1 - bit) }\n bin_arr.join\nend", "def bits\n\t\t# Get a safe copy of the @bits array\n\t\tbts = @bits.clone\n\t\t##\n\t\t# If carrying and not [HACK catch the pattern tha breaks it by adding an extrax 1]\n\t\t##\n\t\tif @carrying && @bits[0,4] != [1, 0, 0, 0]\n\t\t\tbts\t\t= [1].concat @bits\n\t\tend\n\t\t# Return to the caller\n\t\tbts\n\tend", "def translate_to_binary(array_of_hex)\n array_of_binary = []\n array_of_hex.each do |num|\n array_of_binary << sprintf(\"%b\", num).rjust(32, '0')\n end\n array_of_binary\n end", "def to_bits(base10_num)\n bits = @bit_vals.map do |b|\n if base10_num >= b\n base10_num -= b\n '1'\n else\n '0'\n end\n end\n bits.join\n end", "def binary_string_to_bit_array(string, minimum_binary_places = 0)\n number = binary_string_to_number(string)\n number_to_bit_array(number, minimum_binary_places)\n end", "def to_set_bit_position_array\n BitMapping.number_to_set_bit_positions_array(number)\n end", "def old_boolean_to_binary(arr)\n binary = \"\"\n\n arr.each do |boolean|\n if boolean\n binary += \"1\"\n else\n binary += \"0\"\n end\n end\n\n binary\nend", "def encode integer_array\n integer_array = integer_array.clone\n bits = BitArray.new\n integer_array.each do |x|\n q = x/@M\n q.times {bits.push 1}\n bits.push 0\n r = x % @M\n (@b-1).downto(0){|i| bits.push r[i]}\n end\n bits\n end", "def Bitwise(arr)\n output_num = ''\n arr[0].split(//).each_with_index {|char,idx| char == arr[1][idx] ? output_num << '0' : output_num << '1'}\n output_num.to_i\nend", "def to_bin(number)\n number = Integer(number);\n if(number == 0)\n return 0;\n end\n ret_bin = \"\";\n ## Untill val is zero, convert it into binary format\n while(number != 0)\n ret_bin = String(number % 2) + ret_bin;\n number = number / 2;\n end\n return ret_bin;\n end", "def encode_bits(bits)\n [bits.map { |b| b ? '1' : '0' }.join].pack('b*')\n end", "def pattern_bits\n str = bits.to_s(2)\n str = str.rjust(self.step_count, '0')\n str.chars.collect{|x|x=='1'}\n end", "def boolean_to_binary(arr)\r\n\r\n binary = \"\"\r\n\r\n # iteration each method\r\n arr.each {|bool|\r\n if bool == true\r\n\r\n # bool true to binary 1\r\n binary << \"1\"\r\n else\r\n\r\n # bool false to binary 0\r\n binary << \"0\"\r\n end }\r\n\r\n binary\r\nend", "def ALU1BIT(a,b,cin,binv,op1,op2) \n\tb = MUX2X1(b,binv)\n\tsUM_RESULT = ADDER(a,b,cin)\n\t#Send out an array pair of result, cout\n\treturn MUX4X1(AND(a,b),OR(a,b),sUM_RESULT[0],0,op1,op2), sUM_RESULT[1]\nend", "def shift_bits(buffer)\n buffer.slice!(0...1).unpack('b8').first.split('').map {|b| b == '1'}\n end", "def bits(number)\n bits = []\n\n while number != 0\n bits << number % 2\n number = number / 2\n end\n\n bits.reverse.join\nend", "def n_to_binary number\n bin_array = []\n until number == 0\n if number % 2 == 0\n bin_array << 0\n else \n bin_array << 1\n end\n number = number / 2\n end\n bin_array.join\nend", "def bits()\n return(NetAddr.mask_to_bits(@netmask))\n end", "def read_bit_array(num_bits)\n size = (num_bits + 7) / 8\n data = read_and_advance(size)\n bit_array = BinData::Array.new(type: :bit1, initial_length: size * 8)\n bit_array.read(data).to_ary\n end", "def number_to_set_bit_positions_array(number)\n assert_non_negative(number)\n array = []\n position = 0\n while number > 0\n array << position if number & 1 == 1\n position += 1\n number >>= 1\n end\n array\n end", "def bitmask(int)\n return int.to_s(2).reverse.split('')\n end", "def setup\n @a = '0b100010011010101111001101'\n end", "def boolean_to_binary(arr)\n result = ''\n i = 0\n while i < arr.length\n result << '1' if arr[i]\n result << '0' if !arr[i]\n i += 1\n end\n return result\nend" ]
[ "0.71019197", "0.64645636", "0.6271918", "0.6154316", "0.6136181", "0.61169845", "0.60882556", "0.6005125", "0.59984744", "0.5980631", "0.59593886", "0.5871188", "0.58386976", "0.5829", "0.58206475", "0.5820063", "0.5797414", "0.5794982", "0.57928", "0.56683254", "0.56529534", "0.56454474", "0.5636628", "0.56294316", "0.55915666", "0.5589879", "0.5566919", "0.55524087", "0.5536534", "0.55266786" ]
0.7963539
0
class_exsits?("String") => ture class_exists?("djfakf20dak") => false
def class_exists?(classname) str = classname.to_s eval("defined?(#{str}) && #{str}.is_a?(Class)") == true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def class_exists? string\n\tc = Object.const_get string\n\treturn c.is_a? Class\nrescue NameError\n\treturn false\nend", "def class_exists?(class_name)\n begin\n class_name.constantize\n true\n rescue NameError => ne\n false\n end\n end", "def class_exists?(class_name)\n klass = Module.const_get(class_name)\n return klass.is_a?(Class)\nrescue NameError\n return false\nend", "def class_exists?(class_name)\n eval(\"defined?(#{class_name}) && #{class_name}.is_a?(Class)\") == true\n end", "def has_class?(sym)\n `var str=' '+this.__native__.className+' ',match=' '+sym.__value__+' '`\n `str.indexOf(match) > -1`\n end", "def classible?\n %w[a b c d e].any? { |s| __send__(:\"class_#{s}?\") }\n end", "def class_exists?(class_name)\n eval(\"defined?(#{class_name}) && #{class_name}.is_a?(Class)\") == true\n end", "def class_exists?(class_name)\n eval(\"defined?(#{class_name}) && #{class_name}.is_a?(Class)\") == true\n end", "def class_exists?(class_name)\n eval(\"defined?(#{class_name}) && #{class_name}.is_a?(Class)\") == true\n end", "def class_exists?(class_name)\n klass = Object.const_get(class_name)\n return klass.is_a?(Class)\n rescue NameError\n return false\n end", "def has_class?(name)\n @class_syms ||= classes.map(&:to_sym)\n @class_syms.include?(name.to_sym)\n end", "def has_class?(c)\n find_all do |q|\n n=q.get_attribute(\"class\").split(\" \")\n n.index(c.to_s)\n end\n end", "def custom_class_present?(cls)\n custom_class.to_s.split.include?(cls)\n end", "def class_variable_defined?(arg0)\n end", "def class_variable_defined?(sym) end", "def select_by_class_exists(class_name)\n return select_by_class(class_name).exist?\nend", "def class_exist?(type, klass)\n !!(plugins_map(type) || {})[string2class(klass)]\n end", "def matches?(klass); end", "def isa? classname\n\t\t\tinit_classlist\n\t\t\[email protected]? classname\n\t\tend", "def findExactClassMatch(name)\n fname = name.tr(':', '_')\n return ClassIndex.classExists?(fname)\n end", "def can_get_class?(klass); true; end", "def has_any? klass\n not find_all(\"class\", klass).empty?\n end", "def system_class?(arg)\n return true ? arg == system_class : false\nend", "def is_strclass?(); @type == GRT_STRCLASS; end", "def string_class_name?(class_pair)\n class_pair.children[1].str_type?\n end", "def div_by_class_exists(class_name)\n return div_by_class(class_name).exist?\nend", "def has_classes?(klasses)\n klasses1 = klasses.kind_of?(Array) ? klasses : klasses.split\n klasses2 = classes.split\n for k in klasses1 do\n if not klasses2.find_index(k)\n return false\n end\n end\n return true\n end", "def class_line?(line)\n line.include?('class') && !line.include?('func') && !line.include?('//') && !line.include?('protocol') && !line.include?('\"')\n end", "def isClass _args\n \"isClass _args;\" \n end", "def has_class?(class_names)\n class_names.strip.downcase.split(' ').compact.any? { |other_class|\n get_classes.any? { |e| e == other_class }\n }\n end" ]
[ "0.8096085", "0.76872027", "0.7647681", "0.7635851", "0.75350523", "0.74830174", "0.7474969", "0.7474969", "0.7474969", "0.7412033", "0.73887044", "0.7370037", "0.72096604", "0.71148914", "0.7091627", "0.70484865", "0.7038288", "0.69804", "0.69743073", "0.6939178", "0.6915956", "0.68401116", "0.6836201", "0.68038714", "0.672197", "0.6647623", "0.6489544", "0.647736", "0.64763945", "0.6441544" ]
0.8161565
0
Returns info for the specified venue.
def venue(id) options = { :venue_id => id } get('/venue_info', options) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def venue(id)\n get(\"venues/#{id}\").venue\n end", "def venue(vid, options = {})\n options.merge!({ :query => { :key => @api_key } })\n self.class.get(\"/venues/#{vid}\", options)\n end", "def venue\n \t@events = Event.where(:venue => params[:venue])\n\n \trespond_to do |format|\n \t\tif @events.size>0\n \t\t\tformat.html { render json: {:message => \"Here are the details of #{@events.size} event(s) happening in #{params[:venue]}.\", :events => @events}}\n \t\telsif @events.size<=0\n \t\t\tformat.html { render json: {:message => \"Cannot find event - that venue does not exist. Please enter a valid venue.\"}}\n \t\tend\n \tend\n end", "def venue_name\n venue.name if venue\n end", "def show\r\n @venue = Venue.fetch(params[:id])\r\n render json: @venue\r\n end", "def show\n @venue = Venue.find(params[:id])\n\n render json: @venue\n end", "def venues(options = {})\n self.class.require_latitude_and_longitude(options)\n\n response = self.class.get(\"/venues.json\", :query => options, :basic_auth => @auth)[\"venues\"]\n response && response.flatten\n end", "def show\n @venue = Venue.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @venue }\n end\n end", "def show\n @venue = Venue.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @venue }\n end\n end", "def events_at_venue(venue)\n venue_events[venue.id]\n end", "def venue\n\t\"Town Hall\"\nend", "def venue_stats(id, options = {})\n get(\"venues/#{id}/stats\", options)\n end", "def show\n venue = Venue.find(params[:id])\n\n redirect_to_venue_index(venue)\n end", "def show\n @manage_venue = Venue.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @manage_venue }\n end\n end", "def venue_show\n client = Foursquare2::Client.new(:client_id => '45M1USHSGHPODOQWPSYJGAW50GBCMIHCKVQF410CKBCSO024', :client_secret => '4GO20RGY0BTI3VAQSS04P35AJ4A0DIZWF2JWLRPBFP0SDNQK',:api_version => '20140201')\n #@restroom = Restroom.find(params[:id])\n @venue = Venue.find_by_venue_id(params[:venue_id])\n @review = Review.new\n #@pics = client.venue_photos(params[:venue_id], options = {:group => 'venue'})\n @review.venue_id = @venue.id\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @restroom }\n end\n end", "def ig_venue\n Rails.cache.fetch cache_key('instagram:venue'), :compress => true do\n Instagram.location_search(nil, nil, :foursquare_v2_id => self.fs_venue_id).first\n end\n end", "def venue_events(id)\n get(\"venues/#{id}/events\").events\n end", "def show\n #@restroom = Restroom.find(params[:id])\n @venue = client.venue(:query => params[:venue_id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @restroom }\n end\n end", "def get_recommended_venues\n uri = \"https://api.foursquare.com/v2/venues/explore?near=#{@location}&client_id=#{CLIENT_ID}&client_secret=#{CLIENT_SECRET}&v=#{Time.now.strftime(\"%Y%m%d\")}&categoryId=4d4b7105d754a06374d81259\"\n encoded = URI.parse(URI.encode(uri)) # to handle spaces in the location\n @api_response = HTTParty.get(encoded)\n @api_response['response']['groups'][0][\"items\"].each do |item|\n @recommended_venues << item[\"venue\"][\"name\"]\n end\n # puts encoded # uncomment this to see the uri that is being used in the HTTP get request\n @recommended_venues\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @venue }\n end\n end", "def show\n @paper_venue = PaperVenue.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @paper_venue }\n end\n end", "def show\n @place = Venue.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @place }\n end\n end", "def show\n @venue_config = VenueConfig.get!(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @venue_config }\n end\n end", "def show\n @venue_product = VenueProduct.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @venue_product }\n end\n end", "def get_recommended_venues\n uri = \"https://api.foursquare.com/v2/venues/explore?near=#{@location}&client_id=#{CLIENT_ID}&client_secret=#{CLIENT_SECRET}&v=#{Time.now.strftime(\"%Y%m%d\")}&categoryId=4d4b7105d754a06374d81259&limit=10\"\n encoded = URI.parse(URI.encode(uri)) # to handle spaces in the location\n @api_response = HTTParty.get(encoded)\n @api_response['response']['groups'][0][\"items\"].each do |item|\n @recommended_venues << item[\"venue\"]\n end\n @recommended_venues\n # puts encoded # uncomment to see the uri that is being used in the HTTP get request\n end", "def show\n\n @venue = Venue.find(params[:id])\n @concerts = Concert.where(:venue_id=>@venue.id)\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @venue }\n end\n end", "def show\n @events = events_index(@venue.events)\n end", "def search(venue, options={})\n get(:standard, {:method => \"venue.search\", :venue => venue}.merge(options))\n end", "def show\n\n\n # respond_to do |format|\n # format.html # show.html.erb\n # format.json { render json: @venue }\n # end\n end", "def venue_events venue_id\n response = get(\"/venues/#{venue_id}/events\")[\"response\"]\n @events = response[\"events\"]\n @events[\"items\"].map!{|item| Foursquared::Response::Event.new(self, item)}\n @events\n end" ]
[ "0.7556617", "0.72925836", "0.71240777", "0.6950226", "0.69235957", "0.6780076", "0.6749551", "0.6677567", "0.66518515", "0.6548156", "0.64478546", "0.6389568", "0.63407123", "0.63203627", "0.63155055", "0.6270055", "0.62002933", "0.6194573", "0.616607", "0.61569226", "0.61444414", "0.61082983", "0.60768706", "0.60666513", "0.60255635", "0.60190034", "0.6014551", "0.5995302", "0.5993458", "0.59926015" ]
0.79124004
0
GET /communities/new GET /communities/new.json
def new @community = Community.new respond_to do |format| format.html # new.html.erb format.json { render json: @community } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @community = @district.communities.new\n\n respond_to do |format|\n format.html\n format.json { render json: @community }\n end\n end", "def create\n @community = @district.communities.new(params[:community])\n\n respond_to do |format|\n if @community.save\n format.html { redirect_to admin_district_communities_url, notice: 'Community was successfully created.' }\n format.json { render json: @community, status: :created, location: @community }\n else\n format.html { render action: \"new\" }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @community = Community.new(params[:community])\n\n respond_to do |format|\n if @community.save\n format.html { redirect_to @community, notice: 'Community was successfully created.' }\n format.json { render json: @community, status: :created, location: @community }\n else\n format.html { render action: \"new\" }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @community = Community.new\n respond_with(@community)\n end", "def new\n @community = Community.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @community }\n end\n end", "def create\n @community = Community.new(community_params)\n\n if @community.save\n render :show, status: :created, location: @community\n else\n render json: @community.errors, status: :unprocessable_entity\n end\n end", "def create\n @community = Community.new(community_params)\n\n respond_to do |format|\n if @community.save\n format.html { redirect_to @community, notice: 'Community was successfully created.' }\n format.json { render action: 'show', status: :created, location: @community }\n else\n format.html { render action: 'new' }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @community = Community.new(community_params)\n\n respond_to do |format|\n if @community.save\n format.html { redirect_to @community, notice: 'Community was successfully created.' }\n format.json { render :show, status: :created, location: @community }\n else\n format.html { render :new }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @community = Community.new(community_params)\n\n respond_to do |format|\n if @community.save\n format.html { redirect_to @community, notice: 'Community was successfully created.' }\n format.json { render :show, status: :created, location: @community }\n else\n format.html { render :new }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @new_comm = NewComm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_comm }\n end\n end", "def new\n\t@community= Community.new\nend", "def new\n @communication = Communication.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @communication }\n end\n end", "def create\n @community_community = Community::Community.new(community_community_params)\n\n respond_to do |format|\n if @community_community.save\n format.html { redirect_to @community_community, notice: 'Community was successfully created.' }\n format.json { render :show, status: :created, location: @community_community }\n else\n format.html { render :new }\n format.json { render json: @community_community.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t@community= Community.new(params[:community])\n\t if @community.save\n\trender ('create')\n else \n\trender ('new')\n end\nend", "def new\n @social_network = SocialNetwork.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @social_network }\n end\n end", "def new\n @colaboration = Colaboration.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @colaboration }\n end\n end", "def new\n @network = Network.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @network }\n end\n end", "def create\n @community = Community.new(community_params)\n #raise community_params.inspect\n respond_to do |format|\n if @community.save\n format.html { redirect_to @community, notice: 'Сообщество успешно создано' }\n format.json { render :show, status: :created, location: @community }\n else\n format.html { render :new }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @user = People.new\n @comunities = Comunity.find(:all, :order => :name)\n end", "def new\n @committees_voivodeship = CommitteesVoivodeship.new\n\t@committees = Committee.all.map do |commi|\n\t\t[commi.id]\n\tend\n\t@voivodeships = Voivodeship.all.map do |voi|\n\t\t[voi.id]\n\tend\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @committees_voivodeship }\n end\n end", "def new\n @internship = Internship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @internship }\n end\n end", "def new\n @internship = Internship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @internship }\n end\n end", "def new\n @community_topic = CommunityTopic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @community_topic }\n end\n end", "def new\n @protocol = Protocol.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @protocol }\n end\n end", "def create\n @membership = Membership.new(membership_params)\n\n respond_to do |format|\n if @membership.save\n format.html { redirect_to community_memberships_path(@community), notice: 'Community membership was successfully created.' }\n format.json { render :show, status: :created, location: @membership }\n else\n format.html { render :new }\n format.json { render json: @membership.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @community = Community.new(community_params)\n flash[:notice] = 'Community was successfully created.' if @community.save\n respond_with @community\n end", "def new\n @cities = City.order 'name'\n @college = College.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @college }\n end\n end", "def new\n @title = \"New Networks\"\n @network = Network.new\n @computers = Computer.find(:all)\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @network }\n end\n end", "def new\n @city = City.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @city }\n end\n end", "def new\n @membership = Membership.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @membership }\n end\n end" ]
[ "0.7959961", "0.71575254", "0.7025313", "0.7009266", "0.6981981", "0.695217", "0.6947142", "0.68749774", "0.68749774", "0.6841163", "0.6815259", "0.67953557", "0.6756949", "0.6732288", "0.6707693", "0.66622007", "0.6636089", "0.66074175", "0.6576715", "0.65577555", "0.65519", "0.65519", "0.64946127", "0.6492686", "0.64803386", "0.647797", "0.647308", "0.6465244", "0.6460512", "0.6452273" ]
0.7494975
1
PUT /communities/1 PUT /communities/1.json
def update @community = Community.find(params[:id]) respond_to do |format| if @community.update_attributes(params[:community]) format.html { redirect_to @community, notice: 'Community was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @community.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @community = current_user.own_communities.find(params[:id])\n flash[:notice] = 'Community was successfully updated.' if @community.update_attributes(update_params)\n respond_with(@community)\n end", "def update\n if @community.update(community_params)\n render :show, status: :ok, location: @community\n else\n render json: @community.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @community.update(params[:community].permit(:name, :about, :link, :rss, :tag_list, :category_list))\n format.html { redirect_to @community, notice: 'Community was successfully updated.' }\n format.json { render :show, status: :ok, location: @community }\n else\n format.html { render :edit }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @community = Community.find(params[:id])\n\n respond_to do |format|\n if @community.update_attributes(params[:community])\n format.html { redirect_to admin_district_communities_url, notice: 'Community was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @community.update(community_params)\n format.html { redirect_to community_url(@community), notice: 'Community was successfully updated.' }\n format.json { render :show, status: :ok, location: @community }\n else\n format.html { render :edit }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @community.update(community_params)\n format.html { redirect_to @community, notice: 'Community was successfully updated.' }\n format.json { render :show, status: :ok, location: @community }\n else\n format.html { render :edit }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @community.update(community_params)\n format.html { redirect_to @community, notice: 'Community was successfully updated.' }\n format.json { render :show, status: :ok, location: @community }\n else\n format.html { render :edit }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @community.update(community_params)\n format.html { redirect_to @community, notice: 'Community was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n flash[:notice] = 'Community was successfully updated.' if @community.update(community_params)\n respond_with @community\n end", "def update\n respond_to do |format|\n if @community.update(community_params)\n format.html { redirect_to @community, notice: 'Сообщество успешно обновлено' }\n format.json { render :show, status: :ok, location: @community }\n else\n format.html { render :edit }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @community.update(community_params)\n format.html { redirect_to community_home_url(:subdomain => @community.subdomain), notice: 'Community was successfully updated.' }\n format.json { render :show, status: :ok, location: @community }\n else\n format.html { render :edit }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def update\n @community = Community.where(street: params[:subscriber][:community]).first\n @subscriber.community = @community\n respond_to do |format|\n if @subscriber.update_attributes(:community => @community)\n format.html { redirect_to \"/subscribers/new?lon=#{params[:lon]}&lat=#{params[:lat]}\", notice: \"您当前绑定社区为: #{@community.street}.\" }\n format.json { render :show, status: :ok, location: @subscriber }\n else\n format.html { render :edit }\n format.json { render json: @subscriber.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def set_community\n @community = Community.find(params[:id])\n end", "def update\n @community = Community.find(params[:id])\n\n\n if @community.update_attributes(params[:community])\n flash[:notice] = 'Community was successfully updated.'\n redirect_to(@community)\n \n else\n render :action => \"edit\" \n end\n \n end", "def set_community\n @community = Community.where(id: params[:community_id]).first\n end", "def index\n @communities = Community.all\n render json: {items: @communities}\n end", "def set_community_community\n @community_community = Community::Community.find(params[:id])\n end", "def create\n @community = @district.communities.new(params[:community])\n\n respond_to do |format|\n if @community.save\n format.html { redirect_to admin_district_communities_url, notice: 'Community was successfully created.' }\n format.json { render json: @community, status: :created, location: @community }\n else\n format.html { render action: \"new\" }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def community_params\n params.require(:community).permit(:name, :owner_id, :description)\n end", "def create\n @community = Community.new(params[:community])\n\n respond_to do |format|\n if @community.save\n format.html { redirect_to @community, notice: 'Community was successfully created.' }\n format.json { render json: @community, status: :created, location: @community }\n else\n format.html { render action: \"new\" }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.70225936", "0.67517334", "0.67264223", "0.6724205", "0.6630993", "0.65974313", "0.65974313", "0.65297955", "0.6431997", "0.6372459", "0.6371188", "0.6314842", "0.6314842", "0.62161005", "0.6210379", "0.6209496", "0.6209496", "0.6209496", "0.6209496", "0.6209496", "0.6209496", "0.6209496", "0.6209496", "0.6131868", "0.6031552", "0.6000155", "0.5985095", "0.5981667", "0.594382", "0.5934644" ]
0.67545354
1
DELETE /communities/1 DELETE /communities/1.json
def destroy @community = Community.find(params[:id]) @community.destroy respond_to do |format| format.html { redirect_to communities_url } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @community = Community.find(params[:id])\n @community.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_district_communities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url, notice: 'Сообщество успешно удалено' }\n format.json { head :no_content }\n end\n end", "def destroy\n # @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url, notice: 'Community was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url, notice: 'Community was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url, notice: 'Community was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url, notice: 'Community was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url, notice: 'Community was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community = Community.find(params[:id])\n @community.destroy\n \n redirect_to(my_communities_url, :notice => 'Community was successfully deleted.')\n \n end", "def destroy\n @communication = Communication.find(params[:id])\n @communication.destroy\n\n respond_to do |format|\n format.html { redirect_to communications_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n end", "def destroy\n @community_community.destroy\n respond_to do |format|\n format.js\n format.json { head :no_content }\n end\n end", "def delete\n if @community.update_attributes(published: false)\n # Yeah, I really don't care if this fails. It's just convenience:\n @community.collection.update_attributes(published: false) rescue nil\n begin\n @community.remove_member(current_user)\n rescue EOL::Exceptions::ObjectNotFound => e\n flash[:error] = I18n.t(:could_not_find_user)\n end\n EOL::GlobalStatistics.decrement('communities')\n log_action(:delete)\n # TODO - it might make sense (?) to remove this community from any collection_items that once pointed to it...\n # that would remove it from watchlists and the like, though, and I don't know if that's wise (since then they\n # wouldn't see the delete log item).\n flash[:notice] = I18n.t(:community_destroyed)\n else\n flash[:error] = I18n.t(:community_not_destroyed_error)\n end\n redirect_to(community_newsfeed_path(@community), status: :moved_permanently)\n end", "def destroy\n @membership.destroy\n respond_to do |format|\n format.html { redirect_to @community, notice: 'Community membership was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community_service.destroy\n respond_to do |format|\n format.html { redirect_to community_services_url, notice: 'Community service was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n flash[:notice] = 'Community was successfully destroyed.'\n respond_with @community\n end", "def delete \n\t\t@community = Community.find(params[:id])\n\t\trescue ActiveRecord::RecordNotFound\n\tend", "def destroy\n @community_section.destroy\n respond_to do |format|\n format.html { redirect_to community_sections_url, notice: 'Community section was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @comunne.destroy\r\n respond_to do |format|\r\n format.html { redirect_to comunnes_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @colaboration = Colaboration.find(params[:id])\n @colaboration.destroy\n\n respond_to do |format|\n format.html { redirect_to colaborations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collaboration.destroy\n respond_to do |format|\n format.html { redirect_to collaborations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_networking.destroy\n\n render json: @social_networking, status: :ok\n end", "def destroy\n @internship = Internship.find(params[:id])\n @internship.destroy\n\n respond_to do |format|\n format.html { redirect_to internships_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @internship = Internship.find(params[:id])\n @internship.destroy\n\n respond_to do |format|\n format.html { redirect_to internships_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @internship = Internship.find(params[:id])\n @internship.destroy\n\n respond_to do |format|\n format.html { redirect_to internships_url }\n format.json { head :no_content }\n end\n end", "def destroy \n\t\tCommunity.find(params[:id]).destroy\n\t\trescue ActiveRecord::RecordNotFound\n\t\tredirect_to(:action => 'list')\n\n\tend", "def destroy\n @graphium_city.destroy\n respond_to do |format|\n format.html { redirect_to graphium_cities_url, notice: 'City was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @communicate.destroy\n respond_to do |format|\n format.html { redirect_to communicates_url, notice: 'Communicate was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community_post.destroy\n respond_to do |format|\n format.html { redirect_to community_posts_url, notice: 'Community post was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @internship = Internship.find(params[:id])\n @internship.destroy\n\n respond_to do |format|\n format.html { redirect_to(internships_url) }\n format.json { head :ok }\n end\n end" ]
[ "0.77494264", "0.7628726", "0.758887", "0.7582639", "0.75190085", "0.75190085", "0.75190085", "0.75190085", "0.7345361", "0.7032567", "0.6991609", "0.6987676", "0.6948728", "0.69379205", "0.69283324", "0.6902466", "0.6833026", "0.68261915", "0.6721534", "0.67208093", "0.66859394", "0.6685231", "0.66849786", "0.66849786", "0.66849786", "0.6680042", "0.66653764", "0.66237456", "0.66183996", "0.6611705" ]
0.77372575
1
Load appium.txt (toml format) into system ENV the basedir of this file + appium.txt is what's used
def load_appium_txt opts raise 'opts must be a hash' unless opts.kind_of? Hash opts.each_pair { |k,v| opts[k.to_s.downcase.strip.intern] = v } opts = {} if opts.nil? file = opts.fetch :file, nil raise 'Must pass file' unless file verbose = opts.fetch :verbose, false # Check for env vars in .txt parent_dir = File.dirname file toml = File.expand_path File.join parent_dir, 'appium.txt' puts "appium.txt path: #{toml}" if verbose # @private def update data, *args args.each do |name| var = data[name] ENV[name] = var if var end end toml_exists = File.exists? toml puts "Exists? #{toml_exists}" if verbose data = nil if toml_exists require 'toml' puts "Loading #{toml}" if verbose # bash requires A="OK" # toml requires A = "OK" # # A="OK" => A = "OK" data = File.read toml data = data.split("\n").map do |line| line.sub /([^\s])\=/, "\\1 = " end.join "\n" data = TOML::Parser.new(data).parsed ap data unless data.empty? if verbose update data, 'APP_PATH', 'APP_APK', 'APP_PACKAGE', 'APP_ACTIVITY', 'APP_WAIT_ACTIVITY', 'DEVICE' # ensure app path is resolved correctly from the context of the .txt file ENV['APP_PATH'] = Appium::Driver.absolute_app_path ENV['APP_PATH'] end # return list of require files as an array # nil if require doesn't exist if data && data['require'] r = data['require'] r = r.kind_of?(Array) ? r : [ r ] # ensure files are absolute r.map! do |file| file = file.include?(File::Separator) ? file : File.join(parent_dir, file) file = File.expand_path file File.exists?(file) ? file : nil end r.compact! # remove nils files = [] # now expand dirs r.each do |item| unless File.directory? item # save file files << item next # only look inside folders end Dir.glob(File.join(item, '**/*.rb')) do |file| # do not add folders to the file list files << File.expand_path(file) unless File.directory? file end end files end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setup_driver\n return if $driver\n caps = Appium.load_appium_txt file: File.join(Dir.pwd, 'appium.txt')\n $driver = Appium::Driver.new caps\n # debug \"setting up driver using #{caps.to_yaml}\"\nend", "def root_dir\n __FILE__.match(%r{.*(appium-test-runner)}).to_s\n end", "def run_android test_file=nil\n wait_for_valid_device\n cmd = 'bundle exec ruby ./appium/run.rb android'\n cmd += %Q( \"#{ test_file }\") if test_file\n bash cmd\nend", "def import_env_file(path)\n return unless File.file?(path)\n File.readlines(path).each do |line|\n next if line.start_with?('#') || line.strip.empty?\n line_to_env(line)\n end\nend", "def app_config_file(filename)\n File.read(File.dirname(__FILE__)+\"/../../app/config/\" + filename).split(\"\\n\")\nend", "def config_file\n File.join(install_directory,'installer','rails_installer.yml')\n end", "def file_text\n text = \"[caps]\\n\"\n text << \"platformName = \\\"#{platform_name}\\\"\\n\"\n text << \"deviceName = \\\"#{device_name}\\\"\\n\"\n text << \"platformVersion = \\\"#{platform_version}\\\"\\n\" unless platform_version.nil?\n text << \"app = \\\"#{app}\\\"\\n\"\n text << \"newCommandTimeout = #{new_command_timeout}\\n\"\n text << \"udid = \\\"#{udid}\\\"\\n\" unless udid.nil?\n Logger.debug \"appium.text == #{text}\"\n text\n end", "def load_monkfile\n file = find_in_project(\"Monkfile\")\n\n if file\n load file\n @project = File.dirname(file)\n Dir.chdir @project\n end\n end", "def config_file\n File.expand_path('../hubble/config.yml', __FILE__)\n end", "def config_file\n File.join(@path, %w[ application config application.php ])\n end", "def config_file\n FilePath.new(@directory, 'tc-config.xml')\n end", "def env_file\n dir['env.rb']\n end", "def setup_app_files\n cp HANAMI_TEMPLATES.join('config/hanami-vite.json'), config.config_path\n inject_line_after root.join('config/environment.rb'), 'environment :development do', ' middleware.use(ViteRuby::DevServerProxy, ssl_verify_none: true) if ViteRuby.run_proxy?'\n inject_line_after_last root.join('apps/web/application.rb'), 'include Web::Assets::Helpers', ' include ViteHanami::TagHelpers'\n inject_line_after root.join('apps/web/application.rb'), 'configure :development do', <<-CSP\n # Allow @vite/client to hot reload changes in development\n security.content_security_policy(\n security.content_security_policy\n .sub('script-src', \"script-src 'unsafe-eval'\")\n .sub('connect-src', \"connect-src ws://\\#{ ViteRuby.config.host_with_port }\")\n )\n CSP\n append root.join('Rakefile'), <<~RAKE\n require 'vite_hanami'\n ViteRuby.install_tasks\n RAKE\n end", "def load_launcher_data launcher_data_file=\"bin/LAUNCHER_TYPE\"\n launcher_data = nil\n\n begin\n File.open launcher_data_file do |f|\n launcher_data = YAML.load(f.read)\n end\n rescue Errno::ENOENT\n end\n\n return launcher_data\nend", "def loadIOSConfigFile(org_id)\n file = \"generic.yaml\" # points to bFAN Sports config\n path = \"./fastlane/\"\n\n if File.exist?(\"FastlaneEnv\")\n path = \"\"\n end\n\n # Is there is a config for the target ?\n if File.file?(\"#{path}./FastlaneEnv/#{org_id}.yaml\")\n file = \"#{org_id}.yaml\"\n end\n\n conf = YAML.safe_load(File.read(\"#{path}./FastlaneEnv/#{file}\"))\n\n UI.important(\"Config used: fastlane/FastlaneEnv/#{file}\")\n\n return conf\nend", "def configure_data\n [:bitcask, :eleveldb, :merge_index].each {|k| env[k] ||= {} }\n env[:bitcask][:data_root] ||= (data + 'bitcask').expand_path.to_s\n env[:eleveldb][:data_root] ||= (data + 'leveldb').expand_path.to_s\n env[:merge_index][:data_root] ||= (data + 'merge_index').expand_path.to_s\n env[:riak_core][:slide_private_dir] ||= (data + 'slide-data').expand_path.to_s\n env[:riak_core][:ring_state_dir] ||= (data + 'ring').expand_path.to_s\n\n TS_NODE_DIRECTORIES.each do |dir|\n env[:riak_core][:\"platform_#{dir}_dir\"] ||= send(dir).to_s\n end\n end", "def config_file\n File.join AppRoot, ConfigFile\n end", "def app_file_path\n File.join(tmp_dir, \"example_app_#{$example_app_counter}.rb\")\n end", "def load_environment_file(name, fail_on_missing = false)\n unless File.exists?(name)\n abort(\"Unable to read environment: #{name}\") if fail_on_missing\n return nil\n end\n\n load_env = EC2Launcher::DSL::Environment.new\n load_env.load(File.read(name))\n load_env\n end", "def intent_fixture_file_path(intent_name)\n File.join(intents_fixture_dir, \"#{intent_name}.txt\")\nend", "def setup_autoinst(autoinst)\n raise \"ERROR: #{autoinst} not found\" unless autoinst.file?\n content = File.read(autoinst)\n autoinst_vars(autoinst.sub_ext(\".vars\")).each { |k, v| content.gsub!(\"{{#{k}}}\", v) }\n content.gsub!(\"/dev/vd\", \"/dev/sd\") if provider == :virtualbox\n File.open(autoinst_path, \"w\") { |f| f.puts content }\n end", "def app\n @app ||= Rack::Builder.parse_file(File.join(OpenRecipeApp.root,\"config.ru\"))[0]\n end", "def default_app_variables_path\n Hanami.root.join(\"apps\", Concierge.app.to_s, \"config\", \"environment_variables.yml\").to_s\n end", "def initialize(app_file)\n @config_file = File.expand_path(File.join(File.dirname(app_file), \"../app.yml\"))\n if !File.exist? @config_file\n @shoes.alert(\"Unable to locate configuration file.\\nFile '#{@config_file}' not found.\")\n @shoes.exit\n end\n\n @config = YAML.load(File.new(@config_file))\n setup\n run\n end", "def config_filepath(name)\n File.expand_path(\"../fixtures/configs/#{name}.yaml\", __dir__)\nend", "def root_dir\n ManageIQ::Providers::Lenovo::Engine.root.join(\"content/ansible_runner\")\n end", "def add_file file\n @config.merge!(YAML::load_file \"#{@@env_dir}/#{file}\")\n end", "def roby_app_fixture_path\n File.expand_path(\n File.join(\"..\", \"..\", \"..\", \"test\", \"app\", \"fixtures\"),\n __dir__\n )\n end", "def load_env_from_file(path)\n File.readlines(path).each do |line|\n values = line.split(\"=\")\n key = values[0]\n value = values[1, values.length - 1 ].map {|v| v.strip() }.join('=')\n ENV[key] = value\n end\n end", "def app_template_fixture(name)\n File.expand_path(\"fixtures/#{name}\",File.dirname(__FILE__))\n end" ]
[ "0.5981987", "0.5774271", "0.56039727", "0.55971855", "0.55521613", "0.54813564", "0.543904", "0.541871", "0.54058915", "0.5370258", "0.5336662", "0.5312171", "0.5307017", "0.5273903", "0.527349", "0.5264785", "0.5259214", "0.5235099", "0.5223799", "0.52233565", "0.519876", "0.5196877", "0.51611173", "0.51579475", "0.515366", "0.51453936", "0.5136753", "0.51355577", "0.51109993", "0.5110647" ]
0.81331265
0
Get the server url for sauce or local based on env vars.
def server_url return @custom_url if @custom_url if !@sauce_username.nil? && !@sauce_access_key.nil? "http://#{@sauce_username}:#{@sauce_access_key}@ondemand.saucelabs.com:80/wd/hub" else "http://127.0.0.1:#{@port}/wd/hub" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def site_url\n if Rails.env.production?\n # Place your production URL in the quotes below\n \"http://www.ezonline.com/\"\n else\n # Our dev & test URL\n \"http://ezonline-dev.com:3000\"\n end\n end", "def host\n return @@nfg_urls['sandbox']['host'] if @use_sandbox\n @@nfg_urls['production']['host']\n end", "def server_url\n \"#{ROCCI_SERVER_CONFIG.common.protocol || 'http'}://\" \\\n \"#{ROCCI_SERVER_CONFIG.common.hostname || 'localhost'}:\" \\\n \"#{ROCCI_SERVER_CONFIG.common.port.to_s || '3000'}\"\n end", "def casein_config_hostname\n if ENV['RAILS_ENV'] == 'production'\n 'http://www.caseincms.com'\n else\n 'http://localhost:3000'\n end\n end", "def url\n options[:test] ? options[:test_url] : options[:production_url]\n end", "def url\n options[:test] ? options[:test_url] : options[:production_url]\n end", "def server_url\n \"http://#{server_host}:#{server_port}\"\n end", "def baseURL\n Rails.env.development? ? GeventAnalysis::Application::CONSTS[:dev_host] : GeventAnalysis::Application::CONSTS[:app_host]\n end", "def app_url\n ENV['APP_URL']\nend", "def url\n return @@nfg_urls['sandbox']['url'] if @use_sandbox\n @@nfg_urls['production']['url']\n end", "def server_url\n url\n end", "def casein_config_hostname\n if ENV['RAILS_ENV'] == 'production'\n 'http://www.caseincms.com'\n else\n 'http://0.0.0.0:3000'\n end\n end", "def site_url\n if development_environment?\n request.protocol + request.host + ':' + request.port.to_s\n else\n request.protocol + 'rehttp.me'\n end\n end", "def url\n env[:url]\n end", "def base_url\n if ENV['BASE_URL']\n ENV['BASE_URL']\n else\n 'https://beam.pro/'\n end\n end", "def server_url\n params[:server_url] || session[:server_url]\n end", "def server_url\n @uri\n end", "def ci_base_url\n # Assume we're in dev if we don't have this url\n return ENV[\"FASTLANE_CI_BASE_URL\"] || \"http://localhost:8080\"\n end", "def prod_server\n PROD_SERVER\n end", "def get_ordercup_path\n if Rails.env.production?\n @ordercup_path = \"https://ship.ordercup.com/connect-to-ordercup\"\n elsif Rails.env.staging?\n @ordercup_path = \"https://ship.ordercup4.com/connect-to-ordercup\"\n else\n @ordercup_path = \"http://localhost:3000/connect-to-ordercup\"\n end \n end", "def get_url(is_local = true)\n is_local ? (return '../../../www/public/') : (return 'https://whimsy.apache.org/public/')\n end", "def auth_server(environment)\n auth_server_url = ENV['ADSAPI_AUTH_URL']\n if auth_server_url.nil?\n environment = environment.upcase.to_sym\n auth_server_url = auth_server_config[environment]\n end\n if auth_server_url.nil?\n # If we don't have an entry for this environment, we just return the\n # default server (the same one being used for the default environment)\n auth_server_url = auth_server_config[default_environment()]\n end\n return auth_server_url\n end", "def default_url_prefix\n case @environment\n when \"development\" then \"https://#{domain}.dev.montagehot.club\"\n when \"production\" then \"https://#{domain}.mntge.com\"\n when \"test\" then @test_url\n end\n end", "def webserver_url\n \"http://#{webserver_host}:#{webserver_port}\"\n end", "def url\n return @url if @url\n\n case environment\n when :production\n PRODUCTION_API_ENDPOINT\n when :sandbox\n SANDBOX_API_ENDPOINT\n end\n end", "def myservices_environment_details_host\n ENV['ENV_DETAILS'].nil? ? 'esu2v871:9080' : ENV['ENV_DETAILS']\n end", "def getserverurl\r\n return getvalue(@@SERVER_URL)\r\n end", "def sslhost\n if ENV['RAILS_ENV'] == 'production'\n \"https://m41.herokuapp.com\"\n else\n \"\"\n end\n end", "def url\n raise \"The 'URL' environment variable was not specified on the cucumber command line.\" if ENV['URL'].nil?\n ENV['URL']\n end", "def repo_url\n ENV[\"FASTLANE_CI_REPO_URL\"]\n end" ]
[ "0.7494612", "0.7353119", "0.7247557", "0.71140593", "0.7103848", "0.7103848", "0.7079462", "0.7078015", "0.70766836", "0.7011295", "0.70039564", "0.69781536", "0.6976606", "0.6950521", "0.6943098", "0.6860118", "0.68076366", "0.6805368", "0.6766746", "0.6763752", "0.67558944", "0.67557734", "0.67414767", "0.67252356", "0.6686264", "0.6675498", "0.66525966", "0.66518605", "0.6644073", "0.6640798" ]
0.7927469
0
Takes a png screenshot and saves to the target path. Example: screenshot '/tmp/hi.png'
def screenshot png_save_path @driver.save_screenshot png_save_path nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_screenshot(png_path)\n extension = File.extname(png_path).downcase\n if extension != '.png'\n ::Appium::Logger.warn 'name used for saved screenshot does not match file type. ' \\\n 'It should end with .png extension'\n end\n File.open(png_path, 'wb') { |f| f << screenshot_as(:png) }\n end", "def screenshot(driver,sess_time,shot_num,descr)\n filename = \"shot-#{shot_num}-#{driver.current_url.sub(\"http://\",\"\").sub(\"admin:123@\",\"\").gsub(\"/\",\"-\")}-(#{descr})-#{sess_time}.png\"\n # driver.save_screenshot (\"shot-#{shot_num}-#{driver.current_url.sub(\"https://format-staging.com/\",\"\").gsub(\"/\",\"-\")}-(#{descr})-#{sess_time}.png\")\n driver.save_screenshot(filename)\n # puts (\" 📸 Shot #{shot_num} (#{driver.current_url})\")\n puts (\" 📸 #{filename}\")\n return 1\nend", "def save_screenshot\n browser.screenshot.save(\"#{report_dir}/shot#{timestamp}.png\")\n end", "def save_shot(screenshot)\n\t\[email protected](screenshot)\n\tend", "def save_screenshot(filename)\n file = File.join(\n @screen_dir,\n sanitize(filename.end_with?('.png') ? filename : \"#{filename}.png\")\n )\n\n dir = File.dirname(file)\n\n mkdir(dir) unless Dir.exist?(dir)\n\n driver.save_screenshot(file)\n end", "def save_screenshot\n @suite.p \"-- CAPTURE SCREENSHOT ::\"\n begin\n screenshot_flag = true\n filename = (ENV['REPORTS_DIR'] + \"/\" + self.class.name + '.png')\n @suite.capture_screenshot(filename)\n @suite.p \"-- SCREENSHOT CAPTURED TO: {#{filename}}\"\n screenshot_flag = false\n rescue => e\n if screenshot_flag\n @suite.p \"FAILED TO CAPTURE SCREENSHOT: \"\n @suite.p e.inspect\n @suite.p e.backtrace\n end\n end\n end", "def take_screenshot(_scenario)\n screenshot_dir = \"#{FigNewton.screenshot_directory}/#{$date_and_time}\"\n FileUtils.mkdir screenshot_dir unless File.directory? screenshot_dir\n encoded_img = @browser.driver.screenshot_as(:base64)\n embed(\"data:image/png;base64,#{encoded_img}\", 'image/png')\nend", "def screenshot(filename)\n platform.screenshot(filename)\n end", "def save_screenshot(path, options = {})\n appium_driver.screenshot path if @appium_driver\n end", "def screenshoot(url, filename)\n unless File.exists?(\"#{IMG_DIR}/#{filename}.png\")\n system \"python webkit2png.py -t #{IMG_TIMEOUT} -o #{IMG_DIR}/#{filename}.png #{url} \"\n else \n puts \"Already screenshoted: #{IMG_DIR}/#{filename}.png\"\n end\nend", "def saos\n save_and_open_screenshot\n end", "def save_screenshot(path, options = {})\n browser.screenshot path\n end", "def make_screenshot\n Logbook.step('Taking a screenshot of a result page')\n @browser.save_screenshot(\"screenshots/screenshot - #{Time.now.strftime('%Y-%m-%d %H-%M-%S')}.png\")\n end", "def screenshot _value\n send_cmd(\"screenshot #{_value}\")\n end", "def add_screenshot(scenario)\n nome = scenario.name.tr(' ', '_').downcase!\n captura = page.save_screenshot(\"log/screenshots/#{nome}.png\")\n attach(captura, 'image/png')\nend", "def save_screenshot(file_name)\n source_image = File.basename(file_name)\n source_image.slice!(/\\.attempt_\\d+/)\n source_image.slice!(/^\\d\\d_/)\n\n FileUtils.cp(File.expand_path(source_image, TEST_IMAGES_DIR), file_name)\n end", "def store_screenshot(path)\n screenshot = screenshots.first\n if (screenshot)\n begin \n variant = screenshot.variant(resize_to_limit: [425, nil], resize_to_fill: [425, 250, { crop: :low }]).processed\n path = variant.blob.service.send(:path_for, variant.key)\n FileUtils.cp(path, \"/Users/jan.prill/Documents/workspace/msp/inviadorepo/web/js/gridsome/inviado/src/assets/images/inviado/#{id}.png\")\n rescue\n p \"There is a problem on #{variant}\"\n end\n end\n end", "def screenshot(filename=nil)\n fn = filename || @ticket || SecureRandom.uuid.to_s\n f = \"screenshots/#{fn}.png\"\n @session.save_screenshot(f)\n puts \"Saved #{f}:\"\n return f\n end", "def save_screenshot(scenario)\n path = SCREENSHOTS_DIR\n\n # prepare dir\n FileUtils.mkdir(path) unless File.directory?(path)\n\n # prepare scenario name\n if scenario.instance_of?(Cucumber::Ast::OutlineTable::ExampleRow)\n scenario_name = scenario.scenario_outline.name.gsub(/[^\\w\\-]/, ' ')\n scenario_name << \"-Example#{scenario.name.gsub(/\\s*\\|\\s*/, '-')}\".chop\n else\n scenario_name = scenario.name.gsub(/[^\\w\\-]/, ' ')\n end\n\n # prepare filename\n filename = \"#{path}/#{scenario_name}.png\"\n\n # save screenshot\n Testing.browser.driver.save_screenshot(filename)\n\n # embed into HTML output\n embed(filename, 'image/png')\n end", "def saveScreenShot(filepath)\n @browser.screenshot.save(filepath)\n end", "def save(path)\n @driver.save_screenshot(path)\n end", "def screenshot path = '~/Desktop'\n capture_screen self, path\n end", "def screenshot\n @browser.save_screenshot(\"screenshot.png\")\n end", "def take_screenshot(scenario)\r\n scenario_name = \"#{scenario.name}_step\"\r\n sshot_name = \"log/screens/\" + scenario_name +\".png\"\r\n @browser.screenshot.save(sshot_name) rescue nil\r\n embed(sshot_name, 'image/png') rescue nil\r\nend", "def png\n @driver.screenshot_as(:png)\n end", "def screen_capture(fileName)\n return $marathon.saveScreenShot(fileName)\nend", "def screen_capture(fileName)\n return $marathon.saveScreenShot(fileName)\nend", "def take_screenshot(scenario)\r\n screen_name = \"log/screens/\" +scenario.name+\".png\"\r\n page.save_screenshot(screen_name) rescue nil\r\n embed(screen_name, 'image/png') rescue nil\r\nend", "def save_image(class_name, test_case_method_name)\r\n if (WatirBrowser.ie?)\r\n #see if CC_BUILD_ARTIFACTS is set, used by cruise control server\r\n build_artifacts_folder = ENV['CC_BUILD_ARTIFACTS']\r\n if (not build_artifacts_folder.nil?)\r\n build_artifacts_folder = build_artifacts_folder.gsub(\"/\", \"\\\\\")\r\n end\r\n #if not set, see if TORNADO_TEST_IMAGE is set\r\n #developer can set this if they want to capture the images on their own machine\r\n if (build_artifacts_folder.nil?)\r\n build_artifacts_folder = ENV['TORNADO_TEST_IMAGE']\r\n end\r\n \r\n# build_artifacts_folder = \"c:\\\\railsproject\"\r\n unless (build_artifacts_folder.nil?)\r\n\r\n file_name = build_artifacts_folder+ \"\\\\\" + class_name + \"-\" + test_case_method_name.to_s + \".png\"\r\n \r\n if (File.exists?(file_name)) \r\n FileUtils.rm(file_name)\r\n end\r\n \r\n begin\r\n\r\n width, height, bitmap = Win32::Screenshot.desktop\r\n img = Magick::Image.from_blob(bitmap)[0]\r\n img.write(file_name)\r\n rescue Magick::ImageMagickError => e\r\n puts(\"cannot capture screen. Exception is \" + e.message)\r\n end\r\n \r\n # @screen_capture = Watir::ScreenCapture\r\n # @screen_capture.screen_capture(file_name, false, false) \r\n end\r\n end\r\n end", "def take_screenshot(to_file = nil, opts = {})\r\n # puts \"calling new take screenshot: #{$screenshot_supported}\"\r\n # unless $screenshot_supported\r\n # puts \" [WARN] Screenhost not supported, check whether win32screenshot gem is installed\" \r\n # return\r\n # end\r\n\r\n if to_file\r\n screenshot_image_filepath = to_file\r\n else\r\n screenshot_image_filename = \"screenshot_\" + Time.now.strftime(\"%m%d%H%M%S\") + \".jpg\"\r\n the_dump_dir = opts[:to_dir] || default_dump_dir\r\n FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir)\r\n screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename)\r\n screenshot_image_filepath.gsub!(\"/\", \"\\\\\") if is_windows?\r\n\r\n FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath)\r\n end\r\n\r\n begin \r\n if is_firefox? then\r\n Win32::Screenshot::Take.of(:window, :title => /mozilla\\sfirefox/i).write(screenshot_image_filepath)\t\t\t\t\t\r\n\t\t elsif ie\r\n Win32::Screenshot::Take.of(:window, :title => /internet\\sexplorer/i).write(screenshot_image_filepath)\t\t\t\t\t\r\n else\r\n Win32::Screenshot::Take.of(:foreground).write(screenshot_image_filepath)\r\n end\r\n notify_screenshot_location(screenshot_image_filepath)\r\n\t\t\t\trescue ::DL::DLTypeError => de\r\n\t\t\t\t\tputs \"No screenshot libray found: #{de}\"\r\n rescue => e\r\n puts \"error on taking screenshot: #{e}\"\r\n end\r\n \r\n\r\n end" ]
[ "0.7713248", "0.73897016", "0.7361552", "0.7261436", "0.72201663", "0.71657145", "0.71561575", "0.7147954", "0.7093388", "0.7071087", "0.7060184", "0.7058387", "0.70374185", "0.70342076", "0.7021363", "0.69934297", "0.69775933", "0.69728357", "0.6949938", "0.69415283", "0.6916968", "0.68982786", "0.68832767", "0.68749493", "0.6871197", "0.68632275", "0.6847745", "0.68095076", "0.6807864", "0.6768278" ]
0.8234669
0
Set implicit wait and default_wait to zero.
def no_wait @last_waits = [@default_wait, 0] @default_wait = 0 @driver.manage.timeouts.implicit_wait = 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def default_wait\n @default_wait\n end", "def set_implicit_wait_by_default(wait)\n return if @default_wait.nil?\n\n @driver.manage.timeouts.implicit_wait = wait\n rescue ::Selenium::WebDriver::Error::UnknownError => e\n unless e.message.include?('The operation requested is not yet implemented')\n raise ::Appium::Core::Error::ServerError, e.message\n end\n\n ::Appium::Logger.debug(e.message)\n {}\n end", "def set_wait timeout=nil\n if timeout.nil?\n # puts \"timeout = @default_wait = @last_wait\"\n # puts \"timeout = @default_wait = #{@last_waits}\"\n timeout = @default_wait = @last_waits.first\n else\n @default_wait = timeout\n # puts \"last waits before: #{@last_waits}\"\n @last_waits = [@last_waits.last, @default_wait]\n # puts \"last waits after: #{@last_waits}\"\n end\n\n @driver.manage.timeouts.implicit_wait = timeout\n end", "def implicit_wait=(seconds); end", "def implicit_wait; end", "def wait\n sleep 0.0001\n end", "def wait\n 0\n end", "def wait\n sleep WAIT_TIME unless @skip_wait\n end", "def reset_wait\n @wait = @t + rand(@t_rand)\n end", "def wait_timeout\n @wait_timeout ||= options[:wait_timeout] || DEFAULT_WAIT_TIMEOUT\n end", "def abs_wait_short\n wait(15)\n end", "def wait!\n sleep(@sleep)\n end", "def wait(arg0)\n end", "def skip_wait\n @skip_wait = true\n end", "def wait\n @running.reset\n @waiting.set\n @running.wait\n end", "def skip_wait=(setting)\n @skip_wait = setting\n end", "def wait(what = T.unsafe(nil)); end", "def wait; end", "def wait; end", "def wait; end", "def sleep_for\n @sleep_for ||= 5\n end", "def wait(seconds)\n @waiting = seconds * 1000\n end", "def no_wait_poll\n remove if can_remove_no_wait?\n end", "def set_max_wait_time\n q = 'Set the MAX WAIT TIME after executing the RESTART command ' \\\n '(>= 180 secs): '\n until @max_wait && @max_wait.to_i > 179\n @max_wait = Utils.qna(q.cyan, true)\n end\n end", "def wait\n true\n end", "def no_wait_poll\n remove if can_remove_no_wait?\n end", "def no_wait_poll\n remove if can_remove_no_wait?\n end", "def wait\n @wait.synchronize do\n sleep 1 while @count >= THREAD_MAX\n @count += 1\n end\n end", "def reset_wait_time_span\n @iteration = 0\n true\n end", "def wait\n\tend" ]
[ "0.76416105", "0.7500537", "0.721602", "0.65911514", "0.65868926", "0.6399924", "0.6341235", "0.63308007", "0.6221979", "0.6141044", "0.60687554", "0.60397017", "0.60141146", "0.5988994", "0.5857542", "0.5737748", "0.5725504", "0.5707285", "0.5707285", "0.5707285", "0.56800336", "0.56691337", "0.56596994", "0.5610205", "0.5606721", "0.5588754", "0.5588045", "0.55802375", "0.5572142", "0.5542457" ]
0.7951602
0
Set implicit wait and default_wait to timeout, defaults to 30. if set_wait is called without a param then the second to last wait will be used. ```ruby` set_wait 2 set_wait 3 set_wait 2 ````
def set_wait timeout=nil if timeout.nil? # puts "timeout = @default_wait = @last_wait" # puts "timeout = @default_wait = #{@last_waits}" timeout = @default_wait = @last_waits.first else @default_wait = timeout # puts "last waits before: #{@last_waits}" @last_waits = [@last_waits.last, @default_wait] # puts "last waits after: #{@last_waits}" end @driver.manage.timeouts.implicit_wait = timeout end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_implicit_wait_by_default(wait)\n return if @default_wait.nil?\n\n @driver.manage.timeouts.implicit_wait = wait\n rescue ::Selenium::WebDriver::Error::UnknownError => e\n unless e.message.include?('The operation requested is not yet implemented')\n raise ::Appium::Core::Error::ServerError, e.message\n end\n\n ::Appium::Logger.debug(e.message)\n {}\n end", "def default_wait\n @default_wait\n end", "def wait_timeout\n @wait_timeout ||= options[:wait_timeout] || DEFAULT_WAIT_TIMEOUT\n end", "def implicit_wait=(seconds); end", "def set_max_wait_time\n q = 'Set the MAX WAIT TIME after executing the RESTART command ' \\\n '(>= 180 secs): '\n until @max_wait && @max_wait.to_i > 179\n @max_wait = Utils.qna(q.cyan, true)\n end\n end", "def wait timeout: 3, &block\n wait = Selenium::WebDriver::Wait.new timeout: timeout\n wait.until(&block)\nend", "def state_wait(set, state, timeout=1200)\n # do a special wait, if waiting for operational (for dns)\n if state == \"operational\"\n set.each { |server| obj_behavior(server, :wait_for_operational_with_dns, timeout) }\n else\n set.each { |server| obj_behavior(server, :wait_for_state, state, timeout) }\n end\n end", "def wait_for(wait_max: 3, step: 0.001, &block)\n stop_at = wait_max.seconds.from_now\n\n sleep step while !block.call && (@time = Time.now) < stop_at\n\n fail \"Timeout of #{wait_max} seconds exceeded!\" unless @time < stop_at\nend", "def no_wait\n @last_waits = [@default_wait, 0]\n @default_wait = 0\n @driver.manage.timeouts.implicit_wait = 0\n end", "def wait(timeout=10)\n Selenium::WebDriver::Wait.new(:timeout => timeout)\n end", "def set_wait_time\n @wait_time = WaitTime.find(params[:id])\n end", "def set_wait_time\n @wait_time = WaitTime.find(params[:id])\n end", "def do_wait(waited)\n wait = get_config(:docker_wait)\n return unless wait.is_a?(Integer) || wait.is_a?(Float)\n return if waited >= wait\n sleep(wait - waited)\n end", "def set_timeout(timeout)\n @log.info('Setting the selenium timeout to: ' + timeout.to_s)\n @driver.manage.timeouts.implicit_wait = timeout\n end", "def abs_wait_short\n wait(15)\n end", "def wait(seconds)\n @waiting = seconds * 1000\n end", "def wait\n sleep WAIT_TIME unless @skip_wait\n end", "def wait(seconds) \r\n\t\texec(\"Wait\", seconds.to_s)\r\n\tend", "def reset_wait\n @wait = @t + rand(@t_rand)\n end", "def wait\n sleep 0.0001\n end", "def pause wait_time\r\n command 'pause', wait_time\r\n end", "def wait!\n sleep(@sleep)\n end", "def brute_wait(delay)\n sleep(delay)\n end", "def set_timeout(timeout, element_timeout)\n @log.info('Setting the selenium timeout to: ' + timeout.to_s + ' element timeout: '+element_timeout.to_s)\n @driver.manage.timeouts.implicit_wait = timeout\n Capybara.default_wait_time = element_timeout\n end", "def set_wait_flags(*flags)\n a = (flags.include?(:a) || flags.include?(:a)) ? '1' : 'X'\n b = (flags.include?(:b) || flags.include?(:b)) ? '1' : 'X'\n c = (flags.include?(:c) || flags.include?(:c)) ? '1' : 'X'\n d = (flags.include?(:d) || flags.include?(:d)) ? '1' : 'X'\n self.wait_flags = d + c + b + a\n self\n end", "def wait timeout = nil\n @mutex.synchronize {\n if @cnt != 0\n if timeout\n @cond_var.wait @mutex, timeout\n else\n @cond_var.wait @mutex\n end\n end\n }\n end", "def implicit_wait; end", "def wait(sec = 5)\n Logbook.message(\"Waiting #{sec} sec >>\" + \"\\n\")\n sec.instance_of?(Integer) ? sleep(sec) : Logbook.message(\"Waiting time is not integer: [#{sec}]\" + \"\\n\")\n end", "def wait(frames)\n return if @wait > 0\n @wait = frames\n end", "def wait(arg0)\n end" ]
[ "0.7200762", "0.6679357", "0.65788174", "0.6443681", "0.6226858", "0.596722", "0.59339607", "0.58681065", "0.5848157", "0.5846182", "0.58411944", "0.58411944", "0.58140564", "0.5790305", "0.57674325", "0.57514125", "0.57201034", "0.5716633", "0.56703126", "0.5669643", "0.560765", "0.56066203", "0.55677146", "0.55675995", "0.5563107", "0.55415636", "0.55283546", "0.552373", "0.5503527", "0.5499676" ]
0.8285323
0
Returns the default client side wait. This value is independent of what the server is using
def default_wait @default_wait end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def wait_timeout\n @wait_timeout ||= options[:wait_timeout] || DEFAULT_WAIT_TIMEOUT\n end", "def set_implicit_wait_by_default(wait)\n return if @default_wait.nil?\n\n @driver.manage.timeouts.implicit_wait = wait\n rescue ::Selenium::WebDriver::Error::UnknownError => e\n unless e.message.include?('The operation requested is not yet implemented')\n raise ::Appium::Core::Error::ServerError, e.message\n end\n\n ::Appium::Logger.debug(e.message)\n {}\n end", "def wait\n 0\n end", "def balloon_wait\n return (@battler.nil? ? BALLOON_WAIT : @battler.balloon_wait)\n end", "def get_waiting\n raise NotImplementedError\n end", "def default_timeout\n @default_timeout ||= 20000\n end", "def abs_wait_short\n wait(15)\n end", "def max_wait_time\n @data[\"max_wait_time\"]\n end", "def default_timeout\n 3\n end", "def default_timeout\n @default_timeout ||= 30\n end", "def wait_connection=(_arg0); end", "def event_wait_delay seconds\n ScriptActionHandler::HandlerResult::waitDelay seconds\n end", "def implicit_wait; end", "def default_value_noninteractive\n default_value\n end", "def implicit_wait=(seconds); end", "def max_select_wait_time; end", "def wait(seconds)\n @waiting = seconds * 1000\n end", "def wait\n status = (\"\\x00\"*SIZEOFINT).to_ptr\n r = CALLS[\"libc!wait:=I\"].call(status).first\n raise SystemCallError.new(\"wait\", DL.last_error) if r== -1\n return status.to_s(SIZEOFINT).unpack('i_').first\n end", "def default_value()\n defval = cpptype.default_value;\n if name == \"accept-mode\" and parent.name == \"transfer\" then defval = \"1\"; end\n return defval\n end", "def set_wait timeout=nil\n if timeout.nil?\n # puts \"timeout = @default_wait = @last_wait\"\n # puts \"timeout = @default_wait = #{@last_waits}\"\n timeout = @default_wait = @last_waits.first\n else\n @default_wait = timeout\n # puts \"last waits before: #{@last_waits}\"\n @last_waits = [@last_waits.last, @default_wait]\n # puts \"last waits after: #{@last_waits}\"\n end\n\n @driver.manage.timeouts.implicit_wait = timeout\n end", "def num_waiting\n @num_waiting\n end", "def wait!\n sleep(@sleep)\n end", "def wait\n @future.value\n end", "def wait(arg0)\n end", "def wait\n sleep 0.0001\n end", "def wait_time\n self.measurement.wait_time\n end", "def wait\n sleep WAIT_TIME unless @skip_wait\n end", "def server_ready_timeout\n Zartan::Config.new['server_ready_timeout'].to_i\n end", "def wait_async\n @wait_async = true\n end", "def wait\n true\n end" ]
[ "0.6918232", "0.60194534", "0.59551215", "0.588512", "0.5776252", "0.57113725", "0.5703889", "0.56906146", "0.56605303", "0.56548905", "0.5632716", "0.5559097", "0.54802066", "0.5451355", "0.54511195", "0.5442161", "0.5430147", "0.5423666", "0.540995", "0.5396949", "0.53838134", "0.5355152", "0.5348608", "0.53484386", "0.53484", "0.53445137", "0.5333474", "0.532643", "0.53183776", "0.53131574" ]
0.7904518
0
Quit the driver and Pry. quit and exit are reserved by Pry.
def x driver_quit exit # exit pry end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def quit!\n quit\n exit!\n end", "def quit_driver()\n @driver.shutdown\n end", "def quit\r\n @@driver.quit\r\n end", "def quit\n\t\[email protected]\n\tend", "def quit\n exit(1)\n end", "def quit\n @ui.close\n @player.close\n @logger.close\n exit\n end", "def quit\n @ui.close\n @player.close\n @logger.close\n exit\n end", "def quit()\n @webdriver.quit()\n cleanUp();\n end", "def quit\n send_cmd \"quit\"\n nil\n end", "def quit\n driver.quit\n end", "def exit\n\t\tquit\n\tend", "def quit_driver\n driver.quitDriver\n end", "def quit\n send_command(:quit)\n read_response # \"Bye!\"\n disconnect\n end", "def command_quit\n command_save\n exit(0)\n end", "def quit; end", "def quit; end", "def quit; @quit = 1 end", "def exit\n send_cmd \"exit\"\n nil\n end", "def quit\n end", "def exit_program\n exit\n end", "def quit\n Rubygame.quit()\n exit\n end", "def exit_program\n exit\n end", "def quit\n Gamework::App.quit\n end", "def quit\n system('clear')\n exit\n end", "def close_driver\n $driver.quit\nend", "def quit()\n @ole.Quit()\n end", "def quit\n puts 'The library is now closed for renovations'\n end", "def quit\n pid = fork{ exec 'killall', 'afplay' }\n exit\n end", "def quit()\n $webdriver.quit()\n cleanUp();\n $webdriver = nil;\n TestAttributes.put(\"reuseFixture\", null);\n end", "def quit(reason = \"You told me to\")\n @t.puts \"QUIT :#{reason}\"\n exit\n end" ]
[ "0.7649962", "0.75097275", "0.7461979", "0.7409583", "0.7335107", "0.7230508", "0.7230508", "0.7108723", "0.70328236", "0.703234", "0.70131856", "0.6982187", "0.69693995", "0.6916052", "0.68841213", "0.68841213", "0.68736315", "0.683998", "0.6834304", "0.682177", "0.6782976", "0.67467445", "0.67307764", "0.6723212", "0.6720591", "0.67072797", "0.6670117", "0.6646268", "0.65607893", "0.654925" ]
0.784934
0
Finds and returns the 1st node whose value is 'value'
def find(value) self.each {|node| return node if node.value == value} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find(value)\n node = @head\n while node\n if node.value == value\n return node\n end\n node = node.next\n end\n\n return nil\n end", "def find_node(value)\n current = @anchor.next_node\n while current != @anchor\n return current if current.value == value\n current = current.next_node\n end\n end", "def find(value)\n current_node = head\n while current_node != nil\n return current_node if current_node.value == value\n current_node = current_node.next\n end\n nil\n end", "def find(value)\n node = @head \n for i in 0..@size-1 \n return i if node.value == value\n node = node.link \n end\n return nil\n end", "def find_node(value)\n met_resp = find_node_support(value)\n return nil if met_resp[:node].nil?\n\n met_resp[:node]\n end", "def find_node(value)\n met_resp = find_node_support(value)\n return nil if met_resp[:node].nil?\n\n met_resp[:node]\n end", "def find_node(value)\n return false if @head.nil?\n curr_node = @head\n match = false\n while curr_node\n break if match = (curr_node.value == value)\n curr_node = curr_node.next\n end\n\n match\n end", "def find(value)\n return nil if @head.nil?\n found = nil\n index = 0\n current_node = @head\n while !node.nil? do\n if node.data == value\n found = true\n break\n end\n index += 1\n current_node = node.next\n end\n found == true ? \"#{value} found at index #{index}!\" : nil\n end", "def find(value)\n current_node = @root\n until current_node.nil?\n if current_node.data < value\n current_node = current_node.right_child\n elsif current_node.data > value\n current_node = current_node.left_child\n else\n return current_node\n end\n end\n return nil\n end", "def value_of_node(node_name)\n value_of_nodes(node_name).first\nend", "def search(value)\n\t\t\treturn nil if self.empty?\n\t\t\telement = self.head\n\t\t\twhile element.value != value\n\t\t\t\tif element.next.nil?\n\t\t\t\t\treturn nil\n\t\t\t\telse\n\t\t\t\t\telement = element.next\n\t\t\t\tend\n\t\t\tend\n\t\t\telement\n\t\tend", "def find(value, node = @root)\n if node.nil?\n return nil\n end\n\n if value < node.value\n return find(value, node.left_node)\n elsif value > node.value\n return find(value, node.right_node)\n else\n return node\n end\n end", "def depth_first(value_to_find)\r\n @children.each do |child|\r\n found_node = child.depth_first(value_to_find)\r\n if found_node != nil\r\n return found_node\r\n end\r\n end\r\n\r\n if payload == value_to_find\r\n return self\r\n else\r\n return nil\r\n end\r\n end", "def find_by_value(value)\n return nil if value.nil? || self.size == 0\n stop_node = self.head\n target = stop_node\n while target && !target.match_by_value(value)\n target = target.next\n break if stop_node.equal?(target)\n end\n target = nil unless target && target.match_by_value(value)\n target\n end", "def find(value, node = @root)\n return nil if node.nil?\n return node if node.value.eql?(value)\n\n node.value > value ? find(value, node.left) : find(value, node.right)\n end", "def find(value, node = root)\n return node if node.nil? || node.data == value\n \n value < node.data ? find(value, node.left) : find(value, node.right)\n end", "def find(value)\n idx = 0\n node = list\n while node != nil\n return idx if node.value == value\n idx += 1\n node = node.nextNode\n end\n return nil\n end", "def find(value)\n index = 0\n temp = @head\n while temp\n return index if temp.value == value\n index += 1\n temp = temp.next_node\n end\n nil\n end", "def find(value)\n curr = @root\n while curr\n return curr if curr.data == value\n\n if value < curr.data\n curr = curr.left\n elsif value > curr.data\n curr = curr.right\n end\n end\n curr\n end", "def find(value, current_node = root)\n return current_node if current_node.nil? || current_node.value == value\n value < current_node.value ? find(value, current_node.left) : find(value, current_node.right)\n\n end", "def breadth_first(value_to_find)\r\n current_node = self\r\n queue = MyQueue.new \r\n\r\n while current_node != nil\r\n if current_node.payload == value_to_find\r\n return current_node\r\n end\r\n current_node.children.each do |child|\r\n queue.enqueue(child)\r\n end\r\n current_node = queue.dequeue\r\n end\r\n end", "def find(value)\n current_node = @head\n counter = 0\n until current_node.nil?\n return counter if current_node.value == value\n\n current_node = current_node.next_node\n counter += 1\n end\n nil \n end", "def find(value, tree_node = @root)\n current_node = tree_node\n while (current_node)\n if value > current_node.value\n current_node = current_node.right\n elsif value < current_node.value\n current_node = current_node.left\n else\n return current_node\n end\n end\n nil\n end", "def search_cell_by_value(value)\n return nil if self.last.nil?\n \n tail = self.last\n \n while true\n if tail.value == value\n return tail\n elsif tail.successor\n tail = tail.successor\n else\n return nil\n end\n end\n end", "def find(value, current_index = 0, node = @head)\n return nil if node.nil?\n return current_index if node.value == value\n\n find(value, current_index + 1, node.next_node)\n end", "def find_before(value)\n node = @head\n return node if !node.next\n return node if node.next.data == value\n\n while (node = node.next)\n return node if node.next && node.next.data == value\n end\n end", "def find(value)\n i = 1\n current_node = @head\n while current_node != nil do\n return i if current_node.data == value\n current_node = current_node.next\n i += 1\n end\n return nil\n end", "def depth_first_search(tree, value, args = {})\r\n verbose = args.fetch(:verbose, false)\r\n return nil if tree == nil\r\n next_node = [tree]\r\n while !next_node.empty?\r\n current = next_node.pop\r\n if verbose\r\n puts \"current = #{current}\"\r\n puts \"head = #{next_node[0]}\"\r\n end\r\n # visited not strictly necessary for future proofs it \r\n if current.visited == false\r\n current.visited = true\r\n return current if current.value == value\r\n current.children.each { |child| next_node.push child if child } \r\n end\r\n end\r\n nil\r\n end", "def find value, root_node=@root\n case value <=> root_node.data\n when -1\n find(value, root_node.left)\n when 1\n find(value, root_node.right)\n when 0\n return root_node\n else\n return\n end\n end", "def find(value) \n index = 0\n node = @head\n while(node.value != value)\n node = node.next_node\n index += 1\n if(node.value == value)\n return index\n end\n if(node == @tail) && (node.value != value)\n return nil\n end\n end\n return 0 \n end" ]
[ "0.80587685", "0.80214393", "0.7959897", "0.7671774", "0.764562", "0.764562", "0.74783874", "0.74122894", "0.7408482", "0.73552215", "0.73340523", "0.7307569", "0.7260175", "0.7225086", "0.7193016", "0.7160144", "0.713884", "0.7131601", "0.7126046", "0.71244234", "0.7061111", "0.7042303", "0.70332366", "0.7014883", "0.69692904", "0.6954615", "0.69402015", "0.6938328", "0.6891725", "0.68704385" ]
0.81960785
0
find_all(value) finds and return (in an array) all the nodes whose value is 'value'
def find_all(value) nodes = [] self.each {|node| nodes << node if node.value == value} nodes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def elements_by_xpath(value)\n find_by_xpath(value)\n end", "def find_all_nodes(xpath, select_result_value=false)\n if self.feed_data_type != :xml\n raise \"The feed data type is not xml.\"\n end\n return FeedTools::XmlHelper.try_xpaths_all(self.channel_node, [xpath],\n :select_result_value => select_result_value)\n end", "def find(value)\n self.each {|node| return node if node.value == value}\n end", "def xpathall(path,xml)\n r=[]\n XPath.each(xml,path){|x|r<<x}\n r\nend\n", "def get_all_xpath(values)\n\t\tif values.nil? then\n\t\t\treturn []\n\t\tend\n\t\treturn xpath('//' + values.join(XPATH_JOIN))\n\tend", "def search_children(node, attribute, search_term)\n matches = []\n end", "def get_elements(xpath); end", "def get_all_vals(node, arr)\n # add the value of the node to the array\n arr << node.val\n \n # using a ternary operator, check if there is another node in the list\n # if so, recursively run the function again\n # if not, return the array\n return node.next ? get_all_vals(node.next, arr) : arr\n end", "def find_all(conditions)\n @root.find_all(conditions)\n end", "def fakesearch_all_nodes(options = {})\n fakesearch_nodes(nil, options)\nend", "def find_all(*args)\n element.all(*args)\n end", "def find_all(&block)\n return to_enum :find_all unless block\n\n ary = []\n self.each{|*val|\n ary.push(val.__svalue) if block.call(*val)\n }\n ary\n end", "def find_all_nodes(*args)\n nodes = @nodes.find_all_nodes(*args)\n nodes.find_all { |n| context?(n) }\n end", "def find_all_paths\n found_paths = []\n \n explore(found_paths, nil, @start_node)\n \n found_paths\n end", "def search(xpath)\n return self.each_element( xpath ){}\n end", "def value_of_nodes(node_name)\n ns = nodes(node_name)\n ns.map do |n|\n raise \"failed to find #{node_name.inspect} in #{subject.inspect}\" if n.nil?\n n.content\n end\nend", "def search(value)\n return @searchMethods.searchAtTree(value, @root)\n end", "def xpath_all(pdoc, path, namespace = '')\n begin\n if namespace != \"\"\n return pdoc.find(path, namespace) if pdoc.find(path, namespace)\n else\n return pdoc.find(path) if pdoc.find(path)\n end\n rescue\n return []\n end\n end", "def search(value, &block)\n work_list = [@root]\n\n while !work_list.empty?\n curr_node = yield(work_list)\n\n unless curr_node.value == value\n work_list << curr_node.left_child unless curr_node.left_child.nil?\n work_list << curr_node.right_child unless curr_node.right_child.nil?\n else\n return curr_node\n end\n end\n\n return nil\n end", "def find_all_nodes(*args)\n raise NotImplementedError\n nodes = @database.all_nodes\n # TODO: design node finder syntax\n nodes\n end", "def xpath_all(pdoc, path, namespace = '')\n if namespace!=\"\"\n return REXML::XPath.match(pdoc, path, namespace)\n else\n return REXML::XPath.match(pdoc, path);\n end\n return []\n end", "def parse_value(nodes); end", "def lookup_unbounded( value )\n elements = []\n if value.has_key?( \"children\" )\n value[\"children\"].each do |key, value|\n elements << key if value[\"unbounded\"]\n if value.has_key?( \"children\" )\n elements << lookup_unbounded( value )\n end\n end\n end\n elements\n end", "def retrieve_elements(filter)\n elements_array = Array.new\n\n if NOKOGIRI\n @xml.xpath(filter.to_s).each { |pelem|\n elements_array << pelem.text if pelem.text\n }\n else\n @xml.elements.each(filter.to_s) { |pelem|\n elements_array << pelem.text if pelem.text\n }\n end\n\n if elements_array.size == 0\n return nil\n else\n return elements_array\n end\n\n end", "def find_nodes\n puts '1st pass: find nodes'\n find :nodes\n self\n end", "def search_recursive(root,target_value)\n\n return root if root.payload == target_value\n\n root.children.each do |child|\n node = search_recursive(child,target_value)\n return node if node\n end\n\n return nil\n\nend", "def search(xpath)\n results = self.find(xpath).to_a\n if block_given?\n results.each do |result|\n yield result\n end\n end\n return results\n end", "def search(xpath)\n results = self.find(xpath).to_a\n if block_given?\n results.each do |result|\n yield result\n end\n end\n return results\n end", "def extract_all_nodes(xpath, node = xml, namespaces = DEFAULT_NAMESPACES)\n _extract_nodes(:match, xpath, node, namespaces)\n end", "def values(context, xpath)\n enum = context.find(xpath) if context\n (enum || []).map { |node| node.value }\n end" ]
[ "0.73790395", "0.6820984", "0.67537713", "0.62753576", "0.62564236", "0.6141319", "0.61087537", "0.6062094", "0.6044982", "0.60254693", "0.59540236", "0.58442485", "0.5819881", "0.5805825", "0.5749595", "0.5743802", "0.57175523", "0.57110125", "0.5671111", "0.56692845", "0.56496537", "0.5601967", "0.55519944", "0.554809", "0.55334055", "0.552994", "0.55176294", "0.55176294", "0.5505288", "0.5498693" ]
0.859019
0
push(value) adds a value 'value' to the end of the linked list
def push(value) last.next_node = Node.new(value, nil) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def push(value)\n @head = LinkedListNode.new(value, @head)\n end", "def push(value)\n\t\t\t\tif @length == 0\n\t\t\t\t\t@head = @tail = newNode(nil, value, nil)\n\t\t\t\telse\n\t\t\t\t\[email protected] = newNode(@tail, value, nil)\n\t\t\t\t\t@tail = @tail.next\n\n\t\t\t\t\tif @length == 1\n\t\t\t\t\t\[email protected] = @tail\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\t@length += 1\n\t\t\tend", "def push(value)\n\t\tlast_node = find_last\n\t\tlast_node.next_node = Node.new(value)\n\tend", "def push(value)\r\n @data = LinkedListNode.new(value, @data)\r\n end", "def push(value)\r\n @data = LinkedListNode.new(value, @data)\r\n end", "def push(value)\n # IMPLEMENT ME!\n if @data == nil\n @data = LinkedListNode.new(value)\n else\n @data = LinkedListNode.new(value, @data)\n end\n end", "def push(value)\n @data = LinkedListNode.new(value, @data)\n end", "def push(value)\n @data = LinkedListNode.new(value, @data)\n end", "def push(value)\n @data = LinkedListNode.new(value, @data)\n end", "def push(value)\r\n @data = LinkedListNode.new(value, @data)\r\n \r\n end", "def push(value)\r\n if @data == nil\r\n @data = LinkedListNode.new(value)\r\n else\r\n @data = LinkedListNode.new(value, @data)\r\n end\r\n end", "def push(value)\n newNode = Node.new(value)\n if @head.nil?\n @head = newNode\n @tail = @head\n else \n old_tail = @tail\n @tail = newNode\n @tail.previous = old_tail\n end\n @length += 1\n nil\n end", "def push(value)\n @data = LinkedListNode.new(value, @data)\n end", "def push(value)\n @data = LinkedListNode.new(value, @data)\n end", "def push(value)\n node = Node.new(value)\n if @length == 0\n @head = node\n @tail = node\n else\n @tail.next = node\n @tail = node\n end\n @length += 1\n end", "def push(value)\r\n if @data != nil\r\n node = LinkedListNode.new(value, @data)\r\n else\r\n node = LinkedListNode.new(value)\r\n end\r\n @data = node\r\n end", "def push(value)\r\n \t@data = LinkedListNode.new(value, @data)\r\n end", "def push(value)\n new_head = Node.new value, @head\n @head = new_head\n end", "def push(value)\r\n @head = Node.new(value, @head)\r\n end", "def push(value)\n @head = Node.new(value, @head)\n end", "def push(value)\n if @tail != nil\n @tail.next_node = Node.new(value)\n @tail.next_node.previous = @tail\n @tail = @tail.next_node\n else\n @tail = Node.new(value)\n if @head == nil\n @head = @tail\n end\n end\n @length += 1\n nil\n end", "def push(value)\n if @tail != nil\n @tail.next_node = Node.new(value)\n @tail.next_node.previous = @tail\n @tail = @tail.next_node\n else\n @tail = Node.new(value)\n if @head == nil\n @head = @tail\n end\n end\n @length += 1\n nil\n end", "def push(value)\r\n @data = LinkedListNode.new(value, self.data)\r\n end", "def push(value)\n new_node = LinkedListNode.new(value, @data)\n @data = new_node\n end", "def push(value)\n new_head = Node.new(value, @head)\n @head = new_head\n if tail.nil?\n @tail = @head\n end\n end", "def push(value)\n @data = LinkedListNode.new(value, @data) \n end", "def push(value)\n @data = LinkedListNode.new(value, data)\n end", "def push(value)\r\n\t\tif @data.nil? \r\n\t\t\t@data = LinkedListNode.new(value) \r\n\t\telse\r\n\t\t\t@data = LinkedListNode.new(value, @data)\r\n\t\tend\r\n\tend", "def push(value)\n new_node = Node.new(value)\n if length > 0\n new_node.prev_value = @tail\n @tail.next_value = new_node\n @tail = new_node\n if length == 1\n @head.next_value = new_node\n new_node.prev_value = head\n end\n else\n @head = new_node\n @tail = new_node\n end\n @length += 1\n return new_node.value\n end", "def push(value)\n @data = LinkedListNode.new value, @data\n end" ]
[ "0.8621315", "0.8543513", "0.8484303", "0.8457438", "0.8457438", "0.84379774", "0.84340274", "0.84340274", "0.84321713", "0.8428468", "0.84120625", "0.84027535", "0.8401683", "0.8401683", "0.83994704", "0.83962727", "0.83738476", "0.8365877", "0.83572245", "0.8356332", "0.83531404", "0.83531404", "0.8349722", "0.8344037", "0.8331988", "0.8322025", "0.8312987", "0.8292562", "0.8270121", "0.82580566" ]
0.86422974
0
The "type" of dependencies this manager manages. This can be the language, tool, etc.
def type raise LicenseScout::Exceptions::Error.new("All DependencyManagers must have a `#type` method") end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def type\n @klass.is_a?(Rubinius::ToolSets::Runtime::ToolSet::AST::Class) ? \"class\" : \"module\"\n end", "def type\n @type ||= self.class.name.split('::').last\n end", "def dependency name, version, type = :runtime\n raise \"Unknown dependency type: #{type}\" unless\n [:runtime, :dev, :development, :developer].include? type\n\n ary = if type == :runtime then\n extra_deps\n else\n extra_dev_deps\n end\n\n ary << [name, version]\n end", "def type\n type_and_version[0]\n end", "def type\n types.first\n end", "def type\n @type.name\n end", "def type\n memoized_info[:type]\n end", "def type\n @props[:type]\n end", "def type\n self.class.type\n end", "def type\n self.class.type\n end", "def type\n self.class.type\n end", "def type\n types.first\n end", "def type_klass; end", "def type; self.class.name.split('::').last.to_sym; end", "def type\n self.class.type\n end", "def type\n self.class.type\n end", "def type\n self.class.type\n end", "def type\n self_class.to_s.to_sym\n end", "def __type; @type == TYPE_BUILDING ? \"Building\" : \"Unit\"; end", "def type\n self.class::TYPE\n end", "def deploys_to_class(type)\n (\n \"Building::%s\" % CONFIG[\"units.#{type.underscore}.deploys_to\"]\n ).constantize\n end", "def type\n\t\tself.class.type\n\tend", "def type\n\t\tself.class.type\n\tend", "def type\n @type\n end", "def type\n @type\n end", "def type\n @type\n end", "def type\n @type\n end", "def type\n @type ||= calculate_type\n end", "def type\n TYPES[@type_id]\n end", "def type\n read_attr :type, :to_sym\n end" ]
[ "0.6768606", "0.64739126", "0.64718497", "0.6274962", "0.61399627", "0.61187696", "0.608098", "0.60559875", "0.60549706", "0.60549706", "0.60549706", "0.601348", "0.6011569", "0.59861875", "0.59820884", "0.59820884", "0.59820884", "0.59811634", "0.59806734", "0.5944626", "0.5923362", "0.5899092", "0.5899092", "0.5898636", "0.5898636", "0.5898636", "0.5897629", "0.5894587", "0.5887393", "0.588487" ]
0.7233944
0
Implementation's of this method in subclasses are the methods that are responsible for all the heavylifting when it comes to determining the dependencies (and their licenses). They should return an array of `LicenseScout::Dependency`.
def dependencies [] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def licenses\n licenses = []\n uris = metadata[dataset_uri][dct.license.to_s]\n if uris.nil?\n []\n else\n uris.each do |uri|\n l = metadata[uri]\n licenses << License.new(:uri => uri, :name => l[dct.title.to_s])\n end\n return licenses\n end\n rescue\n []\n end", "def dependencies_for(specification)\n []\n end", "def dependencies\n []\n end", "def licenses *names\n names.to_strings.each do |name| \n begin\n module_name = \"#{name.camelize}License\"\n clazz = module_name.constantize\n clazz.new(self).enforce!\n rescue\n raise \"License #{module_name} not found\"\n end\n end\n end", "def dependencies\n []\n end", "def licenses *names\n names.to_strings.each do |name| \n begin\n module_name = \"#{name.camelize}License\"\n clazz = module_name.constantize\n rescue\n raise \"License #{module_name} is not defined\"\n end\n\n begin\n clazz.new(self).enforce!\n rescue\n raise \"License #{clazz} could not be enforced using #{self.inspect}\"\n end\n end\n end", "def licenses\n @licenses ||= []\n end", "def depend_upon(match_name) #, constraint)\n list = []\n each do |name, libs|\n case libs\n when Library\n list << libs if libs.requirements.any?{ |r| match_name == r['name'] } \n else\n libs.each do |lib|\n list << lib if lib.requirements.any?{ |r| match_name == r['name'] } \n end\n end\n end\n list\n end", "def dependencies\n @dependencies.collect { |name, dependency| dependency }\n end", "def dependencies( *args )\n names = args # note: for now assume all args are just names\n # e.g. 'pluto-models', 'pluto-update', etc.\n deps = @versions.select do |rec| names.include?( rec[0] ) end\n .map do |rec| [rec[0], rec[1]] end\n\n ## todo/fix: throw exception if dependency is missing!\n ## names.size == deps.size\n puts \"names.size == deps.size #{names.size} == #{deps.size}\"\n deps\n end", "def licenses\n if @licenses.nil?\n @licenses = self.links.select do |link|\n link.rel == \"license\"\n end\n end\n return @licenses\n end", "def dependencies\n @dependencies.values\n end", "def depends_upon(match_name) #, constraint)\n list = []\n $LEDGER.each do |name, libs|\n case libs\n when Library\n list << libs if libs.requirements.any?{ |r| match_name == r['name'] } \n else\n libs.each do |lib|\n list << lib if lib.requirements.any?{ |r| match_name == r['name'] } \n end\n end\n end\n list\n end", "def dependencies\n @dependencies ||= []\n end", "def dependencies\n @dependencies ||= []\n end", "def dependencies\n @dependencies ||= []\n end", "def dependencies\n @dependencies ||= []\n end", "def getDependencies service\r\n deps = []\r\n Util.csprojs(service).each do |csproj|\r\n deps += getDeps(csproj) \r\n end\r\n return deps.uniq\r\nend", "def dependencies\n version_req = if options[:version]\n ::Gem::Requirement.create(options[:version])\n else\n ::Gem::Requirement.default\n end\n if gem_dir\n ::Gem.clear_paths; ::Gem.path.unshift(gem_dir)\n ::Gem.source_index.refresh!\n end\n deps = []\n ::Gem.source_index.each do |fullname, gemspec| \n if version_req.satisfied_by?(gemspec.version)\n deps << ::Gem::Dependency.new(gemspec.name, \"= #{gemspec.version}\")\n end\n end\n ::Gem.clear_paths if gem_dir\n deps.sort\n end", "def dependencies(include_parent = false)\n []\n end", "def dependencies(include_parent = false)\n []\n end", "def dependencies(include_parent = false)\n []\n end", "def dependencies\n EMPTY_SET\n end", "def find_licenses_in_source\n license_files = []\n\n @find_class.find(@gem_source) do |path|\n license_files << path if path.include?(\"LICENSE\")\n end\n\n license_files\n end", "def dependencies\n @dependencies ||= []\n end", "def dependencies( names )\n names.each do |name|\n if calculation = fetch( name, nil )\n calculation.dependencies.each do |dependency|\n names << dependency unless names.include?( dependency )\n end\n end\n end\n end", "def dependencies\n @dependencies\n end", "def dependencies\n return @dependencies unless @dependencies.nil?\n @dependencies = [ ]\n lockfile.each_line do |line|\n if line =~ /^\\s{4}([-\\w_.0-9]+)\\s*\\((.*)\\)/\n @dependencies << [$1, $2]\n end\n end\n @dependencies\n end", "def dependencies\n to_a.reject { |a| a.filename.eql?(self.filename) }\n end", "def dependencies_for(specification)\n specification.dependencies\n end" ]
[ "0.6979492", "0.68642575", "0.6855722", "0.6850754", "0.6844061", "0.684021", "0.67019534", "0.6685572", "0.66536504", "0.65131265", "0.6511361", "0.6506128", "0.64482623", "0.64454293", "0.64454293", "0.64454293", "0.64454293", "0.643095", "0.6416843", "0.63927746", "0.63927746", "0.63927746", "0.6362662", "0.6360732", "0.63509893", "0.6253492", "0.62397605", "0.6207319", "0.61332333", "0.61059904" ]
0.69650996
1
A helper that allows you to quickly create a new Dependency (with the type)
def new_dependency(name, version, path) LicenseScout::Log.debug("[#{type}] Found #{name} #{version}#{" #{path}" unless path.nil?}") Dependency.new(name, version, path, type) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def d(*args)\n Dependency.new(*args)\n end", "def as_a_dependency\n Aws::Templates::Utils::Dependency.new(object)\n end", "def add_dependency_with_type(dependency, type, requirements)\n requirements = if requirements.empty?\n Gem::Requirement.default\n else\n requirements.flatten\n end\n\n unless dependency.respond_to?(:name) &&\n dependency.respond_to?(:requirement)\n dependency = Gem::Dependency.new(dependency.to_s, requirements, type)\n end\n\n dependencies << dependency\n end", "def initialize(name, *requirements)\n case name\n when String then # ok\n when Regexp then\n msg = [\"NOTE: Dependency.new w/ a regexp is deprecated.\",\n \"Dependency.new called from #{Gem.location_of_caller.join(\":\")}\"]\n warn msg.join(\"\\n\") unless Gem::Deprecate.skip\n else\n raise ArgumentError,\n \"dependency name must be a String, was #{name.inspect}\"\n end\n\n type = Symbol === requirements.last ? requirements.pop : :runtime\n requirements = requirements.first if 1 == requirements.length # unpack\n\n unless TYPES.include? type\n raise ArgumentError, \"Valid types are #{TYPES.inspect}, \" +\n \"not #{type.inspect}\"\n end\n\n @name = name\n @requirement = Gem::Requirement.create requirements\n @type = type\n @prerelease = false\n\n # This is for Marshal backwards compatibility. See the comments in\n # +requirement+ for the dirty details.\n\n @version_requirements = @requirement\n end", "def artifact(type, params = nil, &blk)\n artifact_object = create_artifact_object(type, params, &blk)\n self[artifact_object.label] = artifact_object\n artifact_object.as_a_dependency.to_self\n end", "def create\n @dependency = Dependency.new(dependency_params)\n\n respond_to do |format|\n if @dependency.save\n format.html { redirect_to @dependency, notice: 'Dependency was successfully created.' }\n format.json { render :show, status: :created, location: @dependency }\n else\n format.html { render :new }\n format.json { render json: @dependency.errors, status: :unprocessable_entity }\n end\n end\n end", "def Factory (name, attrs = {})\n Factory.create(name, attrs)\nend", "def direct_dependency(type, result = T.unsafe(nil)); end", "def dependency name, version, type = :runtime\n raise \"Unknown dependency type: #{type}\" unless\n [:runtime, :dev, :development, :developer].include? type\n\n ary = if type == :runtime then\n extra_deps\n else\n extra_dev_deps\n end\n\n ary << [name, version]\n end", "def add(name:, depends_on:, **kwargs)\n check_for_missing_dependencies!(depends_on)\n graph[name] = dependency_class.new(kwargs.merge(name: name, depends_on: depends_on))\n end", "def create\n name_to_const.new\n end", "def make(thing) end", "def create_object\n definition.sought_type.new\n end", "def create_dependency_graph\n service_types.map do |key, i|\n i.service_producers.map do |j|\n j.factory.machine.depends.each do |k|\n binding.pry unless service_types[k.name]\n service_types[k.name].join(i)\n end\n j.factory.machine.requires.each do |k|\n binding.pry unless service_types[k.name]\n i.join(service_types[k.name])\n end\n end\n end\n end", "def build(attrs = {})\n attrs[:type] ? attrs[:type].constantize.new(attrs) : new(attrs)\n end", "def initialize(dependency, requester)\n @dependency = dependency\n @requester = requester\n end", "def create(type, opts = nil)\n proxy_info = OmfRc::ResourceFactory.proxy_list[type]\n if proxy_info && proxy_info.create_by && !proxy_info.create_by.include?(self.type.to_sym)\n raise StandardError, \"Resource #{type} is not designed to be created by #{self.type}\"\n end\n\n before_create(type, opts) if respond_to? :before_create\n new_resource = OmfRc::ResourceFactory.new(type.to_sym, opts, @comm)\n after_create(new_resource) if respond_to? :after_create\n children << new_resource\n new_resource\n end", "def object_with_type(cl)\n o = cl.allocate.compile_time_init\n name = cl.name.split(\"::\").last.to_sym\n o.set_type @types[name]\n o\n end", "def add_dependency(dep)\n unless dep.is_a?(Dependency)\n raise TypeError, 'illegal argument type: must be a Dependency'\n end\n\n raise NotImplementedError\n end", "def parse_dependency(name, op) # :nodoc:\n return Gem::Dependency.new name, op unless peek[0] == :text\n\n version = get(:text).value\n\n requirements = [\"#{op} #{version}\"]\n\n while peek.type == :comma do\n get :comma\n op = get(:requirement).value\n version = get(:text).value\n\n requirements << \"#{op} #{version}\"\n end\n\n Gem::Dependency.new name, requirements\n end", "def create; super(:type); end", "def convert_package_to_dependency(pkg)\n path, errors = check_dep_path(pkg)\n Dependency.new(\n name: pkg[:name],\n version: pkg[:version],\n path: path,\n metadata: pkg[:metadata].merge(\"type\" => self.class.type),\n errors: errors + Array(pkg[:error])\n )\n end", "def factory(klass, *args)\n klass.new(*args)\n end", "def create(type:, **options)\n find(type).new(**options)\n end", "def create\n identify.tap { type }\n end", "def make_node(type, *args)\n elem = type.new self, *args\n @nodes << elem\n self.core_node ||= elem.id\n elem.expand\n elem\n end", "def build (name, attrs = {})\n factory_by_name(name).build(attrs)\n end", "def build (name, attrs = {})\n factory_by_name(name).build(attrs)\n end", "def depend(location, type, *args)\n deps = fetch(:dependencies, {})\n deps[location] ||= {}\n deps[location][type] ||= []\n deps[location][type] << args\n set :dependencies, deps\n end", "def depend(location, type, *args)\n deps = fetch(:dependencies, {})\n deps[location] ||= {}\n deps[location][type] ||= []\n deps[location][type] << args\n set :dependencies, deps\n end" ]
[ "0.70160085", "0.6388023", "0.62843645", "0.61787224", "0.6020573", "0.59608924", "0.5925612", "0.5895755", "0.5841771", "0.5823852", "0.5804395", "0.57698995", "0.5739764", "0.5675239", "0.567129", "0.5561659", "0.55614346", "0.5532884", "0.5526409", "0.5510601", "0.54771894", "0.54721177", "0.5467415", "0.54398954", "0.54347265", "0.5401282", "0.5397357", "0.5397357", "0.538574", "0.538574" ]
0.694366
1
Creates and returns a new RecBack MazeHelper object. Many options are supported: [:width] The number of columns in the maze. [:height] The number of rows in the maze. [:seed] The maze algorithm to use. This should be a class,
def initialize(options = {}) @width = (options[:width] || 10).to_i @height = (options[:height] || @width).to_i @seed = (options[:seed] || rand(0xFFFF_FFFF)).to_i @grid = Array.new(height) {Array.new(width, 0)} srand(@seed) # start carving the maze passage from the upper-left corner carve_passages_from(0, 0, @grid) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def redesign\r\n\t\tm = MazeMaker.new(@n,@m)\r\n\t\t@maze = m.make_maze\r\n\tend", "def get_maze(full=true)\n Maze.new(@width, @height, @start_p, @end_p, full)\n end", "def generate\n carve maze.cell_at(0,0)\n maze\n end", "def initialize(options = {})\n @width = (options[:width] || 10).to_i\n @height = (options[:height] || @width).to_i\n @seed = (options[:seed] || rand(0xFFFF_FFFF)).to_i\n @grid = Array.new(height) { Array.new(width, 0) }\n\n srand(seed)\n end", "def initialize(width, height)\n @grid = Array.new(height) { Array.new(width) }\n create_maze(0, 0, 3)\n end", "def initialize(maze, options)\n @options = DEFAULTS.merge(options)\n\n [:background, :wall_color, :cell_color, :solution_color].each do |c|\n @options[c] = ChunkyPNG::Color.from_hex(@options[c]) if String === @options[c]\n end\n\n @paths = @options[:paths] || []\n\n if @options[:solution]\n path = maze.new_solver(type: @options[:solution]).solve.to_path(color: @options[:solution_color])\n @paths = [path, *@paths]\n end\n end", "def create_maze(row, col, direction)\n curr_cell = Cell.new\n @grid[row][col] = curr_cell\n\n curr_cell.walls[direction] = false\n\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n 4.times do\n index = rand(directions.length)\n direction = directions.delete_at(index)\n direction_from =\n case direction\n when [0, 1]\n 0\n when [0, -1]\n 2\n when [1, 0]\n 3\n when [-1, 0]\n 1\n end\n\n direction_to =\n case direction\n when [0, 1]\n 2\n when [0, -1]\n 0\n when [1, 0]\n 1\n when [-1, 0]\n 3\n end\n new_row = row + direction[0]\n new_col = col + direction[1]\n\n unless new_row.negative? ||\n new_col.negative? ||\n new_row >= @grid.length ||\n new_col >= @grid[0].length ||\n @grid[new_row][new_col]\n\n curr_cell.walls[direction_to] = false\n create_maze(new_row, new_col, direction_from)\n end\n end\n end", "def redesign()\n\t\tr_maze= maze {|r,c| r_maze[r][c].to_i}\n\t\t(1..row-2).each {|r| (1..col-2).each {|c| r_maze[r][c] = Random.rand(2).to_s}}\n\t\treturn r_maze\n\tend", "def initializeMaze(size)\n return Array.new(size[0] + 1){Array.new(size[1] + 1, '#')}\nend", "def create_maze(file)\n line = file.gets\n if line == nil then return end\n\n # read 1st line, must be maze header\n sz, sx, sy, ex, ey = line.split(/\\s/)\n #course is the maze course\n @course = Array.new(sz.to_i)\n @course.map!{Array.new(sz.to_i)}\n \n @course[sx.to_i][sy.to_i] = Cell.new(sx.to_i, sy.to_i)\n \n @start_x = sx.to_i\n @start_y = sy.to_i\n @course[sx.to_i][sy.to_i].change_mode(\"Start\")\n \n @course[ex.to_i][ey.to_i] = Cell.new(ex.to_i, ey.to_i)\n @end_x = ex.to_i\n @end_y = ey.to_i\n @course[ex.to_i][ey.to_i].change_mode(\"End\")\n \n @paths = Array.new\n # read additional lines\n while line = file.gets do\n\n # begins with \"path\", must be path specification\n if line[0...4] == \"path\"\n p, name, x, y, d = line.split(/\\s/)\n ds = d.split(//)\n temp = Path.new(nil, nil, nil, nil)\n temp.initialize(name, x.to_i, y.to_i, ds)\n @paths.push(temp)\n \n # otherwise must be cell specification (since maze spec must be valid)\n else\n x, y, d, w = line.split(/\\s/,4)\n if @course[x.to_i][y.to_i] == nil\n @course[x.to_i][y.to_i] = Cell.new(x.to_i,y.to_i)\n end\n \n ds = d.split(//)\n ws = w.split(/\\s/)\n (0...ds.size).each { |i| \n @course[x.to_i][y.to_i].new_direction(ds[i], ws[i])}\n end\n end\n end", "def initialize(maze, meta={})\n @maze = maze\n @paths = Hash.new(0)\n @cells = Hash.new(0)\n @meta = meta\n end", "def redesign(); load(MazeRedesign.new(across,down).produce) end", "def initialize( w=DEFAULT_WIDTH, h=DEFAULT_HEIGHT, s=DEFAULT_SEED, a=DEFAULT_ANIMATE, d=DEFAULT_DELAY )\n\t\t# \n\t\t# Invoke super-constructor\n\t\t#\n\t\tsuper(w,h,s)\n\n\t\t@frontier = []\n\n\t\t# \n\t\t# Only prepare the maze beforehand if we are doing \"static\" (i.e., animate = false) drawing\n\t\t#\n\t\t@delay = d\n\t\t@animate = a\n\t\tif not @animate\n\t\t\tcarve_passages\n\t\tend\n\tend", "def initialize(seeds)\n @grid = Array.new(9) { Array.new(9, nil) }\n @rows = {}\n @columns = {}\n @squares = {}\n 1.upto(9) do |i|\n @rows[i] = Hash.new(false)\n @columns[i] = Hash.new(false)\n @squares[i] = Hash.new(false)\n end\n seed_board(seeds)\n end", "def make_graph\n\t\t@graph = Graph.new(@width2, @height2, @maze)\n\tend", "def initialize(window, width, height, rooms_width, rooms_height)\n @window = window\n @width, @height = width, height\n @rooms_width, @rooms_height = rooms_width, rooms_height\n\n # Create RoomGenerator\n generator = RoomGenerator.new(@window, @rooms_width, @rooms_height)\n \n @rooms = Array.new(@height) do |l|\n Array.new(@width) do |c|\n generator.generate_room(c, l)\n end\n end\n \n puts \"Created maze of #{@width}*#{@height} rooms.\"\n puts \"=> #{@width*@rooms_width}*#{@height*@rooms_height} squares\"\n end", "def redesign\n new_maze = Maze.new\n #continues until it gets a valid maze\n while !new_maze.loaded?\n new_maze = self.create_minimum\n string = new_maze.save\n string.strip!\n #tries to load the maze\n new_maze.load string, (@old_maze.width-1)/2, (@old_maze.height-1)/2\n #resets the maze full of walls if it is needed again\n @maze = Maze.new\n @maze.load @old_string, (@old_maze.width-1)/2, (@old_maze.height-1)/2, true\n end\n new_maze\n end", "def initialize\n @start_vertical = nil\n @start_horizontal = nil\n @processed_maze = nil\n end", "def initialize (n, m)\n @r = m\n @c = n\n @n = m * 2 + 1\n @m = n * 2 + 1\n @maze_mat = Array.new(@n){Array.new(@m)}\n end", "def initialize n, m\n\t\t@width = n \n\t\t@height = m \n\t\t@width2 = @width * 2 + 1\n\t\t@height2 = @height * 2 + 1\n\t\t@maze = Array.new(@height2) {Array.new(@width2)}\n\tend", "def setup_maze_presenter(algorithm, state)\n state[:current_grid_length] = INITIAL_MAZE_GRID_LENGTH\n state[:remaining_time] = TIME_LIMIT\n state[:algorithm] = algorithm\n state[:needs_reset] = true\n state[:footsteps] = []\n state[:level_record] = []\n state[:algorithm_state] = {}\n state[:pop_sound] = Gosu::Sample.new('assets/music/pop.ogg')\n state[:warning_sound] = Gosu::Sample.new('assets/music/warning.ogg')\nend", "def initialize(maze, a=maze.start, b=maze.finish)\n @maze = maze\n @a = a\n @b = b\n @solution = nil\n end", "def initialize(args={})\n @size = args[:size] || 10\n @seed = args[:seed] || 20\n raise ArgumentError, \"seed is larger than board size (size**2)\" if size**2 < seed\n @born = 0\n @died = 0\n @prospered = 0\n\n @board = Table.new(rows: size, cols: size, obj: Cell)\n #seed_board\n end", "def initialize( w=DEFAULT_WIDTH, h=DEFAULT_HEIGHT, s=DEFAULT_SEED)\n \t @width = w\n\t @height = h\n\t @seed = s\n\t \n\t srand(@seed)\n\t \n\t # TODO --> remove grid??\n\t @grid = Array.new(h) { Array.new(w,0) }\n end", "def recur_divide(x, y, w, h, dir)\n #we first check the size of our given part of the maze\n if w >= 5 and h >= 5\n #then we set where we want to add the wall in the maze\n check_h_cut = dir == \"H_cut\"\n c = (w-1)/2\n wall_x = x + (check_h_cut ? 1 : (rand(c - 1)+1)*2)\n r = (h-1)/2\n wall_y = y + (check_h_cut ? (rand(r - 1)+1)*2 : 1)\n\n #the incrementing number for maze\n incre_x = check_h_cut ? 2 : 0\n incre_y = check_h_cut ? 0 : 2\n\n #every time we break the maze into two part, we need to leave a hole in\n #the wall so that we could enter from one part to the other\n hole_x = wall_x + (check_h_cut ? rand(c)*2 : 0)\n hole_y = wall_y + (check_h_cut ? 0 : rand(r)*2)\n wall_length = check_h_cut ? c : r\n\n #draw the wall here\n wall_length.times do\n if wall_x != hole_x || wall_y != hole_y\n maze_mat[wall_y][wall_x] = 1\n end\n wall_x += incre_x\n wall_y += incre_y\n end\n\n #recirsively divide the maze into two parts and then draw the wall the the two parts\n new_x = x\n new_y = y\n new_w = check_h_cut ? w : wall_x - x + 1\n new_h = check_h_cut ? wall_y - y + 1 : h\n recur_divide(new_x, new_y, new_w, new_h, cut_dir(new_w, new_h)) #this is the top/left part of the maze\n new_x = check_h_cut ? x : wall_x\n new_y = check_h_cut ? wall_y : y\n new_w = check_h_cut ? w : w - wall_x + x\n new_h = check_h_cut ? h - wall_y + y : h\n recur_divide(new_x, new_y, new_w, new_h, cut_dir(new_w, new_h)) #this is the bottom/right part of the maze\n end\n end", "def initialize (n, m)\n\t\t@width = n \n\t\t@height = m \n\t\t@array = []\n\t\t@maze = Array.new(n*2 + 1) {Array.new(m*2 + 1)}\n\tend", "def initialize (n,m)\n\t\t@row = 2*m + 1\n\t\t@col = 2*n + 1\n\t\t@maze = []\n\t\t@visited = Array.new(row){Array.new(col) {|x| x = false}}\n\t\t@trace = []\n\n\tend", "def initialize \n @rows = 8\n @columns = 8\n @grid = create_board\n end", "def redesign\n @waiting = []\n @maze_table = Array.new(2*@m+1){Array.new(2*@n+1, \"1\")}\n for i in 0..2*@m\n for j in 0..2*@n\n @maze_table[i][j] = \"w\" if i%2==1 && j%2==1\n end\n end\n sx = 2*rand(@m)+1\n sy = 2*rand(@n)+1\n @maze_table[sx][sy] = \"0\"#set cell\n add_neighbor(sx, sy)\n until @waiting.empty?\n wall, cell, dir = @waiting.delete_at(rand(@waiting.length))\n pre = [cell[0]-2, cell[1]] if dir == \"down\"\n pre = [cell[0]+2, cell[1]] if dir == \"up\"\n pre = [cell[0], cell[1]-2] if dir == \"right\"\n pre = [cell[0], cell[1]+2] if dir == \"left\"\n if @maze_table[cell[0]][cell[1]] == \"w\" && count_walls(pre[0],pre[1]) > 1\n @maze_table[cell[0]][cell[1]] = \"0\"\n @maze_table[wall[0]][wall[1]] = \"0\"\n add_neighbor(cell[0], cell[1]) \n end\n end\n end", "def make_maze\n\tk = 0\n\t\tfor i in 0 ..@height*2\n\t\t\tfor j in 0 ..@width*2\n\t\t\t\t@maze[i][j] = @array[k]\n\t\t\t\tprint @maze[i][j]\n\t\t\t\tk += 1\n\t\t\tend\n\t\t\tputs \"\"\n\t\tend\n\tend" ]
[ "0.60306096", "0.5867004", "0.5722799", "0.5674609", "0.55316454", "0.5510154", "0.54470944", "0.5416506", "0.5395136", "0.5344716", "0.5318697", "0.52820045", "0.5241874", "0.5171722", "0.5171573", "0.5103918", "0.5090913", "0.5081683", "0.5038239", "0.49908844", "0.49598753", "0.49444863", "0.49332064", "0.48911515", "0.48837274", "0.48722452", "0.4828539", "0.48111343", "0.47782248", "0.47733656" ]
0.680969
0
Returns original window if defined, current window if not See Windowuse
def original_window @original_window ||= window end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_window; @window; end", "def window\r\n return $window\r\n end", "def window\n @session.request(:vim_get_current_window)\n end", "def window\n @win\n end", "def usable_window\n window = @windows.last\n window if window.loaded?\n end", "def active_window\n window_pointer = FFI::MemoryPointer.new :ulong, 1\n XDo::FFILib.xdo_window_get_active @_pointer, window_pointer\n XDo::Window.new self, window_pointer.read_ulong\n end", "def current_window\n @driver.window_handle\n rescue Selenium::WebDriver::Error::NoSuchWindowError\n nil\n end", "def window\n Window\n end", "def current_window_builder\n return UI::Window.window_builder(current_windowskin)\n end", "def current_window_builder\n return UI::Window.window_builder(current_windowskin)\n end", "def window\n Window_Base.new(0, 0, 0, 0)\n end", "def current_window\n case current_action\n when :buy\n @goods_window\n when :sell\n @sell_window\n when :rebuy\n @rebuy_window\n else\n nil\n end\n end", "def active_window\n if File.exists?(wmii_namespace)\n 'wmiir cat /client/sel/ctl | sed 1q'\n else\n %q[xprop -root _NET_ACTIVE_WINDOW | awk '/#/ { print $(NF) ; exit } END { exit 1 }' || xdotool getwindowfocus]\n end\nend", "def window\n @window || create_window\n end", "def window\n self\n end", "def current_windowskin_settings\n if $game_variables != nil\n winvar = YE::SYSTEM::WINDOW_VARIABLE\n if $game_variables[winvar] == 0\n $game_variables[winvar] = YE::SYSTEM::DEFAULT_WINDOW\n elsif !MENU_CONFIG::WINDOW_HASH.include?($game_variables[winvar])\n $game_variables[winvar] = YE::SYSTEM::DEFAULT_WINDOW\n end\n mso_windowskin = MENU_CONFIG::WINDOW_HASH[$game_variables[winvar]]\n else\n mso_windowskin = MENU_CONFIG::WINDOW_HASH[YE::SYSTEM::DEFAULT_WINDOW]\n end\n return mso_windowskin\n end", "def current_windowskin_settings\n if $game_variables != nil\n winvar = YE::SYSTEM::WINDOW_VARIABLE\n if $game_variables[winvar] == 0\n $game_variables[winvar] = YE::SYSTEM::DEFAULT_WINDOW\n elsif !MENU_CONFIG::WINDOW_HASH.include?($game_variables[winvar])\n $game_variables[winvar] = YE::SYSTEM::DEFAULT_WINDOW\n end\n mso_windowskin = MENU_CONFIG::WINDOW_HASH[$game_variables[winvar]]\n else\n mso_windowskin = MENU_CONFIG::WINDOW_HASH[YE::SYSTEM::DEFAULT_WINDOW]\n end\n return mso_windowskin\n end", "def switch_window\n current_window = window\n wins = windows\n wait_until { (wins = windows) && wins.size > 1 } if wins.size == 1\n raise StandardError, 'Unable to determine which window to switch to' if wins.size > 2\n\n wins.find { |w| w != current_window }.use\n window\n end", "def active_window\n current_terminal.current_session\n end", "def win\n @win\n end", "def overwrite_window\n return @window.overwrite(@otherwin.get_window)\n end", "def active_window\n return @active_members_window if @last_window == :active_members_window\n return @reserve_members_window if @last_window == :reserve_members_window\n nil\n end", "def focused_window\n window_pointer = FFI::MemoryPointer.new :ulong, 1\n XDo::FFILib.xdo_window_get_focus @_pointer, window_pointer\n XDo::Window.new self, window_pointer.read_ulong\n end", "def current_name_window_builder\n return UI::Window.window_builder(current_name_windowskin)\n end", "def active_window\n windows = @terminal.windows.get\n windows.detect do |window|\n window.properties_.get[:frontmost] rescue false\n end\n end", "def active_window\n windows = @terminal.windows.get\n windows.detect do |window|\n window.properties_.get[:frontmost] rescue false\n end\n end", "def get_window_number()\r\n $jssh_socket.send(\"getWindows().length;\\n\", 0)\r\n @@current_window = read_socket().to_i - 1\r\n \r\n # Derek Berner 5/16/08 \r\n # If at any time a non-browser window like the \"Downloads\" window \r\n # pops up, it will become the topmost window, so make sure we \r\n # ignore it.\r\n @@current_window = js_eval(\"getWindows().length\").to_i - 1\r\n while js_eval(\"getWindows()[#{@@current_window}].getBrowser\") == ''\r\n @@current_window -= 1;\r\n end\r\n\r\n # This will store the information about the window.\r\n #@@window_stack.push(@@current_window)\r\n #puts \"here in get_window_number window number is #{@@current_window}\"\r\n return @@current_window\r\n end", "def real_focused_window\n window_pointer = FFI::MemoryPointer.new :ulong, 1\n XDo::FFILib.xdo_window_sane_get_focus @_pointer, window_pointer\n XDo::Window.new self, window_pointer.read_ulong\n end", "def selected_window\n list_windows[@command_window.item]\n end", "def window_handle; end" ]
[ "0.787422", "0.7749725", "0.7462729", "0.7365655", "0.73364246", "0.7200005", "0.7185287", "0.7107227", "0.7069621", "0.7069621", "0.7031164", "0.69700843", "0.695627", "0.6947236", "0.69061977", "0.6901702", "0.6901667", "0.68819124", "0.68757325", "0.6871016", "0.68509674", "0.67669237", "0.6752168", "0.6696656", "0.66760147", "0.66760147", "0.6655991", "0.66300064", "0.6613878", "0.66078645" ]
0.82171977
0
Returns estimated effort for a ProjectPhase by calculating the sum of the estimated effort for each StockDeliverableType and CustomDeliverableType
def estimated_effort total_estimated_effort = 0 self.project_phase_deliverables.each do |deliverable| total_estimated_effort += deliverable.estimated_effort.to_f unless deliverable.nil? end return total_estimated_effort end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calculate_phase_actual_effort(project_id, phase)\n @hours = 0\n @dataset = Deliverable.find_all_by_phase_and_project_id(phase, project_id)\n puts @dataset\n if @dataset.nil?\n return 0\n else\n @dataset.each do |d|\n @hours += d.hours_logged\n end\n return @hours\n end\n end", "def logged_effort\n total_logged_effort = 0\n\n self.project_phase_deliverables.each do |deliverable|\n total_logged_effort += deliverable.logged_effort.to_f unless deliverable.nil?\n end\n\n return total_logged_effort\n end", "def project_phase_deliverables\n project_phase_deliverables = []\n stock_deliverable_types.each do |stock|\n stock.deliverables.each do |d|\n project_phase_deliverables << d\n end\n end\n\n custom_deliverable_types.each do |custom|\n custom.deliverables.each do |d|\n project_phase_deliverables << d\n end\n end\n project_phase_deliverables\n end", "def amount_missing_on_deliverables\n # Bisect the issues because NOT IN isn't reliable\n all_issues = self.project.issues.all\n return 0 if all_issues.empty?\n\n deliverable_issues = self.project.issues.find(:all, :conditions => [\"deliverable_id IN (?)\", self.deliverables.collect(&:id)])\n\n missing_issues = all_issues - deliverable_issues\n\n time_logs = missing_issues.collect(&:time_entries).flatten\n \n return time_logs.collect(&:cost).sum\n end", "def hours_spent\n hours_spent = 0\n project_tasks.each do |project_task|\n hours_spent += project_task.hours_spent\n end\n hours_spent\n end", "def hours_planned\n hours_planned = 0\n project_tasks.each do |project_task|\n hours_planned += project_task.hours_planned\n end\n hours_planned\n end", "def spent\n self.deliverables.collect(&:spent).delete_if { |d| d.blank?}.inject { |sum, n| sum + n } || 0.0\n end", "def expense_by_party_and_line_item_subtype party, line_item_sub_type, invoiced=nil, document_id=nil\n sub_total = expense_subtotal_by_party(party)\n accum = Money.new(0)\n\n filter_invoiced(line_items, invoiced, document_id).select{|li| li.line_item_sub_type == line_item_sub_type}.each do |li|\n if li.after_subtotal\n\n if li.billable_party == party\n accum -= li.percentage_of_subtotal ? li.revenue_total_with_percentage(sub_total) : li.revenue_total\n end\n\n if li.payable_party == party\n accum += li.percentage_of_subtotal ? li.expense_total_with_percentage(sub_total) : li.expense_total\n end\n\n else\n\n if li.billable_party == party\n accum -= li.revenue_total\n end\n\n if li.payable_party == party\n accum += li.expense_total\n end\n \n end\n\n end\n accum\n end", "def project_costs(proj)\n Issue.cross_project_scope(proj, 'descendants')\n .select('spent_on, SUM(hours) AS sum_hours')\n .where(\"#{SQL_COM}\")\n .joins(:time_entries)\n .group(:spent_on)\n .collect { |issue| [issue.spent_on.to_date, issue.sum_hours] }\n end", "def amount_spent_on(project)\n self.expenses.where(:project_id => project.id).sum(:amount)\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 show\n @project_phase = ProjectPhase.find(params[:id])\n @lifecycle_phase = @project_phase.lifecycle_phase\n @project_phase_deliverables = []\n @project_phase.stock_deliverable_types.each do |stock|\n stock.deliverables.each do |d|\n @project_phase_deliverables << d\n end\n end\n\n @project_phase.custom_deliverable_types.each do |custom|\n custom.deliverables.each do |d|\n @project_phase_deliverables << d\n end\n end\n\n respond_to do |format|\n format.json { render :json => { :lifecycle_phase_container => @lifecycle_phase,\n :deliverables_container => @project_phase_deliverables,\n :project_phase_estimated_effort => @project_phase.estimated_effort,\n :project_phase_logged_effort => @project_phase.logged_effort} }\n end\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 charged_so_far\n charges = stages.collect{ |pr| pr.charged_so_far }.sum\n invoices.collect{ |inv| inv.total }.sum + charges\n end", "def revenue_by_party_and_line_item_subtype party, line_item_sub_type, invoiced=nil, document_id=nil\n sub_total = revenue_subtotal_by_party(party)\n accum = Money.new(0)\n\n filter_invoiced(line_items, invoiced, document_id).select{|li| li.line_item_sub_type == line_item_sub_type}.each do |li|\n if li.after_subtotal\n\n if li.billable_party == party\n accum += li.percentage_of_subtotal ? li.revenue_total_with_percentage(sub_total) : li.revenue_total\n end\n\n if li.payable_party == party\n accum -= li.percentage_of_subtotal ? -li.expense_total_with_percentage(sub_total) : li.expense_total\n end\n\n else\n\n if li.billable_party == party\n accum += li.revenue_total\n end\n\n if li.payable_party == party\n accum -= li.expense_total\n end\n \n end\n\n end\n accum\n end", "def timesheet_total_price(paied_actions = [])\n paied_actions.reject!(&:blank?)\n total_price = 0\n paied_actions.each do |paied_action|\n if paied_action.is_a? Numeric\n total_price += paied_action\n else\n paied_action.each do |act|\n total_price += price_sum(act)\n end\n end\n end\n total_price\n end", "def total_initial_investment\n fetch(:total_initial_investment) do\n if initial_investment.nil? && ccs_investment.nil? && cost_of_installing.nil? &&\n storage_costs&.zero? && capacity_costs&.zero?\n nil\n else\n (initial_investment || 0.0) +\n (ccs_investment || 0.0) +\n (cost_of_installing || 0.0) +\n (storage_costs || 0.0) +\n (capacity_costs || 0.0)\n end\n end\n end", "def invested(domain)\n #binding.pry\n funding_rounds.select{|fr| fr.startup.domain == domain}.map{|fr| fr.investment}.sum\n end", "def budget\n return self.deliverables.collect(&:budget).delete_if { |d| d.blank?}.inject { |sum, n| sum + n} || 0.0\n end", "def progress\n return 100 unless self.deliverables.size > 0\n return 100 if self.budget == 0.0\n \n balance = 0.0\n \n self.deliverables.each do |deliverable|\n balance += deliverable.budget * deliverable.progress\n end\n \n return (balance / self.budget).round\n end", "def consolidate_phase_trays(plans)\n tray_plans = []\n plans.each do |p|\n tp = tray_plans.detect { |x| x[:phase] == p[:phase] }\n if tp.present?\n tp[:quantity] += p[:quantity]\n tp[:trays] += p[:trays]\n else\n tray_plans << p\n end\n end\n tray_plans\n end", "def amount_missing_on_issues\n time_logs = TimeEntry.where(project_id: self.project.id)\n\n return time_logs.collect(&:cost).sum\n end", "def find_team_values\n #sets the total investments as an empty hash\n team_investments = {}\n #iterates through every team\n @teams.each do |team, value|\n #initializes the value for the team\n investment_values = 0\n #finds every investment for the team\n Investment.where(team_id: team.id).each do |i|\n #only adds the investment if it is in the selected quarter\n Feature.find(i.feature_id).quater == @quater ? investment_values += i.investment : a=0\n end\n team_investments[team.id] = investment_values\n end\n return team_investments\n end", "def update_invested\n self.invested_amount = self.investments.map(&:amount).sum\n self.goal_investment = 0 unless self.goal_investment\n self.equity_offered = 0 unless self.equity_offered\n self.save\n end", "def update_totals\n # update_adjustments\n self.payment_total = payments.completed.map(&:amount).sum\n self.item_total = line_items.map(&:amount).sum\n \n self.adjustment_total = adjustments.eligible.map(&:amount).sum\n self.total = item_total + adjustment_total + gift_packaging_total\n end", "def calculate_total_money_spent\n return @trips.inject(0.0) { |sum, trip|\n trip.is_in_progress? ? sum + 0 : sum + trip.cost }\n end", "def equip\n @project = Project.find(params[:id])\n @totprice=0\n @totsize=0\n @project.baskets.each do |p|\n if not p.equipment.price.nil? #if the basket equipment price is not nil\n @totprice=@totprice+(p.equipment.price*p.quantity) #add to the running total\n end\n if (not p.equipment.width.nil?) and (not p.equipment.depth.nil?) #if width and depth are not nil\n @totsize=@totsize+ (p.equipment.width*p.equipment.depth*p.quantity) #calculate total surface area and add to the running total\n end\n end\n \n @[email protected](2)\n @totprice=sprintf \"%.02f\", @totprice #display total price in currency format to 2 dp\n \n respond_to do |format|\n format.html # equip.html.erb\n format.json { render json: @project }\n \n end\n end", "def total_funds\n #binding.pry\n funding_rounds.map{|fr| fr.investment}.sum\n end", "def calc_need(assets)\n\n a = {}\n assets.find_each do |asset|\n # see if this asset sub type has been seen yet\n if a.has_key?(asset.asset_subtype)\n report_row = a[asset.asset_subtype]\n else\n report_row = AssetSubtypeReportRow.new(asset.asset_subtype)\n a[asset.asset_subtype] = report_row\n end\n # get the replacement cost for this item based on the current policy\n report_row.add(asset)\n end \n\n return a \n end", "def getDeveloperTaskEffort\r\n effortHash = {}\r\n\t#Read in the developers from theexcel sheet\r\n\tdevelopers = getUniqueColumnItems $ws1,$columnNumbers1[\"Developer\"],2,$validRow\r\n developers.each do |name|\r\n criterion = {$columnNumbers1[\"Effort\"] => /^\\s*\\d/i, $columnNumbers1[\"Developer\"] => /^\\s*#{name}/i, $columnNumbers1[\"Acceptence\"] => /^\\s*Yes/i}\r\n efforts = readColumnsCrieteria $ws1,$columnNumbers1[\"Normalised Effort\"],criterion,$validRow\r\n #Store the result in the hash\r\n\t\ttotalEffort = efforts.inject{|result,element| result + element} \r\n\t\t#Default values of zero\r\n\t\ttotalEffort = 0 unless totalEffort\r\n effortHash[name] = totalEffort\r\n end\r\n effortHash\r\nend" ]
[ "0.6394787", "0.62272865", "0.5798721", "0.56754416", "0.5484788", "0.5387674", "0.536942", "0.53105897", "0.52936953", "0.5292658", "0.52565676", "0.5237736", "0.51657087", "0.51464784", "0.51193655", "0.5102273", "0.50990856", "0.5075204", "0.5070166", "0.5062832", "0.50492275", "0.50472766", "0.5015658", "0.50116754", "0.5005082", "0.49914458", "0.49834132", "0.4958452", "0.49563697", "0.4953459" ]
0.7271085
0
function to get the total logged effort for this deliverable
def logged_effort total_logged_effort = 0 self.project_phase_deliverables.each do |deliverable| total_logged_effort += deliverable.logged_effort.to_f unless deliverable.nil? end return total_logged_effort end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def estimated_effort\n total_estimated_effort = 0\n\n self.project_phase_deliverables.each do |deliverable|\n total_estimated_effort += deliverable.estimated_effort.to_f unless deliverable.nil?\n end\n\n return total_estimated_effort\n end", "def total\n count = 0\n self.total_time_exercise_workouts.each do |ex|\n count += ex.duration\n end\n count\n end", "def amount_missing_on_deliverables\n # Bisect the issues because NOT IN isn't reliable\n all_issues = self.project.issues.all\n return 0 if all_issues.empty?\n\n deliverable_issues = self.project.issues.find(:all, :conditions => [\"deliverable_id IN (?)\", self.deliverables.collect(&:id)])\n\n missing_issues = all_issues - deliverable_issues\n\n time_logs = missing_issues.collect(&:time_entries).flatten\n \n return time_logs.collect(&:cost).sum\n end", "def total_sum()\n return self.work_packets.sum( :worked_hours )\n end", "def avarage_calories_burned\n total_workout_calories / set_sport_by_user.count\n rescue\n 0\n end", "def calculate_phase_actual_effort(project_id, phase)\n @hours = 0\n @dataset = Deliverable.find_all_by_phase_and_project_id(phase, project_id)\n puts @dataset\n if @dataset.nil?\n return 0\n else\n @dataset.each do |d|\n @hours += d.hours_logged\n end\n return @hours\n end\n end", "def total_workout_calories\n set_sport_by_user.sum(:burned_calories) || 0\n end", "def get_total_review_effort(issue)\n issue['fields']['customfield_10029'].to_f + issue['fields']['customfield_10034'].to_f + issue['fields']['customfield_10038'].to_f + issue['fields']['customfield_10105'].to_f + issue['fields']['customfield_10106'].to_f\n end", "def hours_planned\n hours_planned = 0\n project_tasks.each do |project_task|\n hours_planned += project_task.hours_planned\n end\n hours_planned\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 amount_missing_on_issues\n time_logs = TimeEntry.where(project_id: self.project.id)\n\n return time_logs.collect(&:cost).sum\n end", "def attack\n total_for(:attack) \n end", "def total_demand\n info[:total_demand]\n end", "def total_hours\n approved_flights.sum(:duration)\n end", "def budget\n return self.deliverables.collect(&:budget).delete_if { |d| d.blank?}.inject { |sum, n| sum + n} || 0.0\n end", "def total_impact\n component_total(components)\n end", "def spent\n self.deliverables.collect(&:spent).delete_if { |d| d.blank?}.inject { |sum, n| sum + n } || 0.0\n end", "def total_charged\n return self.trips.sum(&:cost)\n end", "def recent_goal_qty\n @recent_goal.stake_qty\n end", "def total_wait\n if cart.delivers\n if !cart.delivery_duration.blank?\n response = estimated_wait + cart.delivery_duration\n else\n response = estimated_wait + 20\n end\n else\n response = estimated_wait\n end\n\n return response\n end", "def progress\n return 100 unless self.deliverables.size > 0\n return 100 if self.budget == 0.0\n \n balance = 0.0\n \n self.deliverables.each do |deliverable|\n balance += deliverable.budget * deliverable.progress\n end\n \n return (balance / self.budget).round\n end", "def dps\n self.total_damage.to_f / self.encounter.duration_in_seconds\n end", "def last_workout_calories\n set_sport_by_user.last.try(:burned_calories) || 0\n end", "def total_owed\n self.appointments.sum(:cost)\n end", "def real_effort_now(date = Date.today)\n return 0 unless !real_hours.blank? && real_hours > 0\n self.task_progresses.where(\"working_day <= ?\", date).sum(:effort)\n end", "def display_total_calories_per_workout\n puts \"This workout will burn an average of #{self.total_calories} calories.\"\n end", "def get_total_duration\n @sport_duration = Sport.where(user_id: current_user.id).sum(:duration)\n end", "def labor_budget\n return self.deliverables.collect(&:labor_budget).delete_if { |d| d.blank?}.inject { |sum, n| sum + n} || 0.0\n end", "def daily_goals\n goals\n end", "def calculate_total_money_spent\n return @trips.inject(0.0) { |sum, trip|\n trip.is_in_progress? ? sum + 0 : sum + trip.cost }\n end" ]
[ "0.7250742", "0.6434303", "0.6432553", "0.6411589", "0.64055353", "0.6349569", "0.6248869", "0.6048537", "0.6018238", "0.5975668", "0.5954886", "0.5953312", "0.5903224", "0.5894547", "0.58932376", "0.58912987", "0.588154", "0.585457", "0.58411676", "0.583361", "0.58333963", "0.58215415", "0.58159196", "0.58124363", "0.580242", "0.57540727", "0.5741179", "0.57389295", "0.57388026", "0.5703248" ]
0.82118356
0
function to return the aggregated project phase deliverables with both stock and custom
def project_phase_deliverables project_phase_deliverables = [] stock_deliverable_types.each do |stock| stock.deliverables.each do |d| project_phase_deliverables << d end end custom_deliverable_types.each do |custom| custom.deliverables.each do |d| project_phase_deliverables << d end end project_phase_deliverables end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def deliverables\n return Deliverable.where(project_id: @project.id)\n end", "def getDeliverableTypes\n @projectPhase = ProjectPhase.find(@project_phase_id)\n @deliverableTypes = DeliverableType.find_all_by_lifecycle_phase_id(@projectPhase.lifecycle_phase_id)\n @deliverableTypesArray = []\n @deliverableTypes.each do |type|\n @deliverableTypesArray.append([type.name,type.id])\n end\n end", "def all_deliverables\n deliverables = self.deliverables.order(\"name ASC\")\n result = []\n deliverables.each do |deliverable|\n if deliverable.has_sub_item == true \n result << [ \"#{deliverable.name} -- SubItem: #{deliverable.sub_item_name} \"+\n \"-- Default SubItem Quantity: #{deliverable.sub_item_quantity} \"+\n \"-- Additional Extra SubItem Price: #{deliverable.independent_sub_item_price}\" , \n deliverable.id ]\n else\n result << [ \"#{deliverable.name}\" , \n deliverable.id ]\n end\n \n end\n return result\n end", "def all_deliverable_projects\n all_digest_projects\n end", "def pending_refund_payments_projects\n pending_refund_payments.map(&:project)\n end", "def portfolio\n funding_rounds.map{|fr| fr.startup}.uniq\n #binding.pry\n end", "def portfolio\n self.funding_rounds.map do |round|\n round.startup.uniq \n end\n end", "def portfolio\n funding_rounds.map{|funding| funding.startup}.uniq\n end", "def show\n @project_phase = ProjectPhase.find(params[:id])\n @lifecycle_phase = @project_phase.lifecycle_phase\n @project_phase_deliverables = []\n @project_phase.stock_deliverable_types.each do |stock|\n stock.deliverables.each do |d|\n @project_phase_deliverables << d\n end\n end\n\n @project_phase.custom_deliverable_types.each do |custom|\n custom.deliverables.each do |d|\n @project_phase_deliverables << d\n end\n end\n\n respond_to do |format|\n format.json { render :json => { :lifecycle_phase_container => @lifecycle_phase,\n :deliverables_container => @project_phase_deliverables,\n :project_phase_estimated_effort => @project_phase.estimated_effort,\n :project_phase_logged_effort => @project_phase.logged_effort} }\n end\n end", "def portfolio()\n # uniq_funding = self.funding_rounds().uniq\n # uniq_funding.map {|funding| funding.startup}\n startups = self.funding_rounds().map { |funding| funding.startup}\n startups.uniq \n end", "def portfolio\n funding_rounds.map {|funding_round| funding_round.startup}.uniq\n end", "def porfolio\n self.funding_rounds.collect do |funding_round|\n funding.round.startup\n end.uniq\nend", "def project_totals(from=7.days.ago, to=Date.today)\n @pt = []\n projects.each do |p|\n hrs = total_project_hours(p.id, from, to)\n @pt << [p.name, hrs] if hrs > 0\n end\n @pt\n end", "def projects_supported\n @pledges = Pledge.all\n project_list = {}\n @pledges.each do |pledge|\n if pledge.user_id == self.id\n if project_list.has_key?(pledge.project_id)\n project_list[pledge.project_id] += pledge.dollar_amount\n else\n project_list[pledge.project_id] = pledge.dollar_amount\n end\n end\n end\n return project_list\n end", "def portfolio\n arr = []\n FundingRound.all.select do |s|\n if s.venture_capitalist == self\n arr << s.startup.name\n end\n end\n arr.uniq\n end", "def project_all\n prj = { '_id' => 0 }\n prj.merge!(make_grp_prj_periods[1])\n prj.merge!(make_grp_prj_nodes[1])\n prj.merge!(project_bookingnet)\n prj.merge!(project_baselist) unless @sensitivity >= 2\n prj.merge!(project_standardcost) unless @sensitivity >= 1\n { '$project' => prj }\n end", "def products_billing_summary_by_stock(year)\n\n current_year = DateTime.now.year\n\n # Build the result holder\n total_cost = 0\n stock_items = if current_year == year\n ::Yito::Model::Booking::BookingItem.all(conditions: {active: true},\n fields: [:reference, :cost],\n order: [:category_code, :reference])\n else\n BookingDataSystem::Booking.historic_stock(year).map do |item|\n OpenStruct.new({reference: item.item_reference, cost: 0})\n end\n end\n\n summary = stock_items.inject({}) do |result, item|\n data_holder = {}\n (1..12).each { |item| data_holder.store(item, 0) }\n data_holder.store(:total, 0)\n data_holder.store(:cost, item.cost || 0)\n data_holder.store(:percentage, 0)\n total_cost = total_cost + item.cost unless item.cost.nil?\n result.store(item.reference, data_holder)\n result\n end\n data_holder = {}\n (1..12).each { |item| data_holder.store(item, 0) }\n data_holder.store(:total, 0)\n data_holder.store(:cost, 0)\n data_holder.store(:percentage, 0)\n summary.store(:TOTAL, data_holder)\n # Fill the data\n data = query_strategy.products_billing_summary_by_stock(year)\n data.each do |data_item|\n if summary.has_key?(data_item.reference)\n # stock\n summary[data_item.reference][data_item.period.to_i] = data_item.total_item_cost\n summary[data_item.reference][:total] += data_item.total_item_cost\n if summary[data_item.reference][:cost] and summary[data_item.reference][:cost] > 0\n summary[data_item.reference][:percentage] = summary[data_item.reference][:total] /\n summary[data_item.reference][:cost] * 100\n end\n # total\n summary[:TOTAL][data_item.period.to_i] += data_item.total_item_cost\n summary[:TOTAL][:total] += data_item.total_item_cost\n summary[:TOTAL][:cost] = total_cost\n if summary[:TOTAL][:cost] and summary[:TOTAL][:cost] > 0\n summary[:TOTAL][:percentage] = summary[:TOTAL][:total] /\n summary[:TOTAL][:cost] * 100\n end\n end\n end\n\n return summary\n end", "def find_company_projects_sum\n \t\t# returns a mapping [project name, client info, sum of hours, id]\n \t\tmy_company.projects.map{\n \t\t\t|p|[p.name, p.client, p.entries.reduce(0) do |sum, entry| \n \t\t\t\t\tsum = sum + entry.hours \n \t\t\t\tend, p.id\n \t\t\t]\n \t\t}\n \tend", "def combined_projects\n self.projects + self.owned_projects + self.all_teams.map(&:projects).flatten(1)\n end", "def get_pending_bucks\n\t\t\t jobcode = self.job_id\n\t\t\t approve_for = ::Department.where('bucks_approve1 = \\'' + jobcode + '\\' OR bucks_approve2 = \\'' + jobcode + '\\'')\n\t\t\t bucks = Array.new\n\t\t\t approve_for.each { |d| Buck.joins('INNER JOIN employees ON bucks_bucks.issuer_id = employees.IDnum WHERE employees.department_id = ' + d.id.to_s + ' AND bucks_bucks.status = \"Pending\"').each { |b| bucks.push(b) }}\n\t\t\t return bucks\n\t\t\t end", "def investors\n funds = []\n num_funding_rounds.each do |round| \n funds << round.venture_capitalist\n end\n funds.uniq\n end", "def project_costs(proj)\n Issue.cross_project_scope(proj, 'descendants')\n .select('spent_on, SUM(hours) AS sum_hours')\n .where(\"#{SQL_COM}\")\n .joins(:time_entries)\n .group(:spent_on)\n .collect { |issue| [issue.spent_on.to_date, issue.sum_hours] }\n end", "def consolidate_phase_trays(plans)\n tray_plans = []\n plans.each do |p|\n tp = tray_plans.detect { |x| x[:phase] == p[:phase] }\n if tp.present?\n tp[:quantity] += p[:quantity]\n tp[:trays] += p[:trays]\n else\n tray_plans << p\n end\n end\n tray_plans\n end", "def index\n @project_phase_deliverables = ProjectPhaseDeliverable.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @project_phase_deliverables }\n end\n end", "def investors\n array = FundingRound.all.select do |element|\n element.startup == self\n end\n array2 = array.map do |element|\n element.venture_capitalist\n end\n array2.uniq\n end", "def investors \n #traverse through all the rounds and identify the rounds related to this startup\n #traverse through the rounds and identify the investors \n #return a unique array \n funding_rounds = FundingRound.all.select do |round|\n round.startup == self \n end\n our_investors = funding_rounds.map do |round| \n round.venture_capitalist\n end\n our_investors.uniq\n end", "def index\n @project_phases = ProjectPhase.all\n end", "def display_pending_refund_payments_projects_name\n source.pending_refund_payments_projects.map(&:name).uniq\n end", "def all_expense_items\n owing_expense_items + paid_expense_items\n end", "def invested(domain)\n get_total_funds = portfolio.map do |startup| \n if startup.domain == domain\n startup.total_funds\n end\n end\n final_fund = get_total_funds.compact\n final_fund.inject{|sum, el| sum + el}\n end" ]
[ "0.65836674", "0.6328863", "0.6298275", "0.60927415", "0.60913974", "0.60671175", "0.6051786", "0.60024947", "0.59516114", "0.58622426", "0.5858245", "0.58278084", "0.57256776", "0.5671447", "0.56512403", "0.55656505", "0.554246", "0.5535978", "0.55007213", "0.54706866", "0.54595196", "0.54362434", "0.54050815", "0.5373351", "0.53617066", "0.5353884", "0.5347255", "0.53424895", "0.53227526", "0.5317603" ]
0.806633
0
gets the current theme or returns default if it comes back blank
def get_theme use_theme = Preference.get_setting('CURRENT_THEME') (use_theme == '' ? 'default' : use_theme).downcase end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def default_theme\n nil\n end", "def get_theme\n\t\tif @current_user and @current_user.theme\n\t\t\t@current_theme = @current_user.theme.css_class\n\t\telse\n\t\t\t@current_theme = \"pond\"\n\t\tend\n\tend", "def theme\n @theme || 'plastik'\n end", "def current_theme(passed_theme = nil)\n theme_name = unless passed_theme .blank?\n passed_theme\n else\n current_blog_user ? current_blog_user.blog_config.theme_name : ''\n end\n Theme.find(theme_name)\n end", "def theme\n return @theme\n end", "def current_theme(passed_theme = nil)\n @current_theme ||= get_current_theme(passed_theme)\n end", "def theme\n Design::Theme.array.find_by_name(self.theme_name) || site.theme\n end", "def current_theme\n account_prefix\n end", "def theme\n @theme\n end", "def current_theme(passed_theme=nil)\n theme = passed_theme || self.class.read_inheritable_attribute(\"theme\")\n \n @active_theme = case theme\n when Symbol then send(theme)\n when Proc then theme.call(self)\n when String then theme\n end\n end", "def theme\n options.fetch(:theme, nil)\n end", "def theme\n @theme ||= resource.cache.theme(theme_id)\n end", "def parent_theme\n ThemesForRails.config.parent_theme(current_theme)\n end", "def for_user(user)\n if user\n by_id(user.theme_id)\n else\n default\n end\n end", "def theme_name\n if params[:action] == \"home\"\n @theme_name = ThemeOption.where(user_id: current_user.id).first.template.downcase\n else\n \"application\"\n end\n end", "def theme_settings\n (settings_data ? settings_data['general'].presence : nil) || {}\n end", "def theme_name\n \n if params[:action] == \"home\"\n @theme_name = ThemeOption.where(user_id: current_user.id).first.template.downcase\n else\n \"application\"\n end\n end", "def theme; end", "def theme; end", "def theme; end", "def theme_resolver\n theme(current_account.account_prefix) if DmCore.config.enable_themes\n end", "def get_default\n if self.current_defaults\n self.current_defaults.first\n else\n raise \"Cette instance ne possède de #{self.class.name} par default\"\n end\n end", "def default_windowskin\n DEFAULT_SKIN\n end", "def theme=(_arg0); end", "def get_theme\n @theme = Broadcaster::Theme.find(params[:theme_id])\n end", "def get_theme\n @theme = Broadcaster::Theme.find(params[:theme_id])\n end", "def get_theme\n @theme = Broadcaster::Theme.find(params[:theme_id])\n end", "def by_id(id)\n THEMES.detect { |t| t.id == id } || default\n end", "def theme=(value)\n @theme = value\n end", "def theme_path\n \"#{ThemesForRails.config.themes_path}/#{current_theme}\"\n end" ]
[ "0.83288646", "0.79230934", "0.7906802", "0.78816706", "0.77404493", "0.7739274", "0.7630222", "0.75294083", "0.74879324", "0.73766637", "0.7246554", "0.70597017", "0.70159614", "0.67778724", "0.6729735", "0.65933573", "0.65707153", "0.6463578", "0.6463578", "0.6463578", "0.64244497", "0.6390925", "0.6381777", "0.63547724", "0.63489467", "0.63489467", "0.63489467", "0.63127965", "0.62844527", "0.62776816" ]
0.85378844
0
The value which is used for sorting. Used on the preset scenario list
def sorting_value respond_to?(:ordering) ? ordering : 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def valueOrder(obj)\n if obj.tutors.exists?\n obj.tutors.sort_by {|t| t.pname }.first.pname\n else\n \"_\"\n end\n end", "def default_sort_attribute\n ::Mincer.config.sorting.sort_attribute\n end", "def calculate_sort_value options\n dummy_time = dummy_time_for_day opening_hash(options['contract.default'])\n options['model'].sort_value = (dummy_time.to_f * 100).to_i\n end", "def sort_value_from_arg(arg) # :nodoc:\n case arg\n when /^asc/i\n arg = 1\n when /^desc/i\n arg = -1\n when Number\n arg.to_i >= 0 ? 1 : -1\n else\n arg ? 1 : -1\n end\n end", "def sort_key(value)\n @sort = value\n end", "def sort_by_default\n 1\n end", "def ordered_values; end", "def default_sort_order\n ::Mincer.config.sorting.order_attribute\n end", "def comparison_value\n return @comparison_value\n end", "def validate_sort_field( value )\n if [ 'title', 'code', 'created_at' ].include?( value )\n return value\n else\n return 'title'\n end\n end", "def sort\n self[:sort]\n end", "def default_sort_option\n\t\t'name'\n\tend", "def variant_column\n \"option_value_#{ order_in_good }\"\n end", "def sort\n return @sort\n end", "def sort_code()\n return @sort_code\n end", "def sort_order\n 0\n end", "def sort_option\n ['Best match', 'Level', 'Provider(s)']\n end", "def order\n @num\n end", "def calculate_sort_value\n return nil unless day\n dummy_time = dummy_time_for_day DAYS.index(day) + 1\n self.sort_value = (dummy_time.to_f * 100).to_i\n end", "def calculate_sort_value\n return nil unless day\n dummy_time = dummy_time_for_day DAYS.index(day) + 1\n self.sort_value = (dummy_time.to_f * 100).to_i\n end", "def order\n @order || \"99_99\"\n end", "def lbSortByValue _args\n \"lbSortByValue _args;\" \n end", "def current_sort_field_selected\n sort_field_from_response || # as in original\n sort_field_from_params || # sort param specified\n sort_field_from_list || # sort param not specified\n default_sort_field # falls back on 'relevance'\n end", "def sort_value(value)\n val = value.to_s.downcase\n return 1 if ASCENDING_CONVERSION.include?(val)\n return -1 if DESCENDING_CONVERSION.include?(val)\n raise InvalidSortValueError.new(\n \"#{self} was supplied as a sort direction when acceptable values are: \" +\n \"EM::Mongo::ASCENDING, 'ascending', 'asc', :ascending, :asc, 1, EM::Mongo::DESCENDING, \" +\n \"'descending', 'desc', :descending, :desc, -1.\")\n end", "def sort_text\n attributes.fetch(:sortText)\n end", "def value_index\n return nil unless self.value\n VALUES.index(self.value.downcase)\n end", "def sort_field(val = nil)\n if val == nil\n @sort_field || name\n else\n @sort_field = val\n end\n end", "def key_for_min_value\n end", "def set_Sort(value)\n set_input(\"Sort\", value)\n end", "def set_Sort(value)\n set_input(\"Sort\", value)\n end" ]
[ "0.6464138", "0.63776237", "0.63436735", "0.6317916", "0.6288007", "0.6167908", "0.61620027", "0.61186767", "0.6088003", "0.59630585", "0.5926655", "0.59065783", "0.58935887", "0.5840346", "0.58377767", "0.5814039", "0.5781655", "0.57744765", "0.57550967", "0.57550967", "0.5734756", "0.57306904", "0.5682885", "0.56593966", "0.56262475", "0.5620908", "0.5619797", "0.5618192", "0.56097305", "0.56097305" ]
0.65542465
0
Creates the four required columns that constitutes a single cascading namespace settings attribute. This helper is only appropriate if the setting is not already present as a noncascading attribute. Creates the `setting_name` column along with the `lock_setting_name` column in both `namespace_settings` and `application_settings`. This helper is not reversible and must be defined in conjunction with `remove_cascading_namespace_setting` in separate up and down directions. setting_name The name of the cascading attribute same as defined in `NamespaceSetting` with the `cascading_attr` method. type The column type for the setting itself (:boolean, :integer, etc.) options Standard Rails column options hash. Accepts keys such as `null` and `default`. `null` and `default` options will only be applied to the `application_settings` column. In most cases, a nonnull default value should be specified.
def add_cascading_namespace_setting(setting_name, type, **options) lock_column_name = "lock_#{setting_name}".to_sym check_cascading_namespace_setting_consistency(setting_name, lock_column_name) namespace_options = options.merge(null: true, default: nil) add_column(:namespace_settings, setting_name, type, **namespace_options) add_column(:namespace_settings, lock_column_name, :boolean, default: false, null: false) add_column(:application_settings, setting_name, type, **options) add_column(:application_settings, lock_column_name, :boolean, default: false, null: false) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setting_class\n @setting_class ||= case orm\n when :activerecord\n require 'settler/orm/activerecord/setting'\n Settler::ORM::Activerecord::Setting\n else\n require 'settler/orm/ruby/setting'\n Settler::ORM::Ruby::Setting\n end\n end", "def setting_params\n params.require(:setting).permit(:namespace, :value)\n end", "def setting(name)\n\t\t\tval = config.settings.where(\"name = ?\", name.to_s).first\n\t\t\tif val.nil?\n\t\t\t\tval = config.control_system.zones.joins(:settings).where('settings.name = ?', name.to_s).first\n\t\t\t\tval = val.settings.where(\"name = ?\", name.to_s).first unless val.nil?\n\t\t\t\t\n\t\t\t\tval = config.dependency.settings.where(\"name = ?\", name.to_s).first if val.nil?\n\t\t\tend\n\t\t\t\n\t\t\tif val.present?\n\t\t\t\tcase val.value_type\n\t\t\t\t\twhen 0\n\t\t\t\t\t\treturn val.text_value\n\t\t\t\t\twhen 1\n\t\t\t\t\t\treturn val.integer_value\n\t\t\t\t\twhen 2\n\t\t\t\t\t\treturn val.float_value\n\t\t\t\t\twhen 3\n\t\t\t\t\t\treturn val.datetime_value\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\treturn nil\n\t\tend", "def has_settings(*args)\n options = args.extract_options!\n attribute_name = args.shift || HasSettings.config[:settings_attribute_name]\n association_name = \"_#{attribute_name}\"\n class_name = options[:class_name] || HasSettings.config[:settings_class_name]\n \n has_many association_name.to_sym,\n :class_name => class_name,\n :as => :configurable,\n :dependent => :destroy\n \n define_method attribute_name do\n instance_variable_get(:\"@#{attribute_name.to_s}\") || instance_variable_set(:\"@#{attribute_name.to_s}\", SettingsAccessor.new(self, association_name.to_sym, options[:inherit]))\n end\n end", "def config_setting\n @config_access_name = \"config_setting\"\n @setting ||= Setting.new(ContainerAdapter.new(self))\n end", "def setting(setting_name)\n context = Config.find_in_hash(options, Keys::Options::CONTEXT)\n Config.find_in_hash(options, setting_name) ||\n Config.find_in_hash(user_config, [Keys::SETTINGS, context, setting_name]) ||\n Config.find_in_hash(user_config, [Keys::SETTINGS, setting_name]) ||\n Config.find_in_hash(defaults, setting_name)\n end", "def [](option_name)\n # :full_table_name will be generated on first request\n generate_full_name if option_name == :full_table_name && !configuration[:full_table_name]\n configuration[option_name]\n end", "def settings=(setting_options = [])\n # for arrays, set in raw form \n @settings = if setting_options.is_a?(Array)\n setting_options\n # set optional shortcuts for settings\n # :keyword_match_setting => { :opt_in => false } # =>\n # { :xsi_type => 'KeywordMatchSetting', :opt_in => false }\n elsif setting_options.is_a?(Hash)\n setting_options.map do |key, values|\n { :xsi_type => key.to_s.camelcase }.merge(values).symbolize_keys\n end\n end\n end", "def wrap_at=(setting)\n @wrap_at = setting == :auto ? output_cols : setting\n end", "def setting_name\n return @setting_name\n end", "def metadata(setting)\n if setting.is_a?(Puppet::Settings::FileSetting)\n {\n :owner => setting.owner,\n :group => setting.group,\n :mode => setting.mode\n }.delete_if { |key, value| value.nil? }\n else\n nil\n end\n end", "def set_setting_type\n @setting_type = SettingType.find(params[:id])\n end", "def table_setting_params\n params.require(:table_setting).permit(:table_name, :column_name, :attribute, :standard, :use, :custom_name_ja, :custom_name_en, :description_ja, :description_en, :required, :default, :sys_lower, :sys_high, :custom_lower, :custom_high, :format, :currency, :order_input, :order_list, :order_result)\n end", "def setting_params\n params.require(:setting).permit(:name, :description, :enabled,\n :tick_types_attributes => [:name, :description, :setting_id],\n :cross_types_attributes => [:name, :description, :setting_id],\n :qa_settings_attributes => [:name, :setting_id, :team_id, :description, :out_of, :qa, :position],\n :qa_general_settings_attributes => [:name, :value, :team_id, :disabled]\n )\n end", "def setting_params\n params.require(:setting).permit(:data_type, :key, :value)\n end", "def create_setting(setting, opts = {})\n create_setting_with_http_info(setting, opts)\n nil\n end", "def setting_type_params\n params.require(:setting_type).permit(:name, :description)\n end", "def setting(name, type=:object, default=nil)\n item = Item.new\n item.name, item.ruby_type, item.default = name.to_s, type, default\n fields[name.to_s] = item\n add_setting_accessor(item)\n end", "def set_standard_defaults( opts = self.opts )\n\n # We set NOT NULL on everything by default, but note the ?\n # syntax (like Text?) which declares the column as NULL.\n\n set_defaults :global, :null => false\n\n # We also like our keys unsigned, so we allow setting that, too.\n # Unfortunately, :unsigned currently works only with :integer,\n # not the default :Integer, and :integer can't be specified for compound keys,\n # so we have to use the callback to set the type only at correct times.\n # Furthermore, Postgres's autoincrementing serials only work with Integer,\n # so we set the type only as long as the unsigned keys are requested.\n\n unsigned_keys = !! opts[ :unsigned_keys ]\n\n set_defaults :Key, :integer, :unsigned => unsigned_keys\n set_defaults :primary_key, :unsigned => unsigned_keys do |opts,args,table|\n opts[ :type ] ||= :integer unless args.first.is_a? Array or not opts[ :unsigned ]\n end\n set_defaults :foreign_key, :key => :id, :unsigned => unsigned_keys do |opts,args,table|\n opts[ :type ] ||= :integer unless args.first.is_a? Array or not opts[ :unsigned ]\n end\n\n # Save some typing for unique and fulltext indexes.\n\n set_defaults :unique, :index, :unique => true\n set_defaults :fulltext, :index, :type => :full_text do |opts,args,table|\n opts[ :name ] ||= [ table, *args, :fulltext ].join( '_' ).to_sym\n end\n\n # Type shortcuts we use frequently.\n\n set_defaults :Bool, :TrueClass\n set_defaults :True, :TrueClass, :default => true\n set_defaults :False, :TrueClass, :default => false\n\n set_defaults :Signed, :integer, :unsigned => false\n set_defaults :Unsigned, :integer, :unsigned => ! opts[ :signed_unsigned ]\n\n set_defaults :String, :text => false\n set_defaults :Text, :String, :text => true\n\n # We want times to be stored as 4 byte timestamps, however\n # we have to be careful to turn off the MySQL autoupdate behavior.\n # That's why we have to set defaults explicitly.\n\n default_time = ( opts[ :zero_timestamps ] || ( opts[ :mysql_timestamps ] && opts[ :zero_timestamps ].nil? ) ) ? ZERO_TIME : DEFAULT_TIME\n set_defaults :Time, :timestamp, :default => default_time\n set_defaults :Time?, :timestamp, :default => nil\n\n self\n end", "def call\n setting_item = build_setting_item(name, type, default)\n register_setting setting_item\n define_setting setting_item\n setting_item\n end", "def setting_name=(value)\n @setting_name = value\n end", "def create_setting\n if setting_options.is_a?(Hash)\n setting_options[:options][:validations] = setting_options[:validations]\n setting = Supports::Settingable::Models::Setting.new name: setting_options[:name]\n setting.options = setting_options[:options]\n setting.settingable= self\n setting.save\n end\n end", "def buildtype_settings(options={})\n assert_options(options)\n response = get(\"buildTypes/#{locator(options)}/settings\")\n response['property']\n end", "def locking_column=(value)\n reload_schema_from_cache\n @locking_column = value.to_s\n end", "def setting_params\n params.require(:setting).permit!\n end", "def settings_for_node\n cluster_name = self.parent.name.to_sym\n cluster_role = self.name.to_sym\n node_settings = {\n :user_data => { :attributes => { :run_list => [] } },\n :cluster_name => cluster_name,\n :cluster_role => cluster_role,\n }.deep_merge(Settings)\n node_settings.delete :pools\n raise \"Please define the '#{cluster_name}' cluster and the '#{cluster_role}' role in your ~/.chef/cluster_chef.yaml\" if (Settings[:pools][cluster_name].blank? || Settings[:pools][cluster_name][cluster_role].blank?)\n node_settings = node_settings.deep_merge(\n Settings[:pools][cluster_name][:common] ||{ }).deep_merge(\n Settings[:pools][cluster_name][cluster_role] ||{ })\n configure_aws_region node_settings\n node_settings\nend", "def settings\n @settings ||= OpenStruct.new(opts[:dm_config].first)\n # dm_js_location, dm_css_location\n # dm_js_location: javascripts\n # dm_css_location: stylesheets\n end", "def setting_params\n params.require(:setting).permit(:name, :value)\n end", "def ensure_setting\n self.setting ||= Setting.build_default(self)\n end", "def setting(name)\n @settings[normalize_key(name)]\n end" ]
[ "0.49649224", "0.4823334", "0.47971034", "0.46413702", "0.4559991", "0.4529144", "0.45199347", "0.450397", "0.44972235", "0.44927645", "0.44905928", "0.44677636", "0.44619715", "0.44599438", "0.44313174", "0.4407542", "0.43775278", "0.43568566", "0.4345559", "0.43305054", "0.43201193", "0.4318149", "0.43176955", "0.4294976", "0.42422625", "0.42403355", "0.42124623", "0.4211681", "0.4204287", "0.420266" ]
0.80753994
0
Because pagy gem method pagy_next_url return url base on request url, but sometime we want specify base url. So this is what this method doing.
def next_url_for_path(path, pagy) return unless pagy.next url = URI.parse(path); url_query = Rack::Utils.parse_query url.query url.query = Rack::Utils.build_query url_query.merge(pagy.vars[:page_param].to_s => pagy.next) url.to_s end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def next_page_url\n \"#{request.path}?page=#{@page + 1}\"\n end", "def next_url_str\n \"#{@url_base_str}?#{QUERY_STRING_PART1}&#{@query_str_next_page}\"\n end", "def next_page_path; end", "def next_page_url\n current_page = params[:page].try(:to_i) || 1\n if request.path.match /\\/page\\/(\\d+)/\n request.path.gsub(/\\/page\\/(\\d+)$/, \"/page/#{current_page+1}\")\n else\n \"#{request.path}/page/#{current_page+1}\"\n end\n end", "def pagy_url_for(page, pagy)\n params = request.query_parameters.merge(:only_path => true, pagy.vars[:page_param] => page )\n url_for(params)\n end", "def next_page; end", "def next_page_path(response)\n response.get(\"_links.next.href\")\n end", "def paginable_base_url(page = 1)\n return url_for(@paginable_path_params.merge({ controller: @paginable_params[:controller],\n action: @paginable_params[:action], page: page }))\n end", "def paginable_base_url(page = 1)\n @args = @args.with_indifferent_access\n url_params = @paginable_path_params.merge(\n controller: @args[:controller],\n action: @args[:action],\n page: page\n )\n url_for(url_params)\n end", "def next_page\n end", "def get_next_url\n @index = @index + 1\n link = @url.to_s + \"?PageNumber=\"\n link = link + @index.to_s\n \n return link\nend", "def get_next_url\n @index = @index + 1\n link = @url.to_s + \"?PageNumber=\"\n link = link + @index.to_s\n \n return link\nend", "def next_page; link 'next' end", "def get_next_url\n\n @index = @index + 1\n\n link = @url.to_s + \"?PageNumber=\"\n\n link = link + @index.to_s\n\n return link\n\nend", "def get_next_url\n\n @index = @index + 1\n\n link = @url.to_s + \"?PageNumber=\"\n\n link = link + @index.to_s\n\n return link\n\nend", "def next_page_link\n paging['next'] if paging\n end", "def url(page)\n if self.class.base_url.blank?\n return super(page)\n else\n url_params = {}\n add_current_page_param(url_params, page)\n ret = @template.url_for(url_params)\n \"#{self.class.base_url}?#{ret.split('?')[-1]}\"\n end\n end", "def url(page)\n if self.class.base_url.blank?\n return super(page)\n else\n url_params = {}\n add_current_page_param(url_params, page)\n ret = @template.url_for(url_params)\n \"#{self.class.base_url}?#{ret.split('?')[-1]}\"\n end\n end", "def next_url(page_number)\n onliner_url.gsub(/page=\\d{1,}/, \"page=#{page_number + 1}\")\n end", "def next\n perform_request(next_page_uri) if next?\n end", "def next_page\n pagination_adapter.next_page\n end", "def next_page(extra_params = {})\n base, args = next_page_params\n base ? @api.get_page([base, args.merge(extra_params)]) : nil\n end", "def next_page!\n page = @doc.css(\".paginator span.pagination_current\").first\n @next_page = page.next_element[\"href\"] if page\n on_url(@next_page) if @next_page\n end", "def next_page\n # The only difference from the default here is we renamed the link to \"More\"\n # and added a custom class, twitter_pagination\n previous_or_next_page(@collection.next_page, '<div class=\"hover-move\"><img src=\"assets/next.png\" alt=\"next\"/></div><img src=\"assets/barre.png\"/>', 'next_pagination') if @collection.next_page\n end", "def url_for_pagination(page, path = request.path, q = request.query_string)\n # Remove any current reference to page in the query string\n q = q.to_s.gsub(/page=(-?[\\d]+)(&?)/, '')\n # Assemble new link\n link = \"#{path}?page=#{page}&#{q}\"\n link = link[0..-2] if link[-1..-1] == '&' # Strip trailing ampersand\n link\n end", "def parse\n super\n if next_page_url\n @doc = get_document(URI(next_page_url))\n self.parse\n end\n self\n end", "def page_url\n page_value = @current_page == 1 ? 0 : @current_page\n \"#{URL}?page=#{page_value}\"\n end", "def next_page(params = nil)\n perform_request(@next_page_link)\n end", "def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape(url)\n next_link = page.xpath(\".//a[@title='Go to next page']\")\n puts next_link\n if next_link && next_link[0]\n puts next_link[0]['href']\n next_url = BASE_URL + next_link[0]['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend", "def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape(url)\n next_link = page.xpath(\".//a[@title='Go to next page']\")\n puts next_link\n if next_link && next_link[0]\n puts next_link[0]['href']\n next_url = BASE_URL + next_link[0]['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend" ]
[ "0.7240253", "0.72379565", "0.71005315", "0.6989908", "0.6839695", "0.674903", "0.66792136", "0.6646795", "0.6597067", "0.6586699", "0.6576461", "0.6576461", "0.65652233", "0.65496325", "0.65496325", "0.6504919", "0.6459087", "0.6459087", "0.6455604", "0.6445155", "0.6340858", "0.63215375", "0.63194704", "0.6291469", "0.6264292", "0.62584305", "0.6257434", "0.6207741", "0.6199298", "0.6199298" ]
0.73391056
0
GET /magic_item_names GET /magic_item_names.json
def index @magic_item_names = MagicItemName.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_item_names\n items = []\n Static.get_item_list.values.each do |f|\n items << f[\"name\"]\n end\n items\n end", "def name_list\n begin\n @products = Product.pluck(:name)\n render json: { names: @products }, status: 200\n rescue => exception\n render json: { errors: exception }\n end\n end", "def names\n get('names')\n end", "def index\n @material_item_names = MaterialItemName.all\n end", "def names()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Names::NamesRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def index\n @magic_items = MagicItem.all.sort_by(&:name)\n end", "def item_name\n params['item_name']\n end", "def index\n @item_selected_names = ItemSelectedName.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @item_selected_names }\n end\n end", "def do_names\n animal_list = get_names()\n print_names(animal_list)\n end", "def name\n Item.find(item_id).name\n end", "def name\n Item.find(item_id).name\n end", "def find_names(names)\n query = names.to_query('displayName').delete('%5B%5D') # delete '[]'\n uri = URI.parse(\"https://developer-paragon.epicgames.com/v1/accounts/find?#{query}\")\n request = Net::HTTP::Get.new(uri)\n request.add_field(\"X-Epic-ApiKey\", ENV[\"API_KEY\"])\n\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n response = http.request(request)\n return JSON.parse response.body\n end", "def gather_names(item:)\n names = []\n return names unless item.present? && item.is_a?(Hash)\n\n names << item[:domain] if item[:domain].present?\n names << item[:aliases] if item[:aliases].present?\n names << item[:acronyms] if item[:acronyms].present?\n item.fetch(:labels, []).map { |hash| names << hash[:label] }\n names.flatten.compact.uniq\n end", "def products_by_name\n render json: Product.where(\"name LIKE ? OR name LIKE ?\", \"#{params[:name]}%\", \"%#{params[:name]}%\").offset(params[:offset]).limit(20).map(&:simple_info), status: :ok\n end", "def named(name)\n # do we need to modify the json\n # url_char_name = name.gsub!(' ','+')\n url_char_name = name.gsub(' ','+')\n self.class.get(\"/cards/named?fuzzy=#{url_char_name}\")\n end", "def item\n # Url generated from Js script function => getitem() of _form.html.erb file under Views of different controllers\n @item = Report.where(\"user_id = ?\" , current_user.id).pluck(:item_name )\n # send item_names' in form of json\n render json: @item\n end", "def get_names\n @names\n end", "def collection_names\n response = RequestResponse.new\n name_resp = collections_info.defer_as_a\n name_resp.callback do |docs|\n names = docs.collect{ |doc| doc['name'] || '' }\n names = names.delete_if {|name| name.index(self.name).nil? || name.index('$')}\n names = names.map{ |name| name.sub(self.name + '.','')}\n response.succeed(names)\n end\n name_resp.errback { |err| response.fail err }\n response\n end", "def name\n metadata['itemName'] rescue nil\n end", "def get_names(spicy_foods)\n spicy_foods.map { |spicy_food_hash| spicy_food_hash[:name] }\nend", "def list\n dispensaries = Dispensary.find(:all, :conditions => [\"name like ?\", params[:term]+\"%\"])\n result = []\n \n for d in dispensaries\n result << d.name\n end\n \n render(:json => result)\n end", "def set_magic_item_name\n @magic_item_name = MagicItemName.find(params[:id])\n end", "def list_names # :nologin:\n query = create_query(:Name, :all, :by => :name)\n show_selected_names(query)\n end", "def getItemList(name, vault = \"Private\")\n regex = %r{#{name}}i\n all = self.op \"list\", \"items\", \"--vault\", vault\n arr = all.select{|i| regex.match?(i[\"overview\"][\"title\"])}\n return_arr = []\n if arr.class == Array\n arr.each do |item|\n return_arr << item[\"overview\"][\"title\"]\n end\n end\n return_arr\n end", "def show\n @itemname = Itemname.find(params[:id])\n @locations = Location.all\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @itemname }\n end\n end", "def names(ids, optional={})\n region = optional[:region] || @sightstone.region\n ids = ids.join(',')\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids}/name\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n\n names_hash = Hash.new\n data.each do |id, name|\n names_hash[id.to_i] = name\n end\n if block_given?\n yield names_hash\n else\n return names_hash\n end\n }\n end", "def list_items\r\n list = \"\"\r\n items.each{ |item| list = list + item.name + \"\\n\"}\r\n list\r\n end", "def get_character_names\n\t\t\tget_all_character_uris.map { |uri| get_character_name(json(uri)) }\n end", "def cmd_people_names\n\t\tquery_json do\n\t\t\t\"SELECT DISTINCT ?name\n\t\t\tWHERE {\n\t\t\t\t?p a foaf:Person .\n\t\t\t\t?p foaf:name ?name .\n\t\t\t}\n\t\t\tORDER BY ?name\"\n\t\tend\n\tend", "def ids_names(items)\n\t\titems.reject(&:new_record?).collect {|item| {id: item.id, name: item.name.html_escape}}\n\tend" ]
[ "0.73406905", "0.67368335", "0.66846734", "0.65237606", "0.63395196", "0.63226616", "0.63028604", "0.6240045", "0.61300594", "0.60667986", "0.60667986", "0.60496145", "0.60417163", "0.59857535", "0.5984824", "0.59831995", "0.59586614", "0.5957465", "0.5909478", "0.58989453", "0.5883512", "0.58757055", "0.58665556", "0.58541787", "0.5836733", "0.58126855", "0.58042794", "0.5738751", "0.5734868", "0.5733761" ]
0.7702119
0
POST /magic_item_names POST /magic_item_names.json
def create @magic_item_name = MagicItemName.new(magic_item_name_params) respond_to do |format| if @magic_item_name.save format.html { redirect_to @magic_item_name, notice: 'Magic item name was successfully created.' } format.json { render :show, status: :created, location: @magic_item_name } else format.html { render :new } format.json { render json: @magic_item_name.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @magic_item_names = MagicItemName.all\n end", "def magic_item_name_params\n params.require(:magic_item_name).permit(:name, :affix)\n end", "def item_name\n params['item_name']\n end", "def set_magic_item_name\n @magic_item_name = MagicItemName.find(params[:id])\n end", "def update_names\n\t\tparams[:item].each do |key, item|\n\t\t\tcurrent_item = Item.find(key)\n\t\t\tcurrent_item.update(:claimed_by => item[:claimed_by])\n\t\tend\n\t\tflash[:success] = \"Names updated.\"\n\t\tredirect_to(:back)\n\tend", "def material_item_name_params\n params.require(:material_item_name).permit(:material_item_id, :name, :name_type_id)\n end", "def get_item_names\n items = []\n Static.get_item_list.values.each do |f|\n items << f[\"name\"]\n end\n items\n end", "def ids_names(items)\n\t\titems.reject(&:new_record?).collect {|item| {id: item.id, name: item.name.html_escape}}\n\tend", "def create\n @request_item = RequestItem.new(request_item_params)\n @request_item.item = Item.new(name: params[:request_item][:item][:name])\n\n if @request_item.save\n render json: @request_item \n else\n render json: @request_item.errors, status: :bad_request\n end\n end", "def create\n item = list.items.create!(item_params)\n render json: item, status: 201\n end", "def names()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Names::NamesRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def item_params\n params.require(:item).permit(:name)\n end", "def item_params\n params.require(:item).permit(:name)\n end", "def name_list\n begin\n @products = Product.pluck(:name)\n render json: { names: @products }, status: 200\n rescue => exception\n render json: { errors: exception }\n end\n end", "def change_item_name(new_name:, **)\n self.name = new_name # This will generate the event!\n end", "def item_params\n params.permit(:name)\n end", "def create\n create_params = item_params\n item = Item.new(\n name: create_params[:name], \n is_complete: false, #create_params[:is_complete], \n list_id: create_params[:list_id])\n\n item.save!\n render json: item\n end", "def test_create_name_with_quotes\n name = 'Foo \"bar\" Author'\n params = {\n :id => observations(:coprinus_comatus_obs).id,\n :name => { :name => name },\n :approved_name => name\n }\n login(\"dick\")\n post(:create_naming, params)\n assert_response(:success) # really means failed\n assert(name = Name.find_by_text_name('Foo \"bar\"'))\n assert_equal('Foo \"bar\" Author', name.search_name)\n end", "def test_create_name_with_quotes\n name = 'Foo \"bar\" Author'\n params = {\n :id => observations(:coprinus_comatus_obs).id,\n :name => { :name => name },\n :approved_name => name\n }\n login(\"dick\")\n post(:create_naming, params)\n assert_response(:success) # really means failed\n assert(name = Name.find_by_text_name('Foo \"bar\"'))\n assert_equal('Foo \"bar\" Author', name.search_name)\n end", "def update\n respond_to do |format|\n if @magic_item_name.update(magic_item_name_params)\n format.html { redirect_to @magic_item_name, notice: 'Magic item name was successfully updated.' }\n format.json { render :show, status: :ok, location: @magic_item_name }\n else\n format.html { render :edit }\n format.json { render json: @magic_item_name.errors, status: :unprocessable_entity }\n end\n end\n end", "def gather_names(item:)\n names = []\n return names unless item.present? && item.is_a?(Hash)\n\n names << item[:domain] if item[:domain].present?\n names << item[:aliases] if item[:aliases].present?\n names << item[:acronyms] if item[:acronyms].present?\n item.fetch(:labels, []).map { |hash| names << hash[:label] }\n names.flatten.compact.uniq\n end", "def rename_fs_item\n\n err_str = ''\n begin # a one time loop to allow break\n \n new_name = params[:name]\n if ( new_name.blank? )\n err_str = 'Empty name not allowed'\n break\n end\n \n generic_ty = Integer(params[:sel_kind]) rescue generic_ty = FSTYPE_INVALID\n elem_id = Integer(params[:sel_id]) rescue elem_id = -1\n if ( elem_id <= 0 )\n err_str = 'Invalid index'\n break\n end\n \n if ( generic_ty == FSTYPE_FILE )\n to_upd = Dfile.find_by_id( elem_id )\n if ( to_upd )\n to_upd.name = new_name\n if to_upd.save\n reponse = { action_id: params[:action_id],\n new_id: to_upd.id,\n new_name: to_upd.name,\n parent_id: to_upd.directory_id,\n kind_name: 'generic'\n }\n render :json => reponse, :layout => false, :status => 200 and return\n else\n err_str = 'Failed to save file name'\n break\n end\n else\n err_str = 'File does not exist'\n break\n end\n elsif ( generic_ty == FSTYPE_DIR )\n to_upd = Directory.find_by_id( elem_id )\n if ( to_upd )\n to_upd.name = new_name\n if to_upd.save\n reponse = { action_id: params[:action_id],\n new_id: to_upd.id,\n new_name: to_upd.name,\n parent_id: to_upd.parent_id,\n kind_name: 'directory'\n }\n render :json => reponse, :layout => false, :status => 200 and return\n else\n err_str = 'Failed to save directory'\n break\n end\n else\n err_str = 'Directory does not exist'\n break\n end\n else\n err_str = 'Invalid entry type'\n break\n end\n \n end until true # a one time loop to allow break\n render json: err_str, status: :unprocessable_entity and return\n end", "def do_names\n animal_list = get_names()\n print_names(animal_list)\n end", "def create_items\n @items.each do |item|\n create_item(item) unless Item.where(name: item['name']).first\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 create\n @locations = Location.all\n @itemname = Itemname.new(params[:itemname])\n\n respond_to do |format|\n if @itemname.save\n format.html { redirect_to @itemname, notice: 'Item creado.' }\n format.json { render json: @itemname, status: :created, location: @itemname }\n else\n format.html { render action: \"new\" }\n format.json { render json: @itemname.errors, status: :unprocessable_entity }\n end\n end\n end", "def item\n # Url generated from Js script function => getitem() of _form.html.erb file under Views of different controllers\n @item = Report.where(\"user_id = ?\" , current_user.id).pluck(:item_name )\n # send item_names' in form of json\n render json: @item\n end", "def item_name=(name)\n self.item_id = Item.find_by(name: name).id if name.present?\n end", "def create\n @material_item_name = MaterialItemName.new(material_item_name_params)\n\n respond_to do |format|\n if @material_item_name.save\n format.html { redirect_to @material_item_name, notice: 'Material item name was successfully created.' }\n format.json { render :show, status: :created, location: @material_item_name }\n else\n format.html { render :new }\n format.json { render json: @material_item_name.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @magic_item = MagicItem.new(magic_item_params)\n\n respond_to do |format|\n if @magic_item.save\n format.html { redirect_to @magic_item, notice: 'Magic item was successfully created.' }\n format.json { render :show, status: :created, location: @magic_item }\n else\n format.html { render :new }\n format.json { render json: @magic_item.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.65030557", "0.64285296", "0.6226741", "0.61364675", "0.59521884", "0.58190954", "0.5768685", "0.5681343", "0.56139356", "0.5612835", "0.5602044", "0.55766296", "0.55756", "0.55729985", "0.5565371", "0.5503138", "0.548819", "0.5464174", "0.5464174", "0.54093695", "0.53995", "0.5398434", "0.53883445", "0.53805864", "0.53731656", "0.5368314", "0.5362268", "0.5358181", "0.534123", "0.5332398" ]
0.6748295
0
PATCH/PUT /magic_item_names/1 PATCH/PUT /magic_item_names/1.json
def update respond_to do |format| if @magic_item_name.update(magic_item_name_params) format.html { redirect_to @magic_item_name, notice: 'Magic item name was successfully updated.' } format.json { render :show, status: :ok, location: @magic_item_name } else format.html { render :edit } format.json { render json: @magic_item_name.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_names\n\t\tparams[:item].each do |key, item|\n\t\t\tcurrent_item = Item.find(key)\n\t\t\tcurrent_item.update(:claimed_by => item[:claimed_by])\n\t\tend\n\t\tflash[:success] = \"Names updated.\"\n\t\tredirect_to(:back)\n\tend", "def set_magic_item_name\n @magic_item_name = MagicItemName.find(params[:id])\n end", "def update\n\n #update the item of request_item\n if (params[:request_item].present?)\n @request_item.item = params[:request_item][:item].present? ? Item.new(name: params[:request_item][:item][:name]) : @request_item.item\n end\n #update all other parameters\n if @request_item.update(request_item_params)\n render json: @request_item\n else\n render json: @request_item.errors, status: :bad_request\n end\n\n end", "def update\n @itemname = Itemname.find(params[:id])\n\n respond_to do |format|\n if @itemname.update_attributes(params[:itemname])\n format.html { redirect_to @itemname, notice: 'Item actualizado.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @itemname.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @magic_item.update(magic_item_params)\n format.html { redirect_to @magic_item, notice: 'Magic item was successfully updated.' }\n format.json { render :show, status: :ok, location: @magic_item }\n else\n format.html { render :edit }\n format.json { render json: @magic_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Item.update(params[\"id\"], params[\"item\"])\n end", "def rename_fs_item\n\n err_str = ''\n begin # a one time loop to allow break\n \n new_name = params[:name]\n if ( new_name.blank? )\n err_str = 'Empty name not allowed'\n break\n end\n \n generic_ty = Integer(params[:sel_kind]) rescue generic_ty = FSTYPE_INVALID\n elem_id = Integer(params[:sel_id]) rescue elem_id = -1\n if ( elem_id <= 0 )\n err_str = 'Invalid index'\n break\n end\n \n if ( generic_ty == FSTYPE_FILE )\n to_upd = Dfile.find_by_id( elem_id )\n if ( to_upd )\n to_upd.name = new_name\n if to_upd.save\n reponse = { action_id: params[:action_id],\n new_id: to_upd.id,\n new_name: to_upd.name,\n parent_id: to_upd.directory_id,\n kind_name: 'generic'\n }\n render :json => reponse, :layout => false, :status => 200 and return\n else\n err_str = 'Failed to save file name'\n break\n end\n else\n err_str = 'File does not exist'\n break\n end\n elsif ( generic_ty == FSTYPE_DIR )\n to_upd = Directory.find_by_id( elem_id )\n if ( to_upd )\n to_upd.name = new_name\n if to_upd.save\n reponse = { action_id: params[:action_id],\n new_id: to_upd.id,\n new_name: to_upd.name,\n parent_id: to_upd.parent_id,\n kind_name: 'directory'\n }\n render :json => reponse, :layout => false, :status => 200 and return\n else\n err_str = 'Failed to save directory'\n break\n end\n else\n err_str = 'Directory does not exist'\n break\n end\n else\n err_str = 'Invalid entry type'\n break\n end\n \n end until true # a one time loop to allow break\n render json: err_str, status: :unprocessable_entity and return\n end", "def update\n item = Item.find(params[:item_id])\n\n item.name = params[:name]\n item.details = params[:details]\n item.save\n end", "def update_item(list_name, item_name, quantity)\r\n list_name[item_name] = quantity if list_name.has_key?(item_name)\r\nend", "def update\n respond_to do |format|\n if @material_item_name.update(material_item_name_params)\n format.html { redirect_to @material_item_name, notice: 'Material item name was successfully updated.' }\n format.json { render :show, status: :ok, location: @material_item_name }\n else\n format.html { render :edit }\n format.json { render json: @material_item_name.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_item(item_id)\n request_body = {\n 'name' => 'Malted Milkshake'\n }\n\n response = Unirest.put CONNECT_HOST + '/v1/' + LOCATION_ID + '/items/' + item_id,\n headers: REQUEST_HEADERS,\n parameters: request_body.to_json\n\n if response.code == 200\n puts 'Successfully updated item:'\n puts JSON.pretty_generate(response.body)\n return response.body\n else\n puts 'Item update failed'\n puts response.body\n return nil\n end\nend", "def update\n json_response(@food_item.update!(food_item_params))\n end", "def rename(id, name = \"\")\n item = Item.find(id)\n item.class == Item ? item.update(:name => name) : item\n end", "def update\n respond_to do |format|\n if @catalog_item.update(name: params[:name], description: params[:description])\n format.json { render json: @catalog_item }\n end\n end\n end", "def update_name(new_name)\n ensure_uri\n response = @client.rest_put(@data['uri'], 'body' => { 'name' => new_name, 'type' => 'ArtifactsBundle' })\n @client.response_handler(response)\n @data['name'] = new_name\n true\n end", "def change_item_name(new_name:, **)\n self.name = new_name # This will generate the event!\n end", "def update_qty(list_items, item_name, new_qty)\n raise ArguementError.new(\"This item does not exist\") unless list_items.include?(item_name)\n list_items[item_name] = item_qty\nend", "def update\n\n if @api_v1_item.update(api_v1_item_params)\n render json: @api_v1_item\n else\n render json: @api_v1_item.errors\n end\n end", "def change_multiple_items\n @items = params[:items]\n\n @items.each do |item|\n @current_item = Item.find(item[:id])\n @current_item.update(quantity: item[:quantity])\n end\n\n render :json => @items.to_json\n end", "def update\n @item = Item.find(item_params)\n respond_to do |format|\n if @item.update(item_params)\n format.html { redirect_to @item, notice: 'Item was successfully updated.' }\n format.json { render :show, status: :ok, location: @item }\n else\n format.html { render :edit }\n format.json { render json: @item.name, status: :unprocessable_entity }\n # format.html { render json: @item, notice: 'Item was not successfully updated.' }\n end\n end\n end", "def update_item(list, name, quantity)\r\n # steps: \r\n # check if item is present\r\n if list[name] != nil\r\n # update with new amount\r\n list[name] = quantity\r\n end\r\n return list\r\n # output: list\r\nend", "def update\n @item_selected_name = ItemSelectedName.find(params[:id])\n\n respond_to do |format|\n if @item_selected_name.update_attributes(item_selected_name_params)\n format.html { redirect_to @item_selected_name, notice: 'Item selected name was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @item_selected_name.errors, status: :unprocessable_entity }\n end\n end\n end", "def magic_item_name_params\n params.require(:magic_item_name).permit(:name, :affix)\n end", "def update_item(list, item_name, new_qty)\n if list.has_key?(item_name)\n list[item_name] = new_qty\n else\n list = add_method(list, item_name, new_qty)\n end\n list\nend", "def updateItem(app, repo_url, item, id)\n headers = defaultHeaders(app[\"token\"])\n data = id.merge(item).to_json\n response = HTTParty.post(repo_url,\n headers: headers,\n body: data)\n response \nend", "def update!(**args)\n @item_option = args[:item_option] if args.key?(:item_option)\n @name_info = args[:name_info] if args.key?(:name_info)\n end", "def update(list, item_name, quantity)\n\tlist[item_name] = quantity\nend", "def rename\n\t\tresult = Investor.update_name(params[:id], params[:name], params[:avatar_id])\n\n\t\treturn render json: result if result[:status] != 0\n\n\t\trender json: { status: 0, avatar_url: result[:result].avatar.url(:thumb) }\n\tend", "def update_quantity(list, item_name, new_quantity)\n list[item_name] = new_quantity\nend", "def update_quantity(list, item_name, new_quantity)\n list[item_name] = new_quantity\nend" ]
[ "0.6601336", "0.6478073", "0.63877803", "0.63482547", "0.63341767", "0.6286458", "0.62237185", "0.622177", "0.6183182", "0.61792547", "0.61488265", "0.6087684", "0.6069304", "0.603378", "0.6031951", "0.6026903", "0.5998217", "0.5994053", "0.5974475", "0.5969632", "0.5966828", "0.5952932", "0.5949463", "0.59352416", "0.59085125", "0.58805484", "0.5863414", "0.58617157", "0.58512175", "0.58512175" ]
0.7312591
0
DELETE /magic_item_names/1 DELETE /magic_item_names/1.json
def destroy @magic_item_name.destroy respond_to do |format| format.html { redirect_to magic_item_names_url, notice: 'Magic item name was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @itemname = Itemname.find(params[:id])\n @itemname.destroy\n\n respond_to do |format|\n format.html { redirect_to itemnames_url }\n format.json { head :no_content }\n end\n end", "def delete_item(item_id)\n response = Unirest.delete CONNECT_HOST + '/v1/' + LOCATION_ID + '/items/' + item_id,\n headers: REQUEST_HEADERS\n\n if response.code == 200\n puts 'Successfully deleted item'\n return response.body\n else\n puts 'Item deletion failed'\n puts response.body\n return nil\n end\nend", "def delete\n render json: Item.delete(params[\"id\"])\n end", "def destroy\n @magic_item.destroy\n respond_to do |format|\n format.html { redirect_to magic_items_url, notice: 'Magic item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(name); end", "def delete(name); end", "def destroy\n item = @item.name\n @item.deleted = true\n @item.deleted_at = Time.now\n @item.save\n\n respond_to do |format|\n format.html { redirect_to items_url, notice: \"#{item} was successfully deleted.\" }\n format.json { head :no_content }\n end\n end", "def delete(items)\n item_ids = items.collect { |item| item.id }\n args = {ids: item_ids.to_json}\n return @client.api_helper.command(args, \"item_delete\")\n end", "def delete(name)\n\n end", "def destroy\n return if new_record?\n \n @api.delete \"/items/#{shortcode_url}.json\"\n end", "def delete_item(id)\n record \"/todos/delete_item/#{id}\"\n end", "def delete_item(grocery,item_name)\n # input: list, item name.\n # steps: delete item_name from the hash\n grocery.delete(item_name)\n # output: display the latest list\n display_list(grocery)\nend", "def delete_item(item)\n @get_items.delete(item)\n end", "def remove_item(list_items, item_name)\n list_items.delete(item_name)\nend", "def delete_item(db, item_name, current_user)\r\n db.execute(\"DELETE FROM items WHERE item_name = ? AND user_id = ?\", [item_name, current_user])\r\nend", "def destroy\n @item.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def delete_item\n\nend", "def remove_item(list, item_name)\n list.delete(item_name)\nend", "def delete_item\n item_id = params[\"item_id\"]\n\n item = TextItem.find_by_id(item_id)\n item = Image.find_by_id(item_id) if item.nil?\n item = Collection.find_by_id(item_id) if item.nil?\n render_json :status => :not_found, :messages => \"Could not find the item with id #{item_id}.\" and return if item.nil?\n\n if item.class == Collection\n if params[\"id\"].nil?\n render_json :status => :bad_request, :messages => \"Can't delete a collection reference without providing the parent collection id. Please use the longer url for item deletion.\" and return\n end\n collection = Collection.find_by_id(params[\"id\"])\n else\n collection = Ownership.find_by_item_id(item_id).parent\n end\n;\n render_json :status => :not_found, :messages => \"Could not find parent collection for the item.\" and return if (collection.nil?)\n render_json :status => :forbidden, :messages => \"The user is not allowed to delete from this collection.\" and return if (!collection.delete?(@user, @client))\n\n collection.delete_item(item_id)\n render_json :entry => {} and return\n end", "def destroy\n# @item = Item.get(params[:id])\n @item.destroy\n\n respond_to do |format|\n format.html { redirect_to({action: :index}, notice: 'Item was successfully deleted.') }\n format.json { head :ok }\n end\n end", "def destroy\n @material_item_name.destroy\n respond_to do |format|\n format.html { redirect_to material_item_names_url, notice: 'Material item name was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @item = @client.items.find(params[:id])\n @item.destroy\n respond_to do |format|\n format.html { redirect_to items_url, notice: 'Item was successfully removed from Inventory.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @apiv1_item.destroy\n respond_to do |format|\n format.html { redirect_to apiv1_items_url, notice: 'Item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def deleted(item)\n end", "def destroy\n @item.destroy\n\n respond_to do |format|\n format.html { redirect_to items_path }\n format.json { head :no_content }\n end\n end", "def test_send_delete_body_with_multiliner_name()\n # Parameters for the API call\n body = DeleteBody.from_hash(APIHelper.json_deserialize(\n '{\"name\":\"farhan\\\\nnouman\",\"field\":\"QA\"}'\n ))\n\n # Perform the API call through the SDK function\n result = @controller.send_delete_body(body)\n\n # Test response code\n assert_equal(200, @response_catcher.response.status_code)\n\n # Test whether the captured response is as we expected\n refute_nil(result)\n expected_body = JSON.parse(\n '{\"passed\":true}'\n )\n received_body = JSON.parse(@response_catcher.response.raw_body)\n assert(TestHelper.match_body(expected_body, received_body, check_values: true))\n end", "def remove_item(list, item_name)\n\t{|list| list.delete(\"mangoes\")}\nend", "def destroy\n @item = Item.find(params[:id])\n @item.destroy\n\n respond_to do |format|\n format.html { redirect_to items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @item = Item.find(params[:id])\n @item.destroy\n\n respond_to do |format|\n format.html { redirect_to items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @item = Item.find(params[:id])\n @item.destroy\n\n respond_to do |format|\n format.html { redirect_to items_url }\n format.json { head :no_content }\n end\n end" ]
[ "0.712925", "0.70415443", "0.6835347", "0.6801185", "0.6763019", "0.6763019", "0.6760498", "0.6754438", "0.67372817", "0.66783565", "0.66700804", "0.6613633", "0.66009676", "0.65984744", "0.65813076", "0.6577654", "0.6559557", "0.6520968", "0.6520809", "0.64875764", "0.6483742", "0.6482077", "0.647296", "0.6444037", "0.6434075", "0.64294827", "0.64228076", "0.64168817", "0.64168817", "0.64168817" ]
0.7403804
0
3 ways to register filter 1. builtin filter filter.add_filter(:mtime, :passed, 30, :days) 2. custom filter filter.add_filter(my_filter) (my_filter must implements match?(path) method) 3. block filter filter.add_filter do |path| filter operations end
def add_filter(*args, &block) # 3. block filter if block_given? filter = File::Visitor::Filter::Proc.new(block) @filters.push(filter) return true end # 2. custom filter if (1 == args.size) custom_filter = args.shift unless (custom_filter.respond_to?(:match?)) raise ArgumentError, "custom_filter must implement match?()" end @filters.push(custom_filter) return true end # 1. built-in filter filter_class = File::Visitor::FilterDispatcher.dispatch(args.shift) @filters.push(filter_class.new(*args)) true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def register_filter(mod); end", "def add_filter(type, path = nil, **options, &block)\n source_location = block.respond_to?(:source_location) ?\n block.source_location.first : caller_files[1]\n result = super\n watch_element(source_location, :\"#{type}_filter\", filters[type].last)\n result\n end", "def add_filter(filter = nil, &block)\n id = \"#{filter.inspect}/#{block.inspect}\".hash\n\n @filters[id] = if filter.is_a?(Filter)\n filter\n elsif filter.is_a?(String)\n StringFilter.new(filter)\n elsif filter.is_a?(Regexp)\n RegexpFilter.new(filter)\n elsif block\n BlockFilter.new(block)\n else\n raise ArgumentError, \"Please specify either a string, \" \\\n \"filter, or block to filter source files with!\"\n end\n\n true\n end", "def add_filter(name, &block)\n raise ArgumentError, \"Expected block to be given\" if block.nil?\n\n @filters[name] = block\n end", "def add_filters(filters); end", "def add_filter filter = nil, &block\n @filters.push( filter ) unless filter.blank?\n @filters.push( block ) if block_given?\n end", "def define_filter(name, &block)\n filters[name.to_sym] = block\n nil\n end", "def filter(name, &block)\n @filters[name.to_s] = block\n end", "def add_filter(filter_argument = T.unsafe(nil), &filter_proc); end", "def filter(&block)\n filters = self.filters << yield\n metaclass.send(:define_method, :_filters) do\n filters\n end\n end", "def add_filter(type, &block)\n filters[type] << block\n end", "def _add_filter(where, method_or_filter, options, block)\n self.filters[where] << [method_or_filter, options, block]\n end", "def apply_filter\n end", "def add_filter(filter)\n @filters << filter\n end", "def add_file_filter(file_filter)\n @filter_file = file_filter\n end", "def add_file_filter(file_filter)\n @filter_file = file_filter\n end", "def named_filter; end", "def add_filter\n @filter = true \n end", "def filter(*args,&block)\n if args && args.any? || block_given?\n @filter = Lolita::Configuration::Filter.new(dbi,*args,&block)\n add_observer(@filter)\n end\n @filter\n end", "def instance_filter(*args, &block)\n instance_filters << [args, block]\n end", "def register_filter(mod)\n Strainer.global_filter(mod)\n end", "def filter(*args, &block)\n @filter = block ? Filter.new(*args, &block) : args.first\n self\n end", "def add_filter(filter)\n @filters << filter\n self\n end", "def filter(*args, &block)\n if args.length == 1\n args = args.first\n else\n args.freeze\n end\n\n with_opts(:filter=>args, :filter_block=>block)\n end", "def register_filter(mod)\n StrainerFactory.add_global_filter(mod)\n end", "def parse_filter(filter_argument = T.unsafe(nil), &filter_proc); end", "def filter(&callable)\n filters << callable\n end", "def add_filter(filter)\n @filters <<\n if filter =~ /\\./\n filter\n else\n \"solr.#{filter}FilterFactory\"\n end\n end", "def filter(name, &block)\n warn [\n \"NOTE: The fixed `filter` class method is deprecated.\",\n \"This will be removed in 0.22. Use the API for modifers instead.\"\n ].join\n registry.filter(name, &block)\n end", "def global_filter; end" ]
[ "0.70155233", "0.6996598", "0.68954813", "0.6658535", "0.663216", "0.658385", "0.6567839", "0.6495973", "0.64650005", "0.6464861", "0.6454527", "0.6416924", "0.6345174", "0.6312059", "0.6290705", "0.6290705", "0.6271176", "0.6257901", "0.6233235", "0.62192565", "0.6142459", "0.61258966", "0.6110519", "0.60721546", "0.60699177", "0.6051691", "0.6044258", "0.603331", "0.6002925", "0.598749" ]
0.7337683
0
dir: target directory mode: file visit all files dir visit directory only handler: proc to call
def visit_with_mode(dir, mode, &handler) assert_directory(dir) entries = Dir.entries(dir) .sort_by { |filename| filename } if @direction == :desc entries.reverse! end entries.each do |entry| next if (dot_dir?(entry) && !@visit_dot_dir) abs_path = File.join(dir, entry) if File.directory?(abs_path) mode == :dir && handler.call(abs_path) visit_with_mode(abs_path, mode, &handler) else if mode == :file && target?(abs_path) handler.call(abs_path) end end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_directory(dir, files, rec)\n dir.children(true).each do |f|\n # ignore sub-directories\n if f.directory?\n if rec == false\n next\n else\n process_directory(f.expand_path, files, rec)\n end\n end\n process_file(f.expand_path, files)\n end\n end", "def process_dir( dir )\n #puts \"Scanning #{dir}\"\n Dir.foreach( dir ) do |entry|\n if entry.start_with?('.')\n next\n end\n path = \"#{dir}/#{entry}\"\n if Dir.exist?(path)\n process_dir(path)\n elsif entry.end_with?( '.rb' )\n process_file( path )\n end\n end\n end", "def directory(dir); end", "def files(rootDir)\n Dir.foreach(rootDir) do |dir|\n if dir != \".\" && dir != \"..\"\n puts \"Processing \" + dir\n Dir.foreach(rootDir + \"/\" + dir) do |file|\n if file != \".\" && file != \"..\"\n open(rootDir + \"/\" + dir + \"/\" + file) do |f|\n yield(f)\n end\n end\n end\n end\n end\nend", "def traverse(dir, base=dir, &block)\n return unless File.directory?(dir)\n Dir.new(dir).each do |file|\n next if file == '.' or file == '..'\n path = File.join(dir, file)\n if File.directory?(path)\n traverse(path, base, &block)\n else\n block.call(path.sub(base+'/',''))\n end\n end\n end", "def for(file_or_dir); end", "def in_each_dir\n dirs.each do |dir|\n Dir.chdir(dir) do\n yield(dir)\n end\n end\n end", "def indir(dir)\n olddir = Dir.pwd\n Dir.chdir(dir)\n yield\n ensure\n Dir.chdir(olddir)\n end", "def indir(dir)\n olddir = Dir.pwd\n Dir.chdir(dir)\n yield\n ensure\n Dir.chdir(olddir)\n end", "def scan_dir (dirname)\n log \"*** Inspect: \" + dirname\n Dir.foreach(dirname) do |filename|\n path_cand = File.join(dirname , filename)\n if File.directory?(path_cand)\n #exams directories\n if (filename != \".\" && filename != \"..\")\n unless @filter_dir.index(filename)\n #directory not filtered\n @explore_dir.push(path_cand)\n @dir_list << path_cand\n end\n end\n else\n # file to be listed\n unless file_is_filtered?(path_cand)\n # file is not filtered\n #p path_cand\n if file_has_admitted_extension?(path_cand)\n @result_list.push(path_cand)\n end\n end\n end #file.directory?\n end\n next_dir = @explore_dir.pop\n scan_dir(next_dir) if next_dir \n end", "def each_file(&bl)\n unpack do |dir|\n Pathname(dir).find do |path|\n next if path.to_s == dir.to_s\n pathstr = path.to_s.gsub(\"#{dir}/\", '')\n bl.call pathstr unless pathstr.blank?\n end\n end\n end", "def scan_dir (dirname)\n log \"*** Inspect: \" + dirname\n Dir.foreach(dirname) do |filename|\n path_cand = File.join(dirname , filename)\n if File.directory?(path_cand)\n #exams directories\n if (filename != \".\" && filename != \"..\")\n unless @filter_dir.index(filename)\n #directory not filtered\n @explore_dir.push(path_cand)\n @dir_list << path_cand\n end\n end\n else\n # file to be listed\n unless file_is_filtered?(path_cand)\n # file is not filtered\n @result_list.push(path_cand)\n end\n end #file.directory?\n end\n next_dir = @explore_dir.pop\n scan_dir(next_dir) if next_dir \n end", "def each_file(&bl)\n unpack do |dir|\n Pathname.new(dir).find do |path|\n next if path.to_s == dir.to_s\n pathstr = path.to_s.gsub(\"#{dir}/\", '')\n bl.call pathstr unless pathstr.blank?\n end\n end\n end", "def dir(*) end", "def read_dir(dir, &blk)\n Dir.chdir(dir){\n Dir[\"*\"].each do |folder|\n unless ::File.directory?(folder)\n yield ::File.expand_path(folder)\n else\n read_dir(folder, &blk) unless ::File.symlink?(folder)\n end\n end\n }\n end", "def dir_foreach( *args, &block )\n warn \"Path#dir_foreach is obsoleted. Use Path#each_entry.\"\n each_entry( *args, &block )\n end", "def scanDir(dirname, matchfn, callfn, recurse)\n\tDir.foreach(dirname) do |filename|\n\t\tfullfilename = dirname + \"/\" + filename;\n\t\tif File.directory?(fullfilename)\n\t\t\tif recurse && filename != \".\" && filename != \"..\"\t\t# don't infinite loop kthx\n\t\t\t\tscanDir(fullfilename, matchfn, callfn, recurse)\n\t\t\tend\n\t\telsif matchfn.call(filename)\n\t\t\tcallfn.call(fullfilename)\n\t\tend\n\tend\nend", "def parse_dir(dir, depth)\n\n # Identify method entry\n debug_print \"#{ self } : #{ __method__ }\\n\"\n\n # Error check on input\n if Watson::FS.check_dir(dir)\n debug_print \"Opened #{ dir } for parsing\\n\"\n else\n print \"Unable to open #{ dir }, exiting\\n\"\n return false\n end\n\n debug_print \"Parsing through all files/directories in #{ dir }\\n\"\n\n # [review] - Shifted away from single Dir.glob loop to separate for dir/file\n # This duplicates code but is much better for readability\n # Not sure which is preferred?\n\n\n # Remove leading . or ./\n _glob_dir = dir.gsub(/^\\.(\\/?)/, '')\n debug_print \"_glob_dir: #{_glob_dir}\\n\"\n\n\n # Go through directory to find all files\n # Create new array to hold all parsed files\n _completed_files = Array.new()\n Dir.glob(\"#{ _glob_dir }{*,.*}\").select { |_fn| File.file?(_fn) }.sort.each do |_entry|\n debug_print \"Entry: #{_entry} is a file\\n\"\n\n\n # [review] - Warning to user when file is ignored? (outside of debug_print)\n # Check against ignore list, if match, set to \"\" which will be ignored\n @config.ignore_list.each do |_ignore|\n if _mtch = _entry.match(_ignore)\n _entry = ''\n break\n end\n end\n\n # If the resulting entry (after filtering) isn't empty, parse it and push into file array\n unless _entry.empty?\n debug_print \"Parsing #{ _entry }\\n\"\n _completed_files.push(parse_file(_entry))\n end\n\n end\n\n\n # Go through directory to find all subdirs\n # Create new array to hold all parsed subdirs\n _completed_dirs = Array.new()\n Dir.glob(\"#{ _glob_dir }{*, .*}\").select { |_fn| File.directory?(_fn) }.sort.each do |_entry|\n debug_print \"Entry: #{ _entry } is a dir\\n\"\n\n # Check if entry is in ignore list\n _skip = false\n\n @config.ignore_list.each do |_ignore|\n if mtch = _entry.match(_ignore)\n _skip = true\n end\n end\n\n debug_print \"#{ _entry } was not on ignorelist, adding\\n\"\n\n # If directory is on the ignore list then skip\n next if _skip == true\n\n ## Depth limit logic\n # Current depth is depth of previous parse_dir (passed in as second param) + 1\n _cur_depth = depth + 1\n debug_print \"Current Folder depth: #{ _cur_depth }\\n\"\n\n # If Config.parse_depth is 0, no limit on subdir parsing\n if @config.parse_depth == 0\n debug_print \"No max depth, parsing directory\\n\"\n _completed_dirs.push(parse_dir(\"#{ _entry }/\", _cur_depth))\n\n # If current depth is less than limit (set in config), parse directory and pass depth\n elsif _cur_depth < @config.parse_depth.to_i + 1\n debug_print \"Depth less than max dept (from config), parsing directory\\n\"\n _completed_dirs.push(parse_dir(\"#{ _entry }/\", _cur_depth))\n\n # Else, depth is greater than limit, ignore the directory\n else\n debug_print \"Depth greater than max depth, ignoring\\n\"\n end\n\n # Add directory to ignore list so it isn't repeated again accidentally\n @config.ignore_list.push(_entry)\n end\n\n\n # [review] - Not sure if Dir.glob requires a explicit directory/file close?\n\n # Create hash to hold all parsed files and directories\n _structure = Hash.new()\n _structure[:curdir] = dir\n _structure[:files] = _completed_files\n _structure[:subdirs] = _completed_dirs\n _structure\n end", "def target_files_in_dir(base_dir = T.unsafe(nil)); end", "def processDir( dirPath )\n return if not File.directory?( dirPath )\n\n puts File.basename( dirPath ) + \"/\"\n\n Dir.foreach( dirPath ) do | content |\n next if content == \".\" or content == \"..\"\n\n contentPath = dirPath + \"/\" + content\n next if File.symlink?( contentPath )\n\n if File.directory?( contentPath )\n processDir contentPath\n elsif File.file?( contentPath )\n fork do\n flacFile = FlacFile.new contentPath\n flacFile.normalize\n end\n end\n end\n\n Process.waitall\nend", "def collect_in_dir directory, recursive = true\n if not File.readable? directory\n puts \"#{directory} not readable. Skipping.\" if @verbose\n else\n directory += \"/\" if not directory.end_with? \"/\"\n if File.directory? directory\n files = Dir.entries directory\n files.reject! {|d| d.match /^\\.{1,2}$/} # ignore parent and self links\n files.map! { |f| directory + f }\n files.each do |fname|\n if File.directory?(fname) and recursive\n collect_in_dir fname\n elsif not File.readable? fname\n puts \"#{fname} not readable.Skipping.\" if @verbose\n elsif File.file? fname and File.extname(fname) == @extension # if no directory\n pkg_info = parse_pkg fname\n @files[fname] = pkg_info if pkg_info\n end\n end\n end\n end\n end", "def readdir(path, fileinfo)\n puts \"#readdir \" + path\n path == \"/\" or @root.directory?(path) and @root.contents(path)\n end", "def walk\n FileTreeProfiler.monitor_report(:profile, :dir, path)\n @children = []\n Dir.foreach(path) do |entry|\n next if (entry == '..' || entry == '.')\n full_path = ::File.join(path, entry)\n if ::File.directory?(full_path)\n children.push DirFile.new(self, entry)\n else\n children.push DataFile.new(self, entry)\n end\n end\n end", "def process()\n scan_dir('.', '.')\n end", "def explore(dir)\n\tterminate if $interrupted\n\tDir.new(dir).each do |node|\n\t\tnode_path = dir + '/' + node\n\t\tif File.directory?(node_path) && !File.symlink?(node_path) && node[0,1] != '.'\n\t\t\texplore node_path\n\t\telsif File.file?(node_path) && node[0] != '.'\n\t\t\tif greppable node_path\n\t\t\t\tif node =~ /#{ARGV[0]}/\n\t\t\t\t\tputs colorize(node_path, 'yellow')\n\t\t\t\t\tStats['name_matches'] += 1\n\t\t\t\tend\n\t\t\t\tgrep_file node_path unless Opts['names']\n\t\t\t\tStats['files_grepped'] += 1\n\t\t\telse\n\t\t\t\tStats['nodes_skipped'] += 1\n\t\t\tend\n\t\telse\n\t\t\tStats['nodes_skipped'] += 1\n\t\tend\n\tend\nend", "def process_directory(path)\n Find.find(path) do |a_path| \n Find.prune if EXCLUDES_DIRECTORIES.include?(File.basename(a_path))\n if (ACCEPTED_FILES_PATTERN.each { | pattern| File.basename(pattern)} and\n !File.directory?(a_path))\n @files_processed += 1\n document = moddify_document(a_path)\n modify_file(a_path,document)\n end\n end\nend", "def collect\n return if stat.ftype == \"directory\"\n self\n end", "def files_in(dir)\n Dir.chdir(dir) do\n Dir.glob('**/*').select { |f| File.file?(f) }\n end\nend", "def find_files(base_dir, flags); end", "def walk(path); end" ]
[ "0.7269948", "0.72344595", "0.7196083", "0.67955124", "0.6779908", "0.67796755", "0.6704745", "0.6700345", "0.6700345", "0.6691016", "0.66885805", "0.66692245", "0.66111976", "0.660302", "0.6600337", "0.65905225", "0.6588868", "0.658193", "0.6553596", "0.64825714", "0.6463325", "0.64290446", "0.64143103", "0.64142454", "0.6408623", "0.63832515", "0.6334949", "0.63204664", "0.63150626", "0.6306632" ]
0.76961493
0
Returns only the children with +results+
def children_with_results children.select(&:any_results_including_children?) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def children\n\t\treturn self.search( :one, '(objectClass=*)' )\n\tend", "def any_results_including_children?\n races.any?(&:any_results?) || children.any?(&:any_results_including_children?)\n end", "def pull_out(parent_hash)\n return parent_hash[\"results\"]\n rescue\n return []\n end", "def search_children(node, attribute, search_term)\n matches = []\n end", "def getTestNames(results)\n path = getCollectionPath(results)\n while !(String(path).end_with? Jekyll::RESULTS_URL_PATTERN || path.root?) do\n path = path.parent\n end\n return path.children\n end", "def results_with_query(results)\n results.find_all do |result|\n query.all? do |attribute, value|\n result.send(attribute) == value\n end\n end\n end", "def get_childs\n childs = Category.any_in(parent_ids: [parent.id])\n\n results = Array.new\n childs.each do |child|\n results << child\n end\n\n results\n end", "def results\n fetch unless @results\n @results\n end", "def filter(results)\n if params[:q].present?\n results = Project.search(results, params[:q])\n end\n \n if params[:tag].present?\n results = Project.match_tag(results, params[:tag])\n end\n \n return results\n end", "def index\n if !signed_in?\n redirect_to root_path\n end\n @children = Child.all\n if !params[:search].nil?\n @result = Child.search(params[:search])\n end\n if @result.nil? && params[:search].nil?\n @result = Child.all\n end\t \n end", "def get_results(with_root = false)\n ret = []\n\n # Iterate over all occupied descendants and create chain data\n @occupied_descendants.each do |node|\n ret << [node.data, node.get_chain(with_root)]\n end\n\n # Return\n ret\n end", "def getAllChildren\n children = Tree.where(\"tree_type_id = ? AND version_id = ? AND subject_id = ? AND grade_band_id = ? AND code like ?\", tree_type_id, version_id, subject_id, grade_band_id, code+'.%')\n Rails.logger.debug(\"*** tree children: #{children.inspect}\")\n return children\n end", "def search_results\r\n @browser.divs(class: 'rc').collect do |div|\r\n div.h3.a.text\r\n end\r\n end", "def all_children\n children(all: true)\n end", "def fetch_search_results(context)\n\n params = @params\n site_id = context['__site_id']\n\n matching_ids = Node.search_ids do\n\n # Site ID\n with :site_id, site_id\n\n # Node classification\n if params['classification']\n with :classification, params['classification']\n end\n\n # Parent\n if params['scope_to']\n parent_scope = context[params['scope_to']]\n with :parent_uri, parent_scope['uri']\n elsif params['parent_uri']\n with :parent_uri, params['parent_uri']\n end\n\n # Ordering\n order_by_fields = params['order_by'].blank? ? [] : params['order_by'].split(',')\n order_by_fields.each do |order_by_field|\n\n field_name, direction = order_by_field.gsub(/[\"']/, '').strip.split(' ', 2)\n direction = 'asc' if direction.blank?\n order_by field_name.to_sym, direction.to_sym\n\n end\n\n # Limit\n if params['limit']\n paginate :page => 1, :per_page => params['limit']\n end\n\n end\n\n results = []\n matching_ids.each do |id|\n\n node = Rails.cache.fetch \"node_id:#{site_id}:#{id}\" do\n Node.where(:site_id => site_id).find(id).to_liquid\n end\n results << node\n\n end\n\n results\n\n end", "def results_from_search(query_results)\n ids = query_results.map do |result|\n result['id']\n end\n find_from_search(*ids)\n end", "def search_results\n builder = search_builder.with(search_state)\n builder.page = search_state.page\n builder.rows = search_state.per_page\n\n builder = yield(builder) if block_given?\n response = repository.search(builder)\n\n if response.grouped? && grouped_key_for_results\n response.group(grouped_key_for_results)\n elsif response.grouped? && response.grouped.length == 1\n response.grouped.first\n else\n response\n end\n end", "def results_list\n list = []\n begin\n self.spans(:class=>\"s3d-search-result-name\").each do |element|\n list << element.text\n end\n rescue\n list = []\n end\n list\n end", "def onlychildren_list\n if matches.length == 1\n [self] + matches[0].onlychildren_list\n else\n [self]\n end\n end", "def process_results (results)\n\t\t\tresults.each do |result|\n\t\t\t\tresult = process_result(result)\n\t\t\tend\n\t\t\treturn results\n\t\tend", "def intend_children\n children.select { |child| !child.has_class :hidden }\n end", "def intend_children\n children.select { |child| !child.has_class :hidden }\n end", "def children\n dataset.nested.filter(self.class.qualified_parent_column => self.id)\n end", "def children\n self.class.where('? = ANY(parent_ids)', id.to_s)\n end", "def results_list\n list = []\n begin\n self.spans(:class=>\"s3d-search-result-name\").each do |element|\n list << element.text\n end\n rescue\n list = []\n end\n return list\n end", "def children(options={})\n @global_page.children.all options\n end", "def find_with(results, with = nil)\n ret = QueryResult.new\n ret << results if results\n ret << with if with\n ret.flatten!\n\n ret.size == 1 ? ret[0] : ret\n end", "def results\n populate\n @results\n end", "def all_children\n find_all_children_with_dotted_ids\n end", "def children()\n #Ressource.filter(:parent_id => self.id, :parent_service_id => self.service_id).all\n end" ]
[ "0.6459362", "0.6355265", "0.63484645", "0.6250594", "0.6238641", "0.5964827", "0.59176993", "0.5885458", "0.5861433", "0.5841403", "0.5840733", "0.5839581", "0.57967174", "0.57507205", "0.5739048", "0.5718785", "0.5714855", "0.56983995", "0.5697021", "0.5694411", "0.5668937", "0.5668937", "0.5663969", "0.5654792", "0.5636998", "0.5633571", "0.56225795", "0.56149083", "0.5608169", "0.5604465" ]
0.8369089
0
Returns only the Races with +results+
def races_with_results races.select(&:any_results?) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def source_results(race)\n Result.all(\n :include => [:race, {:person => :team}, :team, {:race => [:event, :category]}],\n :conditions => [%Q{\n members_only_place between 1 AND #{point_schedule.size - 1}\n and results.person_id is not null\n and events.type = 'SingleDayEvent' \n and events.sanctioned_by = \"#{RacingAssociation.current.default_sanctioned_by}\"\n and categories.id in (#{category_ids_for(race).join(\", \")})\n and (races.bar_points > 0 or (races.bar_points is null and events.bar_points > 0))\n and events.date between '#{date.beginning_of_year}' and '#{date.end_of_year}'\n }],\n :order => 'person_id'\n )\n end", "def source_results(race)\n return [] if event.events.empty?\n \n event_ids = event.events.collect do |event|\n event.id\n end\n event_ids = event_ids.join(', ')\n category_ids = category_ids_for(race)\n \n Result.find_by_sql(\n %Q{ SELECT results.id as id, race_id, racer_id, team_id, place FROM results \n JOIN races ON races.id = results.race_id \n JOIN categories ON categories.id = races.category_id \n JOIN standings ON races.standings_id = standings.id \n JOIN events ON standings.event_id = events.id \n WHERE (standings.type = 'Standings' or standings.type is null)\n and place between 1 and 18\n and categories.id in (#{category_ids})\n and events.id in (#{event_ids})\n order by racer_id\n }\n )\n end", "def source_results(race)\n category_ids = category_ids_for(race).join(\", \")\n\n Result.all(\n :include => [:race, {:person => :team}, :team, {:race => [{:event => { :parent => :parent }}, :category]}],\n :conditions => [%Q{\n (events.type in ('Event', 'SingleDayEvent', 'MultiDayEvent') or events.type is NULL)\n and bar = true\n and categories.id in (#{category_ids})\n and (events.discipline = '#{race.discipline}'\n or (events.discipline is null and parents_events.discipline = '#{race.discipline}')\n or (events.discipline is null and parents_events.discipline is null and parents_events_2.discipline = '#{race.discipline}'))\n and (races.bar_points > 0\n or (races.bar_points is null and events.bar_points > 0)\n or (races.bar_points is null and events.bar_points is null and parents_events.bar_points > 0)\n or (races.bar_points is null and events.bar_points is null and parents_events.bar_points is null and parents_events_2.bar_points > 0))\n and events.date between '#{date.year}-01-01' and '#{date.year}-12-31'\n }],\n :order => 'person_id'\n )\n end", "def source_results(race)\n query = Result.\n select([\"results.id as id\", \"person_id as participant_id\", \"people.member_from\", \"people.member_to\", \"place\", \"results.event_id\", \"race_id\", \"events.date\", \"year\"]).\n joins(:race, :event, :person).\n where(\"place != 'DNS'\").\n where(\"races.category_id is not null\").\n where(\"events.type = 'SingleDayEvent' or events.type = 'Event' or events.type is null\").\n where(\"events.ironman = true\").\n where(\"results.year = ?\", year)\n\n Result.connection.select_all query\n end", "def source_results(race)\n if race.discipline == 'Road'\n race_disciplines = \"'Road', 'Circuit'\"\n else\n race_disciplines = \"'#{race.discipline}'\"\n end\n \n # Cat 4/5 is a special case. Can't config in database because it's a circular relationship.\n category_ids = category_ids_for(race)\n category_4_5_men = Category.find_by_name(\"Category 4/5 Men\")\n category_4_men = Category.find_by_name(\"Category 4 Men\")\n if category_4_5_men && category_4_men && race.category == category_4_men\n category_ids << \", #{category_4_5_men.id}\"\n end\n\n Result.find(:all,\n :include => [:race, {:person => :team}, :team, {:race => [{:event => { :parent => :parent }}, :category]}],\n :conditions => [%Q{\n place between 1 AND #{point_schedule.size - 1}\n and (events.type in ('Event', 'SingleDayEvent', 'MultiDayEvent', 'Series', 'WeeklySeries', 'TaborOverall') or events.type is NULL)\n and bar = true\n and events.sanctioned_by = \"#{ASSOCIATION.default_sanctioned_by}\"\n and categories.id in (#{category_ids})\n and (events.discipline in (#{race_disciplines})\n or (events.discipline is null and parents_events.discipline in (#{race_disciplines}))\n or (events.discipline is null and parents_events.discipline is null and parents_events_2.discipline in (#{race_disciplines})))\n and (races.bar_points > 0\n or (races.bar_points is null and events.bar_points > 0)\n or (races.bar_points is null and events.bar_points is null and parents_events.bar_points > 0)\n or (races.bar_points is null and events.bar_points is null and parents_events.bar_points is null and parents_events_2.bar_points > 0))\n and events.date between '#{date.year}-01-01' and '#{date.year}-12-31'\n }],\n :order => 'person_id'\n )\n end", "def source_results(race)\n Result.find_by_sql(\n %Q{SELECT results.points, results.id as id, race_id, racer_id, team_id, place \n FROM results \n LEFT OUTER JOIN races ON races.id = results.race_id \n LEFT OUTER JOIN standings ON races.standings_id = standings.id \n LEFT OUTER JOIN events ON standings.event_id = events.id \n LEFT OUTER JOIN categories ON races.category_id = categories.id \n where results.id in (select source_result_id \n from scores \n LEFT OUTER JOIN results as competition_results \n ON competition_results.id = scores.competition_result_id\n LEFT OUTER JOIN races as competition_races \n ON competition_races.id = competition_results.race_id\n LEFT OUTER JOIN standings as competition_standings \n ON competition_races.standings_id = competition_standings.id \n LEFT OUTER JOIN events as competition_events \n ON competition_standings.event_id = competition_events.id \n where competition_events.type = 'Bar' \n and competition_events.date >= '#{date.year}-01-01' \n and competition_events.date <= '#{date.year}-12-31')\n order by team_id}\n )\n end", "def after_source_results(results, _race)\n results.reject do |result|\n result[\"category_name\"][\"Junior\"] &&\n result[\"category_ages_begin\"] &&\n (\n result[\"category_ages_begin\"] > ::Categories::Ages::JUNIORS.begin ||\n result[\"category_ages_end\"] < ::Categories::Ages::JUNIORS.end\n )\n end\n end", "def get_results\n\t\trace_id = params[:id]\n\t\t\n\t\trace = Race.find_by_id(race_id)\n\t\tresults = Result.get_race_results(race_id)\n\t\t\n\t\trender :json=>{:results=>results}\n\tend", "def source_results(race)\n []\n end", "def competition_results\n results.select(&:competition_result?)\n end", "def create_competition_results_for(results, race)\n competition_result = nil\n results.each_with_index do |source_result, index|\n logger.debug(\"#{self.class.name} scoring result: #{source_result.date} race: #{source_result.race.name} pl: #{source_result.place} mem pl: #{source_result.members_only_place if place_members_only?} #{source_result.last_name} #{source_result.team_name}\") if logger.debug?\n\n racer = source_result.racer\n points = points_for(source_result)\n if points > 0.0 && (!members_only? || member?(racer, source_result.date))\n \n if first_result_for_racer(source_result, competition_result)\n # Intentionally not using results association create method. No need to hang on to all competition results.\n # In fact, this could cause serious memory issues with the Ironman\n competition_result = Result.create!(\n :racer => racer, \n :team => (racer ? racer.team : nil),\n :race => race)\n end\n \n Competition.benchmark('competition_result.scores.create_if_best_result_for_race') {\n competition_result.scores.create_if_best_result_for_race(\n :source_result => source_result, \n :competition_result => competition_result, \n :points => points\n )\n }\n end\n \n # Aggressive memory management. If competition has a race with many results, \n # the results array can become a large, uneeded, structure\n results[index] = nil\n GC.start if index > 0 && index % 1000 == 0\n end\n end", "def create_competition_results_for(results, race)\n competition_result = nil\n for source_result in results\n logger.debug(\"#{self.class.name} scoring result: #{source_result.race.name} #{source_result.place} #{source_result.name} #{source_result.team_name}\") if logger.debug?\n\n teams = extract_teams_from(source_result)\n logger.debug(\"#{self.class.name} teams for result: #{teams}\") if logger.debug?\n for team in teams\n if member?(team, source_result.date)\n\n if first_result_for_team(source_result, competition_result)\n # Bit of a hack here, because we split tandem team results into two results,\n # we can't guarantee that results are in team-order.\n # So 'first result' really means 'not the same as last result'\n competition_result = race.results.detect {|result| result.team == team}\n competition_result = race.results.create(:team => team) if competition_result.nil?\n end\n\n score = competition_result.scores.create(\n :source_result => source_result, \n :competition_result => competition_result, \n :points => points_for(source_result).to_f / teams.size\n )\n end\n end\n end\n end", "def create_competition_results_for(results, race)\n competition_result = nil\n results.each_with_index do |source_result, index|\n logger.debug(\"#{self.class.name} scoring result: #{source_result.date} race: #{source_result.race.name} pl: #{source_result.place} mem pl: #{source_result.members_only_place if place_members_only?} #{source_result.last_name} #{source_result.team_name}\") if logger.debug?\n\n racer = source_result.racer\n points = points_for(source_result)\n \n # We repeat some calculations here if a racer is disallowed\n if points > 0.0 && (!event.completed? || (event.completed? && raced_minimum_events?(racer, race))) && (!members_only? || member?(racer, source_result.date))\n\n if first_result_for_racer(source_result, competition_result)\n # Intentionally not using results association create method. No need to hang on to all competition results.\n # In fact, this could cause serious memory issues with the Ironman\n competition_result = Result.create!(\n :racer => racer, \n :team => (racer ? racer.team : nil),\n :race => race)\n end\n\n Competition.benchmark('competition_result.scores.create_if_best_result_for_race') {\n competition_result.scores.create_if_best_result_for_race(\n :source_result => source_result, \n :competition_result => competition_result, \n :points => points\n )\n }\n end\n\n # Aggressive memory management. If competition has a race with many results, \n # the results array can become a large, uneeded, structure\n results[index] = nil\n if index > 0 && index % 1000 == 0\n logger.debug(\"GC start after record #{index}\")\n GC.start\n end\n\n end\n end", "def results_with_query(results)\n results.find_all do |result|\n query.all? do |attribute, value|\n result.send(attribute) == value\n end\n end\n end", "def event_results(reload = true)\n if reload\n return Result\n .includes(:team, :person, :scores, :category, race: %i[event category])\n .where(\"people.id\" => id)\n .reject(&:competition_result?)\n end\n results.reject(&:competition_result?)\n end", "def filter(results)\n if params[:q].present?\n results = Project.search(results, params[:q])\n end\n \n if params[:tag].present?\n results = Project.match_tag(results, params[:tag])\n end\n \n return results\n end", "def any_results?\n races.any?(&:any_results?)\n end", "def process_round_results(results_feed)\n race_table = results_feed['RaceTable']\n races = race_table['Races']\n round = race_table['round']\n race = races.first\n finishers = race['Results']\n race_result = {}\n qly_result = {}\n\n finishers.each do |finisher|\n driver = finisher['Driver']\n if finisher['position'].to_i <= 10\n race_result[finisher['position']] = get_driver_id(driver)\n end\n\n if finisher['grid'].to_i <= 3\n qly_result[finisher['grid']] = get_driver_id(driver)\n end\n end\n\n seed_race_result(round, race_result[\"1\"], race_result[\"2\"], race_result[\"3\"],\n race_result[\"4\"], race_result[\"5\"], race_result[\"6\"],\n race_result[\"7\"], race_result[\"8\"], race_result[\"9\"],\n race_result[\"10\"])\n seed_qly_result(round, qly_result[\"1\"], qly_result[\"2\"], qly_result[\"3\"])\n end", "def exclude_results(results, options)\n exclude_oob = options.fetch(:excluding_out_of_bounds, false)\n exclude_occupied = options.fetch(:excluding_occupied_spaces, false)\n\n results = excluding_out_of_bounds(results) if exclude_oob\n results = excluding_occupied_spaces(results) if exclude_occupied\n results\n end", "def fill_in_missing_results\n Result.all.group_by(&:race).each do |race, results|\n all_results=results.collect(&:place) #get an array of just places for this race \n results.sort!{|a,b| a.place.to_i <=> b.place.to_i} #important to get last place in last\n need_results=[]\n (1..results.last.place.to_i).reverse_each {|res|\n unless all_results.include?(res.to_s)\n #we need a result, there is a gap here\n race.results.create!(:place => res)\n end \n }\n end\n end", "def search_results(*args)\n ranks_and_ids = search_result_ranks_and_ids(*args)\n search_results_from_ids(ranks_and_ids.map(&:last))\n end", "def results\n \t\t@teams = Team.all\n\tend", "def merge_movie_search_results(results)\n results.flatten\n end", "def search_results(game_type)\n CombinedReplayData.search do\n all do\n any_of do\n with(:p1_rank).between(1..5)\n without(:p1_legend_rank, nil)\n end\n any_of do\n with(:p2_rank).between(1..5)\n without(:p2_legend_rank, nil)\n end\n end\n with(:played_at).greater_than(5.days.ago)\n with(:game_type, game_type)\n facet :p1_class_and_archetype\n facet :p2_class_and_archetype\n end\n end", "def get_rt_search_results\n search_results = RottenMovie.find(:title => \"#{params[:search]}\", :limit => 20)\n if search_results.length == nil #check if search returned a single object\n search_results = [search_results] #make it an array\n end\n search_results.each do |x| #capture relevant info from rottentomatoes\n film = Film.new(\"title\"=>\"#{x.title}\", \"year\"=>\"#{x.year}\", \"length\"=>\"#{x.runtime}\", \"synopsis\"=>\"#{x.synopsis}\", \"trailer\"=>\"\", \"rt_rating\"=>\"#{x.ratings.critics_score}\")\n @results << film\n \n if x.posters.thumbnail == nil\n @thumbs << \"/Users/skylersidner/Code/2015-02-13-reel-bad-night/public/images/poster_default.gif\"\n else\n @thumbs << x.posters.thumbnail\n end\n end #each\n @results\n end", "def results\n fetch unless @results\n @results\n end", "def results\n results = result_maker(RACER_RECORDS)\n total_time = total_time_maker(RACER_RECORDS)\n @view.display_results(results, total_time)\n end", "def test_results_filter(test_results)\n test_results.select do |tr|\n # Non TestResult items are never filtered.\n next true unless tr.kind_of?(Automation::TestDatabase::TestResult)\n entity_result(tr) != Automation::Result::Pass\n end\n end", "def run_results()\n sql = \"SELECT * FROM results\"\n results = run(sql)\n results.each do |result|\n event = Event.find(result['event_id'].to_i)\n knight = filter(result['knight_id'].to_i)\n trophy = Trophy.new(event,result['position'].to_i)\n knight.add_trophy(trophy)\n end\n end", "def get_likely_racers(race_id)\n already_registered = StartItem.where(:race_id => race_id).pluck(:racer_id)\n if already_registered.length > 0\n likely_racers = Racer.where([\"(race_count > ? OR current_streak > ?) AND id not in (?)\", 20, 0, already_registered]).order(\"current_streak DESC, race_count DESC\").first(20)\n else\n likely_racers = Racer.where([\"race_count > ? OR current_streak > ?\", 20, 0]).order(\"current_streak DESC, race_count DESC\").first(20)\n end\n return likely_racers\n end" ]
[ "0.72392356", "0.70322144", "0.69340986", "0.69137114", "0.6877534", "0.67981076", "0.6605429", "0.6552044", "0.64661694", "0.633136", "0.6317928", "0.62822217", "0.62274146", "0.6181003", "0.61339587", "0.59963137", "0.5985405", "0.5925433", "0.5776336", "0.5770774", "0.5759061", "0.5729884", "0.5728552", "0.5715455", "0.56708694", "0.566765", "0.56639206", "0.56456673", "0.56397337", "0.5635931" ]
0.7977516
0
Returns an array with the relative path of the selected songs (Overrides def on MusicBaseController)
def get_selected_paths return get_songs_column( :path ) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_selected_paths\n return get_songs_relation.pluck( :path )\n end", "def song_plays\n SongPlay.where(:song_path => path)\n end", "def path\n File.expand_path File.join(songs.first.path, '..').gsub(' ','\\ ')\n end", "def path # getter method \n # - this method will get the path passed through the MusicImporter object\n @path\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs\n @songs\n end", "def songs \n @songs\n end", "def songs\n @songs\nend", "def songs\n Song.all\n end", "def show_songs_in_playlist\n \n file_name = params[:file_name]\n\n @song_list = []\n File.read(\"#{Rails.root}/public/Playlist/#{params[:file_name]}\").each_line do |line|\n @song_list << line.chop\n end\n end", "def all_songs\n end", "def files\n\t\t@array_of_mp3s = Dir[\"#{@path}/*.mp3\"]\n\t\t@array_of_mp3s.map do |mp3|\n\t\t\tmp3.slice!(\"#{@path}/\")\n\t\t\tmp3\n\t\tend\n\tend", "def songs\n MusicImporter.new(path).print_songs\n end", "def songs\n Song.find_by_album(@id)\n end", "def songs\n Song.all\n end", "def files\n # fetch the appropriate files\n filenames = Dir.glob(@path + \"/*.mp3\")\n filenames.map { |filename| @files << File.basename(filename) }\n @files\n end", "def songs\n # @@songs.select { |song| song.name == @name }\n @songs\n end", "def files\n Dir.glob(self.path + '**/*.mp3').collect {|file| File.basename(file)}\n end", "def files\n # fetch the appropriate files\n file_paths = Dir.glob(@path + \"/*.mp3\")\n file_paths.map { |file_path| @files << File.basename(file_path) }\n @files\n end", "def files\n @files_array ||= Dir.glob(\"#{@path}/*.mp3\").collect do |filename|\n filename.rpartition(\"/\").last \n end \n end" ]
[ "0.7602469", "0.6756914", "0.6566635", "0.6497871", "0.64439666", "0.64439666", "0.6416481", "0.6416481", "0.6416481", "0.6416481", "0.6416481", "0.6416481", "0.6416481", "0.6416481", "0.6416481", "0.6416481", "0.6335312", "0.63043845", "0.62646556", "0.6229565", "0.6189326", "0.6186246", "0.6181002", "0.61462206", "0.61374694", "0.61339235", "0.6132415", "0.6128909", "0.6118086", "0.61145043" ]
0.7722529
0
NOTE do not pattern your production application after this (refer to test_should_create_customer_profile_transaction_auth_only_and_then_prior_auth_capture_requests instead as the correct way to do an auth then capture). capture_only "is used to complete a previously authorized transaction that was not originally submitted through the payment gateway or that required voice authorization" and can in some situations perform an auth_capture leaking the original authorization.
def test_should_create_customer_profile_transaction_auth_only_and_then_capture_only_requests @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:auth_only)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_only, amount: @amount } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] assert_equal 'auth_only', response.params['direct_response']['transaction_type'] assert_equal 'Gw4NGI', approval_code = response.params['direct_response']['approval_code'] @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:capture_only)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :capture_only, amount: @amount, approval_code: approval_code } ) assert_instance_of Response, response assert_success response assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_authorization_and_capture\n return if Base.mode == :test # only tests in production mode\n assert_equal Base.mode, :production\n assert authorization = @gateway.authorize(@amount, @credit_card, @options)\n assert_success authorization\n \n assert capture = @gateway.capture(@amount, authorization.authorization)\n assert_success capture\n assert_match(/This transaction has been approved/, capture.message)\n end", "def auth_capture_transaction\n data = full_params.merge(\n 'x_unique_id' => unique_id,\n 'x_invoice_num' => invoice_num,\n 'x_type' => \"AUTH_CAPTURE\"\n )\n\n astro_curl(@validator_url, data)\n end", "def authorize_and_capture\n \n resp = StdClass.new \n if self.financial_status == Invoice::FINANCIAL_STATUS_CAPTURED\n resp.error = \"Funds for this invoice have already been captured.\"\n else\n \n sc = self.site.store_config \n case sc.pp_name \n when StoreConfig::PAYMENT_PROCESSOR_STRIPE\n \n Stripe.api_key = sc.stripe_secret_key.strip\n bt = nil\n begin\n c = Stripe::Charge.create(\n :amount => (self.total * 100).to_i,\n :currency => 'usd',\n :customer => self.customer.stripe_customer_id,\n :capture => true,\n :metadata => { :invoice_id => self.id },\n :statement_descriptor => \"#{self.site.description.truncate(22)}\"\n ) \n rescue Exception => ex\n resp.error = \"Error during capture process\\n#{ex.message}\" \n end \n if resp.error.nil?\n InvoiceTransaction.create(\n :invoice_id => self.id,\n :transaction_id => c.id,\n :transaction_type => InvoiceTransaction::TYPE_AUTHCAP,\n :payment_processor => sc.pp_name,\n :amount => c.amount / 100.0,\n :captured => true,\n :date_processed => DateTime.now.utc,\n :success => c.status == 'succeeded'\n )\n if c.status == 'succeeded'\n self.financial_status = Invoice::FINANCIAL_STATUS_CAPTURED\n self.save\n resp.success = true\n else\n resp.error = \"Error capturing funds.\"\n end\n end\n \n end \n end \n return resp\n end", "def authorized_with_capture(options = {})\n options = { date_authorized: Date.current, date_captured: Date.current }.merge(options)\n request_params = {\n 'customerID' => customer_id,\n 'cartID' => cart_id,\n 'orderID' => order_id,\n 'dateAuthorized' => xml_date(options[:date_authorized]),\n 'dateCaptured' => xml_date(options[:date_captured])\n }\n\n response = TaxCloud.client.request :authorized_with_capture, request_params\n TaxCloud::Responses::AuthorizedWithCapture.parse response\n end", "def capture_transaction\n data = full_params.merge(\n 'x_unique_id' => unique_id,\n 'x_invoice_num' => invoice_num,\n 'x_auth_code' => approval_code,\n 'x_type' => \"CAPTURE_ONLY\"\n )\n\n astro_curl(@validator_url, data)\n end", "def capture(_, authorization, options = {})\n transaction { transaction_api.capture_transaction(preferences[:access_token], location_id, authorization) }\n end", "def create_transaction_auth_capture(amount, profile_id, payment_profile_id, order = nil, options = {})\n create_transaction(:auth_capture, amount, profile_id, payment_profile_id, order, options)\n end", "def authorized_with_capture(options = {})\n options = { :date_authorized => Date.today, :date_captured => Date.today }.merge(options)\n request_params = {\n 'customerID' => customer_id,\n 'cartID' => cart_id,\n 'orderID' => order_id,\n 'dateAuthorized' => options[:date_authorized],\n 'dateCaptured' => options[:date_captured]\n }.merge(TaxCloud.auth_params)\n\n response = TaxCloud.client.request :authorized_with_capture, :body => request_params\n end", "def test_authorization_and_capture\n assert authorization = @gateway.authorize(@amount, @good_card, @options)\n assert_success authorization\n\n assert capture = @gateway.capture(@amount, authorization.authorization)\n assert_success capture\n assert capture.params['aux_msg'].include? 'has been successfully marked for settlement.'\n assert_equal 'Success', capture.message\n end", "def capture(money, authorization, options = {})\n post = { trans_id: authorization }\n add_customer_data(post, options)\n commit('PRIOR_AUTH_CAPTURE', money, post)\n end", "def capture\n raise InvalidOperation unless authorized?\n raise InvalidOperation if captured?\n\n @payment_gateway.capture(@payment_gateway_transaction_identifier)\n\n apply(Payments::CaptureSucceeded.strict(data: {\n transaction_identifier: @transaction_identifier,\n payment_gateway_identifier: @payment_gateway.identifier,\n payment_gateway_transaction_identifier: @payment_gateway_transaction_identifier,\n order_number: @order_number,\n amount: @amount,\n currency: @currency\n }))\n rescue PaymentGatewayCaptureFailed\n apply(Payments::CaptureFailed.strict(data: {\n transaction_identifier: @transaction_identifier,\n payment_gateway_identifier: @payment_gateway.identifier,\n order_number: @order_number\n }))\n end", "def test_authorization_and_capture\n assert authorization = @gateway.authorize(100, @good_creditcard)\n assert authorization.success?\n \n assert capture = @gateway.capture(100, authorization.authorization)\n assert capture.success?\n assert_equal 'Success', capture.message\n end", "def purchase!\n if ratepay?\n capture!\n elsif adyen_cc_payment?\n authorize!\n capture!\n else\n super\n end\n end", "def capture_payment(options = {})\n # transaction do\n capture = OrderTransaction.capture(amount, authorization_reference, options)\n self.save!\n self.order_transactions << capture\n\n if capture.success?\n self.payment_captured!\n else\n self.transaction_declined!\n end\n\n capture\n # end\n end", "def process_with_active_merchant\n options = populate_options\n auth = authorize_payment(options)\n save!\n if APP_CONFIG['pre_and_post_authorization'] == true\n if auth.success == true\n capture_payment(options)\n save!\n end\n end\n end", "def test_credit_card_authorize_and_capture_amount_low\n assert auth = @gateway.authorize(@amount, @credit_card, @options)\n assert_success auth\n assert_equal 'Approved', auth.message\n assert capture = @gateway.capture(@amount-100, auth.authorization, @credit_card, @options)\n assert_success capture\n assert_equal 'Approved', capture.message\n end", "def test_authorize_and_capture\n amount = @amount\n assert response = @gateway.authorize(amount, @credit_card, @options)\n assert_success response\n assert_nil response.message\n assert response.authorization\n assert capture = @gateway.capture(amount, response.authorization)\n assert_success capture\n end", "def test_successful_authorize_and_capture\n response = @gateway.authorize(@amount, @credit_card, @options)\n assert_success response\n\n response = @gateway.capture(@amount, response.authorization)\n assert_success response\n end", "def capture!(capture_amount = nil)\n if hpp_payment? || adyen_cc_payment? || ratepay?\n amount = money.money.cents\n process do\n payment_method.send(\n :capture, amount, response_code, gateway_options)\n end\n else\n super\n end\n end", "def create_transaction_prior_auth_capture(transaction_id, amount, order = nil, options = {})\n handle_transaction_id(transaction_id)\n create_transaction(:prior_auth_capture, amount, nil, nil, order, options)\n end", "def capture(\n amazon_authorization_id,\n capture_reference_id,\n amount,\n currency_code: @currency_code,\n seller_capture_note: nil,\n soft_descriptor: nil,\n provider_credit_details: nil,\n merchant_id: @merchant_id,\n mws_auth_token: nil\n )\n\n parameters = {\n 'Action' => 'Capture',\n 'SellerId' => merchant_id,\n 'AmazonAuthorizationId' => amazon_authorization_id,\n 'CaptureReferenceId' => capture_reference_id,\n 'CaptureAmount.Amount' => amount,\n 'CaptureAmount.CurrencyCode' => currency_code\n }\n\n optional = {\n 'SellerCaptureNote' => seller_capture_note,\n 'SoftDescriptor' => soft_descriptor,\n 'MWSAuthToken' => mws_auth_token\n }\n\n optional.merge!(set_provider_credit_details(provider_credit_details)) if provider_credit_details\n\n operation(parameters, optional)\n end", "def capture(amount, authorization, options = {})\n xml = signon_app_cert_rq\n response = commit('session_ticket', xml)\n if response.success?\n options[:session_ticket] = response.authorization\n xml = customer_credit_card_capture_rq(amount, authorization, options)\n commit('capture', xml)\n end\n end", "def capture(money, authorization, options = {})\r\n request = RocketGate::GatewayRequest.new\r\n response = RocketGate::GatewayResponse.new\r\n service = RocketGate::GatewayService.new\r\n if test? # Test transaction?\r\n service.SetTestMode(true) # Set internal test mode\r\n end\r\n\r\n#\r\n#\tAdd the details of the transaction to the request.\r\n#\r\n add_merchant_data(request, options) # Add merchant information\r\n add_financial_data(request, money, options)\r\n request.Set(RocketGate::GatewayRequest::TRANSACT_ID, authorization)\r\n\r\n#\r\n#\tPeform the transaction and return a response.\r\n#\r\n service.PerformTicket(request, response)\r\n return create_response(response)\r\n end", "def capture(money, authorization, options = {})\n post = {}\n\n # remove last 4 digits of cc number as they are not required here\n post[:postonly] = authorization[0...-4]\n\n commit(post[:userprofileid] ? :profile_sale : :ns_quicksale_cc, money, post)\n end", "def capture(money, authorization, options = {})\n requires!(options, :order_id) \n \n order = retrieve_order(options[:order_id])\n return order if order.is_a?(Response)\n commit(build_capture_request(money, options[:order_id], order[:payment_product_id])) \n end", "def capture(transaction_id, amount)\n\t\t\traise \"Sorry we haven't compelted this functionality yet.\"\n\t\tend", "def get_auth_transaction\n\t\ttrans = self.create_transaction\n\t\t# Set order specific fields\n\t\ttrans.type = 'AUTH_CAPTURE'\n\t\treturn trans\n\tend", "def purchase!\n if adyen_cc_payment?\n capture!\n else\n super\n end\n end", "def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end", "def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end" ]
[ "0.6622601", "0.66165835", "0.66148984", "0.64050114", "0.6402435", "0.62876874", "0.6284776", "0.62716687", "0.6201491", "0.6200618", "0.61151105", "0.6092354", "0.606081", "0.6026894", "0.6023429", "0.601596", "0.5996501", "0.5947878", "0.59419584", "0.5903622", "0.5870499", "0.58447015", "0.5835913", "0.57892", "0.5742579", "0.5726837", "0.57035184", "0.56795263", "0.56758344", "0.56758344" ]
0.6712602
0
Get an strategy by its id
def get(id) self.class.strategies.select { |strategy| strategy.id == strategy.id } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_strategy\n @strategy = Strategy.find(params[:id])\n end", "def set_strategy\n if params[:id]\n @strategy = Strategy.find(params[:id])\n else \n @strategy = Strategy.find_by(uuid: params[:uuid])\n end\n end", "def _fetch_strategy(name, scope)\n @strategies[scope][name] ||= if klass = Watchman::Strategies[name]\n klass.new(@env, scope)\n elsif @config.silence_missing_strategies?\n nil\n else\n raise \"Invalid strategy #{name}\"\n end\n end", "def sso_strategy_id\n @attributes[:sso_strategy_id]\n end", "def find id\n result = perform_request api_url \"champions/#{id}\"\n DynamicModel.new result\n end", "def find_strategy(type)\n \"Simple::OAuth2::Strategies::#{type.to_s.camelize}\".constantize\n end", "def get(id)\n klass.find(:first, params: { klass.primary_key => wrap_key(id) })\n end", "def [](label)\n _strategies[label]\n end", "def find_resource(id)\n query_service.find_by(id: Valkyrie::ID.new(id.to_s))\n end", "def set_b_strategy\n @b_strategy = BStrategy.find(params[:id])\n end", "def get_service_by_id(id)\n if params[:id]\n Service.find(params[:id])\n else\n nil #todo error handling.\n end\n end", "def service(id)\n ss = services\n ss.keep_if {|s| s.id == id}.first unless ss.nil?\n end", "def find_by_id(id)\n find(id)\n end", "def find(id)\n klass.find(id)\n end", "def [](label)\n strategies[label]\n end", "def lookup(id_or_slug)\n id_or_slug = id_or_slug.to_s\n\n # find plan by a specific objectid\n result = where(:_id => id_or_slug).first if BSON::ObjectId.legal?(id_or_slug)\n result ||= find_by_slug(id_or_slug) if id_or_slug.present?\n\n # make sure the plan exists\n result\n end", "def get(id, db = database)\n begin\n get!(id, db)\n rescue\n nil\n end\n end", "def find_by_id(id)\n @features.find { |feature| feature.id == id }\n end", "def find_driver(id)\n return find_by_id(@drivers, id)\n end", "def find_by_id(id)\n find_by_attributes(:id => id).first\n end", "def trip_get_driver(driver_id)\n RideShare::Driver.find(driver_id)\n end", "def find_by_id(id)\n id = id.to_i\n\n @id_hash[id]\n end", "def get(id)\n @service.get(id)\n end", "def find_by(id:)\n storage_adapters.values.find do |storage_adapter|\n storage_adapter.handles?(id: id)\n end.find_by(id: id)\n end", "def find_by_id(clazz, id)\n clazz.find(id)\n end", "def find_service(id)\n self.class.get(\"/services/#{id}.json?apikey=#{apikey}\")\n end", "def show\n @strategy = Strategy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @strategy }\n end\n end", "def find(id, options = {})\n decorated = decorated_class.find(id)\n decorated ? resolve_associations([new(decorated)], options).first : nil\n end", "def get_from_id(id)\n @bucket_id_map[id]\n end", "def get_object_by_id(class_name, id)\n obj = nil\n get_objects_of_class(class_name).each do |o|\n if o.id == id\n obj = o\n break\n end\n end\n obj\n end" ]
[ "0.687599", "0.6719225", "0.61248964", "0.60925907", "0.603201", "0.59219956", "0.58672255", "0.57997185", "0.5797541", "0.5793163", "0.57907176", "0.57891375", "0.57810223", "0.5767059", "0.5754778", "0.5749873", "0.5743043", "0.5742503", "0.5708508", "0.5689515", "0.5684819", "0.5668946", "0.56682014", "0.5664523", "0.56596684", "0.5641643", "0.56390446", "0.56352186", "0.56272787", "0.5621144" ]
0.854905
0