query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
sequencelengths
19
19
metadata
dict
Sets the showNameNextToLogo property value. Boolean that represents whether the administratorsupplied display name will be shown next to the logo image.
def show_name_next_to_logo=(value) @show_name_next_to_logo = value end
[ "def show_display_name_next_to_logo=(value)\n @show_display_name_next_to_logo = value\n end", "def show_name_next_to_logo\n return @show_name_next_to_logo\n end", "def show_display_name_next_to_logo\n return @show_display_name_next_to_logo\n end", "def show_logo=(value)\n @show_logo = value\n end", "def show_logo\n return @show_logo\n end", "def small_logo=(value)\n @children['small-logo'][:value] = value\n end", "def show_logo(seller, size: nil)\n logo = seller.spree_image\n link_to image_tag( main_app.url_for(logo.url(:size))), main_app.url_for(logo.url(:size)) if logo.present?\n end", "def logo=(value)\n @logo = value\n end", "def set_avatar_name\n self.display_name ||= self.username\n end", "def show_series_name=(value)\n @show_series_name = value\n end", "def logo_img?\n !to_bool(ENV[\"DISABLE_DASHBOARD_LOGO\"])\n end", "def large_logo=(value)\n @children['large-logo'][:value] = value\n end", "def show_name?\n !!self[:show_name]\n end", "def HideNextButton\n if UI.WizardCommand(term(:SetNextButtonLabel, \"\")) == false\n if UI.WidgetExists(Id(:rep_next))\n UI.ReplaceWidget(Id(:rep_next), Empty())\n end\n end\n\n nil\n end", "def set_image_title\n controller_name == 'temp_listings' ? '' : 'Pin it @ Pinterest'\n end", "def auto_name_favorites\n self.title = self.description = self.user.name + \"'s Favorite tracks on alonetone\" if self.is_favorite?\n end", "def admin_consent_display_name=(value)\n @admin_consent_display_name = value\n end", "def get_logo_display\n\t\tif !logged_in?\n\t\t\treturn \"City Produce\"\n\t\tend\n\t\tif current_user.admin?\n\t\t\treturn \"Admin\"\n\t\tend\n\t\treturn \"Home\"\n\tend", "def SetTitleIcon(icon_name)\n icon = icon_name == \"\" ?\n \"\" :\n Ops.add(Ops.add(Ops.add(@icon_path, \"/\"), icon_name), \".png\")\n\n UI.WizardCommand(term(:SetDialogIcon, icon))\n\n nil\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the themeColor property value. Primary theme color used in the Company Portal applications and web portal.
def theme_color return @theme_color end
[ "def theme_color(theme_object=current_theme)\n if theme_object\n return theme_object[:color].to_s.downcase if theme_object[:color]\n return theme_name_color(theme_object[:type]) if theme_object[:type]\n end\n end", "def theme_color=(value)\n @theme_color = value\n end", "def style_name\n theme_color\n end", "def theme\n return @theme\n end", "def chrome_themecolor\n return unless zone&.chrome_themecolor&.present?\n\n tag :meta, name: 'theme-color', content: zone.chrome_themecolor\n end", "def theme\n Design::Theme.array.find_by_name(self.theme_name || 'Default')\n end", "def theme_style_url\n theme_color_url\n end", "def color_scheme\n @color_scheme\n end", "def get_slides_theme_color_scheme(request)\n data, _status_code, _headers = get_slides_theme_color_scheme_with_http_info(request)\n data\n end", "def current_theme \n if @current_theme.nil? \n @current_theme = get_default_theme \n end \n @current_theme \n end", "def theme=(value)\n @theme = value\n end", "def style_variables\n default_style_variables = {\n \"primary_color\" => \"#e91b23\", # red\n \"secondary_color\" => \"#3498db\", # blue\n \"action_color\" => \"green\",\n \"body_style\" => \"siteLayout.wide\",\n \"theme\" => \"light\",\n }\n style_variables_for_theme[\"default\"] || default_style_variables\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 alt_heading_colour\n if self.theme.background_colour == Color::RGB::White.html\n self.palette.foreground_dark\n else\n self.palette.foreground_light\n end\n end", "def get_theme\n use_theme = Preference.get_setting('CURRENT_THEME')\n (use_theme == '' ? 'default' : use_theme).downcase\n end", "def getColor(theColor, default = 'gray')\n preset = Proc.new do |color|\n case color\n when 'windowBackground' then return NSColor.windowBackgroundColor # 0.93\n when 'textColor' then return NSColor.textColor # 0.0\n when 'backgroundColor' then return NSColor.textBackgroundColor # 1.0\n when 'clear' then return NSColor.clearColor\n else color\n end\n end\n if preset.call(theColor) == 'box' # box fill color doesn't have a system color\n dark = !NSAppearance.currentAppearance.name.to_s.index('Dark').nil?\n rgb = dark ? [0.12, 0.12, 0.12] : [0.89, 0.89, 0.89]\n else # get the specified color or default - no dark mode swaps are performed\n rgb = COLORS[preset.call(default)] if (rgb = COLORS[theColor]).nil?\n end\n rgb = [0.5, 0.5, 0.5] if rgb.nil? # get gray if nothing else has worked\n NSColor.colorWithSRGBRed( rgb[0],\n green: rgb[1],\n blue: rgb[2],\n alpha: 1.0 )\n end", "def current_theme\n @theme\n end", "def selected_theme\n @themes[@selected_theme]\n end", "def current_theme_name\n @theme_name\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the themeColor property value. Primary theme color used in the Company Portal applications and web portal.
def theme_color=(value) @theme_color = value end
[ "def theme=(value)\n @theme = value\n end", "def theme_color\n return @theme_color\n end", "def change_theme_color!(old_theme_color, new_theme_color, bg_color = ChunkyPNG::Color::WHITE, tolerance = 5)\n base, mask = extract_mask(old_theme_color, bg_color, tolerance)\n mask.change_mask_color!(new_theme_color)\n self.replace(base.compose(mask))\n end", "def chrome_themecolor\n return unless zone&.chrome_themecolor&.present?\n\n tag :meta, name: 'theme-color', content: zone.chrome_themecolor\n end", "def set_box_theme(id, theme)\n @themes[id] = theme.to_i\n end", "def color=(theColor)\n @shadowHash[:fillcolor] = theColor\n end", "def theme_color(theme_object=current_theme)\n if theme_object\n return theme_object[:color].to_s.downcase if theme_object[:color]\n return theme_name_color(theme_object[:type]) if theme_object[:type]\n end\n end", "def theme(theme)\n case theme\n when :dark\n @methods[:theme] = MIDNIGHT\n when :deep\n @methods[:theme] = SUBMARINE\n when :light\n @methods[:theme] = BLUESCALE\n else\n throw ArgumentError.new('Not a valid theme')\n end\n end", "def set_fg_color(color = 0x40)\n @fg_color = get_color(color)\n end", "def set_app_color\n\t\t# update the color values with params of color\n\t\tsetting.update(type_app_color: params[:color])\n\t\t# redirect to the same page of color palette page\n\t\tredirect_to :back\n\tend", "def change_theme_color!(old_theme_color, new_theme_color, bg_color = T.unsafe(nil), tolerance = T.unsafe(nil)); end", "def color=(value)\n @color = value\n end", "def set_forum_theme\n @forum_theme = ForumTheme.find(params[:id])\n end", "def set_Color(value)\n set_input(\"Color\", value)\n end", "def set_color color\n unless COLORS.include? color\n raise \"Invalid color: #{color}\"\n end\n reset\n set_color_raw color\n end", "def set_Color(value)\n set_input(\"Color\", value)\n end", "def set_theme\n cookies.permanent[:themeMode] = params[:theme][:mode] || \"light\"\n cookies.permanent[:themeVariantName] = params[:theme][:variantName]\n cookies.permanent[:themeVariantHue] = params[:theme][:variantHue]\n\n flash[:success] = \"Theme has been set to #{params[:theme][:mode].capitalize} #{params[:theme][:variantName]}\"\n redirect_back fallback_location: root_path\n end", "def apply_theme( theme )\n self.theme_id= theme.id\n save!\n end", "def apply_theme( theme)\n self.theme_id= theme.id \n save!\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a relative filepath to the dataset. Handles dicoms by returning the dataset directory, and pfiles by returning either the pfile filename or, if passed a visit directory, the relative path from the visit directory to the pfile (i.e. P00000.7 or raw/P00000.7).
def relative_dataset_path(visit_dir = nil) if pfile? relative_dataset_path = scanned_file else # Then it's a dicom. relative_dataset_path = File.basename(path) end return relative_dataset_path end
[ "def relative_dataset_path(visit_dir = nil)\n image_file = @raw_image_files.first\n case image_file.file_type\n when 'dicom', 'geifile'\n relative_dataset_path = File.basename(directory)\n when 'pfile'\n full_dataset_path = Pathname.new(File.join(directory, image_file.filename))\n if visit_dir\n relative_dataset_path = full_dataset_path.relative_path_from(visit_dir)\n else\n relative_dataset_path = image_file.filename\n end\n when 'scan_archive_h5_json'\n full_dataset_path = Pathname.new(File.join(directory, image_file.filename))\n if visit_dir\n relative_dataset_path = full_dataset_path.relative_path_from(visit_dir)\n else\n relative_dataset_path = image_file.filename\n end\n else raise \"Cannot identify #{@raw_image_files.first.filename}\"\n end\n \n return relative_dataset_path\n end", "def dataset_dir\n path.parent\n end", "def dataset_path\n @dataset_path ||= filename\n end", "def data_file_full_path\n File.join(@data_lib.dir_name,\"#{@data_set_name}\")\n end", "def dataset_file_path(dataset_name, file)\n path = File.join(datasets_dir, dataset_name, file)\n unless File.file?(path)\n raise \"#{path} does not exist\"\n end\n\n path\n rescue\n flunk(\"dataset #{dataset_name} has not been generated: #{$!.message}\")\n end", "def resolve_paths\n [dataset_dir, parent.dataset_dir]\n end", "def get_data_file_path(file_name)\n base = File.dirname __FILE__\n File.join(base, \"data\", file_name)\nend", "def relative_path_of file, dir\n file.relative_path_from(dir)\n end", "def file_path(relative = false)\n File.join(data_directory(relative), self.id.to_s)\n end", "def rel_path \n dir = File.dirname(@descriptor_path)\n dir.split(\"DIPs/\").last\n end", "def pages_path\n return File.expand_path(\"data/imdb_pages\") if File.exist?(\"data/imdb_pages\")\n File.join(File.dirname(File.expand_path(\"../../\", __FILE__)), 'data/imdb_pages')\n end", "def relative_path(filename, base_directory)\n if (is_root? filename) && (is_root? base_directory)\n offset = base_directory.chomp(@file_separator).length + 1\n filename[offset..-1]\n else\n filename\n end\n end", "def resolve_paths\n [dataset_dir]\n end", "def dir_path\n Index.virtual_parent_dir_for(filename,false) || path.sub(/\\/[^\\/]+\\Z/m,'')\n end", "def data_path(db_name, collection_name)\n File.join(@path, db_name, collection_name, 'data')\n end", "def relative_path(filename)\n\t\t\tpieces = split_filename(File.expand_path(filename))\n\t\t\tFile.join(pieces[@mount_dir_pieces.size..-1])\n\t\tend", "def basedir\n File.directory?(@file) ? @file : File.dirname(@file)\n end", "def relative_directory\n return '' unless @directory_root\n @path - @directory_root - name\n end", "def generate_filepath_nature\n data = get_fat32_compliant_data\n\n path = []\n path << root_dir\n path << \"nature\"\n path << data['album']\n path << \"#{data['index']} - #{data['title']}#{data['ext']}\"\n\n return path.join(\"/\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries ActiveResource for an array of ImageDatasetQualityCheckResources
def image_dataset_quality_checks @image_dataset_quality_checks ||= ImageDatasetQualityCheckResource.find(:all, :params => {:image_dataset_id => id }) end
[ "def index\n scan_procedure_array = (current_user.view_low_scan_procedure_array).split(' ').map(&:to_i)\n @image_dataset = ImageDataset.where(\"image_datasets.visit_id in (select visit_id from scan_procedures_visits where scan_procedure_id in (?))\", scan_procedure_array).find(params[:image_dataset_id]) if params[:image_dataset_id]\n @image_dataset_quality_checks = @image_dataset ? @image_dataset.image_dataset_quality_checks : ImageDatasetQualityCheck.includes(:user).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @image_dataset_quality_checks }\n end\n end", "def media_quality_list\n return @media_quality_list\n end", "def query_resources\n powershell_exec(\"get-dscresource\").result\n end", "def qualities()\n @watches.sort_by!{|watch| watch[:time]}\n ret = []\n @watches.each do |watch|\n next unless watch[:quality_info] and /video/ =~ watch[:quality_info]['response_content_type']\n ret << watch[:quality_info]\n end\n ret\n end", "def query_image_scg_list\n query_image_list\n get_url('compute')\n @resource_id_list.each do |img|\n ind = @resource_id_list.index(img)\n puts \"The supported Storage Connectivity groups for the image #{@resource_name_list[ind]} are:\"\n response = rest_get(\"#{@resource_url}/images/#{img}/storage-connectivity-groups\", @token_id)\n response_array = JSON.parse(response)\n @response_hash = response_array['storage_connectivity_groups']\n @response_hash.each do |scg|\n puts scg['display_name']\n end\n end\n end", "def index\n @image_queries = ImageQuery.all.with_attached_image\n end", "def applied_resources\n report.resource_statuses.values.collect { |status| catalog.resource(status.resource) }\n end", "def medium_images\r\n return pictures.select{ |pic| pic.size_type == Picture::SIZE_MEDIUM }\r\n end", "def getQualityScores(filestream, directory, numElements, numBases)\n qualityScore = []\n (0..numElements-1).each do |i|\n if (get(directory[i], \"name\") == \"PCON\") && (get(directory[i], \"tag_number\") == 2)\n byteArray_seq = \"\"\n filestream.seek(get(directory[i], \"data_offset\"))\n filestream.read(numBases,byteArray_seq)\n (0..numBases-1).each do |j|\n qualityScore[j] = byteArray_seq.getbyte(j)\n end\n end\n end\n return qualityScore\n end", "def project_thumbnail_resources(project)\n resources = Array.new\n for image in project_images(project)\n resources << project_thumbnail_resource(project, image)\n end \n\n return resources\n end", "def images\n self.assets.find_all{ |asset| asset.image? }\n end", "def resources\n '.Resources|with_entries(.value.LogicalResourceId = .key)[]'\n end", "def quick_view_images\n returned_images = []\n images = @record.fetch('ImageQuickViewItems', {})\n if images.count > 0\n images.each do |quick_view_item|\n image_id = quick_view_item['DbId']\n image_accession = quick_view_item['An']\n image_type = quick_view_item['Type']\n # todo: change to https, large/small url?\n image_url = quick_view_item['Url']\n returned_images.push({url: image_url, id: image_id, accession_number: image_accession, type: image_type})\n end\n end\n returned_images\n end", "def scan_images\n assert_privileges(\"image_scan\")\n showlist = @lastaction == \"show_list\"\n ids = showlist ? find_checked_ids_with_rbac(ContainerImage) : find_current_item(ContainerImage)\n\n if ids.empty?\n add_flash(_(\"No %{model} were selected for Analysis\") % {:model => ui_lookup(:tables => \"container_image\")},\n :error)\n else\n process_scan_images(ids)\n end\n\n showlist ? show_list : show\n ids.count\n end", "def query_resource(resource_name)\n ret_val = powershell_exec(\"get-dscresource #{resource_name}\").result\n if ret_val.empty?\n []\n elsif ret_val.is_a? Array\n ret_val\n else\n [ret_val]\n end\n end", "def scan_images\n assert_privileges(\"image_scan\")\n showlist = @lastaction == \"show_list\"\n ids = showlist ? find_checked_items : find_current_item(ContainerImage)\n\n if ids.empty?\n add_flash(_(\"No %{model} were selected for Analysis\") % {:model => ui_lookup(:tables => \"container_image\")},\n :error)\n else\n process_scan_images(ids)\n end\n\n showlist ? show_list : show\n ids.count\n end", "def full_matching_images\n images = @grpc.full_matching_images\n @full_matching_images ||= Array(images).map do |i|\n Image.from_grpc i\n end\n end", "def get_qual_records\n records = storage_engine.get_all\n qual_records = []\n records.each do |record|\n qual_records << record if record.qualified?\n end\n qual_records\n end", "def get_all_image_type_obj_for_job\r\n image_type_obj_array = []\r\n images_for_jobs.each do |images_for_job|\r\n image_type_obj_array << ImageType.where([\"images_for_job_id = ?\", images_for_job.id])\r\n end\r\n image_type_obj_array = image_type_obj_array.flatten\r\n image_type_obj_array\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether user submitted pid
def is_problem_submitted? pid runs.where(pid: pid).count > 0 end
[ "def user_process?\n @priority > 0\n end", "def given_user_can_submit?(user_id)\n given_user_can?(user_id, 'submit')\n end", "def valid_pid?(pid)\n (pid.is_a?(Integer) and pid > 0) ? true : false\n end", "def valid_pid?(pid)\n pid.length == 9\n end", "def got_term?\n pid && @raw[4] != 0\n end", "def is_processed?\n return meet_id? # might be faster than check meet directly\n end", "def pid_file?\n return true if File.exist?(pid_path)\n false\n end", "def running?\n return true if pid\n end", "def pid_exists?\n return FileTest.exists?(pid_file)\n end", "def already_punched?(user_id)\n punch = Punch.where(user_id: id, user_punched: user_id)\n punch.size > 0 ? true : false\n end", "def pid_running?(pid)\n ps = pid ? Sys::ProcTable.ps(pid) : nil\n if ps\n # Asume, that if the command of the 'ps'-output is 'ruby', the process is still running\n ps.comm == 'ruby'\n else\n false\n end\n end", "def has_prot?(pid)\n @proteins.has_key?(pid)\n end", "def has_uid_or_gid_action\n uid = request[:uid]\n\n begin\n Etc.getpwuid(uid)\n Etc.getgrgid(uid)\n reply[:output] = true\n rescue TypeError, ArgumentError\n reply[:output] = false\n end\n reply[:exitcode] = 0\n end", "def process_running?(pid)\n return false unless pid\n Process.getpgid(pid) != -1\n rescue Errno::ESRCH\n false\n end", "def process_running?(pid_file_or_pid)\n pid = pidize(pid_file_or_pid)\n (pid and system(\"ps -p #{pid} | grep #{pid}\")) ? true : false\n end", "def _pid_file_process_running?\n begin\n Process.getpgid(_pid_file_pid)\n return true\n rescue\n return false\n end\n end", "def submitted?\n not @time_submitted.nil?\n end", "def is_problem_accepted? pid\n runs.where(result: \"Accepted\", pid: pid).count > 0\n end", "def worker_process?\n @pid == $$\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the rank of user
def rank User.where('local_ac > :local_ac OR ( local_ac = :local_ac AND ( total_ac > :total_ac OR ( total_ac = :total_ac AND ( total_submit < :total_submit OR ( total_submit = :total_submit AND username < :username )))))', local_ac: local_ac, total_ac: total_ac, total_submit: total_submit, username: username).count + 1 end
[ "def user_rank!\n r = 1\n users.order('rating DESC').each do |u|\n user_universities.find_by_user_id(u.id).update_attribute(:rank, r)\n r += 1\n end\n end", "def rank_players(competition)\n\t\tusers=competition.users\n\t\tsorted_users = users.sort_by{|u| [(100 - user_percents(u)), u.submitted_at]}\n\t\tcount=0\n\t\trank=1\n\t\tsorted_users.each do |u|\n\t\t\t#if two or more users have the same result and submit at the end of the competition they must have equal ranks!!!\n\t\t\tif count > 0 \n\t\t\t\tprevious_user=sorted_users[count-1]\n\t\t\t\t#check if both the user's percents and submitted time are equal to the those of the previous user and if not it change the rank +1\n\t\t\t\t#if they are percents and the times are equal the rank is not changed!!!\n\t\t\t\tif (user_percents(previous_user) != user_percents(u)) || ((u.submitted_at - previous_user.submitted_at) > 5) && (user_percents(previous_user) != 0) \n\t\t\t\t\trank = count+1\n\t\t\t\tend\n\t\t\tend\n\t\t\tu.results[\"rank\"]=rank\n\t\t\tu.save!\n\t\t\tcount += 1\n\t\tend\t\n\tend", "def ranking\n\n s = self.score\n\n # Natural logarithms are the only logaritms that matter.\n # Why do math in base 10 when you can use base e?\n order = Math.log([s.abs, 1].max)\n\n if s > 0\n sign = 1\n elsif s < 0\n sign = -1\n else\n sign = 0\n end\n\n rank = (order * sign) + self.created_at.to_i / 45000\n\n rank\n end", "def get_access_rank\n guest_user_rank = 4\n user = get_user()\n if user != nil\n current_user = User.find_by user_id: \"#{user}\"\n user_rank = current_user.access_rank\n\n #Handler if user access rank missing\n if user_rank === nil\n flash[:notice] = \"Problem getting user access level.\n Please contact site administrator.\"\n user_rank = guest_user_rank\n end\n\n user_rank\n\n else\n user_rank = guest_user_rank\n end\n end", "def getAccessRank\n guest_user_rank = 4\n user = getUser()\n if user != nil\n current_user = User.find_by userid: \"#{user}\"\n user_rank = current_user.access_rank\n\n #Handler if user access rank missing\n if user_rank === nil\n flash[:notice] = \"Problem getting user access level.\n Please contact site administrator.\"\n user_rank = guest_user_rank\n end\n\n user_rank\n\n else\n user_rank = guest_user_rank\n end\n end", "def total_rank(user, interest_weight, skill_weight)\n interest_rank(user, interest_weight) + skill_rank(user, skill_weight)\n end", "def update_rank\n score = Game.where(user_id: id).average(:yscore)\n save!\n rank = User.all.order(:score).map(&:id).index(id) + 1\n save!\n increment!(:played)\n end", "def compute_rank\n age = Time.now.to_i - ctime\n rank = (score * 1000000) / ((age + NewsAgePadding) ** RankAgingFactor)\n rank = - age if age > TopNewsAgeLimit\n rank\n end", "def rank_for_student(name)\n end", "def rank\n BetaUser.where(selected: false).order(score: :desc).index(self)\n end", "def skill_rank(user, weight)\n self.match_skills(user).count * weight.to_f\n end", "def rank\n return @rank\n end", "def rank\n return inv + neg + nsp\n end", "def interest_rank(user, weight)\n self.match_interests(user).count * weight.to_f\n end", "def rank\n x = self.how_many_wins.to_f\n y = self.how_many_wins.to_f + self.how_many_losses.to_f\n if y == 0\n y = 1\n end\n score = x / y\n return score\n end", "def rank\n swish_result_property_u_long(@result, \"swishrank\")\n end", "def get_interest_rank\n \n rank = (self.stories.count * 2) + (self.adding_users.count * 5)\n\n end", "def _user_reference_ranking(text, profile)\n user_references = text.split(WORD_DELIMITER).find_all do |word|\n word.match(/^@/)\n end\n \n return 100 if user_references.size == 0\n\n user_references.inject(0) do |ranking, user|\n ranking + (profile.user_mentions.has_key?(user) ? (100 / user_references.size) : 0)\n end\n end", "def get_rank\n hash = Hash[UserGame.for_game(self.game.id).by_portfolio_value.map.with_index.to_a]\n if hash[self] == 0\n return 1\n else\n x = hash[self]\n while x > 0 && hash.key(x).get_portfolio == hash.key(x-1).get_portfolio\n x -= 1\n end\n return x + 1\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /locations/new GET /locations/new.xml
def new @loc = Location.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @loc } end end
[ "def new\n @location = Location.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @location }\n end\n end", "def new\n @location = Location.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @location }\n end\n end", "def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @location_region }\n end\n end", "def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @location_website }\n end\n end", "def new\n @location_name = LocationName.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @location_name }\n end\n end", "def new\n @testloc = Testloc.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @testloc }\n end\n end", "def new\n @locationset = Locationset.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @locationset }\n end\n end", "def new\n @locations_locationset = LocationsLocationset.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @locations_locationset }\n end\n end", "def new_outgoing_location\n @outgoing_location = Location.find(params[:id])\n @location = Location.new\n\n respond_to do |format|\n format.html { render :action => \"new\" }\n format.xml { render :xml => @location }\n end\n end", "def new\n @location_tag = LocationTag.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @location_tag }\n end\n end", "def new\n @web_location = WebLocation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @web_location }\n end\n end", "def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @location_contact }\n end\n end", "def new\n @class_location = ClassLocation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @class_location }\n end\n end", "def new\n @provider_location = ProviderLocation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @provider_location }\n end\n end", "def new\n @location_context = LocationContext.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @location_context }\n end\n end", "def new\n @map = Map.new\n\n puts @saved_locations\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @map }\n end\n end", "def new\n @groups_location = GroupsLocation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @groups_location }\n end\n end", "def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @location_email }\n end\n end", "def new\n @ship = Ship.new\n @locations = Location.find :all\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ship }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO Abstract retrieval of tracking status to be applicable for before_create and webhook methods
def fetch_tracking_status begin tracker = track(tracking_number) message = extract_message(tracker) self.status = tracker.status self.message= message rescue puts "@@@@@@@@@@@@@@@@@@@@@@ tracking number not found @@@@@@@@@@@@@@@@@@@@@@@@" end end
[ "def check_track_status\n #processing = current_user.jingles.processing\n if jingle.complete?\n render status: :created\n else\n render status: 102\n end\n end", "def tracking?\n result = getEvent(false).result\n result[54] && result[54]['trackingFocusStatus'] == 'Tracking'\n end", "def tracking_url\n end", "def tracking_status_enum\n [ \"paid\", \"suggestion\", \"meeting\", \"choice\", \"inscription\" ]\n end", "def default_status\n tracker.try(:default_status)\n end", "def associate_status\n self.build_status(:content => \"Click here to upload league Status\")\n end", "def retrieve_status\n \n end", "def handle_tracking options = {}\n @tracking_number ||= options[:tracking_number]\n @last_payload_access ||= options[:last_payload_access]\n return unless tracking_number if app_name == :main\n creator = caller[1]\n tracking_service = MessageTrackingService\n .new(tracking_hash.merge(creator: creator))\n .process_payload_creation\n @tracking_number = tracking_service.tracking_number\n begin\n @last_payload_access = tracking_service.message_to_log.slice :checkpoint_hash, :timestamp\n rescue\n @last_payload_access = nil\n end\n end", "def trackable?\n true\n end", "def trackable? \n true \n end", "def tracking_stats\n buyer = @current_user\n property_tracking_count = Events::Track.where(buyer_id: buyer.id).where(type_of_tracking: Events::Track::TRACKING_TYPE_MAP[:property_tracking]).count\n street_tracking_count = Events::Track.where(buyer_id: buyer.id).where(type_of_tracking: Events::Track::TRACKING_TYPE_MAP[:street_tracking]).count\n locality_tracking_count = Events::Track.where(buyer_id: buyer.id).where(type_of_tracking: Events::Track::TRACKING_TYPE_MAP[:locality_tracking]).count\n stats = {\n type: (buyer.is_premium? ? 'Premium' : 'Standard'),\n locality_tracking_count_limit: Events::Track::BUYER_LOCALITY_PREMIUM_LIMIT[buyer.is_premium.to_s],\n street_tracking_count_limit: Events::Track::BUYER_STREET_PREMIUM_LIMIT[buyer.is_premium.to_s],\n property_tracking_count_limit: Events::Track::BUYER_PROPERTY_PREMIUM_LIMIT[buyer.is_premium.to_s],\n locality_tracking_count: locality_tracking_count,\n property_tracking_count: property_tracking_count,\n street_tracking_count: street_tracking_count\n }\n render json: stats, status: 200\n end", "def tracking_number\n @tracking_number\n end", "def create\n @order_status_tracker = OrderStatusTracker.new(order_status_tracker_params)\n\n respond_to do |format|\n if @order_status_tracker.save\n format.html { redirect_to @order_status_tracker, notice: 'Order status tracker was successfully created.' }\n format.json { render :show, status: :created, location: @order_status_tracker }\n else\n format.html { render :new }\n format.json { render json: @order_status_tracker.errors, status: :unprocessable_entity }\n end\n end\n end", "def check_create_status\n if self.v_status.nil?\n status = VStatus.new\n status.v_project = self\n status.v_user_data = self.v_user_data\n self.v_status = status\n end\n end", "def before_create \n self.status = InvoiceStatus.find_by_name('new') \n end", "def tracking_id\n settings.tracking_id\n end", "def status\n @status ||= @raw_status.load\n end", "def check_status\n if status_was && status_was != status\n if status_was == 'pending' && status == 'active'\n feed_post_create\n end\n end\n end", "def incoming_tracked? uid\n @_incoming_tracked ||= tracking_number || randomly_chosen_for_tracking? ||\n has_unexpired_tracker?(uid) || Settings.message_tracking_all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Following function parses Hpricot HTML document. I used Online Plain Text English Dictionary ( to write this app. This specifies following structure for a word entry: Word will be enclosed in HTML tag Category part of speech or type will be enclosed in ( ) Meaning It follows character ')' after category And this whole entry will be enclosed in HTML tag Also it is mentioned that original text is written in "Western MacRoman" encoding.
def parse_html_and_update_dictionary (html_wordsdoc) # Whole word entry is wrapped under <p> </p> tag html_words = (html_wordsdoc/"p") if html_words.empty? @error = "could not find word entries in given document" # Insert a timestamp as well return false end count = 0 # Counter to count number of words pushed into database html_words.each do |html_wordentry| db_wordentry = { } # Actual word is wrapped under <b> </b> tag word = (html_wordentry/"b").inner_html str = html_wordentry.inner_html # If the encoding selected by Ruby itself is wrong then force # "macroman" encoding and re-encode in "UTF-8" for split # function on the word entry. unless str.valid_encoding? str.force_encoding("macRoman") str.encode("UTF-8") end unless word.valid_encoding? word.force_encoding("macRoman") word.encode("UTF-8") end # Meaning follows character ")" meaning= str.split(")") unless word.empty? if meaning.count >= 2 db_wordentry.merge!("word" => word.strip.split(" ")[0].downcase) # Categories of word is wrapped under <i> </i> db_wordentry.merge!("category" => (html_wordentry/"i").inner_html) db_wordentry.merge!("meaning" => meaning[1].strip) count = count.succ if self.add_word(db_wordentry) end end end unless count > 0 @error = "No word entry added in database. Hence invalid html file" # Add timestamp also return false end return true end
[ "def process_words(html)\n\t\t\t\tpage_content = html\n# \t\t\t\tpage_content = Nokogiri::HTML::DocumentFragment.parse(html)\n# \t\t\t\tpage_content = page_content.css(\"page__content\")\n\t\t\t\t@posts.docs.each do |post|\n\t\t\t\t\tpost_title = post.data['title'] || post.name\n\t\t\t\t\tpost_title_lowercase = post_title.downcase\n# \t\t\t\t\tif post_title != @title\n\t\t\t\t\t\tif page_content.include?(\" \" + post_title_lowercase + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title_lowercase + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title_lowercase + \",\") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title_lowercase + \".\")\n# \t\t\t\t\t\t\tif post_title_lowercase == \"groller\"\n# \t\t\t\t\t\t\tputs \"YES, \" + post_title_lowercase + \" will be replaced\"\n# \t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tpage_content = page_content.sub(post_title_lowercase, \"<a href=\\\"#{post.url}\\\">#{post_title.downcase}</a>\")\n\t\t\t\t\t\telsif page_content.include?(\" \" + post_title + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title + \",\") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title + \".\")\n# \t\t\t\t\t\t\tif post_title == \"Groller\"\n# \t\t\t\t\t\t\tputs \"YES, \" + post_title + \" will be replaced\"\n# \t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tpage_content = page_content.sub(post_title, \"<a href=\\\"#{post.url}\\\">#{post_title}</a>\")\n\t\t\t\t\t\tend\n# \t\t\t\t\tend\n\t\t\t\tend\n# \t\t\t\tpage_content.to_html\n\t\t\t\tpage_content\n\t\t\tend", "def parse_tag_descriptions\n \tdoc = Hpricot(open('http://www.scs.leeds.ac.uk/ccalas/tagsets/brown.html'))\n tag_descriptions = []\n tag_keywords = {}\n \t(doc/\"html\"/\"table\"/\"tr\").each do |tr|\n \t idx=1\n \t tag = description = examples = nil\n \t (tr/\"td\").each do |d|\n \t text = d.inner_text.strip.tr(\"\\n\", ' ').gsub(/\\s+/, ' ')\n \t case idx\n when 1; tag = text.downcase\n when 2; description = text\n when 3; examples = text\n end\n \t idx += 1\n end\n tag_descriptions << [ tag, description, examples ] unless tag.nil? or tag == \"Tag\"\n # Use the descriptions to pull out some search keywords for the tag\n if not tag.nil? and description.nil?\n puts \"Description for \" + tag + \" is nil!!!\"\n end\n tag_keywords[tag] = description.tr(\",\",'').tr(\"+\",'').split(/ /) unless tag.nil? or tag == \"Tag\"\n \tend\n \t\n \tclauses = []\n tag_descriptions.map do |td|\n clauses << \"brown_tag_description(\" + (td.map { |e| e.to_prolog }).join(\",\") + \").\"\n end\n\n tag_descriptions.map do |td|\n clauses << \"brown_tag_description(\" + (td.map { |e| e.to_prolog }).join(\",\") + \").\"\n end\n tag_keywords.each_key do |key|\n tag_keywords[key].each do |keyword|\n clauses << \"brown_tag_keyword(\" + key.to_prolog + \",\" + keyword.to_prolog + \").\"\n end\n end\n clauses\n end", "def test_complex2\n parser = HTML_Parser::Parser.new(\"test/testfile2.txt\", \"lib/dictionary.txt\")\n begin\n parse(parser)\n fail \"Unexpected no exception!\"\n rescue Exception => e\n assert_equal(\"Unknown tag mark '<abc>' within '<title>' context.\", e.message)\n end\n end", "def extract_text body, options = {}\n # spans will have no effect on the way things look, we'll just get rid of them\n body.gsub!(/<\\/?span[^>]*>/, '')\n\n # there shall be only one white space between things.\n body.gsub!(/\\s+/o, ' ')\n\n # block-level tag don't need surrounding white space\n ['p', 'li', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div'].each do |tagname|\n body.gsub!(/\\s*(<#{tagname}[^>]*>)\\s*/i, \"\\\\1\")\n body.gsub!(/\\s*(<\\/#{tagname}>)\\s*/i, \"\\\\1\")\n end\n\n document = Hpricot(body)\n\n # replace a lot of common elements, outputs something like markdown\n document.search('head').remove();\n document.search('script').remove();\n document.search('h1').prepend(\"\\n\\n# \").append(\" #\\n\")\n document.search('h2').prepend(\"\\n\\n## \").append(\" ##\\n\")\n document.search('h3').prepend(\"\\n\\n### \").append(\" ###\\n\")\n document.search('h4').prepend(\"\\n\\n#### \").append(\" ####\\n\")\n document.search('h5').prepend(\"\\n\\n##### \").append(\" #####\\n\")\n document.search('h6').prepend(\"\\n\\n###### \").append(\" ######\\n\")\n document.search('p, li').append(\"\\n\")\n document.search('ul li').prepend(\"* \")\n document.search('ol li').prepend(\"1. \") # markdown doesn't care.\n document.search('br').each {|br| br.swap(\"\\n\")}\n document.search('ul, ol').prepend(\"\\n\").append(\"\\n\")\n document.search('a').each {|a| a.swap(\"[#{a.inner_text}](#{a.attributes['href']})\") }\n\n content = if options.has_key? :css\n document.search(options[:css]).inner_text.strip\n elsif options.has_key? :xpath\n (document/options[:xpath]).inner_text.strip\n else\n document.inner_text.strip\n end\n\n if content.length < 100 # 100 characters is an abritrary value. Basically \"small\"\n raise \"Very short content (#{content.length} bytes) after text-extraction. Double-check the selector \\\"#{options[:css] || options[:xpath]}\\\"\"\n end\n content\nend", "def dictionary(search)\n\n # Create new hash object to hold data\n word_object = Hash.new\n\n # Load the document page, find data\n \tdoc = Nokogiri::HTML(open(\"http://www.oxforddictionaries.com/us/definition/american_english/#{search}\")) rescue false\n\n # Add data if response from Nokogiri\n if doc != false\n # set meta data\n word_object[\"word\"] = search\n word_object[\"syll\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div/div/div/header/span/span\").text\n word_object[\"speech\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div[1]/div/div/div[1]/div/section[1]/h2/span\").text\n word_object[\"data\"] = []\n\n # set dictionary data\n 3.times do |i|\n # Create new definition_data object\n definition_data = Hash.new\n\n if (word_object[\"speech\"] == \"noun\")\n if (doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div[1]/div/div/div[1]/div/section[1]/div[1]/div[1]/div/span[2]\").text rescue false == true)\n definition_data[\"definition\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div[1]/div/div/div[1]/div/section[1]/div[1]/div[#{i + 1}]/div/span[2]\").text rescue false\n definition_data[\"example\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div[1]/div/div/div[1]/div/section[1]/div[1]/div[#{i + 1}]/div/span[3]/em\").text rescue false\n else\n definition_data[\"definition\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div/div/div/div[1]/div/section/div[#{i + 1}]/div/span[2]\").text rescue false\n definition_data[\"example\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div/div/div/div[1]/div/section/div[#{i + 1}]/div/span[3]/em\").text rescue false\n end\n elsif (word_object[\"speech\"] == \"adjective\")\n definition_data[\"definition\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div/div/div/div[1]/div/section/div[#{i + 1}]/div/span[2]\").text rescue false\n definition_data[\"example\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div/div/div/div[1]/div/section/div[#{i + 1}]/div/span[3]/em\").text rescue false\n elsif (word_object[\"speech\"] == \"verb\")\n definition_data[\"definition\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div/div/div/div[1]/div/section[#{i + 1}]/div/div/span[1]\").text rescue false\n definition_data[\"example\"] = doc.at_xpath(\"//*[@id='firstClickFreeAllowed']/div[1]/div/div[1]/div/div/div/div[1]/div/section[#{i + 1}]/div/div/span[2]\").text rescue false\n end\n # add if data exists\n if (definition_data[\"definition\"] != false)\n word_object[\"data\"][i] = definition_data\n end\n end\n return word_object.to_json\n else\n wikipedia(search)\n end\n end", "def html_to_words_and_tags\n tokens = []\n n = 0\n html_split(@html.strip).each do |word, offset|\n if word == \"<\" \n tokens[n] = Token.new(offset, word)\n elsif word.match(/^[>.;\\s]$/)\n tokens[n-1].merge Token.new(offset, word)\n else\n token = Token.new(offset, word)\n tokens[n] ? tokens[n].merge(token) : tokens[n] = token\n n += 1\n end\n end\n tokens.map { |t| [t.value.strip, t.offset] }\n end", "def process_text(raw, preserve = false)\n raw.gsub!(/\\s+/, ' ') unless preserve\n src = Kramdown::Utils::StringScanner.new(raw)\n result = []\n until src.eos?\n if (tmp = src.scan_until(/(?=#{HTML_ENTITY_RE})/o))\n result << Element.new(:text, tmp)\n src.scan(HTML_ENTITY_RE)\n val = src[1] || (src[2]&.to_i) || src[3].hex\n result << if %w[lsquo rsquo ldquo rdquo].include?(val)\n Element.new(:smart_quote, val.intern)\n elsif %w[mdash ndash hellip laquo raquo].include?(val)\n Element.new(:typographic_sym, val.intern)\n else\n begin\n Element.new(:entity, entity(val), nil, original: src.matched)\n rescue ::Kramdown::Error\n src.pos -= src.matched_size - 1\n Element.new(:entity, ::Kramdown::Utils::Entities.entity('amp'))\n end\n end\n else\n result << Element.new(:text, src.rest)\n src.terminate\n end\n end\n result\n end", "def toWikiCode(orig)\n\t\tparsed = \"\"\n #Construct Table Of Contents\n\t\tchapters = \"<div id='listOfContents' class='contextual'><b>Table of contents</b><br />\"\n #chapTmp = orig.scan(/<h1>(.*?)<\\/h1>/)\n\t\ttmp = orig.split(\"\\n\")\n\t\turl = getPage(true,true)\n\t\th1 = 0\n\t\th2 = 0\n\t\th3 = 0\n\t\ttmp.each do |a|\n\t\t\t\n\t\t\t#Look for h1\n\t\t\tif(a.include?(\"<h1>\"))\n\t\t\t\th1 += 1\n\n\t\t\t\ta = '<a name=\"'+h1.to_s+'.'+h2.to_s+'.'+h3.to_s+'\"></a>' + a\n\t\t\t\ta = '<div style=\"float:right\"><a href=\"'+url+'/edit?chapter='+h1.to_s+'\">Edit</a></div>' + a\n\n\t\t\t\t#Get chapter name\n\t\t\t\tchapTmp = a.split(\"<h1>\")\n\t\t\t\tchapter = chapTmp[1].split(\"</h1>\").first\n\t\t\t\tchapters = chapters + '<a href=\"#'+h1.to_s+'.'+h2.to_s+'.'+h3.to_s+'\">'+chapter+'</a><br />'\n\t\t\tend\n\n\t\t\tif(a.include?(\"<h2>\"))\n\t\t\t\th2 += 1\n\n\t\t\t\ta = '<a name=\"'+h1.to_s+'.'+h2.to_s+'.'+h3.to_s+'\"></a>' + a\n\t\t\t\ta = '<!-- <div style=\"float:right\"><a href=\"'+url+'/edit?chapter='+h1.to_s+'&h2='+h2.to_s+'\">Edit</a></div> --> ' + a\n\n\t\t\t\t#Get chapter name\n\t\t\t\tchapTmp = a.split(\"<h2>\")\n\t\t\t\tchapter = chapTmp[1].split(\"</h2>\").first\n\t\t\t\tchapters = chapters + '|-- <a href=\"#'+h1.to_s+'.'+h2.to_s+'.'+h3.to_s+'\">'+chapter+'</a><br />'\n\t\t\tend\n\n\t\t\tif(a.include?(\"<h3>\"))\n\t\t\t\th3 += 1\n\t\t\t\t\n\t\t\t\ta = '<a name=\"'+h1.to_s+'.'+h2.to_s+'.'+h3.to_s+'\"></a>' + a\n\t\t\t\ta = '<!-- <div style=\"float:right\"><a href=\"'+url+'/edit?chapter='+h1.to_s+'&h2='+h2.to_s+'&h3='+h3.to_s+'\">Edit</a></div> --> ' + a\n\n\t\t\t\t#Get chapter name\n\t\t\t\tchapTmp = a.split(\"<h3>\")\n\t\t\t\tchapter = chapTmp[1].split(\"</h3>\").first\n\t\t\t\tchapters = chapters + '|--- <a href=\"#'+h1.to_s+'.'+h2.to_s+'.'+h3.to_s+'\">'+chapter+'</a><br />'\n\t\t\tend\n\t\t\t\n\t\t\tparsed += a\n\t\tend\n\n\t\tchapters = chapters + \"</div>\"\n\n\t\tparsed = chapters + parsed\n\n\t\treturn parsed\n\tend", "def html_parser; end", "def test_complex3\n parser = HTML_Parser::Parser.new(\"test/testfile3.txt\", \"lib/dictionary.txt\")\n begin\n parse(parser)\n fail \"Unexpected no exception!\"\n rescue Exception => e\n assert_equal(\"Unexpected tag mark '<i>' within '<head>' context.\", e.message)\n end\n end", "def parse(html)\n\t\t\thtml = html.dup\n\t\t\thtml.gsub!(/(<h\\d>)(.*?)(<\\/h\\d>)/m) do |match|\n\t\t\t\topen = $1\n\t\t\t\ttext = $2\n\t\t\t\tclose = $3\n\t\t\t\tif open == \"<h1>\"\n\t\t\t\t\t@h1 += 1\n\t\t\t\t\t@h2 = 0\n\t\t\t\t\tnum = \"#{@h1}.\"\n\t\t\t\telsif open == \"<h2>\"\n\t\t\t\t\t@h2 += 1\n\t\t\t\t\t@h3 = 0\n\t\t\t\t\tnum = \"#{@h1}.#{@h2}\"\n\t\t\t\telsif open == \"<h3>\"\n\t\t\t\t\t@h3 += 1\n\t\t\t\t\tnum = \"#{@h1}.#{@h2}.#{@h3}\"\n\t\t\t\tend\n\t\t\t\ttags = \"\"\n\t\t\t\tif text[/(<.*>)(.*)/m] then\n\t\t\t\t\ttags = $1\n\t\t\t\t\ttext = $2\n\t\t\t\tend\n\t\t\t\tlink = text.strip\n\t\t\t\ttoc_print \"#{open}<a href=\\\"\\##{link}\\\">#{num} #{text}</a>#{close}\"\n\t\t\t\t\"#{open}#{tags}<a name=\\\"#{link}\\\">#{num} #{text}</a>#{close}\"\n\t\t\tend\n\t\t\t@toc << \"</div>\\n\"\n\t\t\tadd_toc!(html)\n\t\t\treturn html\n\t\tend", "def text_wikimedia_html page\n html = @client.text_wikimedia_html page\n # normalize html by removing <!-- html comments -->\n doc = Nokogiri.HTML html\n (doc.xpath '//comment()').remove\n doc.inner_html\n end", "def html_markup_asciidoc(text); end", "def parse\n return @tree if @tree\n\n # parse tree\n tree = MetaArray.new\n\n # paragraph, sentence, subsentence\n p_id, s_id, ss_id = 0, 0, 0\n\n # current token\n token = ''\n\n # run FSM\n text.each_char do |c|\n case c\n when END_OF_LINE then begin\n case token\n when EMPTY then token << c\n when END_OF_LINE then begin\n token = ''\n p_id += 1\n s_id = 0\n ss_id = 0\n end\n else\n tree[p_id][s_id][ss_id] << token\n token = c\n end\n end\n when SEPARATOR then begin\n case token\n when EMPTY\n else\n tree[p_id][s_id][ss_id] << token\n while tree[p_id][s_id][ss_id].last == c\n tree[p_id][s_id][ss_id].pop\n end\n tree[p_id][s_id][ss_id] << c\n token = ''\n end\n end\n when PUNCTUATION then begin\n case token\n when EMPTY\n else\n tree[p_id][s_id][ss_id] << token\n tree[p_id][s_id][ss_id] << c\n token = ''\n s_id += 1\n ss_id = 0\n end\n end\n when SENTENCE_PUNCTUATION then begin\n case token\n when EMPTY\n else\n tree[p_id][s_id][ss_id] << token\n tree[p_id][s_id][ss_id] << c\n token = ''\n ss_id += 1\n end\n end\n when RUSSIAN_LEXEME then begin\n case token\n when END_OF_LINE then begin\n tree[p_id][s_id][ss_id] << ' '\n token = c\n end\n else\n token << c\n end\n end\n when ENGLISH_LEXEME then begin\n case token\n when END_OF_LINE then begin\n tree[p_id][s_id][ss_id] << ' '\n token = c\n end\n else\n token << c\n end\n end\n when DIGIT then begin\n case token\n when END_OF_LINE then begin\n tree[p_id][s_id][ss_id] << ' '\n token = c\n end\n else\n token << c\n end\n end\n when DIGIT_LETTER then begin\n case token\n when END_OF_LINE then begin\n tree[p_id][s_id][ss_id] << token\n token = c\n end\n else\n token << c\n end\n end\n end\n end\n\n unless token.empty?\n tree[p_id][s_id][ss_id] << token\n end\n\n tree.delete(nil)\n\n @tree = tree.to_a\n end", "def parse_tag(html)\n puts \"-----------------------------------------------------------\"\n str = html.match(/<(.*)>/).captures[0]\n elements= str.scan(/[a-z]{2,5}='[\\w\\s]*'/)\n\n puts \"\\nstring is:: #{str}\"\n puts \"element is:: #{elements} \\n\"\n\n hash = {}\n hash[:type] =str.sub(elements.join(' '), \"\").strip\n \n elements.each do |info|\n clazz = info.match(/([a-z]*)=/).captures[0].to_sym\n clazz_val = info.match(/'(.*)'/).captures[0]\n\n hash[clazz] = clazz_val\n end\n\n print \"hash is:: #{hash} \\n\"\n puts \"-----------------------------------------------------------\"\n end", "def parse_story_from_unknown(story)\r\n work_params = {:chapter_attributes => {}}\r\n storyhead = (@doc/\"head\").inner_html unless (@doc/\"head\").blank?\r\n storytext = (@doc/\"body\").inner_html unless (@doc/\"body\").blank?\r\n if storytext.blank?\r\n storytext = (@doc/\"html\").inner_html\r\n end\r\n if storytext.blank?\r\n # just grab everything\r\n storytext = story\r\n end\r\n meta = {}\r\n unless storyhead.blank?\r\n meta.merge!(scan_text_for_meta(storyhead))\r\n end\r\n meta.merge!(scan_text_for_meta(storytext))\r\n work_params[:title] = (@doc/\"title\").inner_html\r\n work_params[:chapter_attributes][:content] = clean_storytext(storytext)\r\n work_params = work_params.merge!(meta)\r\n\r\n return work_params\r\n end", "def test_complex10\n parser = HTML_Parser::Parser.new(\"test/testfile10.txt\", \"lib/dictionary.txt\")\n begin\n parse(parser)\n fail \"Unexpected no exception!\"\n rescue Exception => e\n assert_equal(\"Bad tag pairing near '</head>'.\", e.message)\n end\n end", "def parse text\n # Extract our headers, if any.\n if text =~ /\\A.*:/\n if text =~ /\\A((?:.|\\n)*?)\\n\\n((?:.|\\n)*)\\z/\n # Headers and body.\n @headers = YAML::load($1)\n content = $2\n else\n # Headers without body.\n @headers = YAML::load(text)\n content = ''\n end\n else\n # Body without headers.\n @headers = {}\n content = text\n end\n\n # Split the body at a <!--more--> marker, if we have one.\n if content =~ /\\A((?:.|\\n)*?)\\n<!--more-->\\s*\\n((?:.|\\n)*)\\z/\n @raw_body = $1\n @raw_extended = $2\n else\n @raw_body = content\n @raw_extended = nil\n end \n end", "def process_page( doc )\n\t\tdoc.xpath( '//p' ).each do |p|\n\t\t\tp.text.split( '.' ).each do |sentence|\n\n\t\t\t\tif @transliterate\n\t\t\t\t\tsentence = I18n.transliterate( sentence.gsub( /[#{UNPROCESSABLE_TRANSLITERATION_CHARACTERS}]/, '' ) )\n\t\t\t\tend\n\n\t\t\t\tused_locale = LOCALE_ALLOWED_CHAR[@locale.to_sym]\n\t\t\t\tused_locale ||= LOCALE_ALLOWED_CHAR[:en]\n\n\t\t\t\tfs = sentence.downcase.gsub( /[,:=<>\\\\\"'\\/{}]/, ' ' ).gsub( /[^#{used_locale}]/, ' ' ).squeeze( ' ' )\n\n\t\t\t\tif fs.length > 5\n\n\t\t\t\t\tword_count = 0\n\t\t\t\t\tlast_word = nil\n\n\t\t\t\t\tfs.split( ' ' ).each do |word|\n\t\t\t\t\t\tif word.length > 1\n\n\t\t\t\t\t\t\tif word_count == 0\n\t\t\t\t\t\t\t\tlast_word = word\n\t\t\t\t\t\t\t\t@first_words[word] ||= 0\n\t\t\t\t\t\t\t\t@first_words[word] += 1\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t@n_grams[last_word] ||= {}\n\t\t\t\t\t\t\t\t@n_grams[last_word][word] ||= 0\n\t\t\t\t\t\t\t\t@n_grams[last_word][word] += 1\n\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t@words[word] ||= 0\n\t\t\t\t\t\t\t@words[word] += 1\n\n\t\t\t\t\t\t\tword_count += 1\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Following function returns all the words that start with given letter. Input : takes a single letter Output: Words: Array which has all the words that starts with given letter
def words_sw_letter(letter) words = [] unless letter.empty? @wordsdb.find({"word" => /^#{letter[0]}/}).each { |word_entry| words << word_entry["word"]} end return words end
[ "def fetch_words_beginning_with(letter)\n regex = Regexp.new(\"^#{letter}\", true)\n return @vocab.select { |key, value| key =~ regex }\nend", "def find_start_letter (array, letter)\n # loop through the array to look for words that start with the letter (use select) \n new_arr_2 = array.select do |value|\n value.downcase.slice(0) == letter.downcase\n end\n new_arr_2\nend", "def words_with_letter (array,letter)\n array.select{|word| word.include? letter}\nend", "def wordsWithLetter(words, letter)\n #only select the words that contain that letter\n words.select{|word| word.include?(letter)} \nend", "def wordFinder(array, letter)\n newArray = []\n array.map do |value|\n if value.include? letter \n newArray << value\n end\n end\n newArray\nend", "def words_with(*letters)\n @lines.select{ |term| \n letters.any?{ |letter|\n term.match(/#{letter}/) \n }\n }\n end", "def basic_letter_parse(letters)\n matching_words = []\n regex = Regexp.new(\"[#{letters}]\").freeze\n @words_collection.each do |word|\n for i in 0..word.length-1 do\n letter = word[i]\n break unless letter =~ regex\n matching_words << word if i == word.length - 1\n end\n end\n matching_words\nend", "def first_wa(array)\n new_array = []\n array.each do |word|\n if word.to_s.start_with?(\"wa\") # or use Regex OR Slice\n new_array << word\n end\n end\n new_array.first\nend", "def first_wa(array)\n first_word_wa = []\n array.detect do |word|\n word[0,2].start_with?(\"wa\")\n end\nend", "def find_a (array)\n new_array=[]\n array.select{|word| \n word.start_with?(\"a\") \n }\nend", "def starts_with(letter)\n titled.find_all { |art| transliterated(art.dup.data.title[0]) == transliterated(letter.dup) }\n end", "def get_all_letters_in_array_of_words(array)\n lets = []\n array.each{|word|\n word.each_char{|letter|\n lets.push(letter)\n }\n }\n lets.sort\nend", "def get_prefixed_words(prefix)\n # FILL ME IN\n return Lexicon.new.trie.find_words_starting_with(prefix)\n end", "def fruits_that_start_with(letter, arr)\n arr.select do |fruit|\n fruit.start_with?(letter)\n end\nend", "def index_of_small_letter(word)\n return_array = []\n\n def which_case(letter)\n case letter\n when /[[:upper:]]/ then return 'uppercase'\n when /[[:lower:]]/ then return 'lowercase'\n else return 'other'\n end\n end\n\n index = 0\n word.chars.each do |char|\n if /[[:lower:]]/ =~ char\n return_array[index] = index\n end\n\n index += 1\n end\n\n # remove nils\n index = 0\n for num in return_array\n if num == nil\n return_array.delete(num)\n end\n\n index += 1\n end\n\n return return_array\nend", "def get_prefixed_words(prefix)\n # This uses Depth First Search with the Trie that was built in the Lexicon Class. It first traverses down the trie \n # until it hits the end of the prefix, then it uses DFS starting there to get all words.\n\n prefix = prefix.downcase\n prefix_copy = prefix[0...-1]\n answer = []\n current_node = @trie.root\n\n while prefix.length > 0\n node = current_node.keys[prefix[0]]\n prefix = prefix[1..-1]\n if node\n current_node = node\n else\n return [\"Sorry, we can't find any words with that prefix\"]\n end\n end\n #we now have the final letter of the prefix as the current node.\n\n answer = dfs(current_node, prefix_copy)\n if @trie.is_word(prefix_copy + current_node.val)\n answer.push(prefix_copy + current_node.val)\n\n end\n return answer.flatten\n end", "def get_all_letters_in_array_of_words(array)\n output = []\n array.each do |word|\n word.chars {|char| output.push(char)}\n end\n return output.sort\nend", "def find_a(array)\n array.find_all do |words|\n words.start_with?(\"a\")\n end\nend", "def select_elements_starting_with_a(array)\n array.select { |string| string.starts_with?('a') }\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets up the numeric value tracker. It will check whether the value and category options are set that are used to extract and categorize the values during parsing. Two lambda procedures are created for these tasks
def prepare raise "No value field set up for numeric tracker #{self.inspect}" unless options[:value] raise "No categorizer set up for numeric tracker #{self.inspect}" unless options[:category] unless options[:multiple] @categorizer = create_lambda(options[:category]) @valueizer = create_lambda(options[:value]) end @categories = {} end
[ "def prepare\n\n raise \"No value field set up for numeric tracker #{self.inspect}\" unless options[:value]\n raise \"No categorizer set up for numeric tracker #{self.inspect}\" unless options[:category]\n\n unless options[:multiple]\n @categorizer = create_lambda(options[:category])\n @valueizer = create_lambda(options[:value])\n end\n \n @number_of_buckets = options[:number_of_buckets] || 1000\n @min_bucket_value = options[:min_bucket_value] ? options[:min_bucket_value].to_f : 0.000001\n @max_bucket_value = options[:max_bucket_value] ? options[:max_bucket_value].to_f : 1_000_000_000\n\n # precalculate the bucket size\n @bucket_size = (Math.log(@max_bucket_value) - Math.log(@min_bucket_value)) / @number_of_buckets.to_f\n\n @categories = {}\n end", "def createvalues\n if @values_valid\n return\n end\n if (@range =~ /(\\d+)-(\\d+)/ )\n @value=Array($1.to_i..$2.to_i)\n elsif (@range =~ /(\\d+):(\\d+):(\\d+)/ )\n @value=Array.new\n r=($1.to_i..$2.to_i).step($3.to_i)\n r.each {|v| @value.push(v)}\n elsif (@range =~ /(\\d+):(\\d+)/ )\n @value=Array($1.to_i..$2.to_i)\n else\n @value=@range.scan(/\"[^\"]+\"|'[^']+'|[^,\\s]+/)\n # Strip containing quotes\n @value.each{|v| v.gsub!(/\\A[\"']|[\"']\\Z/, '') }\n end\n\n @nvalues=@value.size\n if (!instance_variable_defined?(\"@default\"))\n @default=@value[0]\n end\n @values_valid=true\n end", "def numbers=(val)\n numbers.algorithm = val\n end", "def handle_value_definition\n value_def = @entry.at_xpath('./*/cda:repeatNumber', HQMF2::Document::NAMESPACES)\n unless value_def\n # TODO: HQMF needs better differentiation between SUM & COUNT...\n # currently using presence of repeatNumber...\n @type = 'SUM' if @type == 'COUNT'\n value_def = @entry.at_xpath('./*/cda:value', HQMF2::Document::NAMESPACES)\n end\n\n # TODO: Resolve extracting values embedded in criteria within outboundRel's\n if @type == 'SUM'\n value_def = @entry.at_xpath('./*/*/*/cda:value', HQMF2::Document::NAMESPACES)\n end\n\n if value_def\n value_type = value_def.at_xpath('./@xsi:type', HQMF2::Document::NAMESPACES)\n @value = HQMF2::AnyValue.new if String.try_convert(value_type) == 'ANY'\n end\n\n value_def\n end", "def parse_values; end", "def on_int(value); end", "def numeric_transformation(value); end", "def setup\n super()\n self.values = []\n self.bins = []\n self.counts = []\n self.total_count = 0\n if edges.nil?\n set_edges_from_min_max_and_num_bins! if min && max && num_bins\n else\n set_bins_and_counts_from_edges!\n end\n end", "def new_value(*args, &block)\n value = value_from_args(args, &block)\n\n value = if incremental\n incremental_value(value)\n else\n filter_value(transformed_value(value))\n end\n\n if value_valid?(value)\n self.custom_value = value\n elsif invalid.to_s == 'default' && !incremental\n default_value\n else\n fail ArgumentError, \"The value #{value.inspect} is not valid.\"\n end\n end", "def process_value(value)\n case value\n when Hash then self.class.new(@_agent, value)\n when Array then value.map { |v| process_value(v) }\n else value\n end\n end", "def setup_data\n if @y_axis_increment && !@hide_line_markers\n self.maximum_value = [@y_axis_increment, maximum_value, (maximum_value / @y_axis_increment).round * @y_axis_increment].max\n self.minimum_value = [minimum_value, (minimum_value / @y_axis_increment).round * @y_axis_increment].min\n end\n\n sort_data if @sort # Sort data with avg largest values set first (for display)\n end", "def store_numeric(key, process, options)\n if(options.has_key?(:between))\n check_min_value(key, options[:between][0])\n check_max_value(key, options[:between][1])\n else\n check_min_value(key, options[:min]) if(options.has_key?(:min))\n check_max_value(key, options[:max]) if(options.has_key?(:max))\n end\n store(key, process, options)\n end", "def addNumberStatsForSingleSettingOfVarianceVariable run_object , values\r\n statsGuy = run_object\r\n # note non use of index to lookup value...\r\n ppAndFile \"-----------\", \"Doing stats on runs runs just numbers #{values.inspect}\"\r\n ppAndFile \"download times %'iles'\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientDownloadTimes\", statsGuy).join(\" \")\r\n ppAndFile \"download total times %'iles'\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientTotalDownloadTimes\", statsGuy).join(\" \")\r\n ppAndFile \"death methods\", statsGuy.getDeathMethodsAveraged.sort.join(\" \")\r\n\r\n ppAndFile \"server upload [received] distinct seconds [instantaneous server upload per second] %'iles'\",\r\n VaryParameter.getDuplesFromClientsAndPercentile(\"allServerServedPointsPartial\", statsGuy).join(\" \")\r\n\r\n ppAndFile \" instantaneous tenth of second throughput %'iles'\",\r\n VaryParameter.getDuplesFromClientsAndPercentile(\"totalThroughPutPointsPartial\", statsGuy).join(\" \")\r\n\r\n ppAndFile \"upload bytes %'iles'\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientTotalUpload\", statsGuy).join(\" \")\r\n ppAndFile \"dht gets\", VaryParameter.getDuplesFromClientsAndPercentile(\"multipleDHTGets\", statsGuy).join(\" \")\r\n ppAndFile \"dht puts\", VaryParameter.getDuplesFromClientsAndPercentile(\"multipleDHTPuts\", statsGuy).join(\" \")\r\n ppAndFile \"dht removes\", VaryParameter.getDuplesFromClientsAndPercentile(\"multipleDHTRemoves\", statsGuy).join(\" \")\r\n ppAndFile \"percentiles of percent received from just peers (not origin)\", VaryParameter.getDuplesFromClientsAndPercentile(\r\n \"createPercentFromClients\", statsGuy).join(\" \") # ltodo graphs for percent dT\r\n\r\n ppAndFile \"client upload sum percentiles:\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientTotalUpload\", statsGuy).join(\" \")\r\n ppAndFile \" :totalBytesReceivedFromPeersAcrossAllRuns #{statsGuy.totalBytesReceivedFromPeersAcrossAllRuns}, :totalBytesUploadedByServerAcrossAllRuns #{statsGuy.totalBytesUploadedByServerAcrossAllRuns} :totalBytesServedFromPeersAcrossAllRuns #{statsGuy.totalBytesServedFromPeersAcrossAllRuns}\"\r\n @totalBytesReceivedFromPeersAcrossAllRuns.plus_equals(statsGuy.totalBytesReceivedFromPeersAcrossAllRuns)\r\n @totalBytesUploadedByServerAcrossAllRuns.plus_equals(statsGuy.totalBytesUploadedByServerAcrossAllRuns)\r\n @totalBytesServedFromPeersAcrossAllRuns.plus_equals(statsGuy.totalBytesServedFromPeersAcrossAllRuns)\r\n #ltodo note how many opendht's never came back\r\n #ltodo say how many did not make it, too...\r\n print \"wrote stats to #{@outputFile.path}\\n\"\r\n end", "def number_and_secondary_value(value, previous_value)\n self.push(:item => [{:text => \"\", :value => value}, {:text => \"\", :value => previous_value}])\n end", "def initialize(value_chain = [])\n @transitions = {}\n @frequencies = {}\n add_input(value_chain)\n end", "def add_values v # first dispatch\n v.addInt self\n end", "def observe_value(metric, value:, labels: {}); end", "def initial_cut_values\n end", "def set_values(values)\n case @type\n when /Dword/ # n .. n, step size: n\n if values =~ /(\\d+)\\s*\\.\\.\\s*(\\d+)\\s*,\\s*step size:\\s*(\\d+)/\n @min = $1.to_f\n @max = $2.to_f\n @step = $3.to_f\n else\n puts \"-E- Unrecognized value format: #{values}\"\n end\n when /Choice/ # 'choice 1'[val1], ......, 'choice n'[valn]\n @choices = Hash.new\n values.scan(/\\s*'([^']+)'\\[([^\\]]+)\\]/) do |c, v|\n @choices[v] = c\n end\n when /Button/\n # do nothing\n when /Boolean/\n # do nothing\n else\n puts \"-E- Unrecognized control type #{@type}\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value information from the request and store it in the respective categories. If a request can contain multiple usable values for this tracker, the :multiple option should be set to true. In this case, all the values and respective categories will be read from the request using the every method from the fields given in the :value and :category option. If the request contains only one suitable value and the :multiple is not set, it will read the single value and category from the fields provided in the :value and :category option, or calculate it with any lambda procedure that is assigned to these options. The request will be passed to procedure as input for the calculation.
def update(request) if options[:multiple] found_categories = request.every(options[:category]) found_values = request.every(options[:value]) raise "Capture mismatch for multiple values in a request" unless found_categories.length == found_values.length found_categories.each_with_index do |cat, index| update_statistics(cat, found_values[index]) if cat && found_values[index].kind_of?(Numeric) end else category = @categorizer.call(request) value = @valueizer.call(request) update_statistics(category, value) if value.kind_of?(Numeric) && category end end
[ "def update(request)\n if options[:multiple]\n found_categories = request.every(options[:category])\n found_values = request.every(options[:value])\n raise \"Capture mismatch for multiple values in a request\" unless found_categories.length == found_values.length\n\n found_categories.each_with_index do |cat, index|\n update_statistics(cat, found_values[index]) if cat && found_values[index].kind_of?(Numeric)\n end\n\n else\n category = @categorizer.call(request)\n value = @valueizer.call(request)\n update_statistics(category, value) if value.kind_of?(Numeric) && category\n end\n end", "def update(request)\n if options[:multiple]\n found_categories = request.every(options[:category])\n found_durations = request.every(options[:duration])\n raise \"Capture mismatch for multiple values in a request\" unless found_categories.length == found_durations.length\n found_categories.each_with_index { |cat, index| update_statistics(cat, found_durations[index]) }\n else\n category = @categorizer.call(request)\n duration = @durationizer.call(request)\n update_statistics(category, duration) if duration.kind_of?(Numeric) && category\n end\n end", "def prepare\n \n raise \"No value field set up for numeric tracker #{self.inspect}\" unless options[:value]\n raise \"No categorizer set up for numeric tracker #{self.inspect}\" unless options[:category]\n\n unless options[:multiple]\n @categorizer = create_lambda(options[:category])\n @valueizer = create_lambda(options[:value])\n end\n\n @categories = {}\n end", "def prepare\n\n raise \"No value field set up for numeric tracker #{self.inspect}\" unless options[:value]\n raise \"No categorizer set up for numeric tracker #{self.inspect}\" unless options[:category]\n\n unless options[:multiple]\n @categorizer = create_lambda(options[:category])\n @valueizer = create_lambda(options[:value])\n end\n \n @number_of_buckets = options[:number_of_buckets] || 1000\n @min_bucket_value = options[:min_bucket_value] ? options[:min_bucket_value].to_f : 0.000001\n @max_bucket_value = options[:max_bucket_value] ? options[:max_bucket_value].to_f : 1_000_000_000\n\n # precalculate the bucket size\n @bucket_size = (Math.log(@max_bucket_value) - Math.log(@min_bucket_value)) / @number_of_buckets.to_f\n\n @categories = {}\n end", "def process_value(value)\n case value\n when Hash then self.class.new(@_agent, value)\n when Array then value.map { |v| process_value(v) }\n else value\n end\n end", "def process_value(value)\n case value\n when Hash then self.class.new(@_client, value)\n when Array then value.map { |v| process_value(v) }\n else value\n end\n end", "def processParam(keyword, value, allow_many_values) #:doc:\n # validate value(s) and if many values, separate terms\n values = nil\n regexp = /[^\\w\\_\\-\\.]/\n if allow_many_values\n regexp = /[^\\w\\s\\_\\-\\.]/\n end\n if not value =~ regexp\n values = value.split(\" \")\n else\n return false\n end\n \n # do transformations into correct form for sizes, dates and states\n if keyword =~ /^.+size$/ or keyword =~ /.+before$/ or keyword =~ /^.+after$/ or (keyword =~ /state/i and @context[:user] and @context[:device])\n if keyword =~ /^.+size$/\n values = transform_size(values.first)\n elsif keyword =~ /.+before$/ or keyword =~ /^.+after$/\n values = QueryController::transform_date(values.first)\n elsif keyword =~ /state/i and @context[:user] and @context[:device]\n values = processState(value)\n end\n if values == false\n return false\n elsif values == :nothingfound\n return values\n elsif values == :combined or values == :default\n return true\n else\n values = [values]\n end\n end\n \n # get location parameters ONLY if the context is defined\n if keyword == \"lat\" or keyword == \"lon\" or keyword == \"distance\"\n if (@context.empty? and @device_ids.empty?)\n return true\n end\n if keyword == \"distance\" and value[-1, 1].downcase == \"m\"\n @locationdata.merge!({keyword => value.to_f * 1000})\n return true\n end\n @locationdata.merge!({keyword => value})\n return true\n end\n \n # add to search conditions\n if @condition_rules.has_key?(keyword)\n processed_values = processValues(keyword, values)\n @conditions.merge!({keyword => processed_values})\n end\n end", "def request\n @request ||= begin\n res = {}\n\n if must_values || must_not_values || filter_values\n res[:query] = {\n bool: {\n must: must_values.to_a,\n must_not: must_not_values.to_a,\n filter: filter_values.to_a\n }.reject { |_, value| value.empty? }\n }\n end\n\n res.update(from: offset_value_with_default, size: limit_value_with_default)\n\n res[:track_total_hits] = track_total_hits_value unless track_total_hits_value.nil?\n res[:explain] = explain_value unless explain_value.nil?\n res[:timeout] = timeout_value if timeout_value\n res[:terminate_after] = terminate_after_value if terminate_after_value\n res[:highlight] = highlight_values if highlight_values\n res[:suggest] = suggest_values if suggest_values\n res[:sort] = sort_values if sort_values\n res[:aggregations] = aggregation_values if aggregation_values\n\n if post_must_values || post_must_not_values || post_filter_values\n res[:post_filter] = {\n bool: {\n must: post_must_values.to_a,\n must_not: post_must_not_values.to_a,\n filter: post_filter_values.to_a\n }.reject { |_, value| value.empty? }\n }\n end\n\n res[:_source] = source_value unless source_value.nil?\n res[:profile] = true if profile_value\n\n res.update(custom_value) if custom_value\n\n res\n end\n end", "def category_value\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 2 )\n hash = nil\n category_class2 = nil\n category_term3 = nil\n category_scheme4 = nil\n category_title5 = nil\n category_rel6 = nil\n category_location7 = nil\n category_attributes8 = nil\n category_actions9 = nil\n # - - - - @init action - - - -\n hash = Hashie::Mash.new({:kinds => [], :mixins => [], :actions => []})\n\n begin\n # at line 56:15: category_term category_scheme category_class ( category_title )? ( category_rel )? ( category_location )? ( category_attributes )? ( category_actions )? ( ';' )?\n @state.following.push(TOKENS_FOLLOWING_category_term_IN_category_value_78)\n category_term3 = category_term\n @state.following.pop\n @state.following.push(TOKENS_FOLLOWING_category_scheme_IN_category_value_80)\n category_scheme4 = category_scheme\n @state.following.pop\n @state.following.push(TOKENS_FOLLOWING_category_class_IN_category_value_82)\n category_class2 = category_class\n @state.following.pop\n # at line 56:60: ( category_title )?\n alt_1 = 2\n look_1_0 = @input.peek(1)\n\n if (look_1_0 == T__11)\n look_1_1 = @input.peek(2)\n\n if (look_1_1 == WS)\n look_1_3 = @input.peek(3)\n\n if (look_1_3 == T__16)\n alt_1 = 1\n end\n elsif (look_1_1 == T__16)\n alt_1 = 1\n end\n end\n case alt_1\n when 1\n # at line 56:60: category_title\n @state.following.push(TOKENS_FOLLOWING_category_title_IN_category_value_84)\n category_title5 = category_title\n @state.following.pop\n\n end\n # at line 56:76: ( category_rel )?\n alt_2 = 2\n look_2_0 = @input.peek(1)\n\n if (look_2_0 == T__11)\n look_2_1 = @input.peek(2)\n\n if (look_2_1 == WS)\n look_2_3 = @input.peek(3)\n\n if (look_2_3 == T__17)\n alt_2 = 1\n end\n elsif (look_2_1 == T__17)\n alt_2 = 1\n end\n end\n case alt_2\n when 1\n # at line 56:76: category_rel\n @state.following.push(TOKENS_FOLLOWING_category_rel_IN_category_value_87)\n category_rel6 = category_rel\n @state.following.pop\n\n end\n # at line 56:90: ( category_location )?\n alt_3 = 2\n look_3_0 = @input.peek(1)\n\n if (look_3_0 == T__11)\n look_3_1 = @input.peek(2)\n\n if (look_3_1 == WS)\n look_3_3 = @input.peek(3)\n\n if (look_3_3 == T__18)\n alt_3 = 1\n end\n elsif (look_3_1 == T__18)\n alt_3 = 1\n end\n end\n case alt_3\n when 1\n # at line 56:90: category_location\n @state.following.push(TOKENS_FOLLOWING_category_location_IN_category_value_90)\n category_location7 = category_location\n @state.following.pop\n\n end\n # at line 56:109: ( category_attributes )?\n alt_4 = 2\n look_4_0 = @input.peek(1)\n\n if (look_4_0 == T__11)\n look_4_1 = @input.peek(2)\n\n if (look_4_1 == WS)\n look_4_3 = @input.peek(3)\n\n if (look_4_3 == T__19)\n alt_4 = 1\n end\n elsif (look_4_1 == T__19)\n alt_4 = 1\n end\n end\n case alt_4\n when 1\n # at line 56:109: category_attributes\n @state.following.push(TOKENS_FOLLOWING_category_attributes_IN_category_value_93)\n category_attributes8 = category_attributes\n @state.following.pop\n\n end\n # at line 56:130: ( category_actions )?\n alt_5 = 2\n look_5_0 = @input.peek(1)\n\n if (look_5_0 == T__11)\n look_5_1 = @input.peek(2)\n\n if (look_5_1 == WS || look_5_1 == T__20)\n alt_5 = 1\n end\n end\n case alt_5\n when 1\n # at line 56:130: category_actions\n @state.following.push(TOKENS_FOLLOWING_category_actions_IN_category_value_96)\n category_actions9 = category_actions\n @state.following.pop\n\n end\n # at line 56:148: ( ';' )?\n alt_6 = 2\n look_6_0 = @input.peek(1)\n\n if (look_6_0 == T__11)\n alt_6 = 1\n end\n case alt_6\n when 1\n # at line 56:148: ';'\n match(T__11, TOKENS_FOLLOWING_T__11_IN_category_value_99)\n\n end\n # --> action\n type = category_class2\n cat = Hashie::Mash.new\n cat.term = category_term3\n cat.scheme = category_scheme4\n cat.title = category_title5\n cat.related = category_rel6\n cat.location = category_location7\n cat.attributes = category_attributes8\n cat.actions = category_actions9\n hash[(type+'s').to_sym] << cat\n\n # <-- action\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 2 )\n\n end\n\n return hash\n end", "def handle_value_definition\n value_def = @entry.at_xpath('./*/cda:repeatNumber', HQMF2::Document::NAMESPACES)\n unless value_def\n # TODO: HQMF needs better differentiation between SUM & COUNT...\n # currently using presence of repeatNumber...\n @type = 'SUM' if @type == 'COUNT'\n value_def = @entry.at_xpath('./*/cda:value', HQMF2::Document::NAMESPACES)\n end\n\n # TODO: Resolve extracting values embedded in criteria within outboundRel's\n if @type == 'SUM'\n value_def = @entry.at_xpath('./*/*/*/cda:value', HQMF2::Document::NAMESPACES)\n end\n\n if value_def\n value_type = value_def.at_xpath('./@xsi:type', HQMF2::Document::NAMESPACES)\n @value = HQMF2::AnyValue.new if String.try_convert(value_type) == 'ANY'\n end\n\n value_def\n end", "def category_value\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 2 )\n hash = nil\n category_class2 = nil\n category_term3 = nil\n category_scheme4 = nil\n category_title5 = nil\n category_rel6 = nil\n category_location7 = nil\n category_attributes8 = nil\n category_actions9 = nil\n # - - - - @init action - - - -\n hash = Hashie::Mash.new( {:kinds=>[],:mixins=>[],:actions=>[] } ) \n\n begin\n # at line 29:15: category_term category_scheme category_class ( category_title )? ( category_rel )? ( category_location )? ( category_attributes )? ( category_actions )? ( SEMICOLON )?\n @state.following.push( TOKENS_FOLLOWING_category_term_IN_category_value_75 )\n category_term3 = category_term\n @state.following.pop\n @state.following.push( TOKENS_FOLLOWING_category_scheme_IN_category_value_77 )\n category_scheme4 = category_scheme\n @state.following.pop\n @state.following.push( TOKENS_FOLLOWING_category_class_IN_category_value_79 )\n category_class2 = category_class\n @state.following.pop\n # at line 29:60: ( category_title )?\n alt_1 = 2\n look_1_0 = @input.peek( 1 )\n\n if ( look_1_0 == SEMICOLON )\n look_1_1 = @input.peek( 2 )\n\n if ( look_1_1 == WS )\n look_1_3 = @input.peek( 3 )\n\n if ( look_1_3 == TITLE )\n alt_1 = 1\n end\n elsif ( look_1_1 == TITLE )\n alt_1 = 1\n end\n end\n case alt_1\n when 1\n # at line 29:60: category_title\n @state.following.push( TOKENS_FOLLOWING_category_title_IN_category_value_81 )\n category_title5 = category_title\n @state.following.pop\n\n end\n # at line 29:76: ( category_rel )?\n alt_2 = 2\n look_2_0 = @input.peek( 1 )\n\n if ( look_2_0 == SEMICOLON )\n look_2_1 = @input.peek( 2 )\n\n if ( look_2_1 == WS )\n look_2_3 = @input.peek( 3 )\n\n if ( look_2_3 == REL )\n alt_2 = 1\n end\n elsif ( look_2_1 == REL )\n alt_2 = 1\n end\n end\n case alt_2\n when 1\n # at line 29:76: category_rel\n @state.following.push( TOKENS_FOLLOWING_category_rel_IN_category_value_84 )\n category_rel6 = category_rel\n @state.following.pop\n\n end\n # at line 29:90: ( category_location )?\n alt_3 = 2\n look_3_0 = @input.peek( 1 )\n\n if ( look_3_0 == SEMICOLON )\n look_3_1 = @input.peek( 2 )\n\n if ( look_3_1 == WS )\n look_3_3 = @input.peek( 3 )\n\n if ( look_3_3 == LOCATION )\n alt_3 = 1\n end\n elsif ( look_3_1 == LOCATION )\n alt_3 = 1\n end\n end\n case alt_3\n when 1\n # at line 29:90: category_location\n @state.following.push( TOKENS_FOLLOWING_category_location_IN_category_value_87 )\n category_location7 = category_location\n @state.following.pop\n\n end\n # at line 29:109: ( category_attributes )?\n alt_4 = 2\n look_4_0 = @input.peek( 1 )\n\n if ( look_4_0 == SEMICOLON )\n look_4_1 = @input.peek( 2 )\n\n if ( look_4_1 == WS )\n look_4_3 = @input.peek( 3 )\n\n if ( look_4_3 == ATTRIBUTES )\n alt_4 = 1\n end\n elsif ( look_4_1 == ATTRIBUTES )\n alt_4 = 1\n end\n end\n case alt_4\n when 1\n # at line 29:109: category_attributes\n @state.following.push( TOKENS_FOLLOWING_category_attributes_IN_category_value_90 )\n category_attributes8 = category_attributes\n @state.following.pop\n\n end\n # at line 29:130: ( category_actions )?\n alt_5 = 2\n look_5_0 = @input.peek( 1 )\n\n if ( look_5_0 == SEMICOLON )\n look_5_1 = @input.peek( 2 )\n\n if ( look_5_1 == WS || look_5_1 == ACTIONS )\n alt_5 = 1\n end\n end\n case alt_5\n when 1\n # at line 29:130: category_actions\n @state.following.push( TOKENS_FOLLOWING_category_actions_IN_category_value_93 )\n category_actions9 = category_actions\n @state.following.pop\n\n end\n # at line 29:148: ( SEMICOLON )?\n alt_6 = 2\n look_6_0 = @input.peek( 1 )\n\n if ( look_6_0 == SEMICOLON )\n alt_6 = 1\n end\n case alt_6\n when 1\n # at line 29:148: SEMICOLON\n match( SEMICOLON, TOKENS_FOLLOWING_SEMICOLON_IN_category_value_96 )\n\n end\n # --> action\n type = category_class2\n \t cat = Hashie::Mash.new\n \t cat.term \t\t= category_term3\n \t cat.scheme \t\t= category_scheme4\n \t cat.title\t\t= category_title5\n \t cat.related\t\t= category_rel6\n \t cat.location\t\t= category_location7\n \t cat.attributes\t\t= category_attributes8\n \t cat.actions\t\t= category_actions9\n \t hash[(type+'s').to_sym] \t<< cat\n \t \n # <-- action\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 2 )\n\n end\n \n return hash\n end", "def assign_valuations(data, request)\n lambda do\n # valuations[i][j] contains the valuation for property i on date j\n data.each_with_index.map do |valuations, property_idx|\n valuations.each_with_index.map do |valuation, date_idx|\n # Fetch the request data for this valuation and\n # extend the raw data to build a local representation\n valuation.property = request.properties[property_idx]\n valuation.valuation_date = request.valuation_dates[date_idx]\n valuation.deal_type = request.deal_type\n valuation.country_code = request.country_code\n # Build the local representation from the raw data\n PriceHubble::Valuation.new(valuation)\n end\n end.flatten\n end\n end", "def set_value\n if resolver.params.key?(name)\n\n # Check if all values present in the options\n if multiple?\n acceptable_values = (resolver.params[name] - options.keys).empty?\n else\n acceptable_values = options.keys.include?(resolver.params[name])\n end\n\n self.value = resolver.params[name] if acceptable_values\n else\n self.value = @attributes[:value]\n end\n end", "def observe_value(metric, value:, labels: {}); end", "def values_for(parameter,parameter_values,scenario_id)\n pv = parameter_values\n return [] unless pv.count > 0\n # If Values are time-dependent\n if signature[parameter].include?(\"period\")\n values = Hash.new\n # Value are gathered by indexes other than period\n case parameter\n when \"demand\"\n @energy_system.commodities.demands.activated.each{|dem|\n key = \"_T \" + dem.name\n values[key] = Hash.new\n dem.demand_values(scenario_id).each{|dv|\n values[key][dv[0]] = dv[1]\n }\n }\n else\n pv.each{ |v|\n key = parameter_value_indexes(parameter,v).join(\" \")\n values[key] = Hash.new if not values[key]\n values[key][v.year] = v.value\n }\n end\n # Values are projected/disaggregated\n str = []\n values.each{ |key,k_values|\n projection(k_values,time_proj[parameter]).each{|period,value|\n if key.index(\"_AN\")\n TIME_SLICES.each { |ts|\n str.concat(key.sub(\"_AN\",ts).sub(/_T/,period.to_s).split)\n if inherit_ts[parameter]==:same\n str << value\n elsif inherit_ts[parameter]==:fraction\n str << value * fraction[ts]\n end\n }\n else\n str.concat(key.sub(/_T/,period.to_s).split)\n str << value\n end\n }\n }\n str\n else\n pv.collect{ |v|\n key = parameter_value_indexes(parameter,v).join(\" \")\n value = case parameter\n when \"flow_act\" then \"f_#{v.flow.id}\"\n when \"avail\" then \"#{period(v.value)}\"\n when \"life\" then \"#{v.value/period_duration}\"\n else \"#{v.value}\"\n end\n str = []\n if key.index(\"_AN\")\n TIME_SLICES.each { |ts|\n str.concat(key.sub(\"_AN\",ts).split)\n if inherit_ts[parameter]==:same\n str << value\n elsif inherit_ts[parameter]==:fraction\n str << value.to_f * fraction[ts]\n end\n }\n else\n str.concat(key.split)\n str << value\n end\n str\n }.flatten\n end\n end", "def parse_value(value)\n if value.include?('$env')\n fetch_environment_variable(value)\n elsif value.include?('$payload')\n fetch_payload_data(value)\n elsif value.instance_of?(Hash)\n parse_payload!(value)\n elsif value.instance_of?(Array)\n # TODO: Add support for accessing a single element\n value.map { |i| parse_payload!(i) }\n else\n value\n end\n end", "def build_value_for_element valueSet, value\n if value.nil?\n return {\n \"type\" => \"CD\",\n \"code_list_id\" => valueSet[\"id\"],\n \"title\" => valueSet[\"name\"],\n }\n else\n if value and value[\"type\"]\n if value[\"type\"] == \"present\"\n return {\"type\" => \"ANYNonNull\" }\n elsif value[\"type\"] == \"value\"\n return build_range_hash(false, value[\"operator\"], value[\"units\"][\"id\"], value[\"valueLow\"], value[\"valueHigh\"])\n end\n end\n end\n nil\n end", "def parse_values; end", "def calculate(value,operation)\n check_calculation_requirements(value)\n calculation_requirements.map do |requirement|\n send(requirement).send(operation,value.send(requirement))\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Block function to build a result table using a provided sorting function. output The output object. amount The number of rows in the report table (default 10). === Options :title The title of the table :sort The key to sort on (:hits, :cumulative, :average, :min or :max)
def report_table(output, sort, options = {}, &block) output.puts top_categories = output.slice_results(sorted_by(sort)) output.with_style(:top_line => true) do output.table(*statistics_header(:title => options[:title], :highlight => sort)) do |rows| top_categories.each { |(cat, info)| rows << statistics_row(cat) } end end end
[ "def report_table(output, sort, options = {}, &block)\n output.puts\n\n top_categories = output.slice_results(sorted_by(sort))\n output.with_style(:top_line => true) do \n output.table(*statistics_header(:title => options[:title],:highlight => sort)) do |rows|\n top_categories.each { |(cat, info)| rows.push(statistics_row(cat)) }\n end\n end\n output.puts\n end", "def report(output)\n\n sortings = output.options[:sort] || [:sum, :mean]\n\n sortings.each do |report|\n case report\n when :mean\n report_table(output, :mean, :title => \"#{title} - sorted by mean\")\n when :stddev\n report_table(output, :stddev, :title => \"#{title} - sorted by standard deviation\")\n when :sum\n report_table(output, :sum, :title => \"#{title} - sorted by sum\")\n when :hits\n report_table(output, :hits, :title => \"#{title} - sorted by hits\")\n else\n raise \"Unknown duration report specified: #{report}!\"\n end\n end\n\n output.puts\n output.puts \"#{output.colorize(title, :white, :bold)} - observed total: \" + output.colorize(display_value(sum_overall), :brown, :bold)\n end", "def top_10_table(output)\n\t\t\t\t\theaders = [\"Description\", \"Count\"]\n\t\t\t\t\theader_widths = {0 => (output.bounds.width - 50), 1 => 50}\n\n\t\t\t\t\tdata = top_10_sorted\n\n\t\t\t\t\toutput.table([headers] + data[0..9], :header => true, :column_widths => header_widths, :width => output.bounds.width) do\n\t\t\t\t\t\trow(0).style(:font_style => :bold, :background_color => 'cccccc')\n\t\t\t\t\t\tcells.borders = [:top, :bottom, :left, :right]\n\t\t\t\t\tend\n\t\t\t\tend", "def make_results_table(drivers,sort_by=:driver_id,order=:lowtohigh)\n # drivers = master[:drivers]\n # sort_by = any key in results_table\n # order = :hightolow or :lowtohigh\n results_table = Array.new\n drivers.each do |h|\n orphan = Hash.new\n orphan[:driver_id] = h[:driver_id]\n orphan[:tot_rides] = h[:rides].size\n orphan[:tot_cost] = h[:rides].reduce(0) {|m,h| m + h[:cost]}\n orphan[:avg_rating] = (( h[:rides].reduce(0) {|m,h| m + h[:rating]}\n ) / h[:rides].size.to_f ).round(3)\n orphan[:best_day] = best_day(h[:rides])\n results_table << orphan\n end\n\n sort_results_table(results_table,sort_by,order)\n return results_table\nend", "def create_summary_report\n @total_fails = 0\n @total_samples = 0\n count = 10\n table = \"<table>\\n<tr id='header'><th>Time</th><th>Users</th><th>Pages/sec</th><th>Page fail rate</th><th>Total fail rate</th><th>Min Page Dur</th><th>Avg Page Dur</th><th>Max Page Dur</th></tr>\\n\"\n\n @groupeddata.each do |data|\n table += \"<tr><td>\" + current_time(count) + \"</td><td>\" + user_count(data) + \"</td><td>\" + pages_per_second(data.count) + \"</td><td>\" + page_fail_rate(data) + \"%</td><td>\" + total_fail_rate(data) + \"%</td><td>\" + min_page_duration(data) + \"</td><td>\" + avg_page_duration(data) + \"</td><td>\" + max_page_duration(data) + \"</td></tr>\\n\"\n count += 10\n end\n\n table += \"</table>\"\n \n return table\n end", "def drawTable(response, request)\n\t\tsortBy = request.GET[\"sort\"]\n\t\t@books = @books.sort_by { |x| x[:\"#{sortBy}\"]}\n\n\t\tresponse.write(\"<table>\")\n\t\tresponse.write(\"<tr>\")\n\t\tresponse.write(\"<td>Rank</td>\")\n\t\tresponse.write(\"<td>Title</td>\")\n\t\tresponse.write(\"<td>Author</td>\")\n\t\tresponse.write(\"<td>Language</td>\")\n\t\tresponse.write(\"<td>Year</td>\")\n\t\tresponse.write(\"<td>Copies</td>\")\n\t\tresponse.write(\"</tr>\")\n\t\t@books.each do |book|\n\t\t\tresponse.write(\"<tr>\")\n\t\t\tresponse.write(\"<td>#{book[:rank]}</td>\")\n\t\t\tresponse.write(\"<td>#{book[:title]}</td>\")\n\t\t\tresponse.write(\"<td>#{book[:author]}</td>\")\n\t\t\tresponse.write(\"<td>#{book[:language]}</td>\")\n\t\t\tresponse.write(\"<td>#{book[:year]}</td>\")\n\t\t\tresponse.write(\"<td>#{book[:copies]}</td>\")\n\t\t\tresponse.write(\"</tr>\")\n\t\tend\n\t\tresponse.write(\"</table>\")\n\tend", "def make_coverage(title, sortby)\n if (sortby != 8)\n @fields.sort! { |a, b| b[sortby].to_f <=> a[sortby].to_f } # (i.e. descending sort)\n else\n @fields.sort! { |a, b| a[sortby] <=> b[sortby] } # (i.e. ascending sort)\n end\n\n @file_coverage_template.rewind\n file_coverage = File.new(@report_dir + \"/#{title}\", 'w') rescue die(\"Can't open #{@report_dir}\\\\#{title}\", __LINE__)\n\n while (line = @file_coverage_template.gets)\n if (line =~ /^table data goes here/)\n get_coverline(file_coverage)\n elsif (line =~ /^Report current.*/)\n file_coverage.puts 'Report current as of: ' + @report_timestamp\n elsif (line =~ /about 90 minutes/)\n # edit the line and insert the actual 'Normal' value from the config file\n line['90'] = @timebox['normal'].to_s\n file_coverage.puts line\n elsif (line =~ /^table header goes here/)\n # print only the column headings we need\n file_coverage.puts indent2 + '<th width=\"7%\"><font face=\"Arial\"><a href=\"cov_by_total.htm\">TOTAL</a></font></th>' if @include_switch['Duration']\n file_coverage.puts indent2 + '<th width=\"7%\"><font face=\"Arial\"><a href=\"cov_by_charter.htm\">CHTR</a></font></th>' if @include_switch['C vs O']\n file_coverage.puts indent2 + '<th width=\"7%\"><font face=\"Arial\"><a href=\"cov_by_opp.htm\">OPP</a></font></th>' if @include_switch['C vs O']\n file_coverage.puts indent2 + '<th width=\"8%\"><font face=\"Arial\"><a href=\"cov_by_test.htm\">% TEST</a></font></th>' if @include_switch['TBS']\n file_coverage.puts indent2 + '<th width=\"7%\"><font face=\"Arial\"><a href=\"cov_by_bug.htm\">% BUG</a></font></th>' if @include_switch['TBS']\n file_coverage.puts indent2 + '<th width=\"8%\"><font face=\"Arial\"><a href=\"cov_by_setup.htm\">% SETUP</a></font></th>' if @include_switch['TBS']\n else\n file_coverage.puts line\n end\n end\n\n file_coverage.close\n end", "def dc_header_for_result()\n c = ''\n actions = @form['result_set']['actions']\n c = '<th>&nbsp;</th>' unless actions.nil? or @form['readonly']\n# preparation for sort icon \n sort_field, sort_direction = nil, nil\n if session[@form['table']]\n sort_field, sort_direction = session[@form['table']][:sort].to_s.split(' ')\n end\n# \n if (columns = @form['result_set']['columns'])\n columns.each do |k,v|\n session[:form_processing] = \"result_set:columns: #{k}=#{v}\"\n th = '<th '\n v = {'name' => v} if v.class == String \n caption = v['caption'] || t(\"helpers.label.#{@form['table']}.#{v['name']}\")\n# no sorting when embedded documents or custom filter is active \n sort_ok = @form['result_set'].nil? || (@form['result_set'] && @form['result_set']['filter'].nil?)\n sort_ok = sort_ok || (@form['index'] && @form['index']['sort'])\n if @tables.size == 1 and sort_ok\n icon = 'sort lg'\n if v['name'] == sort_field\n icon = sort_direction == '1' ? 'sort-alpha-asc lg' : 'sort-alpha-desc lg'\n end \n th << \">#{dc_link_to(caption, icon, sort: v['name'], table: params[:table], formname: params[:formname], action: :index )}</th>\"\n else\n th << \">#{caption}</th>\"\n end\n c << th\n end\n end\n c.html_safe\nend", "def dc_header_for_result\n html = '<div class=\"dc-result-header\">'\n if @form['result_set']['actions'] #&& !@form['readonly']\n ignore, width, has_check = dc_actions_column()\n check_all = fa_icon('check-box-o', class: 'dc-check-all') if has_check\n html << %(<div class=\"dc-result-actions\" style=\"width:#{width}px;\">#{check_all}</div>)\n end\n # preparation for sort icon \n sort_field, sort_direction = nil, nil\n if session[@form['table']]\n sort_field, sort_direction = session[@form['table']][:sort].to_s.split(' ')\n end\n\n if (columns = @form['result_set']['columns'])\n columns.sort.each do |key, options|\n session[:form_processing] = \"result_set:columns: #{key}=#{options}\"\n next if options['width'].to_s.match(/hidden|none/i)\n\n th = %(<div class=\"th\" style=\"width:#{options['width'] || '15%'};text-align:#{options['align'] || 'left'};\" data-name=\"#{options['name']}\")\n label = t_label_for_column(options)\n # no sorting when embedded documents or custom filter is active\n sort_ok = !dc_dont?(@form['result_set']['sort'], false)\n sort_ok = sort_ok || (@form['index'] && @form['index']['sort'])\n sort_ok = sort_ok && !dc_dont?(options['sort'], false)\n if @tables.size == 1 && sort_ok\n icon = 'sort_unset md-18'\n filter_class = form_has_input_field?(options['name']) ? nil : 'no-filter'\n if options['name'] == sort_field\n icon = sort_direction == '1' ? 'sort_down md-18' : 'sort_up md-18'\n else\n # no icon if filter can not be set\n icon = nil if filter_class\n end\n # sort and filter icon\n icon = mi_icon(icon, class: filter_class) if icon\n url = url_for(controller: 'cmsedit', action: 'run', control: 'cmsedit.sort', sort: options['name'],\n t: CmsHelper.table_param(params), f: CmsHelper.form_param(params))\n th << %(><span data-url=\"#{url}\">#{label}</span>#{icon}</div>)\n else\n th << \">#{label}</div>\"\n end\n html << %(<div class=\"spacer\"></div>) + th\n end\n end\n (html << '</div>').html_safe\nend", "def make_coverage( title, sortby )\n if ( sortby != 8)\n @fields.sort! { |a,b| b[ sortby ].to_f <=> a[ sortby ].to_f } # (i.e. descending sort)\n else\n @fields.sort! { |a,b| a[ sortby ] <=> b[ sortby ] } # (i.e. ascending sort)\n end\n \n @f_TCOVER.rewind\n @f_COVER = File.new(@report_dir + \"/#{title}\", 'w') rescue die( \"Can't open #{@report_dir}\\\\#{title}\", __LINE__ )\n\n while ( line = @f_TCOVER.gets )\n if ( line =~ /^table data goes here/ )\n get_coverline\n elsif ( line =~ /^Report current.*/ )\n @f_COVER.puts \"Report current as of: #{@thedate}\"\n elsif ( line =~ /about 90 minutes/ )\n # edit the line and insert the actual 'Normal' value from the config file\n line['90'] = @timebox['normal'].to_s\n @f_COVER.puts line\n elsif ( line =~ /^table header goes here/)\n # print only the column headings we need\n @f_COVER.puts ' <td width=\"6%\"><b><font face=\"Arial\"><a href=\"c_by_total.htm\">TOTAL</a></font></b></td>' if @include_switch['Duration']\n @f_COVER.puts ' <td width=\"6%\"><b><font face=\"Arial\"><a href=\"c_by_chtr.htm\">CHTR</a></font></b></td>' if @include_switch['C vs O']\n @f_COVER.puts ' <td width=\"6%\"><b><font face=\"Arial\"><a href=\"c_by_opp.htm\">OPP</a></font></b></td>' if @include_switch['C vs O']\n @f_COVER.puts ' <td width=\"6%\"><b><font face=\"Arial\"><a href=\"c_by_test.htm\">TEST</a></font></b></td>' if @include_switch['TBS']\n @f_COVER.puts ' <td width=\"7%\"><b><font face=\"Arial\"><a href=\"c_by_bug.htm\">BUG</a></font></b></td>' if @include_switch['TBS']\n @f_COVER.puts ' <td width=\"7%\"><b><font face=\"Arial\"><a href=\"c_by_setup.htm\">SETUP</a></font></b></td>' if @include_switch['TBS']\n else\n @f_COVER.puts line\n end\n end\n \n @f_COVER.close\nend", "def output_results_table(results={})\n puts\n puts \"----------------------------------------\"\n puts \"| Type | Mean | Median |\"\n puts \"----------------------------------------\"\n results.each do |label, hash|\n print \"| \" + label.ljust(10) + \" | \"\n print sprintf(\"%.6f\", hash[:mean]).rjust(10) + \" | \"\n puts sprintf(\"%.6f\", hash[:median]).rjust(10) + \" |\"\n end\n puts \"----------------------------------------\"\n puts\nend", "def output_results_table(results={})\n puts\n puts \"----------------------------------------\"\n puts \"| Type | Mean | Median |\"\n puts \"----------------------------------------\"\n results.each do |label, hash|\n print \"| \" + label.ljust(10) + \" | \"\n print sprintf(\"%.6f\", hash[:mean]).rjust(10) + \" | \"\n puts sprintf(\"%.6f\", hash[:median]).rjust(10) + \" | \"\n end\n puts \"----------------------------------------\"\n puts\nend", "def prepare_summaries\n @show_instances = false\n @show_summaries = true\n\n @test_case_commits = @test_case.find_test_case_commits(test_case_params.permit(\n :status, :sort_query, :sort_order, :page, :branch), @start_date, @end_date)\n\n # These \"orders\" tell the table headings what they should do if they\n # are clicked on. They do NOT mean anything for the ordering of test\n # case commits on the current page, which was already dealt with when\n # the commits were ordered from the database\n # \n # if order is set to ascending, switch it. Otherwise pick default\n # value of descending\n status_order = if (test_case_params[:sort_order] == 'desc') && test_case_params[:sort_query] == 'status'\n :asc\n else\n :desc\n end\n @status_params = {sort_query: :status, sort_order: status_order}\n date_order = if test_case_params[:sort_order].nil? ||\n test_case_params[:sort_order].empty? ||\n ((test_case_params[:sort_order] == 'desc') &&\n (test_case_params[:sort_query] == 'created_at'))\n :asc\n else\n :desc\n end\n @date_params = {sort_query: :created_at, sort_order: date_order}\n # names of default columns in the table of instances, can be toggled on\n # and off\n # NOTE the order of these data columns are hard-coded into the view.\n # Their default visibility, however, is not. So don't mess with the\n # ordering of this array without also changing the view. You CAN, however\n # change the vsibility or titles, which the view will respect.\n @default_columns = %w{commit status date checksum restart_photo} +\n %w{restart_checksum steps retries redos} +\n %w{solver_iterations solver_calls_made} +\n %w{solver_calls_failed}\n @sortable_columns = %w{commit status date}\n\n @default_column_titles = {\n 'commit' => 'Commit',\n 'status' => 'Status',\n 'date' => 'Commit Date',\n 'checksum' => 'Checksum',\n 'restart_photo' => 'Re Photo',\n 'restart_checksum' => 'Re Checksum',\n 'steps' => 'Steps',\n 'retries' => 'Retries',\n 'redos' => 'Redos',\n 'solver_iterations' => 'Iterations',\n 'solver_calls_made' => 'Calls Made',\n 'solver_calls_failed' => 'Calls Failed'\n }\n\n # names for columns as they appear in the checkbox form\n @default_column_check_titles = {\n 'commit' => 'Commit',\n 'status' => 'Status',\n 'date' => 'Commit Date',\n 'checksum' => 'Checksum',\n 'restart_photo' => 'Re Photo',\n 'restart_checksum' => 'Re Checksum',\n 'steps' => 'Steps',\n 'retries' => 'Retries',\n 'redos' => 'Redos',\n 'solver_iterations' => 'Solver Iterations',\n 'solver_calls_made' => 'Solver Calls Made',\n 'solver_calls_failed' => 'Solver Calls Failed',\n 'log_rel_run_E_err' => 'Log Rel. Run E Err.'\n }\n\n @default_column_visibility = {\n 'commit' => true,\n 'status' => true,\n 'date' => false,\n 'checksum' => false,\n 'restart_photo' => false,\n 'restart_checksum' => false,\n 'steps' => true,\n 'retries' => true,\n 'redos' => false,\n 'solver_iterations' => false,\n 'solver_calls_made' => false,\n 'solver_calls_failed' => false\n }\n\n @inlist_column_visibility = Hash.new({\n 'steps' => true,\n 'retries' => true,\n 'redos' => false,\n 'solver_iterations' => false,\n 'solver_calls_made' => false,\n 'solver_calls_failed' => false,\n 'log_rel_run_E_err' => false\n })\n\n @sortable_columns = %w{commit status date}\n\n # only care about inlists for passing commits\n @inlists = []\n\n @passing_tccs = @test_case_commits.select { |tcc| tcc.status == 0 }\n\n @passing_tccs.each do |tcc|\n tcc.test_instances.each do |ti|\n @inlists += ti.instance_inlists.pluck(:inlist)\n end\n end\n # this will have many duplicates\n @inlists.uniq!\n\n # for consistency, sort alphabetically. Almost certainly isn't in\n # order of how inlists work in the test case\n @inlists.sort!\n\n @inlist_columns = {}\n @inlists.each do |inlist|\n # all inlists have these columns\n @inlist_columns[inlist] = %w{steps retries redos \n solver_iterations solver_calls_made solver_calls_failed\n log_rel_run_E_err}\n\n # now get custom ones\n extras = []\n\n # only get \"this\" inlist from each test instance. Need to handle\n # the case where the inlist doesn't exist, though\n @passing_tccs.each do |tcc|\n tcc.test_instances.each do |ti|\n to_access = nil\n ti.instance_inlists.each do |instance_inlist|\n to_access = instance_inlist if (instance_inlist.inlist == inlist)\n end\n\n # don't have this inlist? just move on\n next if to_access.nil?\n\n # get names of data for this inlist\n extras += to_access.inlist_data.pluck(:name)\n end\n # same uniqueness/sorting situation as with inlists. Might not be\n # reasonable, but it's consistent\n end\n extras.uniq!\n extras.sort!\n @inlist_columns[inlist] += extras\n end\n\n # to get scalar data for each commit, look at the first non-skipped\n # instance (only applies to fully-passing, uniform checksum cases)\n # \n # Note that this doesn't care if there are no checksums, so this may\n # not be EXACTLY a representative test instance.\n @first_instances = {}\n @passing_tccs.each do |tcc|\n @first_instances[tcc] = tcc.test_instances.reject do |ti|\n ti.success_type == 'skip'\n end.first\n end\n end", "def report(output)\n output.title(options[:title]) if options[:title]\n\n if @categories.empty?\n output << \"None found.\\n\"\n else\n sorted_categories = output.slice_results(sorted_by_frequency)\n total_hits = overall_frequency\n\n output.table({:align => :left}, {:align => :right }, {:align => :right}, {:type => :ratio, :width => :rest}) do |rows|\n sorted_categories.each do |(cat, count)|\n rows << [cat, \"#{count} hits\", '%0.1f%%' % ((count.to_f / total_hits.to_f) * 100.0), (count.to_f / total_hits.to_f)]\n end\n end\n\n end\n end", "def report(output)\n output.title(options[:title]) if options[:title]\n\n if @last > 0 && @first < 99999999999999\n output.with_style(:cell_separator => false) do\n output.table({:width => 20}, {}) do |rows|\n rows << ['First request:', first_timestamp.strftime('%Y-%m-%d %H:%M:%I')]\n rows << ['Last request:', last_timestamp.strftime('%Y-%m-%d %H:%M:%I')]\n rows << ['Total time analyzed:', \"#{timespan.ceil} days\"]\n end\n end\n end\n end", "def report(output)\n output.title(title)\n\n if total_requests == 0\n output << \"None found.\\n\"\n return\n end\n\n days = [1, timespan].max\n output.table({}, {:align => :right}, {:type => :ratio, :width => :rest, :treshold => 0.15}) do |rows|\n @hour_frequencies.each_with_index do |requests, index|\n ratio = requests.to_f / total_requests.to_f\n requests_per_day = (requests / days).ceil\n rows << [\"#{index.to_s.rjust(3)}:00\", \"%d hits/day\" % requests_per_day, ratio]\n end\n end\n end", "def table_for(collection, options={}, html_options={}, &block)\n return if collection.nil? || collection.empty?\n builder = KingList::Builder::Table.new(render_context, collection)\n # extract options\n builder.sorting = options.delete(:sorting) != false # default => true\n capture do\n concat(\"<table #{ to_attr(html_options) }><thead><tr>\".html_safe)\n # Build header row\n builder.mode = :header\n builder.current_record = collection.first\n yield(builder, builder.current_record)\n concat(\"</tr></thead><tbody>\".html_safe)\n builder.mode = :content\n # Build content row for each collection item\n collection.each do |c|\n builder.current_record = c\n concat(\"<tr>\".html_safe)\n yield(builder, builder.current_record)\n concat(\"</tr>\".html_safe)\n end\n concat( \"</tbody></table>\".html_safe)\n end\n end", "def puts_tableized(output, data, headers: nil, &block)\n table = tableize(data, headers: headers, &block)\n output.puts table\n end", "def sorted_results\n if @config[\"sort_method\"] == \"alphabetical\"\n @results.sort_by { |c| c[0] }\n elsif @config[\"sort_method\"] == \"expiration\"\n @results.sort_by { |c| c[1] }\n else # default to alphabetical\n @results.sort_by { |c| c[0] }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the categories and the tracked duration as a hash than can be exported to YAML
def to_yaml_object return nil if @categories.empty? @categories end
[ "def to_yaml_object\n return nil if @categories.empty?\n @categories.each do |cat, info|\n info[:stddev] = stddev(cat)\n info[:median] = median(cat) if info[:buckets]\n info[:interval_95_percent] = percentile_interval(cat, 95) if info[:buckets]\n end\n @categories\n end", "def to_yaml() end", "def export_yaml\n hash = {}\n\n all.each do |c|\n next unless c.value\n hash_fatten!(hash, [c.locale].concat(c.key.split(\".\")), c.value)\n end\n\n hash.to_yaml\n end", "def categories\n raw_categories.to_hashugar\n end", "def to_yaml\n # This implementation intentionally builds up a YAML string manually instead of using YAML::dump().\n # Ruby 1.8 makes it difficult to ensure a consistent ordering of hash keys, which makes the output ugly\n # and also hard to test.\n \n yaml_output = \"Song:\\n\"\n yaml_output += \" Tempo: #{@tempo}\\n\"\n yaml_output += flow_to_yaml()\n yaml_output += @kit.to_yaml(2)\n yaml_output += patterns_to_yaml()\n \n return yaml_output\n end", "def to_yaml_object\n yaml_object = {}\n @hour_frequencies.each_with_index do |freq, hour|\n yaml_object[\"#{hour}:00 - #{hour+1}:00\"] = freq\n end\n yaml_object\n end", "def to_yaml\n require 'yaml'\n trackers_export = @trackers.inject({}) do |export, tracker|\n export[tracker.title] = tracker.to_yaml_object; export\n end\n YAML.dump(trackers_export)\n end", "def to_yaml\n {:drops => drops.collect(&:to_hash)}.to_yaml\n end", "def tips_hash(duration)\n if duration.present?\n today = Date.today\n range = (today - duration)..(today + 1.day)\n tips_list = tips.where(created_at: range)\n else\n tips_list = tips\n end\n # creates a hash with empty arrays for categories with no tips\n empty_categories_hash.merge(tips_list.to_a.group_by(&:category)).map{|category, tips|\n [category, tips.sort_by{ |tip| -1*tip.score }]\n }.to_h\n end", "def to_yaml\n to_hash.to_yaml\n end", "def to_yaml\n to_h.to_yaml\n end", "def to_yaml_properties\n end", "def to_yaml()\n @var_set.values.to_yaml\n end", "def tips_hash(duration)\n if duration.present?\n today = Date.today\n range = (today - duration)..(today + 1.day)\n tips_list = tips.where(created_at: range)\n else\n tips_list = tips\n end\n # creates a hash with empty arrays for categories with no tips\n empty_categories_hash.merge(tips_list.to_a.group_by(&:category)).map{|category, tips|\n good_tips, bad_tips = [], []\n tips.each{|tip| tip.is_shameful ? bad_tips << tip : good_tips << tip}\n good_tips.sort_by!{|tip| -1*tip.score}\n bad_tips.sort_by!{|tip| -1*tip.score}\n [category, {good_tips: good_tips, bad_tips: bad_tips}]\n }.to_h\n end", "def format_as_yaml\n\t\tobjects = {}\n\t\tself.instance_variables.each do |k|\n\t\t\tobjects[k.to_s.gsub('@','')] = instance_eval(k.to_s)\n\t\tend\n\t\tobjects.delete(\"filename\")\n\t\tobjects.delete(\"previous_file\")\n\t\treturn objects\n\tend", "def unique_events_data\n categories.each_with_object({}) do |category, category_results|\n events_names = events_for_category(category)\n\n event_results = events_names.each_with_object({}) do |event, hash|\n hash[\"#{event}_weekly\"] = unique_events(**weekly_time_range.merge(event_names: [event])) unless event == \"i_package_composer_deploy_token\"\n hash[\"#{event}_monthly\"] = unique_events(**monthly_time_range.merge(event_names: [event]))\n end\n\n if eligible_for_totals?(events_names) && CATEGORIES_FOR_TOTALS.include?(category)\n event_results[\"#{category}_total_unique_counts_weekly\"] = unique_events(**weekly_time_range.merge(event_names: events_names))\n event_results[\"#{category}_total_unique_counts_monthly\"] = unique_events(**monthly_time_range.merge(event_names: events_names))\n end\n\n category_results[\"#{category}\"] = event_results\n end\n end", "def descriptions\n @timing_hash.keys\n end", "def to_yaml\n @trees.to_yaml\n end", "def to_yaml_style\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update sthe running calculation of statistics with the newly found numeric value. category:: The category for which to update the running statistics calculations number:: The numeric value to update the calculations with.
def update_statistics(category, number) @categories[category] ||= {:hits => 0, :sum => 0, :mean => 0.0, :sum_of_squares => 0.0, :min => number, :max => number } delta = number - @categories[category][:mean] @categories[category][:hits] += 1 @categories[category][:mean] += (delta / @categories[category][:hits]) @categories[category][:sum_of_squares] += delta * (number - @categories[category][:mean]) @categories[category][:sum] += number @categories[category][:min] = number if number < @categories[category][:min] @categories[category][:max] = number if number > @categories[category][:max] end
[ "def update_statistics(category, number)\n @categories[category] ||= { :hits => 0, :sum => 0, :mean => 0.0, :sum_of_squares => 0.0, :min => number, :max => number, \n :buckets => Array.new(@number_of_buckets, 0) }\n \n delta = number - @categories[category][:mean]\n\n @categories[category][:hits] += 1\n @categories[category][:mean] += (delta / @categories[category][:hits])\n @categories[category][:sum_of_squares] += delta * (number - @categories[category][:mean])\n @categories[category][:sum] += number\n @categories[category][:min] = number if number < @categories[category][:min]\n @categories[category][:max] = number if number > @categories[category][:max]\n\n bucketize(category, number)\n end", "def modify_category(cat)\n if @categorized_amounts.include?(cat)\n @categorized_amounts[cat][:amount] = yield(\n @categorized_amounts[cat][:amount]\n )\n else\n new_amount = yield(0.0)\n if new_amount != 0.0\n @categorized_amounts[cat] = {\n :used => false, :amount => new_amount\n }\n end\n end\n end", "def update(request)\n if options[:multiple]\n found_categories = request.every(options[:category])\n found_values = request.every(options[:value])\n raise \"Capture mismatch for multiple values in a request\" unless found_categories.length == found_values.length\n \n found_categories.each_with_index do |cat, index| \n update_statistics(cat, found_values[index]) if cat && found_values[index].kind_of?(Numeric)\n end\n \n else\n category = @categorizer.call(request)\n value = @valueizer.call(request)\n update_statistics(category, value) if value.kind_of?(Numeric) && category\n end\n end", "def update(request)\n if options[:multiple]\n found_categories = request.every(options[:category])\n found_values = request.every(options[:value])\n raise \"Capture mismatch for multiple values in a request\" unless found_categories.length == found_values.length\n\n found_categories.each_with_index do |cat, index|\n update_statistics(cat, found_values[index]) if cat && found_values[index].kind_of?(Numeric)\n end\n\n else\n category = @categorizer.call(request)\n value = @valueizer.call(request)\n update_statistics(category, value) if value.kind_of?(Numeric) && category\n end\n end", "def number_in_category(category)\n number_by_category_query(category, turns)\n end", "def update_metric_values!\n puts \"Updating metric values...\"\n update_daily_happiness_distributions!\n update_weekly_happiness_distributions!\n update_monthly_happiness_distributions!\n update_annual_happiness_distributions!\n update_average_happiness_distributions!\n update_averages_for_metrics!\n puts \"Done updating metric values.\"\n end", "def update(value)\n @mutex.synchronize do\n @min = (value < @min) ? value : @min\n @max = (value > @max) ? value : @max\n\n @count += 1\n @sum += value\n @sumsq += (value * value)\n\n # from Nomnial update\n @frequencies[value] += 1 if @collecting_frequencies\n end\n\n return value\n end", "def update_complaint_score\n complaint_score.update_complaint_avg_score\n end", "def category_total_input(category, year = year_range.last)\n categories[category].inject(0) do |sum, asset|\n sum + (asset_total_input(asset, year) || 0)\n end\n end", "def update(sample)\n now = Time.new\n elapsed = now - @time\n @sum += sample\n if elapsed > 1.0\n @value = newValue elapsed, @sum/elapsed\n @time = now\n @sum = 0.0\n end\n end", "def update(request)\n if options[:multiple]\n found_categories = request.every(options[:category])\n found_durations = request.every(options[:duration])\n raise \"Capture mismatch for multiple values in a request\" unless found_categories.length == found_durations.length\n found_categories.each_with_index { |cat, index| update_statistics(cat, found_durations[index]) }\n else\n category = @categorizer.call(request)\n duration = @durationizer.call(request)\n update_statistics(category, duration) if duration.kind_of?(Numeric) && category\n end\n end", "def update_statistics # :nodoc:\n @statistics.add_result self\n end", "def set_cat_data\n if session[:category_a] != 0\n ar = '(' + ((session[:rex_spending_category_a].to_f / session[:category_a].to_f)*100).to_i.to_s + '%)'\n @a_research = (session[:rex_spending_category_a].to_s + '/' + session[:category_a].to_s) + ar\n end\n if session[:category_a] != 0\n ag = '(' + ((session[:grant_category_a].to_f / session[:category_a].to_f)*100).to_i.to_s + '%)'\n @a_grant = (session[:grant_category_a].to_s + '/' + session[:category_a].to_s) + ag\n end\n\n\n if session[:category_b] != 0\n br = '(' + ((session[:rex_spending_category_b].to_f / session[:category_b].to_f)*100).to_i.to_s + '%)'\n @b_research = (session[:rex_spending_category_b].to_s + '/' + session[:category_b].to_s) + br\n end\n if session[:category_b] != 0\n bg = '(' + ((session[:grant_category_b].to_f / session[:category_b].to_f)*100).to_i.to_s + '%)'\n @b_grant = (session[:grant_category_b].to_s + '/' + session[:category_b].to_s) + bg\n end\n\n if session[:category_c] != 0\n cr = '(' + ((session[:rex_spending_category_c].to_f / session[:category_c].to_f)*100).to_i.to_s + '%)'\n @c_research = (session[:rex_spending_category_c].to_s + '/' + session[:category_c].to_s) + cr\n end\n if session[:category_c] != 0\n cg = '(' + ((session[:grant_category_c].to_f / session[:category_c].to_f)*100).to_i.to_s + '%)'\n @c_grant = (session[:grant_category_c].to_s + '/' + session[:category_c].to_s) + cg\n end\n\n if session[:category_d] != 0\n dr = '(' + ((session[:rex_spending_category_d].to_f / session[:category_d])*100).to_i.to_s + '%)'\n @d_research = (session[:rex_spending_category_d].to_s + '/' + session[:category_d].to_s) + dr\n end\n if session[:category_d] != 0\n dg = '(' + ((session[:grant_category_d].to_f / session[:category_d])*100).to_i.to_s + '%)'\n @d_grant = (session[:grant_category_d].to_s + '/' + session[:category_d].to_s) + dg\n end\n\n if session[:category_e] != 0\n er = '(' + ((session[:rex_spending_category_e].to_f / session[:category_e].to_f)*100).to_i.to_s + '%)'\n @e_research = (session[:rex_spending_category_e].to_s + '/' + session[:category_e].to_s) + er\n end\n if session[:category_e] != 0\n eg = '(' + ((session[:grant_category_e].to_f / session[:category_e].to_f)*100).to_i.to_s + '%)'\n @e_grant = (session[:grant_category_e].to_s + '/' + session[:category_e].to_s) + eg\n end\nend", "def increment_examples(category)\n cat_data(category)[:examples] += 1\n end", "def record_new_category_sum\n @category_sum_new = true if category_sum.try(:new_record?)\n end", "def update_call_counts!(layer)\n @call_set[layer.name].update!(layer.desc)\n end", "def update_category_counter\n category = item.category\n category.update_items_counter if category\n end", "def run_batch_test(category)\n unrun_tests = Item.where(category: category, item_type: 'test').where('result IS NULL')\n unrun_tests.each do |item|\n most_common_category = find_closest_category(item.phash)\n item.update(:result => most_common_category)\n end\n end", "def update\n @calculation_categories = CalculationCategory.order(name: :asc).map { |u| [ u.name, u.id ] }\n #@calculations = Calculation.where(deleted: false).order(name: :asc).map { |u| [ u.name, u.id ] }\n respond_to do |format|\n if @calculation_category.update(calculation_category_params)\n flash[:success] = 'Категория калькуляций успешно отредактирована.'\n format.html { redirect_to edit_calculation_category_path(@calculation_category) }\n format.json { render :show, status: :ok, location: @calculation_category }\n else\n flash[:danger] = 'Ошибка редактирования категории калькуляций'\n format.html { render :edit }\n format.json { render json: @calculation_category.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the number of hits of a specific category. cat The category
def hits(cat) @categories[cat][:hits] end
[ "def category_count(category)\n @persistence.category_count(category)\n end", "def get_category_frequency(cat)\n @categories[cat].to_f / @corpus_size.to_f \n end", "def number_in_category(category)\n number_by_category_query(category, turns)\n end", "def category_search_count(query, category_id)\n # JD: I refactored this into the model\n Item.category_search_count(query, category_id)\n end", "def hits_overall\n @categories.inject(0) { |sum, (name, cat)| sum + cat[:hits] }\n end", "def amount_cat(category)\n @words.count {|word| word.cat == category && word.level == 0}\n end", "def amount_cat(category)\n @words.count {|word| word.level == 0 && word.cat == category}\n end", "def count(category)\n count = 0\n self.votes.each do |v|\n if v.category == category\n count+=1\n end\n end\n count\n end", "def get_words_with_count_for_category(category)\n @redis.hgetall base_category_key + category\n end", "def get_total_word_count_for_category(category)\n ret = @redis.get sum_key(category)\n # create :total key for this category if it doesn't already exist\n if !ret\n words_with_count_for_category = get_words_with_count_for_category category\n total_word_count_sum_for_category = words_with_count_for_category.values.reduce(0){|sum, count| sum += count.to_i}\n @redis.set sum_key(category), total_word_count_sum_for_category\n end\n ret\n end", "def post_count(category)\n @context.registers[:site].categories[category.downcase].size\n end", "def get_product_category_count(input_category)\n count = 0\n Product.all.each do |product|\n if product.category == input_category\n count += 1\n end\n end\n return count\n end", "def count_of(category)\n @transactions.select {|transaction| transaction.category.to_sym == category}.size\n end", "def feature_count(feature, category)\n @feature_category_counts[feature][category] || 0\n end", "def refs_in_category(catid)\n cf = category_families.where(:category_id => catid).first\n cf ? cf.ref_count : nil\n end", "def mean_cat(category)\n cats = measurement.assessment.test.get(\"cat_abbrev\")\n sum = 0\n antworten = self.responses.dup\n count_of_items = 0\n (0..cats.length).each do |x|\n if cats[x] == category and antworten[x] > 0\n sum += antworten[x]\n count_of_items +=1\n end\n end\n return count_of_items > 0 ? (sum.to_f / count_of_items).to_i : 0\n end", "def category_item_count(category)\n c = category.is_a?(EquipmentCategory) ? category : EquipmentCategory.find(category)\n c.as_same_category? ? equipments.in_as_same_category(c.as_same_category).size : equipments.in_category(c).size \n end", "def count\n hits.count\n end", "def total_category_item_count(category)\n @total_category_item_count ||= overlapping_reservations_for_person.collect{|r| r.category_item_count(category)}.sum\n @total_category_item_count + category_item_count(category)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the minimal duration of a specific category. cat The category
def min(cat) @categories[cat][:min] end
[ "def min\n assert_ordered :min\n categories.first\n end", "def minimum_duration(duration = nil)\n if @headers['EXT-X-TARGETDURATION'].empty?\n return duration if duration\n return 999_999_999 # TODO: Infinity or Zero?\n end\n\n # see\n # http://tools.ietf.org/html/draft-pantos-http-live-streaming-13\n # #section-6.2.2\n spec_min = Integer(@headers['EXT-X-TARGETDURATION'][0].value) * 3\n return duration if duration && duration > spec_min\n spec_min\n end", "def min_duration\n [m4a_duration, ogg_duration].map(&:to_i).min\n end", "def getMin(mod = 60, unit = 1)\n return normalize(getSec(0,0)/60.0, mod, unit) ;\n end", "def daily_tot_current_cat(category = nil)\n cat = category || status[0]\n return \"\" if cat == nil\n totals = get_daily_totals(try {File.read(Filename)})[0]\n return \"\" if totals == nil\n if cat.downcase.index('phd')\n tot = 0\n totals.each {|c, sec| tot += sec if c.downcase.index('phd') }\n incl = \"(all PhD)\"\n else\n tot = totals[cat]\n incl = ''\n end\n return \"#{minutes_format(tot)} so far today #{incl}\"\nend", "def min_duration\n [mp4_duration, webm_duration].map(&:to_i).min\n end", "def duration\n duration = item_hash.deep_find(:listing_duration)\n return nil if duration.nil?\n return :GTC if duration == 'GTC'\n match = duration.match(/[0-9]+/)\n return match.nil? ? 0 : match[0].to_i\n end", "def duration_min\n @tracks.each do |track_info, value|\n @album_duration_min += track_info.duration_ms.to_f/1000/60\n end\n sprintf('%.2f',@album_duration_min)\n end", "def category\n categories.live.order(depth: :desc, lft: :asc).first\n end", "def duration(type='integer')\n case type\n when 'integer'\n return @duration\n when 'text'\n if @duration == 5\n return 'lightning'\n else\n return \"#{duration}min\"\n end\n when 'seconds'\n return @duration * 60\n end\n end", "def shortest_duration(timing)\n case timing\n when Run::REAL\n Duration.new(realtime_shortest_duration_ms)\n when Run::GAME\n Duration.new(gametime_shortest_duration_ms)\n end\n end", "def mean_cat(category)\n cats = measurement.assessment.test.get(\"cat_abbrev\")\n sum = 0\n antworten = self.responses.dup\n count_of_items = 0\n (0..cats.length).each do |x|\n if cats[x] == category and antworten[x] > 0\n sum += antworten[x]\n count_of_items +=1\n end\n end\n return count_of_items > 0 ? (sum.to_f / count_of_items).to_i : 0\n end", "def medium_duration(med)\n\t\thh_mm_sec physical_objects.where(medium: med).inject(0){|sum, p| p[:duration] ? p[:duration].to_i + sum : 0 + sum }\n\tend", "def get_min(key, start_time, end_time, granularity = DEFAULT_STATS_GRANULARITY)\n get_stat(\"min\", key, start_time, end_time, granularity)\n end", "def get_duration\n (DURATION_IN_MINUTES > 60) ? 60 : DURATION_IN_MINUTES\n end", "def duration_by_section\n @library_duration ||= collection_data[:duration]\n end", "def duration\n duration_property ? duration_property.ruby_value : nil\n end", "def duration\n @duration ||= begin\n duration = @test_case['time']\n duration ? duration.to_f : nil\n end\n end", "def delta_min; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the maximum duration of a specific category. cat The category
def max(cat) @categories[cat][:max] end
[ "def maximum_duration\n return @maximum_duration\n end", "def max\n assert_ordered :max\n categories.last\n end", "def max_duration traces\r\n traces_max=0\r\n\ttraces.each_index do |index|\r\n\t\ttraces_max=traces[index].duration unless traces_max>traces[index].duration\r\n\t\tend\r\n\ttraces_max\r\n end", "def maximum_duration=(value)\n @maximum_duration = value\n end", "def max_time\n max = -1\n max = master_file.duration.to_f if master_file.present? && master_file.duration.present?\n if master_file.present?\n master_file.derivatives.each do |derivative|\n max = derivative.duration.to_f if derivative.present? && derivative.duration.present? && derivative.duration.to_f > max\n end\n end\n max\n end", "def category\n categories.live.order(depth: :desc, lft: :asc).first\n end", "def duration(type='integer')\n case type\n when 'integer'\n return @duration\n when 'text'\n if @duration == 5\n return 'lightning'\n else\n return \"#{duration}min\"\n end\n when 'seconds'\n return @duration * 60\n end\n end", "def duration\n duration = item_hash.deep_find(:listing_duration)\n return nil if duration.nil?\n return :GTC if duration == 'GTC'\n match = duration.match(/[0-9]+/)\n return match.nil? ? 0 : match[0].to_i\n end", "def max_time\n @max_time ||= 0.2\n end", "def youngestCat\n @cat = Animal.youngestCat\n json_response(@cat)\n end", "def get_duration\n (DURATION_IN_MINUTES > 60) ? 60 : DURATION_IN_MINUTES\n end", "def max_record_duration_in_seconds\n return @max_record_duration_in_seconds\n end", "def get_maximum(context)\n max_value\n end", "def max_duration=(duration)\n nodes = @nodes.to_a\n add_edge(nodes.last, nodes.first, -duration)\n duration\n end", "def min(cat)\n @categories[cat][:min]\n end", "def longest(num)\n @movies.sort_by(&:duration).last(num)\n end", "def max_video_duration\n # 2:20m\n 140\n end", "def last_activity\n if topics.empty?\n # If there are no topics yet in thic category then:\n updated_at\n else\n # Otherwise last activity is newest topic in this category is returned.\n topics.first.last_activity\n end\n end", "def medium_duration(med)\n\t\thh_mm_sec physical_objects.where(medium: med).inject(0){|sum, p| p[:duration] ? p[:duration].to_i + sum : 0 + sum }\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the standard deviation of the duration of a specific category. cat The category
def stddev(cat) Math.sqrt(variance(cat)) end
[ "def std_dev\n Math.sqrt((@sum2.to_f - ((@sum.to_f * @sum.to_f)/@count.to_f)) / (@count.to_f - 1))\n end", "def stddev()\n\t\tarray = error()\n\t\tm = mean()\n\t\tvariance = array.inject(0) { |variance, x| variance += (x - m) ** 2 }\n\t\tMath.sqrt(variance / (array.size - 1))\n\tend", "def variance(cat)\n return 0.0 if @categories[cat][:hits] <= 1\n (@categories[cat][:sum_of_squares] / (@categories[cat][:hits] - 1))\n end", "def stddev\n\t\tsum = 0\n\t\tm = mean\n\t\tpred_list.each do |pred|\n\t\t\tsum += (pred[:error] - m) ** 2\n\t\tend\n\t\treturn Math.sqrt(sum / size)\n\tend", "def stddev\n sum = 0\n get_mean = mean\n pred_error.each { |e| sum += (e-get_mean)**2}\n return Math.sqrt(sum/pred_error.length.to_f)\n end", "def deviation(clusters, queryLength)\n hits = clusters.map{|c| c.lengths.map{ |x| a = Array.new(x[1],x[0])}.flatten}.flatten\n raw_hits = clusters.map{|c| c.lengths.map{ |x| a = Array.new(x[1],x[0])}.flatten}.flatten.to_s.gsub('[','').gsub(']','')\n R.eval(\"sd = sd(c(#{raw_hits}))\")\n sd = R.pull(\"sd\")\n sd = standard_deviation(hits)\n \n (queryLength - mean).abs / sd\n\n end", "def std_dev\n mean = avg\n deviations = @results.map { |r| (r - mean) ** 2 }\n variance = deviations.reduce(:+) / deviations.size\n Math.sqrt(variance)\n end", "def mean(cat)\n @categories[cat][:mean]\n end", "def std_deviation(measure = :avg_total_payments)\n measure_values = charges.map{|c| c.read_attribute(measure)}\n stats = DescriptiveStatistics::Stats.new(measure_values)\n @std_deviation ||= stats.variance\n end", "def std_dev\n Statistics.std_dev @data\n end", "def stddev(population, opts={:sample=>false})\n sqrt(variance(population, opts))\n end", "def deviation(datum)\n datum.to_f - mean.to_f\n end", "def stddev\n return @stddev if @stddev\n @stddev = 0\n return if @t == 1\n @thresholds.each { |t| @stddev += (t - @mean)*(t - @mean) }\n @stddev /= @t - 1\n @stddev = @stddev\n end", "def sample_stdev\n Math.sqrt(sample_variance)\n end", "def mean_cat(category)\n cats = measurement.assessment.test.get(\"cat_abbrev\")\n sum = 0\n antworten = self.responses.dup\n count_of_items = 0\n (0..cats.length).each do |x|\n if cats[x] == category and antworten[x] > 0\n sum += antworten[x]\n count_of_items +=1\n end\n end\n return count_of_items > 0 ? (sum.to_f / count_of_items).to_i : 0\n end", "def stddev\n m = mean\n #variance = avg squared deviation from mean\n variance = @err.map { |e| diff(e, m) * 2 }.mean\n #stddev = square_root(variance)\n return Math.sqrt(variance).round(2)\n end", "def stddev\n return 0.0 unless @count > 1\n Math.sqrt((@sumsq - ((@sum * @sum)/@count)) / (@count - 1))\n end", "def std(dimen=0)\n variance(dimen).sqrt\n end", "def stddevCount(v)\r\n if (@theMetric.series_type == 'event')\r\n if !(@stddev.nil? or @stddev == 0)\r\n return z = (v-@mean)/@stddev\r\n end\r\n end\r\n #if the conditions fall through, just return the value\r\n return v\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the variance of the duration of a specific category. cat The category
def variance(cat) return 0.0 if @categories[cat][:hits] <= 1 (@categories[cat][:sum_of_squares] / (@categories[cat][:hits] - 1)) end
[ "def stddev(cat)\n Math.sqrt(variance(cat))\n end", "def variance; end", "def variance\n (var_between_cluster*1.0/var_within_cluster)\n end", "def discover_variance\r\n end", "def variance\n return nil if @numSamples < 2\n (@sumSamplesSquared - (@sumSamples ** 2) / @numSamples) / (@numSamples - 1)\n end", "def variance\n @variance ||= \n @data.inject(0) { |i,j| i += (j - mean(@data)) ** 2} / (@data.size)\n end", "def sample_variance\n avg = self.average\n sum = self.inject(0) { |acc, i| acc + (i - avg) ** 2 }\n 1 / self.length.to_f * sum\n end", "def mean(cat)\n @categories[cat][:mean]\n end", "def variance\n @cleaned_data.map{ |datum| deviation(datum) ** 2.0 }.sum / n.to_f\n end", "def mean_cat(category)\n cats = measurement.assessment.test.get(\"cat_abbrev\")\n sum = 0\n antworten = self.responses.dup\n count_of_items = 0\n (0..cats.length).each do |x|\n if cats[x] == category and antworten[x] > 0\n sum += antworten[x]\n count_of_items +=1\n end\n end\n return count_of_items > 0 ? (sum.to_f / count_of_items).to_i : 0\n end", "def variance(k)\n submatrix([k])[0,0]\n end", "def sample_variance\n if @n <= 1\n Float::NAN\n else\n @m2 / (@n - 1)\n end\n end", "def variance(attribute_name) \n enumerateAttributes.each_with_idx do |att,idx|\n return variance(idx) if att.name==attribute_name\n end\n end", "def variance(data, mu=nil, opts={}, &block)\n return 0 if data.nil? || data.empty?\n\n mu = CentralTendency.mean(data, &block) if mu.nil?\n\n deviation = data.reduce([]) do |memo, datum|\n datum = yield(datum) if block_given?\n memo << (datum.to_f - mu) ** 2\n end\n\n variance = CentralTendency.mean(deviation)\n return variance\n end", "def variance(series)\r\n n = 0\r\n avg = 0.0\r\n s = 0.0\r\n series.each { |x|\r\n n = n + 1\r\n delta = x - avg\r\n avg = avg + (delta / n)\r\n s = s + delta * (x - avg)\r\n }\r\n # if you want to calculate std deviation\r\n # of a sample change this to \"s / (n-1)\"\r\n return s / n\r\n end", "def sample_variance\n m = mean\n numerator = sum { |v| (v - m)**2 }\n numerator / (size - 1).to_f\n end", "def sample_variance(column = nil)\n data = column ? map(&column.to_sym) : self\n return nil unless data.first\n avg = data.average\n sum = data.inject(0) {|acc, i| acc + (i - avg)**2 }\n 1 / data.length.to_f * sum\n end", "def variance(dimen=0)\n m = mean(dimen)\n reduce_along_dim(dimen, 0.0) do |var, sub_mat|\n var + (m - sub_mat)*(m - sub_mat)/(shape[dimen]-1)\n end\n end", "def add_variance\n\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the total hits of a all categories.
def hits_overall @categories.inject(0) { |sum, (name, cat)| sum + cat[:hits] } end
[ "def hits(cat)\n @categories[cat][:hits]\n end", "def total\n hits.total\n end", "def total_hits_count\n return top_hits_count + all_hits_count\n end", "def set_total_hits\n return set_top_hits + set_all_hits\n end", "def total_categories\n total_specific_category = 0\n total_surprise_category = 0\n total_categories = {}\n\n # You know if a user selects 'Just Surprise Me', that will be the only possible category for the interview\n object.mock_interviews.each do |interview|\n interview.user_selected_categories.each do |category|\n # where returns an array; there will only be 1 value\n question_category = QuestionCategory.where([\"id = ?\", category.question_category_id]).first\n if question_category.name === 'Just Surprise Me'\n total_surprise_category +=1\n end\n end\n end\n total_categories[:specific_category] = object.mock_interviews.count - total_surprise_category\n total_categories[:surprise_category] = total_surprise_category\n\n return total_categories\n end", "def get_words_with_count_for_category(category)\n @redis.hgetall base_category_key + category\n end", "def get_total_word_count_for_category(category)\n ret = @redis.get sum_key(category)\n # create :total key for this category if it doesn't already exist\n if !ret\n words_with_count_for_category = get_words_with_count_for_category category\n total_word_count_sum_for_category = words_with_count_for_category.values.reduce(0){|sum, count| sum += count.to_i}\n @redis.set sum_key(category), total_word_count_sum_for_category\n end\n ret\n end", "def overall_frequency\n categories.inject(0) { |carry, item| carry + item[1] }\n end", "def get_category_frequency(cat)\n @categories[cat].to_f / @corpus_size.to_f \n end", "def total\n if response.response['hits']['total'].respond_to?(:keys)\n response.response['hits']['total']['value']\n else\n response.response['hits']['total']\n end\n end", "def all_hits_count\n return @all_results.length || 0\n end", "def count(include_subcats = false)\n @count ||= begin\n out = {}\n ci = category_info\n\n out[@name] = {\n :pages => ci.pages.to_i\n }\n\n if include_subcats and ci.subcats.to_i > 0\n out[@name][:subcats] = {}\n members.each do |m|\n out[@name][:subcats].merge! self.class.new(@wiki_bot, m[\"title\"]).count(include_subcats)\n end\n end\n\n out\n end\n end", "def category_search_count(query, category_id)\n # JD: I refactored this into the model\n Item.category_search_count(query, category_id)\n end", "def total\n sum = 0\n @keywords_for_tag.each_key {|key|\n sum += @keywords_for_tag[key].count\n }\n sum\n end", "def total_hits(id)\n connection.get(\"#{namespace}:#{name}:total:#{id}\").to_i\n end", "def count\n hits.count\n end", "def all\n @hits\n end", "def occurrences_of_all_features_in_class(classification)\n # return the cached value, if there is one\n return @occurrences_of_all_features_in_class[classification] if @occurrences_of_all_features_in_class[classification]\n\n @feature_counts.each_value do |feature_count|\n @occurrences_of_all_features_in_class[classification] ||= 0\n @occurrences_of_all_features_in_class[classification] += feature_count.count_for_class(classification)\n end\n @occurrences_of_all_features_in_class[classification]\n end", "def hits\n return @hits\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return categories sorted by a given key. by The key to sort on. This parameter can be omitted if a sorting block is provided instead
def sorted_by(by = nil) if block_given? categories.sort { |a, b| yield(b[1]) <=> yield(a[1]) } else categories.sort { |a, b| send(by, b[0]) <=> send(by, a[0]) } end end
[ "def sort_by!(hash, &block)\n hash.replace(sort_by(hash, &block))\n end", "def sort_by_key\n sorted = @data.sort{|a, b| a.first <=> b.first}\n return Catalog.new(sorted)\n end", "def sort_by(&blk)\n self.class.new colorset: @colorset.sort_by(&blk)\n end", "def sort_customers(sort_by)\n sort_by ||= ::LoremIpsumNearby.config.result_sort_by\n\n return [] if @customers.empty?\n raise ::LoremIpsumNearby::InvalidSortKey, \"Invalid sort key\" unless @customers.first.has_key?(sort_by)\n\n @customers.sort_by! { |obj| obj[sort_by.to_s] }\n\n self\n end", "def sort_by_key!\n sorted = @data.sort!{|a, b| a.first <=> b.first}\n return self\n end", "def sort_by(collection, key)\n collection.sort{|x,y| x[key] <=> y[key]}\n end", "def sort(key)\n @items = @items.sort_by{|i| i[key] }\n rescue NoMethodError => e\n Smoke.log.info \"You're trying to sort by \\\"#{key}\\\" but it does not exist in your item set\"\n ensure\n return self\n end", "def sort_categories\n for cat in @all_categories\n if(cat.parent_id == nil)\n @all_categories_hash[0] = [cat]\n else\n if(@all_categories_hash[cat.parent_id] == nil)\n @all_categories_hash[cat.parent_id] = []\n end\n @all_categories_hash[cat.parent_id].push(cat)\n end\n end\n for key in @all_categories_hash.keys\n @all_categories_hash[key].sort!{|x,y| x.name <=> y.name}\n end\n end", "def sort_by!(param)\n if param==\"names\"\n @items.sort_by! {|items| items.display_description}\n end\n end", "def sort_by!( &block )\n @sheets = @sheets.sort_by( &block )\n end", "def sort_cats(suitable_cats)\r\n suitable_cats.sort_by! {|cat| cat.criteria_matches}\r\n suitable_cats.reverse\r\nend", "def sort_by(&block)\n raise BlockRequired unless (block_given?)\n\n @sort_by = block\n @filters.synchronize do\n @tasks = Pigeon::SortedArray.new(&@sort_by) + @tasks\n \n @next_task = { }\n end\n end", "def sort_by_without_hooks!( & block )\n \n @without_hooks = true\n\n sort_by!( & block )\n \n @without_hooks = false\n \n return self\n \n end", "def sort_by_key(key = :name)\n sort do |x, y|\n x_value = x[key]\n y_value = y[key]\n x_value <=> y_value\n end\n end", "def sort_by=(value)\n @sort_by = value\n end", "def sort_by\n return @sort_by\n end", "def sort_by( & block )\n\n return to_enum unless block_given?\n\n new_hooked_array = self.class.new_without_internal_array( @configuration_instance )\n new_hooked_array.internal_array = @internal_array.sort_by( & block )\n \n return new_hooked_array\n\n end", "def sort_by(att, options = {})\n sort(options.merge(:by => to_key(att)))\n end", "def sort_items\n new_citems = @citems.sort_by do |i|\n [lookup_citem_by_identifier(i.subsection + \"index.html\").order,\n ((i.type == \"page\" ? 100 : 1) * i.order)]\n end\n @items = new_citems\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a row of statistics information for a report table, given a category
def statistics_row(cat) [cat, hits(cat), display_value(sum(cat)), display_value(mean(cat)), display_value(stddev(cat)), display_value(min(cat)), display_value(max(cat))] end
[ "def statistics_row(cat)\n [cat, hits(cat), display_value(sum(cat)), display_value(mean(cat)), display_value(stddev(cat)),\n display_value(min(cat)), display_value(max(cat)), \n display_value(percentile_interval(cat, 95).begin) + '-' + display_value(percentile_interval(cat, 95).end) ]\n end", "def get_statictics(values_in_category)\n stats = {}\n q1 = values_in_category.percentile(25)\n q3 = values_in_category.percentile(75)\n iqr = q3 - q1\n stats['whisker_bottom'] = q1 - 1.5 * iqr\n stats['q1'] = q1\n stats['med'] = values_in_category.median\n stats['q3'] = q3\n stats['whisker_upper'] = q3 + 1.5 * iqr\n stats\n end", "def metrics_by_category metrics\n categorized_metrics = {}\n METRIC_CATEGORIES.keys.each do |category|\n categorized_metrics[category] = @report[:metrics].slice *METRIC_CATEGORIES[category]\n end\n categorized_metrics\n end", "def report_table(output, sort, options = {}, &block)\n output.puts\n top_categories = output.slice_results(sorted_by(sort))\n output.with_style(:top_line => true) do\n output.table(*statistics_header(:title => options[:title], :highlight => sort)) do |rows|\n top_categories.each { |(cat, info)| rows << statistics_row(cat) }\n end\n end\n end", "def create_summary_report\n @total_fails = 0\n @total_samples = 0\n count = 10\n table = \"<table>\\n<tr id='header'><th>Time</th><th>Users</th><th>Pages/sec</th><th>Page fail rate</th><th>Total fail rate</th><th>Min Page Dur</th><th>Avg Page Dur</th><th>Max Page Dur</th></tr>\\n\"\n\n @groupeddata.each do |data|\n table += \"<tr><td>\" + current_time(count) + \"</td><td>\" + user_count(data) + \"</td><td>\" + pages_per_second(data.count) + \"</td><td>\" + page_fail_rate(data) + \"%</td><td>\" + total_fail_rate(data) + \"%</td><td>\" + min_page_duration(data) + \"</td><td>\" + avg_page_duration(data) + \"</td><td>\" + max_page_duration(data) + \"</td></tr>\\n\"\n count += 10\n end\n\n table += \"</table>\"\n \n return table\n end", "def report_table(output, sort, options = {}, &block)\n output.puts\n\n top_categories = output.slice_results(sorted_by(sort))\n output.with_style(:top_line => true) do \n output.table(*statistics_header(:title => options[:title],:highlight => sort)) do |rows|\n top_categories.each { |(cat, info)| rows.push(statistics_row(cat)) }\n end\n end\n output.puts\n end", "def print_mapping_stats(ios, category, stats)\n name = @@CategoryName[category]\n ios.puts \"#{name} Reads: #{stats['Total Reads']}\"\n if @eland\n mapping_stats = @@ElandMappingStats\n elsif @bwa\n mapping_stats = @@BwaMappingStats\n else\n return\n end\n mapping_stats.each do |label|\n ios.puts \"#{name} #{label}: #{stats[label]}\"\n end\n end", "def statistics\n find(:all, :select => \"title, count(*) AS count, sum(amount) AS sum, avg(amount) AS avg\", :group => :title).map{|stat| stat.attributes}\n end", "def entry_stats_table(game_type, week_to_entry_stats_map, current_week)\n stats_html = \"<h4>Entry Stats</h4>\n <table class='\" + ApplicationHelper::TABLE_CLASS + \"'>\n <thead>\n <tr>\n <th rowspan=2>Stat</th>\"\n if current_week > 0\n stats_html << \"<th colspan='\" + SurvivorEntry::MAX_BETS_MAP[game_type].to_s + \"'>Weeks</th>\"\n end\n stats_html << \"</tr><tr>\"\n 1.upto(current_week) { |week|\n stats_html << \"<th>\" + week.to_s + \"</th>\"\n }\n stats_html << \"</thead>\"\n\n stats_html << \"<tr><td class='rightborderme'>Total Entries</td>\"\n 1.upto(current_week) { |week|\n stats_html << \"<td>\" + week_to_entry_stats_map[week][\"alive\"].to_s + \"</td>\"\n }\n \n stats_html << \"</tr>\n <tr><td class='rightborderme'>Eliminated Entries</td>\"\n 1.upto(current_week) { |week|\n stats_html << \"<td>\" + week_to_entry_stats_map[week][\"elim\"].to_s + \"</td>\"\n }\n\n stats_html << \"</tr>\n <tr><td class='rightborderme'>Remaining Entries</td>\"\n 1.upto(current_week) { |week|\n stats_html << \"<td>\" + (week_to_entry_stats_map[week][\"alive\"] -\n week_to_entry_stats_map[week][\"elim\"]).to_s + \"</td>\"\n }\n\n stats_html << \"</tr></table>\"\n return stats_html.html_safe\n end", "def entry_stats_table(game_type, week_to_entry_stats_map, current_week)\n stats_html = \"<h4>Entry Stats</h4>\n <table class='\" + ApplicationHelper::TABLE_CLASS + \" smallfonttable'>\n <thead>\n <tr>\n <th rowspan=2>Stat</th>\"\n if current_week > 0\n stats_html << \"<th class='leftborderme' colspan='\" +\n SurvivorEntry::MAX_BETS_MAP[game_type].to_s + \"'>Weeks</th>\"\n end\n stats_html << \"</tr><tr>\"\n SurvivorEntry::START_WEEK_MAP[game_type].upto(current_week) { |week|\n stats_html << \"<th class='leftborderme'>\" + week.to_s + \"</th>\"\n }\n stats_html << \"</thead>\"\n\n stats_html << \"<tr><td class='rightborderme'>Total Entries</td>\"\n SurvivorEntry::START_WEEK_MAP[game_type].upto(current_week) { |week|\n stats_html << \"<td>\" + week_to_entry_stats_map[week][\"alive\"].to_s + \"</td>\"\n }\n \n stats_html << \"</tr>\n <tr><td class='rightborderme'>Eliminated Entries</td>\"\n SurvivorEntry::START_WEEK_MAP[game_type].upto(current_week) { |week|\n stats_html << \"<td>\" + week_to_entry_stats_map[week][\"elim\"].to_s + \"</td>\"\n }\n\n stats_html << \"</tr>\n <tr><td class='rightborderme'>Remaining Entries</td>\"\n SurvivorEntry::START_WEEK_MAP[game_type].upto(current_week) { |week|\n stats_html << \"<td>\" + (week_to_entry_stats_map[week][\"alive\"] -\n week_to_entry_stats_map[week][\"elim\"]).to_s + \"</td>\"\n }\n\n stats_html << \"</tr></table>\"\n return stats_html.html_safe\n end", "def get_stat(iTimeStamp, iLocationID, iObjectID, iCategoryID, iValueType)\n rValue = nil\n\n @StatementSelectFromStatsValues.execute(iTimeStamp.to_MySQLTime, iLocationID, iObjectID, iCategoryID)\n if (@StatementSelectFromStatsValues.num_rows > 0)\n @StatementSelectFromStatsValues.each do |iRow|\n lStrValue = iRow[0]\n case iValueType\n when STATS_VALUE_TYPE_INTEGER\n rValue = Integer(lStrValue)\n when STATS_VALUE_TYPE_FLOAT\n rValue = Float(lStrValue)\n when STATS_VALUE_TYPE_PERCENTAGE\n rValue = Float(lStrValue)\n when STATS_VALUE_TYPE_UNKNOWN\n rValue = lStrValue\n when STATS_VALUE_TYPE_MAP\n # TODO\n rValue = lStrValue\n when STATS_VALUE_TYPE_STRING\n rValue = lStrValue\n else\n log_err \"Unknown category value type: #{iValueType}. It will be treated as Unknown.\"\n rValue = lStrValue\n end\n break\n end\n end\n\n return rValue\n end", "def stats\n table_name = @tables.keys.sample\n table = @tables[table_name]\n\n column = table.defs.to_a.sample\n while String == column[1]\n column = table.defs.to_a.sample\n end\n\n column_idx = table.defs.keys.index column[0]\n\n values = table.data.map{ |r| r[column_idx].to_f }.sort\n\n # LLL.info values\n\n count = values.length\n mean = values.inject{ |memo, obj| memo + obj } / count\n\n midpoint = count / 2\n median = values[midpoint]\n\n squared_differences = values.map do |obj|\n d = mean - obj\n d * d\n end\n\n # LLL.info squared_differences\n\n stddev = Math.sqrt(squared_differences.sum / (count - 1))\n\n pseudo_expectation = [[\"stddev\".k, stddev],\n [\"median\".k, median],\n [\"count\".k, count],\n [\"mean\".k, mean]]\n\n got = evaluate([\"stats\".k, [\"table\".k, table_name],\n [\"row-lambda\".k, column[0].k]]).to_h\n\n pseudo_expectation.each do |x|\n assert_in_epsilon(x[1], got[x[0]])\n end\n end", "def meals_by_category(category)\n # API EXAMPLE: https://www.themealdb.com/api/json/v1/1/filter.php?c=Seafood\n content = api_call(\"filter.php?c=#{category}\")\n validate(content)\n content\n end", "def report(output)\n output.title(options[:title]) if options[:title]\n\n if @categories.empty?\n output << \"None found.\\n\"\n else\n sorted_categories = output.slice_results(sorted_by_frequency)\n total_hits = overall_frequency\n\n output.table({:align => :left}, {:align => :right }, {:align => :right}, {:type => :ratio, :width => :rest}) do |rows|\n sorted_categories.each do |(cat, count)|\n rows << [cat, \"#{count} hits\", '%0.1f%%' % ((count.to_f / total_hits.to_f) * 100.0), (count.to_f / total_hits.to_f)]\n end\n end\n\n end\n end", "def statistic\n data.statistic\n end", "def descriptive_statistics_table(values)\n desc_stats = descriptive_statistics(values)\n table = Utils::RdeTable.new(\n desc_stats.map { |stat|\n Utils::RdeTableRow.new(\n :tr,\n [\n Utils::RdeTableCell.new(:th, stat[:label], css_class: 'rde-row_header'),\n Utils::RdeTableCell.new(:td, stat[:value], ruby_formatter: stat[:ruby_formatter], css_class: 'rde-cell-value'),\n ],\n css_class: 'rde-row-values',\n )\n }\n )\n table\n end", "def histograms( category, extra_params = {})\n params = { \"categoryId\" => TOP_LEVEL_US_CATEGORIES[category]||category }.merge!(extra_params)\n fetch(build_url(\"getHistograms\", params))\n end", "def render_for_webquery( statement, group_by_columns )\n\n report_state_hash = YAML.load(self.view_state)\n conn = User.connection\n recordset = conn.select_all(Globals.cleanup_where(statement))\n\n if group_by_columns.nil? || group_by_columns.empty?\n if report_state_hash[:columns_list].nil? || report_state_hash[:columns_list].empty?\n if recordset.empty?\n keys = ['No records found']\n else\n keys = recordset[0].keys\n end\n else\n # Use the provided list of columns.\n keys = report_state_hash[:columns_list].map {|k| k.gsub('\"', '').strip }\n end\n else\n keys = group_by_columns\n # Include the sum or count columns.\n unless recordset.empty?\n extra_cols = recordset[0].keys - keys\n keys += extra_cols\n end\n end\n\n s = \"<table><tr><th>#{keys.join('</th><th>')}</th></tr>\"\n recordset.each do |record|\n s << '<tr>'\n keys.each do |k|\n s << \"<td>#{format_for_spreadsheet(record[k])}</td>\"\n end\n s << '</tr>'\n end\n s << '</table>'\n end", "def concentration_statistics\n stats = Array.new\n \n results = self.concentrations.select('concentration_units, avg(concentration_value) as average_concentration, std(concentration_value) std_concentration').\n group('concentration_units')\n \n results.each do |r|\n stats << \"<strong>Average:</strong> #{r.average_concentration.round(1)} #{r.concentration_units} (&sigma;=#{r.std_concentration.round(1)})\"\n end\n stats\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send money is triggered at the end of the TransactionCreator in order to deliver the money
def send_money if @transaction.status == "Succeed" @money = @transaction.money remove_money give_money get_comission end end
[ "def give_money\n\t\taccount = Account.where(id: @transaction.receiver_id).first\n\t\taccount.update_attribute(:money, account.money + @money)\n\tend", "def give_back_money\n if(@transaction.sender)\n @transaction.sender.balance += @transaction.amount\n @transaction.sender.save\n \n end\n\n if(@transaction.receiver)\n @transaction.receiver.balance -= Monetize.parse(convert(Money.new(@transaction.amount,findCurrency(@transaction.sender_id,@transaction.receiver_id,'sent')), @transaction.receiver.currency)).fractional\n @transaction.receiver.save\n end\n end", "def transfer_funds()\n vendor = Portfolio.find(self.seller_id)\n customer = Portfolio.find(self.buyer_id)\n amount = self.transaction_cost\n customer.balance -= amount\n vendor.balance += amount\n \n Transactor.transaction do \n raise \"Transaction of funds failed!\" unless customer.save && vendor.save\n end\n end", "def send_money sender, recipient, sum \n if !sender.has_enough_money sum \n return \"nedostatuchno\"\n end\n sender.take_balance sum \n recipient.give_balance sum \nend", "def execute_transaction\n#each transfer can only happen once\n if valid? && sender.balance > amount && self.status == \"pending\"\n receiver.balance += amount\n sender.balance -= amount\n self.status = \"complete\"\n else\n#rejects a transfer if the sender doesn't have a valid account\n reject_transfer\n end\n end", "def execute_transaction\n if valid? && sender.balance > amount && self.status == \"pending\"\n sender.balance -= amount\n receiver.balance += amount\n self.status = \"complete\"\n else\n reject_transfer\n end\n\n end", "def execute_transaction\n if valid? && sender.balance > amount && self.status == \"pending\"\n sender.balance -= amount\n receiver.balance += amount\n self.status = \"complete\"\n else\n reject_transfer\n end\n end", "def create_money_transfer!\n if self.payment_method.type == \"PaymentMethod::MoneyTransfer\"\n # with money transfer shipment borns ready\n self.shipment.ready\n update_shipment_state\n update_totals\n end\n end", "def transfer(amount, *args)\n do_transaction :transfer, amount, *args\n end", "def spend( amt )\n @spending_amount += amt\n end", "def depositing_money_saving amount\n @saving_amount += amount\n self\n end", "def transfer_pending_to_money\n @pending_money.each do |coin, value|\n @money[coin] += value\n @pending_money[coin] = 0\n end\n update_pending\n update_money\n end", "def transfer(amount, other)\n @balance -= amount\n other.balance += amount\n puts \"#{@owner} your balance will be #{@balance} after the transfering to #{other.owner}\"\n end", "def test_accept_money\n assert_equal(10, @register.total_money)\n\n @transaction.amount_paid = 3\n @register.accept_money(@transaction)\n assert_equal(13, @register.total_money)\n end", "def release_amount!\n quickbooks_find_or_create_vendor\n quickbooks_create_transaction\n\n hold_account = Account::CashOutHold.instance\n liability_account = Account::Liability.instance\n\n transaction = Transaction::InternalTransfer.create(\n audited: true,\n description: \"#{self.class.name}(#{id}) - $#{amount} moved from #{hold_account.class.name}(#{hold_account.id}) to #{liability_account.class.name}(#{liability_account.id})\"\n )\n\n transaction.splits.create(\n amount: -1 * amount,\n account: hold_account,\n item: self\n )\n\n transaction.splits.create(\n amount: amount,\n account: liability_account,\n item: self\n )\n end", "def do_transfer(debtor,creditor,amount)\n\t\t\n\tend", "def transfer_money(room_name)\n room = @rooms.find { |room| room.name == room_name }\n amount = room.money_received\n room.minus_money(amount)\n @bank_account += amount\n end", "def execute_transaction\n # accounts must be valid\n # sender must have more money in thier account, than the transfer amount\n # status should be \"pending\" so that transaction cannot be repeated\n if self.valid? && self.sender.balance >= self.amount && self.status == \"pending\"\n # remove amount from sender's balance, add amount to receiver's balance, change status to complete\n self.sender.balance -= self.amount\n self.receiver.balance += self.amount\n self.status = \"complete\"\n else\n self.status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\"\n end\n end", "def capture_and_cash\n if self.active? && self.pending_purchase_order && self.accepted_receiver\n\n # start transaction\n ActiveRecord::Base.transaction do\n capture = self.pending_purchase_order.capture\n if capture.success?\n \n sales_order = self.accepted_receiver.sell_to(self.sender, self.accepted_receiver.cart.cart_line_item(self))\n cash = sales_order.cash(self.accepted_receiver.piggy_bank)\n \n if cash.success?\n self.pending_purchase_order.update_origin_address_from(self.accepted_receiver)\n \n service_fee_product = Product.service_fee(:country_code => self.accepted_receiver.default_country)\n \n if service_fee_product\n reward_item = self.accepted_receiver.cart.add(self)\n service_fee_item = self.accepted_receiver.cart.add(service_fee_product, 1, :dependent => reward_item)\n \n purchase_order = self.accepted_receiver.purchase(service_fee_item,\n :seller => Organization.probono)\n charge = purchase_order.pay(self.accepted_receiver.piggy_bank)\n \n if charge.success?\n probono = Organization.probono\n\n if probono\n\n probono_sales_order = probono.sell_to(self.accepted_receiver, service_fee_item)\n probono_cash = probono_sales_order.cash(probono.piggy_bank)\n\n if probono_cash.success?\n # congrats, we are done!\n return true\n else\n logger.error \"Error cashing service fee sales order {#{probono_sales_order.id}} \" +\n \"for reward {#{self.id}} kase {#{self.kase.id}}\\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n \n else\n logger.error \"Error probono organization not found for reward {#{self.id}} kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n\n else\n logger.error \"Error when charging service fee to partner on order \" + \n \"##{purchase_order.number} for kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n else\n logger.error \"Error could not find service fee for accepted_receiver {#{self.accepted_receiver.id}}, \" + \n \"country code \\\"#{self.accepted_receiver.default_country}\\\" for kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n \n else\n logger.error \"Error when cashing sales order {#{sales_order.id}} #{sales_order.number} for kase {#{self.kase.id}}\\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n \n else\n logger.error \"Error when capturing pending order {#{self.pending_purchase_order.id}} #{self.pending_purchase_order.number} for kase {#{self.kase.id}} \\\"#{self.kase.title}\\\"\"\n raise ActiveRecord::Rollback\n end\n end\n end\n false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes money from sender account
def remove_money account = Account.where(id: @transaction.sender_id).first account.update_attribute(:money, account.money - @money) end
[ "def remove_money(amount)\n @wallet -= amount\nend", "def remove_from_money(rem_money)\n rem_money.each do |coin, value|\n @money[coin] -= value\n end\n update_money\n end", "def remove_credit(amount_to_remove)\n sql = \"UPDATE store_credits SET amount = (amount - #{amount_to_remove.to_f.round_at(2)}) WHERE id = #{self.id}\"\n ActiveRecord::Base.connection.execute(sql)\n end", "def debitCoins(amount)\r\n @betESSCoins -= amount\r\n end", "def remove_credit(amount_to_remove)\n sql = \"UPDATE store_credits SET amount = (amount - #{amount_to_remove}) WHERE id = #{self.id}\"\n ActiveRecord::Base.connection.execute(sql)\n end", "def deduct_money_from_account(balance_to_deduct)\n self.balance -= balance_to_deduct\n self.save\n end", "def subtract_amount(amount)\n @balance -= amount\n end", "def remove_customer_cash(customer, amount)\n return customer[:cash] -= amount\nend", "def deduct_wallet\n user = User::find(self.user_id)\n user.budget -= self.pending_money\n user.save\n\n self.pending_money = 0\n self.save\n end", "def subtract_money(amount)\n\t\t@money -= amount\n\t\t@money = 0 if @money < 0\n\t\treturn @money\n\tend", "def withdrawl(amount)\n @balance -= amount\n end", "def withdrawl (amount)\n @balance -= amount\n end", "def debit_player(p, bet)\n\tp.money -= bet\nend", "def subtract(amount)\n @money -= amount\n transactions << \"[#{date_str(Date.today)}]subtracted:#{amount}\"\n end", "def when_removed\n WebMoney::Ext::Client.get_user_purses_balance(self.account_identifier).pursesBalances.each do |purse|\n WebMoney::Ext::Client.remove_purse(self.account_identifier, purse.purse.to_i)\n end\n end", "def remove_customer_cash(customer_hash, money_to_remove)\n customer_hash[:cash] -= money_to_remove\nend", "def transfer_money(room_name)\n room = @rooms.find { |room| room.name == room_name }\n amount = room.money_received\n room.minus_money(amount)\n @bank_account += amount\n end", "def payment(amount)\n @balance -= amount\n end", "def give_back_money\n if(@transaction.sender)\n @transaction.sender.balance += @transaction.amount\n @transaction.sender.save\n \n end\n\n if(@transaction.receiver)\n @transaction.receiver.balance -= Monetize.parse(convert(Money.new(@transaction.amount,findCurrency(@transaction.sender_id,@transaction.receiver_id,'sent')), @transaction.receiver.currency)).fractional\n @transaction.receiver.save\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gives money to receiver account
def give_money account = Account.where(id: @transaction.receiver_id).first account.update_attribute(:money, account.money + @money) end
[ "def money_transfer(sender_account_id, receiver_account_id, amount)\n db.execute(\"UPDATE accounts SET balance = (balance - #{amount}) WHERE \n account_id = ?\", sender_account_id)\n db.execute(\"UPDATE accounts SET balance = (balance + #{amount}) WHERE \n account_id = ?\", receiver_account_id)\n end", "def transfer_money(room_name)\n room = @rooms.find { |room| room.name == room_name }\n amount = room.money_received\n room.minus_money(amount)\n @bank_account += amount\n end", "def activemerchant_amount\n (amount * 100).to_i\n end", "def findCurrency(sender,reciever,direction)\n\n if(Account.find_by(:id => sender).nil?)\n return \"USD\"\n else\n return Account.find_by(:id => sender).currency\n end\n\n end", "def exchange(from)\n # 실시간으로 패치에서 정보를 받아옴\n @bank.update_rates\n @bank.exchange(100, from, 'KRW')\nend", "def send_money sender, recipient, sum \n if !sender.has_enough_money sum \n return \"nedostatuchno\"\n end\n sender.take_balance sum \n recipient.give_balance sum \nend", "def net_amount; debit; end", "def give_back_money\n if(@transaction.sender)\n @transaction.sender.balance += @transaction.amount\n @transaction.sender.save\n \n end\n\n if(@transaction.receiver)\n @transaction.receiver.balance -= Monetize.parse(convert(Money.new(@transaction.amount,findCurrency(@transaction.sender_id,@transaction.receiver_id,'sent')), @transaction.receiver.currency)).fractional\n @transaction.receiver.save\n end\n end", "def enough_money\n\t\tif same_bank?\n\t\t\tmoney.to_f <= Account.where(id: sender_id).first.money.to_f\n\t\telse\n\t\t\tmoney.to_f + 5 <= Account.where(id: sender_id).first.money.to_f\n\t\tend\n\tend", "def charge_cost_to_my_account\n self.my_account.debit(self.aircrafttype.cost)\n end", "def get_paid(amount)\n self.bank_account += amount \n \"all about the benjamins\" \n end", "def balance_for(other_user)\n Money.new(all_balances[other_user.id], 'PLN')\n end", "def charge_cost_to_my_account\n self.my_account.debit(self.airport.terminal_cost_new)\n end", "def gross_transfer_amount\n self.transfer_amount\n end", "def money\n tot = @money\n tot += subenvelopes_money\n tot\n end", "def currency\n account.currency\n end", "def balance\n account.market_value.amount\n end", "def deposit amount, account\n if account == \"checkings\"\n @checkings += amount.round(2)\n else\n @savings += amount.round(2)\n end\n self\n end", "def do_transfer(debtor,creditor,amount)\n\t\t\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets comission and gives it to the account's bank
def get_comission if !@same_bank Account.where(id: @transaction.sender_id).first.update_attribute(:money, Account.where(id: @transaction.sender_id).first.money - 5) Account.where(id: @transaction.sender_id).first.bank.update_attribute(:comissions_amount_earned, Account.where(id: @transaction.sender_id).first.bank.comissions_amount_earned + 5) end end
[ "def close_account\n self.void_pending_authorizations\n if probono = Organization.probono\n if probono.piggy_bank && probono.piggy_bank.reload && probono.piggy_bank != self\n result = self.transfer(probono.piggy_bank, self.available_balance, :limits => false) if probono.piggy_bank\n raise BankError, \"remaining funds could not be transferred\" if !result || !result.success?\n end\n end\n end", "def do_transfer(debtor,creditor,amount)\n\t\t\n\tend", "def get_paid(amount)\n self.bank_account += amount \n \"all about the benjamins\" \n end", "def send_money\n\t\tif @transaction.status == \"Succeed\"\n\t\t\t@money = @transaction.money\n\t\t\tremove_money\n\t\t\tgive_money\n\t\t\tget_comission\n\t\tend\n\tend", "def commission\n get 'commission'\n end", "def transferir(monto, caja)\n Caja.transaction do\n recibo = Recibo.interno_nuevo\n salida = extraer(monto, true)\n entrada = caja.depositar(monto, true)\n salida.causa = entrada.causa = Operacion.new\n recibo.movimientos << salida << entrada\n recibo\n end\n end", "def cc_purchase (person, cc_number, amount)\r\n\t\tif @bank_listing[person.id_number][:cc_spent] < @bank_listing[person.id_number][:cc_limit] && cc_number == @bank_listing[person.id_number][:cc_number]\r\n\t\t\t@bank_listing[person.id_number][:cc_spent]+=amount\r\n\t\t\tputs \"#{@bank_name}: Card accepted.\"\r\n\t\telse\r\n\t\t\tputs \"#{@bank_name}: Card has been declined.\"\r\n\t\tend\r\n\tend", "def others_transfer_same_bank(client, client1, amount)\n puts \"Seleccione la cuenta origen de la cual trasladara los fondos (opciones ahorro o corriente):\"\n origin = gets.chomp.to_s.downcase\n puts \"Seleccione a que cuenta desea trasladar los fondos:\"\n puts \"Ahorro #{client1.saving_account} opcion 1\"\n puts \"Corriente #{client1.check_account} opcion 2\"\n destination = gets.chomp.to_i\n\n if origin == \"ahorro\" && destination == 1\n if client.saving_amount >= amount\n client.saving_amount -= amount\n client1.saving_amount += amount\n success_transfer\n else\n no_money\n end\n elsif origin == \"ahorro\" && destination == 2\n if client.check_amount >= amount\n client.saving_amount -= amount\n client1.check_amount += amount\n success_transfer\n else\n no_money\n end\n elsif origin == \"corriente\" && destination == 1\n if client.check_amount >= amount\n client.check_amount -= amount\n client1.saving_amount += amount\n success_transfer\n else\n no_money\n end\n elsif origin == \"corriente\" && destination == 2\n if client.saving_amount >= amount\n client.check_amount -= amount\n client1.check_amount += amount\n success_transfer\n else\n no_money\n end\n else \n return \"Las opciones validas son ahorro y corriente\"\n end \n end", "def credit\n account.balance += amount\n end", "def charge_cost_to_my_account\n self.my_account.debit(self.airport.terminal_cost_new)\n end", "def charge_cost_to_my_account\n self.my_account.debit(self.aircrafttype.cost)\n end", "def credit(money, identification, options = {})\n post = { :gateid => identification }\n\n commit('CREDIT', money, post)\n end", "def transferir\n caja.transferir monto, caja_destino\n end", "def do_bank_logics\n aba = parse(config[\"MICR\"][\"aba_routing_number\"])\n payer_account_number = parse(config[\"MICR\"][\"payer_account_number\"])\n check_number = parse(config['CHEQUE']['check_number'])\n if facility.details[:is_transpose]\n transpose = InputBatch.do_transpose(@bat, aba, check_number)\n if transpose\n row[config[\"MICR\"][\"payer_account_number\"]], row[config['CHEQUE']['check_number']]\\\n = row[config['CHEQUE']['check_number']], row[config[\"MICR\"][\"payer_account_number\"]]\n end\n end\n if facility.details[:is_warrant]\n if aba == WARRANT_ABA\n row[config['CHEQUE']['check_number']] , row[config[\"MICR\"][\"payer_account_number\"]]\\\n = row[config[\"MICR\"][\"payer_account_number\"]], WARRANT_PAYER_ACCOUNT_NUMBER\n end\n end\n end", "def deposit (amount, account)\n if account == \"checking\"\n @checking_account_balance += amount\n elsif account == \"saving\"\n @saving_account_balance += amount\n else\n puts \"No account was selected\"\n end\n end", "def transferAccount()\n\t\t@transferee = Account.find_by_id(self.transferee_id)\n\tend", "def open_cc (person, cc_limit)\r\n\t\t\r\n\t\t#not quite robust yet\r\n\t\tcase cc_limit.downcase\r\n\t\t\twhen \"silver\"\r\n\t\t\t\t@cc_limit = 2_000\r\n\t\t\twhen \"gold\" \r\n\t\t\t\t@cc_limit = 3_000\r\n\t\t\twhen \"platinum\"\r\n\t\t\t\t@cc_limit = 5_000\r\n\t\t\twhen \"black\"\r\n\t\t\t\t@cc_limit = 10000000000000000000000000\r\n\t\t\telse\r\n\t\t\t\t@cc_limit = 1_000\r\n\t\tend\r\n\t\t\r\n\t\tif @bank_listing[person.id_number][:cc_number] == nil\r\n\t\t\t@bank_listing[person.id_number][:cc_number] = 1234 #used for testing withdraw\r\n\t\t\t#@bank_listing[person.id_number][:credit] = 1_000_000_000_000_000 + rand(10_000_000_000_000_000)\r\n\t\t\t@bank_listing[person.id_number][:cc_limit] = @cc_limit\r\n\t\t\t@bank_listing[person.id_number][:cc_spent] = 0\r\n\r\n\t\t\t#@bank_listing[person.id_number][:credit_limit] = @cc_limit\r\n\t\t\tputs \"#{@bank_name}: Thanks for opening up a #{cc_limit.capitalize} level credit card, #{person.name}. Your limit is $#{@cc_limit}.\" \r\n\t\t\tputs \"#{@bank_name}: Your credit card number is: #{@bank_listing[person.id_number][:cc_number]}.\"\r\n\t\telse\r\n\t\t\tputs \"#{@bank_name}: #{person.name} already has a credit card.\"\r\n\t\tend\r\n\tend", "def transfer(raccount, amount, purpose = [])\n raise \"#{self.inspect} is unavailable for online banking\"\n end", "def transferir(conta, valor)\n \n if self.saldo > valor\n if valor > 1000 #Se a transferencia for maior que 1000 \n retirar_valor(valor+self.taxa)\n depositar_valor(conta,valor) \n else\n depositar_valor(conta,valor) \n retirar_valor(valor)\n end\n else\n p \"Nao e possivel transferir R$#{valor} para #{conta.proprietario}\" \n end\n \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /mission_inventories GET /mission_inventories.json
def index @mission_inventories = MissionInventory.all end
[ "def index\n @inventories = @user.inventories\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @inventories }\n end\n end", "def index\n @inventories = @warehouse.inventories\n\n render json: @inventories\n end", "def index\n @missions = Mission.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @missions }\n end\n end", "def inventory \n @inventories = Inventory.where(:item_id => params[:id])\n @item_name = Item.find(params[:id]).name\n respond_to do |format|\n format.html\n format.json { render json: @inventories }\n end\n end", "def accessories\n render json: { collections: Collection.published_accessories }\n end", "def index\n @skill_inventories = SkillInventory.all\n end", "def index\n @missions = Mission.all\n end", "def show\n @mostsmallmissioninventory = Mostsmallmissioninventory.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mostsmallmissioninventory }\n end\n end", "def list_inventors\n json_out(Inventor.all)\n end", "def index\n @missions = Mission.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @missions }\n end\n end", "def index\n @equipaments = Equipament.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @equipaments }\n end\n end", "def index\n @item_inventories = ItemInventory.all\n end", "def index\n @mission_environments = MissionEnvironment.all\n end", "def index\n @warehouse_inventories = WarehouseInventory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @warehouse_inventories }\n end\n end", "def index\n @tactical_equipments = TacticalEquipment.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tactical_equipments }\n end\n end", "def index\n @missions = Mission.all(:include => :user)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @missions }\n end\n end", "def index_pubic\n @missions = @missions + Mission.where(:is_public => true)\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @missions }\n\n end\n end", "def index\n unless current_user.inventory\n redirect_to :action => 'new'\n return\n end\n @inventory = current_user.inventory\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @inventories }\n end\n end", "def index\n @emissions = Emission.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /zmm/item_suppliers POST /zmm/item_suppliers.json
def create @zmm_item_supplier = Zmm::ItemSupplier.new(zmm_item_supplier_params) respond_to do |format| if @zmm_item_supplier.save format.html { redirect_to @zmm_item_supplier, notice: 'Item supplier was successfully created.' } format.json { render :show, status: :created, location: @zmm_item_supplier } else format.html { render :new } format.json { render json: @zmm_item_supplier.errors, status: :unprocessable_entity } end end end
[ "def create\n @supplier = current_merchant.suppliers.new(supplier_params)\n\n respond_to do |format|\n if @supplier.save\n format.html { redirect_to @supplier, notice: 'Supplier was successfully created.' }\n format.json { render :show, status: :created, location: @supplier }\n else\n format.html { render :new }\n format.json { render json: @supplier.errors, status: :unprocessable_entity }\n end\n end\n @supplier.ordering_method_ids = params[:supplier][:ordering_method_ids]\n @supplier.delivery_location_ids = params[:supplier][:delivery_location_ids]\n @supplier.online_retail_service_type_ids = params[:supplier][:online_retail_service_type_ids]\n @supplier.product_category_ids = params[:supplier][:product_category_ids]\n end", "def create\n @supplier_item = SupplierItem.new(supplier_item_params)\n\n respond_to do |format|\n if @supplier_item.save\n format.html { redirect_to @supplier_item, notice: 'Supplier item was successfully created.' }\n format.json { render action: 'show', status: :created, location: @supplier_item }\n else\n format.html { render action: 'new' }\n format.json { render json: @supplier_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supplier = Supplier.new(params[:supplier])\n @prizes = Array.new\n\n respond_to do |format|\n if @supplier.save\n flash[:notice] = 'Supplier was successfully created.'\n format.html { redirect_to(suppliers_url) }\n format.xml { render :xml => @supplier, :status => :created, :location => @supplier }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @supplier.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @supplier = Supplier.new(supplier_params)\n\n respond_to do |format|\n if @supplier.save\n format.html { redirect_to(suppliers_path, notice: 'Supplier added.') }\n else\n format.html { render :new }\n format.json { render json: @supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supplier = Supplier.new(supplier_params)\n\n if @supplier.save\n render json: @supplier, status: :created, location: @supplier\n else\n render json: {errors: @supplier.errors}, status: :unprocessable_entity\n end\n end", "def create\n @supplement = current_user.supplements.new(supplement_params)\n\n respond_to do |format|\n if @supplement.save\n format.html { redirect_to @supplement, notice: 'Supplement was successfully created.' }\n format.json { render action: 'show', status: :created, location: @supplement }\n else\n format.html { render action: 'new' }\n format.json { render json: @supplement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_supplier = Admin::Supplier.new(params[:admin_supplier])\n\n respond_to do |format|\n if @admin_supplier.save\n format.html { redirect_to admin_suppliers_url }\n format.json { render json: @admin_supplier, status: :created, location: @admin_supplier }\n else\n format.html { render action: \"new\" }\n format.json { render json: @admin_supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supplement = Supplement.new(supplement_params)\n\n respond_to do |format|\n if @supplement.save\n format.html { redirect_to @supplement, notice: \"Supplement was successfully created.\" }\n format.json { render :show, status: :created, location: @supplement }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @supplement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supplies_needed = SuppliesNeeded.new(supplies_needed_params)\n @supplies_needed.user = current_user\n\n if @supplies_needed.save\n render :show, status: :created, location: @supplies_needed\n else\n render json: @supplies_needed.errors, status: :unprocessable_entity\n end\n end", "def create\n @supply = Supply.new(params[:supply])\n\n respond_to do |format|\n if @supply.save\n format.html { redirect_to supplies_path, notice: 'Supply was successfully created.' }\n format.json { render json: @supply, status: :created, location: @supply }\n else\n format.html { render action: \"new\" }\n format.json { render json: @supply.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tqrdc_supplier = Tqrdc::Supplier.new(tqrdc_supplier_params)\n\n respond_to do |format|\n if @tqrdc_supplier.save\n format.html { redirect_to @tqrdc_supplier, notice: 'Supplier was successfully created.' }\n format.json { render :show, status: :created, location: @tqrdc_supplier }\n else\n format.html { render :new }\n format.json { render json: @tqrdc_supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supplire = Supplire.new(supplire_params)\n\n respond_to do |format|\n if @supplire.save\n format.html { redirect_to @supplire, notice: t(\"message.successfully_created\", name: Supplire.model_name.human) }\n format.json { render action: 'show', status: :created, location: @supplire }\n else\n format.html { render action: 'new' }\n format.json { render json: @supplire.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supply = Supply.new(supply_params)\n\n respond_to do |format|\n if @supply.save\n format.html { redirect_to supplies_path, notice: 'Goods was successfully created.' }\n format.json { render :show, status: :created, location: @supply }\n else\n format.html { render :new }\n format.json { render json: @supply.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @catalogs_supplier = Catalogs::Supplier.new(catalogs_supplier_params)\n\n respond_to do |format|\n if @catalogs_supplier.save\n format.html { redirect_to @catalogs_supplier, notice: 'Supplier was successfully created.' }\n format.json { render :show, status: :created, location: @catalogs_supplier }\n else\n format.html { render :new }\n format.json { render json: @catalogs_supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supplier = Supplier.new(params[:supplier])\n\n respond_to do |format|\n if @supplier.save\n format.html { redirect_to @supplier, notice: 'Supplier was successfully created.' }\n format.json { render json: @supplier, status: :created, location: @supplier }\n else\n format.html { render action: \"new\" }\n format.json { render json: @supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_supplement = UserSupplement.new(params[:user_supplement])\n\n respond_to do |format|\n if @user_supplement.save\n format.html { redirect_to @user_supplement, notice: 'User supplement was successfully created.' }\n format.json { render json: @user_supplement, status: :created, location: @user_supplement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_supplement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @supply_product_info = SupplyProductInfo.new(supply_product_info_params)\n\n respond_to do |format|\n if @supply_product_info.save\n format.js { render_js \"/suppliers/#{@supply_product_info.supplier_id}/supply_product_infos\", '供货信息新建成功!' }\n else\n format.html { render :new }\n format.json { render json: @supply_product_info.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @supplier_items = SupplierItem.all\n 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" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /zmm/item_suppliers/1 PATCH/PUT /zmm/item_suppliers/1.json
def update respond_to do |format| if @zmm_item_supplier.update(zmm_item_supplier_params) format.html { redirect_to @zmm_item_supplier, notice: 'Item supplier was successfully updated.' } format.json { render :show, status: :ok, location: @zmm_item_supplier } else format.html { render :edit } format.json { render json: @zmm_item_supplier.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @supplier_item.update(supplier_item_params)\n format.html { redirect_to @supplier_item, notice: 'Supplier item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @supplier_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @supplier = Supplier.find(params[:id])\n @supplier.update_attributes(params[:supplier])\n respond_with(@supplier)\n end", "def update\n if @supplies_needed.update(supplies_needed_params)\n render :show, status: :ok, location: @supplies_needed\n else\n render json: @supplies_needed.errors, status: :unprocessable_entity\n end\n end", "def update\n @admin_supplier = Admin::Supplier.find(params[:id])\n\n respond_to do |format|\n if @admin_supplier.update_attributes(params[:admin_supplier])\n format.html { redirect_to admin_suppliers_url }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @admin_supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @supply = Supply.find(params[:id])\n\n respond_to do |format|\n if @supply.update_attributes(params[:supply])\n format.html { redirect_to supplies_path, notice: 'Supply was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @supply.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @supplire.attributes = supplire_params\n\n respond_to do |format|\n if @supplire.save\n format.html { redirect_to @supplire, notice: t(\"message.successfully_updated\", name: Supplire.model_name.human) }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @supplire.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @supplement.update(supplement_params)\n format.html { redirect_to @supplement, notice: 'Supplement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @supplement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @supplement = Supplement.find(params[:id])\n\n respond_to do |format|\n if @supplement.update_attributes(params[:supplement])\n format.html { redirect_to @supplement, notice: 'Supplement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @supplement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @stocker_item.update(stocker_item_params)\n render json: @stocker_item\n end", "def update\n @supplier = Supplier.find(params[:id])\n\n respond_to do |format|\n if @supplier.update_attributes(params[:supplier])\n format.html { redirect_to @supplier, notice: 'Supplier was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @user_supplement = UserSupplement.find(params[:id])\n\n respond_to do |format|\n if @user_supplement.update_attributes(params[:user_supplement])\n format.html { redirect_to @user_supplement, notice: 'User supplement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user_supplement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @supply.update(supply_params)\n format.html { redirect_to supplies_path, notice: 'Record was successfully updated.' }\n format.json { render :show, status: :ok, location: @supply }\n else\n format.html { render :edit }\n format.json { render json: @supply.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @catalogs_supplier.update(catalogs_supplier_params)\n format.html { redirect_to @catalogs_supplier, notice: 'Supplier was successfully updated.' }\n format.json { render :show, status: :ok, location: @catalogs_supplier }\n else\n format.html { render :edit }\n format.json { render json: @catalogs_supplier.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n json_response(@food_item.update!(food_item_params))\n end", "def update\n respond_to do |format|\n if @supply_product_info.update(supply_product_info_params)\n format.js { render_js \"/suppliers/#{@supply_product_info.supplier_id}/supply_product_infos\", '供货信息更新成功!' }\n else\n format.html { render :edit }\n format.json { render json: @supply_product_info.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @supplier_without_account = SupplierWithoutAccount.find(params[:id])\n\n respond_to do |format|\n if @supplier_without_account.update_attributes(params[:supplier_without_account])\n format.html { redirect_to @supplier_without_account, notice: 'Supplier without account was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @supplier_without_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @grocery_item = GroceryItem.where(\n grocery_list_id: params[:grocery_list_id],\n id: params[:id]\n )\n\n if @grocery_item.update(grocery_item_params)\n render json: @grocery_item\n else\n render json: {\n errors: @grocery_item.errors.full_messages\n },\n status: 404\n end\n end", "def update\n @supplier_product = SupplierProduct.find(params[:id])\n\n respond_to do |format|\n if @supplier_product.update_attributes(params[:supplier_product])\n format.html { redirect_to @supplier_product, notice: 'Supplier product was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @supplier_product.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @catalog_supplier.update(catalog_supplier_params)\n format.html { redirect_to @catalog_supplier, notice: 'Supplier was successfully updated.' }\n format.json { render :show, status: :ok, location: @catalog_supplier }\n else\n format.html { render :edit }\n format.json { render json: @catalog_supplier.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /zmm/item_suppliers/1 DELETE /zmm/item_suppliers/1.json
def destroy @zmm_item_supplier.destroy respond_to do |format| format.html { redirect_to zmm_item_suppliers_url } format.json { head :no_content } end end
[ "def destroy\n @supplier_item.destroy\n respond_to do |format|\n format.html { redirect_to supplier_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @supplier = Supplier.find(params[:id])\n @supplier.destroy\n \n respond_to do |format|\n format.html { redirect_to suppliers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_supplier = Admin::Supplier.find(params[:id])\n @admin_supplier.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_suppliers_url }\n format.json { head :ok }\n end\n end", "def destroy\n @supply = Supply.find(params[:id])\n @supply.destroy\n\n respond_to do |format|\n format.html { redirect_to supplies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @supplier = Supplier.find(params[:id])\n @supplier.destroy\n\n respond_to do |format|\n format.html { redirect_to suppliers_url }\n format.json { head :ok }\n end\n end", "def destroy\n @supplier = Supplier.find(params[:id])\n @supplier.destroy\n\n respond_to do |format|\n format.html { redirect_to suppliers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @supplement.destroy\n respond_to do |format|\n format.html { redirect_to supplements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @water_supplier.destroy\n respond_to do |format|\n format.html { redirect_to water_suppliers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tqrdc_supplier.destroy\n respond_to do |format|\n format.html { redirect_to tqrdc_suppliers_url, notice: 'Supplier was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @supply.destroy\n respond_to do |format|\n format.html { redirect_to supplies_path, notice: 'Record was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_supplement = UserSupplement.find(params[:id])\n @user_supplement.destroy\n\n respond_to do |format|\n format.html { redirect_to user_supplements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @supply = Supply.find(params[:id])\n @supply.destroy\n\n respond_to do |format|\n format.html { redirect_to(supplies_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @supplier = Supplier.find(params[:id])\n @supplier.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_suppliers_url) }\n format.xml { head :ok }\n end\n end", "def delete_mobile_carrier(args = {}) \n delete(\"/mobile.json/#{args[:carrierId]}\", args)\nend", "def destroy_rest\n @item_usage = ItemUsage.find(params[:id])\n @item_usage.destroy\n\n respond_to do |format|\n format.html { redirect_to(item_usages_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @supplier_without_account = SupplierWithoutAccount.find(params[:id])\n @supplier_without_account.destroy\n\n respond_to do |format|\n format.html { redirect_to supplier_without_accounts_url }\n format.json { head :ok }\n end\n end", "def destroy_rest\n @v1_item_usage = V1ItemUsage.find(params[:id])\n @v1_item_usage.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_item_usages_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @lab_supplier = LabSupplier.find(params[:id])\n @lab_supplier.destroy\n\n respond_to do |format|\n format.html { redirect_to lab_suppliers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @supplemental_detail = SupplementalDetail.find(params[:id])\n @supplemental_detail.destroy\n\n respond_to do |format|\n format.html { redirect_to supplemental_details_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mimic how Jekyll's LiquidRenderer would process a nonstatic file, with some dummy payload
def always_liquid(content) Liquid::Template.error_mode = :warn Liquid::Template.parse(content, :line_numbers => true).render( "author" => "John Doe", "title" => "FooBar" ) end
[ "def render_liquid(content, payload, info, path); end", "def page_from_static_file(static_file); end", "def render_liquid(content, payload, info, path)\n renderer.render_liquid(content, payload, info, path)\n end", "def render_with_liquid?\n source =~ /\\.md$/\n end", "def static_template_file?; end", "def template\n @template ||= Liquid::Template.parse body\n end", "def analyze_template(filename)\n tmp = \"\"\n collect = { :data => false, :css => false, :js => false }\n item = \"\"\n name = \"application\"\n load = { :css => true, :js => true }\n \n load[:css] = !File.exists?(\"#{@www}#{name}.css\")\n load[:js] = !File.exists?(\"#{@www}#{name}.js\")\n \n if not File.exists? filename\n filename = \"#{@www}home.#{@lang}.soli\"\n #exit 404\n end\n IO.readlines(filename).each do |line|\n if line[0..6] == \":layout\"\n analyze_template \"#{@www}#{line[7..-1].strip}\"\n end\n if line[0..4] == \":page\"\n @layout = IO.read \"#{@www}#{line[5..-1].strip}\" rescue \"\"\n end\n if line[0..4] == \":name\"\n name = line[5..-1].strip\n load[:css] = !File.exists?(\"#{@www}#{name}.css\")\n load[:js] = !File.exists?(\"#{@www}#{name}.js\")\n end\n \n if [\"#\", \":\", \"@\"].include?(line[0])\n unless item == \"\"\n #\n @layout.gsub!(\"<!-- #{item} -->\", tmp)\n item = \"\"\n tmp = \"\"\n end\n if collect[:css]\n Dir.mkdir \"#{@www}cache/\" rescue nil\n IO.write \"#{@www}cache/#{name}.css\", tmp unless File.exists? \"#{@www}cache/#{name}.css\"\n @layout.gsub!(\"<!-- :css -->\", \"<link rel='stylesheet' type='text/css' href='/cache/#{name}.css' />\")\n tmp = \"\"\n collect[:css] = false\n end\n if collect[:js]\n Dir.mkdir \"#{@www}cache/\" rescue nil\n IO.write \"#{@www}cache/#{name}.js\", tmp unless File.exists? \"#{@www}cache/#{name}.js\"\n @layout.gsub!(\"<!-- :js -->\", \"<script src='/cache/#{name}.js'></script>\")\n tmp = \"\"\n collect[:js] = false\n end\n end\n \n if line[0..3] == \":css\"\n collect[:css] = true\n end\n\n if line[0..2] == \":js\"\n collect[:js] = true\n end\n \n if line[0] == \"#\"\n item = line.strip\n collect[:data] = true\n end\n\n if not [\"#\", \":\", \"@\"].include?(line[0]) and collect[:data]\n tmp += line\n end\n if not [\"#\", \":\", \"@\"].include?(line[0]) and (collect[:css] or collect[:js]) and line.strip.size > 0\n tmp += IO.read \"#{@www}#{line.strip}\" rescue \"\"\n tmp += \"\\n\"\n end\n end\nend", "def parse(string)\n Liquid::Template.parse(string)\nend", "def static_files; end", "def process_with_liquid(text, context={})\n begin\n context = context.stringify_keys if context.respond_to? :stringify_keys\n Liquid::Template.parse(text).render(context)\n rescue\n raise \"Liquid Error: #{$!}\"\n end\n end", "def process_default_render exp\n process_layout\n process_template template_name, nil\n end", "def prepare_liquid_template(template)\n end", "def read(files)\n files.each do |file|\n @unfiltered_content << StaticFile.new(@site, @site.source, @dir, file)\n end\n @unfiltered_content\n end", "def render_with_liquid?\n return false if data[\"render_with_liquid\"] == false\n\n !(coffeescript_file? || yaml_file? || !Utils.has_liquid_construct?(content))\n end", "def liquid_renderer; end", "def processed_template\n unprocessed_content = \"\"\n File.open(source_path) do |f|\n unprocessed_content = f.read\n end\n process_template(unprocessed_content)\n end", "def jekyll_post_object(path, file)\n\n original_stdout = $stdout\n $stdout = File.new('/tmp/null.txt', 'w')\n\n config = Jekyll.configuration({'source' => path})\n site = Jekyll::Site.new(config)\n \n $stdout = original_stdout\n\n Jekyll::Post.new(site, site.source, '', file)\n\nend", "def liquid_for(markup)\n Liquid::Template.file_system = IncludeTemplateFileSystem.new(@design)\n Liquid::Template.register_tag('navigation', NavigationTag)\n Liquid::Template.register_tag('resource_link', ResourceLinkTag)\n Liquid::Template.register_tag('resource_image', ResourceImageTag)\n Liquid::Template.register_tag('search', SearchBlock)\n Liquid::Template.parse(markup)\n end", "def static_files=(_arg0); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /post214s/1 GET /post214s/1.xml
def show @post214 = Post214.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @post214 } end end
[ "def show\n @post170 = Post170.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post170 }\n end\n end", "def show\n @post185 = Post185.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post185 }\n end\n end", "def show\n @post57 = Post57.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post57 }\n end\n end", "def show\n @post181 = Post181.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post181 }\n end\n end", "def show\n @post145 = Post145.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post145 }\n end\n end", "def show\n @post140 = Post140.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post140 }\n end\n end", "def show\n @post105 = Post105.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post105 }\n end\n end", "def show\n @post172 = Post172.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post172 }\n end\n end", "def show\n @post211 = Post211.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post211 }\n end\n end", "def show\n @post254 = Post254.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post254 }\n end\n end", "def show\n @post71 = Post71.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post71 }\n end\n end", "def show\n @post207 = Post207.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post207 }\n end\n end", "def show\n @post231 = Post231.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post231 }\n end\n end", "def show\n @post203 = Post203.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post203 }\n end\n end", "def show\n @post142 = Post142.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post142 }\n end\n end", "def show\n @post150 = Post150.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post150 }\n end\n end", "def show\n @post153 = Post153.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post153 }\n end\n end", "def show\n @post253 = Post253.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post253 }\n end\n end", "def show\n @post155 = Post155.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @post155 }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /post214s POST /post214s.xml
def create @post214 = Post214.new(params[:post214]) respond_to do |format| if @post214.save format.html { redirect_to(@post214, :notice => 'Post214 was successfully created.') } format.xml { render :xml => @post214, :status => :created, :location => @post214 } else format.html { render :action => "new" } format.xml { render :xml => @post214.errors, :status => :unprocessable_entity } end end end
[ "def post(data, tags_in = {}) ; post_to nil, data, tags_in end", "def create\n @post211 = Post211.new(params[:post211])\n\n respond_to do |format|\n if @post211.save\n format.html { redirect_to(@post211, :notice => 'Post211 was successfully created.') }\n format.xml { render :xml => @post211, :status => :created, :location => @post211 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post211.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post168 = Post168.new(params[:post168])\n\n respond_to do |format|\n if @post168.save\n format.html { redirect_to(@post168, :notice => 'Post168 was successfully created.') }\n format.xml { render :xml => @post168, :status => :created, :location => @post168 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post168.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post170 = Post170.new(params[:post170])\n\n respond_to do |format|\n if @post170.save\n format.html { redirect_to(@post170, :notice => 'Post170 was successfully created.') }\n format.xml { render :xml => @post170, :status => :created, :location => @post170 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post170.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post217 = Post217.new(params[:post217])\n\n respond_to do |format|\n if @post217.save\n format.html { redirect_to(@post217, :notice => 'Post217 was successfully created.') }\n format.xml { render :xml => @post217, :status => :created, :location => @post217 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post217.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post181 = Post181.new(params[:post181])\n\n respond_to do |format|\n if @post181.save\n format.html { redirect_to(@post181, :notice => 'Post181 was successfully created.') }\n format.xml { render :xml => @post181, :status => :created, :location => @post181 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post181.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post254 = Post254.new(params[:post254])\n\n respond_to do |format|\n if @post254.save\n format.html { redirect_to(@post254, :notice => 'Post254 was successfully created.') }\n format.xml { render :xml => @post254, :status => :created, :location => @post254 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post254.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post207 = Post207.new(params[:post207])\n\n respond_to do |format|\n if @post207.save\n format.html { redirect_to(@post207, :notice => 'Post207 was successfully created.') }\n format.xml { render :xml => @post207, :status => :created, :location => @post207 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post207.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post164 = Post164.new(params[:post164])\n\n respond_to do |format|\n if @post164.save\n format.html { redirect_to(@post164, :notice => 'Post164 was successfully created.') }\n format.xml { render :xml => @post164, :status => :created, :location => @post164 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post164.errors, :status => :unprocessable_entity }\n end\n end\n end", "def post *args\n make_request :post, *args\n end", "def create\n @post156 = Post156.new(params[:post156])\n\n respond_to do |format|\n if @post156.save\n format.html { redirect_to(@post156, :notice => 'Post156 was successfully created.') }\n format.xml { render :xml => @post156, :status => :created, :location => @post156 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post156.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post157 = Post157.new(params[:post157])\n\n respond_to do |format|\n if @post157.save\n format.html { redirect_to(@post157, :notice => 'Post157 was successfully created.') }\n format.xml { render :xml => @post157, :status => :created, :location => @post157 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post157.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post154 = Post154.new(params[:post154])\n\n respond_to do |format|\n if @post154.save\n format.html { redirect_to(@post154, :notice => 'Post154 was successfully created.') }\n format.xml { render :xml => @post154, :status => :created, :location => @post154 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post154.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post155 = Post155.new(params[:post155])\n\n respond_to do |format|\n if @post155.save\n format.html { redirect_to(@post155, :notice => 'Post155 was successfully created.') }\n format.xml { render :xml => @post155, :status => :created, :location => @post155 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post155.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post167 = Post167.new(params[:post167])\n\n respond_to do |format|\n if @post167.save\n format.html { redirect_to(@post167, :notice => 'Post167 was successfully created.') }\n format.xml { render :xml => @post167, :status => :created, :location => @post167 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post167.errors, :status => :unprocessable_entity }\n end\n end\n end", "def POST; end", "def create\n @post231 = Post231.new(params[:post231])\n\n respond_to do |format|\n if @post231.save\n format.html { redirect_to(@post231, :notice => 'Post231 was successfully created.') }\n format.xml { render :xml => @post231, :status => :created, :location => @post231 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post231.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post137 = Post137.new(params[:post137])\n\n respond_to do |format|\n if @post137.save\n format.html { redirect_to(@post137, :notice => 'Post137 was successfully created.') }\n format.xml { render :xml => @post137, :status => :created, :location => @post137 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post137.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post182 = Post182.new(params[:post182])\n\n respond_to do |format|\n if @post182.save\n format.html { redirect_to(@post182, :notice => 'Post182 was successfully created.') }\n format.xml { render :xml => @post182, :status => :created, :location => @post182 }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post182.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds current AIML document
def build if !@content.empty? @content += "</aiml>" else raise "build function needs to be called when specification is finished" end end
[ "def document\n build.config.document\n end", "def build\n write_ly_file\n compile_pdf\n end", "def build_new_docs\n FileUtils.mkdir_p @temp_root\n @automations.each do |auto|\n \n debug_msg \"Working with #{auto.short_name}\"\n build = @builds_map[auto.short_name]\n versions_to_build = []\n debug_msg \" fetching available verions\"\n if build\n max_build_version = build.versions.max\n versions_to_build += auto.available_versions.select{|v| v > max_build_version}\n else\n n = (auto.respond_to? :versions_to_build) ? auto.versions_to_build : 1\n versions_to_build += auto.available_versions.sort[-n..-1]\n end\n \n if versions_to_build.size > 0\n debug_msg \" versions to build: #{versions_to_build.join(', ')}\"\n else\n debug_msg \" nothing to build\"\n end\n versions_to_build.each do |version|\n build_version auto, version\n end\n \n debug_msg \"\"\n end\n \n clean_up\n end", "def document(options=nil)\n options ||= {}\n\n # TODO: get rid of options (?) originally they were used for commanline overrides,\n # but that's not being used anymore, and it's probably better that way.\n title = options['title'] || self.title\n output = options['output'] || self.output\n main = options['main'] || self.main\n template = options['template'] || self.template\n files = options['files'] || self.files\n exclude = options['exclude'] || self.exclude\n #adfile = options['adfile'] || self.adfile\n extra = options['extra'] || self.extra\n root = options['root'] || self.root\n\n # NOTE: Due to a bug in RDOC this needs to be done so that\n # alternate templates can be used.\n begin\n gem('rdoc')\n #gem(templib || template)\n rescue LoadError\n end\n\n require 'rdoc/rdoc'\n\n #output = File.expand_path(output)\n\n # you can specify more than one possibility, first match wins\n #adfile = [adfile].flatten.compact.find do |f|\n # File.exist?(f)\n #end\n\n main = Dir.glob(main, File::FNM_CASEFOLD).first\n\n include_files = files.to_list.uniq\n exclude_files = exclude.to_list.uniq\n\n if mfile = project.manifest_file\n exclude_files << mfile.basename.to_s # TODO: I think base name should retun a string?\n end\n\n filelist = amass(include_files, exclude_files)\n filelist = filelist.select{ |fname| File.file?(fname) }\n\n if outofdate?(output, *filelist) or force?\n status \"Generating #{output}\"\n\n #target_main = Dir.glob(target['main'].to_s, File::FNM_CASEFOLD).first\n #target_main = File.expand_path(target_main) if target_main\n #target_output = File.expand_path(File.join(output, subdir))\n #target_output = File.join(output, subdir)\n\n argv = []\n argv.concat(extra.split(/\\s+/))\n argv.concat ['--op', output]\n argv.concat ['--main', main] if main\n argv.concat ['--template', template] if template\n argv.concat ['--title', title] if title\n\n exclude_files.each do |file|\n argv.concat ['--exclude', file]\n end\n\n argv = argv + filelist #include_files\n\n rdoc_target(output, include_files, argv)\n #rdoc_insert_ads(output, adfile)\n\n touch(output)\n else\n status \"WebRI RDocs are current (#{output}).\"\n end\n end", "def build\n if expand_document\n combine_layout\n combine_activity_metadata\n document.update! build_params\n else\n document.document_parts.delete_all\n document.update! document_params.merge(toc: template.toc, material_ids: template.toc.collect_material_ids)\n end\n end", "def build\n if expand_document\n combine_layout\n combine_activity_metadata\n document.update! build_params\n else\n document.document_parts.delete_all\n document.update! document_params.merge(toc: template.toc, material_ids: template.toc.collect_material_ids)\n end\n end", "def generate_doc\n\n end", "def build_text\n text = @text\n @solr.build do\n fulltext text\n end\n end", "def generate(doc_dir = Dir.pwd)\n #FileUtils.rm_rf(doc_dir)\n FileUtils.mkdir_p(doc_dir)\n template_path = File.dirname(__FILE__) + \"/../../../markup\"\n template = File.read(\"#{template_path}/template.haml\")\n index_template = File.read(\"#{template_path}/index_template.haml\")\n stylesheet_path = \"#{template_path}/stylesheet.css\"\n documented_sources.traverse(true) do |node|\n if node.value # leaf\n dir = doc_dir + File.dirname(node.full_path)\n FileUtils.mkdir_p(dir)\n file_from_contents(dir + \"/#{node.name}.html\", create_documentation_for_source(node.value, template))\n else\n dir = doc_dir + node.full_path\n FileUtils.mkdir_p(dir)\n FileUtils.cp(stylesheet_path, dir)\n file_from_contents(dir + \"/index.html\", create_index_for_node(node, index_template))\n end\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 createDocument(srcFile)\r\n\r\n # Setup context object builder\r\n ctxBuilder = ContextParser.new(@context)\r\n ctxBuilder.setFlag(@options)\r\n\r\n statusMsg \"Creating guideline context.\"\r\n\r\n ctxBuilder.parse(srcFile)\r\n\r\n printMetrics(@context)\r\n\r\n\r\n\r\n statusMsg \"Parsing external variable definitions.\"\r\n\r\n parseExternalVarDefs(@context)\r\n\r\n\r\n\r\n statusMsg \"Parsing rule data (#{ctxBuilder.context.rules.size.to_s} rules).\"\r\n\r\n ruleBuilder = RuleParser.new(@context)\r\n ruleBuilder.setFlag(@options)\r\n\r\n @context.rules.each do |key, rule|\r\n rule.src = ruleBuilder.parse(rule.xml)\r\n print \".\"\r\n end # rules.each\r\n puts\r\n\r\n\r\n# ctxBuilder.dumpResults\r\n\r\n\r\n # Create output file and output src.\r\n statusMsg \"Generating document.\"\r\n\r\n gdlDoc = GdlDoc.new(srcFile, @context)\r\n gdlDoc.setOptions(@options)\r\n\r\n genFile = gdlDoc.generate\r\n\r\n statusMsg \"Document created: #{genFile}\"\r\n\r\n genFile = gdlDoc.generateRenameList\r\n\r\n statusMsg \"Rename list document created: #{genFile}\"\r\n\r\n end", "def build(config)\n config = defaults.merge(config)\n config[\"config_yml\"] = config\n\n config[\"renderer\"] = Hologram::Utils.get_markdown_renderer(config[\"custom_markdown\"])\n config[\"base_path\"] = \".\"\n\n builder = Hologram::DocBuilder.new(config)\n\n if builder.is_valid?\n builder.build\n else\n $stderr.puts builder.errors\n end\n end", "def build(document)\n document.geom_type = geom_type\n document.format = format\n end", "def createDocument(srcPath)\n $LOG.debug \"GdlDocBuilder::createDocument( #{srcPath} )\"\n\n # Setup context object builder\n ctxBuilder = ContextParser.new(@context)\n ctxBuilder.setFlag(@options)\n\n statusMsg \"Creating context based on src file [ #{srcPath} ].\"\n\n ctxBuilder.parse(srcPath)\n\n printMetrics(@context)\n=begin\n statusMsg \"Parsing external variable definitions.\"\n\n parseExternalVarDefs(@context)\n\n\n\n statusMsg \"Parsing rule data (#{ctxBuilder.context.rules.size.to_s} rules).\"\n\n ruleBuilder = RuleParser.new(@context)\n ruleBuilder.setFlag(@options)\n\n @context.rules.each do |key, rule|\n rule.src = ruleBuilder.parse(rule.xml)\n print \".\"\n end # rules.each\n puts\n=end\n\n # ctxBuilder.dumpResults\n\n # Create output file and output src.\n statusMsg \"Generating document.\"\n\n gdlDoc = GdlDoc.new(srcPath, @context)\n gdlDoc.setOptions(@options)\n\n genFile = gdlDoc.generate\n\n statusMsg \"Document created: #{genFile}\"\n\n #genFile = gdlDoc.generateRenameList\n\n #statusMsg \"Rename list document created: #{genFile}\"\n\n end", "def build(options)\n t = Time.now\n display_folder_paths(options)\n if options[\"unpublished\"]\n Bridgetown.logger.info \"Unpublished mode:\",\n \"enabled. Processing documents marked unpublished\"\n end\n incremental = options[\"incremental\"]\n Bridgetown.logger.info \"Incremental build:\",\n (incremental ? \"enabled\" : \"disabled. Enable with --incremental\")\n Bridgetown.logger.info \"Generating…\"\n process_site(@site)\n Bridgetown.logger.info \"Done! 🎉\", \"#{\"Completed\".green} in less than\" \\\n \" #{(Time.now - t).ceil(2)} seconds.\"\n end", "def build\n new_dir = \"#{@category}/#{@slug}\"\n empty_directory(new_dir)\n template('lesson.json.erb', File.join(new_dir, '.lesson.json'))\n template('etignore.erb', File.join(new_dir, '.etignore'))\n template(\"#{@category}.md.erb\", File.join(new_dir, \"#{@slug}.md\"))\n end", "def generate_build\n filename = \"#{self.build_path}/#{ANT_BUILD_NAME}\"\n log \"Writing build xml to #{filename}\"\n File.open(filename, 'w') do |f|\n f.write(self.build_doc)\n f.close\n end\n filename\n end", "def build\n Automaton.new(@name, @dimensions, @type, @width, @rule)\n end", "def doc\n # get_html beforehand for good output messages\n html = get_html\n print \"Parsing doc...\"\n doc = Nokogiri::HTML(html)\n puts \"done.\"\n puts\n doc\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /listings/new GET /listings/new.json
def new @listing = Listing.new respond_to do |format| format.html # new.html.erb format.json { render json: @listing } end end
[ "def new\n # need to route for neighborhoods\n @listing = Listing.new\n end", "def new\n @listing = Listing.new\n end", "def new\n # allow user to create a new todo item\n @listing = Listing.new\n end", "def new\n @spot_listing = SpotListing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @spot_listing }\n end\n end", "def new\n @listing = Listing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @listing }\n end\n end", "def create\n @listing = Listing.new(listing_params)\n if @listing.save\n render json: @listing, status: :created\n else\n render json: @listing.errors, status: :unprocessable_entity\n end\n end", "def new\n @waiting_list = WaitingList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @waiting_list }\n end\n end", "def create_listing(options = {})\n defaults = { status: 'Saved' }\n post 'listings', defaults.merge(options)\n end", "def get_listings sub\n uri = URI(\"#{base_uri}/r/#{sub}/new.json\")\n params = { limit: 100 }\n uri.query = URI.encode_www_form(params)\n JSON.parse(Net::HTTP.get_response(uri).body)\n end", "def new\n @visiting_list = VisitingList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @visiting_list }\n end\n end", "def new\n @finding = Finding.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @finding }\n end\n end", "def new\n @viewing = Viewing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @viewing }\n end\n end", "def new\n @lending = Lending.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lending }\n end\n end", "def new\n @listing = Listing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.fbml # new.fbml.erb\n format.xml { render :xml => @listing }\n end\n end", "def create\n @listing = Listing.new(item_params)\n\n if @listing.save\n render json: @listing\n else\n render json: { error: t('story_create_error') }, status: :unprocessable_entity\n end\n end", "def new_stories\n get('/newstories.json')\n end", "def new\n @inning = Inning.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @inning }\n end\n end", "def new\n @gear_list = GearList.new\n @gear_list.gear_listings.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gear_list }\n end\n end", "def new\n @posting = Posting.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @posting }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The attributes of a PhidgetLED
def attributes super.merge({ :leds => leds.size, }) end
[ "def attribs\n\t\t@attributes\n\tend", "def attr_info; end", "def attributes(*) end", "def attrib_bits; end", "def def_attributes\n def_attr = []\n @features.each {|feat|\n def_attr.push(feat.data_id) if feat.code == Game_BattlerBase::FEATURE_ELEMENT_RATE\n }\n return def_attr\n end", "def getAttrs\n @attrs\n end", "def attributes\r\n [@x, @y, @angle, @center_x, @center_y, @factor_x, @factor_y, @color.dup, @mode, @zorder]\r\n end", "def attributes\n node[1]\n end", "def lightness\n rgb_to_hsl!\n @attrs[:lightness]\n end", "def print_attribute(*) end", "def lights\n Lights.new(@attributes.fetch('lights', {}))\n end", "def attributes\n map(&:attribute)\n end", "def attributes\n return nil if not @rep\n @rep.get_attributes \"camera\"\nend", "def attribute_names; end", "def values\n @attrs.values\n end", "def attribute\n machine.attribute\n end", "def attribute; end", "def attributes\n platform.attributes.rmerge(suite.attributes)\n end", "def attribute\r\n 0x23c0 | (@val & 0xc00) | # 0xc00 takes the 2 nametable bits\r\n ATTR_ADDRS[@val & 0xfff]\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new Unit object. Can be initialized using a String, a Hash, an Array, Time, DateTime Valid formats include: "5.6 kgm/s^2" "5.6 kgms^2" "5.6 kilogrammetersecond^2" "2.2 kPa" "37 degC" "1" creates a unitless constant with value 1 "GPa" creates a unit with scalar 1 with units 'GPa' 6'4" recognized as 6 feet + 4 inches 8 lbs 8 oz recognized as 8 lbs + 8 ounces
def initialize(*options) @scalar = nil @base_scalar = nil @unit_name = nil @signature = nil @output = {} if options.size == 2 # options[0] is the scalar # options[1] is a unit string begin cached = @@cached_units[options[1]] * options[0] copy(cached) rescue initialize("#{options[0]} #{(options[1].units rescue options[1])}") end return end if options.size == 3 options[1] = options[1].join if options[1].kind_of?(Array) options[2] = options[2].join if options[2].kind_of?(Array) begin cached = @@cached_units["#{options[1]}/#{options[2]}"] * options[0] copy(cached) rescue initialize("#{options[0]} #{options[1]}/#{options[2]}") end return end case options[0] when Hash @scalar = options[0][:scalar] || 1 @numerator = options[0][:numerator] || UNITY_ARRAY @denominator = options[0][:denominator] || UNITY_ARRAY @signature = options[0][:signature] when Array initialize(*options[0]) return when Numeric @scalar = options[0] @numerator = @denominator = UNITY_ARRAY when Time @scalar = options[0].to_f @numerator = ['<second>'] @denominator = UNITY_ARRAY when DateTime, Date @scalar = options[0].ajd @numerator = ['<day>'] @denominator = UNITY_ARRAY when /^\s*$/ raise ArgumentError, "No Unit Specified" when String parse(options[0]) else raise ArgumentError, "Invalid Unit Format" end self.update_base_scalar raise ArgumentError, "Temperatures must not be less than absolute zero" if self.is_temperature? && self.base_scalar < 0 unary_unit = self.units || "" if options.first.instance_of?(String) opt_scalar, opt_units = Unit.parse_into_numbers_and_units(options[0]) unless @@cached_units.keys.include?(opt_units) || (opt_units =~ /(#{TEMP_REGEX})|(pounds|lbs[ ,]\d+ ounces|oz)|('\d+")|(ft|feet[ ,]\d+ in|inch|inches)|%|(#{TIME_REGEX})|i\s?(.+)?|&plusmn;|\+\/-/) @@cached_units[opt_units] = (self.scalar == 1 ? self : opt_units.unit) if opt_units && !opt_units.empty? end end unless @@cached_units.keys.include?(unary_unit) || (unary_unit =~ /#{TEMP_REGEX}/) then @@cached_units[unary_unit] = (self.scalar == 1 ? self : unary_unit.unit) end [@scalar, @numerator, @denominator, @base_scalar, @signature, @is_base].each {|x| x.freeze} self end
[ "def parse(passed_unit_string = '0')\n unit_string = passed_unit_string.dup\n unit_string = \"#{Regexp.last_match(1)} USD\" if unit_string =~ /\\$\\s*(#{NUMBER_REGEX})/\n unit_string.gsub!(\"\\u00b0\".force_encoding('utf-8'), 'deg') if unit_string.encoding == Encoding::UTF_8\n\n unit_string.gsub!(/[%'\"#]/, '%' => 'percent', \"'\" => 'feet', '\"' => 'inch', '#' => 'pound')\n\n if defined?(Complex) && unit_string =~ COMPLEX_NUMBER\n real, imaginary, unit_s = unit_string.scan(COMPLEX_REGEX)[0]\n result = self.class.new(unit_s || '1') * Complex(real.to_f, imaginary.to_f)\n copy(result)\n return\n end\n\n if defined?(Rational) && unit_string =~ RATIONAL_NUMBER\n sign, proper, numerator, denominator, unit_s = unit_string.scan(RATIONAL_REGEX)[0]\n sign = sign == '-' ? -1 : 1\n rational = sign * (proper.to_i + Rational(numerator.to_i, denominator.to_i))\n result = self.class.new(unit_s || '1') * rational\n copy(result)\n return\n end\n\n unit_string =~ NUMBER_REGEX\n unit = self.class.cached.get(Regexp.last_match(2))\n mult = Regexp.last_match(1).nil? ? 1.0 : Regexp.last_match(1).to_f\n mult = mult.to_int if mult.to_int == mult\n\n if unit\n copy(unit)\n @scalar *= mult\n @base_scalar *= mult\n return self\n end\n\n while unit_string.gsub!(/(<#{self.class.unit_regex})><(#{self.class.unit_regex}>)/, '\\1*\\2')\n # collapse <x><y><z> into <x*y*z>...\n end\n # ... and then strip the remaining brackets for x*y*z\n unit_string.gsub!(/[<>]/, '')\n\n if unit_string =~ TIME_REGEX\n hours, minutes, seconds, microseconds = unit_string.scan(TIME_REGEX)[0]\n raise ArgumentError, 'Invalid Duration' if [hours, minutes, seconds, microseconds].all?(&:nil?)\n\n result = self.class.new(\"#{hours || 0} h\") +\n self.class.new(\"#{minutes || 0} minutes\") +\n self.class.new(\"#{seconds || 0} seconds\") +\n self.class.new(\"#{microseconds || 0} usec\")\n copy(result)\n return\n end\n\n # Special processing for unusual unit strings\n # feet -- 6'5\"\n feet, inches = unit_string.scan(FEET_INCH_REGEX)[0]\n if feet && inches\n result = self.class.new(\"#{feet} ft\") + self.class.new(\"#{inches} inches\")\n copy(result)\n return\n end\n\n # weight -- 8 lbs 12 oz\n pounds, oz = unit_string.scan(LBS_OZ_REGEX)[0]\n if pounds && oz\n result = self.class.new(\"#{pounds} lbs\") + self.class.new(\"#{oz} oz\")\n copy(result)\n return\n end\n\n # stone -- 3 stone 5, 2 stone, 14 stone 3 pounds, etc.\n stone, pounds = unit_string.scan(STONE_LB_REGEX)[0]\n if stone && pounds\n result = self.class.new(\"#{stone} stone\") + self.class.new(\"#{pounds} lbs\")\n copy(result)\n return\n end\n\n # more than one per. I.e., \"1 m/s/s\"\n raise(ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string.count('/') > 1\n raise(ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string =~ /\\s[02-9]/\n\n @scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] # parse the string into parts\n top.scan(TOP_REGEX).each do |item|\n n = item[1].to_i\n x = \"#{item[0]} \"\n if n >= 0\n top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/) { x * n }\n elsif n.negative?\n bottom = \"#{bottom} #{x * -n}\"\n top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/, '')\n end\n end\n if bottom\n bottom.gsub!(BOTTOM_REGEX) { \"#{Regexp.last_match(1)} \" * Regexp.last_match(2).to_i }\n # Separate leading decimal from denominator, if any\n bottom_scalar, bottom = bottom.scan(NUMBER_UNIT_REGEX)[0]\n end\n\n @scalar = @scalar.to_f unless @scalar.nil? || @scalar.empty?\n @scalar = 1 unless @scalar.is_a? Numeric\n @scalar = @scalar.to_int if @scalar.to_int == @scalar\n\n bottom_scalar = 1 if bottom_scalar.nil? || bottom_scalar.empty?\n bottom_scalar = if bottom_scalar.to_i == bottom_scalar\n bottom_scalar.to_i\n else\n bottom_scalar.to_f\n end\n\n @scalar /= bottom_scalar\n\n @numerator ||= UNITY_ARRAY\n @denominator ||= UNITY_ARRAY\n @numerator = top.scan(self.class.unit_match_regex).delete_if(&:empty?).compact if top\n @denominator = bottom.scan(self.class.unit_match_regex).delete_if(&:empty?).compact if bottom\n\n # eliminate all known terms from this string. This is a quick check to see if the passed unit\n # contains terms that are not defined.\n used = \"#{top} #{bottom}\".to_s.gsub(self.class.unit_match_regex, '').gsub(%r{[\\d*, \"'_^/$]}, '')\n raise(ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") unless used.empty?\n\n @numerator = @numerator.map do |item|\n self.class.prefix_map[item[0]] ? [self.class.prefix_map[item[0]], self.class.unit_map[item[1]]] : [self.class.unit_map[item[1]]]\n end.flatten.compact.delete_if(&:empty?)\n\n @denominator = @denominator.map do |item|\n self.class.prefix_map[item[0]] ? [self.class.prefix_map[item[0]], self.class.unit_map[item[1]]] : [self.class.unit_map[item[1]]]\n end.flatten.compact.delete_if(&:empty?)\n\n @numerator = UNITY_ARRAY if @numerator.empty?\n @denominator = UNITY_ARRAY if @denominator.empty?\n self\n end", "def parse(passed_unit_string=\"0\")\n unit_string = passed_unit_string.dup\n if unit_string =~ /\\$\\s*(#{NUMBER_REGEX})/\n unit_string = \"#{$1} USD\"\n end\n unit_string.gsub!(/%/,'percent')\n unit_string.gsub!(/'/,'feet')\n unit_string.gsub!(/\"/,'inch')\n unit_string.gsub!(/#/,'pound')\n \n #:nocov:\n if defined?(Uncertain) && unit_string =~ /(\\+\\/-|&plusmn;)/\n value, uncertainty, unit_s = unit_string.scan(UNCERTAIN_REGEX)[0]\n result = unit_s.unit * Uncertain.new(value.to_f,uncertainty.to_f)\n copy(result)\n return \n end\n #:nocov:\n \n if defined?(Complex) && unit_string =~ COMPLEX_NUMBER\n real, imaginary, unit_s = unit_string.scan(COMPLEX_REGEX)[0]\n result = Unit(unit_s || '1') * Complex(real.to_f,imaginary.to_f)\n copy(result)\n return \n end\n \n if defined?(Rational) && unit_string =~ RATIONAL_NUMBER\n numerator, denominator, unit_s = unit_string.scan(RATIONAL_REGEX)[0]\n result = Unit(unit_s || '1') * Rational(numerator.to_i,denominator.to_i)\n copy(result)\n return \n end\n \n unit_string =~ NUMBER_REGEX\n unit = @@cached_units[$2] \n mult = ($1.empty? ? 1.0 : $1.to_f) rescue 1.0\n mult = mult.to_int if (mult.to_int == mult)\n if unit\n copy(unit)\n @scalar *= mult\n @base_scalar *= mult\n return self\n end\n unit_string.gsub!(/<(#{@@UNIT_REGEX})><(#{@@UNIT_REGEX})>/, '\\1*\\2')\n unit_string.gsub!(/[<>]/,\"\")\n \n if unit_string =~ /:/\n hours, minutes, seconds, microseconds = unit_string.scan(TIME_REGEX)[0]\n raise ArgumentError, \"Invalid Duration\" if [hours, minutes, seconds, microseconds].all? {|x| x.nil?}\n result = \"#{hours || 0} h\".unit + \n \"#{minutes || 0} minutes\".unit + \n \"#{seconds || 0} seconds\".unit +\n \"#{microseconds || 0} usec\".unit\n copy(result)\n return\n end\n \n \n # Special processing for unusual unit strings\n # feet -- 6'5\"\n feet, inches = unit_string.scan(FEET_INCH_REGEX)[0]\n if (feet && inches)\n result = Unit.new(\"#{feet} ft\") + Unit.new(\"#{inches} inches\")\n copy(result)\n return \n end\n\n # weight -- 8 lbs 12 oz \n pounds, oz = unit_string.scan(LBS_OZ_REGEX)[0]\n if (pounds && oz)\n result = Unit.new(\"#{pounds} lbs\") + Unit.new(\"#{oz} oz\")\n copy(result)\n return \n end\n \n raise( ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string.count('/') > 1\n raise( ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string.scan(/\\s[02-9]/).size > 0\n @scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts\n top.scan(TOP_REGEX).each do |item|\n n = item[1].to_i\n x = \"#{item[0]} \"\n case \n when n>=0\n top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/) {|s| x * n}\n when n<0\n bottom = \"#{bottom} #{x * -n}\"; top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/,\"\")\n end\n end \n bottom.gsub!(BOTTOM_REGEX) {|s| \"#{$1} \" * $2.to_i} if bottom\n @scalar = @scalar.to_f unless @scalar.nil? || @scalar.empty?\n @scalar = 1 unless @scalar.kind_of? Numeric \n @scalar = @scalar.to_int if (@scalar.to_int == @scalar)\n \n @numerator ||= UNITY_ARRAY\n @denominator ||= UNITY_ARRAY\n @numerator = top.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if top\n @denominator = bottom.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if bottom\n \n \n us = \"#{(top || '' + bottom || '')}\".to_s.gsub(@@UNIT_MATCH_REGEX,'').gsub(/[\\d\\*, \"'_^\\/\\$]/,'')\n raise( ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") unless us.empty?\n\n @numerator = @numerator.map do |item|\n @@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]\n end.flatten.compact.delete_if {|x| x.empty?}\n\n @denominator = @denominator.map do |item|\n @@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]\n end.flatten.compact.delete_if {|x| x.empty?}\n\n @numerator = UNITY_ARRAY if @numerator.empty? \n @denominator = UNITY_ARRAY if @denominator.empty?\n self\n end", "def initialize(value, unit)\n @value = value\n @unit = unit\n end", "def convert_unit(options={})\n return self unless is_numeric? && (unit || per_unit)\n\n new = clone\n if has_numeric_value?\n if options[:unit] && unit\n new_unit = Unit.for(options[:unit])\n Term.validate_dimensional_equivalence?(unit,new_unit)\n new.value Quantity.new(new.value,new.unit).to(new_unit).value\n end\n if options[:per_unit] && per_unit\n new_per_unit = Unit.for(options[:per_unit])\n Term.validate_dimensional_equivalence?(per_unit,new_per_unit)\n new.value Quantity.new(new.value,(1/new.per_unit)).to(Unit.for(new_per_unit)).value\n end\n end\n new.unit options[:unit] if options[:unit]\n new.per_unit options[:per_unit] if options[:per_unit]\n return new\n end", "def initialize(unit, quantity)\n unit = UOM::Unit.for(unit) if Symbol === unit\n @quantity = quantity\n @unit = unit\n @unit_alias = unit unless unit == @unit.label\n end", "def initialize(unit_type)\n \n @resolution_unit = unit_type\n \n # Create our hash.\n # The default value is an empty bucket with\n # a start point and resolution.\n @buckets = Hash.new do |hash, key|\n period = create_period( key )\n @buckets[ key ] = TimeSeries::Bucket.new( period )\n end\n \n if not UNITS.member?(unit_type)\n raise ArgumentError, \"#{unit_type} is not an allowed unit of time\"\n end\n\n end", "def as(unit)\n unit = UOM::Unit.for(unit.to_sym) if String === unit or Symbol === unit\n return self if @unit == unit\n Measurement.new(unit, @unit.as(quantity, unit))\n end", "def initialize(symbol, name, base, from_and_to_base)\n\n # If a Unit with this symbol exists...\n if @@registry.has_key?(symbol)\n raise(PhysicalQuantifier::Error,\n \"Unit already defined for symbol '#{symbol.to_s}'\")\n \n # If a BaseUnit with this symbol exists...\n else\n unless BaseUnit.exists?(base)\n raise PhysicalQuantifier::Error::BaseUnit::NotDefined\n end \n @symbol = symbol\n @name = name\n @base = Unit.get(base)\n if from_and_to_base.kind_of?(Numeric)\n @from_base = eval \"[lambda{ |x| x / #{from_and_to_base.to_f} }]\"\n @to_base = eval \"[lambda{ |x| x * #{from_and_to_base.to_f} }]\"\n else\n unless from_and_to_base.is_a?(Array)\n raise(PhysicalQuantifier::Error,\n \"You must pass an array of two lambda objects to Unit#new\")\n end\n @from_base = [from_and_to_base[0]]\n @to_base = [from_and_to_base[1]]\n end\n @@registry[@symbol] = self\n end\n end", "def as unit\n check_unit! unit\n dist = self.dup\n dist.number = convert_to_meters * meters_map[unit]\n dist.unit = unit\n dist \n end", "def unit=(value)\n @unit = value\n end", "def test_parse_tricky_units\n unit1 = Unit.new('1 mm') #sometimes parsed as 'm*m'\n assert_equal ['<milli>','<meter>'], unit1.numerator\n unit2 = Unit.new('1 cd') # could be a 'centi-day' instead of a candela\n assert_equal ['<candela>'], unit2.numerator\n unit3 = Unit.new('1 min') # could be a 'milli-inch' instead of a minute\n assert_equal ['<minute>'], unit3.numerator\n unit4 = Unit.new('1 ft') # could be a 'femto-ton' instead of a foot\n assert_equal ['<foot>'], unit4.numerator\n unit5 = \"1 atm\".unit\n assert_equal ['<atm>'], unit5.numerator\n unit6 = \"1 doz\".unit\n assert_equal ['<dozen>'], unit6.numerator\n end", "def parse(tokens)\n tokens.delete_if { |t| t == '*' } # multiplication is the default\n tokens.map! do |token|\n # singularize, but make sure not to replace seconds with ''\n token == 's' ? token : token.singularize\n end\n\n # only supports one instance of division\n division = tokens.index('/')\n tokens.delete('/')\n\n # units :: [CUnit]\n units = tokens.map do |token|\n unit = Unit.find_by unit_name: token\n if unit.nil?\n unit = Unit.where('? = ANY(symbols)', token).first\n end\n if unit.nil?\n raise \"No unit found named #{token}.\"\n end\n CUnit.new(unit, 1)\n end\n\n unless division.nil?\n numerator = units[0...division]\n denominator = units[division..-1].map do |u|\n u.exponent *= -1\n u\n end\n\n units == numerator + denominator\n end\n\n return units\n end", "def convertUnitValue(value,unit)\n if (unit.present?)\n unit.strip!\n else\n return value\n end\n unitRegEx=/^([afpnu\\xC2\\xB5\\316\\274mcdhkMGTPE]?)[ ]*(.+)/\n matchSet=unitRegEx.match(unit)\n if (matchSet.nil?)\n return value\n else\n prefix=matchSet[1]\n baseUnit=matchSet[2]\n case prefix\n when \"a\"\n mult=1.0E-18\n when \"f\"\n mult=1.0E-15\n when \"p\"\n mult=1.0E-12\n when \"n\"\n mult=1.0E-9\n when \"u\",\"\\316\\274\",\"\\xC2\\xB5\"\n mult=1.0E-6\n when \"m\"\n mult=1.0E-3\n when \"c\"\n mult=1.0E-2\n when \"d\"\n mult=1.0E-1\n when \"\"\n mult=1.0\n when \"h\"\n mult=1.0E2\n when \"k\"\n mult=1.0E3\n when \"M\"\n mult=1.0E6\n when \"G\"\n mult=1.0E9\n when \"T\"\n mult=1.0E12\n when \"P\"\n mult=1.E15\n when \"E\"\n mult=1.0E18\n else\n mult=1.0\n end\n return value*mult\n end\n end", "def parse(string, format: '%f %U', unit: ?b, prefix: nil)\n prefixes = prefixes(prefix)\n FormatParser.new(format, UnitParser.new(string, unit, prefixes)).parse\n end", "def unit=(value)\n @unit = value\n end", "def initialize(*params, &converter)\n # this long initializer ensures that every unit is correct by construction\n # the first symbol is the label\n labels = params.select { |param| Symbol === param }\n @label = labels.first\n # the optional Factor parameters are the permissible scaling factors\n factors = params.select { |param| Factor === param }.to_set\n # a convertable unit must have a unique factor\n if converter and factors.size > 1 then\n raise MeasurementError.new(\"Derived unit #{label} can have at most one scalar: #{factors.to_a.join(', ')}\")\n @permissible_factors = []\n else\n @permissible_factors = factors\n end\n # a Numeric parameter indicates a conversion multiplier instead of a converter block\n multiplier = params.detect { |param| Numeric === param }\n if multiplier then\n # there can't be both a converter and a multiplier\n if converter then\n raise MeasurementError.new(\"Derived unit #{label} specifies both a conversion multiplier constant and a converter block\")\n end\n # make the converter block from the multiplier\n converter = lambda { |n| n * multiplier }\n end\n # the optional single Unit parameter is the axis for a derived unit\n axes = params.select { |param| Unit === param }\n raise MeasurementError.new(\"Unit #{label} can have at most one axis: #{axes.join(', ')}\") if axes.size > 1\n @axis = axes.first\n # validate that a convertable unit has an axis; the converter argument is an axis quantity\n raise MeasurementError.new(\"Derived unit #{label} has a converter but does not have an axis unit\") if @default_converter and @axis.nil?\n # the axis of an underived base unit is the unit itself\n @axis ||= self\n # validate that there is not a converter on self\n raise MeasurementError.new(\"Unit #{label} specifies a converter but not a conversion unit\") unless converter.nil? if @axis == self\n # the default converter for a derived unit is identity\n converter ||= lambda { |n| n } unless @axis == self\n # the scalar is the first specified factor, or UNIT if there are multiple permissible factors\n @scalar = @permissible_factors.size == 1 ? @permissible_factors.to_a.first : UNIT\n # validate the scalar\n if @axis == self then\n #a derived unit cannot have a scalar factor\n raise MeasurementError.new(\"Base unit #{label} cannot have a scalar value - #{@scalar}\") unless @scalar == UNIT\n elsif @scalar != UNIT and not @axis.permissible_factors.include?(@scalar) then\n # a derived unit scalar factor must be in the axis permissible factors\n raise MeasurementError.new(\"Derived unit #{label} scalar #{scalar} not a #{@axis} permissible factor #{@axis.permissible_factors.to_a.join(', ')}\")\n end\n # if a scalar is defined, then adjust the converter\n scaled_converter = @scalar == UNIT ? converter : lambda { |n| @scalar.as(@axis.scalar) * converter.call(n) } \n # add the axis converter to the converters hash\n @converters = {}\n @converters[@axis] = scaled_converter if converter\n # define the multiplier converter inverse\n @axis.add_converter(self) { |n| 1.0 / scaled_converter.call(1.0 / n) } unless @scalar.nil? and multiplier.nil?\n # make the label from the scalar and axis\n @label ||= create_label\n # validate label existence\n raise MeasurementError.new(\"Unit does not have a label\") if self.label.nil?\n # validate label uniqueness\n if Unit.extent.association.has_key?(@label) then\n raise MeasurementError.new(\"Unit label #{@label} conflicts with existing unit #{Unit.extent.association[@label].inspect}\")\n end\n # get the dimension\n dimensions = params.select { |param| Dimension === param }\n if dimensions.empty? then\n # a base unit must have a dimension\n raise MeasurementError.new(\"Base unit #{label} is missing a dimension\") if @axis == self\n # a derived unit dimension is the axis dimension\n @dimension = axis.dimension\n elsif dimensions.size > 1 then\n # there can be at most one dimension\n raise MeasurementError.new(\"Unit #{label} can have at most one dimension\")\n else\n # the sole specified dimension\n @dimension = dimensions.first\n end\n # the remaining symbols are abbreviations\n @abbreviations = labels.size < 2 ? [] : labels[1..-1]\n # validate abbreviation uniqueness\n conflict = @abbreviations.detect { |abbrev| Unit.extent.association.has_key?(abbrev) }\n raise MeasurementError.new(\"Unit label #{@label} conflicts with an existing unit\") if conflict\n # add this Unit to the extent\n Unit << self\n end", "def parse_unit_part(string, denominator = false)\n return {} if string.nil?\n units = {}\n matches = string.scan(/(\\w+)(\\^\\d)?/)\n matches.each do |m|\n exp = (m[1] ? m[1][1..-1].to_i : 1) * (denominator ? -1 : 1)\n units[m[0].intern] = exp\n end\n units\n end", "def to_metric(str)\n num, unit = str.split\n to_numeric(num).send(unit.to_sym)\nend", "def create_unit(unit, *args)\n send(unit.to_s.pluralize.to_sym).create! args\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate human readable output. If the name of a unit is passed, the unit will first be converted to the target unit before output. some named conversions are available :ft outputs in feet and inches (e.g., 6'4") :lbs outputs in pounds and ounces (e.g, 8 lbs, 8 oz) You can also pass a standard format string (i.e., '%0.2f') or a strftime format string. output is cached so subsequent calls for the same format will be fast
def to_s(target_units=nil) out = @output[target_units] if out return out else case target_units when :ft inches = self.to("in").scalar.to_int out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\"" when :lbs ounces = self.to("oz").scalar.to_int out = "#{(ounces / 16).truncate} lbs, #{(ounces % 16).round} oz" when String out = case target_units when /(%[\-+\.\w#]+)\s*(.+)*/ #format string like '%0.2f in' begin if $2 #unit specified, need to convert self.to($2).to_s($1) else "#{$1 % @scalar} #{$2 || self.units}".strip end rescue (DateTime.new(0) + self).strftime(target_units) end when /(\S+)/ #unit only 'mm' or '1/mm' "#{self.to($1).to_s}" else raise "unhandled case" end else out = case @scalar when Rational "#{@scalar} #{self.units}" else "#{'%g' % @scalar} #{self.units}" end.strip end @output[target_units] = out return out end end
[ "def format_with_unit(*other)\n if other.first.is_a?(RubyUnits::Unit)\n other.first.to_s(self)\n else\n original_format(*other)\n end\n end", "def to_s(target_units = nil)\n out = @output[target_units]\n return out if out\n\n separator = RubyUnits.configuration.separator\n case target_units\n when :ft\n inches = convert_to('in').scalar.to_int\n out = \"#{(inches / 12).truncate}'#{(inches % 12).round}\\\"\"\n when :lbs\n ounces = convert_to('oz').scalar.to_int\n out = \"#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz\"\n when :stone\n pounds = convert_to('lbs').scalar.to_int\n out = \"#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb\"\n when String\n out = case target_units.strip\n when /\\A\\s*\\Z/ # whitespace only\n ''\n when /(%[-+.\\w#]+)\\s*(.+)*/ # format string like '%0.2f in'\n begin\n if Regexp.last_match(2) # unit specified, need to convert\n convert_to(Regexp.last_match(2)).to_s(Regexp.last_match(1))\n else\n \"#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}\".strip\n end\n rescue StandardError # parse it like a strftime format string\n (DateTime.new(0) + self).strftime(target_units)\n end\n when /(\\S+)/ # unit only 'mm' or '1/mm'\n convert_to(Regexp.last_match(1)).to_s\n else\n raise 'unhandled case'\n end\n else\n out = case @scalar\n when Complex\n \"#{@scalar}#{separator}#{units}\"\n when Rational\n \"#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}\"\n else\n \"#{'%g' % @scalar}#{separator}#{units}\"\n end.strip\n end\n @output[target_units] = out\n out\n end", "def output(millimeters, options = {})\n options[:unit] ||= 'millimeters'\n options[:format] ||= :default\n \n unit_options = unit_formatting_options[options[:format]]\n options[:format] = :short if options[:format] == :default\n unit = unit_format(options[:unit], options[:format])\n \n result = humanize_distance(\n distance_in_unit(millimeters, options[:unit]),\n unit,\n unit_options[:pluralize],\n unit_options[:spacer]\n )\n \n result.length == 0 ? nil : result\n end", "def to_s( options = {} )\n options = self.class.options.merge( options )\n units_error( options[ :units ] ) if not self.class::CONVERSIONS.has_key?( options[ :units ] )\n value_in_units = self.send(\"to_#{ options[:units] }\")\n localized_value = I18n.localize_float(value_in_units, {:format => \"%0.#{ options[:precision] }f\"})\n\n key = 'units.' + self.class.measurement_name + '.' + options[:units].to_s\n options[:abbreviated] ? key += '.abbreviated' : key += '.full'\n unit = I18n.t(key, {:count => value_in_units})\n\n \"#{ localized_value }%s#{ unit }\" % (options[:abbreviated] ? '' : ' ')\n end", "def format_as_unit(context, value, **options)\n key = value.downcase\n get_name(context, value, **options) do |style|\n style = :long if style == :default\n context.locale_data(:units, :units, key, style, :display_name)\n end\n end", "def pretty_unit\n return if unitless?\n\n numerator = Inspection.prettify_unit_part(numerators)\n denominator = Inspection.prettify_unit_part(denominators)\n\n numerator = '1' if numerator.empty?\n return \" #{numerator}\" if denominator.empty?\n\n UNIT_FORMAT % [numerator, denominator]\n end", "def result_formatted\n formatted = simplify_number(self.result)\n\n if !formatted.is_a? Numeric\n return nil\n elsif self.prefix\n formatted = '%.2f' % self.result\n return \"#{prefix}#{formatted}\"\n elsif self.out_unit\n return \"#{formatted} #{out_unit}\"\n else\n return formatted\n end\n end", "def format_unit(number)\n scale = (Math.log10(number) / 3).to_i\n scale = 0 if scale > 5\n suffix = UNITS[scale]\n\n \"%.3g#{suffix}\" % [number.to_f / (1000 ** scale)]\n end", "def unit_s\n self.unit.to_s if self.unit\n end", "def to_s\n stats.map { |k, v| \"#{k}: #{v.to_s.rjust(6)} #{unit.ljust(3)} \" }.join\n end", "def printUnits(uUnit: nil, dbUnit: 1e-9)\n if !uUnit\n uUnit = 0.001\n else\n @Resolution = (1 / uUnit); ## default is 1000 - already set in new()\n end\n @UUnits = uUnit\n @DBUnits = dbUnit\n printGds2Record(type: 'UNITS', data: [uUnit, dbUnit])\n end", "def format_rufus_unit(interval_unit)\n if interval_unit == \"seconds\"\n return 's'\n elsif interval_unit == \"minutes\"\n return 'm'\n elsif interval_unit == \"hours\"\n return 'h'\n elsif interval_unit == \"days\"\n return 'd'\n end\n \n return 'time string not found!'\n end", "def format_helper(value, unit)\n \"#{pluralize(value.abs, unit.to_s)} #{value >= 0 ? 'from now' : 'ago'}\"\n end", "def unit_t\n I18n.t \"#{self.unit_s}\", :count => 1\n end", "def units_abbr(unit_type = 'mm')\n @Unit = {\n 'mm' => 'millimeters',\n 'cm' => 'centimeters',\n 'ft' => 'feet',\n 'km' => 'kilometers',\n 'm' => 'meters',\n 'min' => 'minutes',\n }\n if @Unit[unit_type]\n return \"<acronym title=\\\"#{@Unit[unit_type]}\\\">#{unit_type}</acronym>\"\n end\n end", "def unit_str\n rv = @numerator_units.sort.join(\"*\")\n if @denominator_units.any?\n rv << \"/\"\n rv << @denominator_units.sort.join(\"*\")\n end\n rv\n end", "def format_filesize(num, options = {})\n precision = options[:precision] || 0\n if options[:unit]\n unit = options[:unit].upcase\n fail \"Invalid unit\" unless UNITS.include?(unit)\n num = num.to_f\n for u in UNITS\n if u == unit\n s = \"%0.#{precision}f\" % round(num, precision)\n return s + unit\n end\n num = num / 1024\n end\n else\n e = (num == 0) ? 0 : (Math.log(num) / Math.log(1024)).floor\n s = \"%0.#{precision}f\" % round((num.to_f / 1024**e), precision)\n s + UNITS[e]\n end\n end", "def format(options={})\n options.reverse_merge!(I18n.t(\"#{self.currency}.format\", :scope => 'currencies')) if I18n.t(\"#{self.currency}.format\", :scope => \"currencies\").is_a?(Hash)\n options.merge!(:unit => \"\") if options.delete(:strip_symbol)\n options.merge!(:unit => self.currency) if options.delete(:currency_code)\n options.delete(:unlocalized) # deprecated\n number_to_currency(Float(self.cents) / 100, options).strip\n end", "def to_s\n \"#{@value.to_s} #{@unit.symbol}\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
true if unit is a 'temperature', false if a 'degree' or anything else
def is_temperature? self.is_degree? && (!(self.units =~ /temp[CFRK]/).nil?) end
[ "def temperature?\n degree? && units.match?(self.class.temp_regex)\n end", "def therm_us? = unit == 'therm-us'", "def ton? = unit == 'ton'", "def celsius? = unit == 'celsius'", "def kelvin? = unit == 'kelvin'", "def electronvolt? = unit == 'electronvolt'", "def volt? = unit == 'volt'", "def metric_ton? = unit == 'metric-ton'", "def temperature?(temp)\n if not temp.int?\n return false\n end\n \n return true\nend", "def teaspoon? = unit == 'teaspoon'", "def micrometer? = unit == 'micrometer'", "def british_thermal_unit? = unit == 'british-thermal-unit'", "def karat? = unit == 'karat'", "def unit?\n !@unit.nil?\n end", "def cubic_meter? = unit == 'cubic-meter'", "def is_unit?(unit)\n if unit\n denominator_units.size == 0 && numerator_units.size == 1 && numerator_units.first == unit\n else\n unitless?\n end\n end", "def is_time_unit?\n self.is_numeric? && TIME_UNITS.include?(self.unit)\n end", "def astronomical_unit? = unit == 'astronomical-unit'", "def fahrenheit? = unit == 'fahrenheit'" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add two units together. Result is same units as receiver and scalar and base_scalar are updated appropriately throws an exception if the units are not compatible. It is possible to add Time objects to units of time
def +(other) case other when Unit case when self.zero? other.dup when self =~ other raise ArgumentError, "Cannot add two temperatures" if ([self, other].all? {|x| x.is_temperature?}) if [self, other].any? {|x| x.is_temperature?} if self.is_temperature? Unit.new(:scalar => (self.scalar + other.to(self.temperature_scale).scalar), :numerator => @numerator, :denominator=>@denominator, :signature => @signature) else Unit.new(:scalar => (other.scalar + self.to(other.temperature_scale).scalar), :numerator => other.numerator, :denominator=>other.denominator, :signature => other.signature) end else @q ||= ((@@cached_units[self.units].scalar / @@cached_units[self.units].base_scalar) rescue (self.units.unit.to_base.scalar)) Unit.new(:scalar=>(self.base_scalar + other.base_scalar)*@q, :numerator=>@numerator, :denominator=>@denominator, :signature => @signature) end else raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" end when Date, Time raise ArgumentError, "Date and Time objects represent fixed points in time and cannot be added to a Unit" else x,y = coerce(other) y + x end end
[ "def +(other)\n if other.is_a?(Volt::Duration)\n Volt::Duration.new(value + other.value, parts + other.parts)\n else\n Volt::Duration.new(value + other, parts + [[:seconds, other]])\n end\n end", "def +(other)\n if Duration === other\n parts = @parts.merge(other._parts) do |_key, value, other_value|\n value + other_value\n end\n Duration.new(value + other.value, parts, @variable || other.variable?)\n else\n seconds = @parts.fetch(:seconds, 0) + other\n Duration.new(value + other, @parts.merge(seconds: seconds), @variable)\n end\n end", "def +(other)\n if (other.is_a?(Numeric))\n Quantity.new(@value + other, @unit)\n elsif(other.is_a?(Quantity) && @unit.dimension == other.unit.dimension)\n Quantity.new({:unit => @unit,:reference_value => @reference_value + other.reference_value})\n else\n raise ArgumentError,\"Cannot add #{self} to #{other}\"\n end\n end", "def +(other)\n case other\n when TZOffset\n TZOffset.new(seconds + other.seconds)\n when Numeric\n TZOffset.new(seconds + other)\n else\n fail ArgumentError, \"Can't sum with #{other.class}\"\n end\n end", "def + m2\n return magnitude amount + m2.amount if m2.quantity == quantity.relative\n return quantity.relative.magnitude( amount + m2.amount ) if\n quantity == m2.quantity\n return self if m2.equal? SY::ZERO\n # o1, o2 = m2.coerce( self )\n # return o1 + o2\n raise SY::QuantityError, \"Unable to perform #{quantity} + #{m2.quantity}!\"\n end", "def +(other)\n if Duration === other\n Duration.new(value + other.value, @parts + other.parts)\n else\n Duration.new(value + other, @parts + [[:seconds, other]])\n end\n end", "def +(other)\n raise TypeError, 'Not one of: [Duration, #to_nanos]' unless other.respond_to?(:to_nanos)\n\n Duration.new(to_nanos + other.to_nanos)\n end", "def +(other)\n case other\n when Duration then Instant.new(@ns + other.to_nanos)\n else raise TypeError, 'Not a Duration'\n end\n end", "def +( other )\r\n\t\tresult = GTime.new\r\n\t\tif GTime === other || other.respond_to?( :to_i )\r\n\t\t\tresult.seconds = self.to_i + other.to_i\r\n\t\tend\r\n\t\treturn result\r\n\tend", "def +(other)\n return TypeError, 'Not one of: [Duration, #to_nanos]' unless other.respond_to?(:to_nanos)\n\n Instant.new(@ns + other.to_nanos)\n end", "def test_duration_sum\n x = TimeTrello::Duration.new(10, 20, 30)\n y = TimeTrello::Duration.new(30, 20, 10)\n r = x + y\n assert_equal(40, r.hours)\n assert_equal(40, r.minutes)\n assert_equal(40, r.seconds)\n end", "def convert_time_between_units(base_value:, original_unit:, new_unit:)\n if original_unit == new_unit\n base_value\n else\n # first convert to seconds\n value_in_seconds = self.calculate_time_in_seconds(base_value: base_value, unit_label: original_unit)\n # now divide by multiplier to get value in new unit\n denominator = TIME_MULTIPLIERS[new_unit]\n value_in_seconds.to_f / denominator\n end\n end", "def convert_time_between_units(base_value:, original_unit:, new_unit:)\n if original_unit == new_unit\n base_value\n else\n # first convert to seconds\n value_in_seconds = calculate_time_in_seconds(base_value: base_value, unit_label: original_unit)\n # now divide by multiplier to get value in new unit\n denominator = TIME_MULTIPLIERS[new_unit]\n value_in_seconds.to_f / denominator\n end\n end", "def add(time, duration)\n EasyTime.new(time) + duration\n end", "def +(other)\n TimeCode.new(@milliseconds + other.milliseconds)\n end", "def +( other )\n TimeDelta.new( @msecs + other.msecs )\n end", "def add(timeobj, val)\n \tsuper normalize_time_input(timeobj),val \n end", "def add_unit(conversion)\n return self\n end", "def add(time)\n newDuration = self.dup() ;\n return self.inc(time) ;\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subtract two units. Result is same units as receiver and scalar and base_scalar are updated appropriately throws an exception if the units are not compatible.
def -(other) case other when Unit case when self.zero? -other.dup when self =~ other case when [self, other].all? {|x| x.is_temperature?} Unit.new(:scalar => (self.base_scalar - other.base_scalar), :numerator => KELVIN, :denominator => UNITY_ARRAY, :signature => @signature).to(self.temperature_scale) when self.is_temperature? Unit.new(:scalar => (self.base_scalar - other.base_scalar), :numerator => ['<temp-K>'], :denominator => UNITY_ARRAY, :signature => @signature).to(self) when other.is_temperature? raise ArgumentError, "Cannot subtract a temperature from a differential degree unit" else @q ||= ((@@cached_units[self.units].scalar / @@cached_units[self.units].base_scalar) rescue (self.units.unit.scalar/self.units.unit.to_base.scalar)) Unit.new(:scalar=>(self.base_scalar - other.base_scalar)*@q, :numerator=>@numerator, :denominator=>@denominator, :signature=>@signature) end else raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" end when Time raise ArgumentError, "Date and Time objects represent fixed points in time and cannot be subtracted from to a Unit, which can only represent time spans" else x,y = coerce(other) y-x end end
[ "def -(other)\n if (other.is_a?(Numeric))\n Quantity.new(@value - other, @unit)\n elsif(other.is_a?(Quantity) && @unit.dimension == other.unit.dimension)\n Quantity.new({:unit => @unit,:reference_value => @reference_value - other.reference_value})\n else\n raise ArgumentError, \"Cannot subtract #{other} from #{self}\"\n end\n end", "def _sub # sub a b -> (result)\r\n a, b = @operands\r\n var = read_byte\r\n\r\n store var, (sint16 a) - (sint16 b)\r\n end", "def -(other)\n if self.class == Double || [Double, ::Float].include?(other.class)\n RDF::Literal::Double.new(to_f - other.to_f)\n elsif ((self.class == RDF::Literal::Float || other.class == RDF::Literal::Float) rescue false)\n RDF::Literal::Float.new(to_f - other.to_f)\n elsif self.class == Decimal || other.class == Decimal\n RDF::Literal::Decimal.new(to_d - (other.respond_to?(:to_d) ? other.to_d : BigDecimal(other.to_s)))\n else\n RDF::Literal::Integer.new(to_i - other.to_i)\n end\n end", "def subtract!(other)\n if other.is_a?(Numeric)\n @data.each_index do |i|\n @data[i] -= other\n end\n elsif other.is_a?(Signal)\n raise ArgumentError, \"other.data.size #{other.size} is not equal to data.size #{@data.size}\" if other.data.size != @data.size\n @data.each_index do |i|\n @data[i] -= other.data[i]\n end\n elsif other.is_a?(Array)\n raise ArgumentError, \"other.size #{other.size} is not equal to data.size #{@data.size}\" if other.size != @data.size\n @data.each_index do |i|\n @data[i] -= other[i]\n end\n else\n raise ArgumentError, \"other is not a Numeric, Signal, or Array\"\n end\n return self\n end", "def subtract!(rhs)\n subtract rhs, self\n end", "def -(other)\n if ::Duration === other\n\t \n ::Duration.new(value - other.value, @parts +( other.parts.dup.map! { |k,v| [k,-v] } ))\n else\n\t if ::Time === other\n\t\t # minus operator is not canonical\n\t else\n ::Duration.new(value - other, @parts + [[:seconds, -other]])\n\t\tend\n end\n end", "def -(other)\n memory_size_operation(other) do |self_bytes, other_bytes|\n self_bytes - other_bytes\n end\n end", "def subtract(n1, n2); n1 - n2 end", "def subtract(a,b)\n a - b\n end", "def -(other)\n raise TypeError unless other.is_a?(Money)\n if self.base_currency == other.base_currency\n Money.new(amount - other.amount, base_currency)\n else\n Money.new(amount - other.convert_to(self.base_currency).amount, base_currency)\n end\n end", "def add_or_subtract!(operator,other)\n if other.is_a? Quantity\n other = other.to(@unit) if other.unit.is_alternative_for?(@unit)\n\n if @unit.is_equivalent_to? other.unit\n @value = @value.send operator, other.value\n\n return self\n else\n raise Quantify::Exceptions::InvalidObjectError, \"Cannot add or subtract Quantities with different dimensions\"\n end\n else\n raise Quantify::Exceptions::InvalidObjectError, \"Cannot add or subtract non-Quantity objects\"\n end\n end", "def -@\n quantity.relative.magnitude( -amount )\n end", "def subtract\n match('-')\n term # Result, b, is in eax.\n asm.pop(EBX)\n asm.neg(EAX) # Fake the subtraction. a - b == a + -b\n asm.add(EAX, EBX) # Add a(ebx) to -b(eax).\n end", "def - other\n to_magnitude - other\n end", "def Subtract(val)\n self.value -= val\n end", "def -(other)\n other.is_a?(Vips::Image) ? \n subtract(other) : linear(1, smap(other) {|x| x * -1})\n end", "def -(other)\n raise TypeError unless other.is_a?(Money)\n other = other.exchange_to(currency)\n build_new(to_d - other.to_d, currency)\n end", "def subtract(t1,t2) ##revisar name\n\t\treturn (t1-t2).to_i\n\tend", "def -(other)\n case other\n when Instant then Duration.new(@ns - other.ns)\n when Duration then Instant.new(@ns - other.to_nanos)\n else raise TypeError, 'Not an Instant or Duration'\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the nth root of a unit, where n = (1..9) if n < 0, returns 1/unit^(1/n)
def root(n) raise ArgumentError, "Cannot take the root of a temperature" if self.is_temperature? raise ArgumentError, "Exponent must an Integer" unless n.kind_of?(Integer) raise ArgumentError, "0th root undefined" if n.zero? return self if n == 1 return self.root(n.abs).inverse if n < 0 vec = self.unit_signature_vector vec=vec.map {|x| x % n} raise ArgumentError, "Illegal root" unless vec.max == 0 num = @numerator.dup den = @denominator.dup for item in @numerator.uniq do x = num.find_all {|i| i==item}.size r = ((x/n)*(n-1)).to_int r.times {|y| num.delete_at(num.index(item))} end for item in @denominator.uniq do x = den.find_all {|i| i==item}.size r = ((x/n)*(n-1)).to_int r.times {|y| den.delete_at(den.index(item))} end q = @scalar < 0 ? (-1)**Rational(1,n) * (@scalar.abs)**Rational(1,n) : @scalar**Rational(1,n) Unit.new(:scalar=>q,:numerator=>num,:denominator=>den) end
[ "def root(x, n) x**(1.0/n) end", "def root(n = 2)\n return (self ** (1.0 / n))\n end", "def calculate_root(number, nth_root)\n case nth_root.to_f\n when 2.0 then Math.sqrt number\n when 3.0 then Math.cbrt number\n else\n root = number**(1 / nth_root.to_f)\n return root.round if root.round**nth_root == number\n root\n end\n end", "def primitive_root(n)\n t = Utils.totient(n)\n ps = PrimeFactorization.prime_factorization(t).to_a\n 2.upto(t) do |a|\n found = true\n ps.each do |q,|\n if mod_pow(a, t / q, n) == 1\n found = false\n break\n end\n end\n return a if found\n end\n nil\n end", "def digital_root(n)\n n < 10 ? n : digital_root(n / 10 + n % 10)\nend", "def rek(n)\n if n == 1\n return 1/3.to_f\n end\n if n == 0\n return 1.to_f\n end\n return 13.0*rek(n-1)/3.0 - 4.0*rek(n-2)/3.0\nend", "def nth_root(number, n, tolerance = 0.001)\n low = 0\n high = number\n loop do\n midpoint = (low + high) / 2.0\n error = midpoint**n - number\n return midpoint if error.abs < tolerance\n if error > 0\n high = midpoint\n else\n low = midpoint\n end\n end\nend", "def cube_root(n)\n # n is less than 1,000,000\n digits = {0=>0, 1=>1, 2=>8, 3=>7, 4=>4, 5=>5, 6=>6, 7=>3, 8=>2, 9=>9}\n digit = digits[n % 10]\n\n (0..9).to_a.each do |t|\n tens = (t * 10)**3\n if n > tens\n next\n elsif n < tens\n return (t - 1) * 10 + digit\n end\n end\n 90 + digit\nend", "def s(n)\n ((9*n-1)*(10**n)+1)/9\nend", "def iroot(n, pow, return_power = false)\r\n\t\t# get integer e s.t. (2 ** (e - 1)) ** pow <= n < (2 ** e) ** pow\r\n\t\te = ilog2(n) / pow + 1\t\t# == Rational(ilog2(n) + 1, pow).ceil\r\n\r\n\t\tx = 1 << e\t\t\t\t\t# == 2 ** e\r\n\t\tz = nil\r\n\t\tq = n >> (e * (pow - 1))\t# == n / (x ** (pow - 1))\r\n\r\n\t\tloop do\r\n\t\t\t# Newtonian step\r\n\t\t\tx += (q - x) / pow\r\n\t\t\tz = x ** (pow - 1)\r\n\t\t\tq = n / z\r\n\r\n\t\t\tbreak if x <= q\r\n\t\tend\r\n\r\n\t\treturn x, x * z if return_power\r\n\t\treturn x\r\n\tend", "def sqrt_iter(n)\n 1 + (0...n).inject(Rational(0)) { |frac,n|\n next_sqrt_iter(frac) # don't need n value\n }\nend", "def potenz(x, n)\n check_pre((n.nat?))\n if (n == 1) then\n x\n elsif (n == 0) then\n 1\n else \n x*=potenz((x), n-1)\n end\n end", "def roots(a,b,c)\n desc = (b**2) - (4.0 * a * c)\n if (desc >= 0 )\n x1 = (-b + Math.sqrt(desc))/(2.0*a)\n x2 = (-b - Math.sqrt(desc))/(2.0*a)\n return (x1 + x2).to_f.round(2) \n else\n return nil\n end\nend", "def cube_root(n)\n table = {}\n (1..99).to_a.each { |num| table[(num * num * num)] = num }\n table[n] ? table[n] : 'invalid input - must be less than 7 digits longs'\nend", "def square_root(k)\n root = k / 2\n square = root * root\n\n while square >= k\n root /= 2\n square = root * root\n end\n\n while square < k\n temp_root = root + 1\n\n if (temp_root * temp_root) > k\n break\n end\n\n root = temp_root\n end\n\n root\nend", "def square_root_of(number)\n\tMath.sqrt(number)\nend", "def newton_rbsqrt(n)\n return nil if n < 0\n return n if n < 2\n b = n.bit_length\n x = 1 << (b-1)/2 | n >> (b/2 + 1)\n while (t = n / x) < x; x = ((x + t) >> 1) end\n x\nend", "def digital_root(n)\r\n digits = n.digits\r\n \r\n counter = digits.length\r\n\r\nuntil counter.size == 1\r\np sum = digits.sum\r\np sum.digits.sum\r\np counter -= 1\r\n end \r\n\r\nend", "def cube_root(x, iterations: 20, guess: 2 ** (Math.log2(x).round / 3))\n root = guess\n iterations.times do\n root = ((x / (root ** 2)) + (2 * root)) / 3\n return root if (root ** 3) == x\n end\n root\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns inverse of Unit (1/unit)
def inverse Unit("1") / self end
[ "def unit \n\t\t\tunitq = self.dup\n\t\t\tmagnitude = self.abs\n\t\t\tunitq[0] /= magnitude\n\t\t\tunitq[1] /= magnitude\n\t\t\tunitq[2] /= magnitude\n\t\t\tunitq[3] /= magnitude\n\t\t\treturn unitq\n\t\tend", "def unit\n (@p1 - @p0).normalize\n end", "def unit_(v_)\n (self - v_).normalize\n end", "def inverse\n result = UnitQuaternion.new\n result.set(@beta0, *(-1*@beta_s))\n return result\n end", "def inverse\n inverse_powers = {}\n powers.each{ |u,p| inverse_powers[u] = -p }\n PhysicalQuantity.new(1.0/@quantity, inverse_powers)\n end", "def unit\n\t\tm = magnitude().to_f\n\t\t@unit or @unit = Ftor.new(@x/m, @y/m)\n\tend", "def reciprocalize\n Unit.unity / self\n end", "def inverse\r\n quaternion.inverse!\r\n end", "def invert\n nt = []\n table.each do |u|\n case u\n when Numeric\n nt << (1.0 / u) # TODO: this right?\n else #Unit\n nt << u.invert\n end\n end\n Measure.new(nt)\n end", "def inv\n Fraction.new(@denom, @numer)\n end", "def inverse()\n map_hash{|k,v|[k,1/v] if v > 0}.to_p\n end", "def unit_in_the_last_place\n if finite?\n if abs < DBL_MINIMUM\n DBL_ULPDENORMAL\n else\n f = exponent_binary_string.to_i(2) - 52\n Float.compile(1, f < 0 ? 1 : f, 0)\n end\n else\n self # nan or infinity\n end\n end", "def inverse_rate\n 1.0 / rate\n end", "def si_unit\n return Unit.steridian if describe == 'solid angle'\n return Unit.radian if describe == 'plane angle'\n\n val = si_base_units\n return nil unless val\n return val[0] if val.length == 1\n val = val.inject(Unit.unity) do |compound,unit|\n compound * unit\n end\n val = val.or_equivalent unless val.acts_as_equivalent_unit\n end", "def unit_normal\n v = Vector[@a, @b, @c]\n v*(1/v.r)\n end", "def inverse\n if @height == 2 and @width == 2\n det = (get(0, 0) * get(1, 1)) - (get(0, 1) * get(1, 0).to_f)\n inv = SparseMatrix.new([[get(1, 1)*(1/det), -get(0, 1)*(1/det)], [-get(1, 0)*(1/det), get(0, 0)*(1/det)]])\n return inv\n end\n \n if !(self.square?)\n raise ArgumentError, \"The object must be square to be invertible.\"\n end\n\n det_value = determinant()\n if (det_value == 0)\n raise ArgumentError, \"The determinant can't be 0.\"\n end\n\n adj_matrix = adjugate()\n\n return adj_matrix.scalar_multiply(1.0 / det_value)\n end", "def unit_price_without_tax\n unit_price - tax_amount\n end", "def inverse!\n inverse self\n end", "def inversed_sum\n 1.0 / sum\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts the unit back to a float if it is unitless. Otherwise raises an exception
def to_f return @scalar.to_f if self.unitless? raise RuntimeError, "Cannot convert '#{self.to_s}' to Float unless unitless. Use Unit#scalar" end
[ "def normalize_as_float!\n (replace('') ; return nil) if blank?\n rval = to_f_or_nil\n replace(rval.to_s) unless rval.nil?\n rval\n end", "def to_f_or_nil\n return nil if blank?\n begin\n Float(self)\n rescue ArgumentError\n nil\n end ; end", "def fahrenheit? = unit == 'fahrenheit'", "def proper_fraction_to_float(proper_fraction)\n float = proper_fraction.split('/').first.to_f/proper_fraction.split('/').last.to_f\n end", "def parse_float(the_input)\n output = 0\n begin\n output = the_input.to_f\n rescue => detail\n nil\n end\n output\n end", "def convert_inches_to_feet( inches )\r\n inches.valid_float? ? (inches.to_f/12.0) : 0.0\r\nend", "def convert_to_unit(value)\n if value.is_a?(Numeric)\n EnergyUnit.new(value, ORIGINAL_UNIT).to_unit(unit)\n else\n puts \"WARNING: Discarding non-numeric #{ value.inspect }\"\n 0.0\n end\n end", "def float(key, default=0.0)\n\t\tstr = self.fetch(key.downcase, nil)\n\t\tif not str.nil?\n\t\t\treturn str.to_f\n\t\tend\n\t\treturn default\n\tend", "def get_f str\n return nil unless has_num(str)\n myfloat = str.strip.match(/(\\d+,)?\\d+(\\.\\d+)?/).to_s.gsub(/,/,'').to_f\n return nil if myfloat == 0 \n return myfloat\n end", "def get_float(node)\n node.content.squish.gsub(/[^\\d\\.]+/, '').to_f if node.present? && node.content.present?\n end", "def convert_float( text_value )\r\n (!text_value.empty?) ? text_value.to_f : 0.0\r\nend", "def to_float_or_int(v)\n v.match('\\.').nil? ? Integer(v) : Float(v)\n end", "def numeric string\n Float(string) rescue nil\nend", "def float_or_nil(str)\n return nil if IGNORE_LIST.include?(str)\n return nil if str == -1\n Float(str || '')\n rescue ArgumentError\n nil\n end", "def duration_to_f (s)\n return s if s.kind_of? Float\n return OpenWFE::parse_time_string(s) if s.kind_of? String\n return Float(s.to_s)\n end", "def Float(p0) end", "def is_unit?(unit)\n if unit\n denominator_units.size == 0 && numerator_units.size == 1 && numerator_units.first == unit\n else\n unitless?\n end\n end", "def coerce(value)\n enum? ? value.to_s : Float(value)\n rescue ArgumentError\n nil\n end", "def float_or_nil(); FLOAT_OR_NIL; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts the unit back to a complex if it is unitless. Otherwise raises an exception
def to_c return Complex(@scalar) if self.unitless? raise RuntimeError, "Cannot convert '#{self.to_s}' to Complex unless unitless. Use Unit#scalar" end
[ "def simplify\n mul, new_unit = *@unit.simplify\n if new_unit.unitless?\n @value * mul\n else\n Units::Value.new(@value * mul, new_unit)\n end\n end", "def convert_units(obj, un)\n begin\n obj.convert_units(un) # for GPhys etc\n rescue\n obj.convert2(un) # for UNumeric etc\n end\n end", "def is_unit?(unit)\n if unit\n denominator_units.size == 0 && numerator_units.size == 1 && numerator_units.first == unit\n else\n unitless?\n end\n end", "def unit \n\t\t\tunitq = self.dup\n\t\t\tmagnitude = self.abs\n\t\t\tunitq[0] /= magnitude\n\t\t\tunitq[1] /= magnitude\n\t\t\tunitq[2] /= magnitude\n\t\t\tunitq[3] /= magnitude\n\t\t\treturn unitq\n\t\tend", "def cubic_mile? = unit == 'cubic-mile'", "def si_unit\n return Unit.steridian if describe == 'solid angle'\n return Unit.radian if describe == 'plane angle'\n\n val = si_base_units\n return nil unless val\n return val[0] if val.length == 1\n val = val.inject(Unit.unity) do |compound,unit|\n compound * unit\n end\n val = val.or_equivalent unless val.acts_as_equivalent_unit\n end", "def test_complex\r\n # simple i, 1 or more digits\r\n assert_equal(0, RegexPractice.get_complex(\"4i\"))\r\n assert_equal(0, RegexPractice.get_complex(\"43i\"))\r\n # simple i, 1 or more digits with sign \r\n assert_equal(0, RegexPractice.get_complex(\"-46i\"))\r\n assert_equal(0, RegexPractice.get_complex(\"+46i\"))\r\n # simple real +/- imaginary\r\n assert_equal(0, RegexPractice.get_complex(\"35+46i\"))\r\n assert_equal(0, RegexPractice.get_complex(\"3-46i\"))\r\n # signed real and signed imaginary\r\n assert_equal(5, RegexPractice.get_complex(\"num: -35+46i\"))\r\n assert_equal(0, RegexPractice.get_complex(\"+3-46i\"))\r\n # a couple non-complex\r\n assert_equal(nil, RegexPractice.get_complex(\"abi\"))\r\n assert_equal(nil, RegexPractice.get_complex(\"65\")) \r\n end", "def test_Complex_InstanceMethods_to_r\n\t\tassert_equal(Rational('5/2'), Complex(2.5, 0).to_r)\n\tend", "def simplify(compound_unit)\n return [] if compound_unit.nil?\n\n simplified_unit = []\n\n compound_unit = compound_unit.compact.sort_by!(&:unit)\n\n compound_unit.each do |u|\n last = simplified_unit.last\n if !last.nil? && last.unit == u.unit\n last.exponent += u.exponent\n else\n simplified_unit << u.dup\n end\n end\n\n simplified_unit.map! do |u|\n u.exponent == 0 ? nil : u\n end.compact!\n\n return simplified_unit\n end", "def test_Complex_InstanceMethods_to_f\n\t\tassert_equal(2.0, Complex(2, 0).to_f)\n\tend", "def to_f\n return @scalar.to_f if self.unitless?\n raise RuntimeError, \"Cannot convert '#{self.to_s}' to Float unless unitless. Use Unit#scalar\"\n end", "def unit\n\t\tm = magnitude().to_f\n\t\t@unit or @unit = Ftor.new(@x/m, @y/m)\n\tend", "def test_double_complex\n (1..10000).each do |i|\n assert_equal(i, Romanizer.to_arabic_complex(Romanizer.to_roman_complex(i)));\n end\n end", "def test_Complex_InstanceMethods_numerator\n\t\tc = Complex('2/3+3/4i')\n\t\tassert_equal(Complex('8+9i'), c.numerator)\n\t\tassert_equal(12, c.denominator)\n\tend", "def parse(passed_unit_string=\"0\")\n unit_string = passed_unit_string.dup\n if unit_string =~ /\\$\\s*(#{NUMBER_REGEX})/\n unit_string = \"#{$1} USD\"\n end\n unit_string.gsub!(/%/,'percent')\n unit_string.gsub!(/'/,'feet')\n unit_string.gsub!(/\"/,'inch')\n unit_string.gsub!(/#/,'pound')\n \n #:nocov:\n if defined?(Uncertain) && unit_string =~ /(\\+\\/-|&plusmn;)/\n value, uncertainty, unit_s = unit_string.scan(UNCERTAIN_REGEX)[0]\n result = unit_s.unit * Uncertain.new(value.to_f,uncertainty.to_f)\n copy(result)\n return \n end\n #:nocov:\n \n if defined?(Complex) && unit_string =~ COMPLEX_NUMBER\n real, imaginary, unit_s = unit_string.scan(COMPLEX_REGEX)[0]\n result = Unit(unit_s || '1') * Complex(real.to_f,imaginary.to_f)\n copy(result)\n return \n end\n \n if defined?(Rational) && unit_string =~ RATIONAL_NUMBER\n numerator, denominator, unit_s = unit_string.scan(RATIONAL_REGEX)[0]\n result = Unit(unit_s || '1') * Rational(numerator.to_i,denominator.to_i)\n copy(result)\n return \n end\n \n unit_string =~ NUMBER_REGEX\n unit = @@cached_units[$2] \n mult = ($1.empty? ? 1.0 : $1.to_f) rescue 1.0\n mult = mult.to_int if (mult.to_int == mult)\n if unit\n copy(unit)\n @scalar *= mult\n @base_scalar *= mult\n return self\n end\n unit_string.gsub!(/<(#{@@UNIT_REGEX})><(#{@@UNIT_REGEX})>/, '\\1*\\2')\n unit_string.gsub!(/[<>]/,\"\")\n \n if unit_string =~ /:/\n hours, minutes, seconds, microseconds = unit_string.scan(TIME_REGEX)[0]\n raise ArgumentError, \"Invalid Duration\" if [hours, minutes, seconds, microseconds].all? {|x| x.nil?}\n result = \"#{hours || 0} h\".unit + \n \"#{minutes || 0} minutes\".unit + \n \"#{seconds || 0} seconds\".unit +\n \"#{microseconds || 0} usec\".unit\n copy(result)\n return\n end\n \n \n # Special processing for unusual unit strings\n # feet -- 6'5\"\n feet, inches = unit_string.scan(FEET_INCH_REGEX)[0]\n if (feet && inches)\n result = Unit.new(\"#{feet} ft\") + Unit.new(\"#{inches} inches\")\n copy(result)\n return \n end\n\n # weight -- 8 lbs 12 oz \n pounds, oz = unit_string.scan(LBS_OZ_REGEX)[0]\n if (pounds && oz)\n result = Unit.new(\"#{pounds} lbs\") + Unit.new(\"#{oz} oz\")\n copy(result)\n return \n end\n \n raise( ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string.count('/') > 1\n raise( ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string.scan(/\\s[02-9]/).size > 0\n @scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts\n top.scan(TOP_REGEX).each do |item|\n n = item[1].to_i\n x = \"#{item[0]} \"\n case \n when n>=0\n top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/) {|s| x * n}\n when n<0\n bottom = \"#{bottom} #{x * -n}\"; top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/,\"\")\n end\n end \n bottom.gsub!(BOTTOM_REGEX) {|s| \"#{$1} \" * $2.to_i} if bottom\n @scalar = @scalar.to_f unless @scalar.nil? || @scalar.empty?\n @scalar = 1 unless @scalar.kind_of? Numeric \n @scalar = @scalar.to_int if (@scalar.to_int == @scalar)\n \n @numerator ||= UNITY_ARRAY\n @denominator ||= UNITY_ARRAY\n @numerator = top.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if top\n @denominator = bottom.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if bottom\n \n \n us = \"#{(top || '' + bottom || '')}\".to_s.gsub(@@UNIT_MATCH_REGEX,'').gsub(/[\\d\\*, \"'_^\\/\\$]/,'')\n raise( ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") unless us.empty?\n\n @numerator = @numerator.map do |item|\n @@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]\n end.flatten.compact.delete_if {|x| x.empty?}\n\n @denominator = @denominator.map do |item|\n @@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]\n end.flatten.compact.delete_if {|x| x.empty?}\n\n @numerator = UNITY_ARRAY if @numerator.empty? \n @denominator = UNITY_ARRAY if @denominator.empty?\n self\n end", "def convert_to_equivalent_unit!(new_unit)\n old_unit = @unit\n self.multiply!(Unit.ratio new_unit, old_unit)\n old_base_units = old_unit.base_units.map { |base| base.unit } if old_unit.is_compound_unit?\n self.cancel_base_units!(*old_base_units || [old_unit])\n end", "def real\n complexget :real\n end", "def converted_value(other_unit)\n if other_unit.special?\n other_unit.magnitude scalar\n else\n scalar / other_unit.scalar\n end\n end", "def subunit_to_unit; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if unitless, returns a Rational, otherwise raises an error
def to_r return @scalar.to_r if self.unitless? raise RuntimeError, "Cannot convert '#{self.to_s}' to Rational unless unitless. Use Unit#scalar" end
[ "def rational\n Rational(integer, integer(0..INTMAX))\n end", "def test_Rational_InstanceMethods_rationalize\n\t\tassert_equal(Rational(\"884279719003555/281474976710656\").to_r, Math::PI.to_r)\n\t\t# TODO, Need add some testcases.\n\t\t# r.rationalize #=>(884279719003555/281474976710656)\n\t\t# r.rationalize(0.01)#=>(22/7)\n\tend", "def test_to_rational\r\n assert_equal(Rational(13,10), (1.3).to_foorth_r)\r\n end", "def to_r\n Rational(self, 1)\n end", "def test_rational_coerce\n assert_respond_to(@rat1, :coerce)\n assert_nothing_raised{ @rat1.coerce(9) }\n assert_nothing_raised{ @rat1.coerce(0.5) }\n #assert_equal(Rational(9,1), @rat1.coerce(9))\n end", "def test_NilClass_InstanceMethod_to_r\n\t\tassert_equal(Rational(0,1), nil.to_r)\n\tend", "def test_to_rational\r\n rat = '1/2'.to_r\r\n assert_equal(rat.to_foorth_r, rat)\r\n end", "def rationalize(eps = nil)\n eps ? Q.new(to_r.rationalize(eps)) : self\n end", "def rationalize(eps = nil)\n eps ? base_amount.rationalize(eps) : base_amount.rationalize\n end", "def rationalize(x, tol = nil)\n x.rationalize(tol)\n end", "def rationalize(*eps)\n #This is a stub, used for indexing\n end", "def to_r\n return Rational(numerator,denominator)\n end", "def RationalLiteral(value); end", "def test_rational_inspect\n assert_respond_to(@rat1, :inspect)\n assert_equal(\"Rational(3, 4)\", @rat1.inspect)\n assert_equal(\"Rational(0, 1)\", @rat4.inspect) # Reduced\n assert_equal(\"Rational(9, 1)\", @rat5.inspect)\n end", "def stringToRational\n return $str1.to_r\nend", "def on_rational(value)\n RationalLiteral.new(\n value: value,\n location:\n Location.token(\n line: lineno,\n char: char_pos,\n column: current_column,\n size: value.size\n )\n )\n end", "def to_r\n Rational(@val, @div)\n end", "def test_rational_to_s\n assert_respond_to(@rat1, :to_s)\n assert_nothing_raised{ @rat1.to_s }\n assert_kind_of(String, @rat1.to_s)\n assert_equal(\"3/4\", @rat1.to_s)\n assert_equal(\"3/4\", @rat7.to_s)\n end", "def test_Rational_InstanceMethods_Comparison\n\t\tassert_equal(0, Rational(\"4/2\") <=> Rational(\"98/49\"))\n\t\tassert_equal(-1, Rational(\"3/4\") <=> 41)\n\t\tassert_equal(0, Rational(\"0\") <=> 0.0)\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
true if scalar is zero
def zero? return self.base_scalar.zero? end
[ "def zero?\n base_scalar.zero?\n end", "def nonzero?() end", "def zero?\n @value.zero?\n end", "def nonzero?\n self\n end", "def zero_vector?\n (@x.eql?(0) && @y.eql?(0) && @z.eql?(0)).eql?(true) ? true : false\n end", "def zero?\n to_f.zero?\n end", "def zero?\n self.map{ |x| return false if x != 0 }\n true\n end", "def zero?\r\n return true if @x == 0 and @y ==0\r\n return false\r\n end", "def zero?\n x.zero? && y.zero? \n end", "def nonzero?\n to_nanos.nonzero?\n end", "def zero?\n @stats.values.map(&:values).flatten.sum.zero?\n end", "def scalar?\n @netcdf_elmt.isScalar()\n end", "def non_zero?(value)\n value != 0\n end", "def zero?\n return ! @content.any? {|b| b != 0 }\n end", "def positive?\n self > ZERO\n end", "def isZeroVector?\n\t\t\treturn @elements.find_all {|i| i.zero?}.length == 0\n\t\tend", "def zero?\n\t\t\t@amount.zero?\n\t\tend", "def scalar?\n true\n end", "def zero?\n to_nanos.zero?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculates the unit signature id for use in comparing compatible units and simplification the signature is based on a simple classification of units and is based on the following publication Novak, G.S., Jr. "Conversion of units of measurement", IEEE Transactions on Software Engineering, 21(8), Aug 1995, pp.651661 doi://10.1109/32.403789
def unit_signature return @signature unless @signature.nil? vector = unit_signature_vector vector.each_with_index {|item,index| vector[index] = item * 20**index} @signature=vector.inject(0) {|sum,n| sum+n} end
[ "def unit_signature\n return @signature unless @signature.nil?\n\n vector = unit_signature_vector\n vector.each_with_index { |item, index| vector[index] = item * (20**index) }\n @signature = vector.inject(0) { |acc, elem| acc + elem }\n @signature\n end", "def id\n unitid.to_i\n end", "def signed_tid; end", "def signed_oid; end", "def subunit_to_unit; end", "def make_analysis_id; UUID.new.generate :compact ; end", "def polish_taxpayer_identification_number; end", "def purchase_unit_factor\n return 1 if unit_id == inventory_unit_id\n return 1 / (pack_size || 1) if inventory_unit_id == pack_unit_id\n return 1 / (pack_size || 1) / (subpack_size || 1) if inventory_unit_id == subpack_unit_id\n 1\n end", "def mnemo_id\n\n Rufus::Mnemo.from_i(h.subid[0, 9].to_i(16))\n end", "def calculate_nus_matric_number(id)\n matric_regex = /^A\\d{7}|U\\d{6,7}/\n matches = matric_regex.match(id.upcase)\n\n if (matches)\n match = matches[0]\n\n if (match[0].eql?('U') && match.length === 8)\n match = match[0, 3] + match[4]\n end\n\n weights = {\n U: [0, 1, 3, 1, 2, 7],\n A: [1, 1, 1, 1, 1, 1]\n }\n\n weights = weights[:\"#{match[0]}\"]\n\n sum = 0\n digits = match[2, 7]\n\n for i in 0..6 do\n sum += weights[i].to_i * digits[i].to_i\n end\n\n match.to_s + 'YXWURNMLJHEAB' [sum % 13]\n end\nend", "def price_unit_factor\n return 1 if unit_id == price_unit_id\n return pack_size || 1 if price_unit_id == pack_unit_id\n return (pack_size || 1) * (subpack_size || 1) if price_unit_id == subpack_unit_id\n return 1\n end", "def convertSecToSimUnits(sec)\n (sec * SimUnitsPerSec).to_i ;\n end", "def signature\n \"#{round}#{result}#{opponent_id}\"\n end", "def get_si_counter_part\n @si_counter_part = si_unit_to_hash\n end", "def magnification\n 1300\n end", "def signature_algorithm(*) end", "def unit_s\n self.unit.to_s if self.unit\n end", "def GetUnitId(unit)\n cmd = Builtins.sformat(\"%1 --no-pager -p Id show %2\", @invoker, unit)\n ret = Convert.convert(\n SCR.Execute(path(\".target.bash_output\"), cmd, { \"TERM\" => \"raw\" }),\n :from => \"any\",\n :to => \"map <string, any>\"\n )\n if Ops.get_integer(ret, \"exit\", -1) != 0\n Builtins.y2error(\n _(\"Unable to query '%1' unit Id\\nCommand returned: %2\\n\"),\n unit,\n ret\n )\n return nil\n end\n\n # extract first line\n _end = Builtins.findfirstof(Ops.get_string(ret, \"stdout\", \"\"), \" \\n\")\n out = Builtins.substring(\n Ops.get_string(ret, \"stdout\", \"\"),\n 0,\n _end != nil ? _end : 0\n )\n\n # extract key anv value\n tmp = Builtins.splitstring(out, \"=\")\n if Builtins.size(tmp) != 2 || Ops.get_string(tmp, 0, \"\") != \"Id\" ||\n Ops.get_string(tmp, 1, \"\") == \"\"\n Builtins.y2error(\n _(\"Unable to parse '%1' unit Id query output: '%2'\\n\"),\n unit,\n out\n )\n return nil\n end\n\n Ops.get_string(tmp, 1, \"\")\n end", "def signed_oid=(_arg0); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a string into a unit object. Typical formats like : "5.6 kgm/s^2" "5.6 kgms^2" "5.6 kilogrammetersecond^2" "2.2 kPa" "37 degC" "1" creates a unitless constant with value 1 "GPa" creates a unit with scalar 1 with units 'GPa' 6'4" recognized as 6 feet + 4 inches 8 lbs 8 oz recognized as 8 lbs + 8 ounces
def parse(passed_unit_string="0") unit_string = passed_unit_string.dup if unit_string =~ /\$\s*(#{NUMBER_REGEX})/ unit_string = "#{$1} USD" end unit_string.gsub!(/%/,'percent') unit_string.gsub!(/'/,'feet') unit_string.gsub!(/"/,'inch') unit_string.gsub!(/#/,'pound') #:nocov: if defined?(Uncertain) && unit_string =~ /(\+\/-|&plusmn;)/ value, uncertainty, unit_s = unit_string.scan(UNCERTAIN_REGEX)[0] result = unit_s.unit * Uncertain.new(value.to_f,uncertainty.to_f) copy(result) return end #:nocov: if defined?(Complex) && unit_string =~ COMPLEX_NUMBER real, imaginary, unit_s = unit_string.scan(COMPLEX_REGEX)[0] result = Unit(unit_s || '1') * Complex(real.to_f,imaginary.to_f) copy(result) return end if defined?(Rational) && unit_string =~ RATIONAL_NUMBER numerator, denominator, unit_s = unit_string.scan(RATIONAL_REGEX)[0] result = Unit(unit_s || '1') * Rational(numerator.to_i,denominator.to_i) copy(result) return end unit_string =~ NUMBER_REGEX unit = @@cached_units[$2] mult = ($1.empty? ? 1.0 : $1.to_f) rescue 1.0 mult = mult.to_int if (mult.to_int == mult) if unit copy(unit) @scalar *= mult @base_scalar *= mult return self end unit_string.gsub!(/<(#{@@UNIT_REGEX})><(#{@@UNIT_REGEX})>/, '\1*\2') unit_string.gsub!(/[<>]/,"") if unit_string =~ /:/ hours, minutes, seconds, microseconds = unit_string.scan(TIME_REGEX)[0] raise ArgumentError, "Invalid Duration" if [hours, minutes, seconds, microseconds].all? {|x| x.nil?} result = "#{hours || 0} h".unit + "#{minutes || 0} minutes".unit + "#{seconds || 0} seconds".unit + "#{microseconds || 0} usec".unit copy(result) return end # Special processing for unusual unit strings # feet -- 6'5" feet, inches = unit_string.scan(FEET_INCH_REGEX)[0] if (feet && inches) result = Unit.new("#{feet} ft") + Unit.new("#{inches} inches") copy(result) return end # weight -- 8 lbs 12 oz pounds, oz = unit_string.scan(LBS_OZ_REGEX)[0] if (pounds && oz) result = Unit.new("#{pounds} lbs") + Unit.new("#{oz} oz") copy(result) return end raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.count('/') > 1 raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.scan(/\s[02-9]/).size > 0 @scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts top.scan(TOP_REGEX).each do |item| n = item[1].to_i x = "#{item[0]} " case when n>=0 top.gsub!(/#{item[0]}(\^|\*\*)#{n}/) {|s| x * n} when n<0 bottom = "#{bottom} #{x * -n}"; top.gsub!(/#{item[0]}(\^|\*\*)#{n}/,"") end end bottom.gsub!(BOTTOM_REGEX) {|s| "#{$1} " * $2.to_i} if bottom @scalar = @scalar.to_f unless @scalar.nil? || @scalar.empty? @scalar = 1 unless @scalar.kind_of? Numeric @scalar = @scalar.to_int if (@scalar.to_int == @scalar) @numerator ||= UNITY_ARRAY @denominator ||= UNITY_ARRAY @numerator = top.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if top @denominator = bottom.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if bottom us = "#{(top || '' + bottom || '')}".to_s.gsub(@@UNIT_MATCH_REGEX,'').gsub(/[\d\*, "'_^\/\$]/,'') raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") unless us.empty? @numerator = @numerator.map do |item| @@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]] end.flatten.compact.delete_if {|x| x.empty?} @denominator = @denominator.map do |item| @@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]] end.flatten.compact.delete_if {|x| x.empty?} @numerator = UNITY_ARRAY if @numerator.empty? @denominator = UNITY_ARRAY if @denominator.empty? self end
[ "def parse(passed_unit_string = '0')\n unit_string = passed_unit_string.dup\n unit_string = \"#{Regexp.last_match(1)} USD\" if unit_string =~ /\\$\\s*(#{NUMBER_REGEX})/\n unit_string.gsub!(\"\\u00b0\".force_encoding('utf-8'), 'deg') if unit_string.encoding == Encoding::UTF_8\n\n unit_string.gsub!(/[%'\"#]/, '%' => 'percent', \"'\" => 'feet', '\"' => 'inch', '#' => 'pound')\n\n if defined?(Complex) && unit_string =~ COMPLEX_NUMBER\n real, imaginary, unit_s = unit_string.scan(COMPLEX_REGEX)[0]\n result = self.class.new(unit_s || '1') * Complex(real.to_f, imaginary.to_f)\n copy(result)\n return\n end\n\n if defined?(Rational) && unit_string =~ RATIONAL_NUMBER\n sign, proper, numerator, denominator, unit_s = unit_string.scan(RATIONAL_REGEX)[0]\n sign = sign == '-' ? -1 : 1\n rational = sign * (proper.to_i + Rational(numerator.to_i, denominator.to_i))\n result = self.class.new(unit_s || '1') * rational\n copy(result)\n return\n end\n\n unit_string =~ NUMBER_REGEX\n unit = self.class.cached.get(Regexp.last_match(2))\n mult = Regexp.last_match(1).nil? ? 1.0 : Regexp.last_match(1).to_f\n mult = mult.to_int if mult.to_int == mult\n\n if unit\n copy(unit)\n @scalar *= mult\n @base_scalar *= mult\n return self\n end\n\n while unit_string.gsub!(/(<#{self.class.unit_regex})><(#{self.class.unit_regex}>)/, '\\1*\\2')\n # collapse <x><y><z> into <x*y*z>...\n end\n # ... and then strip the remaining brackets for x*y*z\n unit_string.gsub!(/[<>]/, '')\n\n if unit_string =~ TIME_REGEX\n hours, minutes, seconds, microseconds = unit_string.scan(TIME_REGEX)[0]\n raise ArgumentError, 'Invalid Duration' if [hours, minutes, seconds, microseconds].all?(&:nil?)\n\n result = self.class.new(\"#{hours || 0} h\") +\n self.class.new(\"#{minutes || 0} minutes\") +\n self.class.new(\"#{seconds || 0} seconds\") +\n self.class.new(\"#{microseconds || 0} usec\")\n copy(result)\n return\n end\n\n # Special processing for unusual unit strings\n # feet -- 6'5\"\n feet, inches = unit_string.scan(FEET_INCH_REGEX)[0]\n if feet && inches\n result = self.class.new(\"#{feet} ft\") + self.class.new(\"#{inches} inches\")\n copy(result)\n return\n end\n\n # weight -- 8 lbs 12 oz\n pounds, oz = unit_string.scan(LBS_OZ_REGEX)[0]\n if pounds && oz\n result = self.class.new(\"#{pounds} lbs\") + self.class.new(\"#{oz} oz\")\n copy(result)\n return\n end\n\n # stone -- 3 stone 5, 2 stone, 14 stone 3 pounds, etc.\n stone, pounds = unit_string.scan(STONE_LB_REGEX)[0]\n if stone && pounds\n result = self.class.new(\"#{stone} stone\") + self.class.new(\"#{pounds} lbs\")\n copy(result)\n return\n end\n\n # more than one per. I.e., \"1 m/s/s\"\n raise(ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string.count('/') > 1\n raise(ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") if unit_string =~ /\\s[02-9]/\n\n @scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] # parse the string into parts\n top.scan(TOP_REGEX).each do |item|\n n = item[1].to_i\n x = \"#{item[0]} \"\n if n >= 0\n top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/) { x * n }\n elsif n.negative?\n bottom = \"#{bottom} #{x * -n}\"\n top.gsub!(/#{item[0]}(\\^|\\*\\*)#{n}/, '')\n end\n end\n if bottom\n bottom.gsub!(BOTTOM_REGEX) { \"#{Regexp.last_match(1)} \" * Regexp.last_match(2).to_i }\n # Separate leading decimal from denominator, if any\n bottom_scalar, bottom = bottom.scan(NUMBER_UNIT_REGEX)[0]\n end\n\n @scalar = @scalar.to_f unless @scalar.nil? || @scalar.empty?\n @scalar = 1 unless @scalar.is_a? Numeric\n @scalar = @scalar.to_int if @scalar.to_int == @scalar\n\n bottom_scalar = 1 if bottom_scalar.nil? || bottom_scalar.empty?\n bottom_scalar = if bottom_scalar.to_i == bottom_scalar\n bottom_scalar.to_i\n else\n bottom_scalar.to_f\n end\n\n @scalar /= bottom_scalar\n\n @numerator ||= UNITY_ARRAY\n @denominator ||= UNITY_ARRAY\n @numerator = top.scan(self.class.unit_match_regex).delete_if(&:empty?).compact if top\n @denominator = bottom.scan(self.class.unit_match_regex).delete_if(&:empty?).compact if bottom\n\n # eliminate all known terms from this string. This is a quick check to see if the passed unit\n # contains terms that are not defined.\n used = \"#{top} #{bottom}\".to_s.gsub(self.class.unit_match_regex, '').gsub(%r{[\\d*, \"'_^/$]}, '')\n raise(ArgumentError, \"'#{passed_unit_string}' Unit not recognized\") unless used.empty?\n\n @numerator = @numerator.map do |item|\n self.class.prefix_map[item[0]] ? [self.class.prefix_map[item[0]], self.class.unit_map[item[1]]] : [self.class.unit_map[item[1]]]\n end.flatten.compact.delete_if(&:empty?)\n\n @denominator = @denominator.map do |item|\n self.class.prefix_map[item[0]] ? [self.class.prefix_map[item[0]], self.class.unit_map[item[1]]] : [self.class.unit_map[item[1]]]\n end.flatten.compact.delete_if(&:empty?)\n\n @numerator = UNITY_ARRAY if @numerator.empty?\n @denominator = UNITY_ARRAY if @denominator.empty?\n self\n end", "def parse_unit_part(string, denominator = false)\n return {} if string.nil?\n units = {}\n matches = string.scan(/(\\w+)(\\^\\d)?/)\n matches.each do |m|\n exp = (m[1] ? m[1][1..-1].to_i : 1) * (denominator ? -1 : 1)\n units[m[0].intern] = exp\n end\n units\n end", "def parse(string, format: '%f %U', unit: ?b, prefix: nil)\n prefixes = prefixes(prefix)\n FormatParser.new(format, UnitParser.new(string, unit, prefixes)).parse\n end", "def parse(str, locale = Locale.default)\n elements = str.to_s.scan(NUMERIC_REGEXP).map do |(v, us)|\n unit = us.nil? ? default : find_unit(us, locale)\n raise ArgumentError, \"Unit cannot be determined (#{us})\" unless unit\n value = Integer(v) rescue Float(v)\n new(value, unit)\n end\n # Coalesce the elements into a single Measure instance in \"expression base\" units.\n # The expression base is the first provided unit in an expression like \"1 mile 200 feet\"\n elements.inject do |t, e|\n raise ArgumentError, \"Inconsistent units in compound metric\" unless t.unit.system == e.unit.system\n converted_value = e.convert(t.unit)\n new(t + converted_value, t.unit)\n end\n end", "def parse(tokens)\n tokens.delete_if { |t| t == '*' } # multiplication is the default\n tokens.map! do |token|\n # singularize, but make sure not to replace seconds with ''\n token == 's' ? token : token.singularize\n end\n\n # only supports one instance of division\n division = tokens.index('/')\n tokens.delete('/')\n\n # units :: [CUnit]\n units = tokens.map do |token|\n unit = Unit.find_by unit_name: token\n if unit.nil?\n unit = Unit.where('? = ANY(symbols)', token).first\n end\n if unit.nil?\n raise \"No unit found named #{token}.\"\n end\n CUnit.new(unit, 1)\n end\n\n unless division.nil?\n numerator = units[0...division]\n denominator = units[division..-1].map do |u|\n u.exponent *= -1\n u\n end\n\n units == numerator + denominator\n end\n\n return units\n end", "def parse_unit\n if @s.scan(/(?=\\()/)\n parse_group\n elsif @s.scan(/(?=\\[|\\\\[dDwWhHsS]|\\.)/)\n parse_char_group\n elsif c = parse_single_char\n Char.new c\n end\n end", "def test_parse_tricky_units\n unit1 = Unit.new('1 mm') #sometimes parsed as 'm*m'\n assert_equal ['<milli>','<meter>'], unit1.numerator\n unit2 = Unit.new('1 cd') # could be a 'centi-day' instead of a candela\n assert_equal ['<candela>'], unit2.numerator\n unit3 = Unit.new('1 min') # could be a 'milli-inch' instead of a minute\n assert_equal ['<minute>'], unit3.numerator\n unit4 = Unit.new('1 ft') # could be a 'femto-ton' instead of a foot\n assert_equal ['<foot>'], unit4.numerator\n unit5 = \"1 atm\".unit\n assert_equal ['<atm>'], unit5.numerator\n unit6 = \"1 doz\".unit\n assert_equal ['<dozen>'], unit6.numerator\n end", "def convertUnitValue(value,unit)\n if (unit.present?)\n unit.strip!\n else\n return value\n end\n unitRegEx=/^([afpnu\\xC2\\xB5\\316\\274mcdhkMGTPE]?)[ ]*(.+)/\n matchSet=unitRegEx.match(unit)\n if (matchSet.nil?)\n return value\n else\n prefix=matchSet[1]\n baseUnit=matchSet[2]\n case prefix\n when \"a\"\n mult=1.0E-18\n when \"f\"\n mult=1.0E-15\n when \"p\"\n mult=1.0E-12\n when \"n\"\n mult=1.0E-9\n when \"u\",\"\\316\\274\",\"\\xC2\\xB5\"\n mult=1.0E-6\n when \"m\"\n mult=1.0E-3\n when \"c\"\n mult=1.0E-2\n when \"d\"\n mult=1.0E-1\n when \"\"\n mult=1.0\n when \"h\"\n mult=1.0E2\n when \"k\"\n mult=1.0E3\n when \"M\"\n mult=1.0E6\n when \"G\"\n mult=1.0E9\n when \"T\"\n mult=1.0E12\n when \"P\"\n mult=1.E15\n when \"E\"\n mult=1.0E18\n else\n mult=1.0\n end\n return value*mult\n end\n end", "def to_metric(str)\n num, unit = str.split\n to_numeric(num).send(unit.to_sym)\nend", "def get_f_with_units str, unit_regex\n return (get_f str.match(float_and_regex(unit_regex)).to_s) \n end", "def parse_unit(unit_name)\n tokens = tokenize(unit_name)\n compound_unit = parse(tokens)\n simplified_unit = simplify(compound_unit)\n return simplified_unit\n end", "def parse_decimal_part(str)\n map = if str.index('割')\n Numeja::JA_割合用小数\n else\n Numeja::JA_小数\n end\n keys = map.keys()\n keys.reduce(0) do |t, ja_digit|\n index = str.index(ja_digit)\n break t if index.nil?\n unit = str.slice!(0, index)\n str.slice!(0, 1)\n t += (unit.to_f * map[ja_digit])\n t\n end\n end", "def parse_weight str\n return nil unless str\n # TODO\n # Metric\n kg = get_f_with_units( str, /(\\s)?k(ilo)?g(ram(s)?)?/i ) || 0\n g = get_f_with_units( str, /(\\s)?g(ram(s)?)?/i ) || 0\n mg = get_f_with_units( str, /(\\s)?m(illi)?g(ram(s)?)?/i ) || 0\n # Imperial\n lbs = get_f_with_units( str, /(\\s)?(lb(s)?|p(oun)?d(s)?)/i ) || 0\n oz = get_f_with_units( str, /(\\s)?o(unce(s)?|z)/i ) || 0\n return [kg,g,mg] if (kg !=0 or g !=0 or mg !=0)\n return [lbs,oz] if (lbs !=0 or oz !=0)\n return nil \n end", "def split_units(input, **options)\n options.reverse_merge!({\n input_language: \"ENGLISH\",\n output_language: \"ARABIC\"\n })\n options.symbolize_keys!\n\n # input = \"0.5l of Milk with 10gm Sugar\"\n # input = \"0.5l of Milk\"\n\n matches = input.scan(UNIT_REGEX)\n # e.g: [[\"0.5\", \"l\"]]\n return nil if matches.empty?\n\n # e.g: [[\"0.5\", \"l\"]].first.first => \"0.5\"\n amount = matches[0][0] #.try(:strip)\n return nil unless amount\n\n possible_unit = matches[0][2] #.try(:strip)\n return nil unless possible_unit\n\n # FIXME - need to populate the dict for units from database\n # Right now it is hardcoded at the top of this module\n possible_units = Translation::UNITS.map{|u| [MarkovChainTranslatorAlgo2.probability_match(possible_unit, u), u]}\n\n # Sorting the Score List\n sorted_possible_units = possible_units.sort_by {|x| x[0]}\n\n score_hash = {}\n translation = translate_word_from_database(possible_unit, options)\n unit_score = sorted_possible_units[0].first # the score of the unit word\n\n # if options[:input_language].upcase == \"ARABIC\"\n # unit_word = [possible_unit, ' ', amount].compact.join('').strip\n # else\n # unit_word = [amount, ' ', possible_unit].compact.join('').strip\n # end\n unit_word = [amount, ' ', possible_unit].compact.join('').strip\n\n # if options[:output_language].upcase == \"ARABIC\"\n # unit_translation = [translation, ' ', amount].compact.join('').strip\n # else\n # unit_translation = [amount, ' ', translation].compact.join('').strip\n # end\n unit_translation = [amount, ' ', translation].compact.join('').strip\n\n score_hash[unit_word] = {score: unit_score, translation: unit_translation}\n\n # e.g of score_hash = {\"grams\"=>{:score=>0, :translation=>\"جرامات\"}, \"10\"=>{:score=>0}, \"Corn\"=>{:score=>0, :translation=>\"ذرة\"}}\n\n return score_hash\n end", "def parse_metric_length str\n return nil if (str.nil? or str=='')\n mm = get_f_with_units( str, /(\\s)m(illi)?m(et(er|re)(s)?)?/i ) || 0\n cm = get_f_with_units( str, /(\\s)c(enti)?m(et(er|re)(s)?)?/i ) || 0\n m = get_f_with_units( str, /(\\s)m(et(er|re)(s)?)?/i ) || 0\n \n return [m, cm, mm] unless [m, cm, mm].uniq == [0]\n return nil\n end", "def unit2raw(str)\n val, unit = str.split()\n\n if unit.casecmp(\"kb\")\n ret = val.to_i * 1024\n elsif unit.casecmp(\"mb\")\n ret = val.to_i * 1024 * 1024\n elsif unit.casecmp(\"gb\")\n ret = val.to_i * 1024 * 1024 * 1024\n end\n \n return ret.to_s\nend", "def get_unit_names\n units = \"\"\n current = \"\"\n\n @si_string.chars.each do |char|\n next if char == \" \" # Skip if the character is a white space\n\n # Handles the case if the character is an operator \"*\", \"/\", \"(\", or \")\"\n if [\"/\", \"*\", \"(\", \")\"].include?(char)\n units += @si_counter_part[current][:unit] if current.length > 0\n units += char\n current = \"\" # Reset the current to \"\"\n else # Append the character to the current (name or symbol)\n current += char\n end\n end\n\n # append the last unit from current (name, or symbol)\n units += @si_counter_part[current][:unit] if current.length > 0\n units\n end", "def handle_u\n @unit = @tokens[@index].get_tag(Unit).type\n @index += 1\n @precision = :unit\n end", "def get_f_with_units_in_front str, unit_regex\n return (get_f str.match(append_regex( unit_regex, @@float_rxp)).to_s) \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /six_results GET /six_results.json
def index @six_results = SixResult.all end
[ "def index\n @five_results = FiveResult.all\n end", "def index\n @results = Result.all\n\n respond_to do |format|\n format.html\n format.json { render json: @results }\n end\n end", "def index\n @results = FourSquare.new(foursquare_params).search\n respond_to do |format|\n format.html\n format.json { render json: @results }\n end\n end", "def results\n vars = {\"trt_id\"=> @test_id}\n vars[\"type\" => @results_type] if @results_type\n\n path = \"test/results\"\n path = \"try_it_now/results\" if login_name == \"try_it_now\"\n response = api_request path, vars\n response[\"results\"]\n end", "def getsearchresults\n query=params['q'].gsub(' ','+')\n query=query.gsub('/','%2F')\n if params[:site]=='metacritic'\n doc=Nokogiri::HTML(open(\"http://metacritic.com/search/game/#{query}/results\"))\n doc.encoding='utf-8'\n @results=doc.css(\"li.result\").inner_html\n elsif params[:site]=='gamerankings'\n doc=Nokogiri::HTML(open(\"http://www.gamerankings.com/browse.html?search=#{query}&numrev=3\"))\n @results=doc.at_css(\"div#main_col > div.pod\").inner_html\n end\n respond_to do |format|\n format.js {render :layout => false}\n end\n end", "def results\n response.results\n end", "def results\n with_monitoring do\n response = perform(:get, results_url, query_params)\n Search::ResultsResponse.from(response)\n end\n rescue => e\n handle_error(e)\n end", "def index\n @three_results = ThreeResult.all\n end", "def index\n @military_battle_faction_results = Military::BattleFactionResult.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @military_battle_faction_results }\n end\n end", "def index\n @game_results = GameResult.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @game_results }\n end\n end", "def index\n @nb_users = NbUser.all\n @response = HTTParty.get(\"https://brianmcauley.nationbuilder.com/api/v1/people?__nonce=adb0731da1b0cf4f6f230c898f8e746b3142a1157bcf9dd9745388f3bbe6358b&limit=200&__proto__=&access_token=adb0731da1b0cf4f6f230c898f8e746b3142a1157bcf9dd9745388f3bbe6358b\",\n :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'})\n @result = @response.body\n respond_to do |format|\n format.json { render :json => JSON.parse(@result) }\n format.html { render \"index.html.erb\" }\n end\n end", "def index\n @four_results = FourResult.all\n end", "def get_results\n\n # An internal counter to get the next\n # set of results from the API\n @result_count = 0\n\n # An array into which the API results can\n # be collected\n @results = []\n\n # Get the first set of results from the API\n json_response = self.query\n\n while true\n\n # Exit the loop if the API doesn't return\n # any results and set the \"skip\" attribute\n # to nil\n if json_response['result_count'] == 0\n self.skip= nil\n break\n end\n\n # Add the count of the returned results to the\n # internal result counter's current value\n @result_count += json_response['result_count']\n\n # Append the current results to the results\n # array\n @results << json_response['results']\n\n # Set the \"skip\" attribute to the value\n # on the internal result counter\n self.skip= @result_count\n\n # Get the next set of results from the API\n json_response = self.query\n\n # A simple progress bar\n print \"#\"\n\n end\n\n # Print the total result count to the console\n puts \"\\nFound #{@result_count} results.\"\n\n return @results\n\n end", "def index\n @call6s = Call6.paginate(:page => params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @call6s }\n end\n end", "def home\n \t#uri = URI.parse(\"http://octopart.com/api/v2/parts/search?q=CY7C2544\")\n \turi = URI.parse(\"http://octopart.com/api/v2/parts/search?q=MT49H&apikey=298ff890\")\n \t#@data = Net::HTTP.get(uri) - works\n \t#render :json => @data\n \t@data = MultiJson.load(Net::HTTP.get(uri))\n \t@data = @data[\"results\"]\n end", "def print_results(response)\n puts response.to_json\nend", "def recipe_results\n # p \"------------\"\n # p params[:search]\n # @ingredients = params[:search].gsub(params[:search][-1],\"\")\n @ingredients = params[:search]\n # interpolate the food name into the url link (don't forget the + sign in front)\n # hardcoded:\n # url = \"https://api.spoonacular.com/recipes/findByIngredients?ingredients=+flour,+sugar&number=5&apiKey=8a69fc25f1ca4ccfa484d58fee68b86a\"\n # ariel's key\n url = \"https://api.spoonacular.com/recipes/findByIngredients?ingredients=#{@ingredients}&number=5&apiKey=8a69fc25f1ca4ccfa484d58fee68b86a\"\n\n #alex's key\n # url = \"https://api.spoonacular.com/recipes/findByIngredients?ingredients=#{@ingredients}&number=5&apiKey=85aeca77d8134a13be3a459305815224\"\n\n\n response = open(url).read\n @recipes = JSON.parse(response)\n\n # @recipes.map!{|r|\n # r['instructions'] = r['instructions']\n # }\n # return the result of the spoonacular API\n render json: { result: @recipes }\n end", "def results\n filter = params[:filter] || {}\n limit = params[:limit] || false\n offset = params[:offset] || false\n\n @total = base.refine(filter)\n @refined = @total.limit(limit) if limit\n @refined = @refined.offset(offset) if offset\n @results = @refined.to_a\n\n @count = @total.count\n\n respond_to do |format|\n format.html { render @results, :layout => false }\n format.json { render :json => @results }\n end\n end", "def results\n\t\titems = @searchData.css('tbody > tr')\n\t\toutput = items[0..9].each_with_index.map { |item, i|\n\t\t\t{\n\t\t\t\tid: i+1,\n\t\t\t\tname: item.css('.sbj').text,\n\t\t\t\tprice: item.css('.prc > strong').text,\n\t\t\t\turl: item.css('.lnk_vw').attr('href'),\n\t\t\t\timg: item.css('.td_thmb> .inner > a > img').attr('gd_src')\n\t\t\t}\n\t\t}\n\t\tJSON.pretty_generate(output)\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /six_results/1 PATCH/PUT /six_results/1.json
def update respond_to do |format| if @six_result.update(six_result_params) format.html { redirect_to @six_result, notice: 'Six result was successfully updated.' } format.json { render :show, status: :ok, location: @six_result } else format.html { render :edit } format.json { render json: @six_result.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @five_result.update(five_result_params)\n format.html { redirect_to @five_result, notice: 'Five result was successfully updated.' }\n format.json { render :show, status: :ok, location: @five_result }\n else\n format.html { render :edit }\n format.json { render json: @five_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @test_result = TestResult.find(params[:id])\n\n respond_to do |format|\n if @test_result.update_attributes(params[:test_result])\n format.html { redirect_to @test_result, notice: 'Test result was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @test_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @eqi_result.update(eqi_result_params)\n format.html { redirect_to @eqi_result, notice: 'Eqi result was successfully updated.' }\n format.json { render :show, status: :ok, location: @eqi_result }\n else\n format.html { render :edit }\n format.json { render json: @eqi_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @shot_result = ShotResult.find(params[:id])\n\n respond_to do |format|\n if @shot_result.update_attributes(params[:shot_result])\n format.html { redirect_to scaffold_shot_result_path(@shot_result), notice: 'Shot result was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @shot_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @result1 = Result1.find(params[:id])\n\n respond_to do |format|\n if @result1.update_attributes(params[:result1])\n format.html { redirect_to @result1, notice: 'Result1 was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @result1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n json_update(factType,factType_params, FactType)\n end", "def update\n @testresult = Testresult.find(params[:id])\n\n respond_to do |format|\n if @testresult.update_attributes(params[:testresult])\n format.html { redirect_to @testresult, notice: 'Testresult was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @testresult.errors, status: :unprocessable_entity }\n end\n end\n end", "def update *_\n @future = users_futures.find(params[:id])\n\n if @future.update_attributes(params[:future])\n render json: @future\n else\n render json: @future.errors, status: :unprocessable_entity\n end\n end", "def update\n @resource_result = Resource::Result.find(params[:id])\n\n respond_to do |format|\n if @resource_result.update_attributes(params[:resource_result])\n format.html { redirect_to @resource_result, notice: 'Result was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @resource_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @thirtysix.update(thirtysix_params)\n format.html { redirect_to @thirtysix, notice: 'Thirtysix was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @thirtysix.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @thief_talent = ThiefTalent.find(params[:id])\n\n if @thief_talent.update(thief_talent_params)\n head :no_content\n else\n render json: @thief_talent.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @test_result.update(test_result_params)\n format.html { redirect_to @test_result, notice: 'Test result was successfully updated.' }\n format.json { render :show, status: :ok, location: @test_result }\n else\n format.html { render :edit }\n format.json { render json: @test_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @rest_test = RestTest.find(params[:id])\n\n respond_to do |format|\n if @rest_test.update_attributes(params[:rest_test])\n format.html { redirect_to(@rest_test, :notice => 'RestTest was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @rest_test.errors, :status => :unprocessable_entity }\n end\n end\n end", "def patch(data, options={})\n raise NotImplementedError, \"We only patchs to singular resources.\" if count > 1\n first.patch(data, options)\n end", "def update\n respond_to do |format|\n if @six.update(six_params)\n format.html { redirect_to @six, notice: 'Six was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @six.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @test_case_result.update(test_case_result_params)\n format.html { redirect_to @test_case_result, notice: 'Test case result was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @test_case_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @survey_result = SurveyResult.find(params[:id])\n\n respond_to do |format|\n if @survey_result.update_attributes(params[:survey_result])\n format.html { redirect_to @survey_result, notice: 'Survey result was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @survey_result.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_rest\n @entry_question = EntryQuestion.find(params[:id])\n\n respond_to do |format|\n if @entry_question.update_attributes(params[:entry_question])\n flash[:notice] = 'EntryQuestion was successfully updated.'\n format.html { redirect_to(@entry_question) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @entry_question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @realtestresult.update(realtestresult_params)\n format.html { redirect_to @realtestresult, notice: 'Realtestresult was successfully updated.' }\n format.json { render :show, status: :ok, location: @realtestresult }\n else\n format.html { render :edit }\n format.json { render json: @realtestresult.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /six_results/1 DELETE /six_results/1.json
def destroy @six_result.destroy respond_to do |format| format.html { redirect_to six_results_url, notice: 'Six result was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @five_result.destroy\n respond_to do |format|\n format.html { redirect_to five_results_url, notice: 'Five result was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @result1 = Result1.find(params[:id])\n @result1.destroy\n\n respond_to do |format|\n format.html { redirect_to result1s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shot_result = ShotResult.find(params[:id])\n @shot_result.destroy\n\n respond_to do |format|\n format.html { redirect_to scaffold_shot_results_url }\n format.json { head :ok }\n end\n end", "def destroy\n @test_result = TestResult.find(params[:id])\n @test_result.destroy\n\n respond_to do |format|\n format.html { redirect_to test_results_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @six.destroy\n respond_to do |format|\n format.html { redirect_to sixes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @testresult = Testresult.find(params[:id])\n @testresult.destroy\n\n respond_to do |format|\n format.html { redirect_to testresults_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @thirtysix.destroy\n respond_to do |format|\n format.html { redirect_to thirtysixes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @test_case_result.destroy\n respond_to do |format|\n format.html { redirect_to test_case_results_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @result.destroy\n\n respond_to do |format|\n format.html { redirect_to results_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @result.destroy\n respond_to do |format|\n format.html { redirect_to results_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @one_test = OneTest.find(params[:id])\n @one_test.destroy\n\n respond_to do |format|\n format.html { redirect_to one_tests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @test_case_result = TestCaseResult.find(params[:id])\n @test_case_result.destroy\n\n respond_to do |format|\n format.html { redirect_to test_case_results_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @result = Result.find(params[:id])\n @result.destroy\n\n respond_to do |format|\n format.html { redirect_to results_url }\n format.json { head :no_content }\n end\n end", "def test_delete_not_exist_experiment\n not_exist_id = '10000'\n output = `curl -X DELETE http://localhost:8080/metrics/experiments/#{not_exist_id}`\n assert_match \"<html>\", output, \"TEST 3: delete not existing experiment - FAILED\"\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n @three_result.destroy\n respond_to do |format|\n format.html { redirect_to three_results_url, notice: 'Three result was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @contest3rd = Contest3rd.find(params[:id])\n @contest3rd.destroy\n\n respond_to do |format|\n format.html { redirect_to contest3rds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @test_run.destroy\n respond_to do |format|\n format.html { redirect_to test_runs_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the description of the repository. This is really just for annotation purposes, the description isn't used by Rosette.
def set_description(desc) @description = desc end
[ "def description=(value)\n @description = value\n end", "def description(descr)\n @project.description = descr\n end", "def description(desc)\n self[:Description] = desc\n end", "def set_description(new_description)\r\n update(description: new_description)\r\n end", "def description(description)\n @controller.description = description\n end", "def description\n @description ||= repo.\n config[\"branch.#{branch_name(repo)}.description\"].\n gsub(/\\n/,\"\")\n end", "def package_description=(desc)\n @package_description = desc\n end", "def description\n @name ||= data.xpath(\"cra:repositoryInfo/c:repositoryDescription\", NS::COMBINED).text\n end", "def set_description(name, opts = {})\n commands = command_builder('description', opts)\n configure_interface(name, commands)\n end", "def description(new_description = nil)\n if new_description\n @description = new_description\n elsif defined?(@description)\n @description\n else\n @description = nil\n end\n end", "def description= new_description\n @gapi.update! description: new_description\n end", "def description=(val)\n Client.put(\"/card/#{id}/desc\", :value => val)\n @description = val\n end", "def setDescription(description)\n\t\tRestClient.put(\"https://#{Cbthelper.username}:#{Cbthelper.authkey}@crossbrowsertesting.com/api/v3/selenium/#{@testId}\",\n \"action=set_description&description=#{description}\")\n\tend", "def set_description\n self.description ||= details[\"Label_Service Description\"] if details[\"Label_Service Description\"]\n end", "def description_for_repo(repo)\n repo.description\n end", "def description(session, id, new_description)\n write_task('rvpe.image.description', session) do\n err_msg = \"You don't have permission to modify the description \" +\n 'of the image.'\n sanity_check(session, id, err_msg) do\n call_one_xmlrpc('one.image.update', session, id,\n 'DESCRIPTION', new_description)\n end\n end\n end", "def description=(desc)\n self.body = desc\n end", "def description\n @description = \"Espresso\"\n end", "def desc=(new_desc)\n @desc = new_desc\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the source locale (i.e. the locale all the source files are in). Defaults to enUS.
def source_locale @source_locale ||= Locale.parse('en-US', Locale::DEFAULT_FORMAT) end
[ "def locale\n @locale ||= 'US'\n LOCALES.include? @locale or raise BadLocale\n\n @locale\n end", "def locale\n return @locale\n end", "def locale\n ::I18n.locale.to_s\n end", "def locale\n I18n.locale if defined?(I18n)\n end", "def get_locale\n @locale\n end", "def default_locale\n return @default_locale\n end", "def current_locale\n Thread.current[:\"localite:locale\"] || base\n end", "def locale\n current_site.locale || I18n.default_locale.to_s\n end", "def locale\n current_site.locale || Archangel::LANGUAGE_DEFAULT\n end", "def detect_locale_from(source)\n case source\n when :params\n params[:locale]\n when :session\n logger.debug \"Session: #{session.inspect}\"\n session[:locale]\n when :cookie\n cookies[:locale]\n when :domain\n parse_host_and_port_for_locale[0]\n when :header\n request.env['HTTP_ACCEPT_LANGUAGE']\n when :default\n default_locale\n else\n raise \"unknown source\"\n end\n end", "def current_locale_code\n Utility.locale_code\n end", "def source_lang\n @doc.xpath(\"/#{@namespace_xliff}xliff/#{@namespace_xliff}file\").first['source-language']\n end", "def system\n locale_from_env || default_locale\n end", "def locale\n Translatomatic::Model::Locale\n end", "def base_locale\n if not @country.nil?\n Locale.new(@language)\n else\n nil\n end\n end", "def locale\r\n read_attribute(:locale).to_sym\r\n end", "def read_locale\n Thread.current[:globalize_locale]\n end", "def default_locale\n evaluate_localization_option!(:default_locale)\n end", "def find_locale\n locale = locales.all.detect(&:default)\n return locale.code unless locale.nil?\n @default_locale\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the source locale.
def set_source_locale(code, format = Locale::DEFAULT_FORMAT) @source_locale = Locale.parse(code, format) end
[ "def locale=(value)\n @locale = value\n end", "def set_locale\n set_locale_or_default(params[:locale])\n end", "def set_locale\n I18n.locale = get_locale_from_params || I18n.default_locale\n end", "def set_locale\n I18n.locale = current_user.try(:locale) || locale_from_header\n end", "def set_locale\n return unless Language.current\n\n ::I18n.locale = Language.current&.locale\n end", "def source_locale\n @source_locale ||= Locale.parse('en-US', Locale::DEFAULT_FORMAT)\n end", "def set_Locale(value)\n set_input(\"Locale\", value)\n end", "def set_Locale(value)\n set_input(\"Locale\", value)\n end", "def setLocale\n if @lOptions.count\n @lOptions.each do | key, value |\n case key\n when :locale_group\n @lgrp = @@lOptions[:locale_group]\n when :locale_language\n @lang = @lOptions[:locale_language]\n when :locale_country\n @ctry = @lOptions[:locale_country]\n when :locale_descriptor\n @desc = @lOptions[:locale_descriptor]\n end\n end\n end\n end", "def set_locale(name, value)\n talk('SET-LOCALE ' + name + '=' +value)\n end", "def setLocale(locale)\n @fields['locale'] = locale\n self\n end", "def set_locale\n I18n.locale = params[:locale] || request.headers['LANG'] || I18n.default_locale\n end", "def set_locale\n session[:locale] = params[:locale]\n session[:locale] ||= extract_locale_from_header\n# return switch_locale_and_redirect_to_referer if params[:locale].present?\n @locale = Locale.new session[:locale]\n I18n.locale = @locale.current\n end", "def set_locale(locale_code)\n @locale = locale_code\n self\n end", "def set_SourceLanguage(value)\n set_input(\"SourceLanguage\", value)\n end", "def set_locale(local_swimmer)\n @locale = local_swimmer if local_swimmer&.instance_of?(Swimmer)\n end", "def set_translation\n if locale_change_needed?\n ::I18n.locale = session[:alchemy_locale] = locale_from_params ||\n locale_from_user || locale_from_browser || ::I18n.default_locale\n else\n ::I18n.locale = session[:alchemy_locale]\n end\n end", "def set_individual_locale\n I18n.locale = preference[:locale] if preference[:locale]\n end", "def input_locale=(value)\n @input_locale = value\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an extractor to this repo.
def add_extractor(extractor_id) klass = ExtractorId.resolve(extractor_id) extractor_configs << ExtractorConfig.new(klass).tap do |config| yield config if block_given? end end
[ "def extractor(name, extract = nil, &block)\r\n tor '@extractor', name, extract, &block\r\n end", "def extractor\n @extractor ||= self.respond_to?(:extract) ? self : instantiate(self.class.get_extractor)\n end", "def add\n @repo.git.git.remote({}, 'add', '--mirror', @name, @url)\n end", "def create\n\t\t@extractor = Extractor.new(params[:extractor])\n\n\t\trespond_to do |format|\n\t\t\tif @extractor.save\n\t\t\t\tformat.html { redirect_to(@extractor, :notice => 'Extractor was successfully created.') }\n\t\t\t\tformat.xml { render :xml => @extractor, :status => :created, :location => @extractor }\n\t\t\telse\n\t\t\t\tformat.html { render :action => \"new\" }\n\t\t\t\tformat.xml { render :xml => @extractor.errors, :status => :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def add_repository repo\n repo.content = self\n @repositories[repo.repoid] = repo\n end", "def set_extractors(extractors)\n self.extractors = extractors\n end", "def add_matcher(matcher)\n @matchers << matcher\n self\n end", "def add path, kwargs={}\n remove_files = kwargs.arg :remove_files, false\n\n cmd = 'aptly repo add'\n cmd += ' -remove-files' if remove_files\n cmd += \" #{@name.quote} #{path}\"\n\n Aptly::runcmd cmd\n end", "def extractor\n base_extractor=PlainTextExtractor.find_by_extension(ext_as_sym)\n if base_extractor then\n returning base_extractor.dup do |xtr|\n xtr.source = complete_path\n end\n else\n EmptyExtractor.instance\n end\n end", "def add_matcher(matcher)\n raise TypeError unless matcher.is_a? Matcher\n @matchers << matcher\n self\n end", "def create\n extractor = create_extractor\n ok = extractor.persisted?\n notify(ok, :successful_extractor_create, :failure_in_extractor_create)\n ok ? redirect_to(edit_book_path(current_book.slug)) : locals(:new, :extractor => extractor)\n end", "def extract(options = {})\n self.warn(self, \"Don't use the extractor anymore, use release.use(:mockup, options) and release.use(:url_relativizer, options) processors\")\n @extractor_options = options\n end", "def <<(repository)\n repositories << repository\n end", "def add_match_expression(expression)\n @matchers << expression.matcher(cache)\n self\n end", "def add_remote(name, url)\n @remotes[name] = Remote::Git.new(self, name, url)\n @remotes[name].add\n end", "def add_remote(uri, name)\n @repository.add_remote(name,uri)\n \n self.remotes\n end", "def add(_feature, _matching_value)\n raise NotImplementedError\n end", "def add_repository(path)\n Dir[\"#{path}/auto-*\"].each do |plugin|\n Plugins.add plugin\n end\n end", "def add_remote(name, url, opts = {})\n url = url.repo.path if url.is_a?(Git::Base)\n self.lib.remote_add(name, url, opts)\n Git::Remote.new(self, name)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds multiple locales to the list of locales this repo supports.
def add_locales(locale_codes, format = Locale::DEFAULT_FORMAT) @locales += Array(locale_codes).map do |locale_code| Locale.parse(locale_code, format) end end
[ "def available_locales=(locales); end", "def with_locales(*locales)\r\n locales = locales.flatten.map(&:to_s)\r\n #where(:locale.in => locales)\r\n where(:locale => {\"$in\" => locales})\r\n end", "def pull_locales()\n @log.info('Downloading locales...'.cyan.bright)\n\n get_locale_ids.each do |id|\n pull_locale(id)\n TranslationBuilder.build(\"#{@locale_specific_map[id.to_sym] || id}\")\n end\n end", "def all_locales_options\n SpreeI18n::Locale.all.map { |locale| locale_presentation(locale) }.push(['English (EN)', :en])\n end", "def available_locales\n @available_locales ||= begin\n locales = Set.new\n Array(config[:read]).map do |pattern|\n [pattern, Dir.glob(format(pattern, locale: '*'))] if pattern.include?('%{locale}')\n end.compact.each do |pattern, paths|\n p = pattern.gsub('\\\\', '\\\\\\\\').gsub('/', '\\/').gsub('.', '\\.')\n p = p.gsub(/(\\*+)/) { Regexp.last_match(1) == '**' ? '.*' : '[^/]*?' }.gsub('%{locale}', '([^/.]+)')\n re = /\\A#{p}\\z/\n paths.each do |path|\n locales << Regexp.last_match(1) if re =~ path\n end\n end\n locales\n end\n end", "def available_locales\n @available_locales ||= begin\n locales = Set.new\n @read.map do |pattern|\n [pattern, Dir.glob(pattern % {locale: '*'})] if pattern.include?('%{locale}')\n end.compact.each do |pattern, paths|\n p = pattern.gsub('\\\\', '\\\\\\\\').gsub('/', '\\/').gsub('.', '\\.')\n p = p.gsub(/(\\*+)/) { $1 == '**' ? '.*' : '[^/]*?' }.gsub('%{locale}', '([^/.]+)')\n re = /\\A#{p}\\z/\n paths.each do |path|\n if re =~ path\n locales << $1\n end\n end\n end\n locales\n end\n end", "def available_locales_set; end", "def add_locale(name, code)\n name, code = sanitize_arguments(name, code)\n return false unless valid_locale?(code)\n @@locales = locales.merge(name.downcase.to_sym => code)\n reload_locales\n true\n end", "def all_locales\n configatron.full_locales | preferred_locales\n end", "def locales\n get(\"platform/locales\")[\"locales\"]\n end", "def available_locales\n locales = Language.sorted_by_abbreviation.pluck(:abbreviation).presence if Language.table_exists?\n (locales.presence || [default_locale])\n end", "def add_current_locale\n locale = ::Mongoid::Fields::I18n.locale.to_s\n self.locales << locale unless self.locales.include?(locale)\n end", "def install_locales_all_on(host)\n install_package(host, 'locales-all') unless check_for_package(host, 'locales-all')\n end", "def each_locale(include_default_locale = true, &block)\n current_locale = ::Mongoid::Fields::I18n.locale\n _locales = include_default_locale ? self.locales : (self.locales - [self.default_locale])\n\n _locales.each do |locale|\n ::Mongoid::Fields::I18n.with_locale(locale) do\n yield locale, current_locale.to_s == locale.to_s\n end\n end\n end", "def in_available_locales\n @tested_locales = I18n.available_locales\n self\n end", "def available_locales\n resource.translations.all(:fields => [:locale_tag], :unique => true).map { |t| t.locale }\n end", "def available_locales\n init_translations unless initialized?\n translations.inject([]) do |locales, (locale, data)|\n locales << locale unless (data.keys - [:i18n]).empty?\n locales\n end\n end", "def add(locale)\n @translations.update(locale[$1] || {}) if @locale =~ /\\A(\\w+)(_|-)/\n @translations.update(locale[@locale] || {})\n @translations.each_value(&:freeze)\n end", "def languages = @languages ||= LocalePreference.new(locales.map(&:language).uniq)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the extractor configs that match the given path.
def get_extractor_configs(path) extractor_configs.select do |config| config.matches?(path) end end
[ "def get_extractor_config(extractor_id)\n extractor_configs.find do |config|\n config.extractor_id == extractor_id\n end\n end", "def config_paths\n Dir.glob(File.join path, \"*.yml\")\n end", "def find_configs( conf_name )\n do_find_configs( File.dirname(@path), conf_name )\n end", "def parse_information(path, keys)\n sources_config.map do |configuration|\n node = response_body.dig(*configuration[path])\n next if node.blank?\n node.slice(*configuration[keys])\n end.compact[0]\n end", "def search_config(glob)\n list = []\n config_paths.each do |path|\n list.concat(Dir[File.join(path, glob)])\n end\n list\n end", "def get_configs()\n config_pool = Dir.glob(\"*.yml\")\n if config_pool.empty?\n config_pool = Dir.glob(\"*.json\") unless\n if config_pool.empty?\n puts \"\\e[33mINFO\\e[0m: No local config found! Using test/content/config.yml...\"\n self.config_file=('test/content/config.yml')\n end\n else\n self.config_file=(config_pool.first)\n end\n end", "def find_by_path path, allow_multiple = false\n @manifest_dir.find_by_path path, allow_multiple\n end", "def extract(path)\n files = files_in_path(path)\n supported_files = filter_files(files)\n\n parse_files(supported_files)\n end", "def get_targets(path)\n config = YAML.load(File.read(path))\n targets = config['storage']['targets'].group_by { |key| key['type'] }\n targets_valid?(targets)\n process_targets(targets)\nend", "def load_config(path)\n # Read and parse the YAML configuration file\n config = YAML.safe_load(File.read(path))\n\n recordings = []\n\n # Build a hash whose keys are URIs and values are local file paths\n # Iterate over the list of each speaker's recordings\n config['recordings'].map do |speaker, sessions|\n # Iterate over the list of sessions\n sessions.map do |session, parts|\n # Iterate over the list of session parts\n (1..parts).map do |part|\n # Assemble a [uri, path] list from the interpolated file name\n ->(file) do\n recordings << %w[uri path].map do |suffix|\n File.join(config[\"base_#{suffix}\"], file)\n end\n end.call(\n format(\n config['file_pattern'],\n { speaker: speaker, session: session, part: part }\n )\n )\n end\n end\n end\n Hash[recordings]\n end", "def config_from_files\n config_file_paths.map do |path|\n all_config = YAML.load_file(path)\n ship_config_defaults = complete_config.fetch('ship', {}).fetch('default', {})\n ship_config_for_service = complete_config.fetch('ship', {}).fetch(config_key, {})\n ship_config_defaults.merge ship_config_for_service\n rescue Errno::ENOENT\n logger.warn \"Config file '#{path}' not found, skipping.\"\n nil\n end.compact\n end", "def read_file(path)\n # build a config file mapping we can manipulate\n ::Chef::Log.debug(\"Reading ssh config #{path}\")\n ::File.read(path).each_line.with_index do |conf_line, index|\n\n # this builds a hash of key => value pairs for every config var it finds\n #if conf_line.match(/^[^#]\\S+\\s/)\n if conf_line.match(/^\\S{2,}\\s/)\n conf_var, conf_val = conf_line.split(/\\s+/, 2)\n if conf_var.start_with?(\"#\")\n conf_var = conf_var[1..-1]\n end\n @conf_lookup[conf_var] ||= []\n @conf_lookup[conf_var] << index\n end\n\n conf_line.rstrip!\n @conf_lines << conf_line\n\n end\n\n end", "def all_config_files\n #files = Dir[File.join(path, \"_config.yml\")]\n files = Dir[File.join(path, \"_*.yml\")]\n return files\n end", "def find_config(file)\n path = Pathname(file).expand_path\n\n while path.parent != path\n config1 = path.join(\"browserslist\")\n return config1.read if config1.exist? && !config1.directory?\n\n config2 = path.join(\".browserslistrc\")\n return config2.read if config2.exist? && !config1.directory?\n\n path = path.parent\n end\n\n nil\n end", "def get(attrib_path)\n \n begin\n first,*elements = attrib_path.split('.')\n config_ele = @config[first]\n elements.each { |val|\n raise \"Test config attribute '#{attrib_path}' not found!\" if !config_ele\n config_ele = Common.get_obj_copy(config_ele[val])\n \n }\n \n $test_logger.result_log(\"Config Read[#{attrib_path}]=#{config_ele}\") if $test_logger != nil\n rescue Exception => ex\n raise ex, \"Error while getting test config!\\n#{ex.message}\", ex.backtrace\n end \n\n config_ele\n end", "def paths\n self.config[:paths]\n end", "def get_all_configs\n\trequire 'json'\n\tDir.glob(\"./features/support/config/**/*.json\").each do |file|\n\t\tfile = File.read(file)\n\t\tdata = JSON.parse(file)\n\t\tdata.each do |key, stuff|\n\t\t\t$config[key] = stuff\n\t\tend\n\tend\nend", "def paths\n Array(config.path).map(&:to_s)\n end", "def get_values(path)\n ret = []\n\n content.match(path).each do |key|\n ret << content.get(key)\n end\n\n ret\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the extractor config by either name or extractor id.
def get_extractor_config(extractor_id) extractor_configs.find do |config| config.extractor_id == extractor_id end end
[ "def get_extractor_configs(path)\n extractor_configs.select do |config|\n config.matches?(path)\n end\n end", "def extractor_for(attr_name)\n extractors.find {|it| it.attr == attr_name }\n end", "def add_extractor(extractor_id)\n klass = ExtractorId.resolve(extractor_id)\n extractor_configs << ExtractorConfig.new(klass).tap do |config|\n yield config if block_given?\n end\n end", "def extractor\n @extractor ||= self.respond_to?(:extract) ? self : instantiate(self.class.get_extractor)\n end", "def configuration(name_or_id)\n if name_or_id =~ /^\\d+$/\n config_data = proxy.GetConfiguration(:configurationId => name_or_id)\n else\n config_data = proxy.GetConfigurationByName(:name => name_or_id)\n end\n Configuration.parse(config_data)\n end", "def find(id)\r\n properties[id]\r\n end", "def extractor(name, extract = nil, &block)\r\n tor '@extractor', name, extract, &block\r\n end", "def find (id_or_conditions)\n if id_or_conditions.is_a?(Hash)\n lookup(id_or_conditions).first\n else\n configs[id_or_conditions.to_s]\n end\n end", "def config_read(id: 1, env: 'sandbox')\n response = http_client.get(\"#{base_path}/configs/#{env}/#{id}\")\n resource_instance(response)\n end", "def get_configlet_by_name(name)\n log(Logger::DEBUG) { \"get_configlet_by_name: #{name}\" }\n @clnt.get('/configlet/getConfigletByName.do', data: { name: name })\n end", "def config_for_lookup(lookup_name); end", "def get(matcher)\n @configurations[parse_matcher(matcher)]\n end", "def get name, default: nil\n name_str = name.to_s\n name_sym = name.to_sym\n\n value = nil\n found = false\n @config.each do |configfile|\n if value = configfile[:config][name_str] or value = configfile[:config][name_sym]\n found = true\n break\n end\n end\n value = default if value.nil? and not found\n value\n end", "def get_serializer_config(name_or_id)\n found = serializer_configs.find do |config|\n config.name == name_or_id\n end\n\n found || serializer_configs.find do |config|\n config.serializer_id == name_or_id\n end\n end", "def extraction\n options[:extraction] || name\n end", "def current_extractor\n @current_extractor ||= Extractor.find_by!(:user => current_user,\n :id => params[:id])\n end", "def getExperiment(id)\n match = nil;\n @experiments.each do |exp|\n if exp.id == id\n match = exp\n break\n end\n end\n return match\n end", "def find(id)\n fetch([name, id]) do\n super\n end\n end", "def extract_id\n selector[:_id]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the serializer config by either name or serializer id.
def get_serializer_config(name_or_id) found = serializer_configs.find do |config| config.name == name_or_id end found || serializer_configs.find do |config| config.serializer_id == name_or_id end end
[ "def get_serializer(name)\n if s = serializers[name]\n s\n else\n Fields.traverse_association_tree(name, serializers, associations, aliased_associations)\n end\n end", "def get_serializer_option(serializer, key)\n get_serializer_options(serializer)[key]\n end", "def getSerializerByName( serializerName )\n\n # parameter TypeCheck\n #BIMserverAPI::TypeCheck::String( serializerName )\n\n # BIMserver request\n request( { serializerName: serializerName } )\n end", "def find_serializer(klass)\n klass.instance_variable_get(SERIALIZER_CLASS)\n end", "def lookup_serializer\n \"#{self.class.name.split('::')[0...-1].join('::')}::#{serializer_class_name}\".safe_constantize\n end", "def serializer_type\n SERIALIZER_TYPES.find { |type|\n self.class.to_s =~ /::#{type}/i\n } || default_serializer_type\n end", "def get_deserializerOid(deserializer_name)\n @conn.plugin_interface.getAllDeserializers(true).each do |deserializer|\n if deserializer[\"name\"] == deserializer_name\n return deserializer[\"oid\"]\n end\n end\n\n # if not found, raise error\n raise \"No deserializer found with name '\" + deserializer_name + \"'.\"\n end", "def serializer\n return @client_serializer if @client_serializer\n\n @opts[:serializer] ? @opts[:serializer] : YAML\n end", "def get_serializer_for(klass)\n begin\n namespaced_module(\"#{klass.name}Serializer\").constantize\n rescue NameError => e\n get_serializer_for(klass.superclass) if klass.superclass\n end\n end", "def association_serializer_for(name)\n model_class_name = self.name.to_s.demodulize.classify.gsub(/Serializer$/, '')\n model_class = model_class_name.safe_constantize\n\n association_class_name = model_class.try(:reflect_on_association, name)&.class_name\n\n return nil unless association_class_name\n\n serializer_for(association_class_name)\n end", "def configuration(name_or_id)\n if name_or_id =~ /^\\d+$/\n config_data = proxy.GetConfiguration(:configurationId => name_or_id)\n else\n config_data = proxy.GetConfigurationByName(:name => name_or_id)\n end\n Configuration.parse(config_data)\n end", "def get_serializer_for(klass)\n begin\n namespaced_module(\"#{klass.is_a?(Class) ? klass.name : klass}Serializer\").constantize\n rescue NameError\n get_serializer_for(klass.superclass) if klass.is_a?(Class) && klass.superclass\n end\n end", "def get(key); custom_serializer_options[key]; end", "def serializer_class\n \"#{self.class.to_s}Serializer\".constantize\n end", "def find_serializer(klass, tag: nil)\n tag ||= DEFAULT_TAG\n hash = klass.instance_variable_get(SERIALIZER_CLASSES)\n serializer = hash&.fetch(tag.to_sym, nil)\n Surrealist::ExceptionRaiser.raise_unknown_tag!(tag) if serializer.nil? && tag != DEFAULT_TAG\n serializer\n end", "def get_controller_native_serializer_config\n return nil unless @controller\n\n if @many == true\n controller_serializer = @controller.try(:native_serializer_plural_config)\n elsif @many == false\n controller_serializer = @controller.try(:native_serializer_singular_config)\n end\n\n return controller_serializer || @controller.try(:native_serializer_config)\n end", "def get_object_config(name)\n @object_configs[name.to_sym] || {}\n end", "def config_read(id: 1, env: 'sandbox')\n response = http_client.get(\"#{base_path}/configs/#{env}/#{id}\")\n resource_instance(response)\n end", "def serializer\n @serializer ||=\n begin\n @serializer = serializer_opts.delete(:serializer)\n @serializer ||= ActiveModel::Serializer.serializer_for(resource, serializer_opts)\n\n if serializer_opts.key?(:each_serializer)\n serializer_opts[:serializer] = serializer_opts.delete(:each_serializer)\n end\n @serializer\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the locale object by locale code.
def get_locale(code, format = Locale::DEFAULT_FORMAT) locale_to_find = Locale.parse(code, format) locales.find { |locale| locale == locale_to_find } end
[ "def find_locale\n locale = ::Contentful::Management::Locale.all(id).detect(&:default)\n return locale.code unless locale.nil?\n @default_locale\n end", "def locale(code)\n @query[:locale] = code\n self\n end", "def find_locale\n locale = locales.all.detect(&:default)\n return locale.code if locale\n\n default_locale\n end", "def find_locale\n locale = locales.all.detect(&:default)\n return locale.code unless locale.nil?\n @default_locale\n end", "def language_code\n return nil if locale.nil?\n @_language_code ||= locale.split(\"-\").first.downcase\n end", "def get_locale\n @locale\n end", "def current_locale_code\n Utility.locale_code\n end", "def locale_code(locale=nil)\n locale ? locale.to_s : I18n.locale.to_s\n end", "def locale\r\n read_attribute(:locale).to_sym\r\n end", "def native_name(locale_code)\n val = language_names(locale_code)\n val = val[:native].first if val\n\n val\n end", "def locale = @lock.with_read_lock { @context.locale(true).code }", "def locale\n return @locale\n end", "def by_locale(locale_name)\n loc = Locale.find_by_name(locale_name)\n page_i18ns.by_locale(loc).first or page_i18ns.first\n end", "def get_locale(locale = nil)\n locale || @_deco_locale || (h.cama_get_i18n_frontend rescue nil) || I18n.locale\n end", "def current_language_code(locale=nil)\n Utility.language_code(locale)\n end", "def get_by_id(id)\n HttpClient::Preconditions.assert_class('id', id, String)\n r = @client.request(\"/reference/locales/#{CGI.escape(id)}\").get\n ::Io::Flow::V0::Models::Locale.new(r)\n end", "def locale_fields_by_locale_code(language_id:, locale_code:)\n args = { languageId: language_id, localeCode: locale_code }\n client_request('GetLocaleFieldsByLocaleCode', args: args)\n end", "def locale\n return nil if errors\n\n locale = YAML.safe_load(@text).keys.first\n locale.to_sym\n end", "def get_language_from_code code\n ISO_639.find(code).english_name if not(code.nil?)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /attendees/new GET /attendees/new.json
def new @attendee = Attendee.new respond_to do |format| format.html # new.html.erb format.json { render json: @attendee } end end
[ "def new\n @event = current_event\n @attendee = Attendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attendee }\n end\n end", "def new\n @attend = Attend.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attend }\n end\n end", "def new\n @attendence = Attendence.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attendence }\n end\n end", "def new\n \n\t@attending = Attending.new\n \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attending }\n \n end\nend", "def create\n @attendee = @current_user.attendees.new(attendee_params)\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to @attendee, notice: 'Attendee was successfully created.' }\n format.json { render :show, status: :created, location: @attendee }\n else\n format.html { render :new }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @attendee = Attendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendee }\n end\n end", "def create\n @admin_attendee = @admin_form.attendees.new(admin_attendee_params)\n respond_to do |format|\n if @admin_attendee.save\n format.html { redirect_to admin_form_attendee_path(@admin_form, @admin_attendee), notice: t('crud.created_successfully!', name: Admin::Attendee.model_name.human) }\n format.json { render :show, status: :created, location: @admin_attendee }\n else\n format.html { render :new }\n format.json { render json: @admin_attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @emailannouncement = Emailannouncement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @emailannouncement }\n end\n end", "def new\n @first_aid_attendee = FirstAidAttendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @first_aid_attendee }\n end\n end", "def new\n @attendee_type = AttendeeType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendee_type }\n end\n end", "def new\n @attendence = Attendence.new\n find_cat\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attendence }\n end\n end", "def create\n\t\tclient = OAuth2::Client.new( ENV[\"FT_UID\"], ENV[\"FT_SECRET\"], site:\"https://api.intra.42.fr\")\n\t\ttoken = client.client_credentials.get_token\n\t\t@user_quest = token.get(\"/v2/users/\" + params[:attendee][:login]).parsed\n\t\t# if @user_quest.nil?\n\t\t# \terrors.add( message: \"cannot be nil\")\n\t\t# end\n\n\t\t@attendee = current_user.attendees.build(attendee_params)\n\t\t@attendee.name = @user_quest[\"displayname\"]\n\t\trespond_to do |format|\n\t\t\tif @attendee.save\n\t\t\t\tformat.html { redirect_to @attendee, notice: 'Attendee was successfully created.' }\n\t\t\t\tformat.json { render :show, status: :created, location: @attendee }\n\t\t\t\tformat.js\n\t\t\telse\n\t\t\t\tformat.html { render :new }\n\t\t\t\tformat.json { render json: @attendee.errors, status: :unprocessable_entity }\n\t\t\t\tformat.js\n\t\t\tend\n\t\tend\n\tend", "def new\n @atendente = Atendente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @atendente }\n end\n end", "def new\n @email = @user.emails.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @email }\n end\n end", "def new\n @attendence = Attendence.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendence }\n end\n end", "def create\n \n \n\t@attending = current_user.attendings.build(params[:attending])\n\n respond_to do |format|\n if @attending.save\n\t \n format.html { redirect_to @attending, notice: 'Your RSVP was successfully created.' }\n format.json { render json: @attending, status: :created, location: @attending }\n else\n format.html { render action: \"new\" }\n format.json { render json: @attending.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @email = @recipient.emails.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @email }\n end\n end", "def new\n @email = Email.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @email }\n end\n end", "def new\n @attendence_entry = AttendenceEntry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendence_entry }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /attendees/1 DELETE /attendees/1.json
def destroy @attendee = Attendee.find(params[:id]) @attendee.destroy respond_to do |format| format.html { redirect_to attendees_url } format.json { head :no_content } end end
[ "def destroy\n @attendee = Attendee.find(params[:id])\n @attendee.destroy\n\n respond_to do |format|\n format.html { redirect_to(attendees_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @attend.destroy\n respond_to do |format|\n format.html { redirect_to attends_url, notice: t('destroy_success') }\n format.json { head :no_content }\n end\n end", "def destroy\n @attend = Attend.find(params[:id])\n @attend.destroy\n\n respond_to do |format|\n format.html { redirect_to attends_url }\n format.json { head :ok }\n end\n end", "def destroy\n @event_attendee.destroy\n respond_to do |format|\n format.html { redirect_to event_attendees_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @first_aid_attendee = FirstAidAttendee.find(params[:id])\n @first_aid_attendee.destroy\n\n respond_to do |format|\n format.html { redirect_to first_aid_attendees_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_attendee.destroy\n respond_to do |format|\n format.html { redirect_to [@admin_form, Attendee] }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence = Attendence.find(params[:id])\n @attendence.destroy\n\n respond_to do |format|\n format.html { redirect_to attendences_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attending = Attending.find(params[:id])\n @attending.destroy\n\n respond_to do |format|\n format.html { redirect_to attendings_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attend = Attend.find(params[:id])\n @attend.destroy\n\n respond_to do |format|\n format.html { redirect_to(attends_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @attendace.destroy\n respond_to do |format|\n format.html { redirect_to attendaces_url, notice: 'Attendace was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence.destroy\n respond_to do |format|\n format.html { redirect_to attendences_url, notice: 'Attendence was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attender.destroy\n respond_to do |format|\n format.html { redirect_to attenders_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attend_event.destroy\n respond_to do |format|\n format.html { redirect_to events_url, notice: 'Request successfully rescinded.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @backend_conf_attendee.destroy\n respond_to do |format|\n format.html { redirect_to backend_conf_attendees_url, notice: 'Conf attendee was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence.destroy\n respond_to do |format|\n format.html { redirect_to attendences_url}\n format.json { head :no_content }\n end\n end", "def destroy\n @not_attending.destroy\n respond_to do |format|\n format.html { redirect_to not_attendings_url, notice: 'Not attending was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence = Attendence.find(params[:id])\n @attendence.destroy\n\n respond_to do |format|\n format.html { redirect_to(attendences_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @event_atendee.destroy\n respond_to do |format|\n format.html { redirect_to event_atendees_url, notice: 'Event atendee was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence_info.destroy\n respond_to do |format|\n format.html { redirect_to attendence_infos_url, notice: 'Attendence info was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /partner_org_components/1 GET /partner_org_components/1.json
def show @partner_org_component = PartnerOrgComponent.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @partner_org_component } end end
[ "def new\n @partner_org_component = PartnerOrgComponent.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @partner_org_component }\n end\n end", "def test_get_org_components\n org = Components[1]\n comps = @jira._find_org_components(org)\n\n assert_equal(1, comps.size)\n assert_equal(org, comps[0].name)\n end", "def create\n @partner_org_component = PartnerOrgComponent.new(params[:partner_org_component])\n\n respond_to do |format|\n if @partner_org_component.save\n format.html { redirect_to @partner_org_component, notice: 'Partner org component was successfully created.' }\n format.json { render json: @partner_org_component, status: :created, location: @partner_org_component }\n else\n format.html { render action: \"new\" }\n format.json { render json: @partner_org_component.errors, status: :unprocessable_entity }\n end\n end\n end", "def components\n\t return JSON.parse(get(\"info/components.json\"))\n\tend", "def destroy\n @partner_org_component = PartnerOrgComponent.find(params[:id])\n @partner_org_component.destroy\n\n respond_to do |format|\n format.html { redirect_to partner_org_components_url }\n format.json { head :no_content }\n end\n end", "def update\n @partner_org_component = PartnerOrgComponent.find(params[:id])\n\n respond_to do |format|\n if @partner_org_component.update_attributes(params[:partner_org_component])\n format.html { redirect_to @partner_org_component, notice: 'Partner org component was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @partner_org_component.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_company_by_company_part\n @parts = CompaniesController::CompanyService.get_company_by_company_part(params[:param_part])\n if !@parts.nil?\n respond_to do |format|\n format.json{ render json: @parts}\n end \n else\n #não foi encontrado as informacoes\n end\n\tend", "def _find_org_components (org)\n comps = []\n if self.components.has_key?(org)\n comps << self.components[org]\n end\n return comps\n end", "def get_organization_info\n path = \"/d2l/api/lp/#{$lp_ver}/organization/info\"\n _get(path)\n # return: Organization JSON block\nend", "def get_component_family(opts)\n opts[:query]['all_elements'] = \"yes\"\n rest_crud_request(opts[:req_uri], opts[:query]['id'], opts[:format],\n {'Model Entity' => 'pack',\n 'Permission' => 'view'},\n opts[:user], opts[:query])\nend", "def index\n @partnering_organizations = PartneringOrganization.all\n end", "def show\n @component = service.components.find_by(slug: params[:id])\n\n render json: @component\n end", "def get_part_by_company_part\n @parts = PartsController::PartService.get_part_by_company_part(params[:param_part])\n if !@parts.nil?\n respond_to do |format|\n format.json{ render json: @parts}\n end \n else\n #não foi encontrado as informacoes\n end\n\tend", "def get_organizations\n params = {\n 'method' => :get,\n 'command' => '/org'\n }\n\n response, headers = send_request(params)\n orgs = response.css('OrgList Org')\n\n results = {}\n orgs.each do |org|\n results[org['name']] = org['href'].gsub(\"#{@api_url}/org/\", \"\")\n end\n results\n end", "def get_domain_competitors_us(params)\n send_get \"get_domain_competitors_us\", params\n end", "def index\n # @composers = Composer.all\n @composers = @category.composers \n\n render json: @composers \n end", "def index\n @components = Component.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @components }\n end\n end", "def index\n @partner_companies = PartnerCompany.all\n end", "def request_components; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /partner_org_components/new GET /partner_org_components/new.json
def new @partner_org_component = PartnerOrgComponent.new respond_to do |format| format.html # new.html.erb format.json { render json: @partner_org_component } end end
[ "def create\n @partner_org_component = PartnerOrgComponent.new(params[:partner_org_component])\n\n respond_to do |format|\n if @partner_org_component.save\n format.html { redirect_to @partner_org_component, notice: 'Partner org component was successfully created.' }\n format.json { render json: @partner_org_component, status: :created, location: @partner_org_component }\n else\n format.html { render action: \"new\" }\n format.json { render json: @partner_org_component.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @part_company = PartCompany.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @part_company }\n end\n end", "def new\n @partner = Admin::Partner.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @partner }\n end\n end", "def new\n @component = Component.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @component }\n end\n end", "def new\n @partner = Partner.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @partner }\n end\n end", "def new\n @componenttype = Componenttype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @componenttype }\n end\n end", "def new\n @component_type = ComponentType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @component_type }\n end\n end", "def new\n @finding_component = FindingComponent.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @finding_component }\n end\n end", "def new\n @contact_partner = ContactPartner.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contact_partner }\n end\n end", "def new\n @component_model = ComponentModel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @component_model }\n end\n end", "def new\n @component = Component.new\n @new_component = 'true'\n list_components\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @component }\n end\n end", "def new\n @partner_type = PartnerType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @partner_type }\n end\n end", "def new\n @toyota_epc_part_number_application_to_models_parent = ToyotaEpc::PartNumberApplicationToModelsParent.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @toyota_epc_part_number_application_to_models_parent }\n end\n end", "def new\r\n @org = Org.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @org }\r\n end\r\n end", "def new\n @componente = Componente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @componente }\n end\n end", "def new\n @provider = current_company.providers.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end", "def new\n @component = current_cms.components.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @component }\n end\n end", "def new\n @serviceorg = Serviceorg.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @serviceorg }\n end\n end", "def create\n @component = service.components.new(component_params)\n\n if @component.save\n render json: @component, status: :created, location: @component\n else\n render json: @component.errors, status: :unprocessable_entity\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /partner_org_components POST /partner_org_components.json
def create @partner_org_component = PartnerOrgComponent.new(params[:partner_org_component]) respond_to do |format| if @partner_org_component.save format.html { redirect_to @partner_org_component, notice: 'Partner org component was successfully created.' } format.json { render json: @partner_org_component, status: :created, location: @partner_org_component } else format.html { render action: "new" } format.json { render json: @partner_org_component.errors, status: :unprocessable_entity } end end end
[ "def new\n @partner_org_component = PartnerOrgComponent.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @partner_org_component }\n end\n end", "def update\n @partner_org_component = PartnerOrgComponent.find(params[:id])\n\n respond_to do |format|\n if @partner_org_component.update_attributes(params[:partner_org_component])\n format.html { redirect_to @partner_org_component, notice: 'Partner org component was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @partner_org_component.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @partner_org_component = PartnerOrgComponent.find(params[:id])\n @partner_org_component.destroy\n\n respond_to do |format|\n format.html { redirect_to partner_org_components_url }\n format.json { head :no_content }\n end\n end", "def post_event_course_org\n course = Course.find_or_initialize_by(id: params[:course][:id])\n authorize course unless course.new_record?\n\n organization = Organization.find_or_initialize_by(id: params[:organization][:id])\n authorize organization unless organization.new_record?\n\n setter = EventCourseOrgSetter.new(event: @event, course: course, organization: organization, params: params)\n setter.set_resources\n if setter.status == :ok\n render json: setter.resources.map { |resource| [resource.class.to_s.underscore, resource.to_json] }.to_h, status: setter.status\n else\n render json: {errors: setter.resources.map { |resource| jsonapi_error_object(resource) }}, status: setter.status\n end\n end", "def test_get_org_components\n org = Components[1]\n comps = @jira._find_org_components(org)\n\n assert_equal(1, comps.size)\n assert_equal(org, comps[0].name)\n end", "def create\n @partnering_organization = PartneringOrganization.new(partnering_organization_params)\n respond_to do |format|\n if @partnering_organization.save\n format.html { redirect_to @partnering_organization, notice: 'Partnering organization was successfully created.' }\n format.json { render :show, status: :created, location: @partnering_organization }\n else\n format.html { render :new }\n format.json { render json: @partnering_organization.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @partnering_organization = PartneringOrganization.new(partnering_organization_params)\n\n respond_to do |format|\n if @partnering_organization.save\n format.html { redirect_to @partnering_organization, notice: 'Partnering organization was successfully created.' }\n format.json { render :show, status: :created, location: @partnering_organization }\n else\n format.html { render :new }\n format.json { render json: @partnering_organization.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @partner = Partner.new(params[:partner])\n @company = Company.find(params[:company_id])\n @partner.company = @company\n @partner.save\n\n respond_to do |format|\n if @partner.save\n format.html { redirect_to @partner}\n format.json { render json: @partner, status: :created, location: @partner }\n else\n format.html { render action: \"new\" }\n format.json { render json: @partner.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @component = service.components.new(component_params)\n\n if @component.save\n render json: @component, status: :created, location: @component\n else\n render json: @component.errors, status: :unprocessable_entity\n end\n end", "def post_event_course_org\n event = params[:id] == 'new' ? Event.new : Event.friendly.find(params[:id])\n\n # This should change to params.dig(:event_group, :id) when the event-staging app supports event_groups\n event_group = EventGroup.find_or_initialize_by(id: event.event_group_id)\n course = Course.find_or_initialize_by(id: params.dig(:course, :id))\n organization = Organization.find_or_initialize_by(id: params.dig(:organization, :id))\n\n persisted_resources = [event, event_group, course, organization].select(&:persisted?)\n skip_authorization if persisted_resources.empty?\n persisted_resources.each { |resource| authorize resource }\n\n setter = EventCourseOrgSetter.new(event: event, event_group: event_group, course: course, organization: organization, params: params)\n setter.set_resources\n if setter.status == :ok\n render json: setter.resources.map { |resource| [resource.class.to_s.underscore, resource] }.to_h, status: setter.status\n else\n render json: {errors: setter.resources.map { |resource| jsonapi_error_object(resource) }}, status: setter.status\n end\n end", "def post_component_family(opts)\n # Get the component profile\n data = LibXML::XML::Parser.string(request.raw_post).parse\n component_profile_uri = parse_element(data, :text, '/pack/component-profile')\n\n unless component_profile_uri\n return rest_response(400, :reason => \"Missing component profile URI\")\n end\n\n component_profile = resource_from_uri(component_profile_uri)\n\n if component_profile.nil?\n return rest_response(404, :reason => \"No component profile found at: #{component_profile_uri}\")\n elsif !component_profile.is_a?(Blob) && !component_profile.is_a?(BlobVersion)\n return rest_response(400, :reason => \"#{component_profile_uri} is not a valid component profile (not a file)\")\n elsif component_profile.content_type.mime_type != 'application/vnd.taverna.component-profile+xml'\n return rest_response(400, :reason => \"#{component_profile_uri} is not a valid component profile (wrong MIME type)\")\n end\n\n # Create the component family\n response = pack_aux('create', opts)\n\n # Awful hack to get the newly created component family\n family = resource_from_uri(response[:xml].find_first('//pack')['resource'])\n\n # Add the profile\n if component_profile.is_a?(Blob)\n PackContributableEntry.create(:pack => family, :contributable => component_profile, :user => opts[:user])\n elsif component_profile.is_a?(BlobVersion)\n PackContributableEntry.create(:pack => family, :contributable => component_profile.blob,\n :contributable_version => component_profile.version, :user => opts[:user])\n end\n\n # Add the tag\n tag = Tag.find_or_create_by_name('component family')\n Tagging.create(:tag => tag, :taggable => family, :user => opts[:user])\n\n # Return resource\n rest_get_request(family, opts[:user], { \"id\" => family.id.to_s })\nend", "def new_partner\n @contact_person = ContactPerson.create(:name => params[:cp_name], :phone_number => params[:cp_phone], :email => params[:cp_email])\n @address = Address.create(:street => params[:address_street], :city => params[:address_city], :zip_code => params[:address_zip], :state => params[:address_state])\n @partner = Partner.create(:name => params[:partner_name], :address_id => @address.id, :contact_person_id => @contact_person.id)\n \n @content_type = 2\n render \"new_whatever.js.erb\"\n end", "def create\n @fdn_party_org = Fdn::PartyOrg.new(fdn_party_org_params)\n\n respond_to do |format|\n if @fdn_party_org.save\n format.html { redirect_to @fdn_party_org, notice: 'Party org was successfully created.' }\n format.json { render :show, status: :created, location: @fdn_party_org }\n else\n format.html { render :new }\n format.json { render json: @fdn_party_org.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company_partner = CompanyPartner.new(company_partner_params)\n\n respond_to do |format|\n if @company_partner.save\n format.js { render layout:false }\n format.html { redirect_to company_partners_path, notice: 'Company partner was successfully created.' }\n format.json { render :show, status: :created, location: @company_partner }\n else\n format.js { render layout:false }\n format.html { render :new }\n format.json { render json: @company_partner.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @partner_company = PartnerCompany.new(partner_company_params)\n\n respond_to do |format|\n if @partner_company.save\n format.html { redirect_to @partner_company, notice: 'Partner Company was successfully created.' }\n format.json { render :show, status: :created, location: @partner_company }\n else\n format.html { render :new }\n format.json { render json: @partner_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @partner_org_component = PartnerOrgComponent.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @partner_org_component }\n end\n end", "def create\n @ctep_org_type = CtepOrgType.new(ctep_org_type_params)\n\n respond_to do |format|\n if @ctep_org_type.save\n format.html { redirect_to @ctep_org_type, notice: 'Ctep org type was successfully created.' }\n format.json { render :show, status: :created, location: @ctep_org_type }\n else\n format.html { render :new }\n format.json { render json: @ctep_org_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def CreateOrganization params = {}\n \n APICall(path: 'organizations.json',method: 'POST',payload: params.to_json)\n \n end", "def provide_org_on_platform\n @platform_service.call(\n org: @params[:org],\n username: @params[:username],\n org_handle: @params[:org_handle],\n email: @params[:email],\n first_name: @params[:first_name],\n last_name: @params[:last_name],\n )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /partner_org_components/1 PUT /partner_org_components/1.json
def update @partner_org_component = PartnerOrgComponent.find(params[:id]) respond_to do |format| if @partner_org_component.update_attributes(params[:partner_org_component]) format.html { redirect_to @partner_org_component, notice: 'Partner org component was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @partner_org_component.errors, status: :unprocessable_entity } end end end
[ "def create\n @partner_org_component = PartnerOrgComponent.new(params[:partner_org_component])\n\n respond_to do |format|\n if @partner_org_component.save\n format.html { redirect_to @partner_org_component, notice: 'Partner org component was successfully created.' }\n format.json { render json: @partner_org_component, status: :created, location: @partner_org_component }\n else\n format.html { render action: \"new\" }\n format.json { render json: @partner_org_component.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @partner_org_component = PartnerOrgComponent.find(params[:id])\n @partner_org_component.destroy\n\n respond_to do |format|\n format.html { redirect_to partner_org_components_url }\n format.json { head :no_content }\n end\n end", "def new\n @partner_org_component = PartnerOrgComponent.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @partner_org_component }\n end\n end", "def update\n respond_to do |format|\n if @company_partner.update(company_partner_params)\n format.html { redirect_to company_partners_path, notice: 'Company partner was successfully updated.' }\n format.json { render :show, status: :ok, location: @company_partner }\n else\n format.html { render :edit }\n format.json { render json: @company_partner.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @partner_company.update(partner_company_params)\n format.html { redirect_to @partner_company, notice: 'Partner Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @partner_company }\n else\n format.html { render :edit }\n format.json { render json: @partner_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @component = service.components.find_by!(slug: params[:id])\n\n if @component.update(component_params)\n head :no_content\n else\n render json: @component.errors, status: :unprocessable_entity\n end\n end", "def change_partner\n get_provider\n get_partner\n get_application_plan\n @provider.partner = @partner # could be nil\n @provider.save\n @provider.force_upgrade_to_provider_plan!(@application_plan)\n render json: @provider.as_json(include: [:bought_cinstance, :partner])\n end", "def update\n respond_to do |format|\n if @partnering_organization.update(partnering_organization_params)\n format.html { redirect_to @partnering_organization, notice: 'Partnering organization was successfully updated.' }\n format.json { render :show, status: :ok, location: @partnering_organization }\n else\n format.html { render :edit }\n format.json { render json: @partnering_organization.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @partner_org_component = PartnerOrgComponent.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @partner_org_component }\n end\n end", "def update\n @partner_person = PartnerPerson.find(params[:id])\n @title = \"association partner <--> people\"\n\n respond_to do |format|\n if @partner_person.update_attributes(params[:partner_person])\n format.html { redirect_to(@partner_person, :notice => 'PartnerPerson was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @partner_person.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update(name: nil)\n data = name.nil? ? {} : {name: name}\n cf_patch(path: \"/organizations/#{org_id}\", data: data)\n end", "def update_organization_from_company\n organization_id = 0;\n \n if params[:box] != '0'\n company = Company.find(params[:box])\n if !company.nil?\n organization_id = company.organization_id\n end\n end\n\n @json_data = { \"organization_id\" => organization_id }\n\n respond_to do |format|\n format.html # update_company_organization_from_office.html.erb does not exist! JSON only\n format.json { render json: @json_data }\n end\n end", "def update\n @component = Component.find(params[:component][:id])\n\n respond_to do |format|\n if @component.update_attributes(params[:component])\n format.xml { head :ok }\n end\n end\n end", "def update\n respond_to do |format|\n if @ctep_org_type.update(ctep_org_type_params)\n format.html { redirect_to @ctep_org_type, notice: 'Ctep org type was successfully updated.' }\n format.json { render :show, status: :ok, location: @ctep_org_type }\n else\n format.html { render :edit }\n format.json { render json: @ctep_org_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @user_org = UserOrg.find(params[:id])\n\n if @user_org.update(user_org_params)\n head :no_content\n else\n render json: @user_org.errors, status: :unprocessable_entity\n end\n end", "def update\n @optinpartner = Optinpartner.find(params[:id])\n\n respond_to do |format|\n if @optinpartner.update_attributes(params[:optinpartner])\n format.html { redirect_to @optinpartner, notice: 'Optinpartner was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @optinpartner.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fdn_party_org.update(fdn_party_org_params)\n format.html { redirect_to @fdn_party_org, notice: 'Party org was successfully updated.' }\n format.json { render :show, status: :ok, location: @fdn_party_org }\n else\n format.html { render :edit }\n format.json { render json: @fdn_party_org.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @partner = Admin::Partner.find(params[:id])\n\n respond_to do |format|\n if @partner.update_attributes(params[:admin_partner])\n format.html { redirect_to @partner, notice: 'Partner was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @partner.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @eg_component.update(eg_component_params)\n format.html { redirect_to @eg_component, notice: 'Eg component was successfully updated.' }\n format.json { render :show, status: :ok, location: @eg_component }\n else\n format.html { render :edit }\n format.json { render json: @eg_component.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /partner_org_components/1 DELETE /partner_org_components/1.json
def destroy @partner_org_component = PartnerOrgComponent.find(params[:id]) @partner_org_component.destroy respond_to do |format| format.html { redirect_to partner_org_components_url } format.json { head :no_content } end end
[ "def destroy\n @allergen_component.destroy\n respond_to do |format|\n format.html { redirect_to allergen_components_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @business_partner.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 @partner = Admin::Partner.find(params[:id])\n @partner.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_partners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_partner = Admin::Partner.find(params[:id])\n @admin_partner.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_partners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @potential_partner.destroy\n respond_to do |format|\n format.html { redirect_to potential_partners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @contact_partner = ContactPartner.find(params[:id])\n @contact_partner.destroy\n\n respond_to do |format|\n format.html { redirect_to contact_partners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @partner_company.destroy\n respond_to do |format|\n format.html { redirect_to partner_companies_url, notice: 'Partner Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @componente = Componente.find(params[:id])\n @componente.destroy\n\n respond_to do |format|\n format.html { redirect_to componentes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @content_partner = ContentPartner.find(params[:id])\n @content_partner.destroy\n\n respond_to do |format|\n format.html { redirect_to content_partners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_partner.destroy\n respond_to do |format|\n format.html { redirect_to company_partners_url, notice: 'Company partner was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @partner = Partner.find(params[:id])\n @partner.destroy\n\n respond_to do |format|\n format.html { redirect_to partners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @part_company = PartCompany.find(params[:id])\n @part_company.destroy\n\n respond_to do |format|\n format.html { redirect_to part_companies_url }\n format.json { head :ok }\n end\n end", "def destroy\n @eg_component.destroy\n respond_to do |format|\n format.html { redirect_to eg_components_url, notice: 'Eg component was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @optinpartner = Optinpartner.find(params[:id])\n @optinpartner.destroy\n\n respond_to do |format|\n format.html { redirect_to optinpartners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @partner = Partner.find(params[:id])\n @partner.destroy\n\n respond_to do |format|\n format.html { redirect_to partners_url }\n format.json { head :ok }\n end\n end", "def destroy\n @component = Component.find(params[:id])\n @component.destroy\n\n respond_to do |format|\n format.html { redirect_to components_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @component = Component.find(params[:id])\n @component.destroy\n \n respond_to do |format|\n format.html { redirect_to(components_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @our_partner = OurPartner.find(params[:id])\n @our_partner.destroy\n\n respond_to do |format|\n format.html { redirect_to our_partners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ctep_org_type.destroy\n respond_to do |format|\n format.html { redirect_to ctep_org_types_url, notice: 'Ctep org type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a partial is a cell or not
def cell?(partial_path) partial_path.end_with? '.rb' end
[ "def can_have_cells?\n definition['cells'].present?\n end", "def o_in_cell?\n\n end", "def partial?\n @object.type == :partial\n end", "def has_cells?\n cells.any?\n end", "def has_cells?\n not @cells.empty?\n end", "def partial?\n qualification == :partial\n end", "def matches?(cell); end", "def find_partial(*)\n super.tap do |partial|\n cell = CellUtils.find_cell(partial.identifier, partial.inspect)\n raise CellHandling, cell if cell\n end\n end", "def is_start?(cell)\n @start_cell.eql?(cell)\n end", "def partial?(template)\n !!template.virtual_path.partial? rescue false\n end", "def x_in_cell?\n\n end", "def partial_column?( col_index )\n\n# [TODO] Doesn't work, because col_range accurately reflects the column range\n# rather than the quantised range. Getting at the latter is tricky, so\n# leaving this for later. At present the method is only used for display\n# purposes in the column headings.\n\n col_range = @column_ranges[ col_index ]\n return ( col_range.min < @range.min or col_range.max > @range.max )\n end", "def partial_column?( range )\n if ( range == @column_ranges.first )\n @column_first_partial\n elsif ( range == @column_ranges.last )\n @column_last_partial\n else\n false\n end\n end", "def has_own_partial?(name)\n view_paths.find_template(\"_#{name}\", default_template_format) != nil\n rescue ActionView::MissingTemplate\n return false\n end", "def empty?(cell)\n\t\tcell == 0 || cell == @@FRONTIER\n\tend", "def partially_magic?(idx)\n cells = []\n\n _idx = idx + 1 # as if cells are numbered from 1\n\n # if the cell ends a row\n if _idx >= @ncols && _idx % @ncols == 0\n r = idx / @nrows\n return false unless sum(row(r)) == @expected_sum\n end\n\n # if the cell ends a column\n if _idx > ncells-ncols\n c = idx % @nrows\n return false unless sum(column(c)) == @expected_sum\n end\n\n # if the cell ends the / diagonal\n if idx == ncells-ncols\n return false unless sum(secondary_diagonal) == @expected_sum\n end\n\n # if the cell ends the \\ diagonal\n if _idx == ncells\n return false unless sum(primary_diagonal) == @expected_sum\n end\n\n true\n end", "def is_colrow?(); @type == GRT_COLROW; end", "def partial_in_use?\n self.partial? and self.mail_templates.count > 0\n end", "def has_col?(str)\n str =~ /\\A\\s*<td\\b/i\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the command ImageMagick's +composite+ needs to transform the image into the white_canvas 1008x1152.
def white_canvas_composite trans = [] trans << "convert " << trans end
[ "def composite(image, opts = {})\n image_path = image.is_a?(Image) ? image.path : image\n args = hash_to_args(opts) + [image_path, @path, @path]\n run_command('composite', *args)\n self\n end", "def composite(image_data, options = {})\n info = SmartImage.info image_data\n opts = {\n :width => info.width,\n :height => info.height,\n :x => 0,\n :y => 0\n }.merge(options)\n \n input_stream = ByteArrayInputStream.new image_data.to_java_bytes\n image = ImageIO.read input_stream\n raise FormatError, \"invalid image\" unless image\n \n graphics = @canvas.graphics\n graphics.draw_image image, opts[:x], opts[:y], opts[:width], opts[:height], nil\n end", "def composite(arguments = \"\", local_options = {})\n Paperclip.run('composite', arguments, local_options)\n end", "def composite_class\n Command::Composite\n end", "def composite!(output, args={})\n tokens = [\"composite\"]\n tokens << convert_to_arguments(args) if args\n tokens << \" '#{@file}#{\"[#{args[:layer].to_s}]\" if args[:layer]}'\"\n tokens << \" -annotate #{args[:annotate].to_s}\" if args[:annotate]\n tokens = convert_to_command(tokens)\n success = run(tokens)[1]\n success\n end", "def composite(data, options = {})\n info = self.class.info data\n \n opts = {\n :x => 0,\n :y => 0,\n :width => info.width,\n :height => info.height,\n :preserve_aspect_ratio => true\n }.merge(options)\n \n dest_width, dest_height = self.class.calculate_aspect_ratio info, opts\n \n @canvas.composite data, :width => Integer(dest_width),\n :height => Integer(dest_height),\n :x => opts[:x], \n :y => opts[:y]\n end", "def custom_commands\n rotate_to = model.rotate_to.nil? ? 0 : model.rotate_to\n\n crop = ImageCrop.from_json(model.crop_json)\n crop_cmd = crop.crop_str(model.width, model.height) unless crop.nil?\n\n custom_command = crop_cmd || ''\n custom_command << \" -rotate #{rotate_to}\" if rotate_to != 0\n custom_command.empty? ? nil : custom_command\n end", "def composite canvas, x, y, style = :overwrite\n canvas.each do |x1, y1, color|\n case style\n when :overwrite then\n self[x+x1, y+y1] = color\n when :add, :underlay then\n self[x+x1, y+y1] = self[x+x1, y+y1] | color\n when :overlay then\n self[x+x1, y+y1] = color | self[x+x1, y+y1]\n when :blend then\n self.point x+x1, y+y1, color\n else\n raise \"unknown style for composite: #{style.inspect}\"\n end\n end\n end", "def composite_operation(img, x_offset, y_offset, composite_op)\n @semaphore.synchronize {\n @buffer.composite!(img, x_offset.to_i, y_offset.to_i, composite_op)\n }\n end", "def create_blank_canvas(width, height, color, out_file)\n IO.popen(\"convert -size #{width}x#{height} xc:#{color} #{out_file}\")\n Process.wait\n # TODO: check for result, raise an exception when there is an error\n end", "def composite(other_image, x, y, mode)\n\t # if other_image has no alpha, we can just paste it straight in, no\n\t # compositing required\n\t if not other_image.alpha?\n\t if alpha?\n\t return insert_noexpand other_image.add_alpha, x, y\n\t else\n\t return insert_noexpand other_image, x, y\n\t end\n\t end\n\t\n\t # we need to composite -- pull out the area we will be overlaying, \n\t # blend the two images and the two alpha channels, paste back again\n\t\n\t # we need to find the rect common to both images\n\n\t h = Set.new(0 ... x_size).intersection(Set.new(x ... (x + other_image.x_size)))\n\t v = Set.new(0 ... y_size).intersection(Set.new(y ... (y + other_image.y_size)))\n\t\n\t # no overlap ... other_image is not visible, just return the \n\t # background\n\t if h.empty? or v.empty?\n\t return self\n\t end\n\t\n\t bg = extract_area h.first, v.first, h.length, v.length \n\t fg = other_image.extract_area h.first - x, v.first - y, h.length, v.length \n\t a1 = fg.get_alpha.lin(1.0 / 255.0, 0)\n\t a2 = bg.get_alpha.lin(1.0 / 255.0, 0)\n\t\n\t c1 = fg.get_image\n\t c2 = bg.get_image\n\t\n\t case mode\n\t when :over\n\t a = a1 + a2 * a1.lin(-1, 1)\n\t c = (c1 * a1 + c2 * a2 * a1.lin(-1, 1)) / a\n\t\n\t else\n\t raise \"bad compositing mode\"\n\t end\n\t\n\t a = a.lin(255.0, 0).clip2fmt(:uchar)\n\t c = c.clip2fmt(band_fmt)\n\t\n\t if alpha?\n\t insert_noexpand c.bandjoin(a), h.first, v.first\n\t else\n\t insert_noexpand c, h.first, v.first\n\t end\n\t end", "def commands\n commands = []\n return commands unless should_process?\n if should_crop?\n size = resize_string + '^'\n # Note: ordering is important.\n commands << '-background' << 'none'\n commands << '-thumbnail' << size\n commands << '-gravity' << gravity\n commands << '-extent' << size\n elsif should_scale?\n commands << \"-thumbnail\" << resize_string\n end\n commands << \"-quality\" << \"75\"\n end", "def composite_images(dest_image, src_image, x, y)\n\t\twidth = [src_image.columns + x, dest_image.columns].max\n\t\theight = [src_image.rows + y, dest_image.rows].max\n\t\timage = Magick::Image.new(width, height) {self.background_color = 'none'}\n\t\timage.composite!(dest_image, 0, 0, Magick::CopyCompositeOp)\n\t\timage.composite!(src_image, x, y, Magick::CopyCompositeOp)\n\t\timage\n\tend", "def composite overlay, mode, **opts\n unless overlay.is_a? Array\n overlay = [overlay]\n end\n unless mode.is_a? Array\n mode = [mode]\n end\n\n mode = mode.map do |x|\n GObject::GValue.from_nick Vips::BLEND_MODE_TYPE, x\n end\n\n Vips::Image.composite([self] + overlay, mode, **opts)\n end", "def generate_convert_command(temp_file)\n cmd = [@options[:convert_command]]\n input_opt = @options[:convert_options][:input]\n output_opt = @options[:convert_options][:output]\n\n cmd += input_opt unless input_opt.empty?\n cmd << Shellwords.shellescape(@image.to_s)\n cmd += output_opt unless output_opt.empty?\n cmd << temp_file.to_s\n cmd.join(\" \")\n end", "def apply_copy(parsed_instr)\n layer = parsed_instr[:src_layer]\n dst_layer = parsed_instr[:dst_layer]\n if layer.to_i != 0\n if @png_buffer[layer]\n img = @png_buffer[layer].crop(parsed_instr[:src_x_offset].to_i, \n parsed_instr[:src_y_offset].to_i, parsed_instr[:src_width].to_i, \n parsed_instr[:src_height].to_i)\n if dst_layer.to_i == 0\n composite_operation(img, parsed_instr[:x_offset].to_i, \n parsed_instr[:y_offset].to_i, Magick::OverCompositeOp)\n else\n img = @png_buffer[layer].crop(parsed_instr[:src_x_offset].to_i, \n parsed_instr[:src_y_offset].to_i, parsed_instr[:src_width].to_i, \n parsed_instr[:src_height].to_i)\n if @png_buffer[dst_layer]\n @png_buffer[dst_layer].composite!(img, parsed_instr[:x_offset].to_i, \n parsed_instr[:y_offset].to_i, Magick::OverCompositeOp)\n end\n end \n end \n elsif layer.to_i == 0\n img = @buffer.crop(parsed_instr[:src_x_offset].to_i, \n parsed_instr[:src_y_offset].to_i, parsed_instr[:src_width].to_i, \n parsed_instr[:src_height].to_i)\n if dst_layer.to_i == 0\n composite_operation(img, parsed_instr[:x_offset], \n parsed_instr[:y_offset], Magick::OverCompositeOp)\n else\n @png_buffer[dst_layer] = img\n end \n end\n end", "def imagemagick?; end", "def make\n src = @file\n dst = Tempfile.new(@basename)\n dst.binmode\n\n command = <<-end_command\n #{transformation_command}\n \"#{File.expand_path(src.path)}[0]\"\n \"#{File.expand_path(dst.path)}\"\n end_command\n\n begin\n success = Paperclip.run('composite', command.gsub(/\\s+/, ' '))\n rescue PaperclipCommandLineError\n raise PaperclipError, \"There was an error processing the watermark for #{@basename}\" if @whiny\n end\n\n dst\n end", "def maincolor(image)\n options = [\n image.shellescape,\n '-scale 1x1!',\n \"-format '%[pixel:u]'\",\n 'info:-'\n ]\n command = \"convert #{options.join(' ')}\"\n raw = `#{command}`\n\n rgb2hex(raw)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively search AST for a node that matches the given type and name.
def grep_tree(node, type, name) walker = lambda do |n| n.children.each_with_object(nil) do |c, res| next unless c.kind_of?(Parser::AST::Node) break c if (c.type == type && c.location.name.source == name) if (res = walker.call(c)) break res end end end walker.call(node) end
[ "def by_type type\n -> (n) {\n n &&\n n.is_a?(AST::Node) &&\n n.type == type.to_sym\n }\n end", "def find_node ast, klass\n ast.find {|n| n.content.class == klass }\nend", "def find(name)\n @nodes.each do |node| \n return node if node.name == name\n end\n nil\n end", "def find_node(name)\n @nodes.each { |node| return node if node[:name] == name }\n end", "def search(node_name)\n tree_details[node_name]\n end", "def find_significant_nodes_with_name(type, name, with_children: true)\n find_significant_nodes(type, with_children: with_children).select { |node|\n node.name == name\n }\n end", "def find(kind, recurse = false, &block)\n children.each do |node|\n if node.kind == kind\n yield node\n elsif recurse\n node.find(kind, true, &block)\n end\n end\n end", "def find_node(name)\n @nodes.find { |node| node.name == name }\n end", "def find_nodes name\n each_sexp.find_all { |sexp| sexp.sexp_type == name }\n end", "def search_node(node, queried_node)\n return unless node&.is_a?(Parser::AST::Node)\n return node if node == queried_node\n\n node.children.each do |child_node|\n result = search_node(child_node, queried_node)\n return result if result\n end\n\n nil\n end", "def search(exp)\n nodes.find_all {|node| node.name =~ exp }\n end", "def find_by_name(name)\n types[name]\n end", "def find_node_by_name(name)\n @nodes[name]\n end", "def find_ruby_ast_node(ast_node, recurse = false, &block)\n raise ArgumentError, 'find_ruby_ast_node requires a block' unless block\n\n is_found = yield ast_node\n return ast_node if is_found\n\n if ast_node.respond_to?(:children)\n ast_node.children.each do |child_node|\n child_found = find_ruby_ast_node(child_node, recurse, &block)\n return child_found unless child_found.nil?\n end\n end\n nil\n end", "def search(root, keytype, key, l)\n l.push(root) if root.match(keytype, key)\n root.children.each {|node| search(node, keytype, key, l) } \\\n if root.children.length > 0\n end", "def search(*names)\n return nil if names.empty?\n find children, names\n end", "def find_type(name)\n @types[name]\n end", "def lookup(type, name)\n type, name = prepare_lookup(type, name)\n found = nil\n\n if defines?(type, name)\n found = definitions[type][name]\n\n # Look up the definition in the parent scope(s) (if any are set).\n elsif lookup_parent?(type)\n parents.each do |parent|\n parent_definition = parent.lookup(type, name)\n\n if parent_definition\n found = parent_definition\n break\n end\n end\n end\n\n return found\n end", "def find_node(name)\n if self.name == name\n return self\n end\n\n # Check the left side\n unless self.left_child.nil?\n left_node = self.left_child.find_node(name)\n end\n\n if left_node.nil?\n # Check the right side\n unless self.right_child.nil?\n return self.right_child.find_node(name)\n end\n else\n return left_node\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shifts the read position at the given +depth+ along by one, by adding
def shift!(depth) return if depth > @depth indexes[depth] += 1 indexes[depth] = 0 if indexes[depth] >= current(depth).size end
[ "def update_depth\n @depth = 1\n end", "def set_depth(depth)\n @depth = depth\n left.set_depth(depth+1) if left != nil\n right.set_depth(depth+1) if right != nil\n end", "def increase_magnitude(val, depth)\n return val if val.zero?\n val.positive? ? (val + depth) : (val - depth)\n end", "def add_by_depth(depth, token, tree = @tree)\n return unless tree.is_a? Array\n\n if depth.zero?\n tree.push token\n elsif tree.last.is_a? Array\n add_by_depth(depth - 1, token, tree.last)\n else\n tree.push []\n add_by_depth(depth - 1, token, tree.last)\n end\n\n tree\n end", "def depth\n unit.depth + 1\n end", "def fbe_shift(offset)\n @_offset += offset\n end", "def set_fix_depth(depth)\n @fix_depth = depth\n left.set_fix_depth(depth+1) if left != nil\n right.set_fix_depth(depth+1) if right != nil\n end", "def advance_read_pointer\n @read_pointer = (@read_pointer + 1) % @size\n end", "def unshift(offset)\n @_buffer.unshift(offset)\n end", "def increment_levels(offset=0)\n set_level(offset)\n unless leaf?\n children.each{|t| t.set_level}\n end\n end", "def update_bush_depth\r\n bsp = @bush_depth_sprite\r\n bsp.z = z\r\n bsp.set_position(x, y)\r\n bsp.zoom = zoom_x\r\n bsp.bitmap = bitmap if bsp.bitmap != bitmap\r\n rc = bsp.src_rect\r\n h = @height\r\n bd = @bush_depth / 2\r\n (rc2 = src_rect).height = h - bd\r\n bsp.set_origin(ox, bd)\r\n rc.set(rc2.x, rc2.y + rc2.height, rc2.width, bd)\r\n end", "def increment_levels(i)\n @level += i\n end", "def slew_pos(pos, factor)\n @pos += (pos - @pos)*factor\n end", "def add_nesting_level\n @cache << @cache[-1].next_level\n end", "def compute_depth(depth)\n @depth = depth\n child_depth = transactions\n .map { |trsc| trsc.compute_depth(depth + 1) }\n .max\n child_depth || depth\n end", "def advance_write_pointer\n @write_pointer = (@write_pointer + 1) % @size\n end", "def read_and_advance(length)\n data = nil\n cursor_start = current.position\n case current.direction\n when :forward\n data = @buffer.slice(current.position, length)\n adjust(length)\n when :backward\n adjust(-length)\n data = @buffer.slice(current.position, length)\n end\n\n record_trace(cursor_start, data.bytes, current.name)\n data\n end", "def enter(node, depth)\n transform(node)\n end", "def do_deprecated_depth\n assert_equal(1, @root.depth, \"A single node's depth is 1\")\n\n @root << @child1\n assert_equal(2, @root.depth, \"This should be of depth 2\")\n\n @root << @child2\n assert_equal(2, @root.depth, \"This should be of depth 2\")\n\n @child2 << @child3\n assert_equal(3, @root.depth, \"This should be of depth 3\")\n assert_equal(2, @child2.depth, \"This should be of depth 2\")\n\n @child3 << @child4\n assert_equal(4, @root.depth, \"This should be of depth 4\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of matches (or groups of matches) on the current read branch at the given +depth+. Returns zero if no branch exists at the given indexes.
def size(depth) return nil if depth > @depth current(depth).size rescue 0 end
[ "def score_at(depth)\n return self.citations.count * depth\n end", "def num_tree_levels\n level = 0\n num_nodes= all_node_values_with_nil.length # considers tree as 'complete\n num_nodes_in_full_tree = 2**level\n until num_nodes_in_full_tree >= num_nodes\n level += 1\n num_nodes_in_full_tree += 2**level\n end\n num_tree_levels = level + 1 # (started count at 0)\n num_tree_levels = 0 if @root.nil?\n return num_tree_levels\n end", "def depth\n if empty?\n 0\n else\n if @left==nil || @right==nil\n if (@left==nil&&@right==nil) then 1\n else -1\n end\n else\n left, right = @left.depth, @right.depth\n if left==-1||right==-1||left!=right then -1\n else 1+left\n end\n end\n end\n end", "def depth\n @levels.size\n end", "def compute_depth(depth)\n @depth = depth\n child_depth = transactions\n .map { |trsc| trsc.compute_depth(depth + 1) }\n .max\n child_depth || depth\n end", "def tree_width\n num_branches = 0\n ancestry = self.steps.pluck(:ancestry)\n repeat_ancestry = ancestry.group_by {|e| e}.select { |k,v| v.size > 1}.keys\n repeat_ancestry.each do |value|\n num_branches = num_branches + ancestry.grep(value).size\n end\n return num_branches\n end", "def depth\n @stack.length\n end", "def depth_of(score, current = @head, count = 0)\n if current.score == nil\n nil\n elsif current.score > score\n count += 1 \n depth_of(score, current.left, count)\n elsif\n current.score < score \n count += 1\n depth_of(score, current.right, count)\n else\n count\n end\n end", "def scanDepth\r\n return caller(2).find_all {|frame|\r\n frame =~ /in `scan(Variable|Tagged|Codeblock|Bracketed|Quotelike)'/\r\n }.length\r\n end", "def leaf_count(tree = self)\n if tree.leaf?\n 1\n else\n tree.children.inject(0) { |a, e| a + leaf_count(e) }\n end\n end", "def depth\n level = 0\n scopelist=[]\n if (doe_scope == \"hvac\")\n scopelist = @hvacLevel\n else\n scopelist = @envelopeLevel\n end\n scopelist.each_index do |index|\n scopelist[index].each do |name|\n if (@commandName == name )\n level = index\n end\n end\n end\n return level\n end", "def get_matched_size(lines, patterns)\n i = 0\n found = true\n patterns.each do |pattern|\n unless lines[i]\n found = false\n break\n end\n\n while true\n match = pattern.match lines[i]\n if not match\n found = false\n break\n # Match precisely for the first line of pattern (i==0),\n # Not pass blank lines.\n elsif match == 0 and i == 0\n found = false\n break\n # Matched.\n elsif match > 0\n break\n # Match next line if this line is blank.\n elsif match == 0\n i += 1\n unless lines[i]\n found = false\n break\n end\n # Never comes here.\n else\n found = false\n break\n end\n end\n\n break unless found\n i += 1\n end\n\n if found\n i\n else\n nil\n end\n end", "def index_depth\n @index_depth ||= first_record_key[/\\+*/].length\n end", "def leaf_count(tree=self)\n if tree.leaf?\n 1\n else\n tree.children.inject(0){|m,t| m += leaf_count(t)} \n end\n end", "def count_expression_logical_branches(expression)\n case expression\n when nil\n 0\n when Array\n expression.map { |exp| count_expression_logical_branches(exp) }.sum\n when Hash\n case expression['type']\n when 'And', 'Or', 'Not'\n count_expression_logical_branches(expression['operand'])\n when 'Query'\n # TODO: Do we need to look into the source side of the query? Can there be logical operators there?\n count_expression_logical_branches(expression['where']) + count_expression_logical_branches(expression['relationship'])\n else\n 1\n end\n else\n 0\n end\n end", "def depth\n breadcrumbs.size\n end", "def depth\n level = 0\n scopelist=[]\n if (doe_scope == \"hvac\")\n scopelist = @hvacLevel\n else\n scopelist = @envelopeLevel\n end\n scopelist.each_index do |index|\n scopelist[index].each do |name|\n if (@commandName == name )\n level = index\n end\n end\n end\n return level \n end", "def depth\n return 0 if self.class != Array\n result = 1\n self.each do |sub_a|\n if sub_a.class == Array\n dim = sub_a.depth\n result = dim + 1 if dim + 1 > result\n end\n end\n result\n end", "def descendants_count_bfs(options={})\n count = 0\n each_level_ids(options) do |level_ids|\n count += level_ids.count\n end\n return count\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the way to add columns to the set. this is primarily useful for virtual columns. note that this also makes columns inheritable
def add(*args) args.flatten! # allow [] as a param args = args.collect(&:to_sym) # make the columns inheritable @_inheritable.concat(args) # then add columns to @set (unless they already exist) args.each { |a| @set << ActiveScaffold::DataStructures::Column.new(a.to_sym, @active_record_class) unless find_by_name(a) } end
[ "def setup_columns\n if inheritable?\n Set.new([primary_key, inheritance_column])\n else\n primary_key.blank? ? Set.new : Set.new([primary_key])\n end \n end", "def setup_columns\n if inheritable?\n SimpleSet.new([primary_key, inheritance_column])\n else\n primary_key.blank? ? SimpleSet.new : SimpleSet.new([primary_key])\n end \n end", "def columns\n super + [:extra_column]\n end", "def add_column(column)\n super\n if @klass\n @klass.define_property_methods(column) if column.should_create_accessors?\n end\n end", "def add_columns_to columns\n @columns.each do | column |\n pos = columns.index column\n if pos.nil?\n columns << column\n pos = columns.size - 1\n end\n column.select_position = pos\n end\n end", "def add_column\n self.name = generate_column_name if name.blank?\n connection.add_column(table_name, name, column_type, column_options)\n klass.reset_column_information\n klass.serialize_custom_fields!\n end", "def add_columns(list)\n list.each { |obj| add_column(obj) }\n self\n end", "def add_columns(transaction, table_name, columns)\n Kernel.raise NotImplementedError\n end", "def columns\n @columns ||= self.class.columns.each { |c| c.datatable = self }\n end", "def set_columns(relation)\n @columns = columns_for(relation)\n end", "def add_column(*col)\n\t\t@columns += col\n\tend", "def new_column_definition(base, name, type)\n definition = ColumnDefinition.new base, name, type\n @columns << definition\n @columns_hash[name] = definition\n definition\n end", "def column(*new_column_args, &block)\n columns << ColumnDef.new(*new_column_args, &block)\n end", "def set_columns(new_columns)\n @columns = new_columns\n def_column_accessor(*new_columns) if new_columns\n @str_columns = nil\n @columns\n end", "def define_columns(columns_props_array)\n view.define_columns(columns_props_array)\n\n # Sync again after adding the columns.\n sync_ui_from_model\n end", "def add_columns!(*columns)\n columns.map { |c| add_column! c }\n end", "def add_column(c)\n @g << c\n end", "def columns\n unless @columns\n columns_without_localization\n @columns.each do |column|\n column.model_class = self\n end\n else\n columns_without_localization\n end\n end", "def columns\n collect = []\n recursive_columns(@base, collect)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the status of a transaction. When a transaction is posted to PesaPal, it may be in a `PENDING`, `COMPLETED` or `FAILED` state. If the transaction is `PENDING`, the payment may complete or fail at a later stage. ```ruby option 1: using merchant reference only payment_status = pesapal.query_payment_status("") option 2: using merchant reference and transaction id (recommended, see note for reason why) payment_status = pesapal.query_payment_status("","") ```
def query_payment_status(merchant_reference, transaction_tracking_id = nil) # initialize setting of @params (oauth_signature left empty) @params = Pesapal::Helper::Status.set_parameters(@config[:consumer_key], merchant_reference, transaction_tracking_id) # generate oauth signature and add signature to the request parameters @params[:oauth_signature] = Pesapal::Oauth.generate_oauth_signature('GET', @api_endpoints[:querypaymentstatus], @params, @config[:consumer_secret], @token_secret) # change params (with signature) to a query string query_string = Pesapal::Oauth.generate_encoded_params_query_string @params # get status response uri = URI.parse "#{@api_endpoints[:querypaymentstatus]}?#{query_string}" http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE response = http.request(Net::HTTP::Get.new(uri.request_uri)) response = CGI.parse response.body response['pesapal_response_data'][0] end
[ "def check_transaction_status\n data = basic_credentials.merge(\n 'x_trans_key' => @x_trans_key,\n 'x_invoice_num' => invoice_num,\n 'x_type' => (type || 0)\n )\n\n astro_curl(@transtatus_url, data)\n end", "def query_status(params, path_url = 'payment_requests', class_type = 'STK')\n super\n end", "def get_merchant_status\n\t\tstatus = 'Pending'\n\t\tif self.paid?\n\t\t\tstatus = \"Paid\"\n\t\telsif self.fullfilled?\n\t\t\tstatus = \"Fullfilled\"\n\t\telsif self.cancelled?\n\t\t\tstatus = \"Cancelled\"\n\t\tend\n\t\tstatus\n\tend", "def payment_status\n payload[\"payment_status\"]\n end", "def get_transaction_status(options = {})\n requires! options, :reference_number\n\n request = build_request(__method__, options)\n commit(__method__, request)\n end", "def status\n if params['fraud_status'] == 'pass' || params['credit_card_processed'] == 'Y'\n 'Completed'\n elsif params['fraud_status'] == 'wait'\n 'Pending'\n else\n 'Failed'\n end\n end", "def status\n if params['fraud_status'] == 'pass' || params['credit_card_processed'] == 'Y'\n 'Completed'\n elsif params['fraud_status'] == 'wait'\n 'Pending'\n else\n 'Failed'\n end\n end", "def api_payment_subscription_status\n\n raise \"No subscription Transaction ID\" unless @payment_subscription_txid\n\n url = \"#{@config['api_host']}/1/payments/transactions/#{@payment_subscription_txid}?access_token=#{@oauth_token}\"\n\n log \"Finding subscription info\"\n log_error \"Request: #{url}\" if @debug >= AttApiReporter::DEBUG_INFO\n\n begin\n page = @agent.get(url)\n subscriptionStatus = JSON.parse(page.body)\n log \"Got subscription info\"\n log_error JSON.pretty_generate(subscriptionStatus)\n rescue Exception => e\n log_error e.backtrace\n log_error e.page.body\n return \"FAILED\"\n end\n return \"OK\"\n end", "def get_telephone_transaction_status(transaction)\n route = \"#{@user.vet360_id}/telephones/status/#{transaction.id}\"\n get_transaction_status(route, TelephoneTransactionResponse)\n end", "def trx_status\n #parse out trx_id\n trx_id = params[:tid]\n\n begin\n status = ApiTransaction.find(trx_id).trx_status\n render json: { trx_id: trx_id, status: status }, status: :ok\n rescue ActiveRecord::RecordNotFound\n render json: { trx_id: trx_id, status: \"Transaction not found\" }, status: :not_found\n end\n end", "def get_person_transaction_status(transaction_id)\n with_monitoring do\n raw_response = perform(:get, \"status/#{transaction_id}\")\n VAProfile::Stats.increment_transaction_results(raw_response, 'init_vet360_id')\n\n VAProfile::ContactInformation::PersonTransactionResponse.from(raw_response, @user)\n end\n rescue => e\n handle_error(e)\n end", "def transaction_status(uuid)\n get_status(withdraw_status_endpoint,uuid)\n end", "def get_address_transaction_status(transaction)\n route = \"#{@user.vet360_id}/addresses/status/#{transaction.id}\"\n get_transaction_status(route, AddressTransactionResponse)\n end", "def get_telephone_transaction_status(transaction_id)\n route = \"#{@user.vet360_id}/telephones/status/#{transaction_id}\"\n transaction_status = get_transaction_status(route, TelephoneTransactionResponse)\n\n changes = transaction_status.changed_field\n send_contact_change_notification(transaction_status, changes)\n\n transaction_status\n end", "def transactional_status(id)\n get \"#{base_url}/journeys/transactional/status/#{id}\"\n end", "def get_email_transaction_status(transaction)\n route = \"#{@user.vet360_id}/emails/status/#{transaction.id}\"\n get_transaction_status(route, EmailTransactionResponse)\n end", "def transaction_status()\n #This is a stub, used for indexing\n end", "def status\n @status ||= if checksum_ok?\n if transaction_id.blank?\n 'invalid'\n else\n transaction_status.downcase\n end\n else\n 'tampered'\n end\n end", "def get_status(options = {})\n options = argument_cleaner(required_params: %i( ), optional_params: %i( rating sms html ), options: options )\n authenticated_get cmd: \"getstatus\", **options\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assign API endpoints depending on the environment.
def assign_endpoints if @env == 'production' @api_domain = 'https://www.pesapal.com' else @api_domain = 'https://demo.pesapal.com' end @api_endpoints = {} @api_endpoints[:postpesapaldirectorderv4] = "#{@api_domain}/API/PostPesapalDirectOrderV4" @api_endpoints[:querypaymentstatus] = "#{@api_domain}/API/QueryPaymentStatus" @api_endpoints[:querypaymentdetails] = "#{@api_domain}/API/QueryPaymentDetails" @api_endpoints end
[ "def api_endpoint\n case current_user.environment\n when 'int', 'integration'\n 'http://newapi.int.brandwatch.com'\n when 'rel', 'release', 'stage'\n 'http://newapi.rel.brandwatch.com'\n else\n 'http://newapi.brandwatch.com'\n end\n end", "def endpoints\n validate_keys(@config[:api_key], @config[:application_key], true)\n\n # the first endpoint is always the url/site + apikey + appkey one\n endpoints = [[config_url(), @config[:api_key], @config[:application_key]]]\n\n # then add extra endpoints\n extra_endpoints = @config[:extra_endpoints] || []\n extra_endpoints.each do |endpoint|\n url = endpoint[:api_url] || endpoint[:url] || config_url()\n api_key = endpoint[:api_key]\n app_key = endpoint[:application_key]\n endpoints << [url, api_key, app_key] if validate_keys(api_key, app_key, false)\n end\n\n endpoints\n end", "def api(*endpoints)\n inject_to_api do |api|\n api.use(*Grape::OAuth2.middleware)\n api.helpers(Grape::OAuth2::Helpers::AccessTokenHelpers)\n\n (endpoints.presence || endpoints_mapping.keys).each do |name|\n endpoint = endpoints_mapping[name.to_sym]\n raise ArgumentError, \"Unrecognized endpoint: #{endpoint}\" if endpoint.nil?\n\n api.mount(endpoint)\n end\n end\n end", "def setup_api\n Api.configure do |config|\n config.base_url = 'http://localhost:8080'\n end\n end", "def initialize_api_endpoint\n if PrMigrator.configuration.github_enterprise_endpoint\n Octokit.configure do |c|\n c.api_endpoint = PrMigrator.configuration.github_enterprise_endpoint\n end\n end\n end", "def add_api_endpoint\n @auth_params.merge!(openstack_auth_url: config[:api_endpoint]) unless config[:api_endpoint].nil?\n end", "def collect_api_definitions!( namespace )\n routes = Rails.application.routes.routes.select { |route| route.path.spec.to_s.start_with?(namespace) }\n \n method_map = {\n /^GET$/ => :get,\n /^PUT$/ => :put,\n /^POST$/ => :post,\n /^DELETE$/ => :delete,\n /^PATCH$/ => :patch\n }\n\n routes.map do |route|\n next if route.path.spec.to_s =~ /api\\/unified\\/docs/\n\n controller = (route.defaults[:controller] + \"_controller\").classify.constantize\n\n endpoint = Endpoint.new( \n route.path.spec.to_s, \n route.try(:verb).try(:downcase).try(:to_sym) || method_map[ route.constraints[:request_method] ],\n controller,\n route.defaults[:action],\n controller.apis[ route.defaults[:action].to_sym ]\n )\n end.compact\n end", "def initialize_endpoints_methods\n possible_post_endpoints.each do |endpoint_path|\n self.class.send(:define_method, endpoint_path) do |params = {}|\n \"B2C2Client::Requests::Post::#{endpoint_path.camelize}\"\n .constantize.new(self.config, params)\n end\n end\n\n possible_get_endpoints.each do |endpoint_path|\n self.class.send(:define_method, endpoint_path) do |params = {}|\n \"B2C2Client::Requests::Get::#{endpoint_path.camelize}\"\n .constantize.new(self.config, params)\n end\n end\n end", "def api_endpoint\n ENV['API_ENDPOINT']\n end", "def endpoint\n endpoints.fetch(environment)\n end", "def context\n env['api.endpoint']\n end", "def endpoints\n @endpoints ||= init_endpoints\n end", "def api_endpoint=(endpoint)\n @api_endpoint = endpoint\n end", "def call env\n #load File.join(LIB_ROOT, \"kepi/api.rb\")\n path, show_api = parse_path_api env['PATH_INFO']\n endpoint = find_endpoint env['REQUEST_METHOD'], path\n\n if endpoint\n env['PATH_INFO'] = path\n response(*endpoint.call(env, show_api))\n\n elsif env['PATH_INFO'] == self.class.api_doc_path\n api_response\n\n elsif @app\n @app.call env\n\n else\n undefined_response env\n end\n end", "def create_apis\n get_apis.each do |api|\n title = api[\"API\"]\n description = api[\"Description\"]\n auth_type = api[\"Auth\"]\n https = api[\"HTTPS\"]\n cors = api[\"Cors\"]\n link = api[\"Link\"]\n category = api[\"Category\"]\n PublicApinception::API.new(title, description, auth_type, https, cors, link, category)\n end\n end", "def setup(args={})\n super\n @conf_key = (args[:config_key] || :http_endpoints).to_sym\n set_points\n end", "def api(params = {})\n Celluloid::Logger.info \"Registering api...\"\n self.use_api = true\n self.api_host = params[:host] || '127.0.0.1'\n self.api_port = params[:port] || '4321'\n end", "def api_endpoint\n @config.fetch(:url)\n end", "def endpoint_settings\n case environment.downcase\n when \"azureusgovernment\"\n ::MsRestAzure2::AzureEnvironments::AzureUSGovernment\n when \"azurechina\"\n ::MsRestAzure2::AzureEnvironments::AzureChinaCloud\n when \"azuregermancloud\"\n ::MsRestAzure2::AzureEnvironments::AzureGermanCloud\n when \"azure\"\n ::MsRestAzure2::AzureEnvironments::AzureCloud\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the cycles: [[a, b, c], [b, c]] to the string: ["a > b > c > a", "b > c > b"]
def build_cycle_strings(cycles) cycles.map do |cycle| cycle_strings = cycle.map(&:to_s) cycle_strings << cycle.first.to_s "\t- #{cycle_strings.join(" → ")}" end end
[ "def format_comb(arr)\n ret = []\n arr.each do |sub_arr|\n if sub_arr.size > 1\n # use dash to connect the multiple strings \n ret << sub_arr.inject('') {|acc, e| acc + e + '-' }[0..-2]\n elsif sub_arr.size == 1\n ret << sub_arr[0]\n else\n # do nothing...\n end\n end\n return ret\n end", "def dot_encoding_strings\n\t\tenc = Array.new\n\t\tedges_considered = Array.new\n\t\t@adjacency_list.keys.each do |v|\n\t\t\tresult = path [v], edges_considered\n\t\t\tenc.push result[:so_far].join(\" -- \") unless result[:so_far].length == 1 and !neighbors(result[:so_far].first).empty?\n\t\t\tedges_considered = result[:edges_considered]\n\t\tend\n\t\tenc \n\tend", "def back_to_s(array)\n array.join(\"\")\nend", "def composeRanges(nums)\n return [] if nums.empty?\n ranges = []\n ranges << [nums.first]\n i = 1\n while i < nums.length\n if nums[i] - nums[i-1] == 1\n ranges.last << nums[i]\n else\n ranges << [nums[i]]\n end\n i += 1\n end\n ranges.map do |range|\n if range.length == 1\n range.first.to_s\n else\n \"#{range.first}->#{range.last}\"\n end\n end\nend", "def to_cartesian(path)\n path.map(&:reverse)\nend", "def condensed_to_s \n concat = \"\"\n tmp = \"\"\n count = 0\n \n @verticies.keys.each do |v| \n if v.edges.length > 0 # only display connected portions of graph\n \n v.edges.each do |edge|\n if edge.passable\n tmp += \" #{edge.vertex.to_s}, w=#{edge.weight}\" \n count+=1\n end\n end\n if count > 0\n concat += \"v: \" + v.to_s + \" edges: \"\n concat += tmp + \"\\n\"\n count = 0\n end\n tmp = \"\"\n end\n end\n concat\n end", "def elements_to_string(elements)\n string = ''\n # Deletes the longest possible range of separators from the end of\n # the array.\n elements = elements.reverse.drop_while {|e| e.type == :sep}\n elements.reverse!.compact!\n\n # Checks if the rest of the above rules are fulfilled.\n elements.each_index do |i|\n e = elements[i]\n if e.type == :sep\n if i != 0 && elements[i-1].type != :sep && \\\n elements[i-1].content != nil && elements[i-1].content != ''\n string << e.content if e.content\n end\n else\n string << e.content if e.content\n end\n end\n string\n end", "def convert_array_to_string(an_array)\n array_len = an_array.length\n combined_string = \"\"\n\n if array_len == 2\n combined_string << an_array[0] << \" and \" << an_array[1]\n return combined_string\n end\n\n an_array.each_with_index do |string, i|\n if i == 0\n combined_string << string\n elsif i == array_len - 1\n combined_string << \", and \" << string\n else\n combined_string << \", \" << string\n end\n end\n\n return combined_string\nend", "def to_s\r\n collect do |element, n|\r\n element.symbol + (n == 1 ? \"\" : \"(#{n})\")\r\n end.sort.join('')\r\n end", "def to_s() edges.to_s; end", "def cycle(tiles, curr)\n i=0\n comb = Array.new #creates new array\n tiles2 = tiles\n curr.each_char {|y| #cycles throught each character in current word\n tiles2 = tiles2.split(y).join(\"\") } #creates a string with removed letters from curr\n tiles2.each_char {|x| #cycles throught remaining letters\n word = curr + x\n comb[i]= word #stores remaining letters.\n\n i +=1\n }\n return comb\nend", "def to_str even_odd: false, show_flats: false\n ConciseString.new( buildings, even_odd: even_odd,\n show_flats: show_flats ).str\n end", "def transpositions\n new_words = []\n @words.each do |word|\n @word = word || '' \n new_words += (0..length-1).map { |i| \"#{@word[0...i]}#{@word[i+1, 1]}#{@word[i,1]}#{@word[i+2..-1]}\" }\n end\n new_words\n end", "def to_s\n (segments || []).inject('') do |str,seg|\n str << (seg.is_a?(Symbol) ? \":#{seg}\" : seg)\n end\n end", "def cycles\n perm = value\n result = [[]]\n seen = {}\n current = nil\n loop do\n current or current = perm.find { |x| !seen[x] }\n break unless current\n if seen[current]\n current = nil\n result << []\n else\n seen[current] = true\n result[-1] << current\n current = perm[current]\n end\n end\n result.pop\n result.select { |c| c.size > 1 }.map do |c|\n min_index = c.index(c.min)\n c[min_index..-1] + c[0...min_index]\n end\n end", "def to_s\n @fractal.reverse.map do |row|\n row.map{|char| \"%1s\" % char}.join(\"\")\n end.join(\"\\n\")\n end", "def stringify(arr)\n arr.map { |s| s.to_s }.join(\"<br>\")\n end", "def to_s\n collection.map(&:to_s).join\n end", "def to_s\n # Loop through each node in our list, starting at @head,\n # and add the 'value' of each node we visit to an output\n # string; then follow the 'next' pointer to get the\n # next node in the list for the next loop iteration...\n # until we find a node whose 'next' value is nil\n output = ''\n\n # node = @head\n #\n # while node # i.e until the current node is nil\n # output += node.value + ', '\n # node = node.next # i++, i.e. increment the counter / move to the next node\n # end\n\n each { |node| output += node.value + ', ' }\n\n output\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given three numbers X, Y & Z. write a function/method that finds the greatest among the numbers.
def greatest puts "Enter value of X" x = gets.chomp puts "Enter value of y" y = gets.chomp puts "Enter value of z" z = gets.chomp max_num = [x,y,z].max puts "The greates number is #{max_num}" end
[ "def max_of_three(num1, num2, num3)\n [num1, num2, num3].max\nend", "def max_of_three(num1, num2, num3)\n\t[num1, num2, num3].max\nend", "def max(num1, num2, num3)\n # Algorith to figure out which is the highest value\n if num1 >= num2 and num1 >= num3\n # @desc if the result of the two comparison is true we return below\n return num1\n elsif num2 >= num1 and num2 >= num3\n # @desc if the result of the two comparison is true we return below\n return num2\n else\n return num3\n end\nend", "def third_greatest(array)\nend", "def largest_number (number_1, number_2)\n \n [number_1, number_2].max\n \nend", "def third_greatest(array)\r\nend", "def maxoffour( num1, num2, num3, num4)\n if num1 > num2\n big1 = num1\n else\n big1 = num2\n end\n if num3 > num4\n big2 = num3\n else\n big2 = num4\n end\n if big1 > big2\n biggest = big1\n else\n biggest = big2\n end\n return biggest\nend", "def max_of_three(num1, num2, num3)\n largest = 0\n if num1 > num2\n largest = num1\n else \n largest = num2\n end\n\n if num3 > largest\n return num3\n else\n return largest\n end\nend", "def max_of_three(n1, n2, n3)\n largest = n1\n if n1 < n2\n largest = n2\n end\n if largest < n3\n largest = n3\n end\n return largest\nend", "def max_of_three(num1, num2, num3)\n largest = 0\n if num1 > num2\n largest = num1\n else\n largest = num2\n end\n return largest if largest > num3\n return num3\nend", "def find_greatest(numbers)\n saved_number = nil\n\n numbers.each do |num|\n saved_number ||= num # assign to first value\n if saved_number >= num\n next\n else\n saved_number = num\n end\n end\n\n saved_number\nend", "def max_of_three(n1,n2,n3)\n max = n1\n if n1 < n2\n max = n2\n end\n if max < n3\n max = n3\n end\n return max\nend", "def find_greatest(numbers)\n saved_number = nil\n\n numbers.each do |num|\n saved_number ||= num\n if saved_number >= num\n next\n else\n saved_number = num\n end\n end\n \n saved_number\nend", "def max_of_three(max,num2, num3)\n if max < num2\n max = num2\n end\n if max < num3\n max = num3\n end\n return max\nend", "def get_largest_two(in_val1, in_val2, in_val3)\n\tcheck_pre(((in_val1.int?) and (in_val2.int?) and (in_val3.int?)))\n\tif(in_val1 >= in_val3 and in_val2 >= in_val3) then [in_val1, in_val2]\n elsif(in_val1 >= in_val2 and in_val3 >= in_val2) then [in_val1, in_val3]\n elsif(in_val3 >= in_val1 and in_val2 >= in_val1) then [in_val2, in_val3]\n else check_pre(false)\n end\nend", "def max_of_three(input1,input2,input3)\n if input1 > input2 && input1 > input3\n output = input1\n elsif input2 > input1 && input2 > input3\n output = input2\n else output = input3\n end\n return output\nend", "def third_greatest(nums)\n\t\n\tnums.sort!\n\treturn nums[-3]\nend", "def third_greatest(nums)\n\t# If can use Array#sort:\n\t# sorted = nums.sort\n\t# sorted[-3]\n\t# If can't use Array#sort:\n\tone = 0\n\ttwo = 0\n\tthree = 0\n\n\tnums.length.times do |i|\n\t\tif nums[i] > one\n\t\t\tthree = two\n\t\t\ttwo = one\n\t\t\tone = nums[i]\n\t\telsif nums[i] > two\n\t\t\tthree = two\n\t\t\ttwo = nums[i]\n\t\telsif nums[i] > three\n\t\t\tthree = nums[i]\n\t\tend\n\tend\n\treturn three\nend", "def max(x, y)\n x > y ? x : y\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Access a GData parameter. +k+ must be symbols, like +:out+, +:reqId+.
def [](k) @params[k] end
[ "def [](key)\n\t\t\t@packet.get_param(key.to_s)\n\t\tend", "def parameter(key)\n\n unless @__parameter_dictionary and @__parameter_dictionary.hasKey(key.to_s) then \n return nil\n end\n\n @__parameter_dictionary.getValueForKey(key.to_s)\n\n end", "def param(k)\n v = self[k.to_sym] || self[k.to_s]\n v && !(v.is_a?(String) && v.empty?) ? v : nil\n end", "def get_parameter(key_name = @base_param_key)\n\n request = {\n names: [key_name], # required\n with_decryption: false,\n }\n\n @base_version = @client.get_parameters(request).parameters[0].value\n puts \"Parameter #{key_name} has value #{ @base_version }\"\n end", "def KwRestParam(name); end", "def []=(k, v)\n @params[k] = v\n end", "def prepared_arg(k)\n @opts[:bind_vars][k]\n end", "def lookupParam(key)\n return DrawParam[key] ;\n end", "def get_param\n @params[name]\n end", "def param_key=(_arg0); end", "def []=(k, v)\n @params[k] = v\n validate\n end", "def get_param(key, default=nil)\n key = expand_local_name(@node_name, key)\n param = @parameter.get_param(key)\n if param\n param\n else\n default\n end\n end", "def param(key)\n @request.params[key.to_s]\n end", "def []=(k, v)\n @params[k] = v\n validate\n end", "def __get(k)\n\t\t\treturn @m[k]\n\t\tend", "def get(name)\n raise InvalidParameter.new(name) unless name.kind_of?(Variable)\n @data[name]\n end", "def Get(key)\n return @parameterList[key]\t\t# Return desired element\n end", "def get k\n\t\tJS::Object.get(\"Ruby.JsObj.get_property\").call(@object,k)\n\t end", "def param_value(name)\n get_param(name).value\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a GData parameter. +k+ must be symbols, like +:out+, +:reqId+. The instance is revalidated afterward.
def []=(k, v) @params[k] = v validate end
[ "def []=(k, v)\n @params[k] = v\n validate\n end", "def []=(k, v)\n @params[k] = v\n end", "def set_opt(k, v)\n x = @data_store.set_opt(k, v)\n save\n x\n end", "def set_parameter(key, value)\n\n return nil unless @__parameter_dictionary \n\n @__parameter_dictionary.setValueForKey(key.to_s, value.to_s)\n\n end", "def set_param(key, value)\n @parameter.set_param(expand_local_name(@node_name, key), value)\n end", "def set_param(key, value = nil)\n validate_param!(key, value)\n\n if value.respond_to?(:set_request)\n value.set_request(self)\n elsif key == :discretionary_data\n set_discretionary(value)\n elsif value != nil\n @params[key] ||= []\n\n @params[key] << value\n end\n end", "def set_param name, value\n @params[name] = value\n end", "def setvalue(key, value)\r\n @@params[key] = value\r\n end", "def set k,v\n key = k.to_s.to_sym\n v = (v.is_a?(JrdObj) ? v.finish : v) unless v == nil\n @_[key] = v unless v == nil\n @_.delete key if v == nil\n end", "def add_parameter(key, value)\r\n @parameters[key] = value\r\n end", "def set k,v\n key = k.to_s.to_sym\n v = (v.is_a?(ASObj) ? v.finish : v) unless v == nil\n @_[key] = v unless v == nil\n @_.delete key if v == nil\n end", "def setParameter(param, value)\r\n @params.set(param,value);\r\n end", "def set_request_data(key, value)\n Bugsnag.configuration.set_request_data(key, value)\n end", "def [](k)\n @params[k]\n end", "def store_data(ky, v = nil, &block)\n if block_given?\n vi.data_store.store_data(directive: name, key: ky, value: data_struct(&block))\n else\n vi.data_store.store_data(directive: name, key: ky, value: v)\n end\n end", "def prepared_arg(k)\n @opts[:bind_vars][k]\n end", "def set_param(name, value)\n session[name] = value\n params[name] = value\n return value\n end", "def []=(name, val)\n Mutex.synchronize do\n VacmanController::LowLevel.set_kernel_param(name, val)\n end\n end", "def asignar_valorKj(valor)\n @valorKj=valor\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Manually adds a new validation error. +key+ should be a symbol pointing to the invalid parameter or element.
def add_error(key, message) @errors[key] = message return self end
[ "def add_error(key, message)\n @errors[key] = message\n return self\n end", "def add(key, error)\n self[key].push(error)\n self\n end", "def add_error\n increment_key(key: errors_key)\n maybe_create_outage\n end", "def append!(errors, attr, key, val)\n return unless val.present?\n\n errors ||= {}\n errors[attr] ||= {}\n errors[attr][key] = val\n end", "def err_on(attr, message_key)\n errors.add(\n attr,\n I18n.t(message_key, :scope=>'activerecord.errors.messages'))\n end", "def invalid_value(key)\n raise_error(\"Invalid '#{key}' value entered!\")\n end", "def add_unique_key_error(exception)\n if unique_key_check_options[:field_name]\n self.errors.add(unique_key_check_options[:field_name], unique_key_check_options[:message]||\"is a duplicate.\")\n else\n self.errors.add_to_base(unique_key_check_options[:message]||\"Duplicate field.\")\n end\n end", "def delete(key)\n attribute = key.to_sym\n errors.delete(attribute)\n end", "def add attribute, msg = default_error_messages[:invalid]\n error_hash[attribute] ||= [] # initialize the errors array for the attribute if necessary\n error_hash[attribute] << msg\n end", "def append_error(attribute_name, error)\n errors[attribute_name] << error\n end", "def add(field_name, message)\n @errors[field_name] << message\n end", "def add(attribute, message)\n @errors[attribute] << message\n end", "def add_error(message)\n self.errors << message\n end", "def add_error(error)\n all_errors << error\n end", "def <<(error)\n raise ArgumentError.new(\"Invalid Error\") if error.nil?\n if error.instance_of?(ValidationException)\n context = error.context\n raise ArgumentError.new(\"Invalid context\") if context.nil?\n raise ArgumentError.new(\"Duplicate error\") if @errors.has_key?(context)\n @errors[context] = error\n else\n raise ArgumentError.new(\"Exception was not a ValdiaitonException\")\n end\n end", "def add_error(error)\n @errors = error\n @errors\n end", "def add(attribute, msg)\n @errors[attribute.to_s] = [] if @errors[attribute.to_s].nil?\n @errors[attribute.to_s] << msg\n end", "def error_key\n :not_empty\n end", "def add(attribute, msg = @@default_error_messages[:invalid])\n @errors[attribute.to_s] = [] if @errors[attribute.to_s].nil?\n @errors[attribute.to_s] << msg\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the data to be exported. +data+ should be a collection of activerecord object. The first index should iterate over rows, the second over columns. Column ordering must be the same used in +add_col+ invokations. Anything that behaves like a 2dimensional array and supports +each+ is a perfectly fine alternative.
def set(cols, data) cols.each do |col| raise ArgumentError, "Invalid column type: #{col.type}" if !@coltypes.include?(col.type) @cols << col.data end # @data should be a 2-dimensional array @data = [] data.each do |record| @data << record end #data return self end
[ "def set_data_from_array_of_hashes(data)\n add_columns(data) if columns.empty?\n set_data(data.map { |row| self.columns.map { |c| row[c[:id].to_s] } })\n end", "def add_col(data)\n for i in (0...@rows)\n @data[i][@cols] = data[i].to_f\n end\n @cols += 1\n end", "def set_data_from_hash(data)\n data[:columns].each_with_index do |column_name, index|\n sample_value = data[:rows].first[index]\n add_column(column_type_for_value(sample_value), :id => column_name, :label => column_name)\n end\n set_data_from_array(data[:rows])\n end", "def data=(data)\n # reset formatted data\n @data = nil\n\n # set unformatted data\n @raw_data = data\n validate\n\n # register virtual columns\n if data.respond_to?(:add_virtual_column)\n @virtual_columns.each { |k, v| data.add_virtual_column(k.to_sym, v[:type]) }\n end\n end", "def add_data(dataset, worksheet, columns)\r\n dataset.rows.each_with_index do |row, rindex|\r\n columns.each_with_index do |col, cindex|\r\n # set column formatting\r\n f = nil\r\n cell_value = nil\r\n col_length = row[col].to_s.length < 20 ? 20 : row[col].to_s.length\r\n if row[col].kind_of? Fixnum or row[col].kind_of? Float\r\n f = @formats[:number_column]\r\n cell_value = [row[col]]\r\n else\r\n f = @formats[:column_format] \r\n cell_value = row[col].to_s\r\n end\r\n \r\n worksheet.write(rindex + STARTING_DATA_ROW, cindex, cell_value, @formats[:column_format])\r\n worksheet.format_column(cindex, col_length, f)\r\n end\r\n end\r\n end", "def map_export_data(collection, options={})\n # Use :only and :except options or else use class defaults for columns.\n if !options[:only].blank?\n options[:columns] = Array.wrap(options[:only]).map(&:to_sym)\n elsif !options[:except].blank?\n options[:columns] = column_names.map(&:to_sym) - Array.wrap(options[:except]).map(&:to_sym)\n else\n options[:columns] = exportable_options[:columns]\n end\n if options[:columns].empty?\n raise MakeExportable::ExportFault.new(\"You are not exporting anything\")\n end\n # TODO: Go ahead and humanize/titleize the column names here\n headers = options[:columns].map(&:to_s)\n rows = collection.map do |item|\n options[:columns].map {|col| item.export_attribute(col) }\n end\n return rows.unshift(headers)\n end", "def populate_by_row(data)\n unless check_array(data) == false\n data.each do |row|\n add_instance(row)\n end\n end\n end", "def data\n datacolumns.reduce({}) do |t, col|\n t[col.name] = col.data; t\n end\n end", "def set_data_from_array(data)\n @data = data\n end", "def set(data, columns = nil)\n self.data = data\n self.columns = columns || guess_columns(@raw_data)\n end", "def write_data(data = nil)\n if block_given?\n while data = yield\n self.write_data_helper(data)\n end\n else\n self.write_data_helper(data)\n end\n end", "def data=(data)\n @data = data\n if @data.is_a? Integer\n bind_set_count(data)\n elsif @data.is_a? Time\n bind_set_time(data.iso8601)\n end\n end", "def writeData(w)\n ygrid = getOption('ygrid')\n \n elems = @data.shape\n if ( elems.length == 1 ) then write_data_1D(w)\n elsif( elems.length == 2 ) then write_data_2D(w)\n end\n end", "def write_row\n @data_sets.each do |ds|\n ds.write_row\n end\n end", "def data=(series)\n @data = []\n series.each do |d|\n @data << [[0,d]]\n end\n end", "def add_data data\n @data = [] unless @data\n \n raise \"No data provided by #{@data.inspect}\" unless data[:data] and\n data[:data].kind_of? Array\n raise \"Data supplied must be x,y pairs! \"+\n \"The data provided contained an odd set of \"+\n \"data points\" unless data[:data].length % 2 == 0\n return if data[:data].length == 0\n\n\n x = []\n y = []\n data[:data].each_index {|i|\n if i%2 == 0\n t = DateTime.parse( data[:data][i] ).to_time\n x << t.to_i\n else\n y << data[:data][i]\n end\n }\n sort( x, y )\n data[:data] = [x,y]\n @data << data\n end", "def populate(data)\n return unless data.respond_to?(:collect)\n\n data.each do |x, y, obj|\n if is_valid?(x,y)\n obj = @def_value if obj.nil?\n @grid[x][y] = obj\n end\n end\n return\n end", "def insert(data)\n validate_insert(data)\n\n # Iterate through each column in the data\n data.each do |column_name, column_data|\n # Push the new data to the end up the currently stored data\n @columns[column_name].push(*column_data)\n\n # Update the length of the table\n @count = @columns[column_name].length\n end\n\n end", "def output_csv(data)\n CSV.open(OUTPUT_FILE, 'wb') do |csv|\n data.each do |datum|\n csv << datum\n end\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fixity_mode can be :fedora, :ingestion or an array containing both
def initialize(params={}) self.fixity_mode = Array.wrap(params.fetch(:fixity_mode, [:fedora, :ingestion])) super(params) end
[ "def retrieve_fixity\n alg = replication.fixity_algorithm.to_sym\n replication.fixity_value = bagit.fixity(alg)\n end", "def set_fixityd!(fixity_value)\n transaction do\n update!(fixity: fixity_value, last_step_completed: :fixityd)\n replication_transfer.update!(fixity_value: fixity)\n send_update(replication_transfer)\n end\n end", "def allow_fixation?\n @fixation\n end", "def allow_fixation? \n @fixation\n end", "def migrate_fixity\n adapter = DataMapper.repository(:package_tracker).adapter \n d1_packages = adapter.select(\"SELECT * FROM packages WHERE id LIKE 'E2%';\")\n\n d1_packages.each do |d1_package|\n # if any bad fixity events, get the whole history\n # otherwise, just get the latest good one\n ieid = d1_package['id']\n puts \"migrating fixity events for #{uid}, #{ieid}\"\n if DataMapper.repository(:daitss1) { EVENT.first(:OID => ieid, :EVENT_TYPE => \"FC\", :OUTCOME => \"FAIL\") }\n fixity_events = DataMapper.repository(:daitss1) { EVENT.all(:OID => ieid, :EVENT_TYPE => \"FC\") }\n\n fixity_events.each do |event|\n DataMapper.repository(:default) { Package.get(ieid).log \"legacy fixity event\", {:timestamp => event.DATE_TIME.ctime, :note => \"outcome: #{event.OUTCOME}; note: #{event.NOTE}\"} }\n end\n else\n event = DataMapper.repository(:daitss1) { EVENT.first(:OID => ieid, :EVENT_TYPE => \"FC\", :order => [ :DATE_TIME.desc ]) }\n\n DataMapper.repository(:default) { Package.get(ieid).log \"legacy fixity event\", {:timestamp => event.DATE_TIME.ctim, :note => \"outcome: #{event.OUTCOME}; note: #{event.NOTE}\"} }\n end\n end\n end", "def fixity_check\n Ddr::Actions::FixityCheck.execute(self)\n end", "def load_fixity_checks\n @fixities.values.each do |fixity|\n bag_uuid = @bags[fixity.bag].uuid\n bag = Bag.where(uuid: bag_uuid).first\n node = Node.where(namespace: fixity.node).first\n FixityCheck.create!(fixity_check_id: fixity.fixity_check_id,\n bag: bag, \n node: node,\n success: fixity.success,\n fixity_at: APRIL_01_2016,\n created_at: APRIL_01_2016)\n \n end\n end", "def fixity(resource_uri, format = \"text/turtle\")\n log \"fixity for #{resource_uri}\"\n get \"#{resource_uri}/fcr:fixity\", format\n end", "def apt_fixity(more_tests_follow)\n\trun_suite(more_tests_follow) do\n\t @build.build(@context.apps['apt_queue_fixity'])\n\t @build.build(@context.apps['apt_fixity_check'])\n\n\t # Run the prerequisite process (with tests)\n\t # Note that the prereq starts most of the required services,\n\t # and apt_queue marks items for restore and pushes them into\n\t # NSQ.\n\t apt_restore_ok = apt_restore(true)\n\t if !apt_restore_ok\n\t\tputs \"Skipping apt_fixity test because of prior failures.\"\n\t\treturn false\n\t end\n\n\t # Queue up some files for fixity checking. Note that service.rb\n\t # sets -maxfiles=10 for apt_queue_fixity.\n\t @service.app_start(@context.apps['apt_queue_fixity'])\n\t @service.app_start(@context.apps['apt_fixity_check'])\n\t sleep 45\n\n\t # Run the post test.\n\t @results['apt_fixity_test'] = run('apt_fixity_check_post_test.go')\n\tend\n end", "def modes\n fix_mode.modes\n end", "def update_mode(data_series=@data_series)\n\t\tif validate_parameters\n\t\t\t@mode = determine_mode(data_series)\n\t\telse\n\t\t\traise RangeError, \"The input parameter must be an array with all numbers\"\n\t\tend\n\tend", "def test_round_trip_feature_modes\n scripts = ['fake1', 'fake2']\n %w{normal scale emergency}.each do |mode|\n FeatureModeManager.set_mode(mode, @gatekeeper, @dcdo, scripts)\n assert_equal mode, FeatureModeManager.get_mode(@gatekeeper, @dcdo, scripts)\n end\n end", "def fixed(entries = @entries)\n mode_filter('fixed', entries)\n end", "def fixable?\n available_actions.map { |a| a.name }.include?('Fix')\n end", "def fixatable(enable=true) \n @fixation = enable \n self\n end", "def resolve_modes(options = {})\n [options.delete(:mode) || options.delete(:modes) || current_mode_id].flatten.compact\n end", "def equip_fix?(equip_type)\n case equip_type\n when 0 # Weapon\n return $data_actors[@actor_id].weapon_fix\n when 1 # Shield\n return $data_actors[@actor_id].armor1_fix\n when 2 # Head\n return $data_actors[@actor_id].armor2_fix\n when 3 # Body\n return $data_actors[@actor_id].armor3_fix\n when 4 # Accessory\n return $data_actors[@actor_id].armor4_fix\n=begin\n when 5 # Accessory\n return $data_actors[@actor_id].piercing1_fix\n when 6 # Accessory\n return $data_actors[@actor_id].piercing2_fix\n when 7 # Accessory\n return $data_actors[@actor_id].piercing3_fix\n when 8 # Accessory\n return $data_actors[@actor_id].piercing4_fix\n when 9 # Accessory\n return $data_actors[@actor_id].piercing5_fix\n when 10 # Accessory\n return $data_actors[@actor_id].piercing6_fix\n when 11 # Accessory\n return $data_actors[@actor_id].piercing7_fix\n=end\n end\n return false\n end", "def step_install_fixes(step,\n target,\n nimres_sortedfixes)\n Log.log_info('Flrtvc step : ' + step.to_s + ' (target=' + target + ')' +\n ' nimres_sortedfixes=' +\n nimres_sortedfixes.to_s)\n #\n begin\n # efixes are sorted : most recent first\n nim_resource = nimres_sortedfixes.keys[0]\n efixes = nimres_sortedfixes.values[0]\n efixes_string = Utils.string_separated(efixes, ' ')\n #\n # efixes are applied\n unless efixes.empty?\n Log.log_debug('Performing efix installation')\n Nim.perform_efix(target, nim_resource, efixes_string)\n Log.log_debug('End performing efix installation')\n else\n Log.log_info('Efix list empty - Nothing to install.')\n end\n rescue StandardError => e\n Log.log_err('Exception e=' + e.to_s)\n end\n end", "def equip_fix?(equip_type)\n case equip_type\n when 0 # Weapon\n return $data_actors[@actor_id].weapon_fix\n when 1 # Shield\n return $data_actors[@actor_id].armor1_fix\n when 2 # Head\n return $data_actors[@actor_id].armor2_fix\n when 3 # Body\n return $data_actors[@actor_id].armor3_fix\n when 4 # Accessory\n return $data_actors[@actor_id].armor4_fix\n end\n return false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate command line option from option symbol
def symbol_to_option(symbol,opt_val) result='--'+symbol.to_s.gsub(OPTION_SEP_NAME,OPTION_SEP_LINE) result=result+'='+opt_val unless opt_val.nil? return result end
[ "def opt(command_option)\n self << \" --#{command_option}\"\n self\n end", "def option(command_option)\n self << \" -#{command_option}\"\n self\n end", "def option=(str)\n @options = Shellwords.shellwords(str)\n end", "def long_opt_symbol(args); end", "def build_option(name, options, scope); end", "def opt_flag(opt, flag, description, sym = nil)\n sym = flag.to_sym if sym.nil?\n opt.on(\"--#{flag.to_s.tr('_', '-')}\", description) { |v| self[sym] = v }\n end", "def java_option option, value\n return unless value\n return if value.to_s.strip.empty?\n \"-D#{option}=#{Shellwords.escape(value.to_s)}\"\n end", "def long_opt_symbol(args)\n long_opt = args.find { |arg| arg.start_with?('--') }\n long_opt[2..-1].sub('[no-]', '').sub(/ .*/, '')\n .tr('-', '_').gsub(/[\\[\\]]/, '').to_sym\n end", "def treat_as_option doption\n option = nil\n valeur = nil\n if doption.start_with? '--'\n doption.gsub(/^--([^=]+)=?(.*)?$/){\n option = $1\n valeur = $2\n }\n else\n option_courte = doption[1..1]\n option = OPTION_LIST[option_courte]\n fatal_error(:unknown_option, :option => option_courte) if option.nil?\n valeur = doption[2..-1]\n end\n # Est-ce que c'est une \"option-command\"\n if OPTION_COMMAND_LIST.has_key? option\n @@command = option\n else\n @@options = @@options.merge option => valeur\n end\n end", "def create_option(flag, argument = nil)\n return '' unless flag\n flag = flag.to_s\n return \" #{argument}\" if flag == 'extra'\n set_pandoc_ruby_options(flag, argument)\n if !argument.nil?\n \"#{format_flag(flag)} #{argument}\"\n else\n format_flag(flag)\n end\n end", "def option(sym, *options)\n @options << options\n @map[options[0]] = sym\n end", "def long_opt_sym(*args)\n long_opt = args.find{ |arg| arg.start_with? '--' }\n long_opt[2..-1].sub(/ .*/, '').gsub('-', '_').to_sym\n end", "def build_option_string(opt)\n before_for(opt) << padding_for(opt) << padding << after_for(opt).rstrip << \"\\n\"\n end", "def add_option(cmd, method_name)\n if (value = new_resource.send(method_name))\n flag_name = method_name.tr('_', '-')\n cmd << \"--#{flag_name} #{value}\"\n else\n cmd\n end\nend", "def dashize opt\n if opt.start_with? '-'\n Puppet.warning \"Passing options with dashes are deprecated. Pass only opt name. You have given: '#{opt}'\"\n return opt\n else\n if opt.size > 1\n return \"--#{opt}\"\n else\n return \"-#{opt}\"\n end\n end\n end", "def cmd_options(output_dir=nil)\r\n options = CONFIG_MAP.collect do |key, flag|\r\n value = (flag == \"D\" ? output_dir : config[key])\r\n next unless value\r\n\r\n # formatting consists of stringifying the value argument, or\r\n # in escaping the value if the arguement is a path\r\n formatted_value = case key\r\n when :use_unified_search_file, :perform_charge_calculations, :write_zta_files\r\n \"\" # no argument\r\n when :output_path, :template_file \r\n # path argument, escape\r\n \"\\\"#{normalize value}\\\"\" \r\n else \r\n # number or string, simply stringify\r\n value.to_s\r\n end\r\n\r\n \"-#{flag}#{formatted_value}\"\r\n end\r\n\r\n options.compact.join(\" \")\r\n end", "def generate_options(filename, code); end", "def option_quote(str)\n option?(str) ? str : quote(str)\n end", "def os_option(option, *args)\n options = args.pop if args.last.is_a?(Hash)\n options ||= {}\n args.push options.merge(os_prefix: true)\n option option, *args\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define an option with date format
def add_opt_date(option_symbol,*on_args) declare_option(option_symbol,:value) Log.log.debug("add_opt_date #{option_symbol}") on_args.unshift(symbol_to_option(option_symbol,"DATE")) Log.log.debug("on_args=#{on_args}") @parser.on(*on_args) do |v| case v when 'now'; set_option(option_symbol,Manager.time_to_string(Time.now),"cmdline") when /^-([0-9]+)h/; set_option(option_symbol,Manager.time_to_string(Time.now-$1.to_i*3600),"cmdline") else set_option(option_symbol,v,"cmdline") end end end
[ "def default_options_date_format(format)\n format || '%Y-%m-%d - %l:%M:%S%p'\n end", "def format_date\n if @opts[:as] == :select\n values = {}\n if v = @attr[:value]\n v = Date.parse(v) unless v.is_a?(Date)\n values[:year], values[:month], values[:day] = v.year, v.month, v.day\n end\n _format_date_select(values, @opts[:order] || DEFAULT_DATE_ORDER)\n else\n _format_input(:date)\n end\n end", "def set_DateFormat(value)\n set_input(\"DateFormat\", value)\n end", "def evaluate_date_format_option(option, *args)\n value = self.send(option)\n case value\n when String\n args.first.strftime(value)\n when Symbol\n args.first.send(value)\n when Proc\n value.call(*args)\n else\n value\n end\n end", "def format_date options = {}\n dates = options[:start_date].strftime(\"%D\") if options[:start_date]\n dates << \" -- \" + options[:end_date].strftime(\"%D\") if options[:end_date]\n dates = \"N/A\" if !dates\n return dates\n end", "def date_format=(value)\n @date_format = value\n end", "def date_select(field, options={}, &block)\n format_with_label(field, options.merge(:field_type => \"date\"), super(field, purge_custom_tags(options)), &block)\n end", "def datepicker_options(format, method, value = nil)\n datepicker_options = {:label_html => {:class => \"date\"}, :input_html => {:id => \"datepicker\", :class => 'formtastic-ui-datepicker datepicker', :value => value.try(:strftime, format)}}\n end", "def expected_format\n options[:expected_format] || 'yyyy-mm-dd'\n end", "def format_date\n self[:value] ||= {}\n self[:value][:format_date] ||= :short_date\n self[:value][:format_date].to_sym\n end", "def datestyle(arg)\n @datestyle = arg\n end", "def datepicker_options(format, value = nil)\n datepicker_options = {:input_html => {:class => 'ui-datepicker', :value => value.try(:strftime, format)}}\n end", "def date_field(attr, html_options = {})\n date_select(attr, {}, html_options)\n end", "def date_format_options\n Import::DATE_FORMATS.map do |f|\n format = f.gsub('%', '').gsub(/[dmY]/) do\n {'d' => 'DD', 'm' => 'MM', 'Y' => 'YYYY'}[$&]\n end\n [format, f]\n end\n end", "def date_format_options\n Import::DATE_FORMATS.map do |f|\n format = f.delete('%').gsub(/[dmY]/) do\n {'d' => 'DD', 'm' => 'MM', 'Y' => 'YYYY'}[$&]\n end\n [format, f]\n end\n end", "def datepicker_options\n datepicker_options = super\n datepicker_options[:datepicker_options] ||= {}\n datepicker_options[:datepicker_options][:dateFormat] = \"MM d, yy\"\n datepicker_options\n end", "def DateTime_SetFormat(hdp, sz) send_date_time_pick_message(hdp, :SETFORMAT, lparam: sz) end", "def date_format_select_options(selected_value)\n unless @date_format_select_options\n @date_format_select_options = []\n AppConfig['date_formats'].each_with_index do |date_format, index|\n @date_format_select_options << \"<option value='#{index}'>#{date_format}</option>\"\n end\n @date_format_select_options = @date_format_select_options.join(\"\") \n end\n set_selected_option(@date_format_select_options, selected_value)\n end", "def short_date(val, options)\n val ? val.to_date.to_s(:short) : val\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
insert the moved items before the dropped on item, and then recalculate the sort order for the new list only updating items that have a new sort order. do not update all items if the sort order has not changed
def do_update_order_of_items_bulk (moved_item_ids, before_item_id) all_items = Item.where("catalog_id = ?", id).order(:sort_order) # will hold item objects based on ids in moved_items new_items = Array.new # loop through all items related to this catalog and insert the moved items before the item all_items.each do |item| # insert the moved items before this item if its id matches the before_item_id if (item.id==before_item_id.to_i) then moved_item_ids.each do |moved_item_id| new_items.push Item.find(moved_item_id) end end # don't add the moved items back into the array at their regular position but add everything else if moved_item_ids.index(item.id.to_s).nil? then new_items.push item end end # a hash to hold the item id and item sort order of any items that were affected by the move changed_items = Hash.new # now loop through all items and reset the sort order. save the item if changed and populate an array # which we will return current_sort_order=1 new_items.each do | item | if (item.sort_order != current_sort_order ) item.sort_order=current_sort_order if item.save then changed_items[item.id]=item.sort_order end end current_sort_order=current_sort_order+1 end Rails.logger.debug("Changed sort orders: #{changed_items.inspect}") return changed_items end
[ "def reorder_items(playlist)\n # we have to do a sort_by, not order, because the updated attributes have not been saved.\n changed_playlist, new, changed_position, unchanged = playlist.items.\n sort_by(&:position).\n group_by do |item|\n\tif item.playlist_id_was != item.playlist_id\n\t :changed_playlist\n\telsif item.position_was.nil?\n\t :new\n\telsif item.position_was != item.position\n\t :changed_position\n\telse\n\t :unchanged\n\tend\n end.values_at(:changed_playlist, :new, :changed_position, :unchanged).map(&:to_a)\n # items that will be in this playlist\n unmoved_items = unchanged\n # place items whose positions were specified\n changed_position.map {|item| unmoved_items.insert(item.position - 1, item)}\n # add new items at the end\n unmoved_items = unmoved_items + new\n # calculate positions\n unmoved_items.compact.\n select {|item| item.playlist_id_was == item.playlist_id}.\n each_with_index do |item, position|\n\titem.position = position + 1\n end\n\n # items that have moved to another playlist\n changed_playlist.select {|item| item.playlist_id_was != item.playlist_id}.each do |item|\n item.position = nil\n end\n end", "def shift_items_after_chunk(chunk)\r\n items_ids = chunk.collect{|item| item['id']}\r\n these_items = self.class.nested_sortable_model.find(\r\n :all,\r\n :conditions=> {\r\n self.class.nested_sortable_options[:parent_column].to_sym=> nil, \r\n :id=>items_ids\r\n }, \r\n :order=>\"#{self.class.nested_sortable_options[:position_column]}\" \r\n )\r\n \r\n first_item_pos = these_items.first.send(self.class.nested_sortable_options[:position_column])\r\n last_item_pos = these_items.last.send(self.class.nested_sortable_options[:position_column])\r\n \r\n first_item_after = self.class.nested_sortable_model.find(\r\n :first,\r\n :conditions=> \"#{self.class.nested_sortable_options[:parent_column]} IS NULL AND #{self.class.nested_sortable_options[:position_column]} > #{last_item_pos} \",\r\n :order=>\"#{self.class.nested_sortable_options[:position_column]}\" \r\n )\r\n \r\n unless(first_item_after.nil?)\r\n first_item_after_pos = first_item_after.send(self.class.nested_sortable_options[:position_column])\r\n delta = first_item_pos + chunk.length - first_item_after_pos\r\n unless(delta == 0)\r\n delta_with_oper = (delta > 0)? \"+ #{delta.abs.to_s}\" : \"- #{delta.abs.to_s}\"\r\n self.class.nested_sortable_model.update_all(\r\n \"#{self.class.nested_sortable_options[:position_column]} = #{self.class.nested_sortable_options[:position_column]} #{delta_with_oper}\",\r\n \"#{self.class.nested_sortable_options[:parent_column]} IS NULL AND #{self.class.nested_sortable_options[:position_column]} > #{last_item_pos}\"\r\n ) \r\n end\r\n end\r\n return first_item_pos\r\n end", "def reorder_items(folder)\n # we have to do a sort_by, not order, because the updated attributes have not been saved.\n changed_folder, new, changed_position, unchanged = folder.items.\n sort_by(&:position).\n group_by do |item|\n if item.folder_id_was != item.folder_id\n :changed_folder\n elsif item.position_was.nil?\n :new\n elsif item.position_was != item.position\n :changed_position\n else\n :unchanged\n end\n end.values_at(:changed_folder, :new, :changed_position, :unchanged).map(&:to_a)\n\n # items that will be in this folder\n unmoved_items = unchanged\n # place items whose positions were specified\n changed_position.map {|item| unmoved_items.insert(item.position - 1, item)}\n # add new items at the end\n unmoved_items = unmoved_items + new\n # calculate positions\n unmoved_items.compact.\n select {|item| item.folder_id_was == item.folder_id}.\n each_with_index do |item, position|\n item.position = position + 1\n end\n\n # items that have moved to another folder\n changed_folder.select {|item| item.folder_id_was != item.folder_id}.each do |item|\n item.position = nil\n end\n end", "def shuffle_positions_on_intermediate_items(old_position, new_position, avoid_id = nil)\n return if old_position == new_position\n scope = acts_as_list_list\n\n if avoid_id\n scope = scope.where(\"#{quoted_table_name}.#{self.class.primary_key} != ?\", avoid_id)\n end\n\n if old_position < new_position\n # Decrement position of intermediate items\n #\n # e.g., if moving an item from 2 to 5,\n # move [3, 4, 5] to [2, 3, 4]\n items = scope.where(\n \"#{quoted_position_column_with_table_name} > ?\", old_position\n ).where(\n \"#{quoted_position_column_with_table_name} <= ?\", new_position\n )\n\n if sequential_updates?\n items.reorder(acts_as_list_order_argument(:asc)).decrement_sequentially\n else\n items.decrement_all\n end\n else\n # Increment position of intermediate items\n #\n # e.g., if moving an item from 5 to 2,\n # move [2, 3, 4] to [3, 4, 5]\n items = scope.where(\n \"#{quoted_position_column_with_table_name} >= ?\", new_position\n ).where(\n \"#{quoted_position_column_with_table_name} < ?\", old_position\n )\n\n if sequential_updates?\n items.reorder(acts_as_list_order_argument(:desc)).increment_sequentially\n else\n items.increment_all\n end\n end\n end", "def move_lower_items(direction, position, list_name = nil)\n options = evaluate_sortable_options(list_name)\n options[:conditions].first << \" AND #{self.class.table_name}.#{options[:column]} > ? AND #{self.class.table_name}.#{options[:column]} IS NOT NULL\"\n options[:conditions] << position\n self.class.base_class.update_all \"#{options[:column]} = #{options[:column]} #{direction == :up ? '-' : '+'} 1\", options[:conditions]\n end", "def drag_to_order( dimension, items )\n positions = Array.new\n items.each_index do |n|\n item=$driver.find_element( items[n][0].to_sym, items[n][1] )\n positions[n] = item.location.send( dimension )\n end\n positions.sort!\n $debug and print \"In drag_to_order: items: #{YAML.dump(items)}\\n\"\n $debug and print \"In drag_to_order: positions: #{YAML.dump(positions)}\\n\"\n drag_to_order_internal( dimension, items, positions )\n\n # Then we re-pull the positions and check them\n last=0\n current=0\n items.each_index do |n|\n item=$driver.find_element( items[n][0].to_sym, items[n][1] )\n current = item.location.send( dimension )\n current.should satisfy { |current| current > last }\n last = current\n end\n end", "def reorder_entries\n i = 1\n self.entries.each do | e |\n if (e.position != i)\n e.position = i\n e.save\n end\n i += 1\n end\n end", "def move_before(other_item)\n destination = other_item[position_field]\n origin = self[position_field]\n\n if origin > destination\n insert_at destination\n else\n insert_at destination - 1\n end\n end", "def move_lower\n acts_as_list_class.transaction do\n lower_item.try(:decrement_position) and increment_position\n end\n end", "def move_sub_items\n self.items.each do |sub_item|\n if self.case != sub_item.case\n sub_item.case = self.case\n sub_item.location = nil\n sub_item.save!\n end\n end\n end", "def fix_dropped_items\n bad_path = nil\n @model.each do |model, path, iter|\n item = iter[ItemColumn]\n if !item.menu? and iter.has_child?\n bad_path = iter.path\n end\n end\n return unless bad_path\n iter = @model.get_iter(bad_path)\n item = iter[ItemColumn]\n child = iter.first_child or return\n target = child[ItemColumn]\n @model.remove(child)\n nxt = @model.insert_after(iter.parent, iter)\n nxt[ItemColumn] = target\n sel = @view.selection\n sel.unselect_all\n sel.select_iter(nxt)\n @view.scroll_to_cell(nxt.path, nil, false, 0, 0)\n return false\n end", "def update_sortable(pos, newVal)\n sort_function = @parent.sort_function(pos)\n if sort_function\n @sortable[pos] = sort_function.call(newVal)\n else\n @sortable[pos] = newVal\n end\n end", "def adjust_items_by amount, start\n puts \"===============\"\n puts \"adjust_items_by\"\n puts \"===============\"\n puts \"amount: #{amount}; start: #{start}\"\n\n @updated_items = []\n @minutes_minute.items.each do |i|\n puts \"* #{i.title} -- #{i.order}\"\n if not i.new_record? and i.order > start\n puts \" updated\"\n i.order += amount\n @updated_items << i\n end\n end\n end", "def reorder_listings_position\n listings = Listing.find_with_reputation(:item_votes, :all, { :conditions => [\"list_id = ?\", self.id], :order => 'item_votes DESC' })\n listings.each_with_index do |listing, index|\n listing.update_attribute(:position, index + 1)\n end\n self.listings\n end", "def update_list_order(model, order)\n order.to_a.each_with_index do |item, pos|\n model.update(item, position:(pos + 1))\n end\n end", "def move_after(other_item)\n destination = other_item[position_field]\n origin = self[position_field]\n\n if origin > destination\n insert_at destination + 1\n else\n insert_at destination\n end\n end", "def remove_from_reorder_list\n\t\tItem.where(id: params[:i_id]).first\n\t\t@reorder_items = Item.all.need_reorder.alphabetical.to_a\n\tend", "def reorder\n end", "def move_lower\n return unless lower_item\n\n acts_as_list_class.transaction do\n lower_item.decrement_position\n increment_position\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the label for this topic.
def label _topic_json.fetch("label", "") end
[ "def label\n return @label\n end", "def getLabelName\n\t\t\t\n\t\t\t\t\treturn @labelName\n\t\t\t\n\t\t\t\tend", "def _label\n field = self.content_type.label_field\n value = self.dynamic_getter(field.name)\n\n if field.type == :belongs_to\n value.try(:_label)\n else\n value\n end\n end", "def label\n name\n end", "def label\n @label || \"unknown\"\n end", "def msg_label()\n type_label= @@msg_types[@msg_type][:TypeLabel]\n if (type_label.is_a?(String))\n return type_label\n else\n return type_label.call(self)\n end\n end", "def get_label\n get_field_config['label']\n end", "def to_s\n label\n end", "def get_label(t)\n labels = t.counterplayers(:atype => @base_locator+\"/association/scoping\", :rtype=>@base_locator+\"/types/named_topic_type\", :otype => @base_locator+\"/types/displaylabel\" )\n for label in labels\n if $current_lang\n return get_label_in_scope(t,$current_lang)\n else\n return get_default_label(label)\n end\n end\n return get_default_label(t)\n end", "def label\n structure.label.to_sentence\n end", "def label(name)\n @labels[name.to_sym]\n end", "def get_label(number)\n return @labels[number]\n end", "def _label\n name = self.content_type.label_field_name\n self.dynamic_getter(name)\n end", "def label_for(key)\n if !@labels\n labels\n end\n @labels[key.to_sym]\n end", "def label(device_id)\n device_label = device_labels.for(device_id).first\n device_label ? device_label.label : device_id\n end", "def get_ds_label ds_id\n ds = self.datastreams[ds_id]\n ds.dsLabel unless ds.nil?\n end", "def to_label\n (@model_decorator.guess_title(@resource) || primary_key_value).to_s\n end", "def node_label\n node_type['label']\n end", "def display_label\n return Xref.find(self.display_xref_id).display_label\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a link to Wikipedia for this topic, or None if this topic couldn't be linked to a wikipedia page.
def wikipedia_link _topic_json.fetch("wikiLink", nil) end
[ "def wikipedia_link\n to_nil _response_entity.fetch(\"wikiLink\", nil)\n end", "def wikipedia\n uri = nil\n @artist_data[\"relations\"].each do |rel|\n if rel[\"type\"] == \"wikipedia\"\n uri = rel[\"url\"][\"resource\"]\n end\n end\n return uri\n end", "def url\n # Some courses do not have corresponding on-wiki pages, so they have no wiki_title or url.\n return unless wiki_page?\n \"#{home_wiki.base_url}/wiki/#{wiki_title}\"\n end", "def make_wiki_uri\n\tif self =~ /\\/wiki/ && !( self =~ /en.wikipedia.org/) \n\t\tthen return \"http://en.wikipedia.org\" + self\n\t\telse puts \"Given non-wiki uri in make_wiki_uri: #{ self}\"; return self end\n end", "def get_default_link(material)\n return 'NO LINK' if material.nil?\n return 'NO LINK' if material == true\n\n url = nil\n\n url = \"topics/#{material['topic_name']}/tutorials/#{material['tutorial_name']}/slides.html\" if material['slides']\n\n if material['hands_on'] && (material['hands_on'] != 'external' && material['hands_on'] != '')\n url = \"topics/#{material['topic_name']}/tutorials/#{material['tutorial_name']}/tutorial.html\"\n end\n\n url\n end", "def wiki_url\n \"https://hq.songbirdnest.com/wiki/index.php?title=Release:#{name}\"\n end", "def get_wiki_url(query)\n search_keywords = query.strip.gsub(/\\s+/,'+')\n url = \"http://www.google.com/search?q=#{search_keywords}+site%3Aen.wikipedia.org&safe=active\"\n begin\n doc = Hpricot(open(url, \"UserAgent\" => \"reader\"+rand(10000).to_s).read)\n result = doc.search(\"//div[@id='ires']\").search(\"//li[@class='g']\").first.search(\"//a\").first\n rescue\n return ''\n end\n if result\n return result.attributes[\"href\"]\n else\n return ''\n end\n end", "def help_link(wiki_entry_name=nil)\n wiki_url = \"https://github.com/indykish/identityprov/wiki\"\n if wiki_entry_name\n wiki_url += \"/#{wiki_entry_name}\"\n link_text = \"Help for #{wiki_entry_name.underscore_humanize}\" \n else\n link_text =\"Help\" \n end\n link_to_ link_text, wiki_url, { :target => '_blank'}\n end", "def wiki(project, slug)\n get(\"/projects/#{url_encode project}/wikis/#{slug}\")\n end", "def wiki\n @wiki ||= Smeagol::Wiki.new(wiki_dir)\n end", "def wiki\n @wiki ||= Smeagol::Wiki.new(wiki_dir)\n end", "def ask_wikipedia(actual_locale, author)\n if author.link =~ /http.*wikipedia.org\\//\n # change http to https, delete mobile version, follow redirection\n author.link = WikipediaService.new.clean_link(author.link)\n result = WikipediaService.new.call(actual_locale, author.link)\n links = result[:links]\n names = result[:names]\n I18n.available_locales.each do |locale|\n if locale != actual_locale\n author.send(\"link_#{locale}=\", links[locale.to_s])\n if names[locale.to_s].present?\n result = split_name(names[locale.to_s], locale)\n author.send(\"firstname_#{locale}=\", result[:firstname])\n author.send(\"name_#{locale}=\", result[:lastname])\n else\n author.send(\"firstname_#{locale}=\", nil)\n author.send(\"name_#{locale}=\", nil)\n end\n end\n end\n end\n end", "def get_wikipedia_image_url(wikipedia_url)\n begin\n\n return nil if !wikipedia_url || wikipedia_url.empty?\n\n # Download the wikipedia page\n page = Nokogiri::HTML(open(wikipedia_url))\n\n # Get the image href:\n link = page.css( @settings.image_selector ).first\n return if !link\n image_href = link.attr('href')\n image_href = URI.unescape(image_href)\n # image_href => '/wiki/Archivo:Metallica_at_The_O2_Arena_London_2008.jpg'\n\n # Get the image \"id\":\n slash_idx = image_href.rindex('/')\n return if !slash_idx\n image_id = image_href[ slash_idx + 1 .. -1 ]\n # image_id => 'Archivo:Metallica_at_The_O2_Arena_London_2008.jpg'\n\n # Get the full URL:\n # /w/api.php?action=query&prop=imageinfo&format=json&iiprop=url&titles=Archivo%3AMetallica_at_The_O2_Arena_London_2008.jpg\n image_info = Wikipedia.client.request( {\n action: 'query',\n prop: 'imageinfo',\n iiprop: 'url',\n titles: image_id,\n format: 'json'\n } )\n # result => {\n # \"batchcomplete\": \"\",\n # \"query\": {\n # \"normalized\": [\n # {\n # \"from\": \"Archivo:Metallica_at_The_O2_Arena_London_2008.jpg\",\n # \"to\": \"Archivo:Metallica at The O2 Arena London 2008.jpg\"\n # }\n # ],\n # \"pages\": {\n # \"-1\": {\n # \"ns\": 6,\n # \"title\": \"Archivo:Metallica at The O2 Arena London 2008.jpg\",\n # \"missing\": \"\",\n # \"imagerepository\": \"shared\",\n # \"imageinfo\": [\n # {\n # \"url\": \"https://upload.wikimedia.org/wikipedia/commons/0/07/Metallica_at_The_O2_Arena_London_2008.jpg\",\n # \"descriptionurl\": \"https://commons.wikimedia.org/wiki/File:Metallica_at_The_O2_Arena_London_2008.jpg\"\n # }\n # ]\n # }\n # }\n # }\n # }\n image_info = search = JSON.parse(image_info)\n\n image_url = image_info['query']['pages']['-1']['imageinfo'][0]['url']\n return image_url\n rescue\n Log.log_last_exception\n return nil\n end\n end", "def link_to_page(page_name, wiki= @wiki, text = nil, options = {})\r\n raise 'Wiki not defined' if wiki.nil?\r\n wiki.make_link(page_name, text, \r\n options.merge(:base_url => \"#{base_url}/#{wiki.name}\"))\r\n end", "def fetch_wiki(url)\n #puts url\n \n @http = Net::HTTP.new(url.host, url.port)\n wikiRequest = Net::HTTP::Get.new(url)\n wikiResponse = @http.request(wikiRequest)\n \n #In case that Wikipedia will redirect the search result to a stored page\n case wikiResponse\n when Net::HTTPSuccess then\n wikiResponse.body\n when Net::HTTPRedirection then\n location = wikiReponse['location']\n warn \"Redirect to #{location}\"\n fetch_wiki(URI(location))\n else\n wikiResponse.value\n end\n end", "def wiki_url\n \"https://hq.songbirdnest.com/wiki/index.php?title=Release:#{name}_Iteration_Notes#Iteration_#{@number}\"\n end", "def open_wiki(params = {})\n Helpers.open_in_browser gem.wiki_url\n end", "def fetch_dokuwiki_link(dw_link)\n dw_link = dw_link.split('|')[0]\n unless @@dokuwiki_links.key?(dw_link)\n print 'Getting dokuwiki link %s... ' % [dw_link]\n href = 'https://door43.org/%s' % [dw_link.gsub(/:/, '/')]\n dw_page = ''\n open(href, 'r') do |f|\n dw_page = f.read\n end\n matches = dw_page.scan(/<title>(.*?)<\\/title>/)\n page_title = matches[0][0].gsub(/\\s\\[Door43\\]$/, '') # remove [Door43] from the end of the title\n @@dokuwiki_links[dw_link] = '[%s](%s)' % [page_title, href]\n puts 'finished.'\n end\n\n @@dokuwiki_links[dw_link]\n end", "def process_href(href)\n \"https://en.wikipedia.org\" + href\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compute the price range
def price_range prices = variants.collect(&:price).collect(&:to_f) format = "%0.2f" if prices.min != prices.max "#{format % prices.min} - #{format % prices.max}" else format % prices.min end end
[ "def price_range\n return @price_range if @price_range\n return @price_range = ['N/A', 'N/A'] if active_variants.empty?\n @price_range = active_variants.inject([active_variants.first.price, active_variants.first.price]) do |a, variant|\n a[0] = variant.price if variant.price < a[0]\n a[1] = variant.price if variant.price > a[1]\n a\n end\n end", "def price_range\n prices = variants.collect(&:price)\n format = \"%0.2f\"\n if prices.min != prices.max\n \"#{format % prices.min} - #{format % prices.max}\"\n else\n format % prices.min\n end\n end", "def price_range\n prices = variants.collect(&:price).collect(&:to_f)\n format = \"%0.2f\"\n if prices.min != prices.max\n \"#{format % prices.min} - #{format % prices.max}\"\n else\n format % prices.min\n end\n end", "def price_at_half_range\n\t\treturn self.half_range + self.low\n\tend", "def price_range\n\t price.price_range #fetches the price range as an attribute when I add it to the controller...\n\tend", "def value_range\n return sale_price_range if deal_type.sale?\n\n rent_gross_range\n end", "def price_range\n return @price_range if @price_range\n return @price_range = ['N/A', 'N/A'] if active_variants.empty?\n @price_range = active_variants.minmax {|a,b| a.price <=> b.price }.map(&:price)\n end", "def price_range\n public_prices = valid_vouchers.select(&:public?).map(&:price)\n public_prices.empty? ? [] : [public_prices.min, public_prices.max]\n end", "def price_range\n public_prices = valid_vouchers.select(&:public?).map(&:price).reject(&:zero?)\n public_prices.empty? ? [] : [public_prices.min, public_prices.max]\n end", "def get_price_ranges(product_price)\n price_ranges = []\n\n count = product_price[:price_ranges][:total_elements].to_i\n\n (0..count - 1).each do|i|\n price_range = product_price[:price_ranges][:priceranges][i]\n\n price_ranges << {\n priceRange: {\n quantityBeginRange: price_range[:quantity_begin_range],\n price: price_range[:price],\n level: price_range[:level],\n eid: price_range[:eid]\n }\n }\n end\n\n price_ranges\n end", "def price(price_range)\n set_range_parameter(:price, price_range)\n end", "def custom_range_compute_price(user)\n Event::JobClosed.\n date_range(custom_range_start, custom_range_end).\n where(dxuser: user.dxuser).\n sum(:price)\n end", "def price_between(products, min, max)\n# list = []\n# products.each do |product|\n# if product[:price] > min && product[:price] < max\n# list << product\n# end \n# end\n# list\n# end\n products.select do |product|\n product[:price] > min && product[:price] < max \n end\nend", "def get_price_range(product_ids_array,sub_category_id,type)\n\n #Senthil: removed exclude_availabilities_array since, availablility should be handled in specific page and\n #because of handling it here, some products shows up without price.\n\n #set_excludable_availability_ids(1)\n # altering this method to fetch only online price\n General.get_price_range(product_ids_array,sub_category_id,\"online\").sort_by{|i| i[1]}\n\n end", "def booking_price_calculation\n\t\tcurrent_booking = (self.start_date..self.end_date).to_a\n\t\tprice = []\n\n\t\tspecial_bookings = SpecialPrice.where('room_id=?', self.room_id)\n\t\t#binding.pry\n\t\tspecial_bookings.each do |sdate|\n\t\t\tspecial_booking = (sdate.start_date..sdate.end_date).to_a\n\n\t\t\tif !(current_booking&special_booking).empty?\n\t\t\t\t#binding.pry\n\t\t\t\tprice << (current_booking&special_booking).count * sdate.price\n\t\t\t\tcurrent_booking -= special_booking\n\t\t\t\t#binding.pry\n\t\t\tend\n\t\tend\n\n\t\tif price.empty?\n\t\t\tspecial_booking_price = 0\n\t\t\t#binding.pry\n\t\telse\n\t\t\tspecial_booking_price = price.inject(:+)\n\t\t\t#binding.pry\n\t\tend\n\n\t\tnormal_day_cost = (current_booking.length) * self.room.price\n\t\tself.price = (special_booking_price + normal_day_cost)\n\t\t#binding.pry\n\n\n\tend", "def list_price\n support_product_number = type == 'hw' ? 'HA104A' : 'HA107A'\n year1 = PricingDbHpPrice.option_price(:product_number => support_product_number, :year => 1, :option_number => option_number)\n year3 = PricingDbHpPrice.option_price(:product_number => support_product_number, :year => 3, :option_number => option_number)\n year4 = PricingDbHpPrice.option_price(:product_number => support_product_number, :year => 4, :option_number => option_number)\n @list_price = [(year4 - year3)/BigDecimal(\"12.0\"), (year3 - year1)/BigDecimal(\"24.0\")].max\n end", "def price_limit\n # earning records do not go back far enough to compute price limit\n return 0 if historic_eps(7).nil? || ttm_eps.nil?\n\n# || historic_eps(7).to_i == 0\n\n lim = min( historic_eps(7).to_f*25, ttm_eps*20 )\n min( historic_eps(3).to_f * 15, lim ) # second criteria from page 182\n end", "def price_range(obj)\n if obj != nil && obj.sharespaces.count > 0\n if obj.sharespaces.order(cost: :desc).first.cost == 0.0 or nil\n \"Free\"\n else\n \"From $#{obj.sharespaces.order(cost: :desc).first.cost.round(2)}\"\n end\n\n else\n \"No sharespaces yet.\"\n end\n end", "def existing_discount_quantity_range\n product_quantity_discounts = self.quantity_discounts\n minimum_quantity = []\n maximum_quantity = []\n product_quantity_discounts.each do |q|\n minimum_quantity << q.low_quantity\n maximum_quantity << q.high_quantity\n end\n return minimum_quantity.sort.first..maximum_quantity.sort.last\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get VirtualBox's version string by capturing the output of 'VBoxManage v'. Returns empty string if unable to determine version.
def get_virtualbox_version begin if windows? ver = `"%ProgramFiles%\\Oracle\\VirtualBox\\VBoxManage" -v 2>NULL` else ver = `VBoxManage -v 2>/dev/null` end rescue ver = '' end ver.gsub(/r.*/m, '') end
[ "def version\n logger.info \"Determining Vagrant version for #{description}\"\n output = execute!(\"--version\").stdout\n Derelict::Parser::Version.new(output).version\n end", "def vagrant_version\n ver = call_vagrant \"-v\"\n unless ver.nil?\n ver = ver[/Vagrant( version)? ([0-9]+(\\.[0-9]+)+)/, 2]\n end\n ver\n end", "def read_guest_additions_version\n output = execute(\"guestproperty\", \"get\", @uuid, \"/VirtualBox/GuestAdd/Version\")\n return $1.to_s if output =~ /^Value: (.+?)$/\n return nil\n end", "def version(*args)\n result = self.exec(\"lxc-version\", *args).scan(REGEX_VERSION).flatten.compact\n result.first.strip\n rescue\n nil\n end", "def hypervisor_version\n output_ptr = FFI::MemoryPointer.new(:ulong)\n FFI::Libvirt.virConnectGetVersion(pointer, output_ptr)\n FFI::Libvirt::Util.parse_version_number(output_ptr.get_ulong(0))\n end", "def version(version)\n @text =~ /^Vagrant version #{version}$/\n end", "def version(*args)\n result = self.exec(\"lxc-version\", *args).scan(REGEX_VERSION)\n result.flatten!.compact!\n\n result.first.strip\n end", "def version\n LXC.run('version').strip.split(' ').last\n end", "def get_version\n execute_cmd(\"lshmc -V | grep 'Version:'|cut -d':' -f2\").chomp\n end", "def host_version\n vm.driver.version\n end", "def ver\n if v = version\n str = +\"#{program_name} #{[v].join('.')}\"\n str << \" (#{v})\" if v = release\n str\n end\n end", "def version\n\t\t\t\t@@version ||= if File.readable?('/sys/devices/virtual/dmi/id/bios_version')\n\t\t\t\t\tIO.read('/sys/devices/virtual/dmi/id/bios_version').tap(&:strip!)\n\t\t\t\telse\n\t\t\t\t\t''.freeze\n\t\t\t\tend\n\t\t\tend", "def revision\n Lib.lib.virtualbox.revision\n end", "def version\n command(:version).split(/\\n/)\n .map { |v| v.split(/\\s*version:?\\s*/) }\n .to_h\n end", "def version\n attr = data.xpath('vnstat').attr('version')\n raise 'Unable to determine version' if attr.nil?\n\n attr.text\n end", "def get_vbox_vm_info(options)\n message = \"Information:\\tGetting value for \"+options['search']+\" from VirtualBox VM \"+options['name']\n if options['search'].to_s.match(/MAC/)\n command = \"#{options['vboxmanage']} showvminfo \\\"#{options['name']}\\\" |grep MAC |awk '{print $4}' |head -1\"\n else\n command = \"#{options['vboxmanage']} showvminfo \\\"#{options['name']}\\\" |grep \\\"#{options['search']}\\\" |cut -f2 -d:\"\n end\n output = execute_command(options,message,command)\n vm_info = output.chomp.gsub(/^\\s+/,\"\")\n return vm_info\nend", "def engine_version\n m = VERSION_REGEX.match(@text)\n return '' unless m && m[1]\n\n m[1]\n end", "def get_version\r\n formats = [\r\n [\"S\", \"descr\"],\r\n [\"I\", \"jdwp_major\"],\r\n [\"I\", \"jdwp_minor\"],\r\n [\"S\", \"vm_version\"],\r\n [\"S\", \"vm_name\"]\r\n ]\r\n sock.put(create_packet(VERSION_SIG))\r\n response = read_reply\r\n entries = parse_entries(response, formats, false)\r\n entries.each { |e| @vars.merge!(e) }\r\n end", "def string\n\t\t\t\t@@string ||= File.readable?('/proc/version') ? IO.read('/proc/version', 1024).tap(&:strip!) : ''\n\t\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a room. If no template is specified, use the default, empty template.
def createRoom(room, template = nil) template = "default" if !template data = "mode=xml&room=#{room}&template=#{template}&#{@authToken}" res = RTC::http_post(@url, data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root if response.local_name != "meeting-info" raise RTC::Error, res else return "ok" end end
[ "def add_room room_template\n raise \"only a room_template may be added to a zone\" unless room_template.is_a? RoomTemplate\n room_template.location = self\n room_instance_id = next_room_instance_id\n get_attribute(:rooms)[room_instance_id] = room_template\n room_instance_id\n end", "def create_room(options)\n\t\t\tdo_api :post, 'room/create', options.merge({ :session => @session })\n\t\tend", "def create_room(id)\n return Room.new(id)\n end", "def create_room\n Room.new\n end", "def create_room(name, topic = nil)\n raise \"Not implemented\"\n # find_room_by_name(name) if verify_response(post(\"account/create/room?from=lobby\", {:room => {:name => name, :topic => topic}}, :ajax => true), :success)\n end", "def create_room(name, topic = nil)\n find_room_by_name(name) if verify_response(post(\"account/create/room?from=lobby\", {:room => {:name => name, :topic => topic}}, :ajax => true), :success)\n end", "def create_template(params = nil, headers = nil)\n post(\"/api/v2/templates\", params, headers)\n end", "def create_room(payload)\n JSON.parse Rooms.create_room(@base_url, @headers, payload.to_json)\n end", "def create_room(name, topic = nil)\n connection.post('/rooms.json', :body => { :room => { :name => name, :topic => topic } }.to_json)\n find_room_by_name(name)\n end", "def create_room(company, params = {})\n $LOG.i \"running \" + __method__.to_s\n @client.post '/messages/v3/' + company + '/rooms', params\n end", "def room(name, participant_identity: nil, **keyword_args)\n append(Room.new(name, participant_identity: participant_identity, **keyword_args))\n end", "def generate_room\n opentok = OpentokApi.new\n session = opentok.create_session\n\n teacher_token = opentok.get_user_token(self.teacher, self, session.session_id)\n student_token = opentok.get_user_token(self.student, self, session.session_id)\n\n create_room(\n name: teacher.first_name,\n teacher_token: teacher_token, \n student_token: student_token,\n session_id: session.session_id\n )\n end", "def new\n # Create a dummy room\n @chat_room = ChatRoom.new\n end", "def create\n @room = Room.new(params[:room])\n\n respond_to do |format|\n if @room.save\n flash[:success] = t('room.created')\n format.html { redirect_to(rooms_path) }\n format.xml { render :xml => @room, :status => :created, :location => @room }\n else\n flash[:error] = t('default_error_message')\n format.html { render :action => \"new\" }\n format.xml { render :xml => @room.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_template(opts)\n opts = check_params(opts,[:templates,:template_attributes])\n super(opts)\n end", "def create\n @tddbc_room = Tddbc::Room.new(params[:tddbc_room])\n\n respond_to do |format|\n if @tddbc_room.save\n format.html { redirect_to @tddbc_room, notice: 'Room was successfully created.' }\n format.json { render json: @tddbc_room, status: :created, location: @tddbc_room }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tddbc_room.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @empty_room = EmptyRoom.new(empty_room_params)\n\n respond_to do |format|\n if @empty_room.save\n format.html { redirect_to @empty_room, notice: 'Empty room was successfully created.' }\n format.json { render :show, status: :created, location: @empty_room }\n else\n format.html { render :new }\n format.json { render json: @empty_room.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @room = Room.new(params[:room])\n\n respond_to do |format|\n if @room.save\n format.html { redirect_to(@room, :notice => 'Room was successfully created.') }\n format.xml { render :xml => @room, :status => :created, :location => @room }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @room.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_chatroom\n Chatroom.create!(user: self)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a room session for external authentication.
def getSession(room) session = Session.new(@roomInstance, url.split("/")[-1], room) session.getSecret(@baseURL, @authToken, @authHeaders) return session end
[ "def auth_session\n @session ||= begin\n @session = Origen.session.user\n @session.private = true\n @session\n end\n end", "def open_session\n return if @session_id\n json = api_get('authenticate')\n @session_id = json['session_id'] or raise RuntimeError, \"No session id returned\"\n end", "def session\n @session = self.session_spawn if !@session\n return @session\n end", "def session\n @@session ||= []\n if @@session[self.id].nil?\n session = GData::Client::Calendar.new\n token = session.clientlogin(username,password)\n @@session[self.id] = session\n end\n @@session[self.id]\n end", "def current_room\n\t@current_room ||= Room.where(:user_id => session[:user_id]).first if session[:user_id] #if current_user is nil then replace it, if there is a current session\n end", "def user_session\n UserSession.new(session)\n end", "def room\n client.room || raise(APIError, 'User is not currently in a room')\n end", "def session\n Thread.current['clients_manager'].client('Website').session\n end", "def activate\n result = remote_call(\"auth.getSession\", {:auth_token => @desktop_auth_token}, true)\n if result != nil\n @session_user_id = result.at(\"uid\").inner_html\n @session_key = result.at(\"session_key\").inner_html\n @session_secret = result.at(\"secret\").inner_html\n end\n end", "def session\n self\n end", "def get\n params.required(:id)\n\n # Grab the device that is trying to authenticate\n unathenticated_error unless @api_consumer.is_a? Service\n service = @api_consumer\n\n @session = service.sessions.find(params[:id])\n end", "def session\n raw_session[\"warden.user.#{scope}.session\"] ||= {}\n end", "def get_session(opts)\n return if not active\n ::ApplicationRecord.connection_pool.with_connection {\n wspace = Msf::Util::DBManager.process_opts_workspace(opts, framework)\n addr = opts[:addr] || opts[:address] || opts[:host] || return\n host = get_host(:workspace => wspace, :host => addr)\n time = opts[:opened_at] || opts[:created_at] || opts[:time] || return\n ::Mdm::Session.find_by_host_id_and_opened_at(host.id, time)\n }\n end", "def session\n @session ||= Session.new(@endpoint)\n end", "def to_session\n BeyondApi::Session.new(api_url: beyond_api_url,\n access_token: beyond_access_token,\n refresh_token: beyond_refresh_token)\n end", "def open_session\n s = Session.wrap(Cproton.pn_session(@impl))\n s.open\n return s\n end", "def obtain_session\n session = @session_storage.obtain_session\n if !session\n session = @auth_client.auth(@username,\n @password,\n @client_id,\n @client_secret)\n @session_storage.store_session(session)\n end\n\n session\n end", "def get_login_session\n raise LoginRequired.new(\"Login required\", self) unless @login_session\n @login_session\n end", "def session\n Wee::Session.current\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /wait_queues POST /wait_queues.json
def create @wait_queue = WaitQueue.new(wait_queue_params) respond_to do |format| if @wait_queue.save format.html { redirect_to @wait_queue, notice: 'Wait queue was successfully created.' } format.json { render :show, status: :created, location: @wait_queue } else format.html { render :new } format.json { render json: @wait_queue.errors, status: :unprocessable_entity } end end end
[ "def create\n @wait_queue = wait_queues.new(wait_queue_params)\n\n respond_to do |format|\n if @wait_queue.save\n format.html { redirect_to @wait_queue, notice: \"Wait queue was successfully created.\" }\n format.json { render :show, status: :created, location: @wait_queue }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @wait_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_queues\n queue\n exchange\n end", "def create_queues\n config[:jobs].each do |k, v|\n next if get_queue_by_queue_name(v[:queue_name]).exists?\n\n queue_name = full_queue_name(v[:queue_name])\n conn.queues.create(queue_name, :visibility_timeout => 60)\n end\n end", "def test_queues\n puts \"test_queues-#{Time.now.to_i}\"\n\n qname = \"some_queue_that_does_not_exist_1\"\n queue = @client.queue(qname)\n # create at least one queue\n queue.post('create queue message')\n # queue should exist now\n m = queue.get\n refute_nil m\n\n res = @client.queues.list(page: 1, per_page: 30)\n # puts \"res.size: #{res.size}\"\n assert_equal 30, res.size\n\n # delete queue on test complete\n resp = queue.delete_queue\n assert_equal 200, resp.code, \"API must response with HTTP 200 status, but returned HTTP #{resp.code}\"\n end", "def index\n @wait_queues = wait_queues\n end", "def autogenerated_queues\n []\n end", "def refill_all_queues!\n # Dla POST musi byc jakies 'body' requestu, bo serwery czesto rzucaja wyjatkami (WEBrick w szczegolnosci).\n post '/queues/refill_all', :body => ' '\n true\n end", "def create_queue(queue, opts={})\n resp = retry_unless([201,422]) { connection.put(\"queues/#{queue}\") } \n raise ObjectAlreadyExistsError, JSON.parse(resp.body)[\"error\"] if resp.status == 422\n raise ConnectionError, \"Failed to create queue. status: #{resp.status} response: #{resp.body}\" unless resp.status == 201\n # No meaningful data in response\n true\n end", "def jobs_waiting\n Hash[@resque_data_store.queue_names.map { |queue_name|\n [\n queue_name,\n @resque_data_store.everything_in_queue(queue_name).map { |json|\n Resque.decode(json)\n }.map { |payload|\n Job.new(payload: payload, queue: queue_name)\n }\n ]\n }]\n end", "def enqueue_workflow\n queue = Amqp::RabbitClient.new\n queue.push id\n end", "def enqueued_jobs; end", "def push(queue, item)\n watch_queue(queue)\n fraggle.set(\"/queue/#{queue}/#{$$}.#{Time.now.to_f}/job\", encode(item))\n end", "def perform_enqueued_at_jobs; end", "def pending_queues\n resp = get '/queues'\n\n Array.new.tap do |pending_queues|\n resp.parsed_response.css('queue').each do |queue_xml|\n queue = Elibri::ApiClient::ApiAdapters::V1::Queue.build_from_xml(self, queue_xml)\n pending_queues << queue if queue.products_count.nonzero?\n end \n end\n end", "def create_construction_queue(queue_type)\n self.queues.create({\n :type_id => queue_type[:id], \n :threads => queue_type[:base_threads],\n# :max_length => queue_type[:base_slots], \n }) \n end", "def create\n @jobs_queue = JobsQueue.new(params[:jobs_queue])\n\n respond_to do |format|\n if @jobs_queue.save\n @jobs_queue.set_visibility(current_user, params)\n @jobs_queue.save_aws_key(current_user, params[:aws_credentials]) if params[:jobs_queue][:is_autoscalable] and (params[:jobs_queue][:is_autoscalable] != '0') and params[:jobs_queue][:aws_key_id] and (params[:jobs_queue][:aws_key_id] == '0')\n @jobs_queue.start_processing_nodes(current_user) if @jobs_queue.is_autoscalable and (@jobs_queue.min_processing_nodes.to_i > 0)\n flash[:notice] = 'JobsQueue was successfully created.'\n format.html { redirect_to(jobs_queues_path) }\n format.xml { render :xml => @jobs_queue, :status => :created, :location => @jobs_queue }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @jobs_queue.errors, :status => :unprocessable_entity }\n end\n end\n end", "def queue(process, units)\n waiting_list.push([process, units])\n end", "def assert_enqueued_jobs(number, only: T.unsafe(nil), except: T.unsafe(nil), queue: T.unsafe(nil), &block); end", "def perform_enqueued_jobs; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /wait_queues/1 PATCH/PUT /wait_queues/1.json
def update respond_to do |format| if @wait_queue.update(wait_queue_params) format.html { redirect_to @wait_queue, notice: 'Wait queue was successfully updated.' } format.json { render :show, status: :ok, location: @wait_queue } else format.html { render :edit } format.json { render json: @wait_queue.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @wait_queue.update(wait_queue_params)\n format.html { redirect_to @wait_queue, notice: \"Wait queue was successfully updated.\" }\n format.json { render :show, status: :ok, location: @wait_queue }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @wait_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_current_queue new_queue\n log_everything(\"Update current queue\")\n log_everything(\"New queue: \\\"#{new_queue.to_s}\\\"\")\n craft_firebase_command(\"minesweeper/queue.json\", \"PUT\", new_queue)\nend", "def update\n min_processing_nodes = @jobs_queue.min_processing_nodes\n respond_to do |format|\n if @jobs_queue.update_attributes(params[:jobs_queue])\n @jobs_queue.set_visibility(@jobs_queue.owner, params)\n @jobs_queue.save_aws_key(@jobs_queue.owner, params[:aws_credentials]) if params[:jobs_queue][:is_autoscalable] and (params[:jobs_queue][:is_autoscalable] != '0') and params[:jobs_queue][:aws_key_id] and (params[:jobs_queue][:aws_key_id] == 'new_key')\n @jobs_queue.update_processing_nodes(current_user, min_processing_nodes) if @jobs_queue.is_autoscalable and ((min_processing_nodes < @jobs_queue.min_processing_nodes) or (@jobs_queue.max_processing_nodes < @jobs_queue.processing_nodes.size))\n flash[:notice] = 'JobsQueue was successfully updated.'\n format.html { redirect_to((current_user and current_user.is_site_admin? and current_user != @jobs_queue.owner) ? by_user_jobs_queues_path(:user_id => @jobs_queue.owner.id) : @jobs_queue) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @jobs_queue.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @task_queue.update(task_queue_params)\n format.html { redirect_to @task_queue, notice: 'Task queue was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @task_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @email_queue.update(email_queue_params)\n format.html { redirect_to @email_queue, notice: 'Email queue was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @email_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ticket_queue.update(ticket_queue_params)\n format.html { redirect_to @ticket_queue, notice: 'Ticket queue was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ticket_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n uid = params[:id]\n movie_id = params[:movie_id]\n new_rank = params[:new_rank]\n validate_movies movie_id\n\n updated_queue = MovieQueues.update_queue(uid, movie_id, new_rank)\n\n render json: updated_queue.to_json, status: :ok\n end", "def create\n @wait_queue = wait_queues.new(wait_queue_params)\n\n respond_to do |format|\n if @wait_queue.save\n format.html { redirect_to @wait_queue, notice: \"Wait queue was successfully created.\" }\n format.json { render :show, status: :created, location: @wait_queue }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @wait_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @message_queue.update(message_queue_params)\n format.html { redirect_to @message_queue, notice: 'Message queue was successfully updated.' }\n format.json { render :show, status: :ok, location: @message_queue }\n else\n format.html { render :edit }\n format.json { render json: @message_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enqueue.update(enqueue_params)\n format.html { redirect_to @enqueue, notice: 'Enqueue was successfully updated.' }\n format.json { render :show, status: :ok, location: @enqueue }\n else\n format.html { render :edit }\n format.json { render json: @enqueue.errors, status: :unprocessable_entity }\n end\n end\n end", "def refill_all_queues!\n # Dla POST musi byc jakies 'body' requestu, bo serwery czesto rzucaja wyjatkami (WEBrick w szczegolnosci).\n post '/queues/refill_all', :body => ' '\n true\n end", "def update\n respond_to do |format|\n if @assignment_queue.update(assignment_queue_params)\n format.html { redirect_to @assignment_queue, notice: 'Assignment queue was successfully updated.' }\n format.json { render :show, status: :ok, location: @assignment_queue }\n else\n format.html { render :edit }\n format.json { render json: @assignment_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @mail_queue.update(mail_queue_params)\n format.html { redirect_to @mail_queue, notice: 'Mail queue was successfully updated.' }\n format.json { render :show, status: :ok, location: @mail_queue }\n else\n format.html { render :edit }\n format.json { render json: @mail_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @training_queue = Training::Queue.find(params[:id])\n\n respond_to do |format|\n if @training_queue.update_attributes(params[:training_queue])\n format.html { redirect_to @training_queue, notice: 'Queue was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @training_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @dequeue.update(dequeue_params)\n format.html { redirect_to @dequeue, notice: 'Dequeue was successfully updated.' }\n format.json { render :show, status: :ok, location: @dequeue }\n else\n format.html { render :edit }\n format.json { render json: @dequeue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @jobs_queue.update_attributes(params[:jobs_queue])\n @jobs_queue.set_visibility(current_user, params)\n flash[:notice] = 'JobsQueue was successfully updated.'\n format.html { redirect_to(@jobs_queue) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @jobs_queue.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @queuing = Queuing.find(params[:id])\n\n respond_to do |format|\n if @queuing.update_attributes(params[:queuing])\n format.html { redirect_to @queuing, notice: 'queuing was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @queuing.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @queue_model.update(queue_model_params)\n format.html { redirect_to @queue_model, notice: 'Queue model was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @queue_model.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @queue_op.update(queue_op_params)\n format.html { redirect_to @queue_op, notice: 'Queue op was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @queue_op.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /wait_queues/1/countup PATCH/PUT /wait_queues/1/countup.json
def countup respond_to do |format| @wait_queue.count += 1 if @wait_queue.save format.html { redirect_to @wait_queue, notice: 'CountUp successfully.' } format.json { render :show, status: :ok, location: @wait_queue } end end end
[ "def update_kept_request_count\n new_kept_data = kept.map do |kept_data|\n parsed = Hanami::Utils::Json.parse(kept_data)\n parsed['count'] += 1 if is_hash?(parsed) && parsed['count'].is_a?(Integer)\n Hanami::Utils::Json.generate(parsed)\n end\n\n update_kept(new_kept_data)\n end", "def set_queueing_method_bucket_count(opts)\n opts = check_params(opts,[:queues,:bucket_counts])\n super(opts)\n end", "def process\n key = \"api_call_count_for_#{from}\"\n data = $redis.get(key)\n\n if data.present?\n $redis.set(key, { 'count': JSON.parse(data)['count'] + 1 }.to_json, { keepttl: true }) == 'OK'\n else\n $redis.set(key, { 'count': 1 }.to_json, { ex: RESET_OUTBOUND_CACHE_TIME }) == 'OK'\n end\n end", "def reset\n respond_to do |format|\n @wait_queue.count = 0\n if @wait_queue.save\n format.html { redirect_to @wait_queue, notice: 'Reset successfully.' }\n format.json { render :show, status: :ok, location: @wait_queue }\n end\n end\n end", "def count\n queue.count\n end", "def sub_queue_count\n sub_queue_obj.count\n end", "def count\n @queue.size\n end", "def queue_count_key\n \"concurrent.queue_counts\"\n end", "def queue_count\n @queues.length\n end", "def updateservercount(count)\n url = \"https://discordbots.org/api/bots/#{@id}/stats\"\n json = '{\"server_count\":' + count.to_s + '}'\n RestClient.post(url, json, :Authorization => @api, :'Content-Type' => :json)\n \"Successfully set the server count to #{count}\"\n end", "def update\n respond_to do |format|\n if @wait_queue.update(wait_queue_params)\n format.html { redirect_to @wait_queue, notice: \"Wait queue was successfully updated.\" }\n format.json { render :show, status: :ok, location: @wait_queue }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @wait_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_current_queue new_queue\n log_everything(\"Update current queue\")\n log_everything(\"New queue: \\\"#{new_queue.to_s}\\\"\")\n craft_firebase_command(\"minesweeper/queue.json\", \"PUT\", new_queue)\nend", "def count\n num_jobs = 0\n Delayed::Worker.queues.each_with_index do |queue, index|\n queue = sqs.queues.named(queue_name(index))\n num_jobs += queue.approximate_number_of_messages + queue.approximate_number_of_messages_delayed + queue.approximate_number_of_messages_not_visible\n end\n num_jobs\n end", "def increment_active_requests\n @active_requests.update { |count| count + 1 }\n end", "def backlog\n @queues.map{|k,v| [k,v.size]} \n end", "def count\n\t\t@queue.length\n\tend", "def update\n respond_to do |format|\n if @wait_queue.update(wait_queue_params)\n format.html { redirect_to @wait_queue, notice: 'Wait queue was successfully updated.' }\n format.json { render :show, status: :ok, location: @wait_queue }\n else\n format.html { render :edit }\n format.json { render json: @wait_queue.errors, status: :unprocessable_entity }\n end\n end\n end", "def decrement_active_requests\n @active_requests.update { |count| count - 1 }\n end", "def count_message_in\n m_in = stat.incr \"hotpotato.counter.apptask.#{Socket.gethostname}.#{self.class.name}.#{Process.pid}.messages_in\"\n stat.publish( \"messages_in\", {\"hotpotato.counter.apptask.#{Socket.gethostname}.#{self.class.name}.#{Process.pid}.messages_in\".gsub('.','_') => m_in.to_s}.to_json )\n stat.expire \"hotpotato.counter.apptask.#{Socket.gethostname}.#{self.class.name}.#{Process.pid}.messages_in\", MESSAGE_COUNT_EXPIRE\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /wait_queues/1/reset PATCH/PUT /wait_queues/1/reset.json
def reset respond_to do |format| @wait_queue.count = 0 if @wait_queue.save format.html { redirect_to @wait_queue, notice: 'Reset successfully.' } format.json { render :show, status: :ok, location: @wait_queue } end end end
[ "def refill_all_queues!\n # Dla POST musi byc jakies 'body' requestu, bo serwery czesto rzucaja wyjatkami (WEBrick w szczegolnosci).\n post '/queues/refill_all', :body => ' '\n true\n end", "def reset_activation_status(args = {}) \n put(\"/arrays.json/#{args[:arrayId]}/activation/reset\", args)\nend", "def requeue\n @action = :requeue\n end", "def reset\n queue.clear\n end", "def reset\n request = {}\n\n logger.debug('Resetting mockserver')\n logger.debug(\"URL: #{RESET_ENDPOINT}. Payload: #{request.to_hash}\")\n\n response = @base[RESET_ENDPOINT].put(request.to_json)\n logger.debug(\"Got reset response: #{response.code}\")\n parse_string_to_json(response)\n end", "def reset_queue_stats\n begin\n queue = PbxQueue.where(:name => params[:queue])[0]\n @pbxis_ws.reset_queue_stats queue.name\n @queue_status = @pbxis_ws.get_status queue.name\n rescue => e\n flash[:alert] = e.message\n end\n \n respond_to do |format|\n format.js\n end\n end", "def reset workers\n workers.each{|worker| @queues[worker].clear if @queues[worker]}\n end", "def purge\n @queues = {}\n end", "def reset!(queue_name = nil)\n if @queue && queue_name\n @queue[queue_name] = []\n else\n @queue = Hash.new { |h, k| h[k] = [] }\n end\n end", "def destroy\n @wait_queue.destroy\n respond_to do |format|\n format.html { redirect_to wait_queues_url, notice: 'Wait queue was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @wait_queue.destroy\n respond_to do |format|\n format.html { redirect_to wait_queues_url, notice: \"Wait queue was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def reset\n head 501 unless request.xhr?\n\n fail ArgumentError, 'Missing reset_workflow' unless params[:reset_workflow].present?\n fail ArgumentError, 'Missing reset_step' unless params[:reset_step].present?\n\n @workflow = params[:reset_workflow]\n @step = params[:reset_step]\n @repo = repo_from_workflow(@workflow)\n @ids = Report.new(params, current_user: current_user).pids\n @ids.each do |pid|\n Dor::Config.workflow.client.update_workflow_status(\n @repo,\n \"druid:#{pid}\",\n @workflow,\n @step,\n 'waiting'\n )\n end\n ### XXX: Where's the authorization?\n end", "def reset_stale_jobs!\n Queue.queued.where('worker_id like :app_id', app_id: \"#{self.id}-%\").update_all(worker_id: nil)\n end", "def reset\n [topics, queues, subscriptions].each do |resource|\n resource.values.each(&:delete)\n resource.clear\n end\n end", "def resetTask(taskId, params)\n data = { :resetTask => { :taskId => taskId } }\n post_data(END_POINT, params, data)\n end", "def clear!\n jobs.clear\n job_updates.clear\n end", "def requeue_jobs\n RocketJob::Job.requeue_dead_server(name)\n end", "def flush_jobs\n Server.redis { |c| c.del(QPush::Base::KEY + ':jobs') }\n end", "def requeue_all_tasks\n response = Connection.new.post(\"/api/tasks/queue/requeue\")\n Tasks.build(response)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /wait_queues/1 DELETE /wait_queues/1.json
def destroy @wait_queue.destroy respond_to do |format| format.html { redirect_to wait_queues_url, notice: 'Wait queue was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @wait_queue.destroy\n respond_to do |format|\n format.html { redirect_to wait_queues_url, notice: \"Wait queue was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def deleteQueue( queue_id)\n params = Hash.new\n params['queue_id'] = queue_id\n return doCurl(\"delete\",\"/queue\",params)\n end", "def delete\n @redis.del @queue_name\n @redis.keys(\"#{@queue_name}:*\").each do |key|\n @redis.del key\n end\n @redis.srem \"timberline_queue_names\", @queue_name\n end", "def destroy\n @email_queue.destroy\n respond_to do |format|\n format.html { redirect_to email_queues_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @queue = CallQueue.find(params[:id])\n @queue.destroy\n\n respond_to do |format|\n format.html { redirect_to(queues_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @send_queue.destroy\n respond_to do |format|\n format.html { redirect_to send_queues_url, notice: 'Send queue was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @task_queue.destroy\n respond_to do |format|\n format.html { redirect_to task_queues_url, notice: \"#{@task_queue.name} Deleted\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @bannerqueue = Bannerqueue.find(params[:id])\n @bannerqueue.destroy\n\n respond_to do |format|\n format.html { redirect_to bannerqueues_url }\n format.json { head :no_content }\n end\n end", "def delete_queued_transaction(request)\n route_terminal_request('POST', '/api/queue/delete', '/api/queue/delete', request)\n end", "def destroy\n @notice_queue = NoticeQueue.find(params[:id])\n @notice_queue.destroy\n\n respond_to do |format|\n format.html { redirect_to notice_queues_url }\n format.json { head :ok }\n end\n end", "def destroy\n @message_queue.destroy\n respond_to do |format|\n format.html { redirect_to message_queues_url, notice: 'Message queue was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @gtd_queue.destroy\n respond_to do |format|\n format.html { redirect_to gtd_queues_url, notice: 'Queue was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @url_queue.destroy\n respond_to do |format|\n format.html { redirect_to url_queues_url, notice: 'Url queue was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @caller_queue = CallerQueue.find(params[:id])\n @caller_queue.destroy\n\n respond_to do |format|\n format.html { redirect_to(caller_queues_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @jobs_queue = JobsQueue.find(params[:id])\n @jobs_queue.destroy\n\n respond_to do |format|\n format.html { redirect_to(jobs_queues_url) }\n format.xml { head :ok }\n end\n end", "def delete( queue_name )\n req = KJess::Request::Delete.new( :queue_name => queue_name )\n resp = send_recv( req )\n return KJess::Response::Deleted === resp\n end", "def delete(name)\n if queues[name]\n queues.delete(name)\n else\n raise 'NonExistentQueue'\n end\n end", "def destroy\n @event_queue = EventQueue.find(params[:id])\n @event_queue.destroy\n\n respond_to do |format|\n format.html { redirect_to(event_queues_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @construction_queue = Construction::Queue.find(params[:id])\n @construction_queue.destroy\n\n respond_to do |format|\n format.html { redirect_to construction_queues_url }\n format.json { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the "uploads" channel for a given user.
def get_upload_channel_id(username) upload_channel = nil puts 'Channels:' channels = list_channels(username) channels.items.each do |item| puts "# #{item.id}" puts "- uploads #{item.content_details.related_playlists.uploads}" upload_channel = item.content_details.related_playlists.uploads end upload_channel end
[ "def get_channel_for(level, user = nil)\n if user\n # \"answers\" are in the channel so instead of doing\n # set_level_source to load answers when looking at another user,\n # we have to load the channel here.\n user_storage_id = storage_id_for_user_id(user.id)\n channel_token = ChannelToken.find_channel_token(level, user_storage_id)\n else\n user_storage_id = storage_id('user')\n channel_token = ChannelToken.find_or_create_channel_token(\n level,\n request.ip,\n user_storage_id,\n {\n hidden: true,\n }\n )\n end\n\n channel_token.try :channel\n end", "def retrieve_channels(user_id)\n return Channel.find(:all, :conditions => [\"user_id = ?\", user_id])\n end", "def channel(user)\n if user.is_a? String\n user\n else\n user.send(:push_id)\n end\n end", "def channels_for(user, app_name)\n channels = []\n if user.present?\n channels += [private_channels_for(user, app_name)]\n channels << REVIEWER_CHANNEL if user.reviewer? and app_name == ADMIN_APP\n channels << SUPERVISOR_CHANNEL if user.supervisor? and app_name == ADMIN_APP\n channels << ORDER_FULFILMENT_CHANNEL if user.order_fulfilment? and app_name == STOCK_APP\n channels << STOCK_CHANNEL if app_name == STOCK_APP\n end\n channels << BROWSE_CHANNEL if app_name == BROWSE_APP\n channels.flatten.compact.uniq\n end", "def get_private_channel(user)\n @users.keys\n .map { |channel| @channels[channel] }\n .compact\n .find { |channel| channel.private }\n # the server doesn't send PMs you don't have access to\n end", "def channel\n @channels[BASE_PATH]\n end", "def channels_with_user nick\n @channels.select { |channel| channel.user_by_nick nick }\n end", "def get_user_dms\n request(Route.new(:GET, '/users/@me/channels'))\n end", "def uploads\n self.user.uploads.where(:client_id => self.id.to_s)\n end", "def pusher_channel\n get(\"user/channel.json\")\n end", "def get_channel_recs_for_user(channel_user_id, limit=1, options={})\n unless channel_user_id.is_a?(BSON::ObjectId)\n channel_user_id_string = channel_user_id.to_s\n if BSON::ObjectId.legal?(channel_user_id_string)\n channel_user_id = BSON::ObjectId.from_string(channel_user_id_string)\n else\n raise ArgumentError, \"must supply a valid channel user id\"\n end\n end\n raise ArgumentError, \"must supply a limit > 0\" unless limit.respond_to?(:to_i) && ((limit = limit.to_i) > 0)\n\n defaults = {\n :shuffle => true,\n :unique_sharers_only => true\n }\n options = defaults.merge(options)\n shuffle = options.delete(:shuffle)\n unique_sharers_only = options.delete(:unique_sharers_only)\n\n # get more recs than the caller asked for because some of them might be eliminated and we want to\n # have the chance to still recommend something\n recs = DashboardEntry.where(\n :user_id => channel_user_id,\n # don't include Notification dbes, since they're only intended for the receiving user to see\n :action => {\n :$nin => [\n DashboardEntry::ENTRY_TYPE[:like_notification],\n DashboardEntry::ENTRY_TYPE[:anonymous_like_notification],\n DashboardEntry::ENTRY_TYPE[:share_notification],\n DashboardEntry::ENTRY_TYPE[:follow_notification]\n ]\n }\n ).order(:_id.desc).limit(limit + 9).fields(:video_id, :frame_id, :actor_id)\n if shuffle\n recs = recs.all\n recs.shuffle!\n end\n recs = filter_recs(recs, {:limit => limit, :recommended_video_key => \"video_id\"}) do |rec|\n # only include recs shared by people other than the current user, and from unique sharers (if specified in the options)\n excluded_sharers = unique_sharers_only ? @recommended_sharer_ids | @excluded_sharer_ids : @excluded_sharer_ids\n include_rec = (rec.actor_id != @user.id && (!excluded_sharers.include?(rec.actor_id)))\n # if the option is specified, keep track of the sharers we've already seen so we don't duplicate them\n @recommended_sharer_ids << rec.actor_id if unique_sharers_only && include_rec\n include_rec\n end\n recs.map! do |rec|\n {\n :recommended_video_id => rec.video_id,\n :src_id => rec.frame_id,\n :action => DashboardEntry::ENTRY_TYPE[:channel_recommendation]\n }\n end\n\n return recs\n end", "def find_user_by_channel_id(channel_id = 1)\n object_from_response(User, :get, \"userChannel?channelCustomerId=#{channel_id}\")\n end", "def user_folder(user)\n folder = self.folders.find_by user_id: user.id\n return folder\n end", "def channel\n return @channel\n end", "def public_channel\n # [\"chat\", \"rumor\", \"wldh\", \"tianshi\", \"bwxy\", \"bh\"]\n @_public_channels\n end", "def watched\n @channels = current_user.watched_channels\n end", "def channel\n request.path\n end", "def select_channel(user_input)\n @channels.each do |channel|\n if channel.id == user_input\n @selected = channel\n elsif channel.name == user_input\n @selected = channel\n end\n end\n return @selected\n end", "def userfolder\n # \"public/upload/user_id_\" + self.user_id.to_s\n User.find_by_id( self.user_id ).userfolder\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }