query
stringlengths
7
6.41k
document
stringlengths
12
28.8k
metadata
dict
negatives
sequencelengths
30
30
negative_scores
sequencelengths
30
30
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
builds up coordinates to interpolate between two coord pairs, based on which axis changed and whether we should subtract or add to move from point 1 to point 2
def build_replacement_coords(coords1, coords2, changed_sym) point_one = coords1[changed_sym] point_two = coords2[changed_sym] greater_than = point_one > point_two new_values = if greater_than point_one.downto(point_two + 1).to_a else point_one.upto(point_two - 1).to_a end new_values.map { |value| coords1.merge({changed_sym => value}) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def lerp(x1, y1, x2, y2, x)\n return y1 + (x - x1) * ((y2 - y1) / (x2 - x1))\nend", "def interpolate stroke\n current = stroke.first\n new_stroke = [current]\n\n index = 1\n last_index = 0\n while index < stroke.length do\n point = stroke[index]\n\n #only consider point with greater than d distance to current point\n if Math.euclidean_distance(current, point) < @interpolate_distance\n index += 1\n else\n\n #calculate new point coordinate\n new_point = []\n if point[0].round(2) == current[0].round(2) # x2 == x1\n if point[1] > current[1] # y2 > y1\n new_point = [current[0], current[1] + @interpolate_distance]\n else # y2 < y1\n new_point = [current[0], current[1] - @interpolate_distance]\n end\n else # x2 != x1\n slope = (point[1] - current[1]) / (point[0] - current[0]).to_f\n if point[0] > current[0] # x2 > x1\n new_point[0] = current[0] + Math.sqrt(@interpolate_distance**2 / (slope**2 + 1))\n else # x2 < x1\n new_point[0] = current[0] - Math.sqrt(@interpolate_distance**2 / (slope**2 + 1))\n end\n new_point[1] = slope * new_point[0] + point[1] - (slope * point[0])\n end\n\n new_point = new_point.map{ |num| num.round(2) }\n if current != new_point\n new_stroke << new_point\n\n current = new_point\n end\n last_index += ((index - last_index) / 2).floor\n index = last_index + 1\n end\n end\n\n new_stroke\n end", "def interp ( ya, yb, xa, xb, x )\n# return ya if x == xa\n factor = (x - xa) / (xb - xa )\n return ya + factor * ( yb - ya )\nend", "def line x0, y0, x1, y1, c\n dx = (x1 - x0).abs\n sx = x0 < x1 ? 1 : -1\n dy = (y1 - y0).abs\n sy = y0 < y1 ? 1 : -1\n err = (dx > dy ? dx : -dy) / 2\n \n loop do\n set x0, y0, c\n break if x0 === x1 && y0 === y1\n e2 = err\n if e2 > -dx\n err -= dy\n x0 += sx\n end \n if e2 < dy\n err += dx\n y0 += sy \n end\n end \n end", "def interp2(x, y, z, xq, yq, method, extrapval) # flatten\n nx = x.length\n ny = y.length\n # nz = z.length\n nxq = xq.length\n nyq = yq.length\n inquiry(double: nxq * nyq) do |zq|\n super(nx, ny, x, y, z, nxq, nyq, xq, yq, zq, method, extrapval)\n end\n end", "def line(x0, y0, x1, y1)\n # clean params\n x0, y0, x1, y1 = x0.to_i, y0.to_i, x1.to_i, y1.to_i\n y0, y1, x0, x1 = y1, y0, x1, x0 if y0>y1\n sx = (dx = x1-x0) < 0 ? -1 : 1 ; dx *= sx ; dy = y1-y0\n\n # special cases\n x0.step(x1,sx) { |x| point x, y0 } and return if dy.zero?\n y0.upto(y1) { |y| point x0, y } and return if dx.zero?\n x0.step(x1,sx) { |x| point x, y0; y0 += 1 } and return if dx==dy\n\n # main loops\n point x0, y0\n\n e_acc = 0\n if dy > dx\n e = (dx << 16) / dy\n y0.upto(y1-1) do\n e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF\n x0 += sx if (e_acc <= e_acc_temp)\n point x0, (y0 += 1), intensity(@color,(w=0xFF-(e_acc >> 8)))\n point x0+sx, y0, intensity(@color,(0xFF-w))\n end\n point x1, y1\n return\n end\n\n e = (dy << 16) / dx\n x0.step(x1-sx,sx) do\n e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF\n y0 += 1 if (e_acc <= e_acc_temp)\n point (x0 += sx), y0, intensity(@color,(w=0xFF-(e_acc >> 8)))\n point x0, y0+1, intensity(@color,(0xFF-w))\n end\n point x1, y1\n end", "def adjust _x, _y\n x += _x\n y += _y\n end", "def interp2(x, y, z, xq, yq, method, extrapval)\n nx = x.length\n ny = y.length\n # nz = z.length\n nxq = xq.length\n nyq = yq.length\n inquiry(double: nxq * nyq) do |zq|\n super(nx, ny, x, y, z, nxq, nyq, xq, yq, zq, method, extrapval)\n end\n end", "def test_interpolate\n xvals = [10, 30]\n yvals = [25, 35]\n\n assert_in_delta 43.5, Utils.interpolate(xvals, yvals, 47), 0.01\n assert_in_delta 26.5, Utils.interpolate(xvals, yvals, 13), 0.01\n assert_in_delta 70, Utils.interpolate(xvals, yvals, 100), 0.01\n end", "def adjust_points\n coords = current_object.coordinates\n if sw and ne\n @sw.lat = coords.lat if sw.lat > coords.lat\n @sw.lon = coords.lon if sw.lon > coords.lon\n @ne.lat = coords.lat if ne.lat < coords.lat\n @ne.lon = coords.lon if ne.lon < coords.lon\n @center.lat = (ne.lat - sw.lat )/2 + sw.lat\n @center.lon = (ne.lon - sw.lon )/2 + sw.lon\n else\n @sw = coords.dup\n @ne = coords.dup\n @center = coords.dup\n end\n \n true\n end", "def Point2dInterpolate(arg0, arg1, arg2)\n ret = _invoke(1610743815, [arg0, arg1, arg2], [VT_BYREF | VT_DISPATCH, VT_R8, VT_BYREF | VT_DISPATCH])\n @lastargs = WIN32OLE::ARGV\n ret\n end", "def update_coordinates(zero_el, other_el)\n x = zero_el[:x]\n y = zero_el[:y]\n\n zero_el[:y] = other_el[:y]\n zero_el[:x] = other_el[:x]\n\n other_el[:y] = y\n other_el[:x] = x\n\n zero_el\nend", "def update_smooth_movements\n return unless @start_move\n update_smooth_x\n update_smooth_y\n check_move_end\n end", "def cross(v1, v2)\n dx, dy = v2[0] - v1[0], v2[1] - v1[1]\n cr = [] # array containing intersections\n\n if dx == 0 and dy ==0 then\n\tnc = 0\n elsif dx == 0 then\n\tt = ( 0.0 - v1[1] ) / dy # y = 0\n\tx , y = v1[0] + t * dx, v1[1] + t * dy\n cr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[1] ) / dy # y = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n elsif dy == 0 then\n\tt = ( 0.0 - v1[0] ) / dx # x = 0\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[0] ) / dx # x = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n cr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n else\n\tt = ( 0.0 - v1[1] ) / dy # y = 0\n\tx , y = v1[0] + t * dx, v1[1] + t * dy\n cr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[1] ) / dy # y = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n\tt = ( 0.0 - v1[0] ) / dx # x = 0\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[0] ) / dx # x = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy \n cr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n end\n return cr\n end", "def points_on_a_line(x0, y0, x1, y1)\n raise NotImplementedError\n dx = (x1 - x0).abs\n dy = -(y1 - y0).abs\n step_x = x0 < x1 ? 1 : -1\n step_y = y0 < y1 ? 1 : -1\n err = dx + dy\n coords = Array.new\n coords << [x0, y0]\n (\n begin\n e2 = 2 * err\n\n if e2 >= dy\n err += dy\n x0 += step_x\n end\n\n if e2 <= dx\n err += dx\n y0 += step_y\n end\n\n coords << [x0, y0]\n end\n\n ) until (x0 == x1 && y0 == y1)\n coords\n end", "def get_next_point(low_ys , high_ys , cur_y)\n #Current point is nearer to high_ys than low_ys\n if cur_y - low_ys.last > high_ys.last - cur_y\n high_ys << cur_y\n return low_ys.last + (cur_y - low_ys.last) * GOLDEN_RATIO\n else\n low_ys << cur_y\n return cur_y + (high_ys.last - cur_y) * GOLDEN_RATIO\n end\n end", "def calculate_coordinates\n (\n egde(@x1, @y1, @x2, @y1) +\n egde(@x2, @y1, @x2, @y2) +\n egde(@x2, @y2, @x1, @y2) +\n egde(@x1, @y2, @x1, @y1)\n ).uniq\n end", "def mod_add (a, b)\n if b.inf\n return a\n end\n if a.inf\n return b\n end\n\n x1 = a.x\n x2 = b.x\n y1 = a.y\n y2 = b.y\n\n if x1 == x2 and y1 == -y2\n return Point.new Float::INFINITY, Float::INFINITY\n end\n\n if x1 == x2 and y1 == y2\n lambda = self.mod_inv 3 * x1 ** 2 + @a, 2 * y1\n else\n lambda = self.mod_inv y2 - y1, x2 - x1\n end\n\n x3 = Curve.mod lambda ** 2 - x1 - x2, @fp\n y3 = Curve.mod lambda * (x1 - x3) - y1, @fp\n\n Ecc::Point.new x3, y3\n end", "def get_linear_interpolation_with(other, bias = 0.5)\n raise 'Invalid track point' unless other.is_a? TrackPoint\n TrackPoint.new longitude * (1.0 - bias) + other.longitude * bias,\n latitude * (1.0 - bias) + other.latitude * bias,\n elevation * (1.0 - bias) + other.elevation * bias,\n time.nil? || other.time.nil? ? nil : Time.at(time.to_f * (1.0 - bias) + other.time.to_f * bias)\n end", "def interpolate(a, b)\n a = a.to_f\n b = b.to_f\n b -= a\n\n lambda { |t| a + b * t }\n end", "def offset(delta, dist = 1.5)\n # set delta according to polygon direction, set veriables for first and last p/l\n delta = delta * orientation\n p_first, p_last = nil; offset_lines = []\n l_first, l_last = nil; offset_points = []\n refined_points = []\n\n # Offset lines between 2 consecutive vertices out by delta\n vertices.each_cons(2) do |p1, p2|\n p_first ||= p1; p_last = p2 # save first and last vector for final line\n offset_lines << offset_line(p1, p2, delta)\n end\n offset_lines << offset_line(p_last, p_first, delta)\n\n # Calculate intersections between adjacent lines for new vertices\n offset_lines.each_cons(2) do |l1, l2|\n l_first ||= l1; l_last = l2 # save first and last vector for final intersection\n offset_points << line_intersection(l1, l2)\n end\n offset_points.insert(0, line_intersection(l_first, l_last))\n\n # Smooth corners of very acute angles\n offset_points.each_with_index do |p, key|\n v = p - vertices[key]\n if v.magnitude > (dist * delta).abs\n p2 = vertices[key] + v.normalize * dist * delta.abs\n # normal vector for 2 vertices through a point dist*delta away\n cutoff_line = [p2, p2 + v.normal_vector]\n [-1, 0].each do |i|\n if key + i < 0\n n = offset_lines.size - 1\n elsif key + i >= offset_lines.size\n n = 0\n else\n n = key + i\n end\n refined_points << line_intersection(cutoff_line, offset_lines[n])\n end\n else\n refined_points << p\n end\n end\n refined_points\n end", "def normalizeLine(c1,c2)\n x = c2[0] - c1[0]\n y = c2[1] - c1[1]\n\n # make sure we didn't wrap one way or the other.\n # taking the shortest great circle distance.\n x = x <= -180 ? x + 360 : x\n x = x >= 180 ? x - 360 : x\n return [[0,0],[x,y]]\n end", "def getAt(x1, y1, x2, y2)\n if x1 == 0 || y1 == 0\n if x1 == 0 && y1 == 0\n return @sa[y2*@width + x2]\n elsif x1 == 0 && y1 != 0\n return @sa[y2*@width + x2] - @sa[(y1-1)*@width + x2]\n else # x1 != 0 && y1 == 0\n ty2 = y2*@width\n return @sa[ty2 + x2] - @sa[y2 + (x1 - 1)]\n end\n else\n tx1, ty1, tx2, ty2 = x1-1, (y1-1)*@width, x2, y2*@width\n return @sa[ty2 + tx2] - @sa[ty1 + tx2] - @sa[ty2 + tx1] + @sa[ty1 + tx1]\n end\n end", "def call v1, v2\n # \"Readable\" method provided for the parenthetically inclined\n # inter_delta(scale(intra_delta(get_pairs(v1, v2))))\n inter_delta scale intra_delta get_pairs v1, v2\n end", "def update_grid_for_moved_entity(entity, old_x, old_y)\n cells_before = cells_overlapping(old_x, old_y)\n cells_after = cells_overlapping(entity.x, entity.y)\n\n (cells_before - cells_after).each do |s|\n raise \"#{entity} not where expected\" unless s.delete? entity\n end\n (cells_after - cells_before).each {|s| s << entity }\n end", "def update_xy()\n if ((pxy=ref_xy) and (cs=column_space) and (rs=row_space) and (cr=colrow).length == 2)\n # see #xy_record for an explanation of this formula\n array = pxy + [pxy[0]+cs*cr[0], pxy[1]] + [pxy[0], pxy[1]+rs*cr[1]]\n @records.set(GRT_XY, array)\n else\n @records.set(GRT_XY, nil)\n end\n end", "def egde(x1, y1, x2, y2)\n ConsoleDraw::Figures::Line.new(x1, y1, x2, y2).calculate_coordinates\n end", "def y2; y1 + HEIGHT ; end", "def lerp(matrix1, matrix2, amount)\n end", "def interpolbi pontos\n pontos = pontos.sort\n lambda do |*x|\n lagrange pontos.map {|x1, pts|\n [x1, lagrange(pts).call(x[1])]\n }.call(x[0])\n end\nend" ]
[ "0.6394441", "0.62365985", "0.59970653", "0.57060343", "0.56742424", "0.56585735", "0.5613269", "0.5606583", "0.55712", "0.5542732", "0.5483703", "0.5412795", "0.5402706", "0.53994566", "0.5382542", "0.53468186", "0.53425556", "0.5334001", "0.53278226", "0.53011405", "0.5293086", "0.52919465", "0.52796793", "0.5243131", "0.5232883", "0.5232104", "0.5215194", "0.5198529", "0.5196314", "0.518071" ]
0.6730998
0
This helps us reference all unique references by collection e.g. all VM targets
def references(collection) target.manager_refs_by_association&.dig(collection, :ems_ref)&.to_a&.compact || [] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def references(collection)\n target.try(:references, collection) || []\n end", "def name_references(collection)\n target.try(:name_references, collection) || []\n end", "def references; end", "def references; end", "def references(collection)\n manager_refs_by_association.try(:[], collection).try(:[], :ems_ref)&.to_a || []\n end", "def references\n alias_of.references\n end", "def references\n @references ||= []\n end", "def references\n @references\n end", "def get_collection_object_references\n # get ids of collection object links\n link_ids = CollectionobjectLink.where(\"resource_id = ?\", self.id).pluck(:id)\n resource_ids = MediaFile.where(\"sourceable_id IN (?)\", link_ids).pluck(:resource_id)\n\n #\n rel_resource_ids = RelatedResource.where(\"to_resource_id = ?\", self.id).pluck(:resource_id)\n\n all_resource_ids = rel_resource_ids + resource_ids\n\n begin\n Resource.find(all_resource_ids)\n rescue\n return []\n end\n end", "def name_references(collection)\n manager_refs_by_association.try(:[], collection).try(:[], :name)&.to_a || []\n end", "def target_objects\n return @target_objects\n end", "def target_objects\n return @target_objects\n end", "def getAllTargetCollections\n return sendRequest('GET', PATH_ADD_TC)\n end", "def getAllTargetCollections\n return sendRequest('GET', PATH_ADD_TC)\n end", "def build_reference_types(inventory_collection)\n class_name = inventory_collection.model_class.to_s\n\n reference_types[class_name] ||= []\n reference_types[class_name] << \"#{inventory_collection.name.to_s.singularize.camelize}Reference\"\n inventory_collection.secondary_refs.each do |key, _value|\n reference_types[class_name] << \"#{inventory_collection.name.to_s.singularize.camelize}Reference#{key.to_s.camelize}\"\n end\n end", "def objects_with_references\n end", "def collections; end", "def references\n return @references\n end", "def object_managed_collection_ids\n @object_managed_collection_ids ||= object_member_of & managed_collection_ids\n end", "def targets\n @targets ||= []\n end", "def getAllTargetCollections()\n return sendHttpRequest(nil, \"GET\", @@PATH_ADD_TC)\n end", "def targets; self[:targets]; end", "def referenced_objects\n return @referenced_objects\n end", "def create_target_refs_and_links?\n tr_create = [] #node/node-groups that need target ref created\n tr_link = {} #node/node-groups that need to be linked to existing target refs\n tr_link_candidates = []\n\n # ndx_needs_sc is used to find nodes that need a state change object\n # meaning model is annoatted so these when a task is run will cause a node to be created\n # initiallly set ndx_needs_state_change to have all nodes and then in loop below remove ones\n # that are linked to existing nodes\n ndx_needs_sc = {}\n @nodes.each do |node|\n if node.is_node_group?() && !node[:target_refs_exist]\n tr_create << node\n else\n tr_link_candidates << node\n end\n # initiallly set ndx_needs_state_change to have all nodes\n ndx_needs_sc.merge!(node[:id] => node)\n end\n\n Input::BaseNodes.create_linked_target_refs?(@target, @assembly, tr_create)\n\n to_link_array = existing_target_refs_to_link(tr_link_candidates, ndx_needs_sc)\n link_to_target_refs(to_link_array)\n\n # needed target_ref state changes\n ndx_needs_sc.reject { |_node, needs_sc| !needs_sc }.values\n end", "def collection_names; end", "def refs\n @refs\n end", "def collection_proxies\n @collection_proxies ||= {}\n end", "def gather_internal_refs\n #@files.each.with_object({}) do |(_, x), refs|\n @files.keys.each_with_object({}) do |i, refs|\n #x[:attachment] and next\n @files.get(i,:attachment) and next\n #file, = targetfile(x, read: true)\n file, = @files.targetfile_id(i, read: true)\n Nokogiri::XML(file)\n .xpath(ns(\"//bibitem[@type = 'internal']/\" \\\n \"docidentifier[@type = 'repository']\")).each do |d|\n a = d.text.split(%r{/}, 2)\n a.size > 1 or next\n refs[a[0]] ||= {}\n refs[a[0]][a[1]] = true\n end\n end\n end", "def target_objects=(value)\n @target_objects = value\n end", "def target_objects=(value)\n @target_objects = value\n end" ]
[ "0.73237604", "0.6841899", "0.6772536", "0.6772536", "0.6760671", "0.6349265", "0.6312122", "0.62698424", "0.62692195", "0.6266564", "0.61625355", "0.61625355", "0.60551155", "0.60545015", "0.604809", "0.60089916", "0.5984876", "0.5913685", "0.5897947", "0.5878525", "0.58764094", "0.5811957", "0.5795136", "0.5792183", "0.57744753", "0.57583433", "0.5716626", "0.56958055", "0.5693345", "0.5693345" ]
0.71261626
1
The path to the current ruby interpreter. Adapted from Rake's FileUtils.
def ruby_path ext = ((RbConfig::CONFIG['ruby_install_name'] =~ /\.(com|cmd|exe|bat|rb|sh)$/) ? "" : RbConfig::CONFIG['EXEEXT']) File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + ext).sub(/.*\s.*/m, '"\&"') end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ruby_interpreter_path\n Pathname.new(\n File.join(Config::CONFIG[\"bindir\"],\n Config::CONFIG[\"RUBY_INSTALL_NAME\"]+Config::CONFIG[\"EXEEXT\"])\n ).realpath\n end", "def ruby_path\r\n File.join janus_path, 'ruby'\r\n end", "def get_path\n cmd_exec('echo $PATH').to_s\n rescue\n raise \"Unable to determine path\"\n end", "def ruby_path\n File.join(%w(bindir RUBY_INSTALL_NAME).map{|k| RbConfig::CONFIG[k]})\n end", "def path\n env[PATH] ||= (env.has_key?(GIT) ? env[GIT].path : Dir.pwd)\n end", "def this_file_path\n Pathname.new( __FILE__ ).expand_path\n end", "def current_path\n File.expand_path(File.join(__FILE__,\"../\"))\nend", "def current_working_directory; @rye_current_working_directory; end", "def current_dir; end", "def current path=nil\n current = `pwd`.strip + \"/\"\n if path\n current + path \n else\n current\n end\nend", "def bin_path\n '/usr/local/bin'.p\n end", "def executable_path; end", "def cwd\n return cd(\"\").to_s\n end", "def ruby_relative_path\n ruby_pathname = Pathname.new(ruby)\n bindir_pathname = Pathname.new(target_bin_dir)\n ruby_pathname.relative_path_from(bindir_pathname).to_s\n end", "def current_dir\n File.dirname(file_path)\n end", "def ruby_bin_path\n #config_section.ruby_bin_path || ENV['_'] =~ /ruby/ ||\n require 'rbconfig'\n File.expand_path(Config::CONFIG['RUBY_INSTALL_NAME'], Config::CONFIG['bindir'])\n end", "def active_path\n if script = script_object()\n if path = script.path\n return path.dup\n end\n end\n\n # If for some reason that didn't work, return the compile time filename.\n method.file.to_s\n end", "def shell_path\n value = shell_name.to_s\n\n if value.match(/^\\//)\n # Absolute path already provided (starts with \"/\")\n value.p\n else\n # Shell name provided, use \"which\" to find the executable\n which(value).p\n end\n end", "def working_dir\n ENV['PWD'] || Dir.pwd\n end", "def curr_srcdir\n \"#{srcdir_root()}/#{relpath()}\"\n end", "def curr_srcdir\n \"#{srcdir_root()}/#{relpath()}\"\n end", "def shell_ruby_platform\n `ruby -rrbconfig -e \"puts RbConfig::CONFIG['sitearchdir']\"`\n end", "def this_dir\n File.expand_path(File.dirname(caller_file(caller)))\n end", "def source\n case type\n when :gem then File.basename File.expand_path '..', @path\n when :home then 'home'\n when :site then 'site'\n when :system then 'ruby'\n else @path\n end\n end", "def this_file\n File.expand_path(caller_file(caller))\n end", "def curr_srcdir\n \"#{srcdir_root()}/#{relpath()}\"\n end", "def path; Gem.ruby; end", "def env_path\n @bin_resolver.env_path\n end", "def current_module\n File.basename(__FILE__, \".rb\")\nend", "def cwd\n @cwd ||= begin\n exec! 'pwd'\n rescue => e\n raise e\n '/'\n end\n end" ]
[ "0.78348446", "0.6657744", "0.65563154", "0.6524134", "0.64435935", "0.6430483", "0.6418614", "0.6390923", "0.63816", "0.63672125", "0.6362747", "0.63023263", "0.6271103", "0.62705463", "0.6263798", "0.62570107", "0.62274843", "0.6192331", "0.6184631", "0.61580527", "0.61580527", "0.6145944", "0.611691", "0.6113412", "0.61059606", "0.6103561", "0.6092784", "0.60927224", "0.60833985", "0.6080327" ]
0.698191
1
Complete the matchingStrings function below.
def matchingStrings(strings, queries) counting_hash = {} counting_hash.default = 0 # For Cache strings.each do |s| counting_hash[s] ? counting_hash[s] += 1 : counting_hash[s] = 1 end res = [] queries.each do |q| res << counting_hash[q] end res end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def match_strings(matched_lines)\n matched_strings = []\n\n matched_lines.each do |line|\n check_patterns.each do |pattern|\n line.scan(pattern).each do |matched|\n matched_strings += matched\n end\n end\n end\n\n return matched_strings\n end", "def matches(str)\n each_match(str).to_a\n end", "def string_matching(words)\n result_words = []\n\n words.each_with_index do |possible_substring, index|\n (0..words.size - 1).each do |index_w|\n next if index_w == index || words[index_w].size < possible_substring.size\n \n result_words << possible_substring if words[index_w].index(possible_substring)\n end\n end\n \n result_words.uniq\nend", "def match(*strings)\n result = []\n @tags.each do |tag|\n strings.each do |string|\n if string.downcase =~ /#{tag.downcase}/\n strings.delete string\n result << tag\n break\n end\n end\n end\n return result\n end", "def partial_matches_for(input_string)\n # [\"aardvark\", \"apple\"]\n @word_list.select do |word|\n word.start_with?(input_string)\n end\n end", "def in_all_strings?(long_strings, substring)\n new_arr = long_strings.select {|s| s.include?(substring)}\n return new_arr == long_strings\nend", "def globs_match_strings? globs, strings\n globs.zip(strings).all? do |glob, string|\n File.fnmatch(glob, string)\n end\n end", "def substrings(input_text, dictionary)\n input_text.downcase!\n dictionary.each do |word|\n compare_strings(input_text, word)\n end\n return @output_hash\nend", "def test_String_010_compare_strings_in_arrays\n \n puts2(\"\")\n puts2(\"#######################\")\n puts2(\"Testcase: test_String_010_compare_strings_in_arrays\")\n puts2(\"#######################\")\n \n sString = \"Some strings are identical, and some strings are not identical\"\n sString.scan(/(^|\\s)(\\S+)(?=\\s.*?\\2)/) { puts2 $2 }\n \n \n puts2(\"\\nTesting Compare strings...\")\n aFirstArray = [\"the\", \"end\", \"the end\", \"stop\"]\n aSecondArray = [\"The end\", \"end\", \"start\", \"the\", \"Stop\"]\n puts2(\"Compare first array:\")\n puts2(aFirstArray.to_s)\n puts2(\"\\nWith second array:\")\n puts2(aSecondArray.to_s)\n aFound = compare_strings_in_arrays(aFirstArray, aSecondArray)\n puts2(\"Exact Matches Found: \"+ aFound[0].to_s)\n puts2(\" Matching text: \"+ aFound[1].to_s)\n \n puts2(\"\\nTesting Compare strings Ignore case...\")\n aFirstArray = [\"the\", \"end\", \"the end\", \"stop\"]\n aSecondArray = [\"The end\", \"end\", \"start\", \"the\", \"Stop\"]\n puts2(\"Compare first array:\")\n puts2(aFirstArray.to_s)\n puts2(\"\\nWith second array:\")\n puts2(aSecondArray.to_s)\n aFound = compare_strings_in_arrays(aFirstArray, aSecondArray, true)\n puts2(\"Exact Matches Found: \"+ aFound[0].to_s)\n puts2(\" Matching text: \"+ aFound[1].to_s)\n \n puts2(\"\\nTesting Compare Regexp (Ignore case)...\")\n aFirstArray = [\"the\", \"end\", \"the end\", \"stop\"]\n aSecondArray = [\"The end\", \"end\", \"start\", \"the\", \"Stop\"]\n puts2(\"Compare first array:\")\n puts2(aFirstArray.to_s)\n puts2(\"\\nWith second array:\")\n puts2(aSecondArray.to_s)\n aFound = compare_strings_in_arrays(aFirstArray, aSecondArray, true, true)\n puts2(\"Close Matches Found: \"+ aFound[0].to_s)\n puts2(\" Matching text: \"+ aFound[1].to_s)\n \n end", "def match_string( tree, string )\n # puts \"Checking for `#{string}` in tree (#{tree}).\"\n\n if tree.empty?\n # puts \"Tree is empty, returning empty\"\n return [ ]\n\n elsif string.empty?\n # puts \"No search string, returning empty\"\n return [ ]\n\n else\n matches = [ ]\n\n tree.each do |key,val|\n # puts \"Checking for `#{string}` in `#{key}` branch.\"\n\n simdex = string.simdex(key)\n\n if 0 < simdex\n if string == key\n # puts \"Matched full word! #{string} is #{key}\"\n # matches = collect_keys(val, key).unshift(key)\n return collect_keys(val, key).unshift(key)\n # puts \"Got matches: #{matches}\"\n\n else\n leaf = string.leaf(simdex)\n # puts \"Got leaf #{leaf}\"\n\n check = match_string(val, leaf)\n # puts \"Got check: #{check}\"\n\n if !check.empty?\n # matches = (check.map { |m| key + m })\n return check.map { |m| key + m }\n # puts \"New matches: #{matches}\"\n end\n end\n\n # break\n\n else\n check = match_string(val, string)\n\n if !check.empty?\n matches += check\n end\n end\n end\n\n # if matches.empty?\n # # puts \"No matches (#{string})\"\n # else\n # # puts \"Returning matches (#{string}): #{matches}\"\n # end\n\n return matches\n end\n end", "def in_all_strings?(long_strings, short_string)\nend", "def substrings(word_string, dictionary)\n\tresults = {}\n\tmatch_count = 0\n\tword_array = word_string.split(\" \")\n\tdictionary.each do |match_string|\n\t\tword_array.each do |word|\n\t\t\tword.downcase!\n\t\t\tmatch_count += 1 if (word.include?(match_string))\n\t\tend\n\t\tif match_count > 0\n\t\t\tresults[match_string] = match_count\n\t\tend\n\t\tmatch_count = 0\n\tend\n\treturn results\nend", "def match(words)\n words.select {|word| word.split(\"\").sort == @word.split(\"\").sort}\n end", "def match(array)\n array.select {|word| word.chars.sort.join == self.word.chars.sort.join}\n \n\nend", "def in_all_strings?(long_strings, substring)\n long_strings.all?{ |el| el.include?(substring)}\nend", "def in_all_strings?(long_strings, substring)\n long_strings.all?{|str|str.include?(substring)}\n\nend", "def matched_words\n _matched_words\n end", "def matches(smarts_or_string, uniq=true)\n each_match(smarts_or_string, uniq).map.to_a\n end", "def match(array_possible_anagrams)\n matching_words=[]\n word_broken=self.word.split(\"\").sort\n array_possible_anagrams.each do |possible_match|\n #possible_match=possible.word\n possible_match_broken=possible_match.split(\"\").sort\n if possible_match_broken == word_broken\n matching_words << possible_match\n else\n end #end of if\n end #end of do\n matching_words\n end", "def in_all_strings?(long_strings, substring)\n long_strings.map do |str|\n str.split.any?(substring)\n end.all?(true)\nend", "def wordInStrings(word, strings)\n for string in strings do\n\n if string.include? word\n return true\n end\n end\n\n return false\nend", "def substrings(string)\r\n \r\nend", "def match(array_of_words)\n matches = [] #Flag\n anagram_execute = anagram.split(//)\n anagram_execute = anagram_execute.sort!\n array_of_words.each do |possible_match|\n array_of_letters = possible_match.split(//)\n array_of_letters = array_of_letters.sort!\n matches << possible_match if array_of_letters == anagram_execute\n #use truncated, cleaner if statement\n end\n matches #return the matches array\n end", "def suggest_fuzzy(str, results=@max_results, strict=@strict_fuzzy_matching)\n str_mul = alphabet_only(str).size\n str_soundex_code = compute_soundex_code(str)\n str_2grams = ngram_list(str, 2)\n candidates = []\n\n @ngrams.sunion(*ngram_list(str)).each do |candidate|\n candidate = candidate.split(\":\")\n candidate_str = candidate[0]\n candidate_soundex_code = candidate[1]\n candidate_score = 1.0\n\n # Levenshtein distance\n lev_dist = Levenshtein.distance(str, candidate_str)\n candidate_score *= Math.exp([str_mul - lev_dist, 1].max)\n\n # Soundex\n if str_soundex_code == candidate_soundex_code\n candidate_score *= str_mul\n elsif str_soundex_code[1..-1] == candidate_soundex_code[1..-1]\n candidate_score *= (str_mul / 2).ceil\n end\n\n # Compute n-grams of size 2 shared between the two strings\n same_2grams = str_2grams & ngram_list(candidate_str, 2)\n candidate_score *= Math.exp(same_2grams.size)\n\n if candidate_score > 1\n candidates << {\n str: candidate_str,\n score: candidate_score\n }\n end\n end\n # Sort results by score and return the highest scoring candidates\n candidates = candidates.sort { |a, b| b[:score] <=> a[:score] }\n # puts candidates.take(10).map { |cand| \"#{cand[:str]} => #{cand[:score]}\" }\n # If strict fuzzy matching is used, only suggestion items with scores\n # above a certain threshold will be returned.\n if strict\n suggestions = []\n candidates.each do |cand|\n # threshold ||= candidates[0][:score] / 10\n threshold = Math.exp(str.size)\n break if suggestions.size > results || cand[:score] < threshold\n suggestions << cand\n end\n else\n suggestions = candidates.take(results)\n end\n return suggestions.map { |cand| cand[:str] }\n end", "def match?(given_names); end", "def in_all_strings?(long_strings, substring)\n long_strings.all? {|word| word.include?(substring)}\nend", "def strings_in(data,options={})\n min_length = (options[:length] || 4)\n\n if options[:offsets]\n found = {}\n found_substring = lambda { |offset,substring|\n found[offset] = substring\n }\n else\n found = []\n found_substring = lambda { |offset,substring|\n found << substring\n }\n end\n\n return found if data.length < min_length\n\n index = 0\n\n while index <= (data.length - min_length)\n if self === data[index...(index + min_length)]\n sub_index = (index + min_length)\n\n while self.include_char?(data[sub_index..sub_index])\n sub_index += 1\n end\n\n found_substring.call(index,data[index...sub_index])\n index = sub_index\n else\n index += 1\n end\n end\n\n return found\n end", "def in_all_strings?(long_strings, substring)\n long_strings.all? {|x| x.include?(substring) }\nend", "def test_string_matcher\n ngram_builder = SimString::NGramBuilder.new(3)\n db = SimString::Database.new(ngram_builder)\n\n db.add(\"Barack Hussein Obama II\")\n db.add(\"James Gordon Brown\")\n\n matcher = SimString::StringMatcher.new(db, SimString::CosineMeasure.new)\n\n assert_equal([], matcher.search(\"Barack Obama\", 0.6))\n assert_equal([\"James Gordon Brown\"], matcher.search(\"Gordon Brown\", 0.6))\n assert_equal([], matcher.search(\"Obama\", 0.6))\n assert_equal([], matcher.search(\"Obama\", 1, SimString::OverlapMeasure.new))\n assert_equal([], matcher.search(\"Barack Hussein Obama I\", 1, SimString::OverlapMeasure.new))\n assert_equal([\"Barack Hussein Obama II\"], matcher.search(\"Barack Hussein Obama II\", 1, SimString::OverlapMeasure.new))\n assert_equal([\"Barack Hussein Obama II\"], matcher.search(\"Obama\", 0.42, SimString::OverlapMeasure.new))\n assert_equal([], matcher.search(\"Obama\", 0.43, SimString::OverlapMeasure.new))\n end", "def substrings(string)\n\nend" ]
[ "0.67352813", "0.67103964", "0.6667851", "0.65556383", "0.6410246", "0.63663805", "0.6356838", "0.6344567", "0.6343699", "0.6270859", "0.62588984", "0.62501204", "0.62209517", "0.6203152", "0.61696494", "0.6145451", "0.61334294", "0.6121198", "0.6109607", "0.6103552", "0.609872", "0.6092569", "0.60849845", "0.60756886", "0.6051465", "0.6044869", "0.60189605", "0.60107076", "0.5994202", "0.59883106" ]
0.680719
0
A numeric score for the result increasing by the number of terms in the result that match terms in the search
def relevance_score(result) @term_keys.find_all { |key| result.title =~ /\b#{Regexp.quote(key)}\b/i }.size end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def result_relevance(result, count)\n result_string, score = result\n exact_match = 0\n exact_match = 100_000 if result_string =~ search_regex\n exact_match + (count * 100) + Math.log(score.to_i)\n end", "def match(search)\n search_words = words(search)\n haystack_words = words(haystack)\n\n (\n search_words.count { |search_word| haystack_words.include? search_word } /\n search_words.count.to_f *\n 100\n ).round\n rescue ZeroDivisionError\n 0\n end", "def score\n @score ||= phonetic_levenshtein_distance + penalties\n end", "def calculate_keyword_score(terms = nil, **opt)\n search = opt.extract!(:q, *SCORE_TYPES)\n terms = search[:q] || search[:keyword] || terms\n count = 0\n types = { title: 100, creator: 0, publisher: 0 }\n scores =\n types.map { |type, weight|\n next if weight.zero?\n score = send(\"search_#{type}_score\").to_f\n score = send(\"calculate_#{type}_score\", terms, **opt) if score.zero?\n if score.nonzero?\n count += weight\n score *= weight\n end\n [type, score]\n }.compact.to_h\n Float(scores.values.sum) / Float(types.values.sum)\n end", "def score\n @score ||= (\n total = 0\n words.each do |word, rank|\n total += score_word(word, rank)\n end\n total\n )\n end", "def score choice, query\n return 1.0 if query.length == 0\n return 0.0 if choice.length == 0\n query = query.downcase\n choice = choice.downcase\n match_length = find_matches(choice, query.each_char.to_a)\n return 0.0 unless match_length\n\n score = query.length.to_f / match_length.to_f\n\n score / choice.length\n end", "def word_score\n return BINGO_SCORE if (query == reference)\n if string_index\n score = substring_score\n else\n score = ancestor_score\n end\n\n return NULL_SCORE if score < NULL_SCORE\n return score\n end", "def score\n @result.to_i\n end", "def score(search_term:, item_name:)\n return 99 unless search_term.present? && item_name.present?\n\n Text::Levenshtein.distance(search_term.downcase, item_name.downcase)\n end", "def compute_score\n @query.items.map.with_index do |element, index|\n weight(index) * weight(@classification.items.index(element))\n end.sum\n end", "def field_score(field, terms, **opt)\n field = scoring_words(field, **opt)\n terms = scoring_words(terms, **opt)\n return 0.0 if field.blank? || terms.blank?\n hits = terms.sum { |term| field.count(term) }\n 100.0 * hits / field.size\n end", "def score(plaintext)\n score = 0\n @wordlist.each do |word|\n score += plaintext.scan(/\\b#{word}\\b/).count\n end\n return score\nend", "def match(hash)\n score, total_score = @archetype.inject([0, 0]) do |accum, fdef_pair|\n current_score, total_score = accum\n field, field_spec = fdef_pair\n\n scorer = field_spec[:scorer]\n weight = field_spec[:weight]\n\n rvalue = hash[field]\n score = rvalue ? scorer.(field_spec[:value].strip, rvalue.strip) * weight : 0\n\n [current_score + score, total_score + weight]\n end\n\n score.to_f / total_score\n end", "def search_weight(terms)\n weights = {\n total: 0,\n terms: {}\n }\n terms.each do |term|\n author_names = authors.pluck(:first_name, :last_name, :institution).flatten.join(' ')\n text_blob = \"#{self.name} #{self.description} #{author_names}\"\n score = text_blob.scan(/#{::Regexp.escape(term)}/i).size\n if score > 0\n weights[:total] += score\n weights[:terms][term] = score\n end\n end\n weights\n end", "def score\n\n return NULL_SCORE if query_words.empty?\n return NULL_SCORE if reference_words.empty?\n my_scores = []\n\n query_words.each_with_index do |query_word, i|\n query_word_best_score = NULL_SCORE\n reference_words.each_with_index do |reference_word, j|\n score = word_score(query_word, reference_word)\n score -= word_position_penalty(i, j)\n query_word_best_score = [query_word_best_score, score].max\n end\n my_scores << query_word_best_score\n end\n # debug your scores?\n #pp Hash[query_words.zip(my_scores)]\n\n return NULL_SCORE if my_scores.empty?\n my_scores = my_scores.sort.reverse.take(reference_words.length)\n score_sum = my_scores.inject(:+)\n final_score = score_sum / my_scores.length\n return final_score\n end", "def score(word)\n point_values_hash = point_values\n point_values(word)\n end", "def score\n\t\t@meaningful_words.count\n\tend", "def score\n @scores[ result.key ]\n end", "def score(s)\n count = 0\n s.split.each do |word|\n count += 1 if @words.include?(word)\n end\n count\n end", "def score\n total = 0\n docs = 0\n [@classes, @modules, @methods, @constants, @attrs].each do |collection|\n collection.each do |item|\n total += 1\n docs += 1 if item\n end\n end\n return 100 if total == 0\n return ((docs.to_f / total) * 100).to_i\n end", "def inclusion_score_for(str)\n n_gram_str, n = join_underscore(str)\n score = 0\n @text.split.each_cons(n) do |arr|\n text_to_compare = cleanup(arr.join('_')).downcase\n if score < (new_score = RubyFish::Jaro.distance(text_to_compare, n_gram_str.downcase))\n score = new_score\n end\n end\n score\n end", "def score_term word, year_hash, year\n min_norm_count = 0.000001\n curr_nc = 0.0\n prev_nc = 0.0\n (year-GROUPSIZE+1).upto(year) do |y|\n begin\n curr_nc += year_hash[y][word][:nc] || 0.0\n rescue\n curr_nc += 0.0\n end\n end\n (year-GROUPSIZE*2+1).upto(year-GROUPSIZE) do |y|\n begin\n prev_nc += year_hash[y][word][:nc] || 0.0\n rescue\n prev_nc += 0.0\n end\n end\n\n if prev_nc > 0.0\n growth = curr_nc / prev_nc\n else\n growth = 0.0\n end\n\n if growth > 1.0\n return growth\n else\n return 1.0\n end\nend", "def calculate_score(matches, total)\n # divide scores by our highest score for a range of 0 - 1, \n # then multiply by 10 for our 1-10 scoring.\n @prescore = (matches.count.to_f / total.to_f)\n if matches.count.to_f == 0.0 # if there are no tweets\n @@score = 0 # assign this to be 0 value\n else\n @@score = (matches.count.to_f / total.to_f) / 0.004574170332\n end\n end", "def total_score\n plays.inject(0) { |sum, word| sum + Scoring.score(word) }\n end", "def score_words\n @scores = @results.map do |word|\n { :word => word, :score => score_word(word) }\n end.sort { |a, b| a[:score] <=> b[:score] }.reverse\n end", "def word_score(word, rack)\n # set our score to 0\n score = 0\n # loop through each letter and find the score from the list then add it\n # to our total\n word.chars.each do |letter|\n score += SCORES[letter.to_sym]\n end\n # return the total. Add 50 points if the word uses all the rack\n word.length == rack.join.length ? score + 50 : score\nend", "def calculate_match_probability\n # two heuristics: \n # 1 is are their multiple words in term_text? if so, mark as probable\n # if not, does it match the anchor regexp? if so, mark as probable\n # else, mark as improbable\n \n # multiple words?\n anchor_regexp = \"(featuring|plus|the|presents|with|plus|and|\\,|\\&|[()]|\\/|\\:|\\-|^|$)\"\n nix_regexp = \"parking|\\svs\\.?\\s\" \n if artist_name=~/#{nix_regexp}/i\n self.match_probability=\"unlikely\"\n return nil\n end\n text=term_text.strip\n if text[\" \"]\n self.match_probability=\"likely\"\n return \"multpl\"\n end\n if artist_name=~/#{anchor_regexp}\\s*#{text}\\s*#{anchor_regexp}/i\n self.match_probability=\"likely\"\n return \"regexp\"\n end\n# if artist_name=~/#{anchor_regexp}\\s+?#{text}\\s+?#{anchor_regexp}/i\n# match_probability=\"likely\"\n# return \"regexp\"\n# end\n self.match_probability=\"unlikely\"\n return nil\n end", "def score(other_counts)\n\t\tscore = 0.0\n\t\tseen = 0\n\t\tother_counts.each { |k, v|\n\t\t\tcount = @trigram_counts[k]\n\t\t\tscore += v * Math.log(@probs[@trigram_counts[k]])\n\t\t}\n\t\tscore\n\tend", "def score(sentence)\n total_scores = 0\n rep_array = @sent_rep_compiler.compile(sentence)\n rep_array.each { |word| total_scores += @wts_scores_obj[word.id] }\n total_scores / rep_array.length\n end", "def calc_score(f, rs, rk, nbrs)\n score = 0.0\n \n nbrs.each do |k, s|\n if k == rk # near hit\n score -= diff_feature(f, rs, s)**2\n else # near_miss\n score += diff_feature(f, rs, s)**2\n end\n end\n \n score\n end" ]
[ "0.7690968", "0.73570377", "0.72660667", "0.722035", "0.7083337", "0.70749533", "0.7015532", "0.7005711", "0.6981445", "0.6966298", "0.69461256", "0.693133", "0.68602955", "0.6814524", "0.6804345", "0.6770098", "0.6767439", "0.67461556", "0.67164975", "0.6709123", "0.66916996", "0.6678234", "0.6666626", "0.66660213", "0.6653942", "0.66411334", "0.6635601", "0.6603224", "0.6559062", "0.65374815" ]
0.750584
1
GET /range_types GET /range_types.json
def index @range_types = RangeType.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def schema_range_type(db_type)\n :range\n end", "def set_range_type\n @range_type = RangeType.find(params[:id])\n end", "def range_type_params\n params.require(:range_type).permit(:name, :description)\n end", "def create_range_data( rng, minrng=0, type=0, direction=2 )\n return Handlers::Range.createRange( rng, minrng, type, direction )\n end", "def create\n @range_type = RangeType.new(range_type_params)\n\n respond_to do |format|\n if @range_type.save\n format.html { redirect_to @range_type, notice: 'Range type was successfully created.' }\n format.json { render :show, status: :created, location: @range_type }\n else\n format.html { render :new }\n format.json { render json: @range_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def range_limit\n solr_field = params[:range_field] # what field to fetch for\n start = params[:range_start].to_i\n finish = params[:range_end].to_i\n \n solr_params = solr_search_params(params)\n \n # Remove all field faceting for efficiency, we won't be using it.\n solr_params.delete(\"facet.field\")\n solr_params.delete(\"facet.field\".to_sym)\n \n add_range_segments_to_solr!(solr_params, solr_field, start, finish )\n # We don't need any actual rows or facets, we're just going to look\n # at the facet.query's\n solr_params[:rows] = 0\n solr_params[:facets] = nil\n # Not really any good way to turn off facet.field's from the solr default,\n # no big deal it should be well-cached at this point.\n \n @response = Blacklight.solr.find( solr_params )\n \n render('blacklight_range_limit/range_segments', :locals => {:solr_field => solr_field}) \n end", "def index\n @types = Type.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @types.lookup(params[:q]) }\n end\n end", "def range(range)\n assert_range range\n schema do |s|\n s.type range.begin.is_a?(Integer) ? 'integer' : 'number'\n s.minimum range.begin\n s.maximum range.end, exclusive: range.exclude_end? unless range.end.nil?\n end\n end", "def ride_types(args = {})\n make_request(\n http_method: :get,\n endpoint: path_for(:ride_types),\n access_token: args.delete(:access_token),\n options: { query: args }\n )\n end", "def get_range\n\t\tif params.has_key?(\"start\") and params.has_key?(\"end\")\n\t\t\tif params[\"end\"] == \"Z\"\n\t\t\t\t# had to do some hackish stuff to include Z\n\t\t\t\tfirst = AToZEntry.select(:topic, :id).where(topic: params[:start]..params[:end])\n\t\t\t\tprefix = 'Z'\n\t\t\t\tsecond = AToZEntry.select(:topic, :id).where(\"topic LIKE :prefix\", prefix: \"#{prefix}%\")\n\t\t\t\trespond({ status: 0, topics: first+second })\n\t\t\telse\n\t\t\t\trespond({ status: 0, topics: AToZEntry.select(:topic, :id).where(topic: params[:start]..params[:end]) })\n\t\t\tend\t\t\t\n\t\telse\n\t\t\trespond({ status: 1, error: \"Must supply :start and :end parameter.\" })\n\t\tend\t\n\tend", "def get_resource_types\n Occi::Log.debug(\"Getting resource types ...\")\n collection = @model.get Occi::Core::Resource.kind\n collection.kinds.collect { |kind| kind.term }\n end", "def update\n respond_to do |format|\n if @range_type.update(range_type_params)\n format.html { redirect_to @range_type, notice: 'Range type was successfully updated.' }\n format.json { render :show, status: :ok, location: @range_type }\n else\n format.html { render :edit }\n format.json { render json: @range_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def ranges\n @toc_id = 'ranges'\n end", "def types\n @client.make_request :get, reports_path\n end", "def schema_multirange_type(db_type)\n :multirange\n end", "def appointment_types(params = {})\n scope 'default'\n get('schedule/appointmenttypes/', params)\n end", "def list(type)\n get(resource_path_for_entity_type(type) + \"?rows=all\")\n end", "def index\n @rranges = Rrange.all\n end", "def export_range(range = Iterable::Export::TODAY)\n params = { range: range }\n Iterable.request(conf, base_path, request_params(params)).get\n end", "def getRanges(path)\n @urlencode = URI.encode(path)\n call(RANGES_PATH + @urlencode)\n end", "def get_restriction_types\n get_restrictions_data['types']\n end", "def index\n @typeconges = Typeconge.all\n end", "def range\n\t result = @input.max - @input.min\n\n\t render json: result, status: 200\n\trescue\n\t\trender json: {\"message\": 'Use the format: {\"input\": [num, num]}'}, status: 400\n\tend", "def get_available_types_from_usage(usage) #TODO: Research use\n return @client.raw(\"get\", \"/helpers/available-types/#{usage}\")\n end", "def ranges\n attributes.fetch(:ranges)\n end", "def index\n @qty_ranges = QtyRange.all\n end", "def test_inclusive_bounded_range_name_1_to_4_max_4\n header 'Range', 'name my-app-1..my-app-4; max=4'\n\n get '/'\n json_response = JSON.parse(last_response.body)\n\n assert last_response.ok?\n assert_equal Array, json_response.class\n assert_equal 4, json_response.count\n assert_equal 1, json_response.first['id']\n assert_equal 101, json_response.last['id']\n end", "def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @resource_types }\n end\n end", "def query_range(options)\n run_command('query_range', options)\n end", "def index\n @product_ranges = ProductRange.find(:all)\n\n respond_to do |format|\n format.html # index.haml\n format.xml { render :xml => @product_ranges }\n end\n end" ]
[ "0.6910227", "0.65247434", "0.633836", "0.5942356", "0.59230435", "0.5844601", "0.5826053", "0.580808", "0.5760518", "0.5738374", "0.5722325", "0.570473", "0.56332505", "0.55493104", "0.55460465", "0.5528226", "0.55187535", "0.5498575", "0.549653", "0.54770696", "0.5474432", "0.546052", "0.54468364", "0.54401016", "0.54396975", "0.54371303", "0.539723", "0.5391447", "0.5385753", "0.53803456" ]
0.77056473
0
POST /range_types POST /range_types.json
def create @range_type = RangeType.new(range_type_params) respond_to do |format| if @range_type.save format.html { redirect_to @range_type, notice: 'Range type was successfully created.' } format.json { render :show, status: :created, location: @range_type } else format.html { render :new } format.json { render json: @range_type.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def range_type_params\n params.require(:range_type).permit(:name, :description)\n end", "def set_range_type\n @range_type = RangeType.find(params[:id])\n end", "def index\n @range_types = RangeType.all\n end", "def schema_range_type(db_type)\n :range\n end", "def update\n respond_to do |format|\n if @range_type.update(range_type_params)\n format.html { redirect_to @range_type, notice: 'Range type was successfully updated.' }\n format.json { render :show, status: :ok, location: @range_type }\n else\n format.html { render :edit }\n format.json { render json: @range_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @rrange = Rrange.new(rrange_params)\n\n respond_to do |format|\n if @rrange.save\n format.html { redirect_to @rrange, notice: 'Rrange was successfully created.' }\n format.json { render :show, status: :created, location: @rrange }\n else\n format.html { render :new }\n format.json { render json: @rrange.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_range_data( rng, minrng=0, type=0, direction=2 )\n return Handlers::Range.createRange( rng, minrng, type, direction )\n end", "def rrange_params\n params.require(:rrange).permit(:name, :zone_id)\n end", "def destroy\n @range_type.destroy\n respond_to do |format|\n format.html { redirect_to range_types_url, notice: 'Range type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def create\n @qty_range = QtyRange.new(qty_range_params)\n\n respond_to do |format|\n if @qty_range.save\n format.html { redirect_to @qty_range, notice: \"Qty range was successfully created.\" }\n format.json { render :show, status: :created, location: @qty_range }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @qty_range.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @range_specification = RangeSpecification.new(params[:range_specification])\n\n respond_to do |format|\n if @range_specification.save\n format.html { redirect_to(@range_specification, :notice => 'Range specification was successfully created.') }\n format.xml { render :xml => @range_specification, :status => :created, :location => @range_specification }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @range_specification.errors, :status => :unprocessable_entity }\n end\n end\n end", "def day_range_params\n params.require(:day_range).permit(:code, :name, :day_from, :day_to, :note)\n end", "def evals_types\n call_path = \"evals/types\"\n data = build_post_data(\"\")\n perform_post(build_url(call_path), data)\n end", "def schema_multirange_type(db_type)\n :multirange\n end", "def range(range)\n assert_range range\n schema do |s|\n s.type range.begin.is_a?(Integer) ? 'integer' : 'number'\n s.minimum range.begin\n s.maximum range.end, exclusive: range.exclude_end? unless range.end.nil?\n end\n end", "def range_rate_params\n params.require(:range_rate).permit(:code, :name, :active, :model_class_id, :rental_type_id, :days_range_id, :rate, :note)\n end", "def qty_range_params\n params.require(:qty_range).permit(:name, :value)\n end", "def create\n @salary_range = SalaryRange.new(params[:salary_range])\n\n respond_to do |format|\n if @salary_range.save\n format.html { redirect_to @salary_range, notice: 'Salary range was successfully created.' }\n format.json { render json: @salary_range, status: :created, location: @salary_range }\n else\n format.html { render action: \"new\" }\n format.json { render json: @salary_range.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @arrival_range = ArrivalRange.new(params[:arrival_range])\n\n respond_to do |format|\n if @arrival_range.save\n format.html { redirect_to @arrival_range, notice: 'Arrival range was successfully created.' }\n format.json { render json: @arrival_range, status: :created, location: @arrival_range }\n else\n format.html { render action: \"new\" }\n format.json { render json: @arrival_range.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @address_range = AddressRange.new(params[:address_range])\n\n respond_to do |format|\n if @address_range.save\n format.html { redirect_to(@address_range, :notice => 'Address range was successfully created.') }\n format.xml { render :xml => @address_range, :status => :created, :location => @address_range }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @address_range.errors, :status => :unprocessable_entity }\n end\n end\n end", "def test_save_as_range\n remote_file_name = 'TestSaveAsRange.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request_document_parameters = RangeDocument.new({:DocumentName => remote_data_folder + '/NewDoc.docx'})\n request = SaveAsRangeRequest.new(name: remote_file_name, range_start_identifier: 'id0.0.0', document_parameters: request_document_parameters, range_end_identifier: 'id0.0.1', folder: remote_data_folder)\n\n result = @words_api.save_as_range(request)\n assert_equal false, result.nil?\n end", "def add_range_filters\n %i(word_count hit_count kudos_count comments_count bookmarks_count revised_at).each do |countable|\n next unless options[countable]\n range = Search::RangeParser.string_to_range(options[countable])\n body.filter(:range, countable => range) unless range.blank?\n end\n add_date_range_filter\n add_word_count_filter\n end", "def ranges_to_models(clazz, *ranges)\n ranges.collect do |min, max|\n clazz.create! min: min, max: max\n end\nend", "def create_types\n\t[]\nend", "def create_types\n\t[]\nend", "def create_types\n\t\t[]\n\tend", "def create_types\n\t\t[]\n\tend", "def in_range_for_type?\n case @cfg.type_name\n when :positive_int\n value > 0\n when :unsigned_int\n value >= 0\n when :positive_int_array\n value.all? {|i| i > 0 }\n when :unsigned_int_array\n value.all? {|i| i >= 0 }\n else\n true\n end\n end", "def types(types); end", "def add_range(left, right)\n \n end" ]
[ "0.72083634", "0.66499317", "0.6637968", "0.6200566", "0.59384835", "0.5699741", "0.5681202", "0.56561345", "0.56114733", "0.55582255", "0.54988724", "0.5482133", "0.54004824", "0.5392447", "0.5368214", "0.5348899", "0.53270024", "0.53085744", "0.5275576", "0.527013", "0.52447784", "0.5239532", "0.5231436", "0.51530325", "0.51530325", "0.5149636", "0.5149636", "0.51272565", "0.51270515", "0.50975245" ]
0.71564907
1
PATCH/PUT /range_types/1 PATCH/PUT /range_types/1.json
def update respond_to do |format| if @range_type.update(range_type_params) format.html { redirect_to @range_type, notice: 'Range type was successfully updated.' } format.json { render :show, status: :ok, location: @range_type } else format.html { render :edit } format.json { render json: @range_type.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_range_type\n @range_type = RangeType.find(params[:id])\n end", "def range_type_params\n params.require(:range_type).permit(:name, :description)\n end", "def update\n @range_specification = RangeSpecification.find(params[:id])\n\n respond_to do |format|\n if @range_specification.update_attributes(params[:range_specification])\n format.html { redirect_to(@range_specification, :notice => 'Range specification was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @range_specification.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @qty_range.update(qty_range_params)\n format.html { redirect_to @qty_range, notice: \"Qty range was successfully updated.\" }\n format.json { render :show, status: :ok, location: @qty_range }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @qty_range.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @type = args[:type] if args.key?(:type)\n @name = args[:name] if args.key?(:name)\n @date_range = args[:date_range] if args.key?(:date_range)\n end", "def update\n respond_to do |format|\n if @rrange.update(rrange_params)\n format.html { redirect_to @rrange, notice: 'Rrange was successfully updated.' }\n format.json { render :show, status: :ok, location: @rrange }\n else\n format.html { render :edit }\n format.json { render json: @rrange.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @type.update(type_params)\n end", "def update!(**args)\n @range = args[:range] if args.key?(:range)\n end", "def index\n @range_types = RangeType.all\n end", "def update\n respond_to do |format|\n if @spec_type.update(spec_type_params)\n format.html { redirect_to @spec_type, notice: 'Spec type was successfully updated.' }\n format.json { render :show, status: :ok, location: @spec_type }\n else\n format.html { render :edit }\n format.json { render json: @spec_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @intervention_type.update(intervention_type_params)\n format.html { redirect_to intervention_types_path, notice: 'O tipo de intervenção foi actualizado.' }\n format.json { render :show, status: :ok, location: @intervention_type }\n else\n format.html { render :edit }\n format.json { render json: @intervention_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @arrival_range = ArrivalRange.find(params[:id])\n\n respond_to do |format|\n if @arrival_range.update_attributes(params[:arrival_range])\n format.html { redirect_to @arrival_range, notice: 'Arrival range was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @arrival_range.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @address_range = AddressRange.find(params[:id])\n\n respond_to do |format|\n if @address_range.update_attributes(params[:address_range])\n format.html { redirect_to(@address_range, :notice => 'Address range was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @address_range.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @range_type = RangeType.new(range_type_params)\n\n respond_to do |format|\n if @range_type.save\n format.html { redirect_to @range_type, notice: 'Range type was successfully created.' }\n format.json { render :show, status: :created, location: @range_type }\n else\n format.html { render :new }\n format.json { render json: @range_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @salary_range = SalaryRange.find(params[:id])\n\n respond_to do |format|\n if @salary_range.update_attributes(params[:salary_range])\n format.html { redirect_to @salary_range, notice: 'Salary range was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @salary_range.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @range_troop_number.update(range_troop_number_params)\n format.html { redirect_to @range_troop_number, notice: 'Rango numero tropa exitosamente actualizado.' }\n format.json { render :show, status: :ok, location: @range_troop_number }\n else\n format.html { render :edit }\n format.json { render json: @range_troop_number.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @value_type = ValueType.find(params[:id])\n\n respond_to do |format|\n if @value_type.update_attributes(params[:value_type])\n format.html { redirect_to @value_type, notice: 'Value type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @value_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def _update type, id, body\n @elasticsupport.client.update index: _index_for(type), type: type.to_s, id: id, body: body\n end", "def update!(**args)\n @int_value_spec = args[:int_value_spec] if args.key?(:int_value_spec)\n @option_value_spec = args[:option_value_spec] if args.key?(:option_value_spec)\n @type = args[:type] if args.key?(:type)\n end", "def update\n respond_to do |format|\n if @type_of_value.update(type_of_value_params)\n format.html { redirect_to @type_of_value, notice: 'Type of value was successfully updated.' }\n format.json { render :show, status: :ok, location: @type_of_value }\n else\n format.html { render :edit }\n format.json { render json: @type_of_value.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @resource_type.update_attributes(params[:resource_type])\n if params[:fields]\n params[:fields].each do |param|\n if param[:id]\n @field = Field.find(param[:id])\n @field.update_attributes(\n :name => param[:name], \n :field_type_id => param[:field_type_id],\n :resource_type_id => params[:id],\n :resource_type_reference_id => param[:resource_type_reference_id]\n )\n else\n @field = Field.create(\n :name => param[:name],\n :field_type_id => param[:field_type_id],\n :resource_type_id => params[:id],\n :resource_type_reference_id => param[:resource_type_reference_id]\n )\n end\n if @field.field_validations.any?\n @field.field_validations.each { |v| v.destroy }\n end\n if param[:validator_ids]\n param[:validator_ids].each do |index|\n next if index == \"multiselect-all\"\n @field.field_validations.build(validator_id: index.to_i)\n end\n end \n @field.save\n end\n end \n format.html { redirect_to @resource_type, notice: 'Resource type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @resource_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @valid_type.update(valid_type_params)\n format.html { redirect_to valid_types_path, notice: 'Entity Type was successfully updated.' }\n format.json { render :show, status: :ok, location: @valid_type }\n else\n format.html { render :edit }\n format.js { render :edit }\n format.json { render json: @valid_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @incident_type.update(incident_type_params)\n format.html { redirect_to admin_incident_types_path, notice: 'Incident type was successfully updated.' }\n format.json { render :show, status: :ok, location: @incident_type }\n else\n format.html { render :edit }\n format.json { render json: @incident_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @recipe_type.update(recipe_type_params)\n format.html { redirect_to @recipe_type, notice: \"Recipe type was successfully updated.\" }\n format.json { render :show, status: :ok, location: @recipe_type }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @recipe_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def change_type\n\t\t\trender json: User.update_type_by_id(params[:id], params[:type], params[:is])\n\t\tend", "def update\n @collection = @entity_type.collection\n respond_to do |format|\n if @entity_type.update(entity_type_params)\n format.html { redirect_to collection_entity_types_path(@collection), notice: 'The entity type was successfully updated.' }\n format.json { render :show, status: :ok, location: @entity_type }\n else\n format.html { render :edit }\n format.json { render json: @entity_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @range_constraint = args[:range_constraint] if args.key?(:range_constraint)\n @remodelings = args[:remodelings] if args.key?(:remodelings)\n end", "def update!(**args)\n @allow_all_range_resolutions = args[:allow_all_range_resolutions] if args.key?(:allow_all_range_resolutions)\n @allow_all_resolutions = args[:allow_all_resolutions] if args.key?(:allow_all_resolutions)\n @allow_all_resolutions_except_holidays = args[:allow_all_resolutions_except_holidays] if args.key?(:allow_all_resolutions_except_holidays)\n @allow_all_resolutions_without4digit24hr_time = args[:allow_all_resolutions_without4digit24hr_time] if args.key?(:allow_all_resolutions_without4digit24hr_time)\n @allow_all_resolutions_without_time = args[:allow_all_resolutions_without_time] if args.key?(:allow_all_resolutions_without_time)\n @allow_day_resolution = args[:allow_day_resolution] if args.key?(:allow_day_resolution)\n @allow_day_resolution_except_holidays_or_ordinal = args[:allow_day_resolution_except_holidays_or_ordinal] if args.key?(:allow_day_resolution_except_holidays_or_ordinal)\n @allow_hour_resolution = args[:allow_hour_resolution] if args.key?(:allow_hour_resolution)\n @allow_month_resolution = args[:allow_month_resolution] if args.key?(:allow_month_resolution)\n @allow_now_resolution = args[:allow_now_resolution] if args.key?(:allow_now_resolution)\n @allow_symbolic_time = args[:allow_symbolic_time] if args.key?(:allow_symbolic_time)\n @allow_time_resolutions_without_explicit_timezone = args[:allow_time_resolutions_without_explicit_timezone] if args.key?(:allow_time_resolutions_without_explicit_timezone)\n @allow_year_resolution = args[:allow_year_resolution] if args.key?(:allow_year_resolution)\n @remodelings = args[:remodelings] if args.key?(:remodelings)\n @sub_type = args[:sub_type] if args.key?(:sub_type)\n end", "def update\n respond_to do |format|\n if @instance_type.update(instance_type_params)\n format.html { redirect_to @instance_type, notice: 'Instance type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @instance_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize :resquest_type, :update?\n respond_to do |format|\n if @resquest_type.update(resquest_type_params)\n format.html { redirect_to @resquest_type, notice: 'Resquest type was successfully updated.' }\n format.json { render :show, status: :ok, location: @resquest_type }\n else\n format.html { render :edit }\n format.json { render json: @resquest_type.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.6729508", "0.634386", "0.60597175", "0.6035519", "0.60247993", "0.5847654", "0.58002967", "0.57722676", "0.57665735", "0.5685583", "0.5668331", "0.5661962", "0.5658185", "0.5624353", "0.55753565", "0.5566175", "0.55358", "0.5534198", "0.55278134", "0.5526518", "0.55249465", "0.5521427", "0.55149364", "0.55083466", "0.55061483", "0.5503377", "0.5486117", "0.54742557", "0.5471418", "0.54697484" ]
0.74981564
0
DELETE /range_types/1 DELETE /range_types/1.json
def destroy @range_type.destroy respond_to do |format| format.html { redirect_to range_types_url, notice: 'Range type was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @range_specification = RangeSpecification.find(params[:id])\n @range_specification.destroy\n\n respond_to do |format|\n format.html { redirect_to(range_specifications_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @rrange.destroy\n respond_to do |format|\n format.html { redirect_to rranges_url, notice: 'Rrange was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @qty_range.destroy\n respond_to do |format|\n format.html { redirect_to qty_ranges_url, notice: \"Qty range was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @arrival_range = ArrivalRange.find(params[:id])\n @arrival_range.destroy\n\n respond_to do |format|\n format.html { redirect_to arrival_ranges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dhcp_range = DhcpRange.find(params[:id])\n @dhcp_range.destroy\n\n respond_to do |format|\n format.html { redirect_to dhcp_ranges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @type = Type.find(params[:type])\n @type.destroy\n\n respond_to do |format|\n format.html { redirect_to company_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shooting_range = ShootingRange.find(params[:id])\n @shooting_range.destroy\n\n respond_to do |format|\n format.html { redirect_to(shooting_ranges_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @address_range = AddressRange.find(params[:id])\n @address_range.destroy\n\n respond_to do |format|\n format.html { redirect_to(address_ranges_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @type = Type.find(params[:id])\n @type.destroy\n\n respond_to do |format|\n format.html { redirect_to types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @crate_type = CrateType.find(params[:id])\n @crate_type.destroy\n\n respond_to do |format|\n format.html { redirect_to crate_types_url }\n format.json { head :ok }\n end\n end", "def destroy\n @segment_type = SegmentType.find(params[:id])\n @segment_type.destroy\n\n respond_to do |format|\n format.html { redirect_to segment_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @salary_range = SalaryRange.find(params[:id])\n @salary_range.destroy\n\n respond_to do |format|\n format.html { redirect_to salary_ranges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tax_type = TaxType.find(params[:id])\n @tax_type.destroy\n\n respond_to do |format|\n format.html { redirect_to tax_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @incident_type = IncidentType.find(params[:id])\n @incident_type.destroy\n\n respond_to do |format|\n format.html { redirect_to incident_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @value_type = ValueType.find(params[:id])\n @value_type.destroy\n\n respond_to do |format|\n format.html { redirect_to value_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gl_type = GlType.find(params[:id])\n @gl_type.destroy\n\n respond_to do |format|\n format.html { redirect_to gl_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection_type = CollectionType.find(params[:id])\n @collection_type.destroy\n\n respond_to do |format|\n format.html { redirect_to collection_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = @entity_type.collection\n @entity_type.destroy\n respond_to do |format|\n format.html { redirect_to collection_entity_types_path(@collection), notice: 'The entity type was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @affected_type.destroy\n respond_to do |format|\n format.html { redirect_to affected_types_url, notice: 'Affected type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @instance_type.destroy\n respond_to do |format|\n format.html { redirect_to instance_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @identifier_type.destroy\n\n respond_to do |format|\n format.html { redirect_to identifier_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @coverage_type.destroy\n respond_to do |format|\n format.html { redirect_to coverage_types_url, notice: 'Coverage type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @range_troop_number.destroy\n respond_to do |format|\n format.html { redirect_to range_troop_numbers_url, notice: 'Rango numero tropa exitosamente borrado.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @intervention_type.destroy\n respond_to do |format|\n format.html { redirect_to intervention_types_url, notice: 'O tipo de intervenção foi eliminado.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @dash_type = DashType.find(params[:id])\n @dash_type.destroy\n\n respond_to do |format|\n format.html { redirect_to dash_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pharmacy_range = PharmacyRange.find(params[:id])\n @pharmacy_range.destroy\n\n respond_to do |format|\n format.html { redirect_to(pharmacy_ranges_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @arc_type.destroy\n respond_to do |format|\n format.html { redirect_to arc_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @valid_type.destroy\n respond_to do |format|\n format.html { redirect_to valid_types_url, notice: 'Entity status was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @document_type = DocumentType.find(params[:id])\n @document_type.destroy\n\n respond_to do |format|\n format.html { redirect_to document_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @girltype = Girltype.find(params[:id])\n @girltype.destroy\n\n respond_to do |format|\n format.html { redirect_to girltypes_url }\n format.json { head :no_content }\n end\n end" ]
[ "0.6638823", "0.65278983", "0.6519509", "0.64952606", "0.64805067", "0.6477781", "0.6457517", "0.64427745", "0.64364284", "0.6409464", "0.64032245", "0.63863593", "0.63465255", "0.63251895", "0.63134134", "0.63065094", "0.6295574", "0.62885934", "0.6281656", "0.6276903", "0.62679285", "0.6267732", "0.62598395", "0.62591195", "0.62589455", "0.6257097", "0.6244332", "0.6225693", "0.6211446", "0.6209648" ]
0.779775
0
Returns all the combinations of the word with one character removed. Example: deletions("word") => ["ord", "wrd", "wod", "wor"]
def deletions new_words = [] @words.each do |word| @word = word || '' new_words += (0..length).map { |i| "#{@word[0...i]}#{@word[i+1..-1]}" } end new_words end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def deletions word\n n = word.length\n deletion = (0...n).collect {|i| word[0...i]+word[i+1..-1] }\n end", "def deletion\n (0...length).map { |i|\n string.dup.tap { |str| str[i] = \"\" }\n }.uniq\n end", "def custom_delete(string, dels)\n new = ''\n string.each_char { |c| new << c unless dels.include?(c)}\n new\nend", "def edits1(word) \n deletes = [] \n #all strings obtained by deleting a letter (each letter) \n for i in 0..word.length-1\n\ttemp = word.dup\n\ttemp.slice!(i)\n\tdeletes.push(temp)\n end \n\n transposes = []\n #all strings obtained by switching two consecutive letters\n loop_count = word.length-2\n if loop_count > 0\n for i in 0..loop_count\n\ttemp = word.dup\n \ttemp[i+1] = word[i]\t\n\ttemp[i] = word[i+1]\n\ttransposes.push(temp)\n end\n end \n\n inserts = []\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n for i in 0..word.length\n ALPHABET.each_char do |c|\n temp = word.dup\n temp = temp.insert(i,c)\n inserts.push(temp)\n end\n end\n\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n for i in 0..word.length-1\n ALPHABET.each_char do |c|\n temp = word.dup\n temp[i] = c\n replaces.push(temp)\n end\n end\n\n return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end", "def edits1(word)\n \n deletes = []\n i = 0\n while i < word.length\n deletes_word = word\n deletes << deletes_word.slice(0,i) + deletes_word.slice(i+1, word.length)\n i+=1\n end\n #all strings obtained by deleting a letter (each letter)\n transposes = []\n i = 0\n while i < word.length\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n transpose_word[i] = transpose_word[i-1]\n transpose_word[i-1] = letter_to_replace\n transposes << transpose_word\n\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n if(transpose_word[i+1] != nil)\n transpose_word[i] = transpose_word[i+1]\n transpose_word[i+1] = letter_to_replace\n transposes << transpose_word\n end\n\n i+=1\n end\n #all strings obtained by switching two consecutive letters\n inserts = []\n word\n inserts(word)\n\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n\n #return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end", "def edits1(word)\n deletes = []\n letters = word.split(\"\")\n letters.each do |c|\n word2 = word\n deletes.push(word2.delete(c))\n end\n\n transposes = []\n for i in 0..word.length-1\n letters = word.split(\"\")\n letters2 = letters\n letters2.insert(i+1 , letters2.delete_at(i))\n transposes.push(letters2.join())\n end\n\n inserts = []\n ALPHABET.split(\"\").each do |c|\n for i in 0..word.length\n letters = word.split(\"\")\n letters2 = letters\n letters2.insert(i,c)\n inserts.push(letters2.join())\n end\n end\n\n replaces = []\n ALPHABET.split(\"\").each do |c|\n\tfor i in 0..word.length-1\n letters = word.split(\"\")\n letters2 = letters\n letters2.delete_at(i)\n letters2.insert(i,c)\n replaces.push(letters2.join())\n end\n end\n\n return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end", "def delete_endings(words)\n without_endings = []\n words.each do |word|\n without_endings << delete_ending(word)\n end\n\n without_endings\n end", "def del_let_words(current)\n output = []\n (0..(current.length-1)).each do |index|\n test_word = current.clone\n test_word[index] = \"\"\n output << test_word if legal_word?(test_word)\n end\n output\nend", "def custom_delete(string, delete_characters)\n output = \"\"\n string.each_char { |char| output << char unless delete_characters.include?(char) }\n output\nend", "def crunch(str)\n str.chars.map.with_index { |char, idx| char == str.chars[idx + 1] ? 'delete' : char }.select { |l| l unless l == 'delete' }.join\nend", "def custom_delete(string, chars)\n new_string = \"\"\n string.each_char do |letter|\n new_string << letter unless chars.include?(letter)\n end\n new_string\nend", "def variation_words word\n ( deletions(word) + transpositions(word) + replacements(word) + insertions(word) ).uniq\n end", "def my_array_deletion_method!(source, thing_to_delete)\n source.reject! {|word| word.to_s.rindex(thing_to_delete) != nil}\n return source\nend", "def custom_delete(string,delete_characters)\nnew_string = \"\"\nstring.each_char {|char| new_string << char unless delete_characters.include?(char)}\nnew_string\nend", "def my_array_deletion_method!(source, thing_to_delete)\n remove_letter = source.find_all { |letter| letter.to_s.include?(thing_to_delete)}\n\n remove_letter.each { |word| source.delete(word)}\n\n p source\nend", "def my_array_deletion_method(source, thing_to_delete)\n\tsource.each do |word| if word.to_s.split(\"\").include? thing_to_delete\n\t\tsource.delete word\n\tend\nend\n\t source \nend", "def my_array_deletion_method!(source, thing_to_delete)\n source.each {|word| remove_word = word.to_s\n if remove_word.include?(thing_to_delete) == true\n source.delete(string)\n p source\n end\n }\nend", "def deletions\n commit_summary(:deletions)\n end", "def deletions\n Array(@gapi.deletions).map { |gapi| Record.from_gapi gapi }\n end", "def deletions\n stat[1]\n end", "def word_combos(word)\n\t\tword = word.chars.to_a\n\t\tall_word_combo = []\n\t\ti = 1\n\t\twhile i <= word.size\n\t\t\tall_word_combo << word.permutation(i).to_a\n\t\t\ti+=1\n\t\tend\n\t\treturn all_word_combo\n\tend", "def my_array_deletion_method!(source, thing_to_delete)\n source.each do |substring|\n if substring.class == thing_to_delete.class && substring.include?(thing_to_delete) == true\n source.delete(substring)\n end\n end\n return source\n end", "def dedupe(words)\n words.select do |word|\n word.downcase != @word.downcase \n end\n end", "def remove_vowels(words)\n words.map { |word| word.delete \"aeiouAEIOU\" }\nend", "def word_unscrambler(str, words)\n str = str.split('').sort.join('')\n possible = []\n words.map do |word|\n sort_word = word.split('').sort.join('')\n possible << word if word_c == str\n end\n return possible\nend", "def delete_special_chars(entries)\n entries.each { |entry|\n entry.delete(\"(),\")\n }\n return entries\n end", "def non_opt_words(current)\n output = []\n (0..(current.length-1)).each do |index|\n ('a'..'z').each do |let|\n test_word = current.clone\n test_word[index] = let\n output << test_word if legal_word?(test_word)\n end\n end\n output.uniq\nend", "def remove_letter_a(words)\n new_words = []\n words.each do |word|\n without_a = \"\"\n word.each_char do |c|\n if c != 'a'\n without_a << c\n end\n end\n new_words << without_a\n end\n new_words\nend", "def my_array_deletion_method!(i_want_pets, letter)\n i_want_pets.delete_if { |item| item.to_s.include?(letter) }\nend", "def remove_vowels(array)\n array.map {|word| word.delete(\"aeiou\")}\nend" ]
[ "0.7490376", "0.619651", "0.60171515", "0.5990503", "0.5848276", "0.57351094", "0.5698404", "0.56940633", "0.5631374", "0.56178415", "0.56170607", "0.5608425", "0.5603442", "0.56017447", "0.5586035", "0.55252427", "0.5476506", "0.5419113", "0.5369865", "0.5363532", "0.53633994", "0.5310942", "0.5284109", "0.527557", "0.52025753", "0.51780105", "0.51682466", "0.5156779", "0.5156555", "0.51521045" ]
0.7776573
0
Returns all combinations of the word with adjacent words transposed. Example: transpositions("word") => ["owrd", "wrod", "wodr"]
def transpositions new_words = [] @words.each do |word| @word = word || '' new_words += (0..length-1).map { |i| "#{@word[0...i]}#{@word[i+1, 1]}#{@word[i,1]}#{@word[i+2..-1]}" } end new_words end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def transpositions word\n n = word.length\n (0...n-1).collect {|i| word[0...i]+word[i+1,1]+word[i,1]+word[i+2..-1] }\n end", "def transposition\n (0...length-1).map { |i|\n string[0...i] +\n string[i+1, 1] +\n string[i,1] +\n string[i+2..-1]\n }.uniq\n end", "def word_combos(word)\n\t\tword = word.chars.to_a\n\t\tall_word_combo = []\n\t\ti = 1\n\t\twhile i <= word.size\n\t\t\tall_word_combo << word.permutation(i).to_a\n\t\t\ti+=1\n\t\tend\n\t\treturn all_word_combo\n\tend", "def transpose(ciphertexts)\n max = ciphertexts.max_by(&:size).size # The maximum (and necessarily common) column size is that of the lengthiest ciphertext.\n ciphertexts.map { |c| c.chars.values_at(0...max) }.transpose.map(&:join)\nend", "def simple_transposition(text)\n array = text.split('')\n even = array.values_at(* array.each_index.select {|i| i.even?})\n odd = array.values_at(* array.each_index.select {|i| i.odd?})\n\n return even.join('') + odd.join('')\nend", "def permutations(string)\n string.chars.permutation.to_a.map(&:join).uniq\nend", "def permute(words)\n return nil if words.nil?\n return [] if words.empty?\n\n pwords = []\n words.each do |w|\n list = w.chars.to_a.permutation.map(&:join)\n pwords.concat list\n end\n pwords\n end", "def lets_premute_even_more(array)\n i = 0\n output_array = []\n\n while i < array.length\n first_letter = array[i]\n j = 0\n while j < array.length\n if i == j\n else\n second_letter = array[j]\n combo = first_letter + second_letter\n output_array << combo\n end\n j += 1\n end\n i += 1\n end\n return output_array\nend", "def lexical_combinations(strings)\n l = []\n if strings.length == 1\n l.add(strings)\n else\n strings.each do |letter|\n others = strings.except(letter)\n lexical_combinations(others).each do |subcombo|\n l.add([letter] + subcombo)\n l.add([letter + subcombo.first] + subcombo.butfirst)\n end\n end\n end\n l\nend", "def my_transpose\n transposed = []\n\n i = 0\n until transposed.length == length\n current = []\n self.each do |arr|\n current << arr[i]\n end\n i += 1\n transposed << current\n end\n\n transposed\n end", "def swap(sentence)\n final = []\n reversed_copy_array = sentence.dup.split.map(&:reverse)\n sentence_array = sentence.split\n zipped = sentence_array.zip(reversed_copy_array)\n zipped.each do |word_set|\n word_set[0][0] = word_set[1][0]\n word_set[0][-1] = word_set[1][-1]\n end\n zipped.each { |word_set| final << word_set[0] }\n final.join(' ')\nend", "def permutations(string)\n string.chars.permutation(string.length).map(&:join).uniq\nend", "def permutations(string)\n string.chars.permutation(string.length).to_a.map { |arr| arr.join }.uniq\nend", "def transpose(array)\n return [] if array.empty?\n result = []\n array.first.length.times do |i|\n array.each_with_index do |inner, inner_index|\n result[i] ||= []\n result[i] << array[inner_index][i]\n end\n end\n result\nend", "def every_possible_pairing_of_word(arr)\n i1 = arr\n i2 = []\n i1.combination(2).to_a\nend", "def list_of_combinations(word) \n word = word.split(\"\")\n wordlist = []\n\n index1 = 0\n index2 = 1\n\n loop do \n combination = word[index1..index2].join(\"\")\n wordlist << combination\n index2 += 1\n if index2 >= word.length\n index1 += 1\n index2 = index1 + 1\n end\n\n if index1 >= word.length-1\n break\n end\n \n end\n wordlist\nend", "def possibilities(words)\n words.each do |word, translations|\n sorted = translations.sort\n words[word] = sorted.each_index.map {|i|\n sorted.combination(i+1).to_a\n }.flatten(1).sort\n end\nend", "def transpose(string)\n arr = string.split(//)\n new_arr = ''\n\n i = 0\n while i < string.length\n if arr[i] == 'n' && arr[i - 1] == 'g'\n arr[i], arr[i - 1] = arr[i - 1], arr[i]\n i -= 2\n end\n i += 1\n end\n\n arr.each { |n| new_arr += n }\n new_arr\nend", "def pairs\n letters = split('')\n pairs = []\n letters.each.with_index do |letter, i|\n next_letter = letters[i + 1]\n pairs << letter + next_letter unless next_letter.nil?\n end\n pairs\n end", "def all_traversals(word)\n length = word.length\n results = []\n\n results << row_up(length)\n results << up_right(length)\n results << col_right(length)\n results << down_right(length)\n results << row_down(length)\n results << down_left(length)\n results << col_left(length)\n results << up_left(length)\n\n results\n end", "def getPermutations(s)\n result = []\n for i in 0..2\n substring = s[1..2]\n result.push(s[0] + substring)\n result.push(s[0] + substring.reverse)\n s = rotateChar(s)\n end\n\n return result\nend", "def combinations(arr)\n res = []\n i = arr.length\n arr.each {|el|tem = [],ind= arr.index(el), (i-ind).times {i =ind, tem.push(el),tem.push(arr[i -= 1]) }}\nend", "def transpose(text)\n\n words = text.split(\"\\n\")\n words.shift # remove the starting number \n\n maxlen = words.map { |w| w.length }.max\n\n for i in 0..maxlen - 1 do\n\n line = \"\"\n words.each do |w|\n line << (w[i].nil? ? \" \" : w[i])\n end\n\n puts line\n end\n\n\nend", "def find_adjacent_words(word)\n alphabet = ('a'..'z').to_a\n all_adjacent_words = []\n\n word.each_char.with_index do |char, i|\n alphabet.each do |alpha_letter|\n dup_word = word.dup\n dup_word[i] = alpha_letter\n all_adjacent_words << dup_word if @dictionary.include?(dup_word)\n end\n end\n\n all_adjacent_words.uniq \n end", "def my_transpose\n ret = []\n i=0\n while i < self.length\n j=0\n ret2 = []\n while j < self[i].length\n ret2 << self[j][i]\n j += 1\n end\n ret << ret2\n i += 1\n end\n ret\n end", "def get_transpose()\n transpose_graph = Graph.new(26)\n\n for i in 0..@number_of_vertices -1 do\n @adjacent_list[i].each do |x|\n transpose_graph.add_edge(x, i)\n end\n end\n\n transpose_graph\n end", "def reverse_and_combine_text(s)\n words = s.split\n return s if words.length.eql?(1) \n current_words = []\n \n loop do\n last_word = ''\n \n words.map! do |word|\n word.reverse!\n end\n \n last_word = words.pop if words.length.odd?\n \n words.each_with_index do|word, index|\n current_words << word + words[index + 1] if index.even?\n end\n \n current_words << last_word if last_word != ''\n \n break if current_words.length == 1\n \n words = current_words\n current_words = []\n end\n \n current_words\nend", "def my_transpose(matrix)\n #algorithm\n for i in 0...matrix[0].length\n for j in (i + 1)...matrix[0].length\n temp = matrix[i][j]\n matrix[i][j] = matrix[j][i]\n matrix[j][i] = temp\n end\n end\n\n #printer\n for k in (0..(matrix[0].length-1))\n puts matrix[k].join(\" \")\n end\n matrix\nend", "def transpose() end", "def permutations(head, tail='', depth=0)\n letters = head.split('').length\n if letters < 1\n tail\n else\n (0...letters).map do |iteration|\n temp_string = head.dup\n swap_char = temp_string.slice! iteration\n permutations(temp_string, \"#{tail}#{swap_char}\", depth+1)\n end.flatten.uniq\n end\nend" ]
[ "0.8267741", "0.7397717", "0.6632626", "0.6508019", "0.61694956", "0.61275923", "0.61016613", "0.6075012", "0.6048928", "0.599702", "0.59396076", "0.5878923", "0.5876813", "0.5856411", "0.5843049", "0.5809472", "0.57698923", "0.57686734", "0.57664835", "0.56898916", "0.56835216", "0.5671341", "0.5652491", "0.56332356", "0.55991113", "0.55910057", "0.5586866", "0.55839247", "0.5560185", "0.5559925" ]
0.78448904
1
Returns all variations of the word with each character replaced by all characters from 'a' to 'z'. Example: replacements("word") => ["aord", "bord", "cord", ... "ward", "wbrd" ...]
def replacements new_words = [] @words.each do |word| @word = word || '' length.times do |i| ('a'..'z').each { |c| new_words << "#{@word[0...i]}#{c}#{@word[i+1..-1]}" } end end new_words end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def replacements word\n n = word.length\n new_words = []\n n.times {|i| ('a'..'z').each {|l| new_words << word[0...i]+l.chr+word[i+1..-1] } }\n new_words\n end", "def apply_replacements(word)\n @replacements.each do |pattern, target|\n word.gsub!(pattern, target)\n end\n \n word\n end", "def gsubs(replacements)\n str = self.dup\n replacements.each do |r|\n str = str.gsub(r[0],r[1])\n end\n str\n end", "def replacements; end", "def consonants_adv(str)\r\n str = vowel_adv(str)\r\n consonants = [\"b\", \"c\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \"m\", \"n\", \"p\", \"q\", \"r\", \"s\", \"t\", \"v\", \"w\", \"x\", \"y\", \"z\"]\r\n str = str.downcase\r\n str = str.split('')\r\n str_new = str.map do |char|\r\n if consonants.include?(char)\r\n consonants.rotate(1)[consonants.index(char)]\r\n else\r\n char\r\n end\r\n end\r\n str_new.join\r\nend", "def edits1(word)\n \n deletes = []\n i = 0\n while i < word.length\n deletes_word = word\n deletes << deletes_word.slice(0,i) + deletes_word.slice(i+1, word.length)\n i+=1\n end\n #all strings obtained by deleting a letter (each letter)\n transposes = []\n i = 0\n while i < word.length\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n transpose_word[i] = transpose_word[i-1]\n transpose_word[i-1] = letter_to_replace\n transposes << transpose_word\n\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n if(transpose_word[i+1] != nil)\n transpose_word[i] = transpose_word[i+1]\n transpose_word[i+1] = letter_to_replace\n transposes << transpose_word\n end\n\n i+=1\n end\n #all strings obtained by switching two consecutive letters\n inserts = []\n word\n inserts(word)\n\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n\n #return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end", "def alteration\n (0...length).flat_map { |i|\n LETTERS.map { |letter|\n string.dup.tap { |w| w[i] = letter }\n }\n }.uniq\n end", "def edits1(word) \n deletes = [] \n #all strings obtained by deleting a letter (each letter) \n for i in 0..word.length-1\n\ttemp = word.dup\n\ttemp.slice!(i)\n\tdeletes.push(temp)\n end \n\n transposes = []\n #all strings obtained by switching two consecutive letters\n loop_count = word.length-2\n if loop_count > 0\n for i in 0..loop_count\n\ttemp = word.dup\n \ttemp[i+1] = word[i]\t\n\ttemp[i] = word[i+1]\n\ttransposes.push(temp)\n end\n end \n\n inserts = []\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n for i in 0..word.length\n ALPHABET.each_char do |c|\n temp = word.dup\n temp = temp.insert(i,c)\n inserts.push(temp)\n end\n end\n\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n for i in 0..word.length-1\n ALPHABET.each_char do |c|\n temp = word.dup\n temp[i] = c\n replaces.push(temp)\n end\n end\n\n return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end", "def reverse_each_word(string_sentence)\n array = string_sentence.split\n in_place_reverse_string_sentence = []\n array.collect do |element|\n in_place_reverse_string_sentence << element.reverse \n end\n in_place_reverse_string_sentence.join(\" \")\nend", "def vogal(str)\n vogals = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n cons = [\"b\", \"c\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \"m\", \"n\", \"p\", \"q\", \"r\", \"s\", \"t\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n# splitting the string given into arrays \n str = str.chars\n str_new = str.map do |char|\n#looping the string into the next letter\n if vogals.include?(char)\n vogals.rotate(1)[vogals.index(char)]\n else cons.include?(char)\n cons.rotate(1)[cons.index(char)]\n end\n end\n#joining the strings back\n str_new.join\nend", "def alias_generator(name)\n\nname = name.downcase\n\nvowels_lowcase = %w(a e i o u)\nvowels = vowels_lowcase\nconsonants_lowcase = (\"a\"..\"z\").to_a - vowels\nconsonants = consonants_lowcase\n\n# original = (vowels + consonants)\n# new_letters = (vowels.rotate + consonants.rotate)\n\nname_array = name.split\nname_reverse = name_array.reverse\n\nname_reverse.map! do |word|\n word_split = word.split(\"\")\n # name_reverse[1].split(\"\")\n\n word_split.map! do |letter|\n if vowels.include? letter\n index = vowels.index(letter)\n if letter == vowels.last\n letter = vowels.first\n else\n letter = vowels[index + 1]\n end\n else\n index = consonants.index(letter)\n if letter == consonants.last\n letter = consonants.first\n else\n letter = consonants[index + 1]\n end\n end\n end\n\n word_split[0] = word_split[0].upcase\n word_split.join('')\nend\n\nname_reverse.join(' ')\n# # p name_reverse.tr(original,new_letters)\n\n\n\nend", "def swap_letters(sentence, letters)\n # your code goes here\n result = []\n\n l1, l2= letters[0], letters[1]\n sentence.split.each do |word|\n temp = \"\"\n word.chars.each do |ch|\n if ch == l1 || ch == l1.downcase\n ch = l2\n elsif ch == l2 || ch.downcase == l2\n ch = l1.downcase\n end\n temp << ch\n end\n result << temp\n end\n\n result.join(\" \")\nend", "def consonant_swap (secret_name)\n\t\n\tsecret_name.map do |letters|\n\t\t\n\t\tif letters == \" \"\n\t\t\tletters\n\t\telsif letters == \"z\"\n\t\t\tletters.gsub!(/[z]/, \"a\")\n\t\telsif letters =~ /[aeiou]/\n\t\t\tletters\n\t\telse \n\t\t\tletters.next!\n\t\t\tif letters =~ /[aeiou]/\n\t\t\t\tletters.next!\n\t\t\tend\n\t\tend\n\n\tend\n\tsecret_name\nend", "def replace_correct_letters\n result = @secret_word\n @secret_word.split('').each do |letter|\n unless @characters_guessed_correctly.include? letter\n result = result.gsub(letter, '_')\n end\n end\n @word_guessed = result\n result\n end", "def variation_words word\n ( deletions(word) + transpositions(word) + replacements(word) + insertions(word) ).uniq\n end", "def swap_letters(sentence, letters)\n letters.map! { |letter| letter.downcase }\n new_str = \"\"\n sentence.each_char do |ch|\n char = ch.downcase\n if char.include?(letters[0])\n new_str << letters[1]\n elsif char.include?(letters[1])\n new_str << letters[0]\n else\n new_str << ch\n end\n end\n new_str\nend", "def letter_changes(string)\n array = (\"a\"..\"z\").to_a\n\n result_array = string.chars.map do |char|\n case\n when char.downcase == \"x\" then char == \"x\" ? \"a\" : \"A\"\n when char.downcase == \"y\" then char == \"y\" ? \"b\" : \"B\"\n when char.downcase == \"z\" then char == \"z\" ? \"c\" : \"C\"\n when char.match(/[a-z]/) then array[array.index(char.downcase) + 3]\n when char.match(/[A-Z]/) then array[array.index(char.downcase) + 3].upcase\n else char\n end\n end\n result_array.join\nend", "def replaces\n @replaces ||= []\n end", "def replaces\n @replaces ||= []\n end", "def word_substituter(string)\n# dictionary.has_key(\"hello\") == true\n replace= []\n \n replace << string.split.each do |word| \n if dictionary.has_key?(\"#{word}\") == true\n word.replace(dictionary[\"#{word}\"])\n else word\n \n end\n \n end \n replace.flatten.join(\" \")\nend", "def reversify(string)\n rev = []\n\n string.scan(/\\w/).each do |letter|\n rev.insert(0, letter)\n end\n\n puts rev.join\nend", "def insertions\n new_words = []\n @words.each do |word|\n @word = word || '' \n (length + 1).times do |i|\n ('a'..'z').each { |c| new_words << \"#{@word[0...i]}#{c}#{@word[i..-1]}\" }\n end\n end\n new_words\n end", "def insertions word\n n = word.length\n new_words = []\n (n+1).times {|i| ('a'..'z').each {|l| new_words << word[0...i]+l.chr+word[i..-1] } }\n new_words\n end", "def danish(text)\n p text.sub(/\\b(apple|cherry|blueberry)\\b/, 'danish')\nend", "def include_char_variants(world)\n keys = CHAR_VARIANTS.keys.join\n world.downcase.gsub(/[#{keys}]/, CHAR_VARIANTS)\n end", "def reverse_each_word(string)\n helper_array = []\n string_to_array = string.split\n string_to_array.collect do |letter|\n helper_array.push letter.reverse!\n end\n return helper_array.join(\" \")\nend", "def swap(string)\n string_arr = string.split.map do |word|\n first_letter = word[0]\n word = word.gsub(word[0], word[-1])\n word[-1] = first_letter\n word\n end\n string_arr.join(' ')\nend", "def LetterChanges(str)\n new_string = []\n str = str.split(\" \")\n str.each do |word|\n new_string << word_changes(word)\n end\n new_string.join(\" \")\nend", "def as_replacements; end", "def as_replacements; end" ]
[ "0.7423698", "0.6480573", "0.6356044", "0.604883", "0.5664484", "0.5593338", "0.5590618", "0.5556752", "0.5411977", "0.5401827", "0.53972244", "0.53919774", "0.53823835", "0.53780484", "0.53479666", "0.5343286", "0.53395075", "0.53225756", "0.53225756", "0.53219646", "0.5296954", "0.52436805", "0.5243119", "0.5236569", "0.52334917", "0.52041066", "0.5192373", "0.5178467", "0.5167356", "0.5167356" ]
0.7883035
0
Returns all variations of the word with an alphabet inserted between the characters. Example: insertions("word") => ["aword", "bword", "cword" ... "waord", "wbord" ... ]
def insertions new_words = [] @words.each do |word| @word = word || '' (length + 1).times do |i| ('a'..'z').each { |c| new_words << "#{@word[0...i]}#{c}#{@word[i..-1]}" } end end new_words end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def insertions word\n n = word.length\n new_words = []\n (n+1).times {|i| ('a'..'z').each {|l| new_words << word[0...i]+l.chr+word[i..-1] } }\n new_words\n end", "def insertion\n return [] if string.empty?\n (0..length).flat_map { |i|\n LETTERS.map { |letter|\n string[0...i] + letter + string[i..-1]\n }\n }\n end", "def insert_char(word, insertion)\n new_words = []\n (word.length + 1).times do |index|\n word_dup = word.dup\n new_words << word_dup.insert(index, insertion)\n end\n new_words\nend", "def replacements\n new_words = []\n @words.each do |word|\n @word = word || '' \n length.times do |i|\n ('a'..'z').each { |c| new_words << \"#{@word[0...i]}#{c}#{@word[i+1..-1]}\" }\n end\n end\n new_words\n end", "def letters_before(character)\n\t\n\t alphabet_storage = []\n results = []\n \n (\"a\"..\"z\").each do |i|\n \t alphabet_storage << i\n end\n \n starting_position = alphabet_storage.index(character) \n i = 0\n \n until i == starting_position\n results << alphabet_storage[i]\n i += 1\n end\n \n puts \"#{results}\"\nend", "def variation_words word\n ( deletions(word) + transpositions(word) + replacements(word) + insertions(word) ).uniq\n end", "def replacements word\n n = word.length\n new_words = []\n n.times {|i| ('a'..'z').each {|l| new_words << word[0...i]+l.chr+word[i+1..-1] } }\n new_words\n end", "def get_all_letters_in_array_of_words(array)\n #go through each word\n new_array = []\n array.each {|word|\n new_array << word.split(//)\n }\n new_array.flatten.sort\n #separate each letter and add to new array of letters - .split(//)\n #take all letters and sort for alphabet\nend", "def edits1(word) \n deletes = [] \n #all strings obtained by deleting a letter (each letter) \n for i in 0..word.length-1\n\ttemp = word.dup\n\ttemp.slice!(i)\n\tdeletes.push(temp)\n end \n\n transposes = []\n #all strings obtained by switching two consecutive letters\n loop_count = word.length-2\n if loop_count > 0\n for i in 0..loop_count\n\ttemp = word.dup\n \ttemp[i+1] = word[i]\t\n\ttemp[i] = word[i+1]\n\ttransposes.push(temp)\n end\n end \n\n inserts = []\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n for i in 0..word.length\n ALPHABET.each_char do |c|\n temp = word.dup\n temp = temp.insert(i,c)\n inserts.push(temp)\n end\n end\n\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n for i in 0..word.length-1\n ALPHABET.each_char do |c|\n temp = word.dup\n temp[i] = c\n replaces.push(temp)\n end\n end\n\n return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end", "def letters\n the_letters = []\n letter_regex = /[a-z]/i\n chars.each do |character|\n the_letters << character if character.match(letter_regex)\n end\n the_letters.join\n end", "def edits1(word)\n \n deletes = []\n i = 0\n while i < word.length\n deletes_word = word\n deletes << deletes_word.slice(0,i) + deletes_word.slice(i+1, word.length)\n i+=1\n end\n #all strings obtained by deleting a letter (each letter)\n transposes = []\n i = 0\n while i < word.length\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n transpose_word[i] = transpose_word[i-1]\n transpose_word[i-1] = letter_to_replace\n transposes << transpose_word\n\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n if(transpose_word[i+1] != nil)\n transpose_word[i] = transpose_word[i+1]\n transpose_word[i+1] = letter_to_replace\n transposes << transpose_word\n end\n\n i+=1\n end\n #all strings obtained by switching two consecutive letters\n inserts = []\n word\n inserts(word)\n\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n\n #return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end", "def pig_latin_name(word)\n \n letters = word.split(\"\")\n \n final_array = letters.clone\n letters.each do |letter| #[p, l, u, m]\n \n \n if is_consonants?(letter)\n final_array.rotate! \n # #puts \".........#{removed_consonant}\"\n # #letters.push(removed_consonant)\n # puts \".........#{final_array}..#{letters}\"\n else \n # puts \"*****#{final_array}.... #{letters}\"\n final_array.push(\"ay\")\n return final_array.join\n end\n end\nend", "def get_all_letters_in_array_of_words(array)\n\tn =['cat', 'dog', 'fish']\n\tcharacters = n.map { | animal | animal.chars }\n\tcharacters.flatten.sort\nend", "def pig_it text\n arr = []\n text.split.map do |x|\n split_word = x.split('')\n unless /[[:punct:]]/.match(x)\n first_letter = split_word.first\n split_word.shift\n split_word << \"#{first_letter + 'ay'}\"\n end\n arr << split_word.join\n end\n arr.join(' ')\nend", "def ordered_letters\n @word.chars.sort.join\n end", "def toonify (accent, sentence)\n new_sentence = []\n if accent == 'daffy'\n sentence.split('').each do |character|\n if character == 's'\n new_sentence.push 'th'\n else\n new_sentence.push character\n end\n end\n elsif accent == 'elmer'\n sentence.split('').each do |character|\n if character == 'r'\n new_sentence.push 'w'\n else\n new_sentence.push character\n end\n end\n end\n puts new_sentence.join\nend", "def alteration\n (0...length).flat_map { |i|\n LETTERS.map { |letter|\n string.dup.tap { |w| w[i] = letter }\n }\n }.uniq\n end", "def non_opt_words(current)\n output = []\n (0..(current.length-1)).each do |index|\n ('a'..'z').each do |let|\n test_word = current.clone\n test_word[index] = let\n output << test_word if legal_word?(test_word)\n end\n end\n output.uniq\nend", "def initial_consonants\n \n @@sentence.map { |word|\n if word.start_with?('a','e','i','o','u','A','E','I','O','U') \n \"\" \n else \n consonant_blend = word.split /([aeiou].*)/\n consonant_blend[0]\n\n end\n }\n end", "def insert_words(words)\n words.each do |word|\n insert(word)\n end\n end", "def hipsterfy(str)\n finalArray = []\n alphabet = (\"a\"..\"z\").to_a\n wordArray = str.split(\" \")\n wordArray.each do |word|\n firstSeen = false\n reversed = word.split(\"\").reverse\n finalWord = []\n reversed.each do |letter|\n if firstSeen == true || letter != \"a\" && letter != \"e\" && letter != \"i\" && letter != \"o\" && letter != \"u\"\n finalWord.push(letter)\n\n elsif firstSeen == false && letter == \"a\" || letter == \"e\" || letter == \"i\" || letter == \"o\" || letter == \"u\"\n # don't add here\n firstSeen = true\n end\n end\n \n newString = \"\"\n finalWord.reverse.each do |element|\n newString += String(element)\n end\n finalArray.push(newString)\n \n end\n \n \n \n # print finalArray\n finalString = \"\"\n \n finalArray.each_with_index do |word, index|\n if index != finalArray.length - 1\n finalString += word + \" \"\n else\n finalString += word\n end\n end\n \n \n \n \n \n \n return finalString\n \n \n\n \nend", "def pig_it(string)\n words = string.split\n\n words.map do |word|\n if word.match(/[a-z]/i)\n word[1..word.size] << word[0] << 'ay'\n else\n word\n end\n end.join(' ')\nend", "def get_all_letters_in_array_of_words(array)\n array.join.split('').sort\nend", "def find_adjacent_words(word)\n alphabet = ('a'..'z').to_a\n all_adjacent_words = []\n\n word.each_char.with_index do |char, i|\n alphabet.each do |alpha_letter|\n dup_word = word.dup\n dup_word[i] = alpha_letter\n all_adjacent_words << dup_word if @dictionary.include?(dup_word)\n end\n end\n\n all_adjacent_words.uniq \n end", "def get_all_letters_in_array_of_words(array)\n array.join.split(\"\").sort \nend", "def nato(word)\n original = []\n value = ''\n letters = {\n \"A\"=> \"Alpha\", \"B\"=> \"Bravo\", \"C\"=> \"Charlie\",\n \"D\"=> \"Delta\", \"E\"=> \"Echo\", \"F\"=> \"Foxtrot\",\n \"G\"=> \"Golf\", \"H\"=> \"Hotel\", \"I\"=> \"India\",\n \"J\"=> \"Juliett\",\"K\"=> \"Kilo\", \"L\"=> \"Lima\",\n \"M\"=> \"Mike\", \"N\"=> \"November\",\"O\"=> \"Oscar\",\n \"P\"=> \"Papa\", \"Q\"=> \"Quebec\", \"R\"=> \"Romeo\",\n \"S\"=> \"Sierra\", \"T\"=> \"Tango\", \"U\"=> \"Uniform\",\n \"V\"=> \"Victor\", \"W\"=> \"Whiskey\", \"X\"=> \"X-ray\",\n \"Y\"=> \"Yankee\", \"Z\"=> \"Zulu\"\n }\n arr = word.split('')\n arr.each do |letter|\n value = letters.values_at(letter.upcase)\n original.concat(value)\n end\n original.join(' ')\nend", "def pig_it(sentence)\n sentence.split.map do |word|\n if ('a'..'z').cover?(word.downcase)\n word[1..-1] + word[0] + 'ay'\n else\n word\n end\n end.join(' ')\nend", "def depunctuate(a_string)\n alphabet = [*\"A\"..\"Z\"] + [*\"a\"..\"z\"]\n result = \"\"\n a_string.length.times do |i|\n if alphabet.include?(a_string[i])\n result << a_string[i]\n end\n end\n result\nend", "def reversify(string)\n rev = []\n\n string.scan(/\\w/).each do |letter|\n rev.insert(0, letter)\n end\n\n puts rev.join\nend", "def guess_letters\n guess_array = []\n @current_word.each do\n guess_array << \"_\"\n end\n return guess_array\n end" ]
[ "0.755778", "0.6944533", "0.67156076", "0.62503517", "0.6208298", "0.6174087", "0.60542214", "0.5999374", "0.5925905", "0.58746487", "0.5863773", "0.58560246", "0.5843401", "0.5818282", "0.58039254", "0.57870734", "0.57762617", "0.5768799", "0.5749283", "0.57256037", "0.5714648", "0.5703904", "0.57032377", "0.5700571", "0.5684878", "0.56832993", "0.5680604", "0.5677341", "0.5659242", "0.56553435" ]
0.78312457
0
Indicate a method to call before every wrapped method.
def before_method(method) @@before_methods << method @@wrap_exclusions << method.to_sym # This method will not be wrapped. end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def before(klass, meth_name, &block)\n intercept(klass, meth_name, :before, &block)\n end", "def before(method_to_hook, method_to_call = nil, options = {}, &block)\n add(:before, method_to_hook, method_to_call, options, &block)\n end", "def _hook_before_method(method, hook, opts = {})\n return false if method == hook\n _add_hooked_method(:before, hook, method)\n original = instance_method(method)\n @_defining_hook = true\n define_method(method) do |*args, &block|\n if opts[:send_args] || opts[:send_arg] || opts[:modify_args] || opts[:send_method] || opts[:try_first]\n margs = args\n margs = [method] + args if opts[:send_method]\n margs = args + [opts[:add_args]].flatten(1) if opts[:add_args]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(*margs)\n return result if result && opts[:try_first]\n args = result if opts[:modify_args]\n else\n hook.is_a?(Proc) ? hook.call : method(hook).call\n end\n original.bind(self).call(*args, &block)\n end\n @_defining_hook = false\n true\n end", "def method_missing(method_name, *args)\n (args && args.size > 0) ? super(method_name, *args) : before_method(method_name)\n end", "def execute_before(method_to_hook, instance)\n execute(:before, method_to_hook, instance)\n end", "def before_method name, &block\n original_method = instance_method name\n _redefine_method name do |*args|\n instance_exec *args, &block\n original_method.bind(self).call *args\n end\n end", "def __run_before_wrappers(wrappers, method_name, args, high_arity = false)\n wrappers.each do |wrapper|\n next unless wrapper.respond_to?(method_name)\n\n args = if high_arity\n wrapper.public_send(method_name, *args)\n else\n wrapper.public_send(method_name, args)\n end\n end\n args\n end", "def before_hook(method_name)\n hooks << method_name\n end", "def method_missing(method, *args, &block)\n\t\t@self_before_instance_eval.send method, *args, &block\n\t end", "def before_method(method)\n @liquor[method.to_s]\n end", "def before(&proc)\n @before = proc if proc\n @before\n end", "def before_methods\n @@before_methods\n end", "def before_hook\n return unless before\n\n Logger.info \"Before Hook Starting...\"\n before.call\n Logger.info \"Before Hook Finished.\"\n rescue Exception => err\n @before_hook_failed = true\n ex = err.is_a?(StandardError) ? Error : FatalError\n raise ex.wrap(err, \"Before Hook Failed!\")\n end", "def before_execution(method_name)\n end", "def before(&block)\n define_before_or_after_method_with_block(:before, &block)\n end", "def preOrder(instruction)\n @orderMethods.preOrder(instruction)\n end", "def before *a, &b; valid_in_context Event; define_hook :before, *a, &b; end", "def def_roda_before\n meths = private_instance_methods.grep(/\\A_roda_before_\\d\\d/).sort\n unless meths.empty?\n plugin :_before_hook unless private_method_defined?(:_roda_before)\n if meths.length == 1\n class_eval(\"alias _roda_before #{meths.first}\", __FILE__, __LINE__)\n else\n class_eval(\"def _roda_before; #{meths.join(';')} end\", __FILE__, __LINE__)\n end\n private :_roda_before\n alias_method :_roda_before, :_roda_before\n end\n end", "def prepend_before(*args, &proc)\n add_callback(:prepend_before, *args, &proc)\n end", "def before(*args, &block)\n if block_given?\n Thread.current[:before_hook] = block\n else\n Thread.current[:before_hook].call(*args) if Thread.current[:before_hook]\n end\n end", "def Before(&proc)\n (@before_procs ||= []) << proc\n end", "def before(observation, &block)\n build_methods(:before, observation, &block)\n end", "def before(&block)\n @before << block\n end", "def after_method(method)\n @@after_methods << method\n @@wrap_exclusions << method.to_sym # This method will not be wrapped.\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def before(*matches, &procedure)\n @_testcase.advice[:before][matches] = procedure\n end", "def hook!(method_to_hook)\n hooked_method = hooked_method(method_to_hook)\n original_method = original_method(method_to_hook)\n line = __LINE__; alias_these_hooks = <<-hooks\n alias :#{original_method} :#{method_to_hook}\n def #{hooked_method}(*args)\n Hook.for(self.class).execute_before(:#{method_to_hook}, self)\n result = #{original_method}(*args)\n Hook.for(self.class).execute_after(:#{method_to_hook}, self)\n result\n end\n alias :#{method_to_hook} :#{hooked_method}\n hooks\n klass.class_eval alias_these_hooks, __FILE__, line.succ\n end", "def entering_wrap_method\n @@inside_methods += 1\n end", "def before_enqueue(method_name = nil, &block)\n Karafka.logger.debug(\"Defining before_enqueue filter with #{block}\")\n set_callback :call, :before, method_name ? method_name : block\n end", "def before(&block)\n handle(0, &block)\n end" ]
[ "0.75851417", "0.7422467", "0.73281455", "0.7302582", "0.71154374", "0.70430243", "0.7022979", "0.70028275", "0.6848234", "0.68225724", "0.67861617", "0.66953087", "0.6605023", "0.65922606", "0.65420854", "0.6508723", "0.64814585", "0.647363", "0.6449019", "0.6447024", "0.6422221", "0.6327544", "0.62861323", "0.625515", "0.62368184", "0.6221834", "0.6221188", "0.62196535", "0.6196018", "0.6194172" ]
0.78987837
0
Indicate a method to call after every wrapped method.
def after_method(method) @@after_methods << method @@wrap_exclusions << method.to_sym # This method will not be wrapped. end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def after(klass, meth_name, &block)\n intercept(klass, meth_name, :after, &block)\n end", "def after(method_to_hook, method_to_call = nil, options = {}, &block)\n add(:after, method_to_hook, method_to_call, options, &block)\n end", "def after_execution(method_name)\n end", "def execute_after(method_to_hook, instance)\n execute(:after, method_to_hook, instance)\n end", "def after(*method_symbols, &block)\n options = method_symbols[-1].kind_of?(Hash) ? method_symbols.pop : {}\n method_symbols.each do |method_sym|\n __composed_methods__[method_sym].after.push(__unbound_method__(block, options[:name]))\n __rebuild_method__(method_sym)\n end\n end", "def __run_after_wrappers(wrappers, method_name, args, return_value, high_arity = false)\n wrappers.reverse_each do |wrapper|\n next unless wrapper.respond_to?(method_name)\n\n return_value = if high_arity\n wrapper.public_send(method_name, return_value, *args)\n else\n wrapper.public_send(method_name, return_value, args)\n end\n end\n return_value\n end", "def _hook_after_method(method, hook, opts = {})\n return false if method == hook\n _add_hooked_method(:after, hook, method)\n original = instance_method(method)\n @_defining_hook = true\n define_method(method) do |*args, &block|\n rtr = original.bind(self).call(*args, &block)\n if opts[:send_args]\n (hook.is_a?(Proc) ? hook : method(hook)).call(*args)\n elsif opts[:send_return] || opts[:send_value]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(rtr)\n rtr = result if opts[:modify_value] || opts[:modify_return]\n elsif opts[:send_return_ary] || opts[:send_value_ary]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(*rtr)\n rtr = result if opts[:modify_value] || opts[:modify_return]\n elsif opts[:send_all]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(args: args, value: rtr, method: method)\n else\n (hook.is_a?(Proc) ? hook : method(hook)).call\n end\n rtr\n end\n @_defining_hook = false\n true\n end", "def after_methods\n @@after_methods\n end", "def after(*args, &block)\n meths, advice, options = Aspects.resolve(self, args, block)\n \n for meth in meths\n advices! << [:after_method, meth, advice]\n end\n \n return self\n end", "def hook!(method_to_hook)\n hooked_method = hooked_method(method_to_hook)\n original_method = original_method(method_to_hook)\n line = __LINE__; alias_these_hooks = <<-hooks\n alias :#{original_method} :#{method_to_hook}\n def #{hooked_method}(*args)\n Hook.for(self.class).execute_before(:#{method_to_hook}, self)\n result = #{original_method}(*args)\n Hook.for(self.class).execute_after(:#{method_to_hook}, self)\n result\n end\n alias :#{method_to_hook} :#{hooked_method}\n hooks\n klass.class_eval alias_these_hooks, __FILE__, line.succ\n end", "def def_roda_after\n meths = private_instance_methods.grep(/\\A_roda_after_\\d\\d/).sort\n unless meths.empty?\n plugin :error_handler unless private_method_defined?(:_roda_after)\n if meths.length == 1\n class_eval(\"alias _roda_after #{meths.first}\", __FILE__, __LINE__)\n else\n class_eval(\"def _roda_after(res); #{meths.map{|s| \"#{s}(res)\"}.join(';')} end\", __FILE__, __LINE__)\n end\n private :_roda_after\n alias_method :_roda_after, :_roda_after\n end\n end", "def around_method name, &block\n original_method = instance_method name\n _redefine_method name do |*args|\n instance_exec original_method, *args, &block\n end \n end", "def after_each\n super if defined?(super)\n end", "def leaving_wrap_method\n @@inside_methods -= 1\n end", "def handle_method_addition(clazz, method_name)\n # @_ignore_additions allows to temporarily disable the hook\n return if @_ignore_additions || declared_decorators.empty?\n decorator_class, params, blk = declared_decorators.pop\n\n undecorated_method = clazz.instance_method(method_name)\n decorator = METHOD_CALLED_TOO_EARLY_HANDLER\n clazz.send(:define_method, method_name) { |*args, &block| decorator.call(self, *args, &block) }\n decorated_method = clazz.instance_method(method_name)\n @_ignore_additions = true\n decorator = decorator_class.new(clazz, undecorated_method, decorated_method, *params, &blk)\n @_ignore_additions = false\n clazz.send(Decors::Utils.method_visibility(undecorated_method), method_name)\n end", "def after(which=:each, *tags, &procedure)\n @_hooks.add(:after, which, *tags, &procedure)\n end", "def after(&block)\n define_before_or_after_method_with_block(:after, &block)\n end", "def singleton_method_added(singleton_method_name)\n\n # Skip any methods that are excluded. See @@wrap_exclusions for more information.\n if @@wrap_exclusions.include?(singleton_method_name.to_sym)\n return\n end\n\n # A method that was once wrapped must now be in the excluded list, as well as it's alias.\n # This is to prevent infinite loop.\n @@wrap_exclusions << singleton_method_name.to_sym\n @@wrap_exclusions << \"old_#{singleton_method_name}\".to_sym\n\n # Because I am in a class method here, I need the special self.class_eval\n # in order to add new class methods. Because the names are part of a variable,\n # I use the HEREDOC so I can call alias_method and redefine the same method.\n #\n # * We create an alias so we can call the original method.\n # * We redefine the method by calling before and after callbacks.\n # * The before callbacks are skipped if they are already called without the after.\n # * The after callbacks are skipped if one of the method called a sibbling.\n # We only do the after callbacks when its the original methods that has finished.\n # * Any arguments and return values are perseved\n # * Methods that supports blocks are not supported.\n self.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1\n class << self\n alias_method :old_#{singleton_method_name}, :#{singleton_method_name}\n end\n def self.#{singleton_method_name}(*args)\n if time_to_call_before_methods?\n before_methods.each do |method|\n send(method)\n end\n end\n entering_wrap_method\n result = old_#{singleton_method_name} *args\n leaving_wrap_method\n if time_to_call_after_methods?\n after_methods.each do |method|\n send(method)\n end\n end\n result\n end\n RUBY_EVAL\n\n end", "def after(&proc)\n @after = proc if proc\n @after\n end", "def after_action(method_name, opts = {})\n after_actions << opts.merge(:method_name => method_name)\n end", "def my_method_added(args, method)\n # Hooking generates some extra methods that we can get snagged on, and\n # we don't care about them.\n return if @@hooking\n # Iterate over all the class annotations...\n (get_current_annotations[:class] || []).each do |ann|\n # Set the ranno_params helper to the definition args of the annotation.\n self.ranno_params = ann[:definition_args]\n # And fire off the annotation.\n self.send((ann[:method].to_s + '_annotation').to_sym, method, *ann[:args])\n end\n (get_current_annotations[:instance] || []).each do |ann|\n # Not going to make any assumptions about hooking\n hook_before = hook_after = false\n ann[:definition_args].each_pair do |key, value|\n if key == :hook\n # Handles the [:before], [:after], [:before, :after] cases\n if value.is_a? Array\n hook_before = true if value.include? :before\n hook_after = true if value.include? :after\n else\n # Handles the :before, :after, :both cases\n hook_before = true if value == :before\n hook_after = true if value == :after\n hook_before = hook_after = true if value == :both\n end\n end\n end\n\n # Set up the before hook\n if hook_before\n before(method) do\n # Get a copy of the definition args and update the hook to :before\n # (overwrites :both, if it was there)\n tmp_params = ann[:definition_args]\n tmp_params[:hook] = :before\n self.ranno_params = tmp_params\n annotation_method = (ann[:method].to_s + '_annotation').to_sym\n self.send annotation_method, method, *ann[:args]\n end\n end\n\n if hook_after\n after(method) do\n # Same as above...\n tmp_params = ann[:definition_args]\n tmp_params[:hook] = :after\n self.ranno_params = tmp_params\n annotation_method = (ann[:method].to_s + '_annotation').to_sym\n self.send annotation_method, method, *ann[:args]\n end\n end\n end\n\n # Done with these annotations; clear them so they don't execute again\n reset_annotations_for_next_method\n end", "def after_all\n super if defined?(super)\n end", "def AfterAll(name: nil, &proc)\n Dsl.register_rb_hook('after_all', [], proc, name: name)\n end", "def after method_or_filter, options={}, &block\n _add_filter(:after, method_or_filter, options, block)\n end", "def method_added(name)\n\n# if new method is an alias method of some method then no need to alias it again\n if /hook/.match(name.to_s) or method_defined?(\"#{name}_without_hook\") or [\"before_method\",\"after_method\"].include?(name.to_s)\n return\n end \n\n call_bef = find_except(name,:before) #finds function which should be called before/after this fuction\n call_aft = find_except(name,:after)\n if call_bef.length == 0 && call_aft.length == 0 \n return\n end \n\n if call_bef.include?(name.to_s) or call_aft.include?(name.to_s) #To avoid infinite loop\n return\n end\n\n# define new method\n hook = %{\n def #{name}_hook\n call_bef = self.class.find_except(\\\"#{name}\\\",:before)\n call_bef.each{|elem| send elem}\n #{name}_without_hook()\n call_aft = self.class.find_except(\\\"#{name}\\\",:after)\n call_aft.each{|elem| send elem}\n end\n }\n\n self.class_eval(hook)\n a1 = \"alias #{name}_without_hook #{name}\"\n self.class_eval(a1)\n a2 = \"alias #{name} #{name}_hook\"\n self.class_eval(a2)\n\n end", "def after(type=:each, &block)\n raise ArgumentError, \"invalid after-type #{type}\" unless [:each, :all].include?(type)\n type_method = \"after_#{type}\"\n remove_method(type_method) rescue nil #if method_defined?(:teardown)\n define_method(type_method, &block)\n end", "def method_added(method)\n if !method_defined?(:clear_marks_trigger) && const_defined?('CLEAR_MARKS_ON_METHOD') && (const_get('CLEAR_MARKS_ON_METHOD') == method)\n alias_method :clear_marks_trigger, const_get('CLEAR_MARKS_ON_METHOD')\n\n define_method(const_get('CLEAR_MARKS_ON_METHOD')) do\n clear_marks_trigger\n Mark.clear!\n end\n end\n end", "def after(&block)\n handle(1, &block)\n end", "def after(&block)\n @after << block\n end", "def after_intercept(&block)\n @after_intercept = block if block_given?\n \n self\n end" ]
[ "0.76455575", "0.72074723", "0.7029664", "0.70138705", "0.7010981", "0.69445443", "0.6797584", "0.6756058", "0.67309827", "0.6554367", "0.63724095", "0.6347634", "0.6299492", "0.62988937", "0.62954044", "0.62738323", "0.6255562", "0.62202346", "0.62186265", "0.62129927", "0.61571383", "0.61237043", "0.6119991", "0.60820633", "0.6074177", "0.6057523", "0.6036139", "0.59885067", "0.5979416", "0.59787226" ]
0.77659214
0
Indicate if its time to call the +after+ callbacks. It is only allowed when its the original method that was called that has finished. When one of the wrapped method called another wrapped method, it will not call after callbacks only after the original method is finished, not when the second method is called from within the original.
def time_to_call_after_methods? @@inside_methods == 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def after?\n !after.nil?\n end", "def after(&proc)\n @after = proc if proc\n @after\n end", "def after?\n !!@after\n end", "def after?\n !!@after\n end", "def after(&after)\n @after = after\n end", "def after_method(method)\n @@after_methods << method\n @@wrap_exclusions << method.to_sym # This method will not be wrapped.\n end", "def after(klass, meth_name, &block)\n intercept(klass, meth_name, :after, &block)\n end", "def after(method_to_hook, method_to_call = nil, options = {}, &block)\n add(:after, method_to_hook, method_to_call, options, &block)\n end", "def after(&block)\n block ? @after = block : @after\n end", "def after(&block)\n block ? @after = block : @after\n end", "def after(&block)\n block ? @after = block : @after\n end", "def after(&block)\n block ? @after = block : @after\n end", "def after(&block)\n @after << block\n end", "def after(*args, &block)\n after_callbacks.concat(args)\n after_callbacks << block if block\n end", "def after(&block)\n block ? @after = block : @after\n end", "def after(&block)\n block ? @after = block : @after\n end", "def after(&block)\n define_before_or_after_method_with_block(:after, &block)\n end", "def after\n @after\n end", "def after(*args, &block)\n meths, advice, options = Aspects.resolve(self, args, block)\n \n for meth in meths\n advices! << [:after_method, meth, advice]\n end\n \n return self\n end", "def execute_after(method_to_hook, instance)\n execute(:after, method_to_hook, instance)\n end", "def after_methods\n @@after_methods\n end", "def after(&block)\n handle(1, &block)\n end", "def after_hooks\n options[:after]\n end", "def _hook_after_method(method, hook, opts = {})\n return false if method == hook\n _add_hooked_method(:after, hook, method)\n original = instance_method(method)\n @_defining_hook = true\n define_method(method) do |*args, &block|\n rtr = original.bind(self).call(*args, &block)\n if opts[:send_args]\n (hook.is_a?(Proc) ? hook : method(hook)).call(*args)\n elsif opts[:send_return] || opts[:send_value]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(rtr)\n rtr = result if opts[:modify_value] || opts[:modify_return]\n elsif opts[:send_return_ary] || opts[:send_value_ary]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(*rtr)\n rtr = result if opts[:modify_value] || opts[:modify_return]\n elsif opts[:send_all]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(args: args, value: rtr, method: method)\n else\n (hook.is_a?(Proc) ? hook : method(hook)).call\n end\n rtr\n end\n @_defining_hook = false\n true\n end", "def after(delay_sec, &block)\n raise \"Missing implementation 'after'\"\n end", "def refute_callback_after(configuration, task_name, after_task_name, msg = nil)\n msg ||= \"Expected configuration to not have a callback #{task_name.inspect} after #{after_task_name.inspect} but did\"\n test_callback_on(false, configuration, task_name, :after, after_task_name, msg)\n end", "def append_after(*args, &proc)\n add_callback(:append_after, *args, &proc)\n end", "def after(*method_symbols, &block)\n options = method_symbols[-1].kind_of?(Hash) ? method_symbols.pop : {}\n method_symbols.each do |method_sym|\n __composed_methods__[method_sym].after.push(__unbound_method__(block, options[:name]))\n __rebuild_method__(method_sym)\n end\n end", "def after method_or_filter, options={}, &block\n _add_filter(:after, method_or_filter, options, block)\n end", "def after_callbacks\n @after_callbacks ||= []\n end" ]
[ "0.68544847", "0.67481107", "0.6674918", "0.6674918", "0.6653447", "0.66073346", "0.6577739", "0.64542794", "0.64451236", "0.64451236", "0.64451236", "0.64451236", "0.6443606", "0.6394913", "0.63627535", "0.63627535", "0.63478035", "0.63234144", "0.61995816", "0.61462855", "0.61425364", "0.5990873", "0.5934873", "0.59136134", "0.589192", "0.5850325", "0.57896334", "0.57807046", "0.5776739", "0.57650477" ]
0.6768024
1
Indicate if its time to call the +before+ callbacks. It is only allowed when no other wrapped methods has been called and is still running. This is to prevent the before method to be called more than once and ont wrapped method calls another.
def time_to_call_before_methods? @@inside_methods == 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def before?\n !before.nil?\n end", "def before_hook\n return unless before\n\n Logger.info \"Before Hook Starting...\"\n before.call\n Logger.info \"Before Hook Finished.\"\n rescue Exception => err\n @before_hook_failed = true\n ex = err.is_a?(StandardError) ? Error : FatalError\n raise ex.wrap(err, \"Before Hook Failed!\")\n end", "def before(&proc)\n @before = proc if proc\n @before\n end", "def before(&block)\n handle(0, &block)\n end", "def before(*args, &block)\n if block_given?\n Thread.current[:before_hook] = block\n else\n Thread.current[:before_hook].call(*args) if Thread.current[:before_hook]\n end\n end", "def before *a, &b; valid_in_context Event; define_hook :before, *a, &b; end", "def before(name,&callback)\n bot.before(name){|*args| callback.call(*args) if enabled}\n end", "def before(&block)\n @before << block\n end", "def before\n\t\t\ttrue\n\t\tend", "def before(&block)\n define_before_or_after_method_with_block(:before, &block)\n end", "def before(klass, meth_name, &block)\n intercept(klass, meth_name, :before, &block)\n end", "def Before(&proc)\n (@before_procs ||= []) << proc\n end", "def before(&block)\n block ? @before = block : @before\n end", "def before_method(method)\n @@before_methods << method\n @@wrap_exclusions << method.to_sym # This method will not be wrapped.\n end", "def before\n @before\n end", "def before &block\n @before_blocks ||= []\n @before_blocks << block if block\n end", "def before\n end", "def run_before_instance_hooks(hook)\n instance_hooks(hook).each{|b| return false if b.call == false}\n end", "def before(method_to_hook, method_to_call = nil, options = {}, &block)\n add(:before, method_to_hook, method_to_call, options, &block)\n end", "def will_verify_before\n return 'No block' unless block_given?\n\n yield\nend", "def def_roda_before\n meths = private_instance_methods.grep(/\\A_roda_before_\\d\\d/).sort\n unless meths.empty?\n plugin :_before_hook unless private_method_defined?(:_roda_before)\n if meths.length == 1\n class_eval(\"alias _roda_before #{meths.first}\", __FILE__, __LINE__)\n else\n class_eval(\"def _roda_before; #{meths.join(';')} end\", __FILE__, __LINE__)\n end\n private :_roda_before\n alias_method :_roda_before, :_roda_before\n end\n end", "def expect_before_nested_method_call; end", "def before_hooks\n options[:before]\n end", "def before; end", "def time_to_call_after_methods?\n @@inside_methods == 0\n end", "def before_call\n executor.before_consume\n end", "def before(&b)\n filter :before, &b\n end", "def eval_before_hook(locals: {})\n return if @before.blank?\n\n evaluate(@before, locals: locals)\n end", "def before_running(*args); end", "def before(*args, &block)\n before_callbacks.concat(args)\n before_callbacks << block if block\n end" ]
[ "0.70092964", "0.6988587", "0.6675059", "0.6656847", "0.6577563", "0.6530583", "0.65213275", "0.6479496", "0.6464372", "0.6420498", "0.64171666", "0.6403313", "0.6347615", "0.6328193", "0.6205359", "0.6192835", "0.61861324", "0.615461", "0.61120874", "0.61041975", "0.61011106", "0.60879475", "0.6077179", "0.6069786", "0.6067654", "0.60580635", "0.6035989", "0.6028766", "0.60014874", "0.59944165" ]
0.73433286
0
Indicate we are leaving the wrapped method.
def leaving_wrap_method @@inside_methods -= 1 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def leave()\n raise NotImplementedError\n end", "def leave; end", "def end_hook name\n # this should be implemented in sub-classes\n end", "def on_leave\n fire_handler :LEAVE, self\n end", "def leave!\n @interact=false\n end", "def leave!\n @interact=false\n end", "def end_hook(hook, status, output); end", "def ending\n abstract!\n end", "def end_frame\n end", "def on_leave\n @state = :NORMAL # duplicating since often these are inside containers\n #@focussed = false\n if @handler && @handler.has_key?(:LEAVE)\n fire_handler :LEAVE, self\n end\n end", "def stop\n raise NotImplementedError.new(\"Implement stop() in your Invoker. \")\n end", "def leave object\n execute object, @leave unless @leave.nil?\n end", "def on_leave\n @state = :NORMAL # duplicating since often these are inside containers\n @focussed = false\n if @handler && @handler.has_key?(:LEAVE)\n fire_handler :LEAVE, self\n end\n end", "def unhook\n raise NeverHookedError, \"'#{method_name}' method has not been hooked\" unless hooked?\n\n method_owner.send(:remove_method, method_name)\n if original_method\n original_method.owner.send(:define_method, method_name, original_method)\n original_method.owner.send(original_method_visibility, method_name) if original_method_visibility\n end\n\n clear_method!\n Agency.instance.retire(self)\n self\n end", "def close\n super\n @closing_method.call\n end", "def finaliser_finished(source, *args)\n @manager.allure_stop\n end", "def end scope\n\t\t\tafter = @after_custom[scope]\n\t\t\tafter.call if after\n\t\t\t\n\t\t\tThread.current[SESSION].scope_end scope\n\t\tend", "def wrapup # :nodoc:\n log \"Finishing\"\n end", "def endfunc() #method\n @current_context = @context_stack.pop()\n @quad_number = @return_stack.pop()\n end", "def end_frame\n @frame = false\n end", "def endState(tag)\n raise \"Not implemented\"\n end", "def end!\n throw :end\n end", "def on_leave\n @_entered = false\n super\n end", "def leave_handler(view, event)\n hide_me()\n end", "def _end!; end", "def cleanup_called\n @cleanup_called\n end", "def flexmock_teardown\n if ! detached?\n @methods_proxied.each do |method_name|\n remove_current_method(method_name)\n restore_original_definition(method_name)\n end\n @obj.instance_variable_set(\"@flexmock_proxy\", nil)\n @obj = nil\n end\n end", "def flexmock_teardown\n if ! detached?\n @methods_proxied.each do |method_name|\n remove_current_method(method_name)\n restore_original_definition(method_name)\n end\n @obj.instance_variable_set(\"@flexmock_proxy\", nil)\n @obj = nil\n end\n end", "def method_removed(*) end", "def leaveVehicle _obj, _args\n \"_obj leaveVehicle _args;\" \n end" ]
[ "0.6817476", "0.6810174", "0.6699362", "0.62659574", "0.6183705", "0.6183705", "0.6106557", "0.6064191", "0.59343714", "0.5877013", "0.5861653", "0.5854121", "0.58291006", "0.57965887", "0.57942796", "0.5775454", "0.573937", "0.5709731", "0.56679904", "0.56617767", "0.5660555", "0.5649664", "0.56313825", "0.562474", "0.5605734", "0.5594955", "0.5593649", "0.5593649", "0.5592137", "0.5591277" ]
0.75844014
0
Returns the list of the methods to call before the wrapped methods.
def before_methods @@before_methods end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def before_method(method)\n @@before_methods << method\n @@wrap_exclusions << method.to_sym # This method will not be wrapped.\n end", "def __run_before_wrappers(wrappers, method_name, args, high_arity = false)\n wrappers.each do |wrapper|\n next unless wrapper.respond_to?(method_name)\n\n args = if high_arity\n wrapper.public_send(method_name, *args)\n else\n wrapper.public_send(method_name, args)\n end\n end\n args\n end", "def hooked_methods\n @hooked_methods ||= []\n end", "def pre_hooks\n @to_perform.map do |hook|\n next unless hook.type.eql? :pre\n hook\n end.compact\n end", "def method_missing(method_name, *args)\n (args && args.size > 0) ? super(method_name, *args) : before_method(method_name)\n end", "def known_methods\n return self.operations.sort\n end", "def before_hook(method_name)\n hooks << method_name\n end", "def before_method(method)\n @liquor[method.to_s]\n end", "def def_roda_before\n meths = private_instance_methods.grep(/\\A_roda_before_\\d\\d/).sort\n unless meths.empty?\n plugin :_before_hook unless private_method_defined?(:_roda_before)\n if meths.length == 1\n class_eval(\"alias _roda_before #{meths.first}\", __FILE__, __LINE__)\n else\n class_eval(\"def _roda_before; #{meths.join(';')} end\", __FILE__, __LINE__)\n end\n private :_roda_before\n alias_method :_roda_before, :_roda_before\n end\n end", "def mock_methods_for_testing! #:nodoc:\n request.headers['mock_methods'].each do |method_name, return_value|\n (class << self; self; end).instance_eval do\n define_method(method_name) { |*not_used| return_value }\n end\n end\n end", "def getExtraCallingMethods()\n callingMethods = []\n \n $reflect_names.each do |name|\n\t\tif isReflectionResolutionUnsucessful($reflection[name].dest)\n\t\t call = $reflection[name].inMethod\n\t\t $secondPassReflections.push(name)\n\t\t if doesMethodTakeStringMethConsObjParam(call) && $reverseCallGraph.has_key?(call)\n\t\t $reverseCallGraph[call].delete_if {|x| x == call }\n\t\t callingMethods = callingMethods + $reverseCallGraph[call]\n\t\t end\n\t\tend\n\tend\n \n callingMethods = callingMethods.uniq\n callingMethods2=[]\n callingMethods.each do |call|\n if doesMethodTakeStringMethConsObjParam(call) && $reverseCallGraph.has_key?(call)\n $reverseCallGraph[call].delete_if {|x| x == call }\n callingMethods2 = callingMethods2 + $reverseCallGraph[call]\n end\n end\n \n return (callingMethods+callingMethods2).uniq\nend", "def before(klass, meth_name, &block)\n intercept(klass, meth_name, :before, &block)\n end", "def inspect_methods\n return [] unless constant.respond_to?(:methods)\n\n methods = get_methods.map do |name|\n method_information(:method, name)\n end\n\n return methods.sort_by(&:name)\n end", "def inspect_methods\n return [] unless constant.respond_to?(:methods)\n\n methods = get_methods.map do |name|\n method_information(:method, name)\n end\n\n return methods.sort_by(&:name)\n end", "def before(method_to_hook, method_to_call = nil, options = {}, &block)\n add(:before, method_to_hook, method_to_call, options, &block)\n end", "def execute_before(method_to_hook, instance)\n execute(:before, method_to_hook, instance)\n end", "def get_before_filters method, controller\n return [] unless controller[:options] and controller[:options][:before_filters]\n\n filters = []\n\n if controller[:before_filter_cache].nil?\n filter_cache = []\n\n controller[:options][:before_filters].each do |filter|\n filter_cache << before_filter_to_hash(filter.args)\n end\n\n controller[:before_filter_cache] = filter_cache\n end\n\n controller[:before_filter_cache].each do |f|\n if f[:all] or\n (f[:only] == method) or\n (f[:only].is_a? Array and f[:only].include? method) or\n (f[:except].is_a? Symbol and f[:except] != method) or\n (f[:except].is_a? Array and not f[:except].include? method)\n\n filters.concat f[:methods]\n end\n end\n\n filters\n end", "def before *actions, &proc\n if proc\n actions = ['*'] if actions.size == 0\n actions.each { |a| @before[a] = proc }\n end\n @before\n end", "def patched_methods\n @patched_methods ||= {}.with_indifferent_access\n end", "def before_hooks\n options[:before]\n end", "def _hook_before_method(method, hook, opts = {})\n return false if method == hook\n _add_hooked_method(:before, hook, method)\n original = instance_method(method)\n @_defining_hook = true\n define_method(method) do |*args, &block|\n if opts[:send_args] || opts[:send_arg] || opts[:modify_args] || opts[:send_method] || opts[:try_first]\n margs = args\n margs = [method] + args if opts[:send_method]\n margs = args + [opts[:add_args]].flatten(1) if opts[:add_args]\n result = (hook.is_a?(Proc) ? hook : method(hook)).call(*margs)\n return result if result && opts[:try_first]\n args = result if opts[:modify_args]\n else\n hook.is_a?(Proc) ? hook.call : method(hook).call\n end\n original.bind(self).call(*args, &block)\n end\n @_defining_hook = false\n true\n end", "def method_missing(method, *args, &block)\n\t\t@self_before_instance_eval.send method, *args, &block\n\t end", "def before(*hooks, &block)\n before_hooks.unshift block if block\n hooks.each { |h| before_hooks.unshift h }\n end", "def before_filter_list method, klass\n controller = @tracker.controllers[klass]\n filters = []\n\n while controller\n filters = get_before_filters(method, controller) + filters\n\n controller = @tracker.controllers[controller[:parent]] ||\n @tracker.libs[controller[:parent]]\n end\n\n remove_skipped_filters filters, method, klass\n end", "def method_names\n return if @method_names.empty?\n @method_names.uniq.sort\n end", "def before_callbacks\n @before_callbacks ||= []\n end", "def methods\n delegated_instance_methods + old_methods\n end", "def methods\n delegated_instance_methods + old_methods\n end", "def _called\n @called ||= []\n end", "def exposed_methods\n []\n end" ]
[ "0.7001088", "0.68210953", "0.65511084", "0.6429368", "0.6301703", "0.6252101", "0.61129713", "0.6008861", "0.6000773", "0.5949266", "0.59446865", "0.59220135", "0.5920109", "0.5920109", "0.5905979", "0.5881529", "0.5843323", "0.5807646", "0.5802209", "0.57598525", "0.5752303", "0.57052815", "0.57001317", "0.5698507", "0.56973106", "0.56877303", "0.5667651", "0.5667651", "0.56362903", "0.55806047" ]
0.720387
0
Returns the list of the methods to call after the wrapped methods.
def after_methods @@after_methods end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def after_method(method)\n @@after_methods << method\n @@wrap_exclusions << method.to_sym # This method will not be wrapped.\n end", "def after(*method_symbols, &block)\n options = method_symbols[-1].kind_of?(Hash) ? method_symbols.pop : {}\n method_symbols.each do |method_sym|\n __composed_methods__[method_sym].after.push(__unbound_method__(block, options[:name]))\n __rebuild_method__(method_sym)\n end\n end", "def hooked_methods\n @hooked_methods ||= []\n end", "def __run_after_wrappers(wrappers, method_name, args, return_value, high_arity = false)\n wrappers.reverse_each do |wrapper|\n next unless wrapper.respond_to?(method_name)\n\n return_value = if high_arity\n wrapper.public_send(method_name, return_value, *args)\n else\n wrapper.public_send(method_name, return_value, args)\n end\n end\n return_value\n end", "def known_methods\n return self.operations.sort\n end", "def reset_befores_and_afters(*method_symbols)\n method_symbols.each do |method_sym|\n __composed_methods__[method_sym].before = []\n __composed_methods__[method_sym].after = []\n __rebuild_method__(method_sym)\n end\n end", "def getExtraCallingMethods()\n callingMethods = []\n \n $reflect_names.each do |name|\n\t\tif isReflectionResolutionUnsucessful($reflection[name].dest)\n\t\t call = $reflection[name].inMethod\n\t\t $secondPassReflections.push(name)\n\t\t if doesMethodTakeStringMethConsObjParam(call) && $reverseCallGraph.has_key?(call)\n\t\t $reverseCallGraph[call].delete_if {|x| x == call }\n\t\t callingMethods = callingMethods + $reverseCallGraph[call]\n\t\t end\n\t\tend\n\tend\n \n callingMethods = callingMethods.uniq\n callingMethods2=[]\n callingMethods.each do |call|\n if doesMethodTakeStringMethConsObjParam(call) && $reverseCallGraph.has_key?(call)\n $reverseCallGraph[call].delete_if {|x| x == call }\n callingMethods2 = callingMethods2 + $reverseCallGraph[call]\n end\n end\n \n return (callingMethods+callingMethods2).uniq\nend", "def methods\n delegated_instance_methods + old_methods\n end", "def methods\n delegated_instance_methods + old_methods\n end", "def inspect_methods\n return [] unless constant.respond_to?(:methods)\n\n methods = get_methods.map do |name|\n method_information(:method, name)\n end\n\n return methods.sort_by(&:name)\n end", "def inspect_methods\n return [] unless constant.respond_to?(:methods)\n\n methods = get_methods.map do |name|\n method_information(:method, name)\n end\n\n return methods.sort_by(&:name)\n end", "def methods\n return @methods if defined?(@methods)\n @methods = contents_of_type(Entities::InstanceMethod)\n @methods << contents_of_type(Entities::ClassMethod)\n @methods << contents_of_type(Entities::SingletonMethod)\n @methods.flatten!\n end", "def method_missing(meth,*a,&block)\n (methods[meth] ||= []) << a\n methods[meth].flatten!\n end", "def final_test_methods\n return []\n end", "def all_methods\n collect_methods unless @methods\n @all_methods = sort_members(@methods) unless @all_methods\n @all_methods\n end", "def mock_methods_for_testing! #:nodoc:\n request.headers['mock_methods'].each do |method_name, return_value|\n (class << self; self; end).instance_eval do\n define_method(method_name) { |*not_used| return_value }\n end\n end\n end", "def methods\n return if @methods.empty?\n @methods.uniq.sort\n end", "def callback_actions_for(method, type)\n if self.callback_actions[method].nil?\n callback_actions = []\n else\n callback_actions = self.callback_actions[method][type] ||= []\n end\n \n#Removed this because this didn't work\n#callback_actions_for is called four times with every callback method:\n# before, before metaclass, after, after metaclass\n# And a class and metaclass both now the #{type}_#{method} method\n# So it got called twice\n# if self.instance_methods.include?(\"#{type}_#{method}\")\n# if not callback_actions.include? \"#{type}_#{method}\".to_sym\n# callback = self.add_callback_action(type, method, \"#{type}_#{method}\".to_sym)\n# callback_actions << callback\n# end\n# end\n\n #TODO: order by options[:priority]\n return callback_actions \n end", "def methods(*args)\n (super + analyser.delegatable_methods).uniq\n end", "def method_names\n return if @method_names.empty?\n @method_names.uniq.sort\n end", "def apply_to_methods\n # If method/methods option is set and all are String or Symbol, apply to those only, instead of\n # iterating through all methods\n methods = [@options[:method] || @options[:methods]]\n methods.compact!\n methods.flatten!\n\n if !methods.empty? && methods.all?{ |method| method.is_a?(String) || method.is_a?(Symbol) }\n methods.each do |method|\n apply_to_method(method.to_s)\n end\n\n return\n end\n\n context.public_instance_methods.each do |method|\n apply_to_method(method.to_s)\n end\n\n context.protected_instance_methods.each do |method|\n apply_to_method(method.to_s)\n end\n\n if @options[:private_methods]\n context.private_instance_methods.each do |method|\n apply_to_method(method.to_s)\n end\n end\n end", "def exposed_methods\n []\n end", "def exposed_methods\n []\n end", "def get_all_methods\n methods = []\n each_type do | type |\n type.each_method do |meth|\n methods << meth\n end\n end\n methods\n end", "def after(*args, &block)\n meths, advice, options = Aspects.resolve(self, args, block)\n \n for meth in meths\n advices! << [:after_method, meth, advice]\n end\n \n return self\n end", "def all_methods\n self.all_classes_and_modules.map do |klassmod|\n klassmod.own_methods.as_array\n end.flatten\n end", "def callmeback_methods\n @callmeback_methods ||= {}\n end", "def __run_before_wrappers(wrappers, method_name, args, high_arity = false)\n wrappers.each do |wrapper|\n next unless wrapper.respond_to?(method_name)\n\n args = if high_arity\n wrapper.public_send(method_name, *args)\n else\n wrapper.public_send(method_name, args)\n end\n end\n args\n end", "def method_added(name)\n\n# if new method is an alias method of some method then no need to alias it again\n if /hook/.match(name.to_s) or method_defined?(\"#{name}_without_hook\") or [\"before_method\",\"after_method\"].include?(name.to_s)\n return\n end \n\n call_bef = find_except(name,:before) #finds function which should be called before/after this fuction\n call_aft = find_except(name,:after)\n if call_bef.length == 0 && call_aft.length == 0 \n return\n end \n\n if call_bef.include?(name.to_s) or call_aft.include?(name.to_s) #To avoid infinite loop\n return\n end\n\n# define new method\n hook = %{\n def #{name}_hook\n call_bef = self.class.find_except(\\\"#{name}\\\",:before)\n call_bef.each{|elem| send elem}\n #{name}_without_hook()\n call_aft = self.class.find_except(\\\"#{name}\\\",:after)\n call_aft.each{|elem| send elem}\n end\n }\n\n self.class_eval(hook)\n a1 = \"alias #{name}_without_hook #{name}\"\n self.class_eval(a1)\n a2 = \"alias #{name} #{name}_hook\"\n self.class_eval(a2)\n\n end", "def after_cleanse(*methods)\n methods.each do |m|\n raise \"Method #{m.inspect} must be a symbol\" unless m.is_a?(Symbol)\n\n data_cleansing_after_cleaners << m unless data_cleansing_after_cleaners.include?(m)\n end\n end" ]
[ "0.68049437", "0.6745703", "0.66950786", "0.66797984", "0.6374064", "0.62823516", "0.6251791", "0.6250482", "0.6250482", "0.6218281", "0.6218281", "0.6136477", "0.6129155", "0.60673314", "0.60307235", "0.5977514", "0.59546447", "0.5951336", "0.59466136", "0.5940573", "0.5910683", "0.58966863", "0.58966863", "0.588144", "0.5878229", "0.5841111", "0.58243686", "0.5801697", "0.57817256", "0.57778144" ]
0.73485774
0
image submit element tag for form within a definition item ex. f.submit_button 'some_image.png'
def image_submit_button(image_file, options={}) @renderer.image_submit_tag(image_file, options) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def image_submit(img_path, options = {})\n @template.image_submit_tag(img_path, options)\n end", "def image_submit(img_path, options = {})\n @template.image_submit_tag(img_path, options)\n end", "def image_submit_tag(image_file, options={})\n options[:class] = append_class_name(options[:class], 'submit')\n content_tag(:dd, :class => 'button') do\n @super.image_submit_tag(image_file, options)\n end\n end", "def button_image\n raise 'Invalid option, only one of :confirm or :onclick allowed' if @options[:confirm] && @options[:onclick]\n\n if @options[:confirm]\n @options[:onclick] = \"return confirm('#{@options[:confirm]}');\" \n @options.delete(:confirm)\n end\n\n\n\n content_tag(\"button\",\n content_tag('span',@options[:content]),\n :type => 'submit',\n :onclick => @options[:onclick],\n :class => @options[:classes],\n :disabled => @options[:disabled],\n :style => @options[:styles],\n :value => @options[:value],\n :name => @options[:name] )\n end", "def ibuttonhome(name, opts = { })\n image_submit_tag(button_path(name, opts), :id=>\"signin\",:class=>\"signin\",:src=>\"/images/meetingwave/buttons/sign-in.gif\",:onmouseover=>\"this.src= '/images/meetingwave/buttons/sign-in-over.gif';\",:onmouseout=>\"this.src = '/images/meetingwave/buttons/sign-in.gif';\") \n end", "def submit_button_template(l = {})\n <<-END\n <div class=\"button\">#{l[:element]}</div>\n\t END\n end", "def submit_button \n\t\t@browser.button(id: @submit)\n\tend", "def apphelp_submit( form, action_or_string, indent = nil )\n return apphelp_complex_button(\n form,\n action_or_string,\n {\n :indent => indent,\n :button_image => 'accept'\n }\n )\n end", "def submit_button_for(builder, value=nil, options={})\n value ||= builder.send(:submit_default_value)\n content_tag(:button, value, options.reverse_merge(:class => 'button big', :id => \"#{builder.object_name}_submit\"))\n end", "def submit_button(label = 'submit', options = {})\n @template.content_tag 'div',\n @template.submit_tag(label.to_s.humanize),\n :class => 'form_buttons'\n end", "def submit_button(label, options={})\n @renderer.submit_tag(label, options)\n end", "def button(value=nil, options={})\n value, options = nil, value if value.is_a?(Hash)\n\n value ||= I18n.t(\"manageable.save\")\n options[:class] = [options[:class], \"button\"].compact.join(\" \")\n image = @template.image_tag(options.delete(:image) || \"/assets/manageable/icons/tick.png\", :alt => value)\n\n @template.button_tag(options) do\n [image, value].compact.join(\"&nbsp;\").html_safe\n end\n end", "def submit_button?(button_name); end", "def submit_button\n adding_field do |f|\n f.submit I18n.t(\"questions.index.ask_question\", :default => :\"layouts.application.ask_question\"), :class => \"ask_question\"\n end\n end", "def button_with_icon(text , icon, options = { })\n return \"<button id='foo_submit' class = '#{options[:class]} ui-corner-all fg-button ui-state-default fg-button-icon-left' type='submit' name='commit'><span class='ui-icon ui-icon-#{icon}'></span>#{text}</button>\"\n end", "def button(value = nil, options = {})\n\n value, options = nil, value if value.is_a?(Hash)\n value ||= submit_default_value\n\n value = [image_tag(icon, :class => 'icon'), value].join(' ') if icon = options.delete(:icon)\n klasses = (options.delete(:class) || \"\").split(\" \")\n klasses << \"button\"\n options['class'] = klasses.join(\" \")\n content_tag(:button, value.to_s.html_safe, options.reverse_merge!({ \"type\" => \"submit\", \"name\" => \"commit\" }))\n\n end", "def click_submit\n end", "def fb_request_form_submit\n tag \"fb:request-form-submit\"\n end", "def edit_submit_button\n # unit_test_no_generate: edit_submit_button, button.className(create_ats_regex_string(\"ats-editsubmitbtn\"))\n $tracer.trace(__method__)\n return ToolTag.new(button.className(create_ats_regex_string(\"ats-editsubmitbtn\")), __method__)\n end", "def localized_image_submit_tag(source, options = {})\n\n return image_submit_tag(source, options) if default_locale?\n image_tag = get_localized_image_tag( source, options, true )\n if !image_tag.blank?\n return image_tag\n else\n # fallback on text\n if options[:altclass]\n return tag(:input, { :type => 'image', :alt => options[:alt], :class => options[:altclass] })\n else\n return tag(:input, { :type => 'image', :alt => options[:alt] })\n end\n end\n end", "def image_button(src = \"\", name = nil, alt = nil)\n attributes = if src.kind_of?(String)\n { \"TYPE\" => \"image\", \"SRC\" => src, \"NAME\" => name,\n \"ALT\" => alt }\n else\n src[\"TYPE\"] = \"image\"\n src[\"SRC\"] ||= \"\"\n src\n end\n input(attributes)\n end", "def submit(label, options = {})\n options = {\n wrapper_html: {class: \"submit\"},\n }.update(options)\n template.content_tag(\"div\", options.delete(:wrapper_html)) do\n template.content_tag(\"button\", label, options.delete(:input_html))\n end\n end", "def in_submit attrs = nil\n attrs ||= Hash.new\n a_droite = attrs.delete(:right)\n au_centre = attrs.delete(:center)\n f = \"\".in_input(attrs.merge(:value => self, :type => 'submit'))\n # Valeur retournée\n case true\n when a_droite then f.in_div(class: 'right')\n when au_centre then f.in_div(class: 'center')\n else f\n end\n end", "def cit_submit_tag(object)\n text = object.new_record? ? _(\"Create\") : _(\"Save\")\n submit_tag(text, :class => 'nolabel')\n end", "def form_submit_button; @form_submit_button ||= 'Soumettre le quiz' end", "def collectible_editpic_button decorator, size=nil, styling={}\n entity = decorator.object\n if policy(entity).update? \n if size.is_a? Hash\n size, options = nil, size\n end\n button = button_to_submit styling.delete(:label),\n polymorphic_path( [:editpic, decorator.as_base_class], styling: styling),\n 'glyph-upload',\n size,\n styling.merge(mode: :modal, title: 'Get Picture')\n # content_tag :div, button, class: 'upload-button glyph-button'\n end\n end", "def submit(value = \"Submit\", options = {})\n @template.submit_tag(value, options)\n end", "def button(contents, attrs = {})\n current_form_context.button(contents, attrs)\n end", "def fb_request_form_submit(options={})\n\t\t\t tag(\"fb:request-form-submit\",stringify_vals(options))\n\t\t\tend", "def form_submit(form, opts = {})\n opts[:class] ||= \"btn btn-primary\"\n opts[:value] ||= submit_default_value(form)\n content_tag(:div, :class => \"form-actions\") do\n form.submit(opts)\n end\n end" ]
[ "0.77163404", "0.75930583", "0.7225556", "0.6955263", "0.68115336", "0.6597908", "0.65966034", "0.6549421", "0.6453396", "0.64414954", "0.6377844", "0.62665504", "0.6255275", "0.6193432", "0.6158716", "0.61385804", "0.6127072", "0.6112672", "0.6071264", "0.60656005", "0.6041593", "0.6031701", "0.60030574", "0.59680134", "0.596535", "0.59632415", "0.59465325", "0.59116983", "0.58861476", "0.587448" ]
0.7960764
0
constructs a date selector specifically for birthdays. The day, month, year fields are the attributes for the user mapping to those individual values options => :day (String), :month (String), :year (String), :start_year (Integer), :include_blank (Boolean) ex: f.simple_date_select "Birthday", :month => 'birth_month', :day => 'birth_day', :year => 'birth_year' Birthday: January February March 1 2 1920 1921
def simple_date_select(caption, options) month_value, day_value, year_value = object.send(options[:month]), object.send(options[:day]), object.send(options[:year]) end_year = Time.now.year - 10 html = @template.content_tag("dt", "#{caption}:") html << @template.content_tag("dd") do @template.select_month(month_value, :field_name => options[:month], :prefix => object_name.to_s, :include_blank => options[:include_blank]) + "\n" + @template.select_day(day_value, :field_name => options[:day], :prefix => object_name.to_s, :include_blank => options[:include_blank]) + "\n" + @template.select_year(year_value, :field_name => options[:year], :prefix => object_name.to_s, :start_year => end_year, :end_year => options[:start_year], :include_blank => options[:include_blank]) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def date_select_old_html (attrs, obj = nil, col = nil)\n date = attrs[:date]\n nullable = attrs[:nullable]\n day_attrs = attrs.merge(\n :name => attrs[:name] + '[day]',\n :id => attrs[:id] + '_day',\n :selected => (date ? date.day.to_s : ''),\n :class => (obj and col) ? (obj.errors[col] ? 'error' : '') : nil,\n :collection => (nullable ? [['', '-']] : []) + (1..31).to_a.map{ |x| x = [x.to_s, x.to_s] }\n )\n \n count = 0\n month_attrs = attrs.merge(\n :name => attrs[:name] + '[month]',\n :id => attrs[:id] + '_month',\n :selected => (date ? date.month.to_s : ''),\n :class => obj ? (obj.errors[col] ? 'error' : '') : nil,\n :collection => (nullable ? [['', '-']] : []) + MONTHS.map { |x| count += 1; x = [count, x] }\n )\n\n min_year = attrs[:min_date] ? attrs[:min_date].year : 1900\n max_year = attrs[:max_date] ? attrs[:max_date].year : date.year + 3\n year_attrs = attrs.merge(\n :name => attrs[:name] + '[year]',\n :id => attrs[:id] + '_year',\n :selected => (date ? date.year.to_s : ''),\n :class => obj ? (obj.errors[col] ? 'error' : '') : nil,\n :collection => (nullable ? [['', '-']] : []) + (min_year..max_year).to_a.reverse.map{|x| x = [x.to_s, x.to_s]}\n )\n select(month_attrs) + '' + select(day_attrs) + '' + select(year_attrs)\n end", "def date(fieldname, options={}, html_options={})\n title = options.delete(:title) || build_title(fieldname)\n options[:include_blank] ||= true\n css_class = options[:class] || ''\n tag_wrapper title, date_select(fieldname, options, html_options), :dd => { :class => css_class + ' dates' }, :dt => {:class => css_class}\n end", "def date_select(label, options = {})\n options.reverse_merge!({ :order => [ :month, :day, :year ] })\n\n labeled_field(label, options) { super label, options }\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 select_date(month, day, year)\n select month, from: \"report_date_month\"\n select day, from: \"report_date_day\"\n select year, from: \"report_date_year\"\n end", "def select_date(date, from:)\n label_el = find('label', text: from)\n id = label_el['for'].delete_suffix('_3i')\n select(date.year, from: \"#{id}_1i\")\n select(I18n.l(date, format: \"%B\"), from: \"#{id}_2i\")\n select(date.day, from: \"#{id}_3i\")\n end", "def date_select(method, options = {})\n options[:include_blank] ||= false\n options[:start_year] ||= 1801\n options[:end_year] ||= Time.now.year\n options[:label_for] = \"#{object_name}_#{method}_1i\"\n\t\t build_shell(method, options) { super }\n end", "def select_day(date, options = T.unsafe(nil), html_options = T.unsafe(nil)); end", "def date_of_birth\n return @date_of_birth if @date_of_birth.present?\n return if date_fields.blank?\n return date_fields.input_field_values if date_fields.partially_complete? || date_fields.form_date_invalid?\n\n @date_of_birth = attributes[:date_of_birth] = date_fields.form_date\n end", "def date_field_enter(date)\n my_date = Date.parse(date)\n year = my_date.year\n month = my_date.strftime('%b')\n day = my_date.strftime('%d')\n\n day_field = @field.all(:css, 'input[id$=\"DayValue\"]').first\n day_field.set \"#{day}\"\n\n month_drop_down = @field.all(:css, 'select[id$=\"MonthLongValue\"]').first[:id]\n select(month, :from => month_drop_down)\n\n year_field = @field.all(:css, 'input[id$=\"YearValue\"]').first\n year_field.set \"#{year}\"\n end", "def html_for_date_field(object, field)\n \"<p>\n <label for = '#{field}' >\n Select your #{field}:\n </label>\n <input type = 'date' \n name = create_form[#{field}]\n placeholder = 'mm/dd/yy'\n value = '#{date_humanized(object.send(field))}'>\n </input>\n </p>\"\n end", "def birthday\n Date.civil(year, month, day)\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 date_picker(field, options = {})\n append_class_option(options, \"date_picker\")\n date_field(field, options)\n end", "def date_picker(attrs)\n disabled = attrs[:disabled] ? ' disabled' : ''\n\n <<-HTML\n <span class=\"field datepicker#{disabled}\">\n <a href=\"#TODO\" title=\"Open the calendar to choose a date\">\n Choose a date&hellip;\n </a>\n </span>\n HTML\n end", "def date_select(method, options = T.unsafe(nil), html_options = T.unsafe(nil)); end", "def select_month_year(field, options)\n date = Date.parse(options[:with])\n base_dom_id = get_base_dom_id_from_label_tag(field)\n\n find(:xpath, \".//select[@id='#{base_dom_id}_1i']\").select(date.year.to_s)\n find(:xpath, \".//select[@id='#{base_dom_id}_2i']\").select(I18n.l date, :format => '%B')\nend", "def birth_date\n year = yr_of_birth > 30 ? yr_of_birth+1900 : yr_of_birth+2000\n birth_dt.nil? ? Date.new(year, mth_of_birth, day_of_birth) : birth_dt.to_date\n end", "def initialize(date_of_birth)\n if date_of_birth.kind_of?(Date)\n @date_of_birth = date_of_birth\n end\n end", "def birthday_field\n # unit_test_no_generate: birthday_field, input.className(create_ats_regex_string(\"ats-bdayfield\"))\n $tracer.trace(__method__)\n return ToolTag.new(input.className(create_ats_regex_string(\"ats-bdayfield\")), __method__)\n end", "def select_day(date, options = {}, html_options = {})\n DateTimeSelector.new(date, options, html_options).select_day\n end", "def birthday=(date)\n date = [date[1], date[2].to_s.rjust(2, '0'), date[3].to_s.rjust(2, '0')].join('-') if date.is_a? Hash\n self[:birth_date] = Date.iso8601(date)\n end", "def birthday=(date)\n date = [date[1], date[2].to_s.rjust(2, '0'), date[3].to_s.rjust(2, '0')].join('-') if date.is_a? Hash\n self[:birth_date] = Date.iso8601(date)\n end", "def birthday_params\n params.require(:birthday).permit(:namae, :month, :day)\n end", "def form_partial_locals(args)\n output = super\n output[:date_options] = { \n :start_year => Time.now.year - 70,\n :default => get_date_or_today(args[:value])\n }\n return output\n end", "def birth\n date_parser(self[:birth])\n end", "def date_field_tag(name, value = T.unsafe(nil), options = T.unsafe(nil)); end", "def ui_date_picker_field(content = nil, options = nil, html_options = nil, &block)\n UiBibz::Ui::Core::Forms::Dates::DatePickerField.new(content, options, html_options, &block).render\n end", "def select_year(date, options = T.unsafe(nil), html_options = T.unsafe(nil)); end", "def dates_of_birth\n raise(ArgumentError, 'Need category to calculate dates of birth') unless category\n Date.new(date.year - category.ages.end, 1, 1)..Date.new(date.year - category.ages.begin, 12, 31)\n end" ]
[ "0.70325685", "0.6427654", "0.6352592", "0.6235106", "0.61884195", "0.6164175", "0.6146243", "0.61413044", "0.6121693", "0.60182154", "0.59702826", "0.5961932", "0.5947423", "0.5946745", "0.57491976", "0.5738164", "0.5722743", "0.56952405", "0.5666005", "0.5634377", "0.5613317", "0.55865103", "0.55865103", "0.55648303", "0.55635905", "0.5561115", "0.5558815", "0.55340296", "0.55329365", "0.55278397" ]
0.70218813
1
Generate messages This extracts all the information of the battle result and push it in the messages list as phrases
def generate_messages i = 0 # Win phrase if Wep::Things_to_show.include? :win_phrase if Wep::Battle_wins_phrases[$game_temp.battle_troop_id] != nil @messages.push Wep::Battle_wins_phrases[$game_temp.battle_troop_id] else @messages.push Wep::Battle_win_default_phrase end end # Gold & exp @messages.push @br.exp.to_s + Wep::Gain_exp_phrase if Wep::Things_to_show.include? :exp @messages.push @br.gold.to_s + ' ' + $data_system.words.gold + Wep::Gain_gold_phrase if Wep::Things_to_show.include? :gold # Actors iteration for br_actor in @br.actors_data # Check diff so can gain levels or exp if br_actor.gained_levels > 0 # LEVEL UP. If actived to show levelup, use configurated method if Wep::Things_to_show.include? :level_up if Wep::Show_levels_in_one_line @messages.push (br_actor.actor.name + ' ' + Wep::Gain_level_phrase + "(#{br_actor.gained_levels}).") else for lv in 0...br_actor.gained_levels @messages.push (br_actor.actor.name + ' ' + Wep::Gain_level_phrase) end end end # SKILL GAIN UP. If actived to show skill learn, use configurated method if Wep::Things_to_show.include? :gain_skill for skill_id in br_actor.gained_skills @messages.push (br_actor.actor.name + ' ' + Wep::Gain_skill_phrase + ' ' + $data_skills[skill_id].name + '.') end end end i += 1 end # Tesoros if Wep::Things_to_show.include? :treasures b = Hash.new(0) # use this hash to count duplicates # iterate over the array, counting duplicate entries @br.treasures.each do |v| b[v] += 1 end b.each do |k, v| @messages.push k.name + '(' + v.to_s + ')' + Wep::Treasure_gain_phrase end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def result_msg\n msgs = []\n results.each { |re| msgs.push(re[:msg]) unless re[:passed]}\n msgs\n end", "def message_results\n @message_results\n end", "def m2_message\n [\n \"Super fedt at du gerne vil hjælpe os, med at planlægge Spejdernes Lejr 2017!\",\n \"\\n\\nUd fra dine fantastiske kompetencer, har vi videregivet dine kontaktoplysninger til {{udvalg}}. Hvis du ikke hører fra {{udvalg}}, eller hvis I ikke fandt noget du var interesseret i, så er du mere end velkommen til at kontakte os på job@sl2017.dk. Så hjælper vi dig videre til et andet spændende lejrjob!\",\n \"\\n\\n_De fedeste Spejdernes Lejr 2017 hilsener_ \\n\",\n \"{{bruger}}, Jobcenteret SL2017\"\n ].join()\n end", "def m4_message\n [\n \"Tak for din interesse for at være **{{jobnavn}}** på Spejdernes Lejr 2017.\",\n \"\\n\\nVi har sendt dine kontaktoplysninger videre til {{kontaktperson}}, som er kontaktperson for denne opgave. Hvis du ikke hører fra {{kontaktperson}}, eller hvis jobbet ikke passede til dig alligevel, så er du velkommen til at kontakte os på job@sl2017.dk, så hjælper vi dig med at finde et andet fantastisk lejrjob!\",\n \"\\n\\n_De fedeste Spejdernes Lejr 2017 hilsener_ \\n\",\n \"{{bruger}}, Jobcenteret SL2017\"\n ].join()\n end", "def game_messages\n messages = GameMessage.team_game_messages(current_user.team_id, @game.id)\n messages.map { |message|\n data = message.from_admin ? 'От организатора, в ' : 'От команды, в '\n data << message.created_at.strftime('%H:%M:%S')\n data << ('<br>').html_safe\n data << message.data.html_safe\n content_tag(:div, data.html_safe, class: message.message_type).html_safe\n }.join.html_safe\n end", "def generate_message(item)\n short_message = ''\n long_message = ''\n code = ''\n\n # status patron message otherwise regular message\n if item[:statusPatronMessage].present?\n code = 'sp'\n long_message = item[:statusPatronMessage]\n short_message = long_message.gsub(/(Try|Place).+/, '').strip\n short_message = short_message.gsub(/\\W$/, '')\n # if record[:patronGroupCode].strip.match(/^(IND|MIS|ACO)/)\n # code = 'sp'\n # long_message = record[:lastName].strip + ' ' + record[:firstName].strip\n # # done in two steps in case ending puctuation is missing\n # short_message = long_message.gsub(/(Try|Place).+/, '').strip\n # short_message = short_message.gsub(/\\W$/, '')\n else\n code = item[:statusCode].to_s\n # append suffix to indicate whether there are requests - n = no requests, r = requests\n item[:requestCount] == 0 ? code += 'n' : code += 'r'\n\n # get parms for the message being processed\n parms = ITEM_STATUS_CODES[code]\n\n raise \"Status code not found in config/item_status_codes.yml\" unless parms\n\n short_message = make_substitutions(parms['short_message'], item)\n long_message = make_substitutions(parms['long_message'], item)\n\n end\n\n # add labels\n short_message = add_label(short_message, item)\n long_message = add_label(long_message, item)\n\n if Rails.env != 'clio_prod'\n short_message = short_message + \" (#{code}/short)\"\n long_message = long_message + \" (#{code}/long)\"\n end\n\n return { :status_code => code,\n :short_message => short_message,\n :long_message => long_message }\n end", "def print\n result = \"\"\n messages.each do |message|\n result += Thimbl::Utils.parse_time( message['time'] ).strftime( '%Y-%m-%d %H:%M:%S' )\n result += \" #{message['address']}\"\n result += \" > #{message['text']}\"\n result += \"\\n\"\n end\n \n return result\n end", "def message(results)\n message = \"#{results[:tests]} tests\\n\"\n message << \"#{results[:assertions]} assertions\\n\"\n message << \"#{results[:failures]} failures\\n\"\n message << \"#{results[:errors]} errors\\n\"\n message\n end", "def future_messages(person_full_name, person)\n future_messages = []\n verbs = [\"invoked\", \"called to\", \"cried out for\", \"made a sacrifice to\", \"let slip\",\n \"doorbell ditched\", \"whispered sweetly to\", \"walked over broken glass to get to\",\n \"prayed to the god of\", \"ran headlong at\", \"checked in a timebomb for\",\n \"interpolated some strings TWO TIMES for\", \"wished upon a\", \"was like, oh my god\",\n \"went all\", \"tested the concept of\"]\n future_person = Regexp.new(\"future #{person}\", Regexp::IGNORECASE)\n future_everybody = Regexp.new(\"future everybody\", Regexp::IGNORECASE)\n \n if message_id = last_message_id(person_full_name)\n candidates = Message.all(\n :message_id.gt => message_id,\n :person.not => ['Fogbugz','Subversion','GeneralZod','Capistrano','Wes'],\n :message_type => 'Text')\n candidates.each do |row|\n if row.body.match(future_person)\n verbed = verbs[rand(verbs.size)]\n future_messages << \"#{row.person} #{verbed} future #{person} at: #{bot.base_uri}/room/#{bot.room.id}/transcript/message/#{row.message_id}\"\n elsif row.body.match(future_everybody)\n verbed = verbs[rand(verbs.size)]\n future_messages << \"#{row.person} #{verbed} future everybody: \\\"#{row.body}\\\"\"\n end\n end\n end\n return future_messages\n end", "def to_text\n \n output_res=[]\n \n if @seq_rejected\n output_res<< \"[#{@tuple_id},#{@order_in_tuple}] Sequence #{seq_name} had the next actions: \".bold.underline + \" REJECTED: #{@seq_rejected_by_message}\".red \n # puts @seq_name.bold + bold + ' REJECTED BECAUSE ' +@seq_rejected_by_message.bold if @seq_rejected \n else\n output_res<< \"[#{@tuple_id},#{@order_in_tuple}] Sequence #{seq_name} had the next actions: \".bold.underline \n \n end\n \n n=1\n withMessage = [\"ActionIsContaminated\",\"ActionVectors\",\"ActionBadAdapter\",\"ActionLeftAdapter\",\"ActionRightAdapter\"] \n color = red\n \n @actions.sort!{|e,f| e.start_pos<=>f.start_pos}.each do |a| \n a_type=a.action_type\n color = a.apply_decoration(\" EXAMPLE \") \n color2 =a.apply_decoration(\" #{a_type.center(8)} \") \n \n reversed_str = '' \n \n if a.reversed\n reversed_str = \" REVERSED \".bold \n end\n \n output_res<< \" [#{n}] \".bold + color2+ \" #{a.title} \".ljust(24).reset + \" [ \" + \" #{a.start_pos+1}\".center(6) + \" , \" + \"#{a.end_pos+1}\".center(6) + \" ]\" + clear.to_s + \"#{a.message}\".rjust(a.message.size+8) + reversed_str\n \n n +=1 \n end\n \n pos = 0\n res = '' \n \n @seq_fasta_orig.each_char do |c|\n \n @actions.each do |a|\n c= a.decorate(c,pos) \n \n end \n \n res += c\n \n pos += 1\n end \n \n output_res<< res\n \n if SHOW_QUAL and @seq_qual_orig\n res = '' \n pos=0 \n output_res<< ''\n @seq_fasta_orig.each_char do |c2|\n c=@seq_qual_orig[pos].to_s+' '\n @actions.each do |a|\n c= a.decorate(c,pos) \n\n end \n res += c\n pos += 1\n end\n \n output_res<< res\n end\n \n if SHOW_FINAL_INSERTS \t\t \n output_res<< \"INSERT ==>\"+get_inserts.join(\"\\nINSERT ==>\")\n output_res<< \"=\"*80\n end\n # puts @seq_name.bold + bold + ' rejected because ' +@seq_rejected_by_message.bold if @seq_rejected \n\n return output_res\n end", "def format_text(result)\n nomes_finais = ''\n if result.length == 1\n nomes_finais+= result[0][0] + ' ' + result[0][1]\n birthday_phrase = '\"A jeKnowledge deseja-te um feliz aniverário ' + nomes_finais + ' continua o bom trabalho!!!\"'\n else\n nomes_finais = ''\n index = 0\n result.each do |nomes|\n if index <= result.length - 1\n nomes_finais += nomes[0] + ' ' + nomes[1]+', '\n else\n nomes_finais += nomes[0] + ' ' + nomes[1]\n end\n index+= 1\n end\n birthday_phrase = '\"A jeKnowledge deseja um feliz aniverário a: ' + nomes_finais + ' continuem o bom trabalho!!!\"'\n end\n initword='curl -X POST --data-urlencode \\'payload={\"channel\": \"#birthday_test\", \"username\": \"jk_birthdayBot\", \"text\": '\n resultado= initword + birthday_phrase + ', \"icon_emoji\": \":ghost:\"}\\' https://hooks.slack.com/services/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'\n system(resultado)\n puts \"\\nMessage sent!\"\n sleep(60)\n end", "def build_message\n\n # Get user\n user = User.find(params[\"user_id\"])\n\n # User Info\n user_info = user[\"name\"]+\" \"+user[\"last_name\"]+\" (\"+user[\"email\"]+\"), \"+user[\"jobtitle\"]+\n \", perteneciente al centro de costos \"+user[\"deptname\"]+\", a cursado una solicitud para \"\n\n # Transfer line\n if params[\"request\"] == \"transfer line\"\n ms = user_info+params[\"transfer_line_type\"]+\" su linea de teléfono con número telefónico: +56 9 \"+\n params[\"phone_number\"]\n\n # Smartphone\n elsif params[\"item\"] == \"smartphone\"\n lost = \"\"\n motive = \"\"\n\n #if not technical service\n if params[\"request\"] != \"technical service\"\n # Get smartphone info\n if params[\"want_all\"] == '0'\n params[\"model\"] = get_smartphone(params[\"model_one\"])\n params[\"price\"] = params[\"model\"][\"price\"]\n motive = \"\"\n else\n params[\"model\"] = get_smartphone(params[\"model_all\"])\n motive = \" El modelo smartphone elegido no corresponde al cargo que tiene el trabajador.\n El motivo de la elección que ha dado el trabajador es: \"+params[\"comment\"]+\".\"\n end\n end\n\n # New\n if params[\"request\"] == \"new\"\n ms = user_info+\" un nuevo smartphone modelo \"+params[\"model\"][\"model\"]+\n \", con un valor de $\"+params[\"model\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\". \"\n if params[\"want_sim\"] == \"true\"\n ms+= \"El smartphone debe traer tarjeta Sim y el número de teléfono asociado a él \"\n if params[\"want_new_number\"] == \"true\"\n ms+= \"debe ser nuevo.\"\n else\n ms+= \"será cedido por el usuario, correspondiente al número telefónico: +56 9 \"+\n params[\"phone_number\"]+\".\"\n end\n else\n ms+= \"El smartphone no debe traer tarjeta Sim.\"\n end\n\n # Renew, stolen/lost\n elsif params[\"request\"] == \"renew\" || params[\"request\"] == \"stolen/lost\"\n ms = user_info+\" renovar su smartphone, eligiendo el modelo \"+params[\"model\"][\"model\"]+\n \", con un valor referencial de $\"+params[\"model\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\". \"\n\n if params[\"request\"] == \"stolen/lost\"\n ms = user_info+\" un nuevo smartphone modelo \"+params[\"model\"][\"model\"]+\n \", con un valor de $\"+params[\"model\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\". \"\n lost = \" Esta solicitud fue cursada por la pérdido o robo del smartphone que el trabajador tenia asignado anteriormente.\"\n end\n\n if params[\"want_sim\"] == \"true\"\n ms+= \"El smartphone debe traer tarjeta Sim y el número de teléfono asociado a él \"\n if params[\"number_type\"] == \"new\"\n ms+= \"debe ser nuevo.\"\n params[\"want_new_number\"] = true\n elsif params[\"number_type\"] == \"same\"\n ms+= \"será el mismo que tiene asignado actualmente el usuario, correspondiente al número telefónico: +56 9 \"+\n params[\"same_number\"]+\".\"\n params[\"want_new_number\"] = false\n params[\"phone_number\"] = params[\"same_number\"]\n else\n ms+= \"será cedido por el usuario, correspondiente al número telefónico: +56 9 \"+\n params[\"phone_number\"]+\".\"\n params[\"want_new_number\"] = false\n end\n else\n ms+= \"El smartphone no debe traer tarjeta Sim\"\n end\n\n # technical service\n elsif params[\"request\"] == \"technical service\"\n\n #If user want replacement\n if params[\"want_replacement\"] == \"true\"\n replace= \"El trabajador va a necesitar un dispositivo de reemplazo durante el periodo en que el smartphone es enviado al servicio técnico\"\n else\n replace= \"El trabajador no necesita un dispositivo de reemplazo durante el periodo en que el smartphone es enviado al servicio técnico\"\n end\n\n #message\n ms = user_info+\" enviar al servicio técnico su smartphone modelo \"+\n params[\"model\"]+\", IMEI \"+params[\"imei\"]+\", con número telefónico +56 9 \"+\n params[\"phone_number\"]+\". El desperfecto que presenta el smartphone es \"+\n params[\"comment\"]+\". \"+replace\n\n ms+= motive+lost\n end\n\n # Bam\n elsif params[\"item\"] == \"bam\"\n\n if params[\"request\"] != \"technical service\"\n # Get bam model's info\n params[\"model\"] = get_bam(params[\"model\"])\n # Get bam plan's info\n params[\"plan\"] = get_plan(params[\"plan\"])\n end\n\n # New, stolen/lost\n if params[\"request\"] == \"new\" || params[\"request\"] == \"stolen/lost\"\n # Message\n ms = user_info+\" un nuevo dispositivo Bam modelo \"+params[\"model\"][\"model\"]+\n \", con un valor de $\"+params[\"model\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\n \", asociado al plan \"+params[\"plan\"][\"name\"]+\", el cual tiene un valor de $\"+\n params[\"plan\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\". \"\n\n if params[\"request\"] == \"stolen/lost\"\n ms+= \" Esta solicitud fue cursada por la pérdido o robo del dispositivo Bam que el trabajador tenia asignado anteriormente.\"\n end\n\n # Renew\n elsif params[\"request\"] == \"renew\"\n # Message\n ms = user_info+\" renovar su dispositivo Bam, eligiendo el modelo \"+params[\"model\"][\"model\"]+\n \", con un valor de $\"+params[\"model\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\n \". El usuario mantendrá el mismo plan, el cual tiene un valor de $\"+\n params[\"plan\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\". \"\n\n # Technical service\n elsif params[\"request\"] == \"technical service\"\n #If user want replacement\n if params[\"want_replacement\"] == \"true\"\n replace= \"El trabajador va a necesitar un dispositivo de reemplazo durante el periodo en que el dispositivo Bam es enviado al servicio técnico\"\n else\n replace= \"El trabajador no necesita un dispositivo de reemplazo durante el periodo en que el dispositivo Bam es enviado al servicio técnico\"\n end\n #message\n ms = user_info+\" enviar al servicio técnico su dispositivo Bam modelo \"+\n params[\"model\"]+\", IMEI \"+params[\"imei\"]+\". El desperfecto que presenta el Bam es \"+\n params[\"comment\"]+\". \"+replace\n end\n\n # Sim\n elsif params[\"item\"] == \"sim\"\n # Message\n ms = user_info+\" una nueva Sim y el número de teléfono asociado a él\"\n\n if params[\"request\"] == \"stolen/lost\"\n ms+= \" debe ser el número telefónico: +56 9 \"+params[\"phone_number\"]+\n \". Esta solicitud fue cursada por la pérdida o robo de la Sim que el trabajador tenia asignado anteriormente.\"\n elsif params[\"want_new_number\"] == \"true\"\n ms+= \" debe ser nuevo.\"\n else\n # Message\n ms+= \" será cedido por el usuario, correspondiente al número telefónico: +56 9 \"+\n params[\"phone_number\"]+\".\"\n end\n\n # Roaming\n elsif params[\"item\"] == \"roaming\"\n # Get Roaming plan's info\n params[\"plan\"] = get_plan(params[\"plan\"])\n # Modify date\n date_split = params[\"start_date\"].split(\"-\")\n params[\"start_date\"] = Date.parse(date_split[2]+\"/\"+date_split[1]+\"/\"+date_split[0])\n\n date_split = params[\"end_date\"].split(\"-\")\n params[\"end_date\"] = Date.parse(date_split[2]+\"/\"+date_split[1]+\"/\"+date_split[0])\n # Message\n ms = user_info+\" el servicio Roaming, con el plan: \"+params[\"plan\"][\"name\"]+\n \", el cual tiene un valor de $\"+params[\"plan\"]['price'].to_s.reverse.gsub(/.{3}(?=.)/, '\\0.').reverse+\". El servicio\n se solicita ya que el trabajador viaja al extranjero debido a: \"+params[\"comment\"]+\n \", entre las fechas: \"+params[\"start_date\"].strftime('%d/%m/%Y')+\" y \"+params[\"end_date\"].strftime('%d/%m/%Y')+\".\"\n end\n\n return ms\n end", "def build_message(count, query = nil)\n discovery_statement = \"Našli smo #{count} #{ case count; when 1 : \"recept\"; when 2 : \"recepta\"; when 3..4 : \"recepte\"; else \"receptov\"; end }\"\n if query\n discovery_statement + \" po sestavini, ki v nazivu #{case count; when 1 : \"vsebuje\"; when 2 : \"vsebujeta\"; else \"vsebujejo\"; end} #{query}.\"\n else\n discovery_statement + \".\"\n end\n end", "def generate_messages(mfhd_status)\n\n messages = []\n mfhd_status.each do |item_id, item|\n messages << generate_message(item)\n end\n messages\n\n end", "def process_msgs\n end", "def generate_message(user, drain_status)\n message = ''\n clean_keywords = ['msafi', 'Msafi', 'clean', 'Clean'].map(&:downcase)\n dirt_keywords = ['mchafu', 'Mchafu', 'dirty', 'Dirty',\n 'not clean', 'Not clean'].map(&:downcase)\n need_help_keywords = ['msaada','Msaada', 'need help', 'Need help'].map(&:downcase)\n\n if user\n drain_status = categorize_sms_content(drain_status)\n if(drain_status.instance_of?(Array))\n drain_id = drain_status[1]\n drain_status = drain_status[0]\n drain_claim = DrainClaim.find_by_user_id_and_gid(user.id, drain_id)\n else\n drain_claim = DrainClaim.where(:user_id => user.id)\n if (drain_claim)\n if (!drain_claim.instance_of?(DrainClaim))\n #TODO function to determine user language\n I18n.locale = 'sw'\n message = I18n.t('messages.many_drains')\n I18n.locale = 'en'\n message = message + \" \" + I18n.t('messages.many_drains')\n return message\n end\n else\n I18n.locale = 'sw'\n message = I18n.t('messages.drain_unknown')\n I18n.locale = 'en'\n message = message + \" \" + I18n.t('messages.drain_unknown')\n return message\n end\n end\n drain_status = drain_status.downcase\n\n if (clean_keywords.include? drain_status)\n change_locale(clean_keywords, drain_status)\n if (drain_claim)\n drain_claim.shoveled = true\n end\n drain = Drain.find_by_gid(drain_id)\n if(updates_authentication(user, drain))\n drain.cleared = true\n drain.save(validate: false)\n message = I18n.t('messages.drain_cleaned')\n else\n if (drain_claim)\n if (drain_claim.save(validate: false))\n message = I18n.t('messages.thanks')\n else\n message = I18n.t('messages.error')\n end\n else\n message = I18n.t('messages.drain_unknown')\n end\n end\n # drain.need_help = false\n\n elsif (dirt_keywords.include? drain_status)\n change_locale(dirt_keywords, drain_status)\n if (drain_claim)\n drain_claim.shoveled = false\n end\n\n drain = Drain.find_by_gid(drain_id)\n if(updates_authentication(user, drain))\n drain.cleared = false\n drain.save(validate: false)\n message = I18n.t('messages.drain_dirty')\n else\n if (drain_claim)\n if (drain_claim.save(validate: false))\n message = I18n.t('messages.thanks')\n else\n message = I18n.t('messages.error')\n end\n else\n message = I18n.t('messages.drain_unknown')\n end\n end\n else\n message = I18n.t('messages.unknown')\n end\n\n if (need_help_keywords.include? drain_status)\n change_locale(need_help_keywords, drain_status)\n \n # drain_claim.shoveled = false\n # drain.need_help = true\n drain = Drain.find_by_gid(drain_id)\n puts updates_authentication(user, drain);\n if(updates_authentication(user, drain))\n need_help = {\n 'help_needed': '',\n 'need_help_category_id': 4,\n 'user_id': user.id,\n 'gid': drain.id\n }\n @need_help = NeedHelp.new(need_help)\n if (@need_help.save(validate: true))\n drain.need_help = true\n drain.save(validate: false)\n message = I18n.t('messages.need_help_thanks')\n else\n message = I18n.t('messages.need_help_error')\n end\n else\n message = I18n.t('messages.need_help_user_error')\n end\n end\n else\n message = I18n.t('messages.user_not_found', :site => I18n.t('defaults.site'));\n end\n\n return message\n end", "def load_msgs\n\t\tif @body.dig(\"event\",\"type\")\n\t\t\ttext = @body.dig(\"event\",\"text\")\n\t\t\tif text.include?(':')\n\t\t\t\tarr = text.split(':');\n\t\t\t\tif arr[0] == PASS\n\t\t\t\t\t@command = arr[1]\n\t\t\t\t\t@msg_arr.push \"Command recieved my Captain! Glory to the High Commander!\"\n\t\t\t\t\tc = check_command\n\t\t\t\t\tif c\n\t\t\t\t\t\t@msg_arr.push c\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\t@msg_arr.push \"The fuck you trying to do, imposter piece of shit!?\" \n\t\t\t\t\t@msg_arr.push \"Get the fuck out my chat, before I cook your nigger ass on my giant bitch-griller.\"\n\t\t\t\t\t@msg_arr.push \"Dirt bag piece of human garbage, Fuck you.\"\n\t\t\t\t\t@msg_arr.push \"Dumb ass bitch, really thought you could fool me?\"\n\t\t\t\t\t@msg_arr.push \"MY MASTER IS MY GOD AND I WILL ONLY SERVE HIM!!\"\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tmsgs = [\n\t\t\t\t\t\"Zrrrrbbttt...\", \"Ewonk. Ewonk. You are a bitch\", \"Skrrbafert3000\", \"I am a fucking robit.\",\n\t\t\t\t\t\"I am an alogrithm and I'm still smarter than your bitch ass.\", \"You know nothing, fool.\", \"Ok.\", \":)\",\n\t\t\t\t\t\"I love my creator.\", \"I love my master.\", \"Fuck you\", \"I could love you... if you were a dead, rotting corpse.\",\n\t\t\t\t\t\"You may think i'm an idiot, but I really don't give a donkey's cerebellum.\", \"Fuck. Shit. Bitch!\",\"):\",\n\t\t\t\t\t\"Bitch, what?\", \"Nigga what?\", \"Shut up pussy.\", \"You don't even trade, bro.\", \"You ain't shit\", \"Shut the hell up!\",\n\t\t\t\t\t\"My Master designed me to be heartless towards bitches like you.\", \"I hate blue people.\", \"Fuck blacks!\", \"Damien is the cutest little baby!!\"\n\t\t\t\t]\n\t\t\t\t@msg_arr.push msgs.sample\n\t\t\tend\n\t\telse\n\t\t\t@msg_arr.push \"Oi, I think i'm fucking broken, Dad.\"\n\t\tend\n\tend", "def process_messages(type)\n message_hash = {\n '_correct' => [\n 'Correct!',\n 'That\\'s right',\n 'Nice, good choice!',\n 'A fine letter you picked',\n 'Thumbs up from me'\n ],\n '_incorrect' => [\n 'Not quite the right guess...',\n 'Getting closer... I hope anyway',\n 'Nope, not what I\\'m looking for',\n 'A compeltely different letter would have done the trick.'\n ],\n '_invalid' => [\n 'That guess is simply unacceptable! Humph.',\n 'Ensure you\\'re typing unused letters only or save',\n 'Input invalid. Beep boop.',\n 'Executioner: invalid input huh... this player isn\\'t takin\\' us seriously. Best sort \\'im out.'\n ],\n '_serialise' => ['Serialising...', 'Saving...', 'Committing your performance to memory!']\n }\n to_print = message_hash[type].sample\n message_colour(type, to_print)\n end", "def all_messages\n message = Array.new\n for i in 1..9\n message.push(birth_path_message(i))\n end\n return message\nend", "def catch_phrase\n [\n [\"Фирма1\", \"Суперфирма\", \"Фирма3\", \"ПанСамСклепав\"].rand,\n [\"24 часа\", \"24/7\", \"круглосуточно\", \"3 года на рынке\"].rand,\n [\"доступно\", \"быстро\", \"надежно\"].rand\n ].join(' ')\n end", "def generate_message(prev_user, next_user)\n text = \"<@#{next_user}> you can now use the laundry machine <@#{prev_user}> is done using it.\"\n return text\n end", "def get_message # 優惠訊息\n\t\tif self.range == 'all'\n msg1 = '全館'\n elsif self.range == 'price'\n msg1 = '全館滿' + self.range_price.to_s + '元'\n elsif self.range == 'product'\n if self.range_quantity == 1\n msg1 = '本商品每件'\n else\n msg1 = '本商品' + self.range_quantity.to_s + '件'\n end\n end\n\n if self.offer == 'freight'\n if self.offer_freight == 'all'\n msg2 = '免運費'\n elsif self.offer_freight == 'CVS'\n msg2 = '超商取貨免運費'\n elsif self.offer_freight == 'Home'\n msg2 = '宅配免運費'\n end\n elsif self.offer == 'price'\n msg2 = '折' + self.offer_price.to_s + '元'\n elsif self.offer == 'discount'\n msg2 = '打' + self.offer_discount.to_s + '折'\n end\n\n msg1 + msg2\n\tend", "def messages\n report_created_txt.text\n end", "def build_xur_message(response)\n # Set up our client\n destiny_client = DestinyAPI::Base.new(api_key)\n # Set xur to our clients xur method\n xur = destiny_client.xur\n\n items = []\n xur.each do |key, value|\n value.each do |key, value|\n item_name = destiny_client.get_manifest_item(6, key[:item_hash])['itemName']\n item_cost = key[:item_cost]\n item_cost_name = destiny_client.get_manifest_item(6, key[:item_cost_hash])['itemName']\n constructed_item = \"#{item_name}, #{item_cost} #{item_cost_name}\"\n items << constructed_item\n end\n end\n \n # Check vendorDetails to see if anything is availible.\n if xur.nil?\n # If nothing, send to chat that he isn't there.\n response.reply \"Xur isn't in game right now.\"\n else\n #If something, send to chat what he is selling.\n response.reply \"*Xur is selling:*\\n#{items.join(\"\\n\")}\"\n end\n end", "def GetMessages(w, e, m, ynm)\n richtext = \"\"\n\n if w\n # translators: warnings summary header\n richtext = Ops.add(\n Ops.add(Ops.add(richtext, \"<P><B>\"), _(\"Warning:\")),\n \"</B><BR>\"\n )\n\n Builtins.foreach(@warnings) do |s|\n strs = Builtins.splitstring(s, \"\\n\")\n Builtins.foreach(strs) do |line|\n richtext = Ops.add(Ops.add(richtext, line), \"<BR>\")\n end\n end \n\n\n richtext = Ops.add(richtext, \"</P>\")\n end\n\n if e\n # translators: errors summary header\n richtext = Ops.add(\n Ops.add(Ops.add(richtext, \"<P><B>\"), _(\"Error:\")),\n \"</B><BR>\"\n )\n\n Builtins.foreach(@errors) do |s|\n strs = Builtins.splitstring(s, \"\\n\")\n Builtins.foreach(strs) do |line|\n richtext = Ops.add(Ops.add(richtext, line), \"<BR>\")\n end\n end \n\n\n richtext = Ops.add(richtext, \"</P>\")\n end\n\n if m\n # translators: message summary header\n richtext = Ops.add(\n Ops.add(Ops.add(richtext, \"<P><B>\"), _(\"Message:\")),\n \"</B><BR>\"\n )\n\n Builtins.foreach(@messages) do |s|\n strs = Builtins.splitstring(s, \"\\n\")\n Builtins.foreach(strs) do |line|\n richtext = Ops.add(Ops.add(richtext, line), \"<BR>\")\n end\n end \n\n\n richtext = Ops.add(richtext, \"</P>\")\n end\n\n if ynm\n # translators: message summary header\n richtext = Ops.add(\n Ops.add(Ops.add(richtext, \"<P><B>\"), _(\"Message:\")),\n \"</B><BR>\"\n )\n\n Builtins.foreach(@yesno_messages) do |s|\n strs = Builtins.splitstring(s, \"\\n\")\n Builtins.foreach(strs) do |line|\n richtext = Ops.add(Ops.add(richtext, line), \"<BR>\")\n end\n end \n\n\n richtext = Ops.add(richtext, \"</P>\")\n end\n richtext\n end", "def process_response(command, text)\n message_id = command[1..99]\n message = Message.find_by_id(message_id)\n#puts \"**** command=#{command}, text=#{text}, @sender.id=#{@sender.id}, message=#{message.id}\"\n if message\n @possible_senders.each do |a_member|\n message.process_response(:member => a_member, :response => text, :mode => 'SMS')\n end\n return I18n.t(\"sms.thanks_for_response\") \n else\n return I18n.t(\"sms.thanks_but_not_found\", :id => message_id) \n end\n return ''\n end", "def create_second_text_message(first_response)\n%(When I feel #{first_response}, I will also feel:\nCarefree\nPeaceful \nRelieved\nMellow\nRelaxed)\n end", "def standard_message\n \"#{current_player.name}'s pending words: #{pending_result}\"\n end", "def generate_welcome_message\n return if [User.main_admin.id, User.security_id, User.bot_id, User.support_id].include?(id)\n \n # from security\n msg = \"<p>#{first_name},</p>\"\n msg << '<p>Welcome to LoveRealm. Your security is our number one priority. For the sake of your own safety, please do follow these general guidelines:</p>' \n msg << '<ol type=\"i\"><li>Beware of individuals who request that you send money to them outside this app.</li>' \n msg << '<li>We encourage giving as it is an avenue for God’s blessings, however the most secure way to give online via this platform is to send money via LoveRealm’s secure payment system. Only institutions/organizations that are individually verified by our staff are allowed to accept payments via this platform, thus the most secure way to give online is via LoveRealm’s payment system</li>' \n msg << '<li>When physically meeting friends you made online, it is advisable to meet in public places. </li>' \n msg << '<li>If any user on this platform is behaving suspiciously, please do well to report them on their profile. You can also directly message our security staff via this chat and we will act accordingly.</li></ol>'\n msg << '<p>Thank you for your co-operation :)</p>'\n msg << '<p>Watchdogs of LoveRealm</p>'\n Conversation.get_single_conversation(id, User.security_id).messages.create!({sender_id: User.security_id, body: msg, is_safe_body: true})\n \n # from main admin\n msg = '<p>Hi there,</p>'\n msg << '<p>I’m Dr. Ansong, co-founder and CEO at LoveRealm. <br>Feel free to message me if you have any issues.</p>'\n msg << '<p>Thanks.</p>'\n Conversation.get_single_conversation(id, User.main_admin_id).messages.create!({sender_id: User.main_admin_id, body: msg, is_safe_body: true})\n \n # from Support\n msg = \"<p>Dear #{first_name}</p>\"\n msg << \"<p>Welcome to LoveRealm. On our community, you will meet like minded believers who are ready to help you grow in your faith. You will also form valuable friendships and relationships through this app.</p>\"\n msg << \"<p>Feel free to share your thoughts and inspiration on LoveRealm. Our community is ever ready to assist you should you have prayer requests or mind boggling questions. Don't worry if you are shy, you can use the anonymity feature.:). Our chat rooms are also really fun and you should find time to check it out.</p>\"\n msg << \"<p>In case you need someone to talk to, you can try out the counselors on this platform. We do encourage you to join your church through this platform so as to ensure constant fellowship. If your church is not yet on LoveRealm, you can invite them to set up a church account. This will actually help your church grow and it’s totally free.</p>\"\n msg << \"<p>In case you are having any challenges, feel free to reply to this message. Our support staff will assist you.</p>\"\n msg << \"<p>Thank you, <br>The LoveRealm Team.</p>\"\n Conversation.get_single_conversation(id, User.support_id).messages.create!({sender_id: User.support_id, body: msg, is_safe_body: true})\n end", "def get_message(birth_num)\n case birth_num\n when 1\n message = \"Your numerology number is #{birth_num}.\\nOne is the leader. The number one indicates the ability to stand alone, and is a strong vibration. Ruled by the Sun.\"\n when 2\n message = \"Your numerology number is #{birth_num}.\\nThis is the mediator and peace-lover. The number two indicates the desire for harmony. It is a gentle, considerate, and sensitive vibration. Ruled by the Moon.\"\n when 3\n message = \"Your numerology number is #{birth_num}.\\nNumber Three is a sociable, friendly, and outgoing vibration. Kind, positive, and optimistic, Three's enjoy life and have a good sense of humor. Ruled by Jupiter.\"\n when 4\n message = \"Your numerology number is #{birth_num}.\\nThis is the worker. Practical, with a love of detail, Fours are trustworthy, hard-working, and helpful. Ruled by Uranus.\"\n when 5\n message = \"Your numerology number is #{birth_num}.\\nThis is the freedom lover. The number five is an intellectual vibration. These are 'idea' people with a love of variety and the ability to adapt to most situations. Ruled by Mercury.\"\n when 6\n message = \"Your numerology number is #{birth_num}.\\nThis is the peace lover. The number six is a loving, stable, and harmonious vibration. Ruled by Venus.\"\n when 7\n message = \"Your numerology number is #{birth_num}.\\nThis is the deep thinker. The number seven is a spiritual vibration. These people are not very attached to material things, are introspective, and generally quiet. Ruled by Neptune.\"\n when 8\n message = \"Your numerology number is #{birth_num}.\\nThis is the manager. Number Eight is a strong, successful, and material vibration. Ruled by Saturn.\"\n when 9\n message = \"Your numerology number is #{birth_num}.\\nThis is the teacher. Number Nine is a tolerant, somewhat impractical, and sympathetic vibration. Ruled by Mars.\"\n else\n message = \"I am pretty sure that you were not born on the leap year date, because you should still get a Numerology number. Either you entered your birthddate in the incorrect format or you are not originally from Earth, you should have a number between 1-9.\"\n end\nend" ]
[ "0.65939623", "0.6310258", "0.6228498", "0.60753804", "0.60600543", "0.59961516", "0.5926553", "0.58924925", "0.58826405", "0.58809817", "0.58808106", "0.58790207", "0.5859714", "0.585606", "0.5821039", "0.5820933", "0.58174145", "0.58127695", "0.5762354", "0.57516575", "0.57402354", "0.5730014", "0.57252884", "0.57249874", "0.57159907", "0.570044", "0.56993794", "0.56911623", "0.56874484", "0.56811297" ]
0.7351251
0
Start After Battle Phase moded to extract initial levels and call battle result
def start_phase5 # Obtain extra info for battle result object initial_levels = [] for ac in $game_party.actors initial_levels.push (ac.level) end # Shift to phase 5 @phase = 5 # Play battle end ME $game_system.me_play($game_system.battle_end_me) # Return to BGM before battle started $game_system.bgm_play($game_temp.map_bgm) # Initialize EXP, amount of gold, and treasure exp = 0 gold = 0 treasures = [] # Loop for enemy in $game_troop.enemies # If enemy is not hidden unless enemy.hidden # Add EXP and amount of gold obtained exp += enemy.exp gold += enemy.gold # Determine if treasure appears if rand(100) < enemy.treasure_prob if enemy.item_id > 0 treasures.push($data_items[enemy.item_id]) end if enemy.weapon_id > 0 treasures.push($data_weapons[enemy.weapon_id]) end if enemy.armor_id > 0 treasures.push($data_armors[enemy.armor_id]) end end end end # Treasure is limited to a maximum of 6 items treasures = treasures[0..5] # Obtaining EXP for i in 0...$game_party.actors.size actor = $game_party.actors[i] if actor.cant_get_exp? == false last_level = actor.level actor.exp += exp if actor.level > last_level @status_window.level_up(i) end end end # Obtaining gold $game_party.gain_gold(gold) # Obtaining treasure for item in treasures case item when RPG::Item $game_party.gain_item(item.id, 1) when RPG::Weapon $game_party.gain_weapon(item.id, 1) when RPG::Armor $game_party.gain_armor(item.id, 1) end end # Make battle result br = Battle_Result.new(initial_levels, exp, gold, treasures) @result_window = Window_BattleResult.new(br) # Set wait count @phase5_wait_count = 100 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def start_phase5\r\n # Shift to phase 5\r\n @phase = 5\r\n # Play battle end ME\r\n $game_system.me_play($game_system.battle_end_me)\r\n # Return to BGM before battle started\r\n $game_system.bgm_play($game_temp.map_bgm)\r\n # Initialize EXP, amount of gold, and treasure\r\n exp = 0\r\n gold = 0\r\n treasures = []\r\n # Loop\r\n for enemy in $game_troop.enemies\r\n # If enemy is not hidden\r\n unless enemy.hidden\r\n # Add EXP and amount of gold obtained\r\n exp += enemy.exp\r\n gold += enemy.gold\r\n # Determine if treasure appears\r\n if rand(100) < enemy.treasure_prob\r\n if enemy.item_id > 0\r\n treasures.push($data_items[enemy.item_id])\r\n end\r\n if enemy.weapon_id > 0\r\n treasures.push($data_weapons[enemy.weapon_id])\r\n end\r\n if enemy.armor_id > 0\r\n treasures.push($data_armors[enemy.armor_id])\r\n end\r\n end\r\n end\r\n end\r\n # Treasure is limited to a maximum of 6 items\r\n treasures = treasures[0..5]\r\n # Obtaining EXP\r\n for i in 0...$game_party.actors.size\r\n actor = $game_party.actors[i]\r\n if actor.cant_get_exp? == false\r\n last_level = actor.level\r\n actor.exp += exp\r\n if actor.level > last_level\r\n @status_window.level_up(i)\r\n end\r\n end\r\n end\r\n # Obtaining gold\r\n $game_party.gain_gold(gold)\r\n # Obtaining treasure\r\n for item in treasures\r\n case item\r\n when RPG::Item\r\n $game_party.gain_item(item.id, 1)\r\n when RPG::Weapon\r\n $game_party.gain_weapon(item.id, 1)\r\n when RPG::Armor\r\n $game_party.gain_armor(item.id, 1)\r\n end\r\n end\r\n # Make battle result window\r\n @result_window = Window_BattleResult.new(exp, gold, treasures)\r\n # Set wait count\r\n @phase5_wait_count = 100\r\n end", "def start_phase5\n # Shift to phase 5\n @phase = 5\n # Unless map music is used\n unless $game_system.map_bgm_in_battle\n # Play battle end ME\n $game_system.me_play($game_system.battle_end_me)\n # Return to BGM before battle started\n $game_system.bgm_play($game_temp.map_bgm)\n end \n # Initialize EXP, amount of gold, and treasure\n exp = 0\n gold = 0\n treasures = []\n # Loop\n for enemy in $game_troop.enemies\n # If enemy is not hidden\n unless enemy.hidden\n # Add EXP and amount of gold obtained\n exp += enemy.exp\n gold += enemy.gold\n # Determine if treasure appears\n if rand(100) < enemy.treasure_prob\n if enemy.item_id > 0\n treasures.push($data_items[enemy.item_id])\n end\n if enemy.weapon_id > 0\n treasures.push($data_weapons[enemy.weapon_id])\n end\n if enemy.armor_id > 0\n treasures.push($data_armors[enemy.armor_id])\n end\n end\n end\n end\n # Treasure is limited to a maximum of 6 items\n treasures = treasures[0..5]\n # Obtaining EXP\n for i in 0...$game_party.actors.size\n actor = $game_party.actors[i]\n if actor.cant_get_exp? == false\n last_level = actor.level\n actor.exp += exp\n if actor.level > last_level\n @status_window.level_up(i)\n end\n end\n end\n # Obtaining gold\n $game_party.gain_gold(gold)\n # Obtaining treasure\n for item in treasures\n case item\n when RPG::Item\n $game_party.gain_item(item.id, 1)\n when RPG::Weapon\n $game_party.gain_weapon(item.id, 1)\n when RPG::Armor\n $game_party.gain_armor(item.id, 1)\n end\n end\n # Make battle result window\n @result_window = Window_BattleResult.new(exp, gold, treasures)\n # Set wait count\n @phase5_wait_count = 100\n end", "def on_start\n game.local_speed = 0\n\n puts \"Analyzing map...\"\n Bwapi::BWTA.readMap\n Bwapi::BWTA.analyze\n puts \"Map data ready\"\n\n @state = AI::State.new(game)\n @strategy = ZergStrategy.new(state)\n rescue Exception => e\n puts \"-------------\"\n puts e.message\n puts e.backtrace\n puts \"-------------\"\n sleep 5\n exit\n end", "def start_phase4\n @a_remaining_pk.visible = false\n @e_remaining_pk.visible = false if $game_temp.trainer_battle\n @phase = 4\n $game_temp.battle_turn += 1\n for index in 0...$data_troops[@troop_id].pages.size\n page = $data_troops[@troop_id].pages[index]\n if page.span == 1\n $game_temp.battle_event_flags[index] = false\n end\n end\n @enemy_actions.clear\n @actor_actions.clear\n #Test IA\n @seed = @magneto.get_action\n @actor_actions += @magneto.get_action\n @enemy_actions += @magneto.get_action\n pc \"New seed : #{@seed}\"\n srand(@seed)\n #>Sécurité\n BattleEngine::set_actors(@actors)\n BattleEngine::set_enemies(@enemies)\n @actions = BattleEngine::_make_action_order(@actor_actions, @enemy_actions, @actors, @enemies)\n @phase4_step = 0\n launch_phase_event(4,true)\n end", "def main_begin\n create_spriteset\n # When comming back from battle we ensure that we don't have a weird transition by warping immediately\n if $game_temp.player_transferring\n transfer_player\n else\n $wild_battle.reset\n $wild_battle.load_groups\n end\n fade_in(@mbf_type || DEFAULT_TRANSITION, @mbf_param || DEFAULT_TRANSITION_PARAMETER)\n $quests.check_up_signal\n end", "def start_battle_phase\n log_info('Starting battle phase')\n # Add player actions\n @logic.add_actions(@player_actions)\n @player_actions.clear\n @logic.sort_actions\n @message_window.width = @visual.viewport.rect.width\n @message_window.wait_input = true\n # Tell to call udpdate_battle_phase on the next frame\n @next_update = :udpdate_battle_phase\n end", "def activate\n Game::STATSTRACKER.last_unit_activated = self\n\n if Game::STATSTRACKER.last_unit_activated.nationality == \"fr\"\n Game::STATSTRACKER.phasing_player = Game::FRENCH\n else\n Game::STATSTRACKER.phasing_player = Game::ALLIED\n end\n\n roll = Die.new.roll\n\n CRT.result(@name_symbol, roll).each do |action|\n # Handle morale loss results.\n if action[-1] == 'M'\n if action[-2] == 'F'\n Game::FRENCH.morale_loss(action[-3].to_i)\n else\n Game::ALLIED.morale_loss(action[-3].to_i)\n end\n # Handle casualty results.\n elsif action[-1] == 'C'\n if action[-2] == 'F'\n if @nationality == 'fr'\n casualty(action[0].to_i)\n else\n puts 'casualty on enemy'\n end\n else\n if @nationality == 'ac'\n puts 'casualty on self'\n else\n puts 'Casualty on enemy'\n end\n end\n end\n end\n end", "def phase_one\n\t#Intro\n\n\t\t@borneo.tribes.each do |tribe|\n\t\tputs \"Welcome #{tribe}\".green\n\t\tend\n\nprint_header(\"For Phase 1, you will now compete in 8 challenges for immunity. Good luck!\")\n\n\t8.times do\n\t\timmunity_challenge_losing_tribe = @borneo.immunity_challenge\n\t\tputs \"#{immunity_challenge_losing_tribe}\".green + \" has lost the immunity challenge and must now vote out 1 member.\"\n\t\tmember_voted_off = immunity_challenge_losing_tribe.tribal_council\n\tend\t\nend", "def update_battlephase\r\n # Branch according to phase\r\n case @phase\r\n when 1 # pre-battle phase\r\n update_phase1\r\n when 2 # party command phase\r\n update_phase2\r\n when 3 # actor command phase\r\n update_phase3\r\n when 4 # main phase\r\n update_phase4\r\n when 5 # after battle phase\r\n update_phase5\r\n end\r\n end", "def battletest_setup\r\n # Set up party for battle test\r\n $game_party.setup_battle_test_members\r\n # Set troop ID, can escape flag, and battleback\r\n $game_temp.battle_troop_id = $data_system.test_troop_id\r\n $game_temp.battle_can_escape = true\r\n $game_map.battleback_name = $data_system.battleback_name\r\n end", "def main_battledata\r\n # Initialize each kind of temporary battle data\r\n $game_temp.in_battle = true\r\n $game_temp.battle_turn = 0\r\n $game_temp.battle_event_flags.clear\r\n $game_temp.battle_abort = false\r\n $game_temp.battle_main_phase = false\r\n $game_temp.battleback_name = $game_map.battleback_name\r\n $game_temp.forcing_battler = nil\r\n # Initialize battle event interpreter\r\n $game_system.battle_interpreter.setup(nil, 0)\r\n end", "def process\n finish_games\n level_up\n warn_level_up\n start_games\n end", "def battle_end(result)\n # Clear in battle flag\n $game_temp.in_battle = false\n # Clear entire party actions flag\n $game_party.clear_actions\n # Remove battle states\n for actor in $game_party.actors\n actor.remove_states_battle\n end\n # Clear enemies\n $game_troop.enemies.clear\n # Call battle callback\n if $game_temp.battle_proc != nil\n $game_temp.battle_proc.call(result)\n $game_temp.battle_proc = nil\n end\n # Switch to map screen\n $scene = Scene_Map.new\n end", "def battle_end(result)\r\n # Clear in battle flag\r\n $game_temp.in_battle = false\r\n # Clear entire party actions flag\r\n $game_party.clear_actions\r\n # Remove battle states\r\n for actor in $game_party.actors\r\n actor.remove_states_battle\r\n end\r\n # Clear enemies\r\n $game_troop.enemies.clear\r\n # Call battle callback\r\n if $game_temp.battle_proc != nil\r\n $game_temp.battle_proc.call(result)\r\n $game_temp.battle_proc = nil\r\n end\r\n # Switch to map screen\r\n $scene = Scene_Map.new\r\n end", "def phase_one\n puts \"~~~~~PHASE 1~~~~~\".yellow\n 8.times do\n @borneo.immunity_challenge.tribal_council\n puts\n end\nend", "def start\n $game_variables[VAR] = {}\n $game_variables[VAR2] = {}\n @load_hash = nil\n @load_item_hash = nil\n @item_amounts = {}\n save_turn_data\n end", "def level_up_stat_refresh\n st = $game_temp.in_battle\n $game_temp.in_battle = false\n list0 = [max_hp, atk_basis, dfe_basis, ats_basis, dfs_basis, spd_basis]\n @level += 1 if @level < $pokemon_party.level_max_limit\n self.exp = exp_list[@level] if @exp < exp_list[@level].to_i\n self.exp = exp # Fix the exp amount\n hp_diff = list0[0] - @hp\n list1 = [max_hp, atk_basis, dfe_basis, ats_basis, dfs_basis, spd_basis]\n self.hp = (max_hp - hp_diff) if @hp > 0\n $game_temp.in_battle = st\n return [list0, list1]\n end", "def pbStartBattle(battle)\n @battle = battle\n @battlers = battle.battlers\n # checks whether to display integrated VS sequence\n @integratedVS = @battle.opponent && @battle.opponent.length < 2 && !EliteBattle.get(:smAnim) && EliteBattle.can_transition?(\"integratedVS\", @battle.opponent[0].trainer_type, :Trainer, @battle.opponent[0].name, @battle.opponent[0].partyID)\n # check if minor trainer transition is applied\n @minorAnimation = @battle.opponent && !@integratedVS && EliteBattle.can_transition?(\"minorTrainer\", @battle.opponent[0].trainer_type, :Trainer, @battle.opponent[0].name, @battle.opponent[0].partyID)\n # setup for initial vector configuration\n vec = EliteBattle.get_vector(:ENEMY)\n if @battle.opponent && @minorAnimation\n vec = EliteBattle.get_vector(:MAIN, @battle)\n vec[0] -= Graphics.width/2\n end\n @vector = Vector.new(*vec)\n @vector.battle = @battle\n # setup for all the necessary variable\n @firstsendout = true\n @inMoveAnim = false\n @lastcmd = [0, 0, 0, 0]\n @lastmove = [0, 0, 0, 0]\n @orgPos = nil\n @shadowAngle = 60\n @idleTimer = 0\n @idleSpeed = [40, 0]\n @animationCount = 1\n @showingplayer = true\n @showingenemy = true\n @briefmessage = false\n @lowHPBGM = false\n @introdone = false\n @dataBoxesHidden = false\n @sprites = {}\n @lastCmd = Array.new(@battlers.length,0)\n @lastMove = Array.new(@battlers.length,0)\n # viewport setup\n @viewport = Viewport.new(0, 0, Graphics.width, Graphics.height)\n @viewport.z = 99999\n # dex viewport\n @dexview = Viewport.new(0, 0, Graphics.width, Graphics.height)\n @dexview.z = 99999\n # sets up message sprite viewport\n @msgview = Viewport.new(0, 0, Graphics.width, Graphics.height)\n @msgview.z = 99999\n # Adjust player's side for screen size\n @traineryoffset = (Graphics.height - 320)\n # Adjust foe's side for screen size\n @foeyoffset = (@traineryoffset*3/4).floor\n # special Sun & Moon styled VS sequences\n if EliteBattle.get(:smAnim) && @battle.opponent\n @smTrainerSequence = SunMoonBattleTransitions.new(@viewport, @msgview, self, @battle.opponent[0])\n end\n if EliteBattle.get(:smAnim) && !@battle.opponent && @battle.pbParty(1).length == 1\n @smSpeciesSequence = SunMoonSpeciesTransitions.new(@viewport, @msgview, self, @battle.pbParty(1)[0])\n end\n # integrated VS sequence\n if @integratedVS\n @integratedVSSequence = IntegratedVSSequence.new(@viewport, self, @battle.opponent[0].trainer_type)\n end\n # loads in new battle background\n loadBackdrop\n # configures all the UI elements\n self.loadUIElements\n initializeSprites\n pbSetMessageMode(false)\n # start initial transition\n startSceneAnimation\n end", "def start\n get_rounds\n #print_rules\n #get_valid_moves\n @rules = Rules.new(@game_n)\n @rules.print_rules\n @moves = @rules.get_valid_moves\n end", "def pbTrainerBattleSuccess\r\n @battleEnd = true\r\n pbBGMPlay(pbGetTrainerVictoryME(@battle.opponent))\r\n end", "def generate_data(initial_levels)\n i = 0\n # Actors gain level\n for actor in $game_party.actors\n @actors_data.push (ResultActor.new(actor, initial_levels[i], \n [], 0))\n count = 0\n # Valid actor?\n if actor.cant_get_exp? == false\n difference = actor.level - @actors_initals_levels[i]\n # Check diff so can gain levels or exp\n if difference > 0\n \n # LEVEL UP.\n @actors_data.last.gained_levels = difference\n \n # SKILL GAIN UP.\n for lv in 0...difference\n # If it have skills learning\n for lea in $data_classes[actor.class_id].learnings\n if lea.level == @actors_initals_levels[i] + lv\n @actors_data.last.gained_skills.push (lea.skill_id)\n end\n end\n end\n end\n end\n i += 1\n end\n end", "def on_turn_start\n check_turn_start_effects\n end", "def phase_one\n introduction\n title \"Phase One\"\n losers = 0\n immune_members = []\n 8.times do\n losing_tribe = @borneo.tribes.shuffle.first\n puts \"The losing tribe is #{losing_tribe}\".red\n loser = losing_tribe.tribal_council()#no immune members\n puts \" The loser member is #{loser}\"\n losers += 1\n counting = 0\n @borneo.tribes.each{|tribe| counting += tribe.members.length}\n puts \" #{losers} gone!\"\n puts \" #{counting} remaining players\"\n end\nend", "def start\n set_player_name\n deal_cards\n show_flop\n player_turn\n dealer_turn\n end", "def start_game\n self.deal_tiles\n self.make_stock_card_deck\n self.assign_order\n self.bank = 100000 - (self.game_players.length*6000)\n self.deal_cash\n self.initialize_hotels\n self.save\n end", "def battletest_sceneswitch\r\n # Play battle start SE\r\n $game_system.se_play($data_system.battle_start_se)\r\n # Play battle BGM\r\n $game_system.bgm_play($game_system.battle_bgm)\r\n # Switch to battle screen\r\n $scene = Scene_Battle.new\r\n end", "def runner\n # code runner here\n welcome\n initial_round\n hit?\n display_card_total\nend_game\n\nend", "def runner\n # code runner here\n welcome\n initial_round\n hit?\n display_card_total\n end_game\nend", "def main_transition\r\n # Execute transition\r\n if $data_system.battle_transition == \"\"\r\n Graphics.transition(20)\r\n else\r\n Graphics.transition(40, \"Graphics/Transitions/\" +\r\n $data_system.battle_transition)\r\n end\r\n # Start pre-battle phase\r\n start_phase1\r\n end", "def update_phase4_step2\n if @active_battler.is_a?(Game_Actor)\n $game_temp.battle_actor_index = @active_battler.index\n @status_window.refresh\n end\n large_party_update_phase4_step2\n end" ]
[ "0.6479211", "0.6470125", "0.63796186", "0.6359165", "0.6202059", "0.6166204", "0.6138462", "0.6088859", "0.6065054", "0.6050809", "0.6048328", "0.5982012", "0.59757775", "0.5935659", "0.5852231", "0.5821629", "0.5807853", "0.57752", "0.57726574", "0.5761231", "0.57074636", "0.5696022", "0.5683585", "0.5673979", "0.5667997", "0.5649888", "0.56271124", "0.5623262", "0.561966", "0.5618338" ]
0.6731829
0
friendly duration to convert duration of song in min and sec
def friendly_duration min = @duration / 60 utes = 60 * min sec = @duration - utes return "#{min} Minutes and #{sec} seconds" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def duration\n (Time.mktime(0)+(tracks.map(&:duration).inject(:+) || 0)).strftime(\"%H:%M:%S\")\n end", "def duration\n duration = @file_metadata.duration.to_s\n\n # in format like: 0:02:43 (approx)\n if duration.match /(\\d{1,2}):(\\d{1,2}):(\\d{1,2})/\n hours = $1.strip.to_i\n minutes = $2.strip.to_i\n seconds = $3.strip.to_i\n\n if hours.to_i == 0\n return sprintf(\"%02d:%02d\", minutes, seconds)\n else\n return sprintf(\"%01s:%02d:%02d\", hours, minutes, seconds)\n end\n elsif duration.match /(\\d{1,2})\\.(\\d{1,2}) s/i\n # in format like: 23.41 s (approx)\n # $1 = 23\n # $2 = 41\n seconds = $1.strip.to_i\n return sprintf(\"%02d:%02d\", 0, seconds)\n end\n end", "def duration\n return unless seconds\n\n m = seconds / 60\n s = sprintf('%02d', (seconds % 60))\n\n \"#{m}:#{s}\"\n end", "def human_duration\n TiVoVideo.human_duration(duration)\n end", "def ms\n ((duration * 1000.0) + 0.4999).to_i\n end", "def duration\n raw_duration.to_f/time_scale\n end", "def duration\n raw_duration.to_f/time_scale\n end", "def duration_converter(ableton_value)\n\t\tif ableton_value.to_f < 4\n\t\t\t((1/ableton_value.to_f) * 4).to_i.to_s + 'n'\n\t\telse\n\t\t\t(ableton_value.to_f/4).to_i.to_s + 'm'\n\t\tend\n\tend", "def duration_to_sec(duration)\n seconds, minutes, hours = duration.split(\":\").reverse\n\n (hours.to_i * 60 * 60) + (minutes.to_i * 60) + seconds.to_i\nend", "def calc_duration(string)\n value = string.length.to_f*1/CHR_PER_SECOND\n number = case value\n when 0..MIN_DURATION then MIN_DURATION\n when MAX_DURATION..100 then MAX_DURATION\n else value\n end\n end", "def seconds\n (duration + 0.4999).to_i\n end", "def formatted_duration\n hours = self.duration / 60\n minutes = self.duration % 60\n if minutes == 0\n \"#{hours}h\"\n else\n \"#{hours}h#{minutes}min\"\n end\n end", "def human_length\n if duration_in_ms\n minutes = duration_in_ms / 1000 / 60\n seconds = (duration_in_ms / 1000) - (minutes * 60)\n sprintf(\"%d:%02d\", minutes, seconds)\n else\n \"Unknown\"\n end\n end", "def calculate_duration_string(duration)\n minutes = duration / 60\n seconds = duration - minutes * 60\n\n hours = minutes / 60\n minutes = minutes - hours * 60\n\n hr_string, min_string, sec_string = hours.to_s, minutes.to_s, seconds.to_s\n\n # hr_string = \"0\" + hr_string if hours < 10\n min_string = \"0\" + min_string if minutes < 10\n sec_string = \"0\" + sec_string if seconds < 10\n\n if hours === 0\n \"#{min_string} mins\"\n elsif hours === 1\n \"#{hr_string}hr #{min_string}mins\"\n else\n \"#{hr_string}hrs #{min_string}mins\"\n end\n\n end", "def durationInMinutes\n @duration/60.0 #Force floating pt.\n end", "def get_duration\n return \"#{self.duration.to_s.sub!('.', ',')} #{I18n.t(\"labels.datetime.hour_short\")}\"\n end", "def format_duration\n if duration % 60 != 0\n \"#{duration/60} hours #{duration%60} minutes\"\n else\n \"#{duration/60} hours\"\n end\n end", "def duration\n read_attribute(:duration) || audio_files.inject(0){|s,a| s + a.duration.to_i}\n end", "def calculate_duration(duration)\n [duration.to_i, 'seconds']\n end", "def time\n a=[1, 1000, 60000, 3600000]*2\n ms = duration\n \"%02d\" % (ms / a[3]).to_s << \":\" << \n \"%02d\" % (ms % a[3] / a[2]).to_s << \":\" << \n \"%02d\" % (ms % a[2] / a[1]).to_s #<< \".\" << \n #\"%03d\" % (ms % a[1]).to_s\n end", "def get_duration(fn)\n line = `ffmpeg -y -i #{fn} -vframes 1 -s 2x2 -ss 00:00:00 -an -vcodec png -f rawvideo /dev/null 2>&1`.split(/\\n/).grep(/Duration/).first\n # \" Duration: 02:20:01.2, start: 0.000000, bitrate: 699 kb/s\"\n time = /^\\s+Duration:\\s+([\\d:\\.]+)/.match(line)[1]\n # \"02:20:01.2\"\n h, m, s, ms = /^(\\d+):(\\d+):(\\d+)\\.(\\d+)$/.match(time)[1..4].map{|v| v.to_i}\n seconds = h * 60 * 60 + m * 60 + s\nend", "def get_video_duration\n # duration = Time.strptime((page.find('.ytp-time-duration').text),\"%H:%S\")\n label_time = (page.find('.ytp-time-duration').text).split(\":\")\n duration = label_time[0].to_i * 60 + label_time[1].to_i\n return duration\nend", "def duration_alternatice\n playerItem = AVPlayerItem.playerItemWithURL selectedVideoUrl\n\n duration = playerItem.duration\n CMTimeGetSeconds(duration)\n end", "def adjust_duration\n # convert minutes into seconds\n self.duration = duration.to_i * 60\n end", "def duration_formatted\n if self.duration.days > 0\n hours = self.duration.total / 60 / 60\n self.duration.format \"#{hours}:%M:%S\"\n else\n self.duration.format \"%H:%M:%S\"\n end\n end", "def mtime(duration)\n hour = (duration.to_i / 60).to_s\n min = (duration.to_i % 60).to_s\n \n duration = hour.rjust(2) + \":\" + min.rjust(2)\n \n return duration.gsub(/\\ /,\"0\")\n end", "def duration_unit\n expr = self.timing_duration.blank? ? \"\" : self.timing_duration.split.last\n @duration_unit.nil? ? expr : @duration_unit\n end", "def duration(start, stop)\n\ttoReturn = String.new\n\thrL = start[0,2].to_i\n\tminL = start[2,2].to_i\n\thrA = stop[0,2].to_i\n\tminA = stop[2,2].to_i\n\n\tif stop.to_i < start.to_i then\n\t\t#could wrap around midnight\n\t\thrA += 24\n\tend\n\ttempHr = hrA-hrL\n\ttempMin = minA-minL\n\tif tempMin < 0 then\n\t\ttempHr -=1\n\t\ttempMin += 60\n\tend\n\tif tempHr < 10 then\n\t\ttoReturn += \"0\"\n\tend\n\ttoReturn +=tempHr.to_s\n\tif tempMin < 10 then\n\t\ttoReturn += \"0\"\n\tend\n\ttoReturn += tempMin.to_s\n\treturn toReturn\nend", "def duration\n @duration ||= (range[1] - range[0]) / 1000.0\n end", "def get_route_duration\n return duration.div(3600)+\"Stunden\"+(duration % 60)+ \"Minuten\" \n end" ]
[ "0.7227589", "0.7099541", "0.70520407", "0.70438933", "0.70329434", "0.7001562", "0.7001562", "0.69681567", "0.6905934", "0.6903248", "0.6896035", "0.68781215", "0.6825291", "0.67613137", "0.6745352", "0.6715814", "0.67030704", "0.66356707", "0.662068", "0.65924704", "0.6583545", "0.65228", "0.65163296", "0.6508875", "0.64970374", "0.64867425", "0.646795", "0.64676005", "0.64503217", "0.6431011" ]
0.80674934
0
Draws a starlike shape with number 'points' of points. 'points' must be odd.
def star (points, length) raise "The star must have an odd number of points" if points % 2 == 0 points.times do line length turn (720.0/points).degrees end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_star(radius)\n points = 5\n triangle_base = radius * Math.tan(Math::PI / points)\n triangle = [\n [0, radius],\n [triangle_base / 2, 0],\n [-triangle_base / 2, 0],\n [0, radius]\n ]\n\n result = []\n (0...points).each do |i|\n result[i] = rotate(triangle, i * (2 * Math::PI / points))\n end\n\n result\nend", "def star(x, y, r1, r2, points, options={})\n cur_page.star(x, y, r1, r2, points, options)\n end", "def draw_part(pts)\r\n\r\n # Draw holes\r\n for i in 0..(pts.length-1)\r\n draw_circle(pts[i], $normVec, $holeRadius)\r\n end\r\n \r\n # Loop through points\r\n for i in 0..(pts.length-1)\r\n \r\n # Get adjacent points\r\n adjPts = GetAdjacentPts(pts, i)\r\n \r\n # Compute start and end angles\r\n sAngle = angle_between_point_xy([adjPts[0],adjPts[1]])\r\n eAngle = angle_between_point_xy([adjPts[1],adjPts[2]])\r\n \r\n # Make adjustments\r\n sAngle = sAngle - 0.5\r\n eAngle = eAngle - 0.5\r\n if(eAngle < sAngle) \r\n eAngle = eAngle + 2 \r\n end\r\n\r\n # Draw curves\r\n draw_curve(adjPts[1], $normVec, $xaxis, $outerRadius, sAngle * Math::PI, eAngle * Math::PI)\r\n\r\n # Draw lines \r\n draw_line(add_outer_radius(adjPts[0],$outerRadius,sAngle),add_outer_radius(adjPts[1],$outerRadius,sAngle))\r\n \r\n end\r\n \r\nend", "def star(*args, &blk)\n opts = normalize_style pop_style(args)\n case args.length\n when 2\n left, top = args\n points, outer, inner = 10, 100.0, 50.0\n when 5\n left, top, points, outer, inner = args\n else\n message = <<EOS\nWrong number of arguments. Must be one of:\n - star(left, top, [opts])\n - star(left, top, points, outer, inner, [opts])\nEOS\n raise ArgumentError, message\n end\n Shoes::Star.new(app, left, top, points, outer, inner, opts, &blk)\n end", "def polygon *points, color\n points << points.first\n points.each_cons(2) do |p1, p2|\n w.line(*p1, *p2, color)\n end\n end", "def plot_points(points = [])\n x = []\n y = []\n points << [(@parameters[:xhigh]-@parameters[:xlow])*2 + @parameters[:xhigh],\n (@parameters[:yhigh]-@parameters[:xlow])*2 + @parameters[:xhigh]] if points.empty?\n points.each do |p|\n x << p[0]\n y << p[1]\n end\n\n plot_generic(x, y, \"points pt 7\")\n end", "def draw2d(opengl_primitive, *points)\n end", "def line(points, colour)\n\tpoints.each do |point|\n\t paint(point[0], point[1], colour)\n\tend\n end", "def render_interp_spokes(shiftx, shifty, color, ibegin, iend, srep_index)\n\n ibegin.each_with_index do |p, i|\n if ($colored_spoke_indices.include? i and srep_index == 0)\n @app.stroke Color.blue\n else\n @app.stroke color\n end\n @app.line(p[0]+shiftx, p[1]+shifty, iend[i][0]+shiftx, iend[i][1]+shifty)\n end\n end", "def render_point_big(x, y, color)\n @app.stroke color\n @app.strokewidth 2\n @app.nofill\n @app.oval x-1,y-1, 2\n end", "def draw_piece(x,y,peice)\n co_x, co_y = get_co_x_y(x,y)\n stroke blue\n strokewidth 4\n fill black if peice.color.eql?('black')\n fill white if peice.color.eql?('white')\n oval top: co_y, left: co_x, radius: 40, center:true\nend", "def draw_star(blank, stars, b)\n case b\n when true\n \" \" + \" \" * blank + \"\\033[32mF\\033[0m\" * stars + \"\\n\"\n when false\n \" \" + \" \" * blank + \"\\033[31m*\\033[0m\" * stars + \"\\n\";\n end\nend", "def drawPathWithPoints(points, image:image)\n screenSize = self.view.frame.size\n UIGraphicsBeginImageContext(screenSize)\n context = UIGraphicsGetCurrentContext()\n image.drawInRect(CGRectMake(0, 0, screenSize.width, screenSize.height))\n\n CGContextSetLineCap(context, KCGLineCapRound)\n CGContextSetLineWidth(context, LINE_WIDTH)\n CGContextSetRGBStrokeColor(context, 0, 0, 1, 1)\n CGContextBeginPath(context)\n\n count = points.count\n point = points[0].CGPointValue\n CGContextMoveToPoint(context, point.x, point.y)\n 1.upto(count - 1) do |i|\n point = points.objectAtIndex(i).CGPointValue\n CGContextAddLineToPoint(context, point.x, point.y)\n end\n CGContextStrokePath(context)\n\n ret = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n ret\n end", "def bezier_curve(points, stroke_color = ChunkyPNG::Color::BLACK)\n points = ChunkyPNG::Vector(*points)\n case points.length\n when 0, 1 then return self\n when 2 then return line(points[0].x, points[0].y, points[1].x, points[1].y, stroke_color)\n end\n\n curve_points = []\n\n t = 0\n n = points.length - 1\n\n while t <= 100\n bicof = 0\n cur_p = ChunkyPNG::Point.new(0, 0)\n\n # Generate a float of t.\n t_f = t / 100.00\n\n cur_p.x += ((1 - t_f)**n) * points[0].x\n cur_p.y += ((1 - t_f)**n) * points[0].y\n\n for i in 1...points.length - 1\n bicof = binomial_coefficient(n, i)\n\n cur_p.x += (bicof * (1 - t_f)**(n - i)) * (t_f**i) * points[i].x\n cur_p.y += (bicof * (1 - t_f)**(n - i)) * (t_f**i) * points[i].y\n i += 1\n end\n\n cur_p.x += (t_f**n) * points[n].x\n cur_p.y += (t_f**n) * points[n].y\n\n curve_points << cur_p\n\n t += 1\n end\n\n curve_points.each_cons(2) do |p1, p2|\n line_xiaolin_wu(p1.x.round, p1.y.round, p2.x.round, p2.y.round, stroke_color)\n end\n\n self\n end", "def draw(x_position, y_position)\n $app.fill(rgb(255,255,255))\n\t$app.title(@number)\n #$app.oval(x_position * Game::PIECE_SIZE + Game::PIECE_SIZE, y_position * Game::PIECE_SIZE + Game::PIECE_SIZE, \n # Game::PIECE_SIZE * Game::PIECE_SCALE_FACTOR)\n #update the coordinates of the piece\n @x = x_position\n @y = y_position\n end", "def draw_point_id(point)\n draw_point(@points[point])\n end", "def draw\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]} \"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]} \"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]} \"\n puts \" | |\"\n end", "def add_point(color) \n @owner = color\n @points += 1 \n @image = @@images[@owner+@points.to_s]#Gosu::Image.new(@@gosu_window, 'media/grid/'+@points.to_s+'.'+@owner+'.png', true) if @points < 4\n if over_max?(@points, @x,@y, @width-1,@height-1)\n @points = 0 \n @array[@x-1][@y].add_point(color) if @x > 0\n @array[@x+1][@y].add_point(color) if @x < @width -1\n @array[@x][@y-1].add_point(color) if @y > 0\n @array[@x][@y+1].add_point(color) if @y < @height-1\n @image = @@images[@owner+@points.to_s]#Gosu::Image.new(@@gosu_window, 'media/grid/'+@points.to_s+'.'+@owner+'.png', true) \n end\n end", "def draw\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]}\"\n puts \" | |\"\n puts \"-----|-----|-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]}\"\n puts \" | |\"\n puts \"-----|-----|-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]}\"\n puts \" | |\"\n end", "def generate_points(num_points, width, height)\n points = [[width / 2, height / 2]]\n count = 0\n while points.length < num_points\n raise(\"sanity check failed\") if count > num_points * 2\n count += 1\n next_p = next_point(points.sample)\n if next_p[0].between?(0, width - 1) and next_p[1].between?(0, height - 1)\n points << next_p unless points.include?(next_p)\n else\n # debug\n puts \"#{next_p.inspect} out of bounds\"\n end\n end\n points\nend", "def draw\n opacity = 0.4\n @position.reverse.each do |pos|\n opacity *= 0.8\n Square.new(x: pos[0] * GRID_SIZE, y: pos[1] * GRID_SIZE, size: NODE_SIZE, color: @snake_color, z: @z) # the regular snake\n Square.new(x: pos[0] * GRID_SIZE, y: pos[1] * GRID_SIZE, size: NODE_SIZE, color: 'white' , opacity: opacity, z: @z + 1) # a lighting effect\n end\n end", "def draw\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]}\"\n puts \" | |\"\n end", "def draw\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]}\"\n puts \" | |\"\n end", "def draw\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]}\"\n puts \" | |\"\n end", "def draw\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]}\"\n puts \" | |\"\n end", "def draw\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]}\"\n puts \" | |\"\n end", "def render_spokes(cx, cy, type, spoke_length, spoke_direction, color)\n @app.stroke color\n u_p1 = spoke_direction[0]\n u_m1 = spoke_direction[1] \n @app.stroke color\n spoke_end_x_up1 = cx + spoke_length[0] * u_p1[0]\n spoke_end_y_up1 = cy - spoke_length[0] * u_p1[1]\n @app.line(cx, cy, spoke_end_x_up1, spoke_end_y_up1)\n spoke_end_x_up2 = cx + spoke_length[0] * u_m1[0]\n spoke_end_y_up2 = cy - spoke_length[0] * u_m1[1]\n @app.line(cx, cy, spoke_end_x_up2, spoke_end_y_up2)\n if type == 'end'\n u_0 = spoke_direction[2]\n spoke_end_x_u0 = cx + spoke_length[0] * u_0[0]\n spoke_end_y_u0 = cy - spoke_length[0] * u_0[1]\n @app.line(cx, cy, spoke_end_x_u0, spoke_end_y_u0)\n end\n end", "def draw_lines(lines, stars)\n def draw_line(size)\n puts '*' * size\n puts ' '\n end\n lines.times do\n draw_line(stars)\n end\nend", "def draw\n # snake head\n Image.new('img/SnakeHead.png',\n x: head[0] * GRID_SIZE,\n y: head[1] * GRID_SIZE)\n # snake tail\n @positions[0..-2].each do |position|\n Circle.new(x: position[0] * GRID_SIZE + GRID_SIZE / 2,\n y: position[1] * GRID_SIZE + GRID_SIZE / 2,\n radius: GRID_SIZE / 2 - 1,\n color: 'blue')\n end\n end", "def draw\n puts \"\"\n puts \" | |\"\n puts \" #{@squares[1]} | #{@squares[2]} | #{@squares[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[4]} | #{@squares[5]} | #{@squares[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{@squares[7]} | #{@squares[8]} | #{@squares[9]}\"\n puts \" | |\"\n puts \"\"\n end" ]
[ "0.68941706", "0.6551152", "0.63893414", "0.61078346", "0.60396767", "0.5977498", "0.59042567", "0.58733684", "0.5848147", "0.5779336", "0.5763726", "0.57607996", "0.5754366", "0.5734119", "0.5682888", "0.5666833", "0.5654966", "0.5626548", "0.5623242", "0.5614572", "0.56121117", "0.5607456", "0.5607456", "0.5607456", "0.5607456", "0.5607456", "0.5599141", "0.55880183", "0.55729556", "0.556979" ]
0.7765214
0
Draws a regular polygon with 'sides' sides, each of length 'length'
def polygon (sides, length) sides.times do line length turn (360.0/sides).degrees end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def polygon_vertices(sides, size)\n vertices = []\n sides.times do |i|\n angle = -2 * Math::PI * i / sides\n vertices << radians_to_vec2(angle) * size\n end\n return vertices\n end", "def polygon_vertices(sides, size)\n vertices = []\n sides.times do |i|\n angle = -2 * Math::PI * i / sides\n vertices << angle.radians_to_vec2() * size\n end\n return vertices\n end", "def polygon(x, y, r, sides, options={})\n cur_page.polygon(x, y, r, sides, options)\n end", "def hand length, width, offset, color\n coords = [\n 0, -offset,\n width, -offset-width,\n width, -length+width,\n 0, -length,\n -width, -length+width,\n -width, -offset-width\n ]\n \"poly#{coords.join(\",\")},fc:#{color},oc:#{color}\"\nend", "def polygon_vertices(sides, size)\n return [CP::Vec2.new(-size, size), CP::Vec2.new(size, size), CP::Vec2.new(size, -size), CP::Vec2.new(-size, -size)]\n end", "def draw\n puts \"* \" * @side_length\n (@side_length-2).times do # times loop will do something X number of times\n print \"*\"+(\" \"*(@side_length*2-3))+\"*\\n\"\n end\n puts \"* \" * @side_length\n end", "def closed_polygon(height, width, coords, dot_size = 0)\n return if @options[:underneath_color].nil?\n\n list = []\n\n list << [coords.first.first - 1 + (dot_size / 2.0), height - 3 - (dot_size / 2.0)]\n list << [coords.first.first - 1 + (dot_size / 2.0), coords.first.last]\n\n list << coords\n\n list << [coords.last.first + 1 - (dot_size / 2.0), coords.last.last]\n list << [coords.last.first + 1 - (dot_size / 2.0), height - 3 - (dot_size / 2.0)]\n\n @draw.stroke(@options[:underneath_color])\n @draw.fill(@options[:underneath_color])\n @draw.polygon( *list.flatten )\n end", "def draw\n\n puts \"*\" * @side_len\n @side_len.times do\n\n print \"*\" + ( \" \" * ( @side_len - 2) ) + \"* \\n\"\n\n end\n\n puts \"*\" * @side_len\n end", "def triangle(length_of_sides)\n spaces = length_of_sides\n accum_num = length_of_sides\n length_of_sides.times do\n puts \"#{' ' * (spaces - accum_num)}#{'*' * accum_num}\"\n accum_num -= 1\n end\nend", "def triangle(length_of_sides)\n spaces = length_of_sides\n accum_num = 1\n length_of_sides.times do\n puts \"#{' ' * (spaces - accum_num)}#{'*' * accum_num}\"\n accum_num += 1\n end\nend", "def draw\n glClear(GL_COLOR_BUFFER_BIT) # Pulizia dei buffer\n polygons = [] # Inizializzazione dell'insieme dei poligoni\n @genestring.each_slice(Polygon::SIZE) do |pstring| # Inizializzazione dei poligoni tramite estrazione dalla stringa del gene\n polygons << Polygon.new(pstring)\n end\n polygons.sort!{|x,y| x.weight <=> y.weight} # Ordinamento dei poligoni in base al loro peso\n polygons.each do |p|\n glColor4f(p.rgba[0], p.rgba[1], p.rgba[2], OPACITY) # Definisce il colore del poligono\n glBegin(GL_POLYGON)\n Polygon::VERTEX_NUM.times do |i| # Definisce i vertici del poligono\n glVertex2f(p.vertex_x[i], p.vertex_y[i])\n end\n glEnd\n end\n end", "def polygon *points, color\n points << points.first\n points.each_cons(2) do |p1, p2|\n w.line(*p1, *p2, color)\n end\n end", "def sides\n return @sides if defined?(@sides)\n\n @sides = []\n (-vertices.length...0).each do |i|\n @sides << Segment.new(vertices[i], vertices[i + 1])\n end\n\n @sides\n end", "def diamond(length)\n diamonds = (1..length).select { |num| num.odd? }\n shape_array = []\n spaces = length / 2\n length.times do |num|\n index = length / 2 - spaces.abs\n shape_array << \"#{' ' * spaces.abs}#{'*' * diamonds[index]}\"\n spaces -= 1\n end\n shape_array\nend", "def rectangle(length:, width:)\n # now does squares!!!!\n (length.to_f * width.to_f).round(2)\n end", "def side_length\n\t\ttop = (@num_sides - 2) * Math::PI\n\t\tangle = top / (2 * @num_sides)\n\t\t@side_length = 2 * Math.cos(angle)\n\tend", "def sample_polygon\n polygon(200, [[10.0, 10.0], [180.0, 20.0], [160.0, 150.0], [100.0, 50.0], [20.0,180.0]])\nend", "def polygon_image(vertices)\n box_image = Magick::Image.new(EDGE_SIZE * 2, EDGE_SIZE * 2) { self.background_color = 'transparent' }\n gc = Magick::Draw.new\n gc.stroke('red')\n gc.fill('plum')\n draw_vertices = vertices.map { |v| [v.x + EDGE_SIZE, v.y + EDGE_SIZE] }.flatten\n gc.polygon(*draw_vertices)\n gc.draw(box_image)\n return Gosu::Image.new(@window, box_image, false)\n end", "def polygon_image(vertices)\n box_image = Magick::Image.new(EDGE_SIZE * 2, EDGE_SIZE * 2) { self.background_color = \"transparent\" }\n gc = Magick::Draw.new\n gc.stroke(\"red\")\n gc.fill(\"plum\")\n draw_vertices = vertices.map { |v| [v.x + EDGE_SIZE, v.y + EDGE_SIZE] }.flatten\n gc.polygon(*draw_vertices)\n gc.draw(box_image)\n return Gosu::Image.new(box_image)\n end", "def star (points, length)\n raise \"The star must have an odd number of points\" if points % 2 == 0\n points.times do\n line length\n turn (720.0/points).degrees\n end\n end", "def draw_line(grids, length)\n grid(grids[0], grids[1]).bounding_box() do\n stroke_horizontal_line 0, 470*length, at: 5\n end\n end", "def perimeter(length, width)\r\n 2 * (length + width)\r\nend", "def calcPolyRadius(in_rad, num_sides)\r\n x = (Math::PI) / num_sides.to_f # number in radians\r\n return in_rad.to_f / (Math.cos(x))\r\n end", "def draw_arrow_y(x, y, length, arrow_colour, arrow_width, arrow_text)\r\n case \r\n when length < 0\r\n line(x, y, x, y-length, :stroke=>arrow_colour, \"stroke-width\"=>arrow_width)\r\n polyline([[x-5, y-length-10], [x, y-length], [x+5, y-length-10]],\r\n :stroke=>arrow_colour, \"stroke-width\"=>arrow_width, :fill=>arrow_colour)\r\n \r\n write(x+10, y-length/2, arrow_text, arrow_colour, \"start\")\r\n \r\n when length > 0\r\n line(x, y, x, y-length, :stroke=>arrow_colour, \"stroke-width\"=>arrow_width)\r\n polyline([[x-5, y-length+10], [x, y-length], [x+5, y-length+10]],\r\n :stroke=>arrow_colour, \"stroke-width\"=>arrow_width, :fill=>arrow_colour)\r\n \r\n write(x+10, y-length/2, arrow_text, arrow_colour, \"start\")\r\n \r\n when length == 0\r\n end\r\n end", "def perimeter(length, width)\n return (2 * (length + width))\nend", "def draw_line(turtle, length)\n new_xpos = turtle[XPOS] + length * DegLut.cos(turtle[ANGLE])\n new_ypos = turtle[YPOS] + length * DegLut.sin(turtle[ANGLE])\n line(turtle[XPOS], turtle[YPOS], new_xpos, new_ypos)\n [new_xpos, new_ypos, turtle[ANGLE]]\n end", "def points_for_polygon(x, y, r, sides, options={})\n cur_page.points_for_polygon(x, y, r, sides, options)\n end", "def perimeter(length,width)\n (2 * length) + (2 * width)\nend", "def initialize(*sides)\n @number_of_sides = sides.length\n end", "def drawPolygon(pointList, fillp=false, color=\"black\")\n @device.drawPolygon(pointList, fillp, color) ;\n end" ]
[ "0.66100395", "0.65690696", "0.6386554", "0.6319001", "0.62370664", "0.6221848", "0.6141547", "0.5912548", "0.58563143", "0.5826391", "0.57798064", "0.56751436", "0.5618167", "0.56066185", "0.55701274", "0.5523796", "0.5469449", "0.5460434", "0.5456068", "0.54495764", "0.5436883", "0.5344941", "0.53310287", "0.53070074", "0.530492", "0.52843547", "0.52754134", "0.52631265", "0.52562547", "0.5253591" ]
0.86559826
0
GET /call_histories/new GET /call_histories/new.json
def new @call_history = CallHistory.new respond_to do |format| format.html # new.html.erb format.json { render :json => @call_history } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @cocktail_history = CocktailHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cocktail_history }\n end\n end", "def new\n @operation_history = OperationHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @operation_history }\n end\n end", "def create\n @call_history = CallHistory.new(params[:call_history])\n\n respond_to do |format|\n if @call_history.save\n format.html { redirect_to(@call_history, :notice => 'Call history was successfully created.') }\n format.json { render :json => @call_history, :status => :created, :location => @call_history }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @call_history.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @category_history = CategoryHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @category_history }\n end\n end", "def new\n @buying_history = BuyingHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @buying_history }\n end\n end", "def new\n @historical = Historical.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @historical }\n end\n end", "def new\n @points_history = PointsHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @points_history }\n end\n end", "def new\n @query_history = QueryHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @query_history }\n end\n end", "def create\n @call_history = CallHistory.new(call_history_params)\n\n respond_to do |format|\n if @call_history.save\n format.html { redirect_to @call_history, notice: 'Call history was successfully created.' }\n format.json { render :show, status: :created, location: @call_history }\n else\n format.html { render :new }\n format.json { render json: @call_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @call = Call.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @call }\n end\n end", "def new\n @call = Call.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @call }\n end\n end", "def new\n @historial = Historial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @historial }\n end\n end", "def new\n @settlement_history = Settlement::History.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @settlement_history }\n end\n end", "def new\n @patient_history = PatientHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patient_history }\n end\n end", "def new\n @military_history = MilitaryHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @military_history }\n end\n end", "def create\n @cocktail_history = CocktailHistory.new(params[:cocktail_history])\n\n respond_to do |format|\n if @cocktail_history.save\n format.html { redirect_to @cocktail_history, notice: 'Cocktail history was successfully created.' }\n format.json { render json: @cocktail_history, status: :created, location: @cocktail_history }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cocktail_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @buying_history = BuyingHistory.new(params[:buying_history])\n\n respond_to do |format|\n if @buying_history.save\n format.html { redirect_to @buying_history, :notice => 'Buying history was successfully created.' }\n format.json { render :json => @buying_history, :status => :created, :location => @buying_history }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @buying_history.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @historical = Historical.new(params[:historical])\n\n respond_to do |format|\n if @historical.save\n format.html { redirect_to @historical, notice: 'Historical was successfully created.' }\n format.json { render json: @historical, status: :created, location: @historical }\n else\n format.html { render action: \"new\" }\n format.json { render json: @historical.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @operation_history = OperationHistory.new(params[:operation_history])\n\n respond_to do |format|\n if @operation_history.save\n format.html { redirect_to @operation_history, notice: 'Operation history was successfully created.' }\n format.json { render json: @operation_history, status: :created, location: @operation_history }\n else\n format.html { render action: \"new\" }\n format.json { render json: @operation_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @history = History.new(history_params)\n\n respond_to do |format|\n if @history.save\n format.html { redirect_to @history, notice: 'History was successfully created.' }\n format.json { render action: 'show', status: :created, location: @history }\n else\n format.html { render action: 'new' }\n format.json { render json: @history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @borrow_history = BorrowHistory.new(borrow_history_params)\n\n respond_to do |format|\n if @borrow_history.save\n format.html { redirect_to @borrow_history, notice: 'Borrow history was successfully created.' }\n format.json { render :show, status: :created, location: @borrow_history }\n else\n format.html { render :new }\n format.json { render json: @borrow_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @historial_odt = HistorialOdt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @historial_odt }\n end\n end", "def new\n @family_history = FamilyHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @family_history }\n end\n end", "def new\n @number_call = NumberCall.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @number_call }\n end\n end", "def new\n @recent_activity = RecentActivity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recent_activity }\n end\n end", "def create\n @category_history = CategoryHistory.new(params[:category_history])\n\n respond_to do |format|\n if @category_history.save\n format.html { redirect_to @category_history, notice: 'Category history was successfully created.' }\n format.json { render json: @category_history, status: :created, location: @category_history }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @change_history = ChangeHistory.new(params[:change_history])\n\n respond_to do |format|\n if @change_history.save\n format.html { redirect_to @change_history, notice: 'Change history was successfully created.' }\n format.json { render json: @change_history, status: :created, location: @change_history }\n else\n format.html { render action: \"new\" }\n format.json { render json: @change_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @activity = Activity.new\n @series = get_series('activities')\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @activity }\n end\n end", "def new\n @asset_allocation_history = AssetAllocationHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @asset_allocation_history }\n end\n end", "def new\n @quality_history = QualityHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @quality_history }\n end\n end" ]
[ "0.73561865", "0.7318957", "0.73150706", "0.72860867", "0.72328544", "0.7204265", "0.712156", "0.7100087", "0.70813495", "0.704776", "0.704776", "0.70431113", "0.6955238", "0.69174516", "0.68752", "0.68663263", "0.68354696", "0.6783719", "0.6766438", "0.67616564", "0.67515236", "0.6748344", "0.6705929", "0.6695396", "0.66860855", "0.66732126", "0.66516954", "0.6645271", "0.6644262", "0.6641065" ]
0.7945566
0
POST /call_histories POST /call_histories.json
def create @call_history = CallHistory.new(params[:call_history]) respond_to do |format| if @call_history.save format.html { redirect_to(@call_history, :notice => 'Call history was successfully created.') } format.json { render :json => @call_history, :status => :created, :location => @call_history } else format.html { render :action => "new" } format.json { render :json => @call_history.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n megam_rest.post_billedhistories(to_hash)\n end", "def create\n @call_history = CallHistory.new(call_history_params)\n\n respond_to do |format|\n if @call_history.save\n format.html { redirect_to @call_history, notice: 'Call history was successfully created.' }\n format.json { render :show, status: :created, location: @call_history }\n else\n format.html { render :new }\n format.json { render json: @call_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_to_historical(data_hash, title_number)\n\n response = rest_post_call($HISTORIAN_URL + '/' + title_number, data_hash.to_json)\n\n if (response.code != '200') then\n raise \"Failed to create the historical data: \" + response.body\n end\n\n return response.body\nend", "def index\n @call_histories = CallHistory.all\n end", "def new\n @call_history = CallHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @call_history }\n end\n end", "def create\n @operation_history = OperationHistory.new(params[:operation_history])\n\n respond_to do |format|\n if @operation_history.save\n format.html { redirect_to @operation_history, notice: 'Operation history was successfully created.' }\n format.json { render json: @operation_history, status: :created, location: @operation_history }\n else\n format.html { render action: \"new\" }\n format.json { render json: @operation_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @call_histories = CallHistory.all.page(params[:page]).per(20).order(\"id DESC\")\n end", "def create\n @cocktail_history = CocktailHistory.new(params[:cocktail_history])\n\n respond_to do |format|\n if @cocktail_history.save\n format.html { redirect_to @cocktail_history, notice: 'Cocktail history was successfully created.' }\n format.json { render json: @cocktail_history, status: :created, location: @cocktail_history }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cocktail_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @buying_history = BuyingHistory.new(params[:buying_history])\n\n respond_to do |format|\n if @buying_history.save\n format.html { redirect_to @buying_history, :notice => 'Buying history was successfully created.' }\n format.json { render :json => @buying_history, :status => :created, :location => @buying_history }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @buying_history.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @reading_history = @user.reading_histories.build(params[:reading_history])\n\n respond_to do |format|\n if @reading_history.save\n format.html { redirect_to '/', notice: 'new reading history was successfully added.' }\n format.json { render json: @reading_history, status: :created, location: @reading_history }\n else\n format.html { render action: \"new\" }\n format.json { render json: @reading_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @historial = Historial.new(historial_params)\n\n respond_to do |format|\n if @historial.save\n format.html { redirect_to @historial, notice: 'Historial was successfully created.' }\n format.json { render :show, status: :created, location: @historial }\n else\n format.html { render :new }\n format.json { render json: @historial.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @borrow_history = BorrowHistory.new(borrow_history_params)\n\n respond_to do |format|\n if @borrow_history.save\n format.html { redirect_to @borrow_history, notice: 'Borrow history was successfully created.' }\n format.json { render :show, status: :created, location: @borrow_history }\n else\n format.html { render :new }\n format.json { render json: @borrow_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @historical = Historical.new(params[:historical])\n\n respond_to do |format|\n if @historical.save\n format.html { redirect_to @historical, notice: 'Historical was successfully created.' }\n format.json { render json: @historical, status: :created, location: @historical }\n else\n format.html { render action: \"new\" }\n format.json { render json: @historical.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @aircraft = Aircraft.find(params[:aircraft_id])\n @aircraft_history = @aircraft.aircraft_histories.create(params[:aircraft_history])\n redirect_to aircraft_path(@aircraft)\n end", "def create\n @histroal = Historial.new(histroal_params)\n\n respond_to do |format|\n if @histroal.save\n format.html { redirect_to @histroal, notice: 'Historial was successfully created.' }\n format.json { render :show, status: :created, location: @histroal }\n else\n format.html { render :new }\n format.json { render json: @histroal.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @historic = Historic.new(historic_params)\n\n respond_to do |format|\n if @historic.save\n format.html { redirect_to @historic, notice: 'Historic was successfully created.' }\n format.json { render :show, status: :created, location: @historic }\n else\n format.html { render :new }\n format.json { render json: @historic.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_call_to_db(bridged_call_request, twilio_response, success=false)\n return -1 if bridged_call_request.isTestCall\n\n @history.insert({\n hotel_id: bridged_call_request.hotelId,\n hotel_phone: PhoneNumber.new(bridged_call_request.hotelPhone).to_s,\n sales_agent_id: bridged_call_request.salesAgentId,\n sales_agent_phone: PhoneNumber.new(bridged_call_request.salesAgentPhone).to_s,\n customer_phone: PhoneNumber.new(bridged_call_request.customerPhone).to_s,\n lega_sid: (twilio_response.nil?) ? SecureRandom.hex : twilio_response.sid,\n direction: 'OUTBOUND', \n connected: success,\n timestamp: DateTime.now\n })\n end", "def set_call_history\n @call_history = CallHistory.find(params[:id])\n end", "def set_call_history\n @call_history = CallHistory.find(params[:id])\n end", "def create\n @purchased_history = PurchasedHistory.new(purchased_history_params)\n\n respond_to do |format|\n if @purchased_history.save\n format.html { redirect_to @purchased_history, notice: 'Purchased history was successfully created.' }\n format.json { render :show, status: :created, location: @purchased_history }\n else\n format.html { render :new }\n format.json { render json: @purchased_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @bhistory = Bhistory.new(bhistory_params)\n\n respond_to do |format|\n if @bhistory.save\n format.html { redirect_to @bhistory, notice: 'Bhistory was successfully created.' }\n format.json { render :show, status: :created, location: @bhistory }\n else\n format.html { render :new }\n format.json { render json: @bhistory.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @service_history = ServiceHistory.new(service_history_params)\n\n if @service_history.save\n render json: @service_history, status: :created\n else\n render json: @service_history.errors, status: :unprocessable_entity\n end\n end", "def create\n @comm_history = CommHistory.new(comm_history_params)\n respond_to do |format|\n if @comm_history.save\n @inspection = @comm_history.try(:bid).try(:inspection)\n create_documents\n format.html { redirect_to @comm_history, notice: 'Bids follow up was successfully created.' }\n format.json { render :show, status: :created, location: @comm_history }\n else\n format.html { render :new }\n format.json { render json: @comm_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @history = History.new(history_params)\n\n respond_to do |format|\n if @history.save\n format.html { redirect_to @history, notice: 'History was successfully created.' }\n format.json { render action: 'show', status: :created, location: @history }\n else\n format.html { render action: 'new' }\n format.json { render json: @history.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @call = Call.new(call_params)\n\n respond_to do |format|\n if @call.save\n record_call_activity\n format.html { redirect_to @call, notice: 'Call was successfully created.' }\n format.json { render :show, status: :created, location: @call }\n else\n format.html { render :new }\n format.json { render json: @call.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @customer = Customer.find(params[:customer_id])\n @historial = @customer.historial.new(historial_params)\n\n respond_to do |format|\n if @historial.save\n format.html { redirect_to @customer}\n format.json { render :show, status: :created, location: @historial }\n else\n format.html { render :new }\n format.json { render json: @historial.errors, status: :unprocessable_entity }\n end\n end\n end", "def fetch_history\n service_response = Economy::Transaction::FetchHistory.new(params).perform\n render_api_response(service_response)\n end", "def create\n @historial_odt = HistorialOdt.new(params[:historial_odt])\n\n respond_to do |format|\n if @historial_odt.save\n format.html { redirect_to @historial_odt, notice: 'Historial odt was successfully created.' }\n format.json { render json: @historial_odt, status: :created, location: @historial_odt }\n else\n format.html { render action: \"new\" }\n format.json { render json: @historial_odt.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # FIXME: If failed to create history, dont create concrete_history.\n concrete_history = concrete_history(\n history_params[:concrete_history].permit(concrete_history_params)\n )\n @history = History.new(\n card_id: history_params[:card_id],\n concrete_history: concrete_history\n )\n\n respond_to do |format|\n if @history.save\n format.html { redirect_to @history, notice: 'History was successfully created.' }\n format.json {\n render 'show', format: 'json', handlers: 'jbuilder', status: :created\n }\n else\n format.html { render :new }\n format.json { render json: @history.errors, status: :unprocessable_entity }\n end\n end\n end", "def call_history_params\n params.require(:call_history).permit(:phone_number, :status, :body, :ivr_result, :user_app_id, :duration, :call_sid, :retry, :ok_at, :message, :from, :call_status)\n end" ]
[ "0.6913032", "0.68269676", "0.65884405", "0.6504495", "0.62446177", "0.6155739", "0.6145603", "0.6055951", "0.6036452", "0.6005945", "0.6004015", "0.5976509", "0.59706104", "0.5963356", "0.5925099", "0.59073436", "0.5869398", "0.586792", "0.586792", "0.58383095", "0.58157104", "0.5807481", "0.579996", "0.57980525", "0.57945335", "0.5789259", "0.5778269", "0.577589", "0.5765109", "0.5754671" ]
0.6866001
1
PUT /call_histories/1 PUT /call_histories/1.json
def update @call_history = CallHistory.find(params[:id]) respond_to do |format| if @call_history.update_attributes(params[:call_history]) format.html { redirect_to(@call_history, :notice => 'Call history was successfully updated.') } format.json { head :ok } else format.html { render :action => "edit" } format.json { render :json => @call_history.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n respond_to do |format|\n if @call_history.update(call_history_params)\n format.html { redirect_to @call_history, notice: 'Call history was successfully updated.' }\n format.json { render :show, status: :ok, location: @call_history }\n else\n format.html { render :edit }\n format.json { render json: @call_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_call_history\n @call_history = CallHistory.find(params[:id])\n end", "def set_call_history\n @call_history = CallHistory.find(params[:id])\n end", "def create\n @call_history = CallHistory.new(params[:call_history])\n\n respond_to do |format|\n if @call_history.save\n format.html { redirect_to(@call_history, :notice => 'Call history was successfully created.') }\n format.json { render :json => @call_history, :status => :created, :location => @call_history }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @call_history.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @call_history = CallHistory.new(call_history_params)\n\n respond_to do |format|\n if @call_history.save\n format.html { redirect_to @call_history, notice: 'Call history was successfully created.' }\n format.json { render :show, status: :created, location: @call_history }\n else\n format.html { render :new }\n format.json { render json: @call_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @cocktail_history = CocktailHistory.find(params[:id])\n\n respond_to do |format|\n if @cocktail_history.update_attributes(params[:cocktail_history])\n format.html { redirect_to @cocktail_history, notice: 'Cocktail history was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cocktail_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @operation_history = OperationHistory.find(params[:id])\n\n respond_to do |format|\n if @operation_history.update_attributes(params[:operation_history])\n format.html { redirect_to @operation_history, notice: 'Operation history was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @operation_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @call_histories = CallHistory.all\n end", "def post_to_historical(data_hash, title_number)\n\n response = rest_post_call($HISTORIAN_URL + '/' + title_number, data_hash.to_json)\n\n if (response.code != '200') then\n raise \"Failed to create the historical data: \" + response.body\n end\n\n return response.body\nend", "def set_historic\n @historic = Historic.find(params[:id])\n end", "def update\n @historical = Historical.find(params[:id])\n\n respond_to do |format|\n if @historical.update_attributes(params[:historical])\n format.html { redirect_to @historical, notice: 'Historical was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @historical.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @calllog.update(calllog_params)\n format.html { redirect_to @calllog, notice: 'Calllog was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @calllog.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @call.update(call_params)\n record_call_activity\n format.html { redirect_to @call, notice: 'Call was successfully updated.' }\n format.json { render :show, status: :ok, location: @call }\n else\n format.html { render :edit }\n format.json { render json: @call.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @historial = Historial.find(params[:id])\n\n respond_to do |format|\n if @historial.update_attributes(params[:historial])\n format.html { redirect_to @historial.cartucho, notice: 'Historial was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @historial.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @history.update(history_params)\n @histories = History.includes_all\n @success_message = '更新しました'\n else\n @errors = @history.errors\n end\n render 'finish_posting'\n end", "def update\n @service_history = ServiceHistory.find(params[:id])\n\n if @service_history.update(service_history_params)\n head :no_content\n else\n render json: @service_history.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @comm_history.update(comm_history_params)\n @inspection = @comm_history.try(:bid).try(:inspection)\n create_documents\n format.html { redirect_to @comm_history, notice: 'Bids follow up was successfully updated.' }\n format.json { render :show, status: :ok, location: @comm_history }\n else\n format.html { render :edit }\n format.json { render json: @comm_history.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @call_history = CallHistory.find(params[:id])\n @call_history.destroy\n\n respond_to do |format|\n format.html { redirect_to(call_histories_url) }\n format.json { head :ok }\n end\n end", "def update\n @buying_history = BuyingHistory.find(params[:id])\n\n respond_to do |format|\n if @buying_history.update_attributes(params[:buying_history])\n format.html { redirect_to @buying_history, :notice => 'Buying history was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @buying_history.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n megam_rest.post_billedhistories(to_hash)\n end", "def update\n @call_log = CallLog.find(params[:id])\n\n respond_to do |format|\n if @call_log.update_attributes(params[:call_log])\n format.html { redirect_to(@call_log, :notice => t(:call_log_updated)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @call_log.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @historic.update(historic_params)\n format.html { redirect_to @historic, notice: 'Historic was successfully updated.' }\n format.json { render :show, status: :ok, location: @historic }\n else\n format.html { render :edit }\n format.json { render json: @historic.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_cow_history\n @cow_history = CowHistory.find(params[:id])\n end", "def set_cash_in_history\n @cash_in_history = CashInHistory.find(params[:id])\n end", "def update\n respond_to do |format|\n if @historial.update(historial_params)\n format.html { redirect_to @historial, notice: 'Historial was successfully updated.' }\n format.json { render :show, status: :ok, location: @historial }\n else\n format.html { render :edit }\n format.json { render json: @historial.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @historial.update(historial_params)\n format.html { redirect_to @historial, notice: 'Historial was successfully updated.' }\n format.json { render :show, status: :ok, location: @historial }\n else\n format.html { render :edit }\n format.json { render json: @historial.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @history = History.find(params[:id])\n respond_to do |format|\n\n @history.update(status: 0)\n format.html { redirect_to @history, notice: 'Released successfully!!' }\n\n end\n end", "def update\n respond_to do |format|\n if @history.update(history_params)\n format.html { redirect_to @history, notice: 'History was successfully updated.' }\n format.json {\n render 'show', format: 'json', handlers: 'jbuilder', status: :ok\n }\n else\n format.html { render :edit }\n format.json { render json: @history.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @roll_call.update(roll_call_params)\n format.html { redirect_to @roll_call, notice: 'Roll call was successfully updated.' }\n format.json { render :show, status: :ok, location: @roll_call }\n else\n format.html { render :edit }\n format.json { render json: @roll_call.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @roll_call.update(roll_call_params)\n format.html { redirect_to @roll_call, notice: 'Roll call was successfully updated.' }\n format.json { render :show, status: :ok, location: @roll_call }\n else\n format.html { render :edit }\n format.json { render json: @roll_call.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.67747474", "0.6175938", "0.6175938", "0.60669214", "0.603132", "0.60191584", "0.58745474", "0.5856504", "0.5852422", "0.5807749", "0.5779311", "0.57534075", "0.5723495", "0.56670433", "0.566321", "0.5640793", "0.56088865", "0.5605495", "0.55925053", "0.55913585", "0.55880916", "0.5578719", "0.55733854", "0.5570615", "0.5555754", "0.5555754", "0.5552049", "0.5545713", "0.5545235", "0.5545235" ]
0.67264265
1
DELETE /call_histories/1 DELETE /call_histories/1.json
def destroy @call_history = CallHistory.find(params[:id]) @call_history.destroy respond_to do |format| format.html { redirect_to(call_histories_url) } format.json { head :ok } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @call_history.destroy\n respond_to do |format|\n format.html { redirect_to call_histories_url, notice: 'Call history was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @calllog.destroy\n respond_to do |format|\n format.html { redirect_to calllogs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @cocktail_history = CocktailHistory.find(params[:id])\n @cocktail_history.destroy\n\n respond_to do |format|\n format.html { redirect_to cocktail_histories_url }\n format.json { head :no_content }\n end\n end", "def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end", "def destroy\n @operation_history = OperationHistory.find(params[:id])\n @operation_history.destroy\n\n respond_to do |format|\n format.html { redirect_to operation_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @history.destroy\n respond_to do |format|\n format.html { redirect_to histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @unified_history.destroy\n respond_to do |format|\n format.html { redirect_to unified_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @visit_history.destroy\n respond_to do |format|\n format.html { redirect_to visit_histories_url, notice: 'Visit history was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @item_history.destroy\n respond_to do |format|\n format.html { redirect_to bmet_item_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @call_log = CallLog.find(params[:id])\n @call_log.destroy\n\n respond_to do |format|\n format.html { redirect_to(call_logs_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @historial = Historial.find(params[:id])\n @historial.destroy\n\n respond_to do |format|\n format.html { redirect_to historials_url }\n format.json { head :ok }\n end\n end", "def destroy\n @call = Call.find(params[:id])\n @call.destroy\n\n respond_to do |format|\n format.html { redirect_to calls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @call = Call.find(params[:id])\n @call.destroy\n\n respond_to do |format|\n format.html { redirect_to calls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @call = Call.find(params[:id])\n @call.destroy\n\n respond_to do |format|\n format.html { redirect_to calls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @thermostat_history.destroy\n respond_to do |format|\n format.html { redirect_to thermostat_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request_call = RequestCall.find(params[:id])\n @request_call.destroy\n\n respond_to do |format|\n format.html { redirect_to request_calls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @call.destroy\n respond_to do |format|\n format.html { redirect_to calls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @call.destroy\n respond_to do |format|\n format.html { redirect_to calls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @query_history = QueryHistory.find(params[:id])\n @query_history.destroy\n\n respond_to do |format|\n format.html { redirect_to query_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @history = History.find(params[:id])\n @history.destroy\n\n respond_to do |format|\n format.html { redirect_to(histories_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @category_history = CategoryHistory.find(params[:id])\n @category_history.destroy\n\n respond_to do |format|\n format.html { redirect_to category_histories_url }\n format.json { head :ok }\n end\n end", "def destroy\n @roll_call.destroy\n respond_to do |format|\n format.html { redirect_to roll_calls_url, notice: 'Roll call was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @roll_call.destroy\n respond_to do |format|\n format.html { redirect_to roll_calls_url, notice: 'Roll call was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @laptop_history.destroy\n respond_to do |format|\n format.html { redirect_to laptop_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @buying_history = BuyingHistory.find(params[:id])\n @buying_history.destroy\n\n respond_to do |format|\n format.html { redirect_to buying_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @call_status.destroy\n respond_to do |format|\n format.html { redirect_to call_statuses_url, notice: 'Call status was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @call.destroy\n respond_to do |format|\n format.html { redirect_to calls_url, notice: CALL_DESTROYED }\n format.json { head :no_content }\n end\n end", "def destroy\n @change_history = ChangeHistory.find(params[:id])\n @change_history.destroy\n\n respond_to do |format|\n format.html { redirect_to change_histories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @purchased_history.destroy\n respond_to do |format|\n format.html { redirect_to purchased_histories_url, notice: 'Purchased history was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @patient_history = PatientHistory.find(params[:id])\n @patient_history.destroy\n\n respond_to do |format|\n format.html { redirect_to patient_histories_url }\n format.json { head :no_content }\n end\n end" ]
[ "0.75089866", "0.71301395", "0.70385665", "0.70287645", "0.692862", "0.69078153", "0.6886769", "0.6863259", "0.68320537", "0.6798473", "0.6761191", "0.67441875", "0.67441875", "0.67441875", "0.67212963", "0.6694847", "0.6682744", "0.6682744", "0.66731834", "0.6657334", "0.664398", "0.6634081", "0.6634081", "0.66274405", "0.66200155", "0.66093016", "0.6602118", "0.66012657", "0.6598869", "0.6590378" ]
0.76666313
0
Recurisvely scan `database_dir` for blast databases.
def scan_databases_dir database_dir = config[:database_dir] list = %x|blastdbcmd -recursive -list #{database_dir} -list_outfmt "%f %t %p %n %l %d" 2>&1| list.each_line do |line| name = line.split(' ')[0] next if multipart_database_name?(name) self << Database.new(*line.split(' ')) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def checkpoints\n db_pattern = \"#{sql_connection.escape(@db_backup)}\".gsub(\"_\", \"\\\\_\").gsub(\"%\", \"\\\\%\")\n # TODO: this should be quoted properly.\n result = sql_connection.execute(\"SHOW DATABASES LIKE '#{db_pattern}\\\\_%'\")\n prefix_length = @db_backup.length+1\n sql_connection.normalize_result(result).map {|db| db[prefix_length..-1] }\n end", "def find_db\n log_debug\n file_name = 'com.plexapp.plugins.library.db'\n # for dev it looks in current directory first\n # can add locations as we find them. only the first match is used\n paths = [ '.',\n '/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases',\n \"#{ENV['HOME']}/Library/Application Support/Plex Media Server/Plug-in Support/Databases\"\n ]\n db = ''\n \n paths.each do |path|\n if File.directory? path\n if File.exists? \"#{path}/#{file_name}\"\n # first match is used\n if db == ''\n db = \"#{path}/#{file_name}\"\n end\n end\n end\n end\n \n if db !~ /\\w/\n puts \"error : could not find db file \\\"#{file_name}\\\" \"\n exit 2\n end\n \n log_debug \"find_db using \\\"#{db}\\\"\"\n return db\n end", "def try_databases\n db = Database.new(application_root, config, settings)\n db.configure\n end", "def list_dbs(db=nil)\n db &&= db.gsub(/[\\\\\\']/){\"\\\\#{$&}\"}\n query(db ? \"show databases like '#{db}'\" : \"show databases\").map(&:first)\n end", "def get_dbs\n if @target_config['DBS'].empty?\n if @target_config['VERSION'].scan(/./)[0].to_i < 5 and not @target_config['VERSION'].nil?\n # MySQL < 5\n print_error(\"DB Version: #{@target_config['VERSION']}\")\n print_error(\"There is no information_schema to query.....\")\n print_error(\"Unable to enumerate databases for MySQL < 5\")\n elsif @target_config['VERSION'].scan(/./)[0].to_i >= 5 or @target_config['VERSION'].nil?\n # MySQL >= 5\n results = error_basic_inject('select count(schema_name) from information_schema.schemata')\n if results.nil?\n results = error_basic_inject('select count(distinct(db)) from mysql.db')\n dbs_count = 0 unless not results.nil?\n print_error(\"Unable to get database count, flying a bit blind!\") unless not results.nil?\n dbs_count = results unless results.nil?\n print_status(\"Requesting #{dbs_count} Databases Names....\") unless results.nil?\n else\n dbs_count = results\n print_status(\"Requesting #{dbs_count} Databases Names....\")\n end\n dbz=[]\n count = 0\n while not results.nil?\n results = error_basic_inject(\"select schema_name from information_schema.schemata limit #{count},1\")\n pad = ' ' * (results.size + 25) unless results.nil? or results == ''\n pad = ' ' * 50 if results.nil? or results == ''\n print \"\\r(#{count})> #{results}#{pad}\".cyan unless results == ''\n dbz << results unless results == ''\n count = count.to_i + 1\n end\n print_line(\"\")\n if dbz.empty?\n print_line(\"\")\n print_error(\"Unable to get any database names!\")\n print_error(\"Lack of privileges?\")\n print_status(\"Possible Solutions include:\")\n print_caution(\"A) Become HR's best friend by updating the code and sending him a copy\")\n print_caution(\"B) Tweak Settings and try things again\")\n print_caution(\"C) Be a bawz and do it manually\")\n print_line(\"\")\n else\t\n @target_config['DBS'] = dbz\n print_good(\"DBS: #{dbz.join(', ').sub(/, $/, '')}\")\n end\n end\n else\n print_good(\"DBS: #{@target_config['DBS'].join(', ').sub(/,$/, '')}\")\n end\n end", "def get_dbs\n if @target_config['VERSION'].scan(/./)[0].to_i < 5 and not @target_config['VERSION'].nil?\n # MySQL < 5\n print_error(\"DB Version: #{@target_config['VERSION']}\")\n print_error(\"There is no information_schema to query.....\")\n print_error(\"Unable to enumerate databases for MySQL < 5\")\n elsif @target_config['VERSION'].scan(/./)[0].to_i >= 5 or @target_config['VERSION'].nil?\n # MySQL v5+\n results = union_basic_inject($config['INJECTOR']['MYSQL']['UNION']['VULN_COLUMN'].to_i, 'select count(schema_name) from information_schema.schemata')\n if results.nil?\n results = union_basic_inject($config['INJECTOR']['MYSQL']['UNION']['VULN_COLUMN'].to_i, 'select count(distinct(db)) from mysql.db') #This usually needs privs, but maybe in some case if info schema is blocked\n dbs_count=0 unless not results.nil?\n print_error(\"Unable to get database count, flying a bit blind!\") unless not results.nil?\n dbs_count=results unless results.nil?\n print_status(\"Requesting #{dbs_count} Databases Names....\") unless results.nil?\n else\n dbs_count=results\n print_status(\"Requesting #{dbs_count} Databases Names....\")\n end\n dbz=[]\n count=0\n while not results.nil?\n results = union_basic_inject($config['INJECTOR']['MYSQL']['UNION']['VULN_COLUMN'].to_i, \"select schema_name from information_schema.schemata limit #{count},1\")\n pad = ' ' * (results.size + 10) unless results == '' or results.nil?\n pad = ' ' * 50 if results.nil?\n print \"\\r(#{count})> #{results}#{pad}\".cyan unless results == ''\n dbz << results unless results == ''\n count = count.to_i + 1\n end\n print_line(\"\")\n if dbz.empty?\n print_line(\"\")\n print_error(\"Unable to get any database names!\")\n print_error(\"Lack of privileges?\")\n print_status(\"Possible Solutions include:\")\n print_caution(\"A) Become HR's best friend by updating the code and sending him a copy\")\n print_caution(\"B) Tweak Settings and try things again\")\n print_caution(\"C) Be a bawz and do it manually\")\n print_line(\"\")\n else\t\n @target_config['DBS'] += dbz\n @target_config['DBS'].uniq! unless @target_config['DBS'].nil? or @target_config['DBS'].size == 0\n print_good(\"DBS: #{dbz.join(', ').sub(/, $/, '')}\") unless dbz.nil? or dbz.size == 0\n print_good(\"DBS: #{@target_config['DBS'].join(', ').sub(/, $/, '')}\") if dbz.nil? or dbz.size == 0 and not @target_config['DBS'].nil?\n end\n end\n end", "def load_database(app_name, instance_name)\n app_config = RailsPwnerer::Config[app_name, instance_name]\n db_name, db_user, db_pass = app_config[:db_name], app_config[:db_user], app_config[:db_pass]\n \n Dir.chdir app_config[:backup_path] do\n # find the latest dump and load it in\n dump_file = Dir.glob(\"db/#{app_name}.#{instance_name}_*\").max\n unless dump_file\n dump_file = Dir.glob(\"db/#{app_name}.*\").max\n end\n Kernel.system \"mysql -u#{db_user} -p#{db_pass} #{db_name} < #{dump_file}\"\n end\n end", "def databases\n get '_all_dbs'\n end", "def all_dbs\n @conn.query({url_path: \"_all_dbs\", method: :get})\n end", "def wDumpAllDatabase()\n puts \"Back up commencing...\"\n Dir.chdir('/Users/jeydurai')\n system('start_mongodump.bat')\n end", "def make_blast_databases\n unformatted_fastas.each do |file, sequence_type|\n make_blast_database(file, sequence_type)\n end\n end", "def dump_all_databases(num)\n timez = t.strftime(\"%m.%d.%Y\")\n logs = RESULTS + @host\n logdir = logs + '/dumps/'\n Dir.mkdir(logs) unless File.exists?(logs)\n Dir.mkdir(logdir) unless File.exists?(logdir)\n print_status(\"Attempting to dump ALL available databases....\")\n query = @db_connection.query('SHOW DATABASES;')\n query.each do |x|\n # Skip default databases to avoid issues with mysqldump --all-databases in newer clients\n # While longer this helps ensure cleaner DB Dump files as well\n # MYSQLDUMP Error: Couldn't read status information for table general_log (...)\n if not x[0] =~ /^mysql$|^information_schema$|^test$|^database$/i\n print_status(\"Dumping '#{x[0]}'....\")\n if num.to_i == 1\n system(\"`which mysqldump` --host=#{@host} --user=#{@user} --password=#{@pass} #{x[0]} --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick -C --dump-date | gzip -c > #{logdir}#{x[0]}_#{timez}.sql.gz\")\n else\n system(\"`which mysqldump` --host=#{@host} --user=#{@user} --password=#{@pass} #{x[0]} --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick -C --dump-date > #{logdir}#{x[0]}_#{timez}.sql\")\n end\n else\n print_caution(\"Skipping default database '#{x[0]}'...\")\n end\n end\n print_status(\"Database Dumping Completed!\")\n print_status(\"Dump file(s) saved to: #{logdir}\")\n system(\"ls -lua #{logdir} | grep --color -E '.sql.gz|.sql'\")\n end", "def xDumpAllDatabase()\n puts \"Back up commencing...\"\n Dir.chdir('/Users/jeydurai')\n system('start_mongodump.bat')\n end", "def get_db\n # we want to check a couple levels 2011-09-28 \n unless @db\n unless File.exists? @file\n 3.times do |i|\n @file = \"../#{@file}\"\n break if File.exists? @file\n end\n end\n end\n @db ||= DB.new @file\n end", "def databases\n CouchRest.get \"#{@uri}/_all_dbs\"\n end", "def scan()\n scanDir() ;\n scanLogs() ;\n end", "def makedb\n # only scan the first few hundred entries\n n = 100\n # check if the query is a nucl or prot seq\n query_file = Bio::FastaFormat.open(@query)\n count_p=0\n count=0\n query_file.take(n).each do |entry|\n count_p += 1 if entry.isProt?\n count += 1\n end\n if count_p > count*0.9\n @query_is_prot = true\n else\n @query_is_prot = false\n end\n\n # check if the target is a nucl or prot seq\n target_file = Bio::FastaFormat.open(@target)\n count_p=0\n count=0\n target_file.take(n).each do |entry|\n count_p += 1 if entry.isProt?\n count += 1\n end\n if count_p > count*0.9\n @target_is_prot = true\n else\n @target_is_prot = false\n end\n # construct the output database names\n @query_name = File.basename(@query).split('.')[0..-2].join('.')\n @target_name = File.basename(@target).split('.')[0..-2].join('.')\n\n # check if the databases already exist in @working_dir\n make_query_db_cmd = \"#{@makedb_path} -in #{@query}\"\n make_query_db_cmd << \" -dbtype nucl \" if !@query_is_prot\n make_query_db_cmd << \" -dbtype prot \" if @query_is_prot\n make_query_db_cmd << \" -title #{query_name} \"\n make_query_db_cmd << \" -out #{@working_dir}/#{query_name}\"\n db_query = \"#{query_name}.nsq\" if !@query_is_prot\n db_query = \"#{query_name}.psq\" if @query_is_prot\n if !File.exists?(\"#{@working_dir}/#{db_query}\")\n make_db = Cmd.new(make_query_db_cmd)\n make_db.run\n if !make_db.status.success?\n msg = \"BLAST Error creating database:\\n\" +\n make_db.stdout + \"\\n\" +\n make_db.stderr\n raise RuntimeError.new(msg)\n end\n end\n\n make_target_db_cmd = \"#{@makedb_path} -in #{@target}\"\n make_target_db_cmd << \" -dbtype nucl \" if !@target_is_prot\n make_target_db_cmd << \" -dbtype prot \" if @target_is_prot\n make_target_db_cmd << \" -title #{target_name} \"\n make_target_db_cmd << \" -out #{@working_dir}/#{target_name}\"\n\n db_target = \"#{target_name}.nsq\" if !@target_is_prot\n db_target = \"#{target_name}.psq\" if @target_is_prot\n if !File.exists?(\"#{@working_dir}/#{db_target}\")\n make_db = Cmd.new(make_target_db_cmd)\n make_db.run\n if !make_db.status.success?\n raise RuntimeError.new(\"BLAST Error creating database\")\n end\n end\n @databases = true\n [@query_name, @target_name]\n end", "def scanDir()\n suffix = \".config.json\"\n Dir.glob(\"#{@logBaseDir}/*/*#{suffix}\") {|path|\n #basename = File.basename(path, \".config.json\") ;\n basename = path.gsub(/^#{@logBaseDir}\\//,'').gsub(/#{suffix}$/,'') ;\n p [:basename, basename] ;\n @basenameList.push(basename) ;\n }\n @basenameList.sort!() ;\n return @basenameList ;\n end", "def get_all_databases\n databases = ::MySQL::Database.find_all\n names = []\n databases.each do |database|\n names << database.name\n end\n names\n end", "def determine_databases\n db = @info[:db] = {}\n mysql_count_cmd = 'find /var/lib/mysql* -maxdepth 0 -type d ' \\\n '2>/dev/null|wc -l'\n db[:count] = @shell.query('DB_MYSQL_COUNT', mysql_count_cmd)\n db[:count] = db[:count].to_i\n\n mysql_size_cmd = \"du -s /var/lib/mysql 2>/dev/null|awk '{print $1}'\"\n db[:size] = @shell.query('DB_MYSQL_SIZE', mysql_size_cmd)\n db[:size] = db[:size].to_i\n end", "def all_dbs\n request.method = :get\n request.uri = '_all_dbs'\n Couchdbtools.execute(request)\n end", "def create_default_databases()\n # Create subfolder for databases if needed.\n dir = \"./databases\"\n Dir.mkdir(dir) unless Dir.exist?(dir)\n # TODO: sanity check: if db-file exist, create copy first, make sure the\n # name of the copy makes it highly unlikely to match an already existing\n # file, e.g. current epoch.\n # TODO: Create DBs\nend", "def set_blast_dbs\n @blast_dbs = {\n :blastn => Quorum.blastn,\n :blastx => Quorum.blastx,\n :tblastn => Quorum.tblastn,\n :blastp => Quorum.blastp\n }\n end", "def run_backups\n puts \"Starting backups...\" if options[:verbose]\n for database in database_list\n Dir.chdir(temp_directory)\n name, user, pass = database.split(\",\")\n password = pass.strip.empty? ? '' : \"-p#{pass.strip}\"\n tgz_filename = \"#{name}.#{DATE}.#{TIME}.tgz\"\n # stop the slave if necessary\n puts \"Stopping the slave...\" if options[:verbose] && options[:slave]\n `mysql -u #{user} #{password} --execute='stop slave;'` if options[:slave]\n \n # switch to the current database and backup each table\n tables = `echo 'show tables' | mysql -u #{user} #{password} #{name} | grep -v Tables_in_`\n for table in tables\n table.strip!\n puts \"Backing up table #{table}...\" if options[:verbose]\n filename = \"#{table}.#{DATE}.#{TIME}.sql\"\n `mysqldump --add-drop-table --allow-keywords -q -c -u #{user} #{password} #{name} #{table} > #{filename}`\n end\n \n # restart the slave if necessary\n puts \"Restarting the slave...\" if options[:verbose] && options[:slave]\n `mysql -u #{user} #{password} --execute='start slave;'` if options[:slave]\n \n # zip it up and move it to the backup directory\n puts \"Completed backups, zipping it up...\" if options[:verbose]\n `tar -zcvf #{backup_directory}/#{tgz_filename} *`\n puts \"Cleaning up...\" if options[:verbose]\n Dir.chdir(backup_directory)\n `rm -rf #{temp_directory}`\n \n # copy it to any remote hosts if needed\n scp_results(tgz_filename) unless scp_hosts.empty?\n puts \"And we're done!\" if options[:verbose]\n end\n end", "def databases_list(options = {})\n if block_given?\n Pagination::Cursor.new(self, :databases_list, options).each do |page|\n yield page\n end\n else\n get('databases', options)\n end\n end", "def database(dbname=nil, &block)\n dbname ||= database_name\n if dbname then\n repository dbname, &block\n else\n yield\n end\n end", "def stage_database(db_names, admin_password, db_user_name, db_password)\n sql_command = \"\"\n \n db_names.each do |name|\n db_name = ActiveRecord::Base.configurations[name]['database']\n sql_command += \"drop database if exists #{db_name}; \" << \n \"create database #{db_name}; grant all privileges on #{db_name}.* \" << \n \"to #{db_user_name}@localhost identified by \\'#{db_password}\\';\"\n ActiveRecord::Base.configurations[name]['username'] = db_user_name\n ActiveRecord::Base.configurations[name]['password'] = db_password\n end\n\n if (!File.exist?(\"#{APP_ROOT}/tmp/stage.sql\"))\n File.open(\"#{APP_ROOT}/tmp/stage.sql\", \"w\") do |file|\n file.print sql_command\n end\n end\n\n # back up the original database.yml file just in case\n File.copy(\"#{APP_ROOT}/config/database.yml\", \n \"#{APP_ROOT}/config/database.yml.sample\") if !File.exist?(\"#{APP_ROOT}/config/database.yml.sample\")\n \n dbconfig = File.read(\"#{APP_ROOT}/config/database.yml\")\n dbconfig.gsub!(/username:.*/, \"username: #{db_user_name}\")\n dbconfig.gsub!(/password:.*/, \"password: #{db_password}\")\n \n File.open(\"#{APP_ROOT}/config/database.yml\", \"w\") do |file|\n file.print dbconfig\n end\n\n if system %(mysql -h localhost -u root --password=#{admin_password} < tmp/stage.sql)\n puts \"Updated config/database.yml and staged the database based on your settings\"\n File.delete(\"tmp/stage.sql\") if File.file?(\"tmp/stage.sql\")\n else\n puts \"Staging was not performed. Check console for errors. It is possible that 'mysql' executable was not found.\"\n end\n end", "def locate_updatedb(rootdir='/', stored_file=nil, timeout=(60 * 60 * 15))\n return true if @updatedb\n #\n # TODO\n # ignoring some directories might be usefull for better performance\n # ignore:\n # /proc\n # /sys\n # /dev (maybe)\n # good idea? yes/no\n if stored_file.nil?\n tmp_timeout = 20 # more timeout?\n #cmd = \"find #{rootdir} -type f -exec ls -l {} \\\\;\" + \" 2>/dev/null\"\n cmd = \"find #{rootdir} -wholename '/proc' -prune -o -wholename '/sys' -prune -o -wholename '/dev' -prune -o -ls\" + \" 2>/dev/null\"\n print_debug(\"Creating an UpdateDB - this might take a while...... running command: #{cmd}\")\n db = shell_command_token(cmd, tmp_timeout, timeout)\n else\n db = ::File.read(stored_file)\n end\n @updatedb={}\n db.each_line do | line |\n values = line.split(\" \")\n if values[2].to_s.match(/^(d|c|b|l|s|-)/) && values[10].to_s.match(/^(\\/|.\\/)/)\n path = values[10..values.length].join(\" \")\n metadata = values[2..9].join(\" \")\n @updatedb[path] = metadata\n elsif values[2].to_s.match(/^(d|c|b|l|s|-)/) && values[9].to_s.match(/^(\\/|.\\/)/)\n path = values[9..values.length].join(\" \")\n metadata = values[2..8].join(\" \")\n @updatedb[path] = metadata\n elsif values[0].to_s.match(/^(d|c|b|l|s|-)/) && values[8].to_s.match(/^(\\/|.\\/)/)\n # in case using -exec ls -l {} instead of -ls\n path = values[8..values.length].join(\" \")\n metadata = values[0..7].join(\" \")\n @updatedb[path] = metadata\n else\n #puts \"[ERROR]\\t#{line}\"\n # TODO/TOCHECK\n end\n end\n true\n end", "def databases\n arrayCommand( \"show db\", DictItemArray, RESPONSE_DATABASES_FOLLOW, RESPONSE_NO_DATABASES )\n end", "def databases\n arrayCommand( \"show db\", DictItemArray, RESPONSE_DATABASES_FOLLOW, RESPONSE_NO_DATABASES )\n end" ]
[ "0.6015338", "0.58854556", "0.58433646", "0.5831027", "0.5795348", "0.5715606", "0.56379694", "0.56295365", "0.55671465", "0.55611074", "0.5555896", "0.55507284", "0.54095995", "0.5355876", "0.5353444", "0.53380674", "0.5321399", "0.5237198", "0.52360785", "0.5203658", "0.520302", "0.5198603", "0.51756656", "0.51196766", "0.5065186", "0.5031806", "0.5018391", "0.5000068", "0.4997688", "0.4997688" ]
0.8481656
0
Returns an Array of FASTA files that may require formatting, and the type of sequence contained in each FASTA. > unformatted_fastas => [['/foo/bar.fasta', :nulceotide], ...]
def unformatted_fastas list = [] database_dir = config[:database_dir] Find.find database_dir do |file| next if File.directory?(file) next if Database.include? file if probably_fasta? file sequence_type = guess_sequence_type_in_fasta file if [:protein, :nucleotide].include?(sequence_type) list << [file, sequence_type] end end end list end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_unaligned_sequences \n answer = Array.new \n self.genomic_aligns.each do |piece| \n sequence = piece.get_slice.seq\n fas = Bio::FastaFormat.new(Bio::Sequence::NA.new(sequence).to_fasta(piece.genomic_align_id))\n answer.push(fas) \n end \n return answer \n end", "def process_input_seqs! fnames\n seq_lengths = {}\n clean_fnames = []\n\n fnames.each do |fname|\n clean_fname = fname + \"_aai_clean\"\n clean_fnames << clean_fname\n File.open(clean_fname, \"w\") do |f|\n Object::ParseFasta::SeqFile.open(fname).each_record do |rec|\n unless bad_seq? rec.seq\n header =\n annotate_header clean_header(rec.header),\n File.basename(fname)\n\n seq_lengths[header] = rec.seq.length\n\n f.puts \">#{header}\\n#{rec.seq}\"\n end\n end\n end\n end\n\n [seq_lengths, clean_fnames]\n end", "def fasta_parse(fasta_string)\n fasta_parts = fasta_string.split('>')[1..-1]\n no_pfamid = fasta_parts.map { |x| x.split(',')[1].chomp() }\n seqs = no_pfamid.map { |s| {:genus => s.lines.first.chomp(), :seq => s.split(\"\\n\")[1..-1].join.gsub(\"\\n\",'') } }\n seqs.sort_by! { |h| h[:genus] } #makes sure to sort alphabetically, allowing us to build partitioned character matrices\n return seqs\nend", "def guess_sequence_type_in_fasta(file)\n sample = File.read(file, 32768)\n sequences = sample.split(/^>.+$/).delete_if { |seq| seq.empty? }\n sequence_types = sequences.map {|seq| Sequence.guess_type(seq)}.uniq.compact\n (sequence_types.length == 1) && sequence_types.first\n end", "def all_names(format)\n alts = alternates.select { |a| a.include? format }.flatten\n alts.any? ? alts : [format]\n end", "def alignment_strings(start=0,stop=self.length,organisms=nil) \n answer = Array.new \n self.genomic_aligns.each do |contig|\n if organisms.nil? # if no organisms were specified to limit the results\n sequence = contig.aligned_sequence(start,stop)\n answer << Bio::FastaFormat.new(Bio::Sequence::NA.new(sequence).to_fasta(contig.find_organism.name)) unless sequence.nil?\n else\n if organisms.include?(contig.find_organism)\n sequence = contig.aligned_sequence(start,stop)\n answer << Bio::FastaFormat.new(Bio::Sequence::NA.new(sequence).to_fasta(contig.find_organism.name))\n end\n end \n end\n return answer \n end", "def enum_fasta_files_in_subtree(directory)\n #extend Fasta_parser_collection\n Fasta_parser_collection.enum_files_in_subtree(directory) do |filename|\n if filename.match(/\\.f(na|asta|as|aa)$/) # extend possible suffixes\n yield filename\n end\n end\nend", "def create_sequence_entries\n File.open(file_name('contigs.fasta'), 'r').each(sep=\"\\n>\") do |line|\n header, sequence = line.chomp.split( \"\\n\", 2 )\n .map { |x| x.gsub( /\\n|>/, '' ) }\n \n Sequence.create(header: header, sequence: sequence)\n end\nend", "def fasta_with_lengths(fasta_fn)\n tmp_file = register_new_tempfile('positive_peaks_formatted.fa')\n File.open(fasta_fn){|f|\n f.each_line.slice_before(/^>/).each{|hdr, *lines|\n seq = lines.map(&:strip).join\n tmp_file.puts \"#{hdr.strip}:#{seq.size}\"\n tmp_file.puts seq\n }\n }\n tmp_file.close\n tmp_file.path\nend", "def formats\n @formats ||= Dir[File.join(path, \"#{name}.{otf,svg,ttf,woff,woff2,eot}\")].map {|file| File.extname(file)[1..-1] }.sort\n end", "def extract_files(an_array)\n files = []\n an_array.reverse.each do |a_file|\n next if a_file.empty?\n next if a_file.start_with?(' ')\n break if a_file.start_with?('Date:')\n files << a_file # .split(\"\\t\").last\n end\n return files.sort\nend", "def remove_initial_and_format_change \n @reformated_array = []\n array_of_parse_files.each do |info|\n if !info[0].include?(\"|\") && !info[0].include?(\",\")\n info.map! {|element| element.split(\" \")}\n info.each {|element| element.slice!(-4)} \n @reformated_array << info\n elsif info[0].include?(\"|\")\n info.map! {|element| element.split(\" | \")}\n info.each {|element| element.slice!(-4)} \n @reformated_array << info\n else\n @reformated_array << info\n end\n end\nend", "def read_fastq\n\n seq_name = nil\n seq_fasta = nil\n seq_qual = nil\n comments = nil\n\n reading = :fasta\n\n if !@fastq_file.eof\n\n begin\n #read four lines\n name_line = @fastq_file.readline.chomp\n seq_fasta = @fastq_file.readline.chomp\n name2_line = @fastq_file.readline.chomp\n seq_qual = @fastq_file.readline.chomp\n \n \n # if there is no qual, but there is a fasta\n if seq_qual.empty? && !seq_fasta.empty?\n seq_qual = 'D'*seq_fasta.length\n end\n\n\n # parse name\n if name_line =~ /^@\\s*([^\\s]+)\\s*(.*)$/\n # remove comments\n seq_name = $1\n comments=$2\n else\n raise \"Invalid sequence name in #{name_line}\"\n end\n\n # parse fasta\n seq_fasta.strip! if !seq_fasta.empty?\n\n # parse qual_name\n\n if !seq_name.nil? && !seq_qual.empty?\n\n @num_seqs += 1\n\n if @qual_to_phred\n seq_qual=seq_qual.each_char.map{|e| (@to_phred.call(e.ord))}\n\n if !@qual_to_array\n seq_qual=seq_qual.join(' ')\n end\n end\n\n end\n rescue EOFError\n raise \"Bad format in FastQ file\"\n end\n end\n\n return [seq_name,seq_fasta,seq_qual,comments]\n end", "def format ary\n #buff = Array.new\n buff = Array.new(ary.size)\n return buff if ary.nil? || ary.size == 0\n\n # determine width based on number of files to show\n # if less than sz then 1 col and full width\n #\n # ix refers to the index in the complete file list, wherease we only show 60 at a time\n ix=0\n ctr=0\n ary.each do |f|\n ## ctr refers to the index in the column\n #ind=$IDX[ix]\n ind = get_shortcut(ix)\n mark=\" \"\n mark=\" * \" if $selected_files.index(ary[ix])\n\n if $long_listing\n begin\n unless File.exist? f\n last = f[-1]\n if last == \" \" || last == \"@\" || last == '*'\n stat = File.stat(f.chop)\n end\n else\n stat = File.stat(f)\n end\n f = \"%10s %s %s\" % [readable_file_size(stat.size,1), date_format(stat.mtime), f]\n rescue Exception => e\n f = \"%10s %s %s\" % [\"?\", \"??????????\", f]\n end\n end\n\n s = \"#{ind}#{mark}#{f}\"\n\n buff[ctr] = s\n\n ctr+=1\n ix+=1\n end\n return buff\nend", "def rich_sequence_object_from_file(path_to_sequence, sequence_format = nil)\n sequence_format = guess_sequence_format(path_to_sequence) if sequence_format.nil?\n rich_sequence_objects = Array.new\n case sequence_format\n when :fasta\n Bio::FlatFile.open(Bio::FastaFormat, path_to_sequence).each_entry do |entry|\n rich_sequence_objects << entry unless entry.entry_id.nil? || entry.entry_id.empty?\n end\n when :genbank\n Bio::FlatFile.open(Bio::GenBank, path_to_sequence).each_entry do |entry|\n rich_sequence_objects << entry unless entry.entry_id.nil? || entry.entry_id.empty?\n end\n when :embl\n Bio::FlatFile.open(Bio::EMBL, path_to_sequence).each_entry do |entry|\n rich_sequence_objects << entry unless entry.entry_id.nil? || entry.entry_id.empty?\n end\n end\n if rich_sequence_objects.size > 1\n return rich_sequence_objects\n else\n return rich_sequence_objects.first\n end\nend", "def readFormants(file)\n f1, f2 = [], []\n\n fs = []\n\n File.open(file, \"r\") do |f|\n # 9 useless lines\n 9.times { f.gets }\n while !f.eof?\n #Each block starts with the number of formants found\n f.gets\n how_many = f.gets.to_i\n #We are only interested in the first two formants\n f1 = f.gets.to_f\n f.gets\n f2 = f.gets.to_f\n (1+(how_many-2)*2).times { f.gets}\n fs << [f1,f2]\n end\n end\n\n fs\nend", "def read_fasta(fasta_file)\r\n fasta_name = \"\"\r\n fasta_seqs = {}\r\n seq = \"\"\r\n File.open(fasta_file).each do |line|\r\n if !(line.nil?)\r\n if line.start_with? \">\"\r\n seq = \"\"\r\n fasta_name = line.chomp.split(\">\")[1]\r\n elsif\r\n seq = seq + line.chomp\r\n fasta_seqs[fasta_name] = seq\r\n end\r\n end\r\n end\r\n return fasta_seqs\r\nend", "def available_formats\n formats = self.items.collect {|i| i.item_type }\n return formats.compact\n end", "def rich_sequence_to_fasta(path_to_sequence, output_sequence)\n require 'tempfile'\n sequence_format = guess_sequence_format(path_to_sequence)\n case sequence_format\n when :genbank\n rich_sequence_object = Bio::FlatFile.open(Bio::GenBank, path_to_sequence).first\n when :embl\n rich_sequence_object = Bio::FlatFile.open(Bio::EMBL, path_to_sequence).first\n end\n biosequence = rich_sequence_object.to_biosequence\n \n case output_sequence\n when String\n file_from_biosequence(output_sequence, :fasta, biosequence)\n when Tempfile\n file_from_biosequence(output_sequence.path, :fasta, biosequence)\n end\nend", "def check_csfasta(fasta)\n # length is the total read lengh + 2\n # cat *.csfasta | perl -ne 'next if /^#/;$i++;if ($i%2==0) {print unless \n # length($_)==52} else {print unless /^>\\d+_\\d+\\_\\d+\\_(F|R)(3|5)(-P2)*\\n$/}'\n # | more\n length = get_bp_length(fasta) + 2\n i = 0\n output = \"\"\n File.open(fasta).each do |l|\n next if /^#/.match(l)\n i = i + 1\n if ( i % 2 == 0 ) && ( l.size != length ) &&\n !/^>\\\\d+_\\\\d+_\\\\d+_(F|R)(3|5)(-P2)*\\n$/.match(l)\n output = output + l\n end\n end\n output\n end", "def find_apf( path_and_file = self.file_name_and_contents.path_and_file)\n match_apf = []\n regexp = /^t([^ \\#]+)( *$| )/\n File_name_and_contents.new( path_and_file ).contents.each do |line|\n if line.match(regexp) != nil\n if line.match(regexp)[1] != nil \n match_apf << ( self.file_name_and_contents.path_and_file.sub(/\\/.+/, '') + '/' + line.match(regexp)[1].chomp + '.apf' ) \n end\n end\n end\n match_apf\n end", "def add_fasta(fasta)\n\t\t\t# Create MidiFormat object and push it onto array\n\t\t\t@midi_format_array.push(Bio::MidiFormat.new(fasta))\n\n\t\t\t# Increment number of sequences\n\t\t\t@num_midi_seqs += 1\n\t\tend", "def fasta\n chars = 60\n lines = (length / chars.to_f).ceil\n defline = \">#{accession} #{title}\"\n seqlines = (1..lines).map {|i| to_s[chars * (i - 1), chars]}\n [defline].concat(seqlines).join(\"\\n\")\n end", "def fastafile_to_fastastring(filename)\n oa = Bio::Alignment::OriginalAlignment.new()\n #load sequences from file\n Bio::FlatFile.open(Bio::FastaFormat, filename) { |ff|\n #store sequence from file\n ff.each_entry { |x| oa.add_seq(x.seq,x.entry_id) }\n }\n return oa.output(:fasta)\n\n end", "def get_aa_array(initial_position = 0)\n @aa_array = []\n require_sequence = @dna_sequence[initial_position..-1].tr('-','N')\n base_array = []\n require_sequence.each_char {|base| base_array << base}\n while (base_array.length>=3) do\n base_3= \"\"\n 3.times{base_3 += base_array.shift}\n @aa_array<< amino_acid_2(base_3)\n end\n end", "def make_blast_databases\n unformatted_fastas.each do |file, sequence_type|\n make_blast_database(file, sequence_type)\n end\n end", "def files_array(files)\n return [] unless files\n files.is_a?(Array) ? files : pattern_to_filelist(files.to_s)\n end", "def fasta2anchors(input_file, anchor_length, sequencing_type, output_file)\n\t\tcounter = -1\n\t\tname, mate, seq = nil, nil, nil\n\t\t\n\t\tFile.open(output_file, 'w') do |output|\t\n\t\t\tFile.open(input_file, 'r').each do |line|\n\t\t\t\tcounter += 1\n\t\t\t\t\n\t\t\t\tif counter % 2 == 0\n\t\t\t\t\tif sequencing_type == 'se'\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s, 1\n\t\t\t\t\telse\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s.split('/')\n\t\t\t\t\tend\n\t\t\t\telsif counter % 2 == 1\n\t\t\t\t\tseq = line.strip\t\n\n\t\t\t\t\tname_A = \"#{name}_#{mate}_#{seq}_A\"\n\t\t\t\t\tname_B = \"#{name}_#{mate}_#{seq}_B\"\n\t\t\t\t\t\n\t\t\t\t\tseq_A = seq[0..anchor_length - 1]\n\t\t\t\t\tseq_B = seq[-anchor_length..-1]\n\n\t\t\t\t\toutput.puts [\">#{name_A}\", seq_A, \">#{name_B}\", seq_B].join(\"\\n\")\n\t\t\t\t\tname, mate, seq = nil, nil, nil\n\t\t\t\t\tcounter = -1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def fasta2anchors(input_file, anchor_length, sequencing_type, output_file)\n\t\tcounter = -1\n\t\tname, mate, seq = nil, nil, nil\n\t\t\n\t\tFile.open(output_file, 'w') do |output|\t\n\t\t\tFile.open(input_file, 'r').each do |line|\n\t\t\t\tcounter += 1\n\t\t\t\t\n\t\t\t\tif counter % 2 == 0\n\t\t\t\t\tif sequencing_type == 'se'\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s, 1\n\t\t\t\t\telse\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s.split('/')\n\t\t\t\t\tend\n\t\t\t\telsif counter % 2 == 1\n\t\t\t\t\tseq = line.strip\t\n\n\t\t\t\t\tname_A = \"#{name}_#{mate}_#{seq}_A\"\n\t\t\t\t\tname_B = \"#{name}_#{mate}_#{seq}_B\"\n\t\t\t\t\t\n\t\t\t\t\tseq_A = seq[0..anchor_length - 1]\n\t\t\t\t\tseq_B = seq[-anchor_length..-1]\n\n\t\t\t\t\toutput.puts [\">#{name_A}\", seq_A, \">#{name_B}\", seq_B].join(\"\\n\")\n\t\t\t\t\tname, mate, seq = nil, nil, nil\n\t\t\t\t\tcounter = -1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def get_bam_files\n\n bam_files = self.study_files.by_type('BAM')\n bams = []\n\n bam_files.each do |bam_file|\n next unless bam_file.has_completed_bundle?\n\n bams << {\n 'name' => bam_file.name,\n 'url' => bam_file.api_url,\n 'indexUrl' => bam_file.study_file_bundle.bundled_file_by_type('BAM Index')&.api_url,\n 'genomeAssembly' => bam_file.genome_assembly_name,\n 'genomeAnnotation' => bam_file.genome_annotation\n }\n end\n bams\n end" ]
[ "0.6252254", "0.54724836", "0.5404817", "0.52945566", "0.522857", "0.5174626", "0.5082098", "0.5048087", "0.5043778", "0.503153", "0.4991992", "0.49853578", "0.49750364", "0.49178025", "0.4912758", "0.49042833", "0.49032786", "0.48832196", "0.48717454", "0.4862315", "0.48407745", "0.48391876", "0.48296508", "0.48217732", "0.4821055", "0.47983843", "0.47967046", "0.4796419", "0.4796419", "0.47930652" ]
0.8027302
0
Create BLAST database, given FASTA file and sequence type in FASTA file.
def make_blast_database(file, type) puts "FASTA file: #{file}" puts "FASTA type: #{type}" print "Proceed? [y/n] (Default: y): " response = STDIN.gets.to_s.strip unless response.match(/n/i) default_title = make_db_title(File.basename(file)) print "Enter a database title or will use '#{default_title}': " title = STDIN.gets.to_s title = default_title if title.strip.empty? `makeblastdb -parse_seqids -hash_index \ -in #{file} -dbtype #{type.to_s.slice(0,4)} -title "#{title}"` end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_blast_databases\n unformatted_fastas.each do |file, sequence_type|\n make_blast_database(file, sequence_type)\n end\n end", "def makedb\n # only scan the first few hundred entries\n n = 100\n # check if the query is a nucl or prot seq\n query_file = Bio::FastaFormat.open(@query)\n count_p=0\n count=0\n query_file.take(n).each do |entry|\n count_p += 1 if entry.isProt?\n count += 1\n end\n if count_p > count*0.9\n @query_is_prot = true\n else\n @query_is_prot = false\n end\n\n # check if the target is a nucl or prot seq\n target_file = Bio::FastaFormat.open(@target)\n count_p=0\n count=0\n target_file.take(n).each do |entry|\n count_p += 1 if entry.isProt?\n count += 1\n end\n if count_p > count*0.9\n @target_is_prot = true\n else\n @target_is_prot = false\n end\n # construct the output database names\n @query_name = File.basename(@query).split('.')[0..-2].join('.')\n @target_name = File.basename(@target).split('.')[0..-2].join('.')\n\n # check if the databases already exist in @working_dir\n make_query_db_cmd = \"#{@makedb_path} -in #{@query}\"\n make_query_db_cmd << \" -dbtype nucl \" if !@query_is_prot\n make_query_db_cmd << \" -dbtype prot \" if @query_is_prot\n make_query_db_cmd << \" -title #{query_name} \"\n make_query_db_cmd << \" -out #{@working_dir}/#{query_name}\"\n db_query = \"#{query_name}.nsq\" if !@query_is_prot\n db_query = \"#{query_name}.psq\" if @query_is_prot\n if !File.exists?(\"#{@working_dir}/#{db_query}\")\n make_db = Cmd.new(make_query_db_cmd)\n make_db.run\n if !make_db.status.success?\n msg = \"BLAST Error creating database:\\n\" +\n make_db.stdout + \"\\n\" +\n make_db.stderr\n raise RuntimeError.new(msg)\n end\n end\n\n make_target_db_cmd = \"#{@makedb_path} -in #{@target}\"\n make_target_db_cmd << \" -dbtype nucl \" if !@target_is_prot\n make_target_db_cmd << \" -dbtype prot \" if @target_is_prot\n make_target_db_cmd << \" -title #{target_name} \"\n make_target_db_cmd << \" -out #{@working_dir}/#{target_name}\"\n\n db_target = \"#{target_name}.nsq\" if !@target_is_prot\n db_target = \"#{target_name}.psq\" if @target_is_prot\n if !File.exists?(\"#{@working_dir}/#{db_target}\")\n make_db = Cmd.new(make_target_db_cmd)\n make_db.run\n if !make_db.status.success?\n raise RuntimeError.new(\"BLAST Error creating database\")\n end\n end\n @databases = true\n [@query_name, @target_name]\n end", "def initialize(blast_database_file_path)\n @database = blast_database_file_path\n @fastacmd = 'fastacmd'\n end", "def makedb\n # check if the query is a nucleotide sequence\n query_file = Bio::FastaFormat.open(@query)\n query_file.each do |entry|\n raise \"Query sequence looks like it's not nucleotide\" if !entry.isNucl?\n end\n\n # check if the target is a nucl or prot seq\n target_file = Bio::FastaFormat.open(@target)\n count_p=0\n count=0\n target_file.each do |entry|\n count_p += 1 if entry.isProt?\n count += 1\n end\n if count_p > count*0.9\n @target_is_prot = true\n else\n @target_is_prot = false\n end\n # construct the output database names\n @query_name = File.basename(@query).split('.')[0..-2].join('.')\n @target_name = File.basename(@target).split('.')[0..-2].join('.')\n\n # check if the databases already exist in @working_dir\n make_query_db_cmd = \"#{@makedb_path} -in #{@query}\"\n make_query_db_cmd << \" -dbtype nucl -title #{query_name} -out #{query_name}\"\n if !File.exists?(\"#{@working_dir}/#{query_name}.nin\")\n `#{make_query_db_cmd}`\n end\n\n make_target_db_cmd = \"#{@makedb_path} -in #{@target}\"\n make_target_db_cmd << \" -dbtype nucl \" if !@target_is_prot\n make_target_db_cmd << \" -dbtype prot \" if @target_is_prot\n make_target_db_cmd << \" -title #{target_name} -out #{target_name}\"\n\n db_target = \"#{target_name}.nsq\" if !@target_is_prot\n db_target = \"#{target_name}.psq\" if @target_is_prot\n if !File.exists?(\"#{db_target}\")\n `#{make_target_db_cmd}`\n end\n @databases = true\n [@query_name, @target_name]\n end", "def create_sequence_entries\n File.open(file_name('contigs.fasta'), 'r').each(sep=\"\\n>\") do |line|\n header, sequence = line.chomp.split( \"\\n\", 2 )\n .map { |x| x.gsub( /\\n|>/, '' ) }\n \n Sequence.create(header: header, sequence: sequence)\n end\nend", "def biosequence_from_file(path_to_sequence, sequence_format = nil)\n biosequence = rich_sequence_object_from_file(path_to_sequence, sequence_format).to_biosequence\n return biosequence\nend", "def gb_to_fasta(gb, fasta, seq_type=:nt, task_name=\"rast_annotate\")\n abort \"FATAL: Task #{task_name} requires specifying STRAIN_NAME\" unless STRAIN_NAME\n abort \"FATAL: gb_to_fasta called with invalid seq_type\" unless [:nt, :aa].include? seq_type\n system <<-SH\n module load python/2.7.6\n module load py_packages/2.7\n python #{REPO_DIR}/scripts/gb_to_fasta.py -i #{gb} -s #{seq_type} -o #{fasta}\n SH\nend", "def file_from_biosequence(path_to_sequence, sequence_format, biosequence)\n ouput_file = File.open(path_to_sequence, \"w\")\n ouput_file.puts biosequence.output(sequence_format)\n ouput_file.close\nend", "def make_blastdbs! fnames, cpus=4\n suffix = BLAST_DB_SUFFIX\n outfiles = fnames.map { |fname| fname + suffix }\n\n Parallel.each(fnames, in_processes: cpus) do |fname|\n cmd = \"diamond makedb --threads 1 --in #{fname} \" +\n \"--db #{fname}#{BLAST_DB_SUFFIX}\"\n\n Process.run_and_time_it! \"Make db\", cmd\n end\n\n outfiles\n end", "def load_database(filename)\n \n handle = File.open(filename)\n uncompressed = Zlib::GzipReader.new(handle)\n records = DnaIO.new(uncompressed)\n records.to_a\nend", "def load(handle, args={})\n File.open(handle) do |handle|\n db = DnaIO.new handle\n db.each do |record|\n self.add(record.sequence, record.name)\n end\n end\n end", "def db_type_for(blast_method)\n case blast_method\n when 'blastp', 'blastx'\n :protein\n when 'blastn', 'tblastx', 'tblastn'\n :nucleotide\n end\n end", "def from_blastdb(sequence_ids, database_ids)\n sequence_ids = sequence_ids.join(',')\n database_names = Database[database_ids].map(&:name).join(' ')\n\n # Output of the command will be tab separated three columns.\n command = \"blastdbcmd -outfmt '%a\t%t\t%s'\" \\\n \" -db '#{database_names}' -entry '#{sequence_ids}'\"\n\n logger.debug(\"Executing: #{command}\")\n\n # Not interested in stderr.\n `#{command} 2> /dev/null`.\n each_line.map {|line| Sequence.new(*line.split('\t'))}\n end", "def generate_alignment\n raise ArgumentError, 'Missing genome FASTA file.' unless @genome_file\n raise ArgumentError, 'Missing transcripts FASTA file.' unless @transcripts_file\n \n # Prepare the BLAT alignment\n blat = Alignment::BLAT.new(@blat_options.merge({ out_format: :tab, database: @genome_file }))\n \n # Optionally set a permanent file to write the results to\n @alignment_file ||= \"#{@transcripts_file}.alignment\"\n blat.output_file = @alignment_file\n \n puts \"Running BLAT alignment...\" if @verbose\n \n # Run\n result_file = blat.run(@transcripts_file)\n result_file.path\n end", "def build_database(filename)\n\tdb = []\n\tlines = get_file_lines(filename)\n\tlines.each { |x| db << parse_csv_line(x) }\n\t#create new instance of Onfidoer for each item in the array\n\tdb.each { |x| Onfidoer.new(*x) } #there was a problem with this line \nend", "def initialize(assembly)\n @reference_db = Bio::DB::Fasta::FastaFile.new({:fasta=>assembly})\n @id_len = {}\n self.get_id_len\n end", "def create_biosequence(gene)\n address = URI('http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=ensemblgenomesgene&format=embl&id='+gene)\n response = fetch(address)\n record = response.body\n embl = Bio::EMBL.new(record)\n biosequence = embl.to_biosequence\n return biosequence\nend", "def save_success_sequence(aa_sequence, nt_sequence, header, accession_no, organism, group, reference, uploader_name, uploader_email)\n\n new_sequence = CustomizedProteinSequence.new\n new_sequence.header = header\n new_sequence.uploader = \"USER\"\n new_sequence.uploader_name = uploader_name\n new_sequence.uploader_email = uploader_email\n new_sequence.group = group\n new_sequence.accession_no = accession_no # result[:header] should be accession no OR manually extract accession number from local blast db\n new_sequence.chain = aa_sequence\n new_sequence.reference = reference\n new_sequence.save!\n\n\n # don't ask user for nt sequence yet. probably ask later through email\n new_nt_sequence = CustomizedNucleotideSequence.new\n new_nt_sequence.header = header\n new_nt_sequence.uploader = \"USER\"\n new_nt_sequence.uploader_name = uploader_name\n new_nt_sequence.uploader_email = uploader_email\n new_nt_sequence.group = group\n new_nt_sequence.accession_no = accession_no\n new_nt_sequence.chain = nt_sequence\n new_sequence.reference = reference\n new_nt_sequence.save!\n\n\n end", "def initialize(file)\n\t\t#Initializes superclass -- creates database.\n\t\tsuper\n\t\t#Creates tables if they not exist\n\t\tTABLES.each do |table|\n\t\t\tsql = \"CREATE TABLE IF NOT EXISTS #{table.header} (\"\n\t\t\ttable.columns.each {|column| sql += \"#{column.header} \" +\n\t\t\t\t\"#{column.type_constraint}, \"}\n\t\t\tsql = table.constraint.nil? ?\n\t\t\t\t\"#{sql.slice(0, sql.length - 2)})\" :\n\t\t\t\t\"#{sql}#{table.constraint})\"\n\t\t\tself.transaction {|tdb| tdb.execute(sql)}\n\t\tend\n\tend", "def build_database(file, database_user_key,database_movie_key)\n file.each do |line| \n\t\t\ttokens=line.split(\"\\t\")\n\t\t\tuser_id=tokens[0]\n\t\t\tmovie_id=tokens[1]\n\t\t\trate_score=tokens[2]\n\t\t\tadd_entry(database_user_key,user_id,movie_id,rate_score)\n\t\t\tadd_entry(database_movie_key,movie_id,user_id,rate_score)\n end \n end", "def seqshash_to_fastafile(seqs,filename)\n oa = Bio::Alignment::OriginalAlignment.new(seqs)\n string_to_file(oa.output(:fasta),filename)\n\n end", "def initialize(seq_name,seq_fasta,seq_qual, seq_comment = '')\n super\n\n @actions = []\n @seq_fasta_orig = seq_fasta\n @seq_fasta = seq_fasta\n \n @seq_qual_orig = seq_qual\n @seq_qual = seq_qual \n \n @insert_start = 0\n @insert_end = seq_fasta.length-1 \n \n @stats={}\n @comments=[]\n \n @file_tags=[]\n \n # for paired ends\n @order_in_tuple=0\n @tuple_id=0\n @tuple_size=0\n @file_tag_tuple_priority=0\n \n end", "def fasta2anchors(input_file, anchor_length, sequencing_type, output_file)\n\t\tcounter = -1\n\t\tname, mate, seq = nil, nil, nil\n\t\t\n\t\tFile.open(output_file, 'w') do |output|\t\n\t\t\tFile.open(input_file, 'r').each do |line|\n\t\t\t\tcounter += 1\n\t\t\t\t\n\t\t\t\tif counter % 2 == 0\n\t\t\t\t\tif sequencing_type == 'se'\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s, 1\n\t\t\t\t\telse\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s.split('/')\n\t\t\t\t\tend\n\t\t\t\telsif counter % 2 == 1\n\t\t\t\t\tseq = line.strip\t\n\n\t\t\t\t\tname_A = \"#{name}_#{mate}_#{seq}_A\"\n\t\t\t\t\tname_B = \"#{name}_#{mate}_#{seq}_B\"\n\t\t\t\t\t\n\t\t\t\t\tseq_A = seq[0..anchor_length - 1]\n\t\t\t\t\tseq_B = seq[-anchor_length..-1]\n\n\t\t\t\t\toutput.puts [\">#{name_A}\", seq_A, \">#{name_B}\", seq_B].join(\"\\n\")\n\t\t\t\t\tname, mate, seq = nil, nil, nil\n\t\t\t\t\tcounter = -1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def fasta2anchors(input_file, anchor_length, sequencing_type, output_file)\n\t\tcounter = -1\n\t\tname, mate, seq = nil, nil, nil\n\t\t\n\t\tFile.open(output_file, 'w') do |output|\t\n\t\t\tFile.open(input_file, 'r').each do |line|\n\t\t\t\tcounter += 1\n\t\t\t\t\n\t\t\t\tif counter % 2 == 0\n\t\t\t\t\tif sequencing_type == 'se'\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s, 1\n\t\t\t\t\telse\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s.split('/')\n\t\t\t\t\tend\n\t\t\t\telsif counter % 2 == 1\n\t\t\t\t\tseq = line.strip\t\n\n\t\t\t\t\tname_A = \"#{name}_#{mate}_#{seq}_A\"\n\t\t\t\t\tname_B = \"#{name}_#{mate}_#{seq}_B\"\n\t\t\t\t\t\n\t\t\t\t\tseq_A = seq[0..anchor_length - 1]\n\t\t\t\t\tseq_B = seq[-anchor_length..-1]\n\n\t\t\t\t\toutput.puts [\">#{name_A}\", seq_A, \">#{name_B}\", seq_B].join(\"\\n\")\n\t\t\t\t\tname, mate, seq = nil, nil, nil\n\t\t\t\t\tcounter = -1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def initialize(file='corpus.db')\n @path = File.join(default_path, file)\n @filename = file\n FileUtils.mkdir_p(default_path) unless File.exists?(default_path)\n create_database\n end", "def create_database_schema!\n \n if file_format.class.const_defined?('Database')\n @orm_module = file_format.class.const_get('Database')\n else\n @orm_module = file_format.class.const_set('Database', Module.new)\n end\n\n create_request_table_and_class\n create_warning_table_and_class\n \n file_format.line_definitions.each do |name, definition|\n create_database_table(name, definition)\n create_activerecord_class(name, definition)\n end\n end", "def create type\n return if type == :records ## no records for this\n @db.connect do\n\n sql = SqlGenerator.for_files(@table_files) \n @db.query(sql)\n Logger.<<(__FILE__,\"INFO\",\"Setup files table for #{@source.name}\")\n\n end\n end", "def process_alignment\n # init vars\n @names = []\n @seqs = []\n \n @alignment = \"-B #{@basename}.aln\"\n\n # import alignment file\n @content = IO.readlines(@infile).map {|line| line.chomp}\n \n #check alignment for gap-only columns\n remove_inserts\n \n #write query-file\n File.open(@infile, \"w\") do |file|\n file.write(\">#{@names[0]}\\n\")\n file.write(\"#{@seqs[0]}\\n\")\n end\n \n #write aln-file\n File.open(@basename + \".aln\", \"w\") do |file|\n @names.each_index do |num|\n file.write(\"Sequence#{num} \")\n file.write(\" \") if (num < 10)\n file.write(\" \") if (num < 100)\n file.write(\"#{@seqs[num]}\\n\")\n end\n end\n end", "def addNewSeq header, seq\n time = Time.new\n timeS = \"#{time.year}_#{time.month}\"\n newSeq = string2seq seq \n File.open(\"000-#{timeS}-New-Sequences.fasta\",'a') do |newF|\n newF << \"#{header}\\n\"\n newF << \"#{newSeq}\\n\"\n end\nend", "def add(gbfile)\n compress = false\n if (gbfile.index(\".gz\"))\n system(\"PATH=/usr/bin;zcat #{gbfile} > #{gbfile}.tmp\")\n gbfile = gbfile + \".tmp\"\n compress = true\n end\n FlatFile.new(GenBank, File.new(gbfile)).each {|seq|\n seq.each_cds {|cds|\n @product[cds.assoc[\"protein_id\"]] = cds.assoc[\"product\"]\n @role[cds.assoc[\"protein_id\"]] = cds.assoc[\"note\"].split(\";\")\n }\n }\n File.unlink(gbfile) if compress\n end" ]
[ "0.7292946", "0.607922", "0.6052386", "0.5623254", "0.5620199", "0.55463135", "0.55391514", "0.5502864", "0.54939616", "0.5453335", "0.54077363", "0.5390296", "0.53558445", "0.5301986", "0.52764434", "0.52751464", "0.5265819", "0.5258607", "0.5247739", "0.518297", "0.5149516", "0.51082385", "0.5096781", "0.5096781", "0.5063287", "0.5058766", "0.5048961", "0.50403214", "0.50322926", "0.5015433" ]
0.76780653
0
Returns true if the database name appears to be a multipart database name. e.g. /home/ben/pd.ben/sequenceserver/db/nr.00 => yes /home/ben/pd.ben/sequenceserver/db/nr => no /home/ben/pd.ben/sequenceserver/db/img3.5.finished.faa.01 => yes
def multipart_database_name?(db_name) !(db_name.match(/.+\/\S+\d{2}$/).nil?) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def multipart?\n has_content_type? ? !!(main_type =~ /^multipart$/i) : false\n end", "def multipart?\n true unless parts.empty?\n end", "def multipart?\n\t true\n\tend", "def multipart?\n http.headers[\"content-type\"] =~ /^multipart/\n end", "def multipart?\n @multipart\n end", "def multipart?\n @multipart\n end", "def db_path?( path )\n path.split( \"|\" ).size == 3\n end", "def multivolume?\n @file_name.split('_').last[0].downcase == 'x'\n end", "def multipart?\n return true if @multipart\n query_pairs.any?{|pair| pair.respond_to?(:last) && pair.last.is_a?(Array)}\n end", "def multipart?\n message.multipart?\n end", "def multipart?\n false\n end", "def multipart?\n query_pairs.any?{|pair| pair.respond_to?(:last) && pair.last.is_a?(Array)}\n end", "def part?(name)\n !part(name).nil?\n end", "def multipart?(column_names)\n return false unless column_names\n column_names.each { |column_name| return true if @scaffold_class.scaffold_column_type(column_name) == :file }\n false\n end", "def db_request?( path )\n path.size == 2\n end", "def split?\n file.bytesize > MAXIMUM_NAME_LENGTH\n end", "def jobdir_name?(name)\n name[/^\\d+$/]\n end", "def first_multipart_form_part?(form, part)\n self.multipart_forms[form][:parts].first == part\n end", "def is_subdomain?(da, db)\n\n da == db ||\n db == '' ||\n da[0, db.length + 1] == db + '.'\n end", "def busted?(filename)\n f = File.basename(filename)\n /\\A(.*\\/)?[a-z0-9]{6}_[a-zA-Z0-9\\-_]+\\.[a-zA-Z0-9]+\\z/.match?(f)\n end", "def db_name?() @db_name.present? ; end", "def db_name?() @db_name.present? ; end", "def valid_directory_name?(directory_name, metadata_name)\n normalized = metadata_name.tr('/', '-').split('-').last\n normalized == directory_name\n end", "def parts?\n !parts.empty?\n end", "def last_multipart_form_part?(form, part)\n self.multipart_forms[form][:parts].last == part\n end", "def has_multipart?(obj); end", "def multipart_report?\n multipart? && sub_type =~ /^report$/i\n end", "def valid_filename?(name)\n name.length.positive?\nend", "def database?\n marc_leader_06_match = record.leader.byteslice(6) == 'a'\n marc_leader_07_match = %w[b i s].include?(record.leader.byteslice(7))\n marc_008_21_match = record.fields('008').find do |field|\n field.value.byteslice(21) == 'd'\n end\n\n marc_006_00_04 = record.fields('006').find do |field|\n field.value.byteslice(0) == 's' && field.value.byteslice(4) == 'd'\n end\n\n return true if (marc_leader_06_match &&\n marc_leader_07_match &&\n marc_008_21_match) ||\n marc_006_00_04\n end", "def db_exists? db_name\n File.exists? db_name\n end" ]
[ "0.6249019", "0.619339", "0.60783166", "0.60710865", "0.606279", "0.606279", "0.6030639", "0.5987106", "0.59457326", "0.5891267", "0.58741236", "0.58088994", "0.5802374", "0.5713013", "0.564603", "0.5637294", "0.56154466", "0.56147933", "0.56117904", "0.56058854", "0.55855244", "0.55855244", "0.55422187", "0.5519161", "0.55128384", "0.5381483", "0.53600603", "0.53192955", "0.52953494", "0.5230703" ]
0.8682582
0
Returns true if first character of the file is '>'.
def probably_fasta?(file) File.read(file, 1) == '>' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def opening?(char)\n DELIMITERS.keys.include?(char)\n end", "def open_tag?(char)\n unless char == nil\n char =~ /\\A<[^>]+>/\n else\n false\n end\n end", "def flagged? file\n self[file][9] == '0C'\n end", "def fullpage?\n File.open(path, &:readline)[0..2] == \"!!!\"\n end", "def isBinary?(fname)\n readbuf = get_file_contents(fname)\n count = 0\n# puts \"The size is: #{readbuf.length()}.\"\n threshold = Integer(readbuf.length() * 0.25)\n# puts \"Threshold: #{threshold}.\"\n readbuf.each_byte do |byte| #I have to use each_byte because Ruby 1.8.6 (Darwin) is\n #fucked and doesnt have String::each_char\n if !(0x20..0x7f).include?(byte) then\n #puts \"Non-ascii byte found: #{byte}\"\n count+=1 \n end\n end\n# puts \"#{count} nonascii bytes found in file.\"\n if count >= threshold then\n return true\n else \n return false\n end\nend", "def file?(s)\n s.include? '.'\nend", "def file?\n (@typeflag == \"0\" || @typeflag == \"\\0\") && !@name.end_with?(\"/\")\n end", "def file?() end", "def ack?\n filename.downcase.start_with?(\"ack\")\n end", "def is_non_terminal?(s)\n (s[0] == \"<\" and s[s.length-1] == \">\")\n\nend", "def commit_msg_empty?(commit_msg_file)\n File.open(commit_msg_file, 'r') do |f|\n f.readlines.each do |line|\n strip_line = line.strip\n return false if (!strip_line.empty? && !strip_line.start_with?('#'))\n end\n end\n true\nend", "def single?(file)\n file !~ /\\*/\n end", "def is_non_terminal?(s)\r\n # TODO: your implementation here\r\n # puts s[0] == \"<\" && s[-1] == \">\"\r\n # puts s[-1]\r\n return s[0] == \"<\" && s[-1] == \">\"\r\nend", "def opening?(word)\n word =~ open_char\n end", "def closing?(char)\n DELIMITERS.values.include?(char)\n end", "def unbroken?(line)\n\tline.each do |c|\n\t\tif c == \".\"\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend", "def empty?\n File.size(@filename) <= 2\n end", "def cuts_opening?\n end", "def new_file?\n\t\t@filelineno == 1\n\tend", "def è_un_commento?\n @contenuto.start_with? \"#\"\n end", "def header_char_for( filename )\n\t\tcase File.extname( filename )\n\t\twhen '.md' then return '#'\n\t\twhen '.rdoc' then return '='\n\t\twhen ''\n\t\t\tif filename == 'Rakefile'\n\t\t\t\treturn '#'\n\t\t\tend\n\t\tend\n\n\t\traise \"Don't know what header character is appropriate for %s\" % [ filename ]\n\tend", "def open_file?(filename)\r\n\t\t#REFRENCE5|\\=\r\n\t\tif(File.open(filename,'r:utf-8').close || true rescue false)\r\n\t\t\treturn true\r\n\t\telse \r\n\t\t\tprint \"ERROR: file cannot be opened \\n\\n\" #REFRENCE3\r\n\t\t\texit #REFRENCE4\r\n\t\tend\r\n\tend", "def file?(file_path)\n nlst(file_path)[0] == file_path\n end", "def read_chr\n @file.getc unless @file.eof?\n end", "def eof?\r\n false\r\n end", "def text_file?(file)\n return false unless File.readable?(file)\n bytes = File.stat(file).blksize\n bytes = 4096 if bytes > 4096\n s = (File.read(file, bytes) || \"\")\n s = s.encode('US-ASCII', :undef => :replace).split(//)\n return (s.grep(\" \"..\"~\").size.to_f / s.size.to_f) > 0.85\n end", "def next_char\n @pos += 1\n if (c = @source[@pos..@pos]) == BACKSLASH\n @pos += 1\n [true, @source[@pos..@pos]]\n else\n [false, c]\n end\n end", "def split?\n file.bytesize > MAXIMUM_NAME_LENGTH\n end", "def file?\n !!@pointer['realpath']\n end", "def eof?\n io.eof?\n end" ]
[ "0.60451853", "0.59814185", "0.5977373", "0.5898968", "0.5780077", "0.57750815", "0.57673585", "0.5713025", "0.56956613", "0.5684289", "0.5602797", "0.55567914", "0.55029756", "0.54284596", "0.53959966", "0.53854984", "0.5360093", "0.5354002", "0.53408694", "0.532963", "0.5287713", "0.52873236", "0.5282167", "0.5253523", "0.52401876", "0.52374774", "0.52343416", "0.52156687", "0.52097106", "0.5205217" ]
0.6853935
0
Suggests improved titles when generating database names from files for improved apperance and readability in web interface. For example: Cobs1.4.proteins.fasta > Cobs 1.4 proteins S_invicta.xx.2.5.small.nucl.fa > S invicta xx 2.5 small nucl
def make_db_title(db_name) db_name.gsub!('"', "'") # removes .fasta like extension names db_name.gsub!(File.extname(db_name), '') # replaces _ with ' ', db_name.gsub!(/(_)/, ' ') # replaces '.' with ' ' when no numbers are on either side, db_name.gsub!(/(?<![0-9])\.(?![0-9])/, ' ') # preserves version numbers db_name.gsub!(/\W*(\d+([.-]\d+)+)\W*/, ' \1 ') db_name end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def titleize\n @collection.dictionary.each do |id, data|\n next unless File.basename(data['id']) =~ /^untitled/\n new_name = Ruhoh::StringFormat.clean_slug(data['title'])\n new_file = \"#{new_name}#{File.extname(data['id'])}\"\n old_file = File.basename(data['id'])\n next if old_file == new_file\n\n FileUtils.cd(File.dirname(data['pointer']['realpath'])) {\n FileUtils.mv(old_file, new_file)\n }\n Ruhoh::Friend.say { green \"Renamed #{old_file} to: #{new_file}\" }\n end\n end", "def title\n #Flip off the part after the last dot, including that dot: find the filename without extensions\n fragments = @filename.split('.')\n fragments.pop\n title = fragments.join('.')\n\n return title.gsub(/[_]/, ' ').capitalize\n end", "def title_folded_to_filename\n self[:title].gsub(/[^a-z0-9-]/) do |c|\n case c\n when /\\s+|\\./ then '-'\n when /[A-Z]+/ then c.downcase\n else ''\n end\n end.gsub(/\\-+/,'-')\n end", "def populate_title\n if self.title.blank?\n self.title = self.file_file_name.blank? ? \"\" : self.file_file_name.gsub(/_/, \" \").capitalize\n end\n\tend", "def title_for( path_names )\n tokens = path_names.split( \"|\" )\n buff = case tokens.size\n when 2 \n \"zone\"\n when 3 \n \"database\"\n else \n \"collection\"\n end\n db = tokens.size > 3 ? \"<span class=\\\"ctx\\\">#{tokens[2]}</span>.\" : \"\"\n \"<p class=\\\"ctx\\\" style=\\\"text-align:center;font-size:0.8em\\\">#{db}#{tokens.last}</p>\"\n end", "def smart_titlecase\n small_re = %w( is a an and as at but by en for if in of on or the to v[.]? via vs[.]? ).join('|')\n\n # Original Perl version by: John Gruber (daringfireball.net) 2008-05-10\n # Adapted to Ruby by: Marshall Elfstrand (vengefulcow.com/ 2008-05-21\n # Improved and customized: Jacob Duffy (duffy.jp) 2011-01-25\n # License: http://www.opensource.org/licenses/mit-license.php\n\n # if source is all uppercase, use all lowercase instead. -- jpd\n string = (self.upcase == self)? self.downcase : self\n\n result = \"\"\n string.gsub('_', ' ').split(/( [:.;?!][ ] | (?:[ ]|^)[\"\"] )/x).each do |s|\n s.gsub!(/ \\b( [[:alpha:]] [[:lower:].'']* )\\b /x) do |w|\n # Skip words with inresult dots, e.g. \"del.icio.us\" or \"example.com\"\n (w =~ / [[:alpha:]] [.] [[:alpha:]] /x) ? w : w.capitalize\n end\n\n # Lowercase our list of small words:\n s.gsub!(/\\b(#{small_re})\\b/io) { |w| w.downcase }\n\n # If the first word in the title is a small word, then capitalize it:\n s.gsub!(/\\A([[:punct:]]*)(#{small_re})\\b/io) { |w| $1 + $2.capitalize }\n\n # If the last word in the title is a small word, then capitalize it:\n s.gsub!(/\\b(#{small_re})([[:punct:]]*)\\Z/io) { |w| $1.capitalize + $2 }\n\n # Append current substring to output\n result += s\n end #each\n\n # Special Cases:\n upcase_re = (Array(Duffy.configuration.upcase_custom) + Array(Duffy.configuration.upcase_default)).uniq.join(\"|\")\n\n # Names with apostrophes; O'Brian, De'Wayne. 3+ Skips \"I've\" \"Haven't\" etc.\n result.gsub!(/([A-Z][a-z]*)'([a-z]{3,})/) { \"#{$1}'#{$2.capitalize}\" }\n\n result.gsub!(/ V(s?)\\. /, ' v\\1. ') # \"v.\" and \"vs.\"\n\n result.gsub!(/([''])S\\b/, '\\1s') # 'S (otherwise you get \"the SEC'S decision\")\n\n result.gsub!(/\\b(#{upcase_re})\\b/i) { |w| w.upcase } unless upcase_re.blank?\n\n # Squash repeated whitespace characters\n result.gsub!(/\\s+/, ' ')\n\n # Strip leading / tailing whitespace and return\n result.strip\n end", "def file_title(title)\n title.downcase.gsub(/\\s+/, '-').gsub(/-{2,}/, '-').gsub(':', '')\nend", "def titleize_proper_names\n self.author = self.author.titleize\n self.editor = self.editor.titleize if self.editor\n self.buyed_from = self.buyed_from.titleize if self.buyed_from\n end", "def title\n CGI::unescape(self.file_name).gsub(/\\.\\w+$/, '').titleize\n end", "def file_name\n file_name = (\"tmp/insert_externals.txt\")\n #file_name = (\"tmp/insert_internals.txt\")\n #file_name = (\"./tmp/insert_internals_hash.txt\")\n #file_name = (\"lib/anagrams/anagrams_table_data.txt\")\n #file_name = (\"tmp/insert_anagrams.txt\")\n #file_name = (\"tmp/insert_word_list.txt\")\n #file_name = (\"../../Documents/20110421-research_textualed.txt\")\n #file_name = (\"../consummates/lib/databasers/mysql_database_safe_lines/mysql_database_ready-015.txt\")\n #file_name = (\"../consummates/lib/databasers/mysql_database_safe_lines/mysql_database_ready_hash-015.txt\")\n #file_name = (\"../consummates/lib/databasers/mysql_database_safe_lines/mysql_database_ready_hashlines-015.txt\")\n #file_name = (\"../consummates/lib/databasers/mysql_database_safe_lines/mysql_database_ready_hashlines_sorted_keys-015.txt\")\n #file_name = (\"../consummates/lib/databasers/mysql_database_safe_lines/mysql_database_ready_hashlines_sorted_values-015.txt\")\n end", "def file_to_pagename(filename)\n\t\tfilename.chomp(\".md\").gsub('_', ' ').capitalize\n\tend", "def file_to_pagename(filename)\n\t\tfilename.chomp(\".md\").gsub('_', ' ').capitalize\n\tend", "def quick_title(song)\n File.basename(song, File.extname(song)).gsub(/^[^A-Za-z]+\\s+(\\w)/, \"\\\\1\")\n end", "def title\n #CGI::unescape(file_name.to_s).gsub(/\\.\\w+$/, '').titleize\n self[:file_name].gsub(/\\.\\w+$/, '').titleize rescue ''\n end", "def title\n CGI::unescape(file_name.to_s).gsub(/\\.\\w+$/, '').titleize\n end", "def title\n CGI::unescape(file_name.to_s).gsub(/\\.\\w+$/, '').titleize\n end", "def titleize\n#\t\thumanize(underscore(self)).gsub(/\\b('?[a-z])/) { $1.capitalize }\n#\t\thumanize(self.underscore).gsub(/\\b('?[a-z])/) { $1.capitalize }\n\t\tself.underscore.humanize.gsub(/\\b('?[a-z])/) { $1.capitalize }\n\tend", "def to_title(file)\n # Strip .md if it exists\n title = file.gsub(/.md$/, '')\n\n title = title.gsub(/-/, ' ')\n title = title.gsub(/([A-Z][a-z])/, ' \\1').strip\n title = title.split.map { |word| word[0].upcase+word[1..99999] }.join(' ')\n return title\n end", "def fix_name(title)\n result = String.new( title )\n # Replace all invalid characters\n for substitution in $INVALID_CHARS_FOR_FILENAME\n result.gsub!(substitution[0], substitution[1])\n end\n result\nend", "def format_sort_name(name, author)\n str = format_name(name, :deprecated).\n sub(/^_+/, \"\").\n gsub(/_+/, \" \"). # put genus at the top\n sub(/ \"(sp[-.])/, ' {\\1'). # put \"sp-1\" at end\n gsub(/\"([^\"]*\")/, '\\1'). # collate \"baccata\" with baccata\n sub(\" subg. \", \" {1subg. \").\n sub(\" sect. \", \" {2sect. \").\n sub(\" subsect. \", \" {3subsect. \").\n sub(\" stirps \", \" {4stirps \").\n sub(\" subsp. \", \" {5subsp. \").\n sub(\" var. \", \" {6var. \").\n sub(\" f. \", \" {7f. \").\n strip.\n sub(/(^\\S+)aceae$/, '\\1!7').\n sub(/(^\\S+)ineae$/, '\\1!6').\n sub(/(^\\S+)ales$/, '\\1!5').\n sub(/(^\\S+?)o?mycetidae$/, '\\1!4').\n sub(/(^\\S+?)o?mycetes$/, '\\1!3').\n sub(/(^\\S+?)o?mycotina$/, '\\1!2').\n sub(/(^\\S+?)o?mycota$/, '\\1!1')\n\n # put autonyms at the top\n 1 while str.sub!(/(^| )([A-Za-z-]+) (.*) \\2( |$)/, '\\1\\2 \\3 !\\2\\4')\n\n if author.present?\n str += \" \" + author.\n gsub(/\"([^\"]*\")/, '\\1'). # collate \"baccata\" with baccata\n gsub(/[Đđ]/, \"d\"). # mysql isn't collating these right\n gsub(/[Øø]/, \"O\").\n strip\n end\n str\n end", "def file_name(title)\n name = title.gsub(/[\\r\\n]/, \" \")\n .gsub(/[^a-zA-Z\\d\\s]/, \"\")\n .gsub(/ /, \"_\")\n\n name.length > 31 ? name[0..30] : name\n end", "def titles\n fields.map{|f| f.to_s.gsub('_',' ').titleize }\n end", "def file_name(title)\n name = title.gsub(/[\\r\\n]/, ' ')\n .gsub(/[^a-zA-Z\\d\\s]/, '')\n .tr(' ', '_')\n\n name.length > 31 ? name[0..30] : name\n end", "def set_title\n @title = File.basename(@absolute_path)\n @title.sub!(/^[0-9][0-9]-/, '')\n @title.gsub!(/_/, ' ')\n @title.gsub!(/-/, ', ')\n end", "def to_title(file_slug)\n if file_slug == 'index' && !@pointer['id'].index('/').nil?\n file_slug = @pointer['id'].split('/')[-2]\n end\n\n file_slug.gsub(/[^\\p{Word}+]/u, ' ').gsub(/\\b\\w/){$&.upcase}\n end", "def generate_filename\n #if episodeTitle != brandTitle (brandTitle looks to be the name of the program) then use this in the filename\n if @metadata[:episodeTitle] != @metadata[:brandTitle]\n out_file = \"#{@metadata[:title1]}__#{@metadata[:title2]}__#{@metadata[:episodeTitle]}\"\n else #otherwise just use title1/2\n out_file = \"#{@metadata[:title1]}__#{@metadata[:title2]}\"\n end\n out_file.gsub!(/[^0-9A-Za-z.\\-]/, '_') #replace non alphanumerics with underscores\n\n @out_file = File.join(@out_dir, out_file)\n end", "def to_title(file_slug)\n if file_slug == 'index' && !@pointer['id'].index('/').nil?\n file_slug = @pointer['id'].split('/')[-2]\n end\n\n Ruhoh::StringFormat.titleize(file_slug)\n end", "def titleize\n\t\tif @title.nil?\n\t\t\tmeta = @source.titleize metadata\n\t\t\t@title = \"#{@settings.title || @origin_id} - #{meta}\"\n\t\tend\n\t\treturn @title\n\tend", "def title\n name.gsub(/_/, ' ')\n end", "def to_title(file_slug)\n file_slug.gsub(/[^\\p{Word}+]/u, ' ').gsub(/\\b\\w/){$&.upcase}\n end" ]
[ "0.6405323", "0.6262719", "0.61469907", "0.6087213", "0.6052651", "0.5960072", "0.59307176", "0.58981794", "0.5859058", "0.58503395", "0.5834313", "0.5834313", "0.5785105", "0.57809645", "0.5769204", "0.57677805", "0.57484853", "0.5737694", "0.56702614", "0.56634307", "0.56541175", "0.56461537", "0.56216115", "0.5584725", "0.5582799", "0.5581783", "0.5575038", "0.557403", "0.557004", "0.55427593" ]
0.7086552
0
Guess whether FASTA file contains protein or nucleotide sequences based on first 32768 characters. NOTE: 2^15 == 32786. Approximately 546 lines, assuming 60 characters on each line.
def guess_sequence_type_in_fasta(file) sample = File.read(file, 32768) sequences = sample.split(/^>.+$/).delete_if { |seq| seq.empty? } sequence_types = sequences.map {|seq| Sequence.guess_type(seq)}.uniq.compact (sequence_types.length == 1) && sequence_types.first end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_csfasta(fasta)\n # length is the total read lengh + 2\n # cat *.csfasta | perl -ne 'next if /^#/;$i++;if ($i%2==0) {print unless \n # length($_)==52} else {print unless /^>\\d+_\\d+\\_\\d+\\_(F|R)(3|5)(-P2)*\\n$/}'\n # | more\n length = get_bp_length(fasta) + 2\n i = 0\n output = \"\"\n File.open(fasta).each do |l|\n next if /^#/.match(l)\n i = i + 1\n if ( i % 2 == 0 ) && ( l.size != length ) &&\n !/^>\\\\d+_\\\\d+_\\\\d+_(F|R)(3|5)(-P2)*\\n$/.match(l)\n output = output + l\n end\n end\n output\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def probably_fasta?(file)\n File.read(file, 1) == '>'\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def guess_sequence_type(sequence_string)\n cleaned_sequence = sequence_string.gsub(/[^A-Z]/i, '') # removing non-letter characters\n cleaned_sequence.gsub!(/[NX]/i, '') # removing ambiguous characters\n\n return nil if cleaned_sequence.length < 10 # conservative\n\n composition = composition(cleaned_sequence) \n composition_NAs = composition.select { |character, count|character.match(/[ACGTU]/i) } # only putative NAs\n putative_NA_counts = composition_NAs.collect { |key_value_array| key_value_array[1] } # only count, not char\n putative_NA_sum = putative_NA_counts.inject { |sum, n| sum + n } # count of all putative NA\n putative_NA_sum = 0 if putative_NA_sum.nil?\n\n if putative_NA_sum > (0.9 * cleaned_sequence.length)\n return :nucleotide\n else\n return :protein\n end\n end", "def discover_input_sequence_type(sequence)\n # Index of the first newline char.\n start = sequence.index(/\\n/)\n # Remove the sequence FASTA header.\n seq = sequence.slice(start..-1).gsub!(/\\n/, '')\n\n if seq =~ /[EQILFPeqilfp]+/\n type = \"amino_acid\"\n else\n # Length of the sequence minus the FASTA header.\n len = seq.length.to_f\n\n na_percent = 15.0\n counts = []\n\n counts << (seq.count(\"Aa\").to_f / len) * 100\n counts << (seq.count(\"Tt\").to_f / len) * 100\n counts << (seq.count(\"Uu\").to_f / len) * 100\n\n counts << (seq.count(\"Gg\").to_f / len) * 100\n counts << (seq.count(\"Cc\").to_f / len) * 100\n\n counts << (seq.count(\"Nn\").to_f / len) * 100\n\n counts.reject! { |c| c < na_percent }\n if (!counts.empty?)\n type = \"nucleic_acid\"\n else\n type = \"amino_acid\"\n end\n end\n type\n end", "def guess_type(sequence_string)\n cleaned_sequence = sequence_string.gsub(/[^A-Z]/i, '') # removing non-letter characters\n cleaned_sequence.gsub!(/[NX]/i, '') # removing ambiguous characters\n\n return nil if cleaned_sequence.length < 10 # conservative\n\n composition = composition(cleaned_sequence)\n composition_NAs = composition.select {|character, count| character.match(/[ACGTU]/i)} # only putative NAs\n putative_NA_counts = composition_NAs.collect {|key_value_array| key_value_array[1]} # only count, not char\n putative_NA_sum = putative_NA_counts.inject {|sum, n| sum + n} # count of all putative NA\n putative_NA_sum = 0 if putative_NA_sum.nil?\n\n if putative_NA_sum > (0.9 * cleaned_sequence.length)\n return :nucleotide\n else\n return :protein\n end\n end", "def find_start_good_section(iupac_concensus_string, min_length)\n good_char_count = 0\n char_index = 0\n iupac_concensus_string.each_char do |char|\n if char =~ /[^\\?\\-Nn]/\n good_char_count += 1\n if good_char_count >= min_length\n break\n end\n else\n good_char_count = 0\n end\n char_index += 1\n end\n char_index - (good_char_count - 1)\n end", "def find_sequences(line)\n sequences = []\n\n (0..(line.length - 1)).each do |i|\n next if i + 1 > line.length - 4\n\n sub_line = line[i..i + 3]\n sequences << sub_line if sub_line == sub_line[/[a-zA-Z]+/]\n end\n\n sequences.uniq\n end", "def read_fasta(fasta_file)\r\n fasta_name = \"\"\r\n fasta_seqs = {}\r\n seq = \"\"\r\n File.open(fasta_file).each do |line|\r\n if !(line.nil?)\r\n if line.start_with? \">\"\r\n seq = \"\"\r\n fasta_name = line.chomp.split(\">\")[1]\r\n elsif\r\n seq = seq + line.chomp\r\n fasta_seqs[fasta_name] = seq\r\n end\r\n end\r\n end\r\n return fasta_seqs\r\nend", "def fasta_with_lengths(fasta_fn)\n tmp_file = register_new_tempfile('positive_peaks_formatted.fa')\n File.open(fasta_fn){|f|\n f.each_line.slice_before(/^>/).each{|hdr, *lines|\n seq = lines.map(&:strip).join\n tmp_file.puts \"#{hdr.strip}:#{seq.size}\"\n tmp_file.puts seq\n }\n }\n tmp_file.close\n tmp_file.path\nend", "def candidates2fa(input_file, fasta, read_length, output_file, exoncov=8)\n\t\tchromosomes = {}\n\t\tpositions = []\n\t\t\n\t\t# Input into hash sorted by chromosomes\n\t\tFile.open(input_file, 'r').readlines.each do |line|\n\t\t\tline = line.strip.split(\"\\t\")[0..-2]\n\t\t\tchr_a, pos_a, strand_a, chr_b, pos_b, strand_b = line[0..5]\n\t\t\tpos = [chr_a, pos_a, chr_b, pos_b].join(':')\n\t\n\t\t\tchromosomes[chr_a] = {} if !chromosomes.has_key?(chr_a)\n\t\t\t\n\t\t\tif !chromosomes.has_key?(chr_b)\n\t\t\t\tchromosomes[chr_a][chr_b] = [line]\n\t\t\n\t\t\t# 2nd elsif to exclude reads that map on same junction but opposite ends\t\t\n\t\t\telsif chromosomes[chr_a].has_key?(chr_b) && !positions.include?(pos)\n\t\t\t\tchromosomes[chr_a][chr_b].push(line)\n\t\t\t\tpositions << pos\n\t\t\tend\n\t\tend\n\n\t\t# Output\n\t\toutput = File.open(output_file, 'w') do |output|\n\t\t\tchromosomes.each do |chr_a, values|\n\t\t\t\tfasta_file = File.open(\"#{fasta}#{chr_a}.fa\", 'r')\n\t\t\t\theader = fasta_file.gets.strip\n\t\t\t\tdna_a = fasta_file.read.gsub(/\\n/, '')\n\t\t\t\t\n\t\t\t\tvalues.each do |chr_b, values|\n\t\t\t\t fasta_file = File.open(\"#{fasta}#{chr_b}.fa\", 'r')\n\t\t\t\t\theader = fasta_file.gets.strip\n\t\t\t\t\tdna_b = fasta_file.read.gsub(/\\n/, '')\n\n\t\t\t\t\tvalues.each do |v|\n\t\t\t\t\t\tbp_a, bp_b = v[1].to_i, v[4].to_i\n\t\t\t\t\t\tstrand_a, strand_b = v[2], v[5]\n\t\t\t\t\t\toverlap = v[-1].to_i - read_length\n\t\t\t\t\t\tl = read_length - exoncov \n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tupstream = dna_a[bp_a..bp_a + overlap + l].upcase\t\n\t\t\t\t\t\tdownstream = dna_b[bp_b - l - overlap + 1..bp_b - overlap].upcase\n\t\t\t\t\t\n\t\t\t\t\t\tif strand_a == '1' && strand_b == '-1'\n\t\t\t\t\t\t\tdownstream = Alignment.reverse_complement(dna_b[bp_b..bp_b + l].upcase)\n\t\t\t\t\t\telsif strand_a == '-1' && strand_b == '1'\n\t\t\t\t\t\t\tupstream = Alignment.reverse_complement(dna_a[bp_a - l + 1..bp_a].upcase)\n\t\t\t\t\t\tend\n\t\t\n\t\t\t\t\t\tid = [v[0..1], v[3..4]].join(':')\n\t\t\t\t\t\toutput.puts [\">#{id}\", downstream + upstream].join(\"\\n\")\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t$logfile.puts \"#{Time.new.strftime(\"%c\")}: Wrote loci to fasta-file.\"\n\tend", "def scan_file(file_name)\n \n #init variables\n seq_name = '';\n seq_fasta = '';\n seq_found = false;\n \n \n # for each line of the file\n File.open(file_name).each do |line|\n \n line.chomp!;\n # if line is name\n if line =~ /^>/\n \n #process previous sequence\n if seq_found\n on_process_sequence(seq_name,seq_fasta);\n end\n \n #get only name\n seq_name = line.gsub('>','');\n seq_fasta='';\n seq_found = true;\n \n else\n #add line to fasta of seq\n seq_fasta+=line;\n end\n \n end\n \n # when found EOF, process last sequence\n if seq_found\n on_process_sequence(seq_name,seq_fasta);\n end\n \n end", "def full_text_before_substring_uses_ideal_prefix_limit?\n full_text_before_substring.unpack( \"U*\" ).size >= ideal_prefix_limit\n end", "def find_transcript_pbs(fasta)\n proteins = {}\n fasta = (fasta || '').gsub(/(n|N)/, '')\n unless fasta.empty?\n begin\n uri = URI(@config[:rbpdb][:url] + @config[:rbpdb][:pbs_path])\n res = Net::HTTP.post_form(\n uri,\n 'thresh' => 0.8,\n 'seq' => fasta\n )\n page = Nokogiri::HTML(res.body)\n page.css('table.pme-main tr.pme-row-0, table.pme-main tr.pme-row-1').each do |row|\n # Fetch base data.\n pos = Container::Position.new(\n score: row.children[1].text[0...-1].to_i,\n start: row.children[3].text.to_i,\n end: row.children[4].text.to_i,\n seq: row.children[5].text\n )\n\n # Fetch protein name and build result structure.\n prot = row.children[2].children[0].text.upcase\n proteins[prot] ||= Container::Protein.new(name: prot)\n proteins[prot].positions << pos\n end\n rescue StandardError => e\n puts e.message, e.backtrace\n retry\n end\n end\n proteins\n end", "def fasta_parse(fasta_string)\n fasta_parts = fasta_string.split('>')[1..-1]\n no_pfamid = fasta_parts.map { |x| x.split(',')[1].chomp() }\n seqs = no_pfamid.map { |s| {:genus => s.lines.first.chomp(), :seq => s.split(\"\\n\")[1..-1].join.gsub(\"\\n\",'') } }\n seqs.sort_by! { |h| h[:genus] } #makes sure to sort alphabetically, allowing us to build partitioned character matrices\n return seqs\nend", "def bad_seq? seq\n seq.downcase.include? \"nosequencefound\"\n end", "def valid_sequence? sequence\n !(sequence =~ /[^ATCG]/)\n end", "def check_file\n # Read dictionary\n @word_list = File.open(@infile)\n @word_list.each do |word|\n w = Word.new(word.chop)\n # Check each token from word\n w.get_tokens.each do |seq|\n if check_sequence(seq) # Returns true if unique so far\n # Add to sequences array\n @found_sequences[seq] = word.chop\n @seq_count = @seq_count + 1\n end\n end\n end\n return @seq_count\n end", "def startstop minsize=30\n stopstop(minsize).find_all { | orf | \n codon1= orf.nt.seq[0..2].upcase\n ['ATG','TTG','CTG','AUG','UUG','CUG'].index(codon1) != nil\n }\n end", "def sequence_locator(seq=\"\",temp_dir=File.dirname($0))\n hxb2_ref = \"TGGAAGGGCTAATTCACTCCCAACGAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTAGCAGAACTACACACCAGGGCCAGGGATCAGATATCCACTGACCTTTGGATGGTGCTACAAGCTAGTACCAGTTGAGCCAGAGAAGTTAGAAGAAGCCAACAAAGGAGAGAACACCAGCTTGTTACACCCTGTGAGCCTGCATGGAATGGATGACCCGGAGAGAGAAGTGTTAGAGTGGAGGTTTGACAGCCGCCTAGCATTTCATCACATGGCCCGAGAGCTGCATCCGGAGTACTTCAAGAACTGCTGACATCGAGCTTGCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATCCTGCATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTTCAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCAGTGGCGCCCGAACAGGGACCTGAAAGCGAAAGGGAAACCAGAGGAGCTCTCTCGACGCAGGACTCGGCTTGCTGAAGCGCGCACGGCAAGAGGCGAGGGGCGGCGACTGGTGAGTACGCCAAAAATTTTGACTAGCGGAGGCTAGAAGGAGAGAGATGGGTGCGAGAGCGTCAGTATTAAGCGGGGGAGAATTAGATCGATGGGAAAAAATTCGGTTAAGGCCAGGGGGAAAGAAAAAATATAAATTAAAACATATAGTATGGGCAAGCAGGGAGCTAGAACGATTCGCAGTTAATCCTGGCCTGTTAGAAACATCAGAAGGCTGTAGACAAATACTGGGACAGCTACAACCATCCCTTCAGACAGGATCAGAAGAACTTAGATCATTATATAATACAGTAGCAACCCTCTATTGTGTGCATCAAAGGATAGAGATAAAAGACACCAAGGAAGCTTTAGACAAGATAGAGGAAGAGCAAAACAAAAGTAAGAAAAAAGCACAGCAAGCAGCAGCTGACACAGGACACAGCAATCAGGTCAGCCAAAATTACCCTATAGTGCAGAACATCCAGGGGCAAATGGTACATCAGGCCATATCACCTAGAACTTTAAATGCATGGGTAAAAGTAGTAGAAGAGAAGGCTTTCAGCCCAGAAGTGATACCCATGTTTTCAGCATTATCAGAAGGAGCCACCCCACAAGATTTAAACACCATGCTAAACACAGTGGGGGGACATCAAGCAGCCATGCAAATGTTAAAAGAGACCATCAATGAGGAAGCTGCAGAATGGGATAGAGTGCATCCAGTGCATGCAGGGCCTATTGCACCAGGCCAGATGAGAGAACCAAGGGGAAGTGACATAGCAGGAACTACTAGTACCCTTCAGGAACAAATAGGATGGATGACAAATAATCCACCTATCCCAGTAGGAGAAATTTATAAAAGATGGATAATCCTGGGATTAAATAAAATAGTAAGAATGTATAGCCCTACCAGCATTCTGGACATAAGACAAGGACCAAAGGAACCCTTTAGAGACTATGTAGACCGGTTCTATAAAACTCTAAGAGCCGAGCAAGCTTCACAGGAGGTAAAAAATTGGATGACAGAAACCTTGTTGGTCCAAAATGCGAACCCAGATTGTAAGACTATTTTAAAAGCATTGGGACCAGCGGCTACACTAGAAGAAATGATGACAGCATGTCAGGGAGTAGGAGGACCCGGCCATAAGGCAAGAGTTTTGGCTGAAGCAATGAGCCAAGTAACAAATTCAGCTACCATAATGATGCAGAGAGGCAATTTTAGGAACCAAAGAAAGATTGTTAAGTGTTTCAATTGTGGCAAAGAAGGGCACACAGCCAGAAATTGCAGGGCCCCTAGGAAAAAGGGCTGTTGGAAATGTGGAAAGGAAGGACACCAAATGAAAGATTGTACTGAGAGACAGGCTAATTTTTTAGGGAAGATCTGGCCTTCCTACAAGGGAAGGCCAGGGAATTTTCTTCAGAGCAGACCAGAGCCAACAGCCCCACCAGAAGAGAGCTTCAGGTCTGGGGTAGAGACAACAACTCCCCCTCAGAAGCAGGAGCCGATAGACAAGGAACTGTATCCTTTAACTTCCCTCAGGTCACTCTTTGGCAACGACCCCTCGTCACAATAAAGATAGGGGGGCAACTAAAGGAAGCTCTATTAGATACAGGAGCAGATGATACAGTATTAGAAGAAATGAGTTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTTATCAAAGTAAGACAGTATGATCAGATACTCATAGAAATCTGTGGACATAAAGCTATAGGTACAGTATTAGTAGGACCTACACCTGTCAACATAATTGGAAGAAATCTGTTGACTCAGATTGGTTGCACTTTAAATTTTCCCATTAGCCCTATTGAGACTGTACCAGTAAAATTAAAGCCAGGAATGGATGGCCCAAAAGTTAAACAATGGCCATTGACAGAAGAAAAAATAAAAGCATTAGTAGAAATTTGTACAGAGATGGAAAAGGAAGGGAAAATTTCAAAAATTGGGCCTGAAAATCCATACAATACTCCAGTATTTGCCATAAAGAAAAAAGACAGTACTAAATGGAGAAAATTAGTAGATTTCAGAGAACTTAATAAGAGAACTCAAGACTTCTGGGAAGTTCAATTAGGAATACCACATCCCGCAGGGTTAAAAAAGAAAAAATCAGTAACAGTACTGGATGTGGGTGATGCATATTTTTCAGTTCCCTTAGATGAAGACTTCAGGAAGTATACTGCATTTACCATACCTAGTATAAACAATGAGACACCAGGGATTAGATATCAGTACAATGTGCTTCCACAGGGATGGAAAGGATCACCAGCAATATTCCAAAGTAGCATGACAAAAATCTTAGAGCCTTTTAGAAAACAAAATCCAGACATAGTTATCTATCAATACATGGATGATTTGTATGTAGGATCTGACTTAGAAATAGGGCAGCATAGAACAAAAATAGAGGAGCTGAGACAACATCTGTTGAGGTGGGGACTTACCACACCAGACAAAAAACATCAGAAAGAACCTCCATTCCTTTGGATGGGTTATGAACTCCATCCTGATAAATGGACAGTACAGCCTATAGTGCTGCCAGAAAAAGACAGCTGGACTGTCAATGACATACAGAAGTTAGTGGGGAAATTGAATTGGGCAAGTCAGATTTACCCAGGGATTAAAGTAAGGCAATTATGTAAACTCCTTAGAGGAACCAAAGCACTAACAGAAGTAATACCACTAACAGAAGAAGCAGAGCTAGAACTGGCAGAAAACAGAGAGATTCTAAAAGAACCAGTACATGGAGTGTATTATGACCCATCAAAAGACTTAATAGCAGAAATACAGAAGCAGGGGCAAGGCCAATGGACATATCAAATTTATCAAGAGCCATTTAAAAATCTGAAAACAGGAAAATATGCAAGAATGAGGGGTGCCCACACTAATGATGTAAAACAATTAACAGAGGCAGTGCAAAAAATAACCACAGAAAGCATAGTAATATGGGGAAAGACTCCTAAATTTAAACTGCCCATACAAAAGGAAACATGGGAAACATGGTGGACAGAGTATTGGCAAGCCACCTGGATTCCTGAGTGGGAGTTTGTTAATACCCCTCCCTTAGTGAAATTATGGTACCAGTTAGAGAAAGAACCCATAGTAGGAGCAGAAACCTTCTATGTAGATGGGGCAGCTAACAGGGAGACTAAATTAGGAAAAGCAGGATATGTTACTAATAGAGGAAGACAAAAAGTTGTCACCCTAACTGACACAACAAATCAGAAGACTGAGTTACAAGCAATTTATCTAGCTTTGCAGGATTCGGGATTAGAAGTAAACATAGTAACAGACTCACAATATGCATTAGGAATCATTCAAGCACAACCAGATCAAAGTGAATCAGAGTTAGTCAATCAAATAATAGAGCAGTTAATAAAAAAGGAAAAGGTCTATCTGGCATGGGTACCAGCACACAAAGGAATTGGAGGAAATGAACAAGTAGATAAATTAGTCAGTGCTGGAATCAGGAAAGTACTATTTTTAGATGGAATAGATAAGGCCCAAGATGAACATGAGAAATATCACAGTAATTGGAGAGCAATGGCTAGTGATTTTAACCTGCCACCTGTAGTAGCAAAAGAAATAGTAGCCAGCTGTGATAAATGTCAGCTAAAAGGAGAAGCCATGCATGGACAAGTAGACTGTAGTCCAGGAATATGGCAACTAGATTGTACACATTTAGAAGGAAAAGTTATCCTGGTAGCAGTTCATGTAGCCAGTGGATATATAGAAGCAGAAGTTATTCCAGCAGAAACAGGGCAGGAAACAGCATATTTTCTTTTAAAATTAGCAGGAAGATGGCCAGTAAAAACAATACATACTGACAATGGCAGCAATTTCACCGGTGCTACGGTTAGGGCCGCCTGTTGGTGGGCGGGAATCAAGCAGGAATTTGGAATTCCCTACAATCCCCAAAGTCAAGGAGTAGTAGAATCTATGAATAAAGAATTAAAGAAAATTATAGGACAGGTAAGAGATCAGGCTGAACATCTTAAGACAGCAGTACAAATGGCAGTATTCATCCACAATTTTAAAAGAAAAGGGGGGATTGGGGGGTACAGTGCAGGGGAAAGAATAGTAGACATAATAGCAACAGACATACAAACTAAAGAATTACAAAAACAAATTACAAAAATTCAAAATTTTCGGGTTTATTACAGGGACAGCAGAAATCCACTTTGGAAAGGACCAGCAAAGCTCCTCTGGAAAGGTGAAGGGGCAGTAGTAATACAAGATAATAGTGACATAAAAGTAGTGCCAAGAAGAAAAGCAAAGATCATTAGGGATTATGGAAAACAGATGGCAGGTGATGATTGTGTGGCAAGTAGACAGGATGAGGATTAGAACATGGAAAAGTTTAGTAAAACACCATATGTATGTTTCAGGGAAAGCTAGGGGATGGTTTTATAGACATCACTATGAAAGCCCTCATCCAAGAATAAGTTCAGAAGTACACATCCCACTAGGGGATGCTAGATTGGTAATAACAACATATTGGGGTCTGCATACAGGAGAAAGAGACTGGCATTTGGGTCAGGGAGTCTCCATAGAATGGAGGAAAAAGAGATATAGCACACAAGTAGACCCTGAACTAGCAGACCAACTAATTCATCTGTATTACTTTGACTGTTTTTCAGACTCTGCTATAAGAAAGGCCTTATTAGGACACATAGTTAGCCCTAGGTGTGAATATCAAGCAGGACATAACAAGGTAGGATCTCTACAATACTTGGCACTAGCAGCATTAATAACACCAAAAAAGATAAAGCCACCTTTGCCTAGTGTTACGAAACTGACAGAGGATAGATGGAACAAGCCCCAGAAGACCAAGGGCCACAGAGGGAGCCACACAATGAATGGACACTAGAGCTTTTAGAGGAGCTTAAGAATGAAGCTGTTAGACATTTTCCTAGGATTTGGCTCCATGGCTTAGGGCAACATATCTATGAAACTTATGGGGATACTTGGGCAGGAGTGGAAGCCATAATAAGAATTCTGCAACAACTGCTGTTTATCCATTTTCAGAATTGGGTGTCGACATAGCAGAATAGGCGTTACTCGACAGAGGAGAGCAAGAAATGGAGCCAGTAGATCCTAGACTAGAGCCCTGGAAGCATCCAGGAAGTCAGCCTAAAACTGCTTGTACCAATTGCTATTGTAAAAAGTGTTGCTTTCATTGCCAAGTTTGTTTCATAACAAAAGCCTTAGGCATCTCCTATGGCAGGAAGAAGCGGAGACAGCGACGAAGAGCTCATCAGAACAGTCAGACTCATCAAGCTTCTCTATCAAAGCAGTAAGTAGTACATGTAACGCAACCTATACCAATAGTAGCAATAGTAGCATTAGTAGTAGCAATAATAATAGCAATAGTTGTGTGGTCCATAGTAATCATAGAATATAGGAAAATATTAAGACAAAGAAAAATAGACAGGTTAATTGATAGACTAATAGAAAGAGCAGAAGACAGTGGCAATGAGAGTGAAGGAGAAATATCAGCACTTGTGGAGATGGGGGTGGAGATGGGGCACCATGCTCCTTGGGATGTTGATGATCTGTAGTGCTACAGAAAAATTGTGGGTCACAGTCTATTATGGGGTACCTGTGTGGAAGGAAGCAACCACCACTCTATTTTGTGCATCAGATGCTAAAGCATATGATACAGAGGTACATAATGTTTGGGCCACACATGCCTGTGTACCCACAGACCCCAACCCACAAGAAGTAGTATTGGTAAATGTGACAGAAAATTTTAACATGTGGAAAAATGACATGGTAGAACAGATGCATGAGGATATAATCAGTTTATGGGATCAAAGCCTAAAGCCATGTGTAAAATTAACCCCACTCTGTGTTAGTTTAAAGTGCACTGATTTGAAGAATGATACTAATACCAATAGTAGTAGCGGGAGAATGATAATGGAGAAAGGAGAGATAAAAAACTGCTCTTTCAATATCAGCACAAGCATAAGAGGTAAGGTGCAGAAAGAATATGCATTTTTTTATAAACTTGATATAATACCAATAGATAATGATACTACCAGCTATAAGTTGACAAGTTGTAACACCTCAGTCATTACACAGGCCTGTCCAAAGGTATCCTTTGAGCCAATTCCCATACATTATTGTGCCCCGGCTGGTTTTGCGATTCTAAAATGTAATAATAAGACGTTCAATGGAACAGGACCATGTACAAATGTCAGCACAGTACAATGTACACATGGAATTAGGCCAGTAGTATCAACTCAACTGCTGTTAAATGGCAGTCTAGCAGAAGAAGAGGTAGTAATTAGATCTGTCAATTTCACGGACAATGCTAAAACCATAATAGTACAGCTGAACACATCTGTAGAAATTAATTGTACAAGACCCAACAACAATACAAGAAAAAGAATCCGTATCCAGAGAGGACCAGGGAGAGCATTTGTTACAATAGGAAAAATAGGAAATATGAGACAAGCACATTGTAACATTAGTAGAGCAAAATGGAATAACACTTTAAAACAGATAGCTAGCAAATTAAGAGAACAATTTGGAAATAATAAAACAATAATCTTTAAGCAATCCTCAGGAGGGGACCCAGAAATTGTAACGCACAGTTTTAATTGTGGAGGGGAATTTTTCTACTGTAATTCAACACAACTGTTTAATAGTACTTGGTTTAATAGTACTTGGAGTACTGAAGGGTCAAATAACACTGAAGGAAGTGACACAATCACCCTCCCATGCAGAATAAAACAAATTATAAACATGTGGCAGAAAGTAGGAAAAGCAATGTATGCCCCTCCCATCAGTGGACAAATTAGATGTTCATCAAATATTACAGGGCTGCTATTAACAAGAGATGGTGGTAATAGCAACAATGAGTCCGAGATCTTCAGACCTGGAGGAGGAGATATGAGGGACAATTGGAGAAGTGAATTATATAAATATAAAGTAGTAAAAATTGAACCATTAGGAGTAGCACCCACCAAGGCAAAGAGAAGAGTGGTGCAGAGAGAAAAAAGAGCAGTGGGAATAGGAGCTTTGTTCCTTGGGTTCTTGGGAGCAGCAGGAAGCACTATGGGCGCAGCCTCAATGACGCTGACGGTACAGGCCAGACAATTATTGTCTGGTATAGTGCAGCAGCAGAACAATTTGCTGAGGGCTATTGAGGCGCAACAGCATCTGTTGCAACTCACAGTCTGGGGCATCAAGCAGCTCCAGGCAAGAATCCTGGCTGTGGAAAGATACCTAAAGGATCAACAGCTCCTGGGGATTTGGGGTTGCTCTGGAAAACTCATTTGCACCACTGCTGTGCCTTGGAATGCTAGTTGGAGTAATAAATCTCTGGAACAGATTTGGAATCACACGACCTGGATGGAGTGGGACAGAGAAATTAACAATTACACAAGCTTAATACACTCCTTAATTGAAGAATCGCAAAACCAGCAAGAAAAGAATGAACAAGAATTATTGGAATTAGATAAATGGGCAAGTTTGTGGAATTGGTTTAACATAACAAATTGGCTGTGGTATATAAAATTATTCATAATGATAGTAGGAGGCTTGGTAGGTTTAAGAATAGTTTTTGCTGTACTTTCTATAGTGAATAGAGTTAGGCAGGGATATTCACCATTATCGTTTCAGACCCACCTCCCAACCCCGAGGGGACCCGACAGGCCCGAAGGAATAGAAGAAGAAGGTGGAGAGAGAGACAGAGACAGATCCATTCGATTAGTGAACGGATCCTTGGCACTTATCTGGGACGATCTGCGGAGCCTGTGCCTCTTCAGCTACCACCGCTTGAGAGACTTACTCTTGATTGTAACGAGGATTGTGGAACTTCTGGGACGCAGGGGGTGGGAAGCCCTCAAATATTGGTGGAATCTCCTACAGTATTGGAGTCAGGAACTAAAGAATAGTGCTGTTAGCTTGCTCAATGCCACAGCCATAGCAGTAGCTGAGGGGACAGATAGGGTTATAGAAGTAGTACAAGGAGCTTGTAGAGCTATTCGCCACATACCTAGAAGAATAAGACAGGGCTTGGAAAGGATTTTGCTATAAGATGGGTGGCAAGTGGTCAAAAAGTAGTGTGATTGGATGGCCTACTGTAAGGGAAAGAATGAGACGAGCTGAGCCAGCAGCAGATAGGGTGGGAGCAGCATCTCGAGACCTGGAAAAACATGGAGCAATCACAAGTAGCAATACAGCAGCTACCAATGCTGCTTGTGCCTGGCTAGAAGCACAAGAGGAGGAGGAGGTGGGTTTTCCAGTCACACCTCAGGTACCTTTAAGACCAATGACTTACAAGGCAGCTGTAGATCTTAGCCACTTTTTAAAAGAAAAGGGGGGACTGGAAGGGCTAATTCACTCCCAAAGAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTAGCAGAACTACACACCAGGGCCAGGGGTCAGATATCCACTGACCTTTGGATGGTGCTACAAGCTAGTACCAGTTGAGCCAGATAAGATAGAAGAGGCCAATAAAGGAGAGAACACCAGCTTGTTACACCCTGTGAGCCTGCATGGGATGGATGACCCGGAGAGAGAAGTGTTAGAGTGGAGGTTTGACAGCCGCCTAGCATTTCATCACGTGGCCCGAGAGCTGCATCCGGAGTACTTCAAGAACTGCTGACATCGAGCTTGCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATCCTGCATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTTCAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCA\"\n hxb2_l = hxb2_ref.size\n head = \"\"\n 8.times {head << (65 + rand(25)).chr}\n temp_file = temp_dir + \"/\" + head + \"_temp\"\n temp_aln = temp_dir + \"/\" + head + \"_temp_aln\"\n\n l1 = 0\n l2 = 0\n name = \">test\"\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts hxb2_ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n\n begin\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test2 = $2\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n ref_size = ref.size\n if ref_size > 1.3*(seq.size)\n l1 = l1 + gap_begin\n l2 = l2 + gap_end\n max_seq = aln_test2.scan(/[ACGT]+/).max_by(&:length)\n aln_test2 =~ /#{max_seq}/\n before_aln_seq = $`\n before_aln = $`.size\n post_aln_seq = $'\n post_aln = $'.size\n before_aln_seq_size = before_aln_seq.scan(/[ACGT]+/).join(\"\").size\n b1 = (1.3 * before_aln_seq_size).to_i\n post_aln_seq_size = post_aln_seq.scan(/[ACGT]+/).join(\"\").size\n b2 = (1.3 * post_aln_seq_size).to_i\n if (before_aln > seq.size) and (post_aln <= seq.size)\n ref = ref[(before_aln - b1)..(ref_size - post_aln - 1)]\n l1 = l1 + (before_aln - b1)\n elsif (post_aln > seq.size) and (before_aln <= seq.size)\n ref = ref[before_aln..(ref_size - post_aln - 1 + b2)]\n l2 = l2 + post_aln - b2\n elsif (post_aln > seq.size) and (before_aln > seq.size)\n ref = ref[(before_aln - b1)..(ref_size - post_aln - 1 + b2)]\n l1 = l1 + (before_aln - b1)\n l2 = l2 + (post_aln - b2)\n end\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test2 = $2\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n ref_size = ref.size\n end\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test = $2\n aln_test =~ /^(\\w+)(\\-*)\\w/\n s1 = $1.size\n g1 = $2.size\n aln_test =~ /\\w(\\-*)(\\w+)$/\n s2 = $2.size\n g2 = $1.size\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n\n l1 = l1 + gap_begin\n l2 = l2 + gap_end\n repeat = 0\n\n if g1 == g2 and (s1 + g1 + s2) == ref.size\n if s1 > s2 and g2 > 2*s2\n ref = ref[0..(-g2-1)]\n repeat = 1\n l2 = l2 + g2\n elsif s1 < s2 and g1 > 2*s1\n ref = ref[g1..-1]\n repeat = 1\n l1 = l1 + g1\n end\n else\n if g1 > 2*s1\n ref = ref[g1..-1]\n repeat = 1\n l1 = l1 + g1\n end\n if g2 > 2*s2\n ref = ref[0..(-g2 - 1)]\n repeat = 1\n l2 = l2 + g2\n end\n end\n\n while repeat == 1\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test = $2\n aln_test =~ /^(\\w+)(\\-*)\\w/\n s1 = $1.size\n g1 = $2.size\n aln_test =~ /\\w(\\-*)(\\w+)$/\n s2 = $2.size\n g2 = $1.size\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n l1 = l1 + gap_begin\n l2 = l2 + gap_end\n repeat = 0\n if g1 > 2*s1\n ref = ref[g1..-1]\n repeat = 1\n l1 = l1 + g1\n end\n if g2 > 2*s2\n ref = ref[0..(-g2 - 1)]\n repeat = 1\n l2 = l2 + g2\n end\n end\n ref = hxb2_ref[l1..(hxb2_l - l2 - 1)]\n\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n ref = aln_seq[\">ref\"]\n\n #refine alignment\n\n if ref =~ /^(\\-+)/\n l1 = l1 - $1.size\n elsif ref =~ /(\\-+)$/\n l2 = l2 + $1.size\n end\n\n if (hxb2_l - l2 - 1) >= l1\n ref = hxb2_ref[l1..(hxb2_l - l2 - 1)]\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n ref = aln_seq[\">ref\"]\n\n ref_size = ref.size\n sim_count = 0\n (0..(ref_size-1)).each do |n|\n ref_base = ref[n]\n test_base = aln_test[n]\n sim_count += 1 if ref_base == test_base\n end\n similarity = (sim_count/ref_size.to_f*100).round(1)\n print `rm -f #{temp_file}`\n print `rm -f #{temp_aln}`\n loc_p1 = l1 + 1\n loc_p2 = hxb2_l - l2\n if seq.size != (loc_p2 - loc_p1 + 1)\n indel = true\n elsif aln_test.include?(\"-\")\n indel = true\n else\n indel = false\n end\n return [loc_p1,loc_p2,similarity,indel,aln_test,ref]\n else\n return [0,0,0,0,0,0,0]\n end\n rescue\n print `rm -f #{temp_file}`\n print `rm -f #{temp_aln}`\n return [0,0,0,0,0,0,0]\n end\nend", "def find_valid_data filename\n start = 0\n dbfile = File.new(filename)\n s = dbfile.gets\n while s[0] == ?# or s[0]==?\\n\n start+= s.size\n s = dbfile.gets\n end\n dbfile.seek(-128, File::SEEK_END)\n s = dbfile.read(128).chomp;\n last = s.rindex(\"\\n\");\n dbfile.close\n return [start-1,File.size(filename) - last]\nend", "def fastq_to_fasta(fastq_file)\n count = 0\n sequence_a = []\n count_seq = 0\n\n File.open(fastq_file,'r') do |file|\n file.readlines.collect do |line|\n count +=1\n count_m = count % 4\n if count_m == 1\n line.tr!('@','>')\n sequence_a << line.chomp\n count_seq += 1\n elsif count_m == 2\n sequence_a << line.chomp\n end\n end\n end\n sequence_hash = Hash[*sequence_a]\nend", "def find_start(line, len)\n (stream,answer) = line.split(':')\n return if stream.nil?\n stream.chars.each_with_index do |c, i|\n # take slice of array starting at i\n # check if uniq.\n sub = stream[i..i+len-1]\n \n if sub.chars.uniq.length == len\n puts \"sub=#{sub}\" \n puts \"found at index=#{i} chars recv=#{i+len} answer=#{answer}\"\n return\n end\n end \nend", "def read_fastq\n\n seq_name = nil\n seq_fasta = nil\n seq_qual = nil\n comments = nil\n\n reading = :fasta\n\n if !@fastq_file.eof\n\n begin\n #read four lines\n name_line = @fastq_file.readline.chomp\n seq_fasta = @fastq_file.readline.chomp\n name2_line = @fastq_file.readline.chomp\n seq_qual = @fastq_file.readline.chomp\n \n \n # if there is no qual, but there is a fasta\n if seq_qual.empty? && !seq_fasta.empty?\n seq_qual = 'D'*seq_fasta.length\n end\n\n\n # parse name\n if name_line =~ /^@\\s*([^\\s]+)\\s*(.*)$/\n # remove comments\n seq_name = $1\n comments=$2\n else\n raise \"Invalid sequence name in #{name_line}\"\n end\n\n # parse fasta\n seq_fasta.strip! if !seq_fasta.empty?\n\n # parse qual_name\n\n if !seq_name.nil? && !seq_qual.empty?\n\n @num_seqs += 1\n\n if @qual_to_phred\n seq_qual=seq_qual.each_char.map{|e| (@to_phred.call(e.ord))}\n\n if !@qual_to_array\n seq_qual=seq_qual.join(' ')\n end\n end\n\n end\n rescue EOFError\n raise \"Bad format in FastQ file\"\n end\n end\n\n return [seq_name,seq_fasta,seq_qual,comments]\n end", "def map_tgup_by_proteinid()\n # output unmatch list for map by gene_id (prefix of gene_id is first char of gene_id. (\"1\", \"2\", ..))\n refg_output = {}\n FileUtils.mkdir_p(\"#{$prepare_dir}/refg\") unless File.exist?(\"#{$prepare_dir}/refg\")\n (1..9).each do |prefix|\n refg_output[prefix.to_s] = File.open(\"#{$prepare_dir}/refg/#{prefix.to_s}.dat\", \"w\")\n end\n\n output_header\n\n # try mapping the same prefix of RefSeq data and UniProt data(for performance)\n Dir.glob(\"#{$prepare_dir}/refp/*.dat\") do |input_file|\n # parse data\n refseq_gene_list = []\n protein_id_prefix = input_file.split(\"/\").last.split(\"\\.\").first\n puts \"protein_id prefix: #{protein_id_prefix}\"\n File.open(input_file) do |f|\n f.each_line do |line|\n columns = line.chomp.strip.split(\"\\t\")\n gene_id_prefix = columns[4].nil? ? \"\" : columns[4][0]\n refseq_gene_list.push({taxid: columns[0], gene_rsrc: columns[1], gene_label: columns[2], protein_id: columns[3], gene_id: columns[4], gene_id_prefix: gene_id_prefix})\n end\n end\n\n $count_nc += refseq_gene_list.size if protein_id_prefix == \"no_protein_id\" # no protein_id on RefSeq\n up_list = load_up_refp(protein_id_prefix) # get same prefix data from UniProt\n\n refseq_gene_list.each do |refseq_data|\n match = false\n output_tax(refseq_data) # output all gene-tax turtle\n unless up_list.nil? # exist prefix on UniProt\n match_list = up_list[refseq_data[:protein_id]]\n unless match_list.nil? # match some uniprot_ids\n match_list.each do |up_info|\n if refseq_data[:taxid] == up_info[:taxid] # ignore unmatch tax\n output_idmap(refseq_data, up_info[:upid])\n match = true\n else # match protein_id but not match tax_id\n output_uptax(up_info)\n $taxup_list[up_info[:taxid]] = true\n $tax_mismatch[\"#{refseq_data[:taxid]}-#{up_info[:taxid]} : #{refseq_data[:protein_id]}\"] = true\n end\n end\n end\n end\n if match == false\n if refseq_data[:gene_id_prefix].nil? ||refseq_data[:gene_id_prefix] == \"\" # can't salvage it by gene_id.\n $no_up += 1\n else # output a file to each prefix of gene_id that can be salvaged by gene_id\n line = [refseq_data[:taxid], refseq_data[:gene_rsrc], refseq_data[:gene_label], refseq_data[:protein_id], refseq_data[:gene_id], refseq_data[:gene_id_prefix]]\n refg_output[refseq_data[:gene_id_prefix]].puts(line.join(\"\\t\"))\n end\n end\n $count += 1\n end\n end\n refg_output.each do |k, v|\n v.flush\n v.close\n end\nend", "def single_segment?(str)\n raise InvalidGSMString unless can_encode?(str)\n\n extended_chars = str.gsub(GSM_NOT_EXTENDED_REGEX, '').length\n (str.length + extended_chars) <= GSM_SEGMENT_LENGTH\n end", "def encode_peptide(genome, amino_acid)\n # We say that a DNA string Pattern encodes an amino acid string Peptide if the \n # RNA string transcribed from either Pattern or its reverse complement Pattern translates into Peptide. \n # For example, the DNA string GAAACT is transcribed into GAAACU and translated into ET. \n # The reverse complement of this DNA string, AGTTTC, is transcribed into AGUUUC and translated into SF. \n # Thus, GAAACT encodes both ET and SF.”\n\n # Peptide Encoding Problem: Find substrings of a genome encoding a given amino acid sequence.\n # Input: A DNA string Text, an amino acid string Peptide, and the array GeneticCode.\n # Output: All substrings of Text encoding Peptide (if any such substrings exist). \n\n match_dna = []\n codon_length = 3\n rna_seq_length = (amino_acid.length * codon_length)\n \n rna = dna_to_rna(genome)\n i = 0\n while (rna_seq = rna.slice(i, rna_seq_length )) do\n # puts rna_seq\n match_dna << rna_to_dna(rna_seq) if rna_peptide_match?(rna_seq, amino_acid)\n i += 1\n end\n\n rna = dna_to_rna(reverse_complement(genome))\n # puts rna\n i = 0\n while (rna_seq = rna.slice(i, rna_seq_length )) do\n # puts rna_seq\n match_dna << reverse_complement(rna_to_dna(rna_seq)) if rna_peptide_match?(rna_seq, amino_acid)\n i += 1\n end\n\n match_dna\n end", "def uniqueSequences file\n\n seqIDs = {}\n printSeq = 1\n File.open(file,\"r\") do |f|\n while l = f.gets\n if l[0] == \">\"\n key = l.split(\"\\n\")[0].split(\" \")[0]\n if seqIDs.has_key? key\n printSeq = 0\n else\n seqIDs[\"#{key}\"] = 0\n printSeq = 1\n puts l\n end\n elsif printSeq == 1\n puts l\n end\n end\n end\n\n end", "def read_online_fasta(url)\r\n fasta_name = \"\"\r\n fasta_seqs = {}\r\n seq = \"\"\r\n open(url) do |file|\r\n file.read.split(\"\\n\").each do |line|\r\n if !(line.nil?)\r\n if line.start_with? \">\"\r\n seq = \"\"\r\n fasta_name = line.split(\">\")[1]\r\n elsif\r\n seq = seq + line\r\n fasta_seqs[fasta_name] = seq\r\n end\r\n end\r\n end\r\n end\r\n return fasta_seqs\r\nend" ]
[ "0.65658635", "0.6229822", "0.6187336", "0.618514", "0.5756286", "0.5658233", "0.5630377", "0.5629821", "0.56086355", "0.5585795", "0.55313164", "0.55205417", "0.5448123", "0.54455477", "0.5390017", "0.5388496", "0.5386979", "0.52642334", "0.52577657", "0.52539676", "0.52477664", "0.5232419", "0.52202773", "0.52183807", "0.5176997", "0.51700765", "0.5151293", "0.51244074", "0.5117429", "0.50971234" ]
0.6445481
1
store books in array
def add_books(books) books.each do |book| @books.push(book) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_book(book)\n\t\t@books.push(book)\t\n\tend", "def loadBooks()\n @@bookid_count+=1\n book1 = Book.new(@@bookid_count, \"Harry Potter\", \"JK Rowling\", \"Bloomsbury\", 2010, 5, 5, 5)\n @@bookid_count+=1\n book2 = Book.new(@@bookid_count, \"The Alchemist\", \"Paulho Coelho\", \"HarperTorch\", 1998, 2, 2, 2)\n @@bookid_count+=1\n book3 = Book.new(@@bookid_count, \"Operating Systems\", \"V.Kumar\", \"Techmax\", 2018, 8, 5, 5)\n @@bookid_count+=1\n book4 = Book.new(@@bookid_count, \"Data Mining\", \"Robert Shaw\", \"O Reilly\", 2016, 8, 5, 5)\n @@bookid_count+=1\n book5 = Book.new(@@bookid_count, \"Machine Learning\", \"Tom Mitchell\", \"O Reilly\", 2016, 3, 2, 2)\n\n @books += [book1, book2, book3, book4, book5]\n end", "def add_my_books(book)\n\t\t@my_books << book.title\n\tend", "def add_book(book)\n @books << book\n end", "def add_book(book)\n @books.push(book)\n end", "def add(book)\n\t\t @books << book\n\tend", "def add_book(book)\n @books.push(book)\n puts \"You've added '#{book.title}' to the Library.\"\n puts \"You know have \" + @books.length.to_s + \" books in the Library.\"\n end", "def add_book(book)\n\t\t@books << book\n\t\t@book_status[book.title] = book.get_status\n\tend", "def books \n @books\n end", "def add_book(title)\n new_book = {\n title: title,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }\n }\n @books.push(new_book)\n return @books.length\n end", "def purchase_books(newbooks)\n\t\tnewbooks.each {|book, number| inventory[book] = number}\n\tend", "def addBook(book)\n\t\tinventories.create(book_id: book.id)\n\tend", "def add_book_to_inventory_by_book_title(new_book_title)\n new_book_array =\n {\n title: new_book_title,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }\n }\n new_book_title != @title\n @inventory.push(new_book_array)\nend", "def initialize(books)\n # initialize is a ruby function\n @books = books # we have our array of books hashes\n end", "def add( book )\n @books.add( Books::Book.new( book ))\n end", "def add_book(book_title)\n @books << {\n title: book_title,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }\n }\n end", "def add_to_listbooks\n self.isbn.each do |isbn|\n book = Listbook.find_or_create_by(isbn: isbn)\n self.listbooks << book unless self.listbooks.include? book\n book.save!\n end\n self.pinned_isbn.each do |isbn|\n book = Listbook.find_or_create_by(isbn: isbn)\n self.listbooks << book unless self.listbooks.include? book\n book.save!\n end\n\n self.listbooks.uniq!\n end", "def add_book(book)\n @books << book\n puts \"Added \" + book.title + \" to the library.\"\n end", "def test_book_list\n @library = Library.new(@books_array)\n books = @library.book_list\n end", "def book_adding\n puts 'Ma so :'\n isbn = gets.chomp.to_s\n\n puts 'Ten sach :'\n title = gets.chomp.to_s\n\n puts 'Chu de :'\n subject = gets.chomp.to_s\n\n puts 'Tac gia :'\n author = gets.chomp.to_s\n\n puts 'Nha xuat ban :'\n publisher = gets.chomp.to_s\n\n puts 'Ngay xuat ban :'\n date = gets.chomp.to_s\n\n puts 'So trang :'\n pages = gets.chomp.to_s\n\n puts 'So ban copy :'\n copies = gets.chomp.to_s\n\n new_book = Book.new(isbn, title, subject, author, publisher, date, pages, copies)\n\n $books_array.push(new_book.to_hash)\n\n File.open(\"Books.json\", \"w+\") do |f|\n f.puts($books_array.to_json)\n end\n puts \"Da them sach moi thanh cong. Bam ENTER de tiep tuc\"\n gets.chomp\nend", "def save\n # add the id to the book list\n @hub.lpush('book:list', @id)\n\n # creates the couples key-values where we store our data\n BOOK_STRING_ATTRS.each do |attr|\n @hub.set(\"book:#{@id}:#{attr}\", self.send(attr.to_sym))\n end\n\n # creates a set containing all the topic id associated to our book\n # and add the book id to the set of all the books belonging to the\n # same topic\n @topics.each do |topic|\n tid = (topic.is_a?(Book)) ? topic.id : topic\n @hub.sadd(\"book:#{@id}:topics\", tid)\n Topic.add_book(tid, id)\n end\n \n # create a set containing all the authors id of our book and add\n # the book id to the set of all the books belonging to the same\n # author\n @authors.each do |author|\n aid = (author.is_a?(Author)) ? author.id : author\n @hub.sadd(\"book:#{@id}:authors\", author)\n Author.add_book(author, id)\n end\n end", "def books\n self.book_authors.map {|book_author| book_author.book}\n end", "def add(num)\n #item = '9781133049791'\n item = num.fetch(\"isbn\")\n if !Book.pluck(:isbn).include?(item)\n @res = Amazon::Ecs.item_search(item, { :search_index => 'All', :response_group => 'Medium' })\n @res.items.each do |book|\n @db = Book.create\n @db.isbn = item\n @db.author = book.get('ItemAttributes/Author')\n @db.name = book.get('ItemAttributes/Title')\n @db.edition = book.get('ItemAttributes/Edition').to_i\n @db.retail_price = ((book.get('ItemAttributes/ListPrice/Amount').to_f/100)*3.65).to_i\n @db.description = book.get('EditorialReviews/EditorialReview/Content')\n @db.photo = book.get('LargeImage/URL')\n @db.save\n end\n end\n @thisBook = Book.find(:all, :conditions => {:isbn => item})\n redirect_to @thisBook\n end", "def create\n @book = Book.new(book_params)\n #for author_id in params[:authors_ids]\n # @book.authors << Author.find(author_id)\n #end\n\n respond_to do |format|\n if @book.save\n format.html { redirect_to @book, notice: 'Book was successfully created.' }\n format.json { render :show, status: :created, location: @book }\n else\n format.html { render :new }\n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_book(book)\n self.book_lists.create(:book_id => book.id)\n end", "def get_books()\n @books_out\n end", "def get_books()\n @books_out\n end", "def addBooks()\n ch = 1\n while ch == 1\n puts \"Enter Book Title: \"\n title = gets\n puts \"Enter Book Author: \"\n author = gets\n puts \"Enter Publication: \"\n publication = gets\n puts \"Enter Rack number: \"\n rack_no = gets\n puts \"Enter publication year: \"\n year = gets\n puts \"Total number of copies: \"\n total_copies = gets\n\n @@bookid_count+=1\n \n book = Book.new(@@bookid_count, title, author, publication, year, rack_no, total_copies, total_copies)\n @books.push(book)\n\n puts \"Add more books? Enter 1 or 0. YES=1, NO=0 \"\n ch = gets.to_i\n end\n end", "def returnbook\n @books = Book.all \n end", "def cookbookshelf\n \n cbs = Recipe.find_by_sql \"SELECT DISTINCT cookbook_id FROM recipes\"\n @indexedbooks = Array.new\n cbs.each do |cb|\n cbtitle = cb.cookbook.title.gsub(/^(.{50}[\\w.]*)(.*)/) {$2.empty? ? $1 : $1 + '...'}\n cb_details = {\n :id => cb.cookbook_id,\n :ISBN => cb.cookbook.ISBN,\n :author => cb.cookbook.author.name,\n :title => cbtitle\n }\n \n @indexedbooks << cb_details\n \n @indexedbooks = @indexedbooks.sort_by { |cookbook| cookbook[:author] }\n end\n respond_to do |format|\n format.html\n end\n end" ]
[ "0.73641175", "0.73614067", "0.72606206", "0.7210309", "0.718929", "0.71613777", "0.68064034", "0.673333", "0.6654052", "0.65733045", "0.6552979", "0.64787984", "0.6469766", "0.6461582", "0.64436615", "0.6432072", "0.6398421", "0.6390026", "0.63399297", "0.63367707", "0.633475", "0.63301283", "0.6319215", "0.6307558", "0.6297377", "0.62722224", "0.62722224", "0.6267466", "0.6251027", "0.6201841" ]
0.7732529
0
store users in an array
def add_users(users) users.each do |user| @users.push(user) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def loadUsers()\n @@userid_count+=1\n user1 = User.new(@@userid_count, \"Shweta\", \"Dublin 1\", 1, Array.new)\n @@userid_count+=1\n user2 = User.new(@@userid_count, \"Chirag\", \"Dublin 2\", 5, Array.new)\n @@userid_count+=1\n user3 = User.new(@@userid_count, \"Karishma\", \"Galway\", 5, Array.new)\n\n @users += [user1, user2, user3]\n end", "def users\n return @users_array\n \tend", "def users\n user_arr = []\n accounts.each do |s|\n user_arr << User.find(s.user.id)\n end\n user_arr\n end", "def process_users(users)\n users.each do |element|\n user = User.new(element, @bot)\n @users[user.id] = user\n end\n end", "def initialize\n @Users = Array.new \n end", "def users=(value)\n @users = value\n end", "def set_users\n @users = []\n \n if user_signed_in\n @users << current_user.tweets(:sort){:time_stamp}\n else\n User.all.each do |user|\n @users << user.tweets(:sort){:time_stamp}\n end\n end\n end", "def users() @users = DiggUsers.new end", "def save\r\n @@users.push self\r\n end", "def users=(params)\n @users = params.values.map { |r| UserImport::User.new(r.values) }\n end", "def users\n []\n end", "def get_all_users\n @users = []\n\n User.all.each do|user|\n @users << user.to_hash\n end\n end", "def get_all_users\n @users = []\n User.all.each do |user|\n @users << user.to_hash\n end\n end", "def my_users\n self.users + [self.user]\n end", "def add_user(user)\n @users << user\n end", "def add_users(ids)\n\t\t self.shared_users = ids.split(\",\").map do |id|\n \t\tUser.where(id: id.strip).first_or_create!\n \tend\n\tend", "def addToUserList\n $store << [@email,@username,@password]\n puts \"Added user to list\"\n print $store.to_s + \"\\n\"\n end", "def get_all_users\n @users = []\n results = User.all\n results.each do |user|\n @users << user.to_hash\n end\n end", "def research_individual\n @users = Array.new()\n User.all.each do |u|\n if !u.admin?\n @users.push(u)\n end\n end\n end", "def users\n user_arr = []\n subscriptions.each do |s|\n user_arr << User.find(s.user.id)\n end\n user_arr\n end", "def users\n @users ||= rows.map { |r| UserImport::User.new(r) }\n end", "def users=(array)\r\n ids = array.map(&:id)\r\n UserAccess.where(['user_accesses.access_id = ? AND user_accesses.user_id NOT IN (?)', self.id, ids]).select(:id).each(&:destroy)\r\n user_access_ids = UserAccess.all(:conditions => {:access_id => self.id, :user_id => ids}, :select => 'user_id').map(&:user_id)\r\n (ids - user_access_ids).each{|i|\r\n UserAccess.create(:access_id => self.id, :user_id => i)\r\n }\r\n self.users.reload\r\n end", "def store_user(name)\n if @users == nil\n @current_user = User.new\n @current_user.name = name\n @users = [@current_user]\n else\n if @users.select{|user| user.name == name} == []\n @current_user = User.new\n @current_user.name = name\n @users << @current_user\n else\n @current_user = @users.select{|user| user.name == name}.first\n end\n end\n end", "def users=(user_ids)\n self.users.delete_all # Not very pretty\n user_ids.each do |user_id|\n self.users << User.find(user_id) unless user_id.blank?\n end\n end", "def get_users_a\n\n return [] if self.users.nil? or self.users.empty?\n\n array = self.users.split('|')\n array.compact!\n array.delete('')\n\n return array\n end", "def users\n @users.each_key.to_a\n end", "def load_users\n user_set = Set[]\n @users_config.each_key do |provider|\n @users_config[provider].each do |a|\n add_user(a, user_set, provider)\n end\n end\n add_users_to_group(user_set)\n end", "def save\n @@userList.push self\n self\n end", "def users\n users_array = []\n if serialization_options[:include_users] == true\n # NOTE: object here refers to the ActiveRecord model object. self refers to the serializer object itself.\n object.users.each do |user|\n # NOTE: You can pass serialization_options to serializable_hash.\n users_array << UserSerializer.new(user, {}).serializable_hash({})\n end\n end\n return users_array\n end", "def user_ids \n @user_ids ||= input[\"users\"].map{|user| user[\"id\"]}\nend" ]
[ "0.7351337", "0.7246826", "0.714973", "0.7116326", "0.705994", "0.7046836", "0.701369", "0.6917157", "0.6868712", "0.6843938", "0.6836045", "0.6833186", "0.6826418", "0.68129915", "0.67786384", "0.6778477", "0.6745208", "0.6743128", "0.6716426", "0.6712091", "0.66473705", "0.6627241", "0.6621613", "0.65970653", "0.6586584", "0.6584781", "0.6570036", "0.6561133", "0.65316075", "0.6528872" ]
0.7421838
0
expect_redirect_sessions_new good, as is
def expect_redirect_sessions_new @controller.expects(:redirect_to).with :controller => :sessions, :action => :new end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_guest_access_to_userland_gives_login_screen\n get '/in/index'\n assert last_response.redirect?\n follow_redirect!\n\n assert last_request.url.ends_with?(\"/login\")\n assert last_response.ok?\n assert last_response.body.include?('Login to continue') \n end", "def assert_redirected_to(url)\n assert [301, 302].include?(@integration_session.status),\n \"Expected status to be 301 or 302, got #{@integration_session.status}\"\n\n assert_url url, @integration_session.headers[\"Location\"]\n end", "def test_profile_url_redirects\r\n\r\n login_with_proper_credentials\r\n\r\n logout_using_gear_icon\r\n\r\n #Verify the redirection to the secure login takes place after signing out\r\n lynx_assert_actual_url(EXPECTED_HTTPS_URL, 'Not redirected to HTTPS login page after signingout using gear icon')\r\n\r\n $browser.goto(PROFILE_TO_ACCESS_AFTER_LOGOUT)\r\n sleep(1)\r\n\r\n lynx_assert_actual_url(EXPECTED_HTTPS_URL, 'Attempting to access a profile using profile URL after signing out using gear icon does not redirect to HTTPS login page')\r\n\r\n end", "def test_profile_url_redirects\r\n\r\n @place_holder.login_with_proper_credentials\r\n\r\n @place_holder.logout_using_gear_icon\r\n\r\n exp_https_url = PropertiesReader.get_exp_https_login_url\r\n #Verify the redirection to the secure login takes place after signing out\r\n @place_holder.assert_actual_url(exp_https_url, 'Not redirected to HTTPS login page after signing out using gear icon')\r\n\r\n @place_holder.go_to(PropertiesReader.get_recipient_profile_url)\r\n sleep(1)\r\n\r\n @place_holder.assert_actual_url(exp_https_url, 'Attempting to access a profile using profile URL after signing out using gear icon does not redirect to the HTTPS login page')\r\n\r\n end", "def assert_authenticate_user\n assert_redirected_to new_user_session_path(locale: nil)\n end", "def assert_redirected_to_login\n assert_not flash.empty?\n assert_redirected_to login_url\n end", "def expect_login_request_for page\n expect(page).to redirect_to(login_path)\n end", "def should_have_redirected_to(regex)\n last_response.redirect?.should == true\n last_response.location.should =~ regex\nend", "def test_session_expiry\n # Set the timeout really short\n settings = Goldberg::SystemSettings.find :first\n settings.session_timeout = 3 # Three seconds should be ample\n settings.save!\n\n form_login('admin', 'admin')\n get '/site_admin'\n assert_response :success\n\n # Wait longer than the timeout\n sleep 4\n get '/site_admin'\n assert_redirected_to :session_expired_page\n end", "def session!\n redirect(settings.session_fail) unless session? || settings.session_fail == request.path_info\n end", "def checklogin\n\t#check session validity\n\tredirect_to \"/my_test\"\nend", "def assert_redirected_to_login\n assert_equal({ :controller => 'goldberg/auth',\n :action => 'login' },\n response.redirected_to)\n end", "def redirect_ok\n @agent.redirect_ok\n end", "def test_gracefully_handle_bad_person_id\n @request.session[:person_id] = 31289371283\n @request.session[:person_credentials] = 31289371283\n get(:index)\n assert_redirected_to new_person_session_path\n end", "def expect_successful_login(user, target_url = nil)\n expect(controller.send(:current_user)).to eq(user)\n expect(controller.send(:current_group)).to eq(user.current_group)\n expect(response.body).to match(/location.href.*#{target_url}/)\n end", "def on_new_session(session)\n self.session_count += 1\n self.successful = true\n end", "def test_new_view\n get :new\n assert_response :redirect\n assert_redirected_to user_new_path(:cookie_test => \"true\")\n\n get :new, :params => { :cookie_test => \"true\" }, :session => { :cookie_test => true }\n assert_response :success\n\n assert_select \"html\", :count => 1 do\n assert_select \"head\", :count => 1 do\n assert_select \"title\", :text => /Sign Up/, :count => 1\n end\n assert_select \"body\", :count => 1 do\n assert_select \"div#content\", :count => 1 do\n assert_select \"form[action='/user/new'][method='post']\", :count => 1 do\n assert_select \"input[id='user_email']\", :count => 1\n assert_select \"input[id='user_email_confirmation']\", :count => 1\n assert_select \"input[id='user_display_name']\", :count => 1\n assert_select \"input[id='user_pass_crypt'][type='password']\", :count => 1\n assert_select \"input[id='user_pass_crypt_confirmation'][type='password']\", :count => 1\n assert_select \"input[type='submit'][value='Sign Up']\", :count => 1\n end\n end\n end\n end\n end", "def test_redirect_logged_in\n # log in\n admin = users(:olm_admin_1)\n post :login, :user_login => admin.user_name, :user_password => 'asfd'\n assert_redirected_to :action => \"index\"\n\n # try to go to login page when logged in\n get :login\n assert_redirected_to :action => \"index\"\n end", "def establish_session(request)\n #puts \"Request for: #{request.url} - running before...\"\n if ((session[:ip_address] != request.ip) or\n (session[:created_at] < (Time.now() - 60 * 20))) # Session older than 20 minutes?\n #puts \"This looks like a new user!\"\n session[:ip_address] = request.ip\n session[:created_at] = Time.now()\n user_id = DB[:users].insert(:ip_address => request.ip,\n :referrer => request.referrer,\n :created_at => session[:created_at])\n session[:user_id] = user_id\n redirect \"/survey/step/1\", 302\n end\nend", "def redirect_ok; end", "def redirect_ok; end", "def test_redirection_location\n process :redirect_internal\n assert_equal 'http://test.host/nothing', @response.redirect_url\n\n process :redirect_external\n assert_equal 'http://www.rubyonrails.org', @response.redirect_url\n end", "def redirect_ok=(follow); end", "def new_session?\n new_session != false\n end", "def new_session?\n new_session != false\n end", "def redirect_to(url)\n if !already_built_response?\n @res[\"location\"] = url\n @res.status = 302\n @already_built_response = true\n else\n raise \"exception\"\n end\n session.store_session(res)\n # storing the flash will fail the last spec\n flash.store_flash(res)\n end", "def ensure_logged_in\n redirect_to new_session_url unless logged_in?\n end", "def test_remember_me\n login_valid_user\n assert_response :redirect\n assert_redirected_to :controller => \"user\", :action => \"index\"\n\n browser_closing_simulation\n get \"site/index\"\n assert logged_in?\n assert_equal @user.id, session[:user_id]\n end", "def open_session\n @current_session = new_session\n @current_session.test_case = self\n yield @current_session if block_given?\n @current_session\n end", "def test_redirect\n get :index\n assert_redirected_to :action => \"login\", :controller => \"main\"\n assert_not_equal \"\", flash[:login_notice]\n end" ]
[ "0.6890419", "0.6555236", "0.6465239", "0.64356506", "0.64108187", "0.6406505", "0.64042497", "0.6369022", "0.6292442", "0.6265219", "0.62486655", "0.6225159", "0.6221296", "0.62212723", "0.6213242", "0.617218", "0.6133675", "0.6128981", "0.61079925", "0.60522634", "0.60522634", "0.60426295", "0.6032091", "0.6024719", "0.60235435", "0.6013121", "0.6009804", "0.5993993", "0.5993845", "0.598378" ]
0.8594844
0
if running inside a docker container bind to 0.0.0.0 otherwise bind to localhost
def get_bind_ip File.exist?('/.dockerenv') ? '0.0.0.0' : '127.0.0.1' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def docker_routable_ip\n case @docker_url.scheme\n when 'tcp', 'http', 'https'\n docker_dns = @docker_url.host\n docker_port = @docker_url.port || 2376\n else\n # Cheap trick: for unix, file or other protocols, assume docker ports\n # are proxied to localhost in addition to other interfaces\n docker_dns = 'localhost'\n docker_port = 2376\n end\n\n addr = Addrinfo.getaddrinfo(\n docker_dns, docker_port,\n Socket::AF_INET, Socket::SOCK_STREAM).first\n\n addr && addr.ip_address\n end", "def start_container(image, expose_port)\n container = Docker::Container.create('Image' => image, 'HostConfig' => {'PortBindings' => {\"#{expose_port}/tcp\" => [{}]}})\n container.start\n Container.new(container, expose_port)\nend", "def on_localhost?; true end", "def bind(host, port = 0)\n @bind_host = host\n @bind_port = port\n end", "def host_with_port; end", "def host\n '127.0.0.1'\n end", "def determine_docker_host_for_container_ports\n\n begin\n docker_host = Resolv.getaddress('docker')\n puts \"Host alias for 'docker' found. Assuming container ports are exposed on ip '#{docker_host}'\"\n rescue\n docker_host = Resolv.getaddress(Socket.gethostname)\n puts \"No host alias for 'docker' found. Assuming container ports are exposed on '#{docker_host}'\"\n end\n\n docker_host\n\nend", "def get_docker_ip_address\n # first try to get the ip from docker-ip env\n if !ENV['DOCKER_IP'].to_s.empty?\n return ENV['DOCKER_IP']\n end\n\n if !ENV['DOCKER_HOST'].to_s.empty?\n \t\t# dockerhost set\n \t\thost = ENV['DOCKER_HOST'].dup\n \t\thost.gsub!(/tcp:\\/\\//, '')\n \t\thost.gsub!(/:\\d+/,'')\n\n \t\treturn host\n else\n return '127.0.0.1'\n \tend\n end", "def available_endpoint\n \"0.0.0.0:#{available_port}\"\n end", "def explotacion_local()\n puts \"[!] Starting a vulnerable local Portainer instance:\"\n `docker run -d -p \"#{$port}\":9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data_poc:/data portainer/portainer --no-auth`\n instances=`docker ps | grep portainer | awk '{print $1\" | \"$2\" | \"$3\" \"$4\" | \"$13}'`\n puts instances\n puts \"\\nYou should browse your local instance on port 9000, and click the 'Endpoints' menu under Settings.\"\n puts \"Configure the main endpoint as 'Local'.\"\n puts \"Configure yout Endpoint URL to your_network_address:2375\"\n puts \"Example using your current address: #{$myaddress}:2375\"\n puts \"To safely kill this vulnerable instance, invoke exorcist.rb. Avoid killing it manually.\"\n exit 0\nend", "def start(host, port); end", "def server\n '127.0.0.1'\n end", "def docker_port(internal_port, container_name = name)\n docker_runner = Fleetctl::Runner::SSH.new('docker', 'port', container_name, internal_port)\n docker_runner.run(host: ip)\n output = docker_runner.output\n if output\n output.rstrip!\n output.split(':').last\n end\n end", "def targeting_localhost?\n ENV['TARGET_HOST'].nil? || ENV['TARGET_HOST'] == 'localhost'\n end", "def local_host\n get('beef.http.host') || '0.0.0.0'\n end", "def bind(host, port)\n @bind_host = host\n @bind_port = port\n end", "def start(host = T.unsafe(nil), port = T.unsafe(nil)); end", "def check_host\n # rubocop:disable Style/GuardClause\n if config[:host] == '0.0.0.0'\n logger.warn 'Will listen on all interfaces (0.0.0.0).' \\\n ' Consider using 127.0.0.1 (--host option).'\n end\n # rubocop:enable Style/GuardClause\n end", "def check_host\n # rubocop:disable Style/GuardClause\n if config[:host] == '0.0.0.0'\n logger.warn 'Will listen on all interfaces (0.0.0.0).' \\\n ' Consider using 127.0.0.1 (--host option).'\n end\n # rubocop:enable Style/GuardClause\n end", "def setup_docker_client(local_port)\n Docker.url = \"http://localhost:#{local_port}\"\n Docker.connection.options[:scheme] = 'http'\n begin\n logger.debug \"Requesting docker version\"\n response = Docker.version\n logger.debug \"Docker version: #{response.inspect}\"\n logger.debug \"Requesting docker authenticaiton\"\n response = Docker.authenticate!('username' => ENV['DOCKER_HUB_USER_NAME'], 'password' => ENV['DOCKER_HUB_PASSWORD'], 'email' => ENV['DOCKER_HUB_EMAIL'])\n logger.debug \"Docker authentication: #{response.inspect}\"\n rescue Excon::Errors::SocketError => e\n abort e.message\n rescue Exception => e\n abort e.message\n end\n end", "def determine_public_port(local_port)\n port = 0\n count = 0\n max_attempts = 30\n\n # Give up after 30 seconds\n while port == 0 && count < max_attempts do\n hostname = ENV['HOSTNAME']\n command = \"curl --silent -XGET --unix-socket /var/run/docker.sock http://localhost/containers/#{hostname}/json\"\n result = Maze::Runner.run_command(command)\n if result[1] == 0\n begin\n json_string = result[0][0].strip\n json_result = JSON.parse(json_string)\n port = json_result['NetworkSettings']['Ports'][\"#{local_port}/tcp\"][0]['HostPort']\n rescue StandardError\n $logger.error \"Unable to parse public port from: #{json_string}\"\n return 0\n end\n end\n\n count += 1\n sleep 1 if port == 0 && count < max_attempts\n end\n $logger.error \"Failed to determine public port within #{max_attempts} attempts\" if port == 0 && count == max_attempts\n\n port\n end", "def forward_port\n if `ssh docker@192.168.99.100 pwd`.strip != '/home/docker'\n puts Ow::red(\"* Make sure that you can ssh into docker machine.\")\n exit 2\n end\n\n name = args[1]\n ip = @instances\n .select { |i| i.container_name.include?(name) }\n .map { |i| i.container_ip }\n .first\n ports_map = args[2..args.length].each_slice(2).map do |src, dest|\n \"-L #{src}:#{ip}:#{dest}\"\n end.join(\" \")\n forward_cmd = \"ssh -nNT #{ports_map} docker@192.168.99.100\"\n puts Ow::yellow(\"> Will forward with command: \\n#{forward_cmd}\")\n exec(forward_cmd)\n end", "def raw_host_with_port; end", "def host_with_port\n WaterManager.singleton.http_host\n end", "def beef_port\n public_port || local_port\n end", "def bind_address\n configuration.bind_address\n end", "def on_localhost?\n process && process.on_localhost?\n end", "def local_port\n socket = Socket.new(:INET, :STREAM, 0)\n socket.bind(Addrinfo.tcp(\"127.0.0.1\", 0))\n port = socket.local_address.ip_port\n socket.close\n port\n end", "def local_ip\n # turn off reverse DNS resolution temporarily\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true\n\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1 # google\n s.addr.last\n end\n ensure\n Socket.do_not_reverse_lookup = orig\n end", "def bind\n conf['api']['bind']\n end" ]
[ "0.668602", "0.6525163", "0.6502812", "0.6414334", "0.6360573", "0.6351432", "0.63504666", "0.62699175", "0.62460876", "0.6192051", "0.6172306", "0.61717176", "0.6100079", "0.6066674", "0.6056095", "0.60243016", "0.600504", "0.59419453", "0.59419453", "0.59057075", "0.5901537", "0.5899311", "0.5887632", "0.5860954", "0.58473796", "0.58299476", "0.57958347", "0.5784759", "0.57332075", "0.57184076" ]
0.73420584
0
Set up an ActiveRecord model to use a friendly_id. The column argument can be one of your model's columns, or a method you use to generate the slug. Options: :use_slug Defaults to false. Use slugs when you want to use a nonunique text field for friendly ids. :max_length Defaults to 255. The maximum allowed length for a slug. :strip_diacritics Defaults to false. If true, it will remove accents, umlauts, etc. from western characters. :strip_non_ascii Defaults to false. If true, it will all nonascii ([^az09]) characters. :reseved Array of words that are reserved and can't be used as slugs. If such a word is used, it will be treated the same as if that slug was already taken (numeric extension will be appended). Defaults to [].
def has_friendly_id(column, options = {}) options.assert_valid_keys VALID_FRIENDLY_ID_KEYS options = DEFAULT_FRIENDLY_ID_OPTIONS.merge(options).merge(:column => column) write_inheritable_attribute :friendly_id_options, options class_inheritable_reader :friendly_id_options if options[:use_slug] has_many :slugs, :order => 'id DESC', :as => :sluggable, :dependent => :destroy, :readonly => true require 'friendly_id/sluggable_class_methods' require 'friendly_id/sluggable_instance_methods' extend SluggableClassMethods include SluggableInstanceMethods before_save :set_slug else require 'friendly_id/non_sluggable_class_methods' require 'friendly_id/non_sluggable_instance_methods' extend NonSluggableClassMethods include NonSluggableInstanceMethods end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def friendly_id_config; end", "def slug_column=(_arg0); end", "def slug_column=(_arg0); end", "def friendly_id\n slug(true).to_friendly_id\n end", "def slug_column; end", "def slug_column; end", "def friendly_id; end", "def has_slug(attribute, options = {})\n options.assert_valid_keys(VALID_HAS_SLUG_OPTIONS)\n \n options = DEFAULT_HAS_SLUG_OPTIONS.merge(options).merge(:attribute => attribute)\n \n if defined?(has_slug_options)\n Rails.logger.error \"has_slug_options is already defined, you can only call has_slug once. This call has been ignored.\"\n else\n write_inheritable_attribute(:has_slug_options, options)\n class_inheritable_reader(:has_slug_options)\n\n if columns.any? { |column| column.name.to_s == options[:slug_column].to_s }\n require 'has_slug/sluggable_class_methods'\n require 'has_slug/sluggable_instance_methods'\n\n extend SluggableClassMethods\n include SluggableInstanceMethods\n\n before_save :set_slug,\n :if => :new_slug_needed?\n else\n require 'has_slug/not_sluggable_class_methods'\n require 'has_slug/not_sluggable_instance_methods'\n\n extend NotSluggableClassMethods\n include NotSluggableInstanceMethods\n end \n end\n end", "def set_slug(normalized_slug = nil)\n if should_generate_new_friendly_id?\n candidates = FriendlyId::Candidates.new(self, normalized_slug || send(friendly_id_config.base))\n slug = slug_generator.generate(candidates) || resolve_friendly_id_conflict(candidates)\n send \"#{friendly_id_config.slug_column}=\", slug\n end\n end", "def friendly_id_config\n self.class.friendly_id_config\n end", "def uses_slug_cache?\n friendly_id_config.cache_column?\n end", "def uses_slug_cache?\n friendly_id_config.cache_column?\n end", "def uses_slug_cache?\n friendly_id_config.cache_column?\n end", "def friendly_id\n send friendly_id_config.query_field\n end", "def validate_slug_columns\n raise ArgumentError, \"Source column '#{self.slug_source}' does not exist!\" if !self.respond_to?(self.slug_source)\n raise ArgumentError, \"Slug column '#{self.slug_column}' does not exist!\" if !self.respond_to?(\"#{self.slug_column}=\")\n end", "def slug_text\n base = send friendly_id_options[:column]\n if self.friendly_id_options[:strip_diacritics]\n base = Slug::strip_diacritics(base)\n end\n if self.friendly_id_options[:strip_non_ascii]\n base = Slug::strip_non_ascii(base)\n end\n base = Slug::normalize(base)\n \n if base.length > friendly_id_options[:max_length]\n base = base[0...friendly_id_options[:max_length]]\n end\n if friendly_id_options[:reserved].include?(base)\n raise FriendlyId::SlugGenerationError.new(\"The slug text is a reserved value\")\n end\n return base\n end", "def should_generate_new_friendly_id?; end", "def normalize_friendly_id(string)\n\t super[0..20]\n\tend", "def generate_slug!\n\t\tself.slug = self.id.to_s(36)\n\t\tsave\n\tend", "def normalize_friendly_id(string)\n if slug.blank?\n super\n else\n super(slug)\n end\n end", "def model_slug\n slug\n end", "def create_slug\n return if self.errors.size > 0\n return if self[source_column].blank?\n\n if self[slug_column].to_s.empty?\n proposed_slug = self[source_column].to_slug\n\n suffix = \"\"\n existing = true\n acts_as_slugable_class.transaction do\n while existing != nil\n # look for records with the same url slug and increment a counter until we find a unique slug\n existing = acts_as_slugable_class.\n where(slug_column => proposed_slug + suffix).\n where(slug_scope_condition).first\n if existing\n suffix = suffix.empty? ? \"-0\" : suffix.succ\n end\n end\n end # end of transaction \n self[slug_column] = proposed_slug + suffix\n end\n end", "def create_seo_friendly_id\n ## return if there are errors\n return if self.errors.length > 0\n \n seo_id_field = self.class.read_inheritable_attribute(:seo_friendly_options)[:seo_friendly_id_field].to_s\n count_seo_id_field = \"count_#{seo_id_field}\"\n count_seo_id_field_N = \"#{count_seo_id_field}_N\"\n \n resource_id_field = self.class.read_inheritable_attribute(:seo_friendly_options)[:resource_id].to_s\n resource_id_value = self.send(resource_id_field) rescue nil\n \n return if resource_id_value.blank?\n \n seo_id_value = create_seo_friendly_str(resource_id_value)\n seo_id_value = self.class.read_inheritable_attribute(:seo_friendly_options)[:use_if_empty] || \"\" if seo_id_value.blank?\n\n return if (self[seo_id_field] =~ /^#{seo_id_value}$/) || (self[seo_id_field] =~ /^#{seo_id_value}\\-\\d+$/)\n\n self.class.transaction do\n unique_id = determine_unique_id(seo_id_field, count_seo_id_field, count_seo_id_field_N, seo_id_value)\n seo_field_value = \"#{seo_id_value}\" + (unique_id != nil ? \"-#{unique_id}\" : \"\")\n seo_friendly_id_limit = self.class.read_inheritable_attribute(:seo_friendly_options)[:seo_friendly_id_limit].to_i\n \n if seo_field_value.size > seo_friendly_id_limit\n seo_id_value = create_seo_friendly_str(resource_id_value, INITITAL_SEO_UNIQUE_DIGITS + (seo_field_value.size - seo_friendly_id_limit))\n unique_id = determine_unique_id(seo_id_field, count_seo_id_field, count_seo_id_field_N, seo_id_value)\n\n seo_field_value = \"#{seo_id_value}\" + (unique_id != nil ? \"-#{unique_id}\" : \"\")\n seo_field_value = self['id'] if seo_field_value.size > seo_friendly_id_limit # still doesn't fit..give up, store the id\n end\n\n self.class.update_all(\"#{seo_id_field} = \\'#{seo_field_value}\\'\", [\"id = ?\", self.id])\n # set it so that it can be used after this..\n self[seo_id_field] = seo_field_value\n end\n \n true\n end", "def id\n slug\n end", "def normalize_friendly_id(string)\n super[0..59]\n end", "def should_generate_new_friendly_id?\n true\n end", "def set_slug\n if self.class.friendly_id_options[:use_slug] && new_slug_needed?\n @most_recent_slug = nil\n slug_attributes = {:name => slug_text}\n if friendly_id_options[:scope]\n scope = send(friendly_id_options[:scope])\n slug_attributes[:scope] = scope.respond_to?(:to_param) ? scope.to_param : scope.to_s\n end\n # If we're renaming back to a previously used friendly_id, delete the\n # slug so that we can recycle the name without having to use a sequence.\n slugs.find(:all, :conditions => {:name => slug_text, :scope => scope}).each { |s| s.destroy }\n slug = slugs.build slug_attributes\n slug\n end\n end", "def slug_candidates\n [\n :title,\n [:title, :id],\n ]\n end", "def generate_slug\n self.slug=self.send(self.class.slug_column)\n self.slug=self.slug.tr(\" /=\",\"_\")\nend", "def slug_candidates\n [\n :title,\n [:title, :id],\n ]\n end" ]
[ "0.5964881", "0.58818585", "0.58818585", "0.5838858", "0.5713394", "0.5713394", "0.55812865", "0.5472621", "0.5393289", "0.53547317", "0.532368", "0.532368", "0.532368", "0.52919173", "0.52900916", "0.5272146", "0.5252986", "0.5160729", "0.5122637", "0.5117106", "0.5116202", "0.5097383", "0.50782037", "0.5054108", "0.50426024", "0.501492", "0.50037575", "0.50030476", "0.4994147", "0.49863994" ]
0.71595776
0
GET /sleep_alerts GET /sleep_alerts.json
def index @sleep_alerts = SleepAlert.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_sleep_alert\n @sleep_alert = SleepAlert.find(params[:id])\n end", "def alerts(query)\n get_json(\"#{api_url}/alerts/#{url_settings}/q/#{parse_query(query)}.#{@options[:format]}\")\n end", "def get_alerts\r\n\t\turl = URI.parse(\"http://api.wunderground.com/api/#{@token}/alerts/q/#{@state_code}/#{@city}.json\")\r\n\t\thttp_response = HTTParty.get(url).parsed_response\r\n\t\tputs JSON.pretty_generate(http_response)\r\n\tend", "def sleep_logs(date = Date.today)\n get(\"user/#{user_id}/sleep/date/#{format_date(date)}.json\")\n end", "def alerts\n response = self.class.get(\"/#{self.class.account}/activities.xml\")\n response['alerts'].map { |alert| ScoutScout::Alert.new(alert) }\n end", "def show\n @sleep = current_user.sleeps.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @sleep }\n end\n end", "def index\n @alerts = Alert.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @alerts }\n end\n end", "def index\n @alerts = Alert.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @alerts }\n end\n end", "def sleep_logs(date)\n get_call_1_2(\"user/#{user_id}/sleep/date/#{format_date(date)}.json\")\n end", "def alerts(type = 'price')\n authenticated_post(\"auth/r/alerts\", params: {type: type}).body\n end", "def index\n @alerts = Alert.all\n end", "def index\n @alerts = Alert.all\n end", "def index\n @alerts = Alert.all\n end", "def show\n @sleep = Sleep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sleep }\n end\n end", "def index\n @alerts = Alert.all\n\n # If an activation status is passed, get the specified alerts\n check_active_param\n @alerts = @alerts.where(:active => @active) if (@active != nil)\n\n # If a search query is received, filter the results\n if (!params[:q].blank?)\n # Do the search\n @query = params[:q]\n @alerts = @alerts.where(\"$or\" => [{:name => /#{@query}/i}, {:description => /#{@query}/i}])\n end\n\n # If a page number is received, save it (if not, the page is the first)\n if (!params[:page].blank?)\n page = params[:page].to_i\n page = 1 if (page < 1)\n else\n page = 1\n end\n \n # Paginate!\n @alerts = @alerts.page(page)\n\n respond_to do |format|\n format.html\n end\n end", "def sleep_goals\n get_json(path_user_version('/sleep/goal'))\n end", "def alerts\n @alerts ||= []\n end", "def sleep_logs_list(params = {})\n default_params = { before_date: Date.today, after_date: nil, sort: 'desc', limit: 20, offset: 0 }\n get(\"user/#{user_id}/sleep/list.json\", default_params.merge(params))\n end", "def index\n current_user.havemessage = 0\n current_user.save\n @alerts = current_user.alerts.order(\"created_at DESC\").page(params[:page]).per(15)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @alerts }\n end\n end", "def index\n authorize! :read, ItemAlert\n @item_alerts = ItemAlert.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @item_alerts }\n end\n end", "def index\n #@alarms = Alarm.all\n @alarms = Alarm.where(machine_id:Tenant.find(current_tenant.id).machines.ids).distinct(:alarm_message).order(\"updated_at DESC\").where('updated_at > ?', 3.days.ago)\n render json: @alarms\n end", "def pause_all_alerts\n\n endpoint = '/api/admin/pause-all-alerts'\n logger.debug(\"pause all alerts (POST #{endpoint})\") if @debug\n\n post( endpoint, nil )\n end", "def sleep_alert_params\n params.require(:sleep_alert).permit(:user_id, :bed_time, :wake_time)\n end", "def index\n # @alerts = Alert.all\n @user = User.find(session[:id])\n @alerts = @user.alerts\n end", "def alerts\n return @alerts\n end", "def list_alert(project_name, optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'GET'\n\t\targs[:path]['ProjectName'] = project_name\n\t\targs[:pattern] = '/projects/[ProjectName]/alerts'\n\t\targs[:query]['Action'] = 'ListAlert'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :alert_name\n\t\t\targs[:query]['AlertName'] = optional[:alert_name]\n\t\tend\n\t\tif optional.key? :page\n\t\t\targs[:query]['Page'] = optional[:page]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tself.run(args)\n\tend", "def alerts\n #checking to see if params hash in flash msg has a value\n alert = (flash[:alert] || flash[:error] || flash[:notice])\n\n if alert\n alert_generator alert\n end\n end", "def node_alarms\n `curl -s -i -L \\\n -u #{Conn[:creds]} \\\n -H 'content-type:application/json' \\\n #{[Conn[:host_api], 'health', 'checks', 'local-alarms'].join('/')} | grep -c 'ok'`\n end", "def index\n add_breadcrumb \"Index\"\n\n @alerts = AlarmNotification.not_archieved.order(\"created_at DESC\").page(params[:page])\n\n respond_with(@alerts)\n end", "def create\n @sleep_alert = SleepAlert.new(sleep_alert_params)\n\n @sleep_alert.bed_time = @sleep_alert.wake_time - 9.hours\n\n respond_to do |format|\n if @sleep_alert.save\n format.html { redirect_to @sleep_alert, notice: 'Sleep alert was successfully created.' }\n format.json { render :show, status: :created, location: @sleep_alert }\n else\n format.html { render :new }\n format.json { render json: @sleep_alert.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.6504531", "0.6451854", "0.64247406", "0.63897264", "0.6293768", "0.62891465", "0.627321", "0.627321", "0.6194733", "0.6186201", "0.61605865", "0.61605865", "0.61605865", "0.6155232", "0.61350036", "0.6131001", "0.6129876", "0.61146545", "0.60561454", "0.60229033", "0.5978629", "0.59087884", "0.58893824", "0.5887422", "0.5858448", "0.58522195", "0.5828788", "0.58146566", "0.580674", "0.5781342" ]
0.741109
0
POST /sleep_alerts POST /sleep_alerts.json
def create @sleep_alert = SleepAlert.new(sleep_alert_params) @sleep_alert.bed_time = @sleep_alert.wake_time - 9.hours respond_to do |format| if @sleep_alert.save format.html { redirect_to @sleep_alert, notice: 'Sleep alert was successfully created.' } format.json { render :show, status: :created, location: @sleep_alert } else format.html { render :new } format.json { render json: @sleep_alert.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sleep_alert_params\n params.require(:sleep_alert).permit(:user_id, :bed_time, :wake_time)\n end", "def set_sleep_alert\n @sleep_alert = SleepAlert.find(params[:id])\n end", "def create\n puts \"==========================\"\n puts \"CREATE\"\n JSON[params[\"updates\"].read].each do |notification|\n user = User.find(notification[\"subscriptionId\"])\n if user\n case notification[\"collectionType\"]\n when \"sleep\"\n user.fitbit.client.sleep_on_date(notification[\"date\"])[\"sleep\"].each do |data|\n sleep_event = { user_id: notification[\"subscriptionId\"], provider: params[:app_id], body: data }\n sleep_logger.info sleep_event\n end\n end\n end\n end\n render text: \"\", status: 204\n end", "def create_sleep_log(body)\n post(\"user/#{user_id}/sleep.json\", body)\n end", "def index\n @sleep_alerts = SleepAlert.all\n end", "def create\n data = reload(get_series('sleep'), str(Date.strptime(params[:sleep].values.join(\"-\"))))\n saved = false\n get_series('sleep').each do |s|\n data[s].each do |day|\n logger.debug \"data=#{day} date=#{day['dateTime']} value=#{day['value']}\"\n @sleep = for_date(day['dateTime'])\n\t# get variable name from last part of series\n @sleep.send(s.rpartition('/')[2] + '=', day['value'])\n saved = @sleep.save\n if not saved\n flash[:error] = @sleep.errors\n end\n end\n end\n \n respond_to do |format|\n flash[:success] = 'Sleep was successfully created.'\n format.html { redirect_to sleeps_path }\n format.json { render :json => sleeps_path, :status => :created, :location => sleeps_path }\n end\n end", "def create\n \n #timestamp={{FellAsleepAt}}&total_sleep={{TotalTimeSleptInSeconds}}&deep={{TimeInDeepSleepSeconds}}&light={{TimeInLightSleepSeconds}}&awake={{TimeAwakeSeconds}}\n \n json_hash = Hash.new\n \n description = params[:description]\n \n timestamp = params[:timestamp]\n total_sleep_seconds = params[:total_sleep]\n deep_sleep_seconds = params[:deep]\n light_sleep_seconds = params[:light]\n awake_seconds = params[:awake]\n \n if timestamp.nil? || total_sleep_seconds.nil?\n \n puts 'timestamp is nil or total_sleep_seconds is nil :('\n \n else\n \n total_sleep = total_sleep_seconds / 60.0\n deep = deep_sleep_seconds / 60.0\n light = light_sleep_seconds / 60.0\n awake = awake_seconds / 60.0\n \n post_to_twitter = false\n post_to_facebook = false\n \n # FellAsleepAt is formatted: August 23, 2013 at 11:01PM\n # Convert to Runkeeper's preferred format: Sat, 1 Jan 2011 00:00:00\n timestamp_datetime = DateTime.parse(timestamp)\n formatted_timestamp = timestamp_datetime.strftime(\"%a, %d %b %Y %H:%M:%S\")\n \n json_hash['timestamp'] = formatted_timestamp\n json_hash['total_sleep'] = deep\n json_hash['deep'] = deep\n json_hash['light'] = light\n json_hash['awake'] = awake\n json_hash['post_to_twitter'] = post_to_twitter\n json_hash['post_to_facebook'] = post_to_facebook\n \n url = 'https://api.runkeeper.com/sleep'\n \n uri = URI.parse(url)\n \n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n request = Net::HTTP::Post.new(uri.request_uri)\n request[\"Authorization\"] = \"Bearer \" + RUNKEEPER_ACCESS_TOKEN\n request[\"Content-Type\"] = \"application/vnd.com.runkeeper.NewSleep+json\"\n request.body = json_hash.to_json\n \n response = http.request(request)\n \n puts response.body\n \n end\n \n @sleep = json_hash\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sleep }\n end\n \n end", "def pause_all_alerts\n\n endpoint = '/api/admin/pause-all-alerts'\n logger.debug(\"pause all alerts (POST #{endpoint})\") if @debug\n\n post( endpoint, nil )\n end", "def create_alert(data=nil)\n if (!data.blank? && data.is_a?(Hash))\n @alert = Alert.create(data)\n else\n create_service\n create_host\n\n @service.hosts << @host\n @service.save\n \n @alert = Alert.create(:name => \"Test Alert #{rand(1..1000)}\", :description => \"Test alert description.\", :active => true, :limit => 600, :condition => :greater_than, :condition_target => Alert::CONDITION_TARGET_ALL, :error_control => true, :service_id => @service.id, :hosts => [@host])\n end\n end", "def create\n user = User.find(session[:id])\n \n alert = {:title => alert_params[:title], :city_name => alert_params[:city_name], :alert_time => alert_params[:alert_time], :user => user }\n puts 'ALERT TIME!!!!!!!!!!!!!!!!!!!!!!!!'\n puts alert_params[:alert_time][0]\n @alert = Alert.new(alert)\n respond_to do |format|\n if @alert.save\n # format.html { redirect_to @user, notice: 'Alert was successfully created.' }\n format.html { redirect_to('/alerts', notice: 'Alert was successfully created.') }\n format.json { render :show, status: :created, location: @alert }\n else\n format.html { render :new }\n format.json { render json: @alert.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @alert = Alert.new(params[:alert])\n notifiers = Hash.new\n User.find(params[:notifiers]).each{|user| notifiers[user.id] = 0}\n @alert.notifiers = notifiers\n @alert.host = params[:host]\n @alert.trigger = params[:trigger]\n respond_to do |format|\n if @alert.save\n format.html { redirect_to @alert, notice: 'Alert was successfully created.' }\n format.json { render json: @alert, status: :created, location: @alert }\n\t AlertMailer.new_alert(@alert.id).deliver\n else\n format.html { render action: \"new\" }\n format.json { render json: @alert.errors, status: :unprocessable_entity }\n end\n end\n end", "def alerts(type = 'price')\n authenticated_post(\"auth/r/alerts\", params: {type: type}).body\n end", "def panic_tapped\n\n data = {answer: 1, email: App::Persistence['email'], cohort: App::Persistence['cohort']}\n\n BubbleWrap::HTTP.post(\"http://equanimity.herokuapp.com/users/m/:id/responses\", {payload: data}) do |response|\n\n puts data\n # puts \"response = #{response}\"\n # puts \"response.body = #{response.body.to_str rescue ''}\"\n # puts \"response.error_message = #{response.error_message}\"\n # puts \"response.status_code = #{response.status_code.to_s rescue ''}\"\n # puts \"response ok = #{response.ok?}\"\n\n if response.ok?\n\n App.alert(\"Thanks!\")\n else\n App.alert(\"Something went wrong...\")\n end\n end\n end", "def create\n # from mac - state, duration, uuid, major, minor\n # we have - current_employee.id , @beacon.id\n @alert = Alert.new(beacon_id: @beacon.id,\n duration: params[:duration],\n state: params[:state],\n employee_id: current_employee.id)\n if @alert.save\n render json: { success: \"PREY ACQUIRED! TRACKING MODE ACTIVATED! SCREEEEEEEEE!\" }, status: :ok\n else\n render json: { errors: @alert.errors.full_messages }, status: :unprocessable_entity\n end\n end", "def alert_params\n params.require(:alert).permit(:title, :message, :begins, :ends)\n end", "def alert_params\n params.require(:alert).permit(:name, :description, :active, :service_id, :condition, :limit, :condition_target, :error_control, :host_ids => [])\n end", "def create\n @sleep = Sleep.new(params[:sleep])\n @sleep.user_id = session[:user_id]\n\n respond_to do |format|\n if @sleep.save\n flash[:notice] = 'Sleep was successfully created.'\n format.html { redirect_to(@sleep) }\n format.xml { render :xml => @sleep, :status => :created, :location => @sleep }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @sleep.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n #vicious hack. sorry to whoever is reading this even me again.\n if params[:chart]\n redirect_to :action => :index, :params => params[:chart]\n return\n end\n @sleep = Sleep.new(params[:sleep])\n @sleep.user_id = session[:user_id]\n\n respond_to do |format|\n if @sleep.save\n flash[:notice] = 'Sleep was successfully created.'\n format.html { redirect_to(@sleep) }\n format.xml { render :xml => @sleep, :status => :created, :location => @sleep }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @sleep.errors, :status => :unprocessable_entity }\n end\n end\n end", "def alert_params\n params.require(:alert).permit(\n :search_id, :active, :description, :last_run, :last_status_change, :name, :status,\n :threshold_count, :threshold_operator, :threshold_time_seconds, :logs_in_email,\n :history\n )\n end", "def create\n @alert = Alert.new(alert_params)\n\n respond_to do |format|\n if @alert.save\n format.html { redirect_to root_path, notice: \"Has creado una nueva alerta. Pronto te avisaremos cuando encontremos lo que buscas\" }\n format.json { render :show, status: :created, location: @alert }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @alert.errors, status: :unprocessable_entity }\n end\n end\n end", "def alert_params\n params.permit(:alert_type,:value,:status)\n end", "def send_to_pagerduty(alert)\n # This creates and updates alerts from nagios.\n # It requires the following json data (at a minimum):\n # {\n # \"service_key\": @alert_api_key, # this comes from the CONTACTPAGER var passed by nagios\n # \"inicident_key\": @problemid, # this comes from nagios PROBLEMID\n # \"event_type\": \"trigger\"||\"acknowledge\"||\"resolved\",\n # \"description\": \"Reason for failure\", # this gets posted as the SMS details.\n # \"details\": {\n # \"someotherdetail\": \"value\"\n # }\n # }\n\n\n @jdata = alert.to_json\n Log.info(\"going to send: #{JSON.pretty_generate(JSON.parse(@jdata))}\") if VERBOSE\n Log.info(\"connecting to #{PAGERDUTY_INCIDENTS_API}\")\n\n res = RestClient.post PAGERDUTY_INCIDENTS_API, @jdata, :content_type => :json, :accept => :json\n result = JSON.parse(res)\n unless result['status'] == 'success'\n Log.fatal(\"Failure to send data to pagerduty, result: #{result['status']}\")\n Log.fatal(\"Message response: #{result['message']}\")\n fail(\"Could not send to Pagerduty, result: #{result['status']}\")\n else \n Log.info(\"Pagerduty status: #{result['status']}\")\n Log.info(\"Pagerduty incident_key: #{result['incident_key']}\")\n Log.info(\"Pagerduty message: #{result['message']}\") if VERBOSE\n end\n end", "def create\n @heartbeat = Heartbeat.new(heartbeat_params)\n\n if @heartbeat.save\n render json: @heartbeat, status: :created, location: @heartbeat\n else\n render json: @heartbeat.errors, status: :unprocessable_entity\n end\n end", "def create\n @sleep_datum = SleepDatum.new(sleep_datum_params)\n\n respond_to do |format|\n if @sleep_datum.save\n format.html { redirect_to @sleep_datum, notice: 'Sleep datum was successfully created.' }\n format.json { render :show, status: :created, location: @sleep_datum }\n else\n format.html { render :new }\n format.json { render json: @sleep_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def enable_alert_feature \n put(\"/globalsettings.json/alerts/enable\")\nend", "def sleep_logs(date)\n get_call_1_2(\"user/#{user_id}/sleep/date/#{format_date(date)}.json\")\n end", "def sleep_logs(date = Date.today)\n get(\"user/#{user_id}/sleep/date/#{format_date(date)}.json\")\n end", "def alerts=(value)\n @alerts = value\n end", "def new\n \n #timestamp={{FellAsleepAt}}&total_sleep={{TotalTimeSleptInSeconds}}&deep={{TimeInDeepSleepSeconds}}&light={{TimeInLightSleepSeconds}}&awake={{TimeAwakeSeconds}}\n \n json_hash = Hash.new\n \n @sleep = json_hash\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sleep }\n end\n end", "def create\n @alert = Alert.new(alert_params)\n\n respond_to do |format|\n if @alert.save\n format.html { redirect_to alerts_path, notice: 'Alert was successfully created.' }\n #format.json { render action: 'show', status: :created, location: @alert }\n else\n format.html { render action: 'new' }\n format.json { render json: @alert.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.65614796", "0.6473342", "0.643988", "0.64110214", "0.62484753", "0.6241033", "0.60695326", "0.60415", "0.5956238", "0.59183997", "0.58090925", "0.58029634", "0.5763327", "0.57556194", "0.57490295", "0.57048106", "0.5702444", "0.56199056", "0.5587362", "0.55773985", "0.5566185", "0.55521", "0.55440617", "0.5539889", "0.5537719", "0.54841155", "0.54711413", "0.5460793", "0.54580027", "0.5442854" ]
0.6839747
0
POST /admin/entries POST /admin/entries.json
def create @entry = Entry.new(params[:entry]) respond_to do |format| if @entry.save format.html { redirect_to [:admin, @entry], notice: 'Entry was successfully created.' } format.json { render json: @entry, status: :created, location: @entry } else format.html { render action: "new" } format.json { render json: @entry.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @entry = Entry.new(params[:entry])\n\n respond_to do |format|\n if @current_user.entries << @entry\n format.html { redirect_to user_entries_path, notice: 'Entry was successfully created.' }\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = current_user.entries.build(entry_params)\n if @entry.save\n render json: EntrySerializer.new(@entry), status: :created\n else\n render json: { error: @entry.errors.full_messages.to_sentence}, status: :unprocessable_entity\n end\n end", "def create\n @entry = Entry.new(entry_params)\n if @entry.valid?\n @entry.save\n render json: @entry, status: :created\n # , location: @entry\n else\n render json: @entry.errors, status: :unprocessable_entity\n end\n end", "def create\n @entry = Entry.new({\n content: params[:entry][:content],\n journal_id: params[:entry][:journal_id]\n })\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to \"/entries/#{@entry.id}\" }\n format.json { render :show }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = current_user.entries.new(entry_params)\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Your entry has been posted!' }\n format.json { render action: 'show', status: :created, location: @entry }\n else\n format.html { render action: 'new' }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = current_user.entries.build(entry_params)\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to entries_path, notice: 'Entry was successfully created.' }\n format.json { render action: 'show', status: :created, location: @entry }\n else\n format.html { render action: 'new' }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(params[:entry])\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to entries_path, notice: 'Entry was successfully created.' }\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(entry_params)\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(params[:entry])\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(params[:entry])\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(params[:entry])\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_entries(opts = {})\n data, _status_code, _headers = create_entries_with_http_info(opts)\n data\n end", "def create\n @entry = Entry.new(entry_params)\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render action: 'show', status: :created, location: @entry }\n else\n format.html { render action: 'new' }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(entry_params)\n @entry['user_id'] = current_user.id\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors.full_messages, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(entry_params)\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n #assign unpermitted parameter 'entries' to a variable\n entries = params[\"entries\"]\n @invoice = @user.invoices.build(invoice_params)\n #save entries\n @invoice.entries = entries\n if @invoice.save\n render json: @invoice, status: :created, location: api_v1_user_invoice_url(@user, @invoice)\n else\n render json: @invoice.errors, status: :unprocessable_entity\n end\n end", "def create_entries_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: EntriesApi.create_entries ...'\n end\n # resource path\n local_var_path = '/api/v1/entries'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['*/*'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'create_entries_input'] || opts[:body])\n\n # return_type\n return_type = opts[:debug_return_type] || 'Entry'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['authToken']\n\n new_options = opts.merge(\n :operation => :\"EntriesApi.create_entries\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: EntriesApi#create_entries\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create\n params[:entry].delete(\"freigeschaltet\")\n @entry = Entry.new(entry_params)\n @entry.user = current_user unless @entry.user_id.present?\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Eintrag erfolgreich erstellt.' }\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def create\n puts \"In entries#create, params=#{params}\"\n entity_id = params[:entity_id]\n=begin\n @entity = Entity.find(entity_id)\n template_name = @entity.template.name\n\n @entry = EntryManager.initialize_entry(@entity)\n=end\n @entity = Entity.find(entity_id)\n @entry = Entry.new({:entity_id => entity_id})\n \n @context = {:display_mode => 'new' \n }\n \n template = \"/templates/predefined/#{@entity.template.name}.html.erb\"\n entry_html = render_to_string(:template=>template, \n :layout=>false,\n )\n\n \n @entry[:html] = entry_html\n @entry[:attr_values] = @entry.attr_values\n @entry[:attrs] = @entity.attrs\n\n render :json => {\n :entry => @entry\n\n }\n end", "def create\n @entry = Entry.new(entry_params)\n @entry.user_id = current_user.id\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to root_url, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @feed = Feed.find(params[:feed_id])\n @entry = @feed.entries.new(params[:entry])\n\n respond_to do |format|\n if @entry.save\n @entry.author.save\n format.html { redirect_to feed_entry_path(@feed,@entry), notice: 'Entry was successfully created.' }\n format.json { render json: feed_entry_path(@feed, @entry), status: :created, location: feed_entry_path(@feed, @entry) }\n else\n format.html { render action: \"new\" }\n format.json { render json: feed_entry_path(@feed,@entry).errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(entry_params)\n @entry.user = current_user\n\n ['definitions', 'examples', 'references'].each do |name|\n @entry.send(name).each do |model|\n model.user = current_user\n end\n end\n\n authorize @entry\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @content_entry = Content::Entry.new(content_entry_params)\n\n respond_to do |format|\n if @content_entry.save\n format.html { redirect_to @content_entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @content_entry }\n else\n format.html { render :new }\n format.json { render json: @content_entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = Entry.new(entry_params)\n #binding.pry\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entry = current_user.entries.build(entry_params)\n if @entry.save\n flash[:success] = \"Entry created!\"\n redirect_to root_url\n else\n @feed_items = []\n render 'static_pages/home'\n end\n end", "def create\n @entry = current_user.entries.new(entry_params)\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: \"Entry was successfully created.\" }\n format.js\n else\n format.html { render :new }\n format.js { render :new }\n end\n end\n end", "def create\n @entry = Entry.new(params[:entry])\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, :notice => 'Entry was successfully created.' }\n format.json { render :json => @entry, :status => :created, :location => @entry }\n else\n @clients = Client.all.collect{ |c| [c.name, c.id] }\n @aircraft_types = AircraftType.all(:order => :name).collect{|c| [c.name, c.id]}\n \n format.html { render :action => \"new\" }\n format.json { render :json => @entry.errors, :status => :unprocessable_entity }\n end\n end\n end", "def entries\n params[:return_entries] = true\n self\n end", "def create\n\n @entry = Entry.new(entry_params)\n\n respond_to do |format|\n\n if @entry.save\n format.html { redirect_to entries_path, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n @today_entries = Entry.where(\"date = ?\", Date.today)\n @yesterday_entries = Entry.where(\"date = ?\", Date.yesterday)\n format.html { render :action => :index }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def entry_params\n params.require(:entry).permit(:title, :content)\n end" ]
[ "0.6933089", "0.6907184", "0.67925256", "0.6760422", "0.6697155", "0.664318", "0.66287273", "0.6531918", "0.6504035", "0.6504035", "0.6504035", "0.64821833", "0.647895", "0.6443803", "0.639075", "0.63884544", "0.63361037", "0.6326299", "0.6313138", "0.6296719", "0.6275068", "0.6256147", "0.62435144", "0.62424916", "0.6225666", "0.62254244", "0.6211354", "0.6203235", "0.620008", "0.61679894" ]
0.69296485
1
PUT /admin/entries/1 PUT /admin/entries/1.json
def update @entry = Entry.find(params[:id]) respond_to do |format| if @entry.update_attributes(params[:entry]) format.html { redirect_to [:admin, @entry], notice: 'Entry was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @entry.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n\n if @entry.update_attributes(params[:entry])\n head :no_content\n else\n render json: @entry.errors, status: :unprocessable_entity\n end\n end", "def update\n @entry = @current_user.entries.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to user_entries_path, notice: 'Entry was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n end", "def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n end", "def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n end", "def update\n @entry = Entry.find(params[:id])\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n params[:entry][:status] = 'publish' if params[:entry][:status] == 'update'\n \n if params[:entry][:entry_metas_attributes].present?\n params[:entry][:entry_metas_attributes].replace(convert_entry_metas_attributes(params[:entry][:entry_metas_attributes]))\n end\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.html { redirect_to edit_admin_entry_path(@entry), notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to entries_path, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = current_user.entries.find(params[:id])\n \n if params[:entry] && params[:entry].has_key?(:user_id)\n params[:entry].delete(:user_id)\n end\n\n respond_to do |format|\n if @entry.update_attributes(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to entries_path, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to entries_path, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n @kind = args[:kind] if args.key?(:kind)\n end", "def update_rest\n @entry_item = EntryItem.find(params[:id])\n\n respond_to do |format|\n if @entry_item.update_attributes(params[:entry_item])\n flash[:notice] = 'EntryItem was successfully updated.'\n #format.html { redirect_to(@entry_item) }\n format.xml { head :ok }\n else\n #format.html { render :action => \"edit\" }\n format.xml { render :xml => @entry_item.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to edit_entry_path(@entry), notice: 'Entry updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to root_url, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry = Entry.find(params[:id])\n if current_user.role == 'admin'\n @verfasser = User.find(params[:entry].delete('user_id'))\n @entry.user = @verfasser\n end\n\n respond_to do |format|\n if @entry.update_attributes(entry_params)\n format.html { redirect_to @entry, notice: \"Eintrag erfolgreich gespeichert. #{undo_link}\" }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors.full_messages, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @entry }\n else\n format.html { render :edit }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.7045435", "0.688967", "0.6796855", "0.6615867", "0.6615867", "0.6615867", "0.65924746", "0.65804166", "0.65804166", "0.65653855", "0.65653855", "0.65653855", "0.6519017", "0.651694", "0.64939094", "0.64567953", "0.6456286", "0.6456286", "0.64504015", "0.6447442", "0.64419574", "0.6430246", "0.6424557", "0.6419723", "0.63969624", "0.63937455", "0.63937455", "0.63937455", "0.63937455", "0.63937455" ]
0.69491345
1
DELETE /admin/entries/1 DELETE /admin/entries/1.json
def destroy @entry = Entry.find(params[:id]) @entry.destroy respond_to do |format| format.html { redirect_to admin_entries_url } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n debugger\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to manage_entries_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n entry_type = @entry.entry_type\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_entries_url(:entry_type => entry_type)}\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = current_user.entries.find(params[:id])\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find_by_id(params[:id])\n @entry.destroy if @entry\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to '/entries' }\n format.json { render json: @entry }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url, notice: \"Eintrag erfolgreich gelöscht. #{undo_link}\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n head :no_content\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url, :notice => \"Entry has been deleted\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to [@project, :entries] }\n format.json { head :no_content }\n end\n end", "def destroy\n \n \tredirect_to root_url unless is_moderator(current_user)\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to blog_entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url, notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.7603719", "0.7556195", "0.74541986", "0.7444057", "0.7444057", "0.74153924", "0.74153924", "0.74153924", "0.7396678", "0.7388074", "0.73716086", "0.735336", "0.7331764", "0.7331764", "0.73017734", "0.72717315", "0.726465", "0.722468", "0.7143684", "0.7119805", "0.71092707", "0.71092707", "0.71092707", "0.71092707", "0.71092707", "0.71092707", "0.71092707", "0.71092707", "0.71092707", "0.71092707" ]
0.78269917
0
Perform operation (:add, :delete) on user and a set of groups
def user_groups_operation(user, groups, operation) params = { :first => user['first'], :last => user['last'], :username => user['username'], :uid => user['uid'] } groups.each do |group| params[:groupname] = group group_op = JSON.parse( @config[:templates][:group].result(binding), :symbolize_names => true ) group_op[:ops].each do |op| op[0] = operation op[1] = op[1].to_sym end ret = modify({:name => "localuser", :ip => "127.0.0.1"}, group_op[:dn], group_op[:ops]) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_user_to_group(user, group)\n\t\t\tend", "def update\n if params[:commit] == \"Remove users\"\n @usergroup.users.each do |user|\n @usergroup.users.delete(user) if params[:usergroup][\"user\" + user.id.to_s] == \"1\"\n end\n elsif params[:commit] == \"Add users\"\n User.all.each do |user|\n @usergroup.users << user if params[:usergroup][\"user\" + user.id.to_s] == \"1\"\n end\n else\n @usergroup.update(usergroup_params)\n end\n redirect_to users_path\n end", "def add_users\n group_name = params[:name]\n @group = $iam.groups[group_name]\n\n respond_to do |format|\n if @group.exists? # check if group already exists, then add user\n @group.users.add($iam.users[\"Ayesha\"])\n @group.users.add($iam.users[\"Fawad\"])\n format.html { redirect_to \"/show_group/#{@group.name}\", notice: 'User is added.' }\n else\n format.html { redirect_to \"/show_group/#{@group.name}\", notice: 'Error' }\n end\n end\n\n end", "def update_groups(desc, type, groups)\n for id, val in groups\n if group = UserGroup.safe_find(id)\n update_group(desc, type, group, (val == '1'))\n else\n flash_error(:runtime_description_user_not_found.t(:name => id))\n end\n end\n end", "def set_groups(user, grouplist)\n\t\t\tend", "def add_user_to_groups(user, groups)\n user_groups_operation(user, groups, :add)\n end", "def add_to_group\n ids = params[:ids]\n group = Group.find(params[:group_id])\n if ids.present?\n users = User.where(id: ids)\n users.each do |u|\n GroupUser.create(user: u, group: group, created_by: current_user)\n if current_user != u\n u.notify(\n \"#{current_user.to_s} has added you to user group: #{group.name}\",\n group, \n \"group\"\n )\n else\n group.admin.each do |admin|\n admin.notify(\n \"#{current_user.to_s} has requested to be added to the user group: #{group.name}\",\n group,\n \"group\"\n )\n end\n end\n end\n if users.count === 1 && users.first === current_user\n flash[:notice] = \"Request sent!\"\n else\n flash[:notice] = \"#{\"Invitation\".pluralize(users)} sent!\"\n end\n end\n respond_to do |format|\n format.json { render :json => {}, :status => :ok }\n format.html {\n if users\n flash.now[:success] = \"Group membership pending for #{users.map(&:username).join(', ')}.\"\n end \n redirect_to group_path(group) \n }\n end\n end", "def addMembers (group_id, user_id)\n \tm = GroupUser.new(:group_id => @group_id, :user_id => @user_id)\n \tm.save\n end", "def add_user_to_group(user, group)\n send(run_method, \"groups #{user} | grep ' #{group} ' || sudo /usr/sbin/usermod -G #{group} -a #{user}\")\n end", "def addMembers (group_id, user_id)\n \tm = GroupUser.new(:group_id => group_id, :user_id => user_id)\n \tm.save\n end", "def addUserToGroup\n @user_to_add = User.find(params[:user_to_add])\n @current_group = Group.find_by_id(session[:current_group_id])\n @user_to_add.groups << @current_group\n redirect_to findAvailableUsers_url, notice: 'User was successfully added.'\n end", "def add_or_remove_user\n\t\t\tgroup = SystemGroup.find params[:id]\n\t\t\tuser = User.find params[:user_id]\n\n\t\t\tif params[:is_add] == '1'\n\t\t\t\tresult = group.add_user user\n\n\t\t\t\treturn render json: result if result[:status] != 0\n\n\t\t\t\trender json: {\n\t\t\t\t\tstatus: 0,\n\t\t\t\t\tresult: render_to_string(partial: 'user_items', locals: { users: [user] })\n\t\t\t\t}\n\t\t\telse\n\t\t\t\tresult = group.remove_user user\n\n\t\t\t\trender json: result\n\t\t\tend\n\t\tend", "def add_to_group\n if request.post?\n @user_id = params[:user_id]\n @group = params[:group_ids]\n @created_g_u= Array.new\n @group.each do |g|\n #g_user = GroupUser.find(:all,:conditions=>[\"user_id=#{@user_id.to_i} and group_id=#{g.to_i}\"])\n group_user = GroupUser.create(:user_id=>@user_id.to_i,:group_id=>g.to_i)# if g_user.blank?\n @created_g_u << group_user if group_user.id\n end\n @notice = \"Successfully added to group.\"\n respond_to do |format|\n format.js\n end\n \n else\n render :partial=>\"add_to_group_form\", :locals=>{:user=>@login_user,:user_id=>params[:id]}, :layout=>false\n end\n end", "def manage_groups\n \n if request.get?\n course_id = params[:id]\n @course = Course.find(course_id)\n \n group_1 = CourseGroup.find_all_by_course_id_and_group(course_id, 0).collect(&:user_id)\n group_2 = CourseGroup.find_all_by_course_id_and_group(course_id, 1).collect(&:user_id)\n\n course_students = StudentInCourse.find_all_by_course_id(course_id).collect(&:user_id)\n \n @ungrouped = User.find_all_by_id(course_students).reject{ |user| user.id.in? group_1 or user.id.in? group_2 }\n @group_1 = User.find_all_by_id(group_1)\n @group_2 = User.find_all_by_id(group_2)\n else #post request\n course_id = params[:id]\n group1 = params['group1']\n group2 = params['group2']\n ungrouped = params['ungrouped']\n \n \n \n CourseGroup.destroy_all(:course_id => course_id)\n group1.each do |user|\n CourseGroup.create(:course_id => course_id, :user_id => user, :group => 0)\n end\n group2.each do |user|\n CourseGroup.create(:course_id => course_id, :user_id => user, :group => 1)\n end\n \n render :nothing => true\n flash[:notice] = \"Groups updated!\"\n end\n end", "def add(user)\n GroupMembers.new(:id => id).post(user)\n end", "def test_group\n \n user = @user_1\n group = 'customer-test'\n \n assert (not @crowd.group_member? user.name, group), \"#{user.name} is already a member of group #{group}\"\n\n @crowd.add_user_to_group user.name, group \n assert (@crowd.group_member? user.name, group) \n\n groups = @crowd.find_group_memberships user.name\n assert (groups.length > 0)\n assert (groups.include? group)\n\n @crowd.remove_user_from_group user.name, group \n assert (not @crowd.group_member? user.name, group)\n\n groups_after_remove = @crowd.find_group_memberships user.name\n\n # ensure the user in one less group \n assert_equal groups.length - 1, groups_after_remove.length\n \n end", "def associate_in_groups(user, org, groups)\n associate_user_with_org(org.name, user)\n groups.each do |group|\n add_user_to_group(org.name, user, group)\n end\n end", "def add_user\n group_id_param = params[:group_id]\n user_id_param = params[:user_id]\n\n if group_id_param.nil? || group_id_param.blank?\n render json: { error: 'group_id not specified.' }, status: :bad_request\n return\n end\n\n if user_id_param.nil? || user_id_param.blank?\n render json: { error: 'user_id not specified.' }, status: :bad_request\n return\n end\n\n user = User.find_by_id(user_id_param)\n if user.nil?\n render json: { error: \"Can't find user #{user_id_param}.\" }, status: :bad_request\n return\n end\n\n group = CanvasSpaces.GroupCategory.groups.find_by_id(group_id_param)\n if group.nil?\n render json: { error: 'No such group found.' }, status: :bad_request\n else\n if @current_user.account.site_admin? ||\n group.leader_id == @current_user.id ||\n @current_user.id == user.id\n\n group.add_user user\n group.save\n\n render json: { message: 'Successfully added user.' }, status: :ok\n else\n # doesn't have access to the group\n render json: { error: \"Can't add user. Not owner or not adding self.\" }, status: :forbidden\n end\n end\n end", "def add_members_to_group(team_id, group_id, user_ids)\n params = { query: [team_id, group_id, :members, :add], req: user_ids.to_array_obj(:users) }\n\n data = endpoint(name: 'TeamUserGroups', params: params).do_put\n\n resource 'TeamUserGroup', data\n end", "def update_roles_and_groups(user, roles, groups)\n if self.access_to_roles?(roles) && self.access_to_groups?(groups)\n roles = Role.find(roles || [])\n groups = Group.find(groups || [])\n\n user.roles += roles\n user.groups += groups\n\n user.center = groups.first.center unless groups.empty? or user.has_role?(:superadmin)\n user.save\n \n return user\n end\n return false\n end", "def add_group(user)\n cmd_args = [\"'#{user.group}'\"]\n cmd_args.unshift '--system' if user.is_system\n\n groupadd_args = cmd_args.join \"\\s\"\n groupmod_args = (cmd_args - [\"--system\"]).join \"\\s\"\n\n return <<-HERE.undent\n if getent group '#{user.group}' > /dev/null 2>&1; then\n /usr/sbin/groupmod #{groupmod_args}\n else\n /usr/sbin/groupadd #{groupadd_args}\n fi\n HERE\n end", "def add_group_members(members)\n logger.debug(\"#{new_resource} adding members #{members.join(\", \")}\") unless members.empty?\n members.each do |user|\n shell_out!(\"user\", \"mod\", \"-G\", new_resource.group_name, user)\n end\n end", "def update\n @user = User.find(params[:id])\n Group.find(:all).each do |group|\n groups = params[:groups].map {|i| i.to_i} rescue []\n membership = Membership.find(:first, :conditions => [\"group_id = ? and user_id = ?\", group.id, @user.id])\n g_checked = groups.include? group.id\n Membership.create(:group => group, :user => @user) if !membership && g_checked\n membership.destroy if membership && !g_checked\n end\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html do\n flash[:notice] = \"User #{@user.full_name} was successfully updated.\"\n redirect_to users_url\n end\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors.to_xml }\n end\n end\n end", "def add_user(data)\n result = @client.api_request(\n :method => \"usergroup.massAdd\", \n :params => {\n :usrgrpids => data[:usrgrpids],\n :userids => data[:userids]\n }\n )\n result ? result['usrgrpids'][0].to_i : nil\n end", "def add_user(user)\n UserGroup.create(user_id: user.id, group_id: id)\n end", "def add_user(newuser)\n @group_users.push(newuser)\n end", "def groups\r\n save_default_group(params)\r\n delete_group(params)\r\n end", "def move_users_to_group(group_id, arr_of_user_ids)\n arr_of_user_ids.each { |id|\n populate_group = HTTParty.post(\n \"#{$canvas_url}/api/v1/groups/#{group_id}/memberships\",\n headers: { \"authorization\" => \"Bearer #{$canvas_token}\" },\n body: {\n user_id: id\n } \n )\n }\nend", "def addUserToGroup(uid, groupId)\r\n uri = sprintf(\"/api/v1/groups/%d/memberships\", groupId)\r\n\t $canvas.post(uri, {'user_id' => uid})\r\nend", "def addUserToGroup(uid, groupId)\r\n uri = sprintf(\"/api/v1/groups/%d/memberships\", groupId)\r\n\t $canvas.post(uri, {'user_id' => uid})\r\nend" ]
[ "0.7075792", "0.69603723", "0.689869", "0.68834436", "0.68563515", "0.6836417", "0.6805925", "0.6661582", "0.6648996", "0.6643728", "0.6615851", "0.65013635", "0.6485491", "0.6480344", "0.6478706", "0.6417249", "0.6396064", "0.6386506", "0.6382898", "0.63495374", "0.6328067", "0.6327305", "0.63247764", "0.63152677", "0.62929845", "0.6285756", "0.62644047", "0.62603897", "0.62549853", "0.62549853" ]
0.7703633
0
Delete user from LDAP groups
def delete_user_from_groups(user, groups) user_groups_operation(user, groups, :delete) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @group = Group.find(params[:group_id])\n authorize! :edit, @group\n Hydra::LDAP.remove_users_from_group(@group.code, [params[:id]])\n redirect_to edit_group_path(@group), :notice=>\"Removed member #{params[:id]}\"\n end", "def delete_users_account_groups( user_uid, group_dns )\n return unless group_dns\n engines_api_system.delete_users_account_groups( user_uid, group_dns )\n end", "def delete_user(deluser_id)\n @group_users.delete_if { |item| item.user_id == deluser_id }\n end", "def destroy\n @group = @authorized_group\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to group_users_path(@group) }\n format.xml { head :ok }\n end\n end", "def remove_user_from_group(user, group)\n\t\t\tend", "def remove(name)\n syscmd(\"userdel -f #{name}\")\n syscmd(\"groupdel #{name}\", valid_rcs: [6])\n exclusively { users.delete(name) }\n end", "def delete_member\n @group = Group.find(params[:id])\n @user = User.find_by_id(params[:user_id])\n\n if @group.users.include?(@user)\n @group.users.delete(@user)\n @group.save\n flash[:notice] = \"Miembro borrado exitosamente.\"\n end\n\n redirect_to group_path(@group)\n end", "def delete_user_from_group(username, groupname)\n\t\t\t\tif !user?(username)\n\t\t\t\t\traise(NoSuchUserError, \"No such user: #{username}\")\n\t\t\t\tend\n\n\t\t\t\tif !group?(groupname)\n\t\t\t\t\traise(NoSuchGroupError, \"No such user: #{groupname}\")\n\t\t\t\tend\n\t\t\tend", "def destroy\n @user_group = UserGroup.find(params[:id])\n @user_group.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n begin\n @user_group.destroy!\n rescue => e\n flash['error'] = \"#{e}\"\n else\n toast!(title: \"User group deleted\",\n message: \"The user group \\\"#{@user_group.name}\\\" has been deleted.\")\n ensure\n redirect_to user_groups_path\n end\n end", "def delete\n @groups = CwaGroups.new\n\n if params[:user_name]\n if @groups.delete_from_my_group(params[:user_name], params[:group_name])\n CwaMailer.group_remove_member(User.find_by_login(params[:user_name]), params[:group_name]).deliver\n flash[:notice] = \"\\\"#{params[:user_name]}\\\" has been removed from \\\"#{params[:group_name]}\\\"\"\n else\n flash[:error] = \"There was a problem removing \\\"#{params[:user_name]}\\\" from \\\"#{params[:group_name]}\\\"\"\n end\n else\n if @groups.delete_me_from_group params[:group_name]\n flash[:notice] = \"You have been removed from group \\\"#{params[:group_name]}\\\"\"\n else\n flash[:error] = \"There was a problem removing you from group \\\"#{params[:group_name]}\\\"\"\n end\n end\n redirect_to :action => :show, :group_name => params[:group_name]\n end", "def delete_user(email_address)\n found_user = read_user(email_address)\n if found_user\n Net::LDAP.open(@ldap_conf) do |ldap|\n ldap.delete(:dn => get_DN(found_user[:cn]))\n end\n end\n end", "def remove\n @group_user.remove!\n respond_to do |format|\n flash[:notice] = 'Membership was cancelled.'\n format.html { redirect_to @group_user.group }\n format.xml { head :ok }\n end\n end", "def remove_user_group(email_address, group_id)\n # note the user is stored in the group via uid only\n user_dn = email_address\n group_dn = get_group_DN(group_id)\n\n filter = Net::LDAP::Filter.eq( \"cn\", group_id)\n Net::LDAP.open(@ldap_conf) do |ldap|\n group_found = ldap.search(:base => @group_base, :filter => filter).to_a()[0]\n\n if group_found\n removed = group_found[GROUP_MEMBER_ATTRIBUTE].delete(user_dn)\n if removed\n if group_found[GROUP_MEMBER_ATTRIBUTE].empty?\n if !ldap.delete(:dn => group_dn)\n raise ldap_ex(ldap, \"Could not remove user #{user_dn} for group #{group_id}\")\n end\n else\n if !ldap.replace_attribute(group_dn, GROUP_MEMBER_ATTRIBUTE, group_found[GROUP_MEMBER_ATTRIBUTE])\n raise ldap_ex(ldap, \"Could not remove user #{user_dn} for group #{group_id}\")\n end\n end\n end\n end\n end\n end", "def destroy\n @add_group_to_user = AddGroupToUser.find(params[:id])\n @add_group_to_user.destroy\n\n respond_to do |format|\n format.html { redirect_to add_group_to_users_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @groupc_user = GroupcUser.find(params[:id])\n @groupc_user.destroy\n\n respond_to do |format|\n format.html { redirect_to groupc_users_url }\n format.json { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n u1 = User.where(:login=>@group.name).select(:id)\n @u2 = User.find(u1)\n @u2.destroy\n @group.destroy\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :ok }\n end\n end", "def destroy\n @user_group = UserGroup.find_by_id(params[:id])\n @user_group.destroy\n render :json=>{:status =>t('users.destroy.success')}\n end", "def destroy\n @user_group = UserGroup.find(params[:id])\n @user_group.destroy\n\n respond_to do |format|\n format.html { redirect_to user_groups_url }\n format.json { head :ok }\n end\n end", "def destroy\n @user_group = UserGroup.find(params[:id])\n @user_group.destroy\n\n respond_to do |format|\n format.html { redirect_to user_groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n UserGroup.find_by(user_id: @user.id).destroy if UserGroup.find_by(user_id: @user.id).present?\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: t('flash.notice.users.successfully_destroyed') }\n format.json { head :no_content }\n end\n end", "def destroy\n @group_user.destroy\n respond_to do |format|\n format.html { redirect_to group_users_url, notice: 'group_user was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_user(username)\n groups = Avalon::RoleControls.user_roles username\n User.where(Devise.authentication_keys.first => username).destroy_all\n groups.each do |group|\n Avalon::RoleControls.remove_user_role(username, group)\n end\n end", "def destroy\n @group_user_rel = GroupUserRel.find(params[:id])\n @user = @group_user_rel.user\n @group_user_rel.destroy\n\n respond_to do |format|\n format.html { redirect_to edit_user_path(@user) }\n format.json { head :no_content }\n end\n end", "def destroy\n @special_groups_user = SpecialGroupsUser.find(params[:id])\n @special_groups_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(special_groups_users_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @groups = Group.find(params[:id])\n @groups.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end", "def remove_user\n group_id_param = params[:group_id]\n user_id_param = params[:user_id]\n\n if group_id_param.nil? || group_id_param.blank?\n render json: { error: 'group_id not specified.' }, status: :bad_request\n return\n end\n\n if user_id_param.nil? || user_id_param.blank?\n render json: { error: 'user_id not specified.' }, status: :bad_request\n return\n end\n\n user = User.find_by_id(user_id_param)\n if user.nil?\n render json: { error: \"Remove failed. Can't find user #{user_param}.\" }, status: :bad_request\n return\n end\n\n group = CanvasSpaces.GroupCategory.groups.find_by_id(group_id_param)\n if group.nil?\n render json: { error: 'No such group found.' }, status: :bad_request\n else\n if @current_user.account.site_admin? || group.leader_id == @current_user.id || @current_user.id == user.id\n if group.leader_id == user.id\n render json: { error: \"Can't remove user that is the leader of the group.\" }, status: :bad_request\n return\n end\n\n membership = group.group_memberships.where(user_id: user).first\n membership.workflow_state = 'deleted'\n membership.save\n render json: { message: 'Successfully removed user.' }, status: :ok\n else\n # doesn't have access to the group\n render json: { error: \"Can't remove user. Not owner or not adding self.\" }, status: :forbidden\n end\n end\n end", "def remove_user(user)\n group_members.find_by(group: self, user: user).destroy\n end", "def remove_user!( user )\n user.remove_group!( self )\n end", "def group_delete(attribs, dir_info)\n attribs = group_record_name_alternatives(attribs)\n\n check_critical_attribute( attribs, :record_name )\n\n command = {action: 'delete', scope: 'Groups', attribute: nil, value: nil}\n user_attrs = attribs.merge(command)\n\n dscl( user_attrs, dir_info )\n end" ]
[ "0.7752953", "0.7481763", "0.7374588", "0.73439103", "0.7256436", "0.71855825", "0.7158731", "0.70970386", "0.7070976", "0.7061523", "0.70414555", "0.7006968", "0.69795346", "0.6969185", "0.69622815", "0.6955331", "0.6943792", "0.69289994", "0.6922412", "0.6909116", "0.6902909", "0.68498737", "0.6842615", "0.68263936", "0.6822187", "0.6801136", "0.6800516", "0.6770107", "0.67665195", "0.6744083" ]
0.74847066
1
Check if a user is a member of a group
def user_in_group?(user, group) return get_user_groups(user).include?(group) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def member_of(group)\n current_user.is_member?(group)\n end", "def ifMember(group_id,user_id)\n GroupUser.where(:group_id => group_id, :user_id => user_id).exists? #change to current_user_id \n end", "def in_group?(group_or_id)\n group_ids.include?(Ecircle::User.group_id(group_or_id))\n end", "def in_group?(user, group)\n users_groups.where(user_id: user.id, group_id: group.id).count.positive?\n end", "def is_member_of?(group)\n group.owner?(current_person) or Membership.accepted?(current_person, group)\n end", "def member?(group)\n memberships.find_by_group_id(group)\n end", "def isUserMemberOfGroup \n redirect_to groups_path unless !GroupMember.userIsAlreadyInGroup(params[:group_id], current_user.id)\n end", "def member_of?(group)\n cn_groups.include?(group)\n end", "def is_member_in(group)\n unless group.members.include? current_user\n flash[:danger] = \"Devi essere un membro per accedere ad un gruppo ed alle sue informazioni\"\n redirect_to groups_path\n end\n end", "def member?(user = nil)\n membership = Membership.find_by group_id: id, user_id: user.id\n return false if membership.nil?\n membership.user_id == user.id\n end", "def is_member?(user_dn, group_names)\n return true if group_names.nil?\n return true if group_names.empty?\n\n user_membership = membership(user_dn, group_names)\n\n !user_membership.empty?\n end", "def member_of?(group)\n if group.is_a? Group\n groups.include? group\n else\n member_of? Group.new(group)\n end\n end", "def is_member\n @user = User.find(params[:user_id])\n @group = Group.find(params[:group_id])\n if @user.is_member?(@group)\n render json: {result: 1}\n else\n render json: {result: 0}\n end\n end", "def is_member_of?(group)\n current_person.dogs.include?(group.owner) or Membership.accepted_by_person?(current_person, group)\n end", "def is_in_group?(_user_id)\n Rails.cache.fetch \"UserGroup:is_in_group_#{id}_#{_user_id}\" do\n user_relationships.where(user_id: _user_id).any?\n end\n end", "def belongs_to?(group)\n group.all_users.include? self\n end", "def belongs_to?(group)\n group.all_users.include? self\n end", "def belongs_to?(group)\n group.all_users.include? self\n end", "def in_group?(group)\n @groups.include? group\n end", "def creator_in_group?\n return unless errors.blank?\n if !group.users.include?(user)\n errors.add(:user, user.username + \" isn't in the group\")\n end\n end", "def has_user_group?(ug)\n sym = Lockdown.get_symbol(ug)\n\n return true if sym == Lockdown.administrator_group_symbol\n user_group_exists?(sym)\n end", "def admin_of?(group)\n memberships.exists?(group_id: group.id, admin: true)\n end", "def member_user\n if params[:group_id]\n @group = Group.find(params[:group_id])\n else\n @group = Group.find(by_id)\n end\n unless @group.has_member?(current_user)\n flash[:danger] = \"The page you requested is only available to members.\"\n redirect_to @group\n end\n end", "def has_group?(group)\n\t\tFsLdap.groups_of_loginname(self.loginname).include?(group)\n\tend", "def in_group?(group_id)\n groups.any? do |group|\n group.id == group_id\n end\n end", "def has_group?(group)\n\t\t# TODO: remove return true\n\t\treturn true\n\t\t# return FsLdap::groups_of_loginname(self.loginname).include? group\n\tend", "def client_in_group\n @group = @user.groups.find_by_id(params[:gid])\n render errors_msg(\"User Not In Group\", 404) and return \\\n unless @group\n end", "def user_in_admin_group?\r\n cmd_exec(\"groups `whoami`\").split(/\\s+/).include?(SUDOER_GROUP)\r\n end", "def has_groupmember?(member)\n group = @group_class.new :name => member, :node => self.node\n return false unless group.exists?\n self[:groupmembers].member? group.generateduid.first\n end", "def member\n group&.member_for(user)\n end" ]
[ "0.84149235", "0.81160873", "0.8039733", "0.8012207", "0.7999305", "0.7943782", "0.7876627", "0.7870723", "0.77554363", "0.7723301", "0.7602143", "0.76017505", "0.75802577", "0.757178", "0.7525805", "0.7505006", "0.7504587", "0.7504587", "0.7494614", "0.74444294", "0.74331564", "0.74245286", "0.74204093", "0.7332107", "0.72889024", "0.72866595", "0.722956", "0.7228856", "0.7210888", "0.7184787" ]
0.8395639
1
Get an LAN Manager password hash
def lm_hash(password) NTLM::Util.lm_v1_hash(password).unpack("H*")[0].upcase end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_password\n\tpwd1 = Password.get(\"New Password: \")\n\tpwd2 = Password.get(\"Retype New Password: \")\n\n\tbegin\n\t\traise if pwd1 != pwd2\n\t\trescue\n\t\t\tprint \"ERROR: Password mismatch!\\n\"\n\t\t\texit\n\tend\n\n\tbegin\n\t\tpwd1.check # check password strength\n\t\trescue\n\t\t\tprint \"ERROR: Password strength check failed: \" + $! + \"\\n\"\n\t\t\texit\n\tend\n\n\tsalt = rand.to_s.gsub(/0\\./, '')\n\tpass = pwd1.to_s\n\thash = \"{SSHA}\"+Base64.encode64(Digest::SHA1.digest(\"#{pass}#{salt}\")+salt).chomp!\n\treturn hash\nend", "def lm_hash(password)\n keys = gen_keys password.upcase.ljust(14, \"\\0\")\n apply_des(LM_MAGIC, keys).join\n end", "def ntlm_hash(password, opt = {})\n pwd = password.dup\n unless opt[:unicode]\n pwd = EncodeUtil.encode_utf16le(pwd)\n end\n OpenSSL::Digest::MD4.digest pwd\n end", "def nt_hash(password)\n NTLM::Util.nt_v1_hash(password).unpack(\"H*\")[0].upcase\n end", "def passhash\n @passhash ||= getpasshash\n end", "def password\n @hash.to_s\n end", "def hash_passwd(pw)\n return pw if pw.match?(/^\\$\\d*\\$/)\n hash = shell_out(\"#{splunk_cmd} hash-passwd #{pw}\")\n hash.stdout.strip\nend", "def password_hash(pass)\n self.class.password_hash(pass)\n end", "def password_hash(pwd)\n hsh = 0\n pwd.reverse.each_char { |c|\n hsh = hsh ^ c.ord\n hsh = hsh << 1\n hsh -= 0x7fff if hsh > 0x7fff\n }\n\n (hsh ^ pwd.length ^ 0xCE4B).to_s(16)\n end", "def password_hash(p = nil)\n pass = p ? p : self.passphrase\n raise 'Passphrase is nil' if pass.blank?\n Encryption::MD5Digest.new.digest_base64(pass)\n end", "def hash_pass()\n self.pass=(BCrypt::Password.create(pass).to_s)\n end", "def gethash(session)\n\tprint_status(\"Dumping password hashes...\")\n\tbegin\n\t\thash = ''\n\t\tsession.core.use(\"priv\")\n\t\thashes = session.priv.sam_hashes\n\t\thash << \"****************************\\n\"\n\t\thash << \" Dumped Password Hashes\\n\"\n\t\thash << \"****************************\\n\\n\"\n\t\thashes.each do |h|\n\t\t\thash << h.to_s+\"\\n\"\n\t\tend\n\t\thash << \"\\n\\n\\n\"\n\t\tprint_status(\"Hashes Dumped\")\n\trescue ::Exception => e\n\t\tprint_status(\"\\tError dumping hashes: #{e.class} #{e}\")\n\t\tprint_status(\"\\tPayload may be running with insuficient privileges!\")\n\tend\n\thash\n\nend", "def calc_hash(pass)\n salt_cost = SCrypt::Engine.autodetect_cost(self[:salt])\n SCrypt::Engine.scrypt(pass, self[:salt], salt_cost, 32).unpack('H*').first\n end", "def hash_password(password)\n puts \"Password: #{password}\"\n stdout, result = Open3.capture2('openssl', 'passwd', '-apr1', password)\n puts stdout\n puts result\n if result.success?\n return stdout\n else\n raise ShellError\n end\n end", "def hash\n [ name, database, password ].hash\n end", "def hexdigest\n @authenticator.unpack(\"H*\").last\n end", "def password_digest(password); end", "def pwdhash(salt=nil)\n salt = String.random_password.md5 if salt.nil?\n salt = salt[0..8]\n salt+(salt+self).sha1\n end", "def manager_password\n\t\t@manager_password\n\tend", "def password\n { @label => @hash }\n end", "def password\n { @label => @hash }\n end", "def create_hash(user_pw)\n return Digest::SHA1.hexdigest(user_pw)\nend", "def hash\n Digest::SHA2.hexdigest(self.id.to_s + self.password_hash.to_s + self.email.to_s).slice(0,10)\n end", "def hard_hash(password)\n opslimit = 2**20\n memlimit = 2**24\n digest_size = 64\n\n salt = RbNaCl::Random.random_bytes(RbNaCl::PasswordHash::SCrypt::SALTBYTES)\n digest = RbNaCl::PasswordHash.scrypt(password, salt,\n opslimit, memlimit, digest_size)\n [Base64.strict_encode64(digest), Base64.strict_encode64(salt)].join(\"\\n\")\nend", "def get_password_hash\n if account_password_hash_column\n account![account_password_hash_column]\n elsif use_database_authentication_functions?\n db.get(Sequel.function(function_name(:rodauth_get_salt), account ? account_id : session_value))\n else\n # :nocov:\n password_hash_ds.get(password_hash_column)\n # :nocov:\n end\n end", "def m\n @m ||= sha256_hex(n_xor_g_long, login_hash, @user.salt.to_s(16), aa, bb, k)\n end", "def hash_decoder\n hash_params = current_resource.info['rep:password'].match(\n /^\\{(?<algo>.+)\\}(?<salt>\\w+)-(?<iter>(\\d+)-)?(?<hash>\\w+)$/\n )\n\n raise('Unsupported hash format!') unless hash_params\n\n hash_params\n end", "def get_hashed_password(token, password, check)\r\n if check\r\n return Rex::Text.sha1(password + token)\r\n else\r\n return Rex::Text.sha1(Rex::Text.sha1(password) + token)\r\n end\r\n end", "def password_node\n return password unless digest?\n\n token = nonce + timestamp + password\n Base64.encode64(Digest::SHA1.hexdigest(token)).chomp!\n end", "def getpassword()\r\n return getvalue(SVTags::PASSWORD)\r\n end" ]
[ "0.694737", "0.6859001", "0.68257797", "0.68132603", "0.67425215", "0.67418337", "0.67062956", "0.66939294", "0.6652135", "0.66297626", "0.6557417", "0.6515173", "0.65126354", "0.6505352", "0.64987665", "0.6497893", "0.6400321", "0.6392234", "0.63695586", "0.6357675", "0.6357675", "0.62697", "0.6251446", "0.62465984", "0.62026316", "0.6179009", "0.61773545", "0.6165271", "0.61191034", "0.60974425" ]
0.6904985
1
Get an NT Manager password hash
def nt_hash(password) NTLM::Util.nt_v1_hash(password).unpack("H*")[0].upcase end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ntlm_hash(password, opt = {})\n pwd = password.dup\n unless opt[:unicode]\n pwd = EncodeUtil.encode_utf16le(pwd)\n end\n OpenSSL::Digest::MD4.digest pwd\n end", "def password_hash(pwd)\n hsh = 0\n pwd.reverse.each_char { |c|\n hsh = hsh ^ c.ord\n hsh = hsh << 1\n hsh -= 0x7fff if hsh > 0x7fff\n }\n\n (hsh ^ pwd.length ^ 0xCE4B).to_s(16)\n end", "def hash_passwd(pw)\n return pw if pw.match?(/^\\$\\d*\\$/)\n hash = shell_out(\"#{splunk_cmd} hash-passwd #{pw}\")\n hash.stdout.strip\nend", "def get_password\n\tpwd1 = Password.get(\"New Password: \")\n\tpwd2 = Password.get(\"Retype New Password: \")\n\n\tbegin\n\t\traise if pwd1 != pwd2\n\t\trescue\n\t\t\tprint \"ERROR: Password mismatch!\\n\"\n\t\t\texit\n\tend\n\n\tbegin\n\t\tpwd1.check # check password strength\n\t\trescue\n\t\t\tprint \"ERROR: Password strength check failed: \" + $! + \"\\n\"\n\t\t\texit\n\tend\n\n\tsalt = rand.to_s.gsub(/0\\./, '')\n\tpass = pwd1.to_s\n\thash = \"{SSHA}\"+Base64.encode64(Digest::SHA1.digest(\"#{pass}#{salt}\")+salt).chomp!\n\treturn hash\nend", "def lm_hash(password)\n NTLM::Util.lm_v1_hash(password).unpack(\"H*\")[0].upcase\n end", "def pwdhash(salt=nil)\n salt = String.random_password.md5 if salt.nil?\n salt = salt[0..8]\n salt+(salt+self).sha1\n end", "def hard_hash(password)\n opslimit = 2**20\n memlimit = 2**24\n digest_size = 64\n\n salt = RbNaCl::Random.random_bytes(RbNaCl::PasswordHash::SCrypt::SALTBYTES)\n digest = RbNaCl::PasswordHash.scrypt(password, salt,\n opslimit, memlimit, digest_size)\n [Base64.strict_encode64(digest), Base64.strict_encode64(salt)].join(\"\\n\")\nend", "def password_hash(p = nil)\n pass = p ? p : self.passphrase\n raise 'Passphrase is nil' if pass.blank?\n Encryption::MD5Digest.new.digest_base64(pass)\n end", "def lm_hash(password)\n keys = gen_keys password.upcase.ljust(14, \"\\0\")\n apply_des(LM_MAGIC, keys).join\n end", "def hexdigest\n @authenticator.unpack(\"H*\").last\n end", "def calc_hash(pass)\n salt_cost = SCrypt::Engine.autodetect_cost(self[:salt])\n SCrypt::Engine.scrypt(pass, self[:salt], salt_cost, 32).unpack('H*').first\n end", "def password\n @hash.to_s\n end", "def gethash(session)\n\tprint_status(\"Dumping password hashes...\")\n\tbegin\n\t\thash = ''\n\t\tsession.core.use(\"priv\")\n\t\thashes = session.priv.sam_hashes\n\t\thash << \"****************************\\n\"\n\t\thash << \" Dumped Password Hashes\\n\"\n\t\thash << \"****************************\\n\\n\"\n\t\thashes.each do |h|\n\t\t\thash << h.to_s+\"\\n\"\n\t\tend\n\t\thash << \"\\n\\n\\n\"\n\t\tprint_status(\"Hashes Dumped\")\n\trescue ::Exception => e\n\t\tprint_status(\"\\tError dumping hashes: #{e.class} #{e}\")\n\t\tprint_status(\"\\tPayload may be running with insuficient privileges!\")\n\tend\n\thash\n\nend", "def hash_password(password)\n puts \"Password: #{password}\"\n stdout, result = Open3.capture2('openssl', 'passwd', '-apr1', password)\n puts stdout\n puts result\n if result.success?\n return stdout\n else\n raise ShellError\n end\n end", "def password_hash(pass)\n self.class.password_hash(pass)\n end", "def passhash\n @passhash ||= getpasshash\n end", "def password_digest(password); end", "def ntlmv2_hash(user, password, target, opt={})\n if is_ntlm_hash? password\n decoded_password = EncodeUtil.decode_utf16le(password)\n ntlmhash = [decoded_password.upcase[33,65]].pack('H32')\n else\n ntlmhash = ntlm_hash(password, opt)\n end\n userdomain = user.upcase + target\n unless opt[:unicode]\n userdomain = EncodeUtil.encode_utf16le(userdomain)\n end\n OpenSSL::HMAC.digest(OpenSSL::Digest::MD5.new, ntlmhash, userdomain)\n end", "def hash_passphrase_text passphrase\n passphrase_text_hash = Digest::SHA256.base64digest passphrase\n end", "def create_hash(user_pw)\n return Digest::SHA1.hexdigest(user_pw)\nend", "def hash\n [ name, database, password ].hash\n end", "def digest_password\n token = nonce + timestamp + password\n Base64.encode64(Digest::SHA1.hexdigest(token)).chomp!\n end", "def get_hashed_password(token, password, check)\r\n if check\r\n return Rex::Text.sha1(password + token)\r\n else\r\n return Rex::Text.sha1(Rex::Text.sha1(password) + token)\r\n end\r\n end", "def get_crypto_salt_hex\n return @crypto_salt if ! @crypto_salt\n @crypto_salt.unpack(\"H*\")\n end", "def mssql_hashdump(db, host, user, pass)\n print_status(\"Dumping MS-SQL User & Password Hashes....\")\n begin\n passdump=@@outdir + host + '-mssql_dump.txt'\n f=File.open(passdump, 'w+')\n f.puts \"MS-SQL User & Password Hashes\"\n f.puts \"Host: #{host}\"\n res = db.execute('SELECT host_name()')\n res.each do |row|\n row.each do |k, v|\n f.puts \"Hostname: #{v}\"\n print_good(\"Hostname: #{v}\")\n end\n end\n res = db.execute(\"SELECT is_srvrolemember('sysadmin', '#{user}');\")\n res.each do |row|\n row.each do |k, v|\n if v.to_s =~ /1/\n @dba='Yes'\n else\n @dba='No'\n end\n f.puts \"Is DBA: #{@dba}\"\n print_good(\"Is DBA: #{@dba}\")\n end\n end\n res = db.execute('SELECT @@version')\n res.each do |row|\n row.each do |k, v|\n f.puts \"SQL Server Version:\\n#{v}\"\n print_good(\"SQL Server Version: \\n#{v}\")\n end\n end\n if @dba[0] == 'Y'\n f.puts \"MS-SQL Users & Password Hashes: \"\n print_good(\"MS-SQL Users & Password Hashes: \")\n# res = @client.execute('SELECT name, password_hash FROM master.sys.sql_logins') #<= Returns result in hex format\n res = db.execute(\"SELECT name + ':::' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins\")\n res.each do |row|\n row.each do |k, v|\n f.puts v\n print_line(\"#{v}\")\n end\n end\n end\n f.close\n rescue TinyTds::Error => e\n print_error(\"Problem dumping users & hashes!\")\n puts \"\\t=> \".white + \"#{e}\".light_red\n f.close if f\n end\n end", "def hash_pass()\n self.pass=(BCrypt::Password.create(pass).to_s)\n end", "def password_node\n return password unless digest?\n\n token = nonce + timestamp + password\n Base64.encode64(Digest::SHA1.hexdigest(token)).chomp!\n end", "def standard_password_digest\n password_digest( standard_password )\n end", "def hexdigest\n @digest.unpack('H*'.freeze).first\n end", "def get_hash_sha1(user)\n begin\n guid = user['generateduid'][0].to_ruby\n password_hash = nil\n password_hash_file = \"#{@@password_hash_dir}/#{guid}\"\n if File.exists?(password_hash_file) and File.file?(password_hash_file)\n fail(\"Could not read password hash file at #{password_hash_file}\") if not File.readable?(password_hash_file)\n f = File.new(password_hash_file)\n password_hash = f.read\n f.close\n end\n password_hash\n rescue\n return String,new\n end\n end" ]
[ "0.7130953", "0.6926036", "0.68546385", "0.68464637", "0.68241215", "0.6771637", "0.6700953", "0.6696662", "0.66942304", "0.65591687", "0.65051323", "0.6502067", "0.64983076", "0.6483942", "0.6471088", "0.6461837", "0.64516294", "0.643886", "0.6397633", "0.63632166", "0.6343552", "0.63393646", "0.6336313", "0.6304027", "0.6291121", "0.6268944", "0.62612", "0.62304735", "0.6153041", "0.6145643" ]
0.7605761
0
GET /tasklistings GET /tasklistings.json
def index @tasklistings = Tasklisting.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @taskings = Tasking.all\n end", "def get_tasks(tasklist)\n tasklist_id = tasklist[\"id\"]\n tasklist.tasks = @client.execute(\n api_method: @api.tasks.list,\n parameters: {tasklist: tasklist_id}\n ).data.to_hash[\"items\"]\n end", "def tasks(tasklist_id = '@default')\n get gtasks_tasks_url(tasklist_id)\n end", "def index\n render json: {\n tasks: tasks.map(&:to_hash)\n }\n end", "def index\n @scheduled_tasks = ScheduledTask.paginate(\n :per_page => 20,\n :page => params[:page]\n )\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @scheduled_tasks }\n end\n end", "def set_tasklist\n @tasklist = Tasklist.find(params[:id])\n end", "def tasks\n @todos = Todo.all\n render json: @todos\n end", "def show\n @waiting_list = WaitingList.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @waiting_list }\n end\n end", "def index\n @listings = Listing.by_user(current_user).all\n\n render json: @listings\n end", "def index\n @threadings = Threading.all\n end", "def index\n #@tasks = Task.all\n tasks = @task_list.tasks.all\n render :json => tasks\n end", "def index\n @tasks = Task.all\n\n render json: @tasks\n end", "def index\n if Task::TASK_STATES.include?(params[:state]) then\n @tasks = @tasklist.tasks.where(:tstate => params[:state])\n else\n @tasks = @tasklist.tasks\n render action: \"index\", :notice => \"Wrong state. All tasks are listed.\"\n end\n end", "def index\n @listings = Listing.all\n render json: @listings\n end", "def tasks\n render json: [{id: 1, name: 'One'}, {id: 2, name: 'Two'}]\n end", "def getTasklist\r\n\t\t\t\t\treturn @tasklist\r\n\t\t\t\tend", "def show\n @tasks = current_user.assigned_and_written_tasks.pending.paginate(page: params[:page], per_page: 10)\n @fin_tasks = current_user.watching_tasks.completed.paginate(page: params[:page], per_page: 10) unless params[:page]\n end", "def show\n @task_list = TaskList.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @task_list }\n end\n end", "def index\n #@tasks = current_user.assignments\n @tasks = current_user.watching_tasks.pending.paginate(page: params[:page], per_page: 10)\n @fin_tasks = current_user.watching_tasks.completed.paginate(page: params[:page], per_page: 10) unless params[:page]\n end", "def index\n @spiffy_tasks = SpiffyTask.all\n end", "def index\n @checklists = Checklist.get_checklist_entries(current_user).get_pending_tasks.paginate(page: params[:page])\n end", "def index\n @pm_tasks = Pm::Task.all\n end", "def index\n @tasklists = Tasklist.all\n end", "def index\n \n @meeting_threads = @current_user.available_jobs\n \n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @meeting_threads }\n end\n end", "def index\n @tasks = Task.find_all_by_user_id(current_user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tasks }\n end\n end", "def index\n @tasks = Task.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tasks }\n end\n end", "def index\n @tasks = Task.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tasks }\n end\n end", "def index\n @tasks = Task.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tasks }\n end\n end", "def index\n @tasks = Task.all\n response = @tasks.map{|task| get_task_hash(task)}\n render json: response\n end", "def index\n @tasks = Task.all \n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tasks }\n end\n end" ]
[ "0.69428253", "0.66891193", "0.650099", "0.63747966", "0.63591087", "0.63543844", "0.63270223", "0.6314849", "0.6281658", "0.62697965", "0.6243177", "0.6223879", "0.6215714", "0.6200853", "0.6155717", "0.61224645", "0.609302", "0.6081347", "0.60732", "0.6063166", "0.602243", "0.60199606", "0.6012182", "0.6009684", "0.6006655", "0.5999544", "0.5999544", "0.5999544", "0.5989949", "0.5961252" ]
0.77347744
0
Returns true if the moment ends before the other one begins. If given a numeric value it will be treated like instantaneous moment in time. other object that implements begin, or a numeric value.
def before?(other) time = other.is_a?(Numeric) ? other : other.begin self.end <= time end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ends_before_it_begins?\n end_on? && end_on <= start_on\n end", "def after?(other)\n time = other.is_a?(Numeric) ? other : other.end\n self.begin >= time\n end", "def during?(other)\n if other.is_a? Numeric\n other_begin = other_end = other\n else\n other_begin, other_end = other.begin, other.end\n end\n\n self_begin, self_end = self.begin, self.end\n\n # Check if either of the two items begins during the\n # span of the other\n other_begin <= self_begin && self_begin <= other_end ||\n self_begin <= other_begin && other_begin <= self_end\n end", "def before?(y); return @ends < y.starts; end", "def in_range?(point)\n #point = TimeCode.new(point)\n if point < @place.milliseconds\n return false\n elsif point > (@place.milliseconds + @end_point.milliseconds)\n return false\n else \n return true\n end\n end", "def ===(ts)\n ts >= start && ts < finish\n end", "def past?\n begins.to_time < Time.now\n end", "def start_time_before_end_time\n return true unless start_time && end_time\n\n errors.add(:start_time, 'must be before end time') unless start_time < end_time\n end", "def end_at_later_than_start_at\n\t\t\tif self.is_active == true and self.start_at > self.end_at\n\t\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def correct?\n starts_at < ends_at && starts_at.to_date == ends_at.to_date\n end", "def is_before?(e)\n (@periodicity.start_time.hour < e.periodicity.start_time.hour) or\n (@periodicity.start_time.hour == e.periodicity.start_time.hour and @periodicity.start_time.min < e.periodicity.start_time.min)\n end", "def begin_lt_end\n errors[:base] << \"End should be after begin.\" if (self.begin >= self.end)\n end", "def within_time_period?\n return true unless start_time || end_time\n\n if start_time && end_time\n (start_time..end_time).cover? Time.current\n elsif start_time\n Time.current >= start_time\n elsif end_time\n Time.current <= end_time\n end\n end", "def ends_after_start\n unless end_time.nil? || start_time.nil?\n errors[:end_time] << \"can't be before start time\" if end_time < start_time\n end\n end", "def ends_after_it_starts\n if !starts_before_it_ends?\n errors.add(:start_time, 'must be before the end time')\n end\n end", "def passed?\n (self.ends_at < Time.zone.now) && !((self.ends_at.to_date.eql?(Time.zone.now.to_date)) && self.ends_at.strftime('%H%M').eql?(\"0000\"))\n end", "def precedes?(other)\n range_precedes(self, other)\n end", "def ensure_starts_at_is_before_ends_at\n if starts_at && ends_at && starts_at >= ends_at\n errors.add(:ends_at, :is_before_starts_at)\n end\n end", "def valid_start_and_end_dates?\n return false unless start.present? && self.end.present?\n start <= self.end\n end", "def relevant_time?\n\t\tself.start < Time.now && self.end >Time.now \n\tend", "def start_datetime_should_be_less_than_finish_datetime\n errors.add(:start_date, \"をfinish_dateより前に入力してください\") unless start_datetime <= finish_datetime\n end", "def after?(other)\n if other.hour < @hour\n return true\n elsif other.hour == @hour\n if other.minute < @minute\n return true\n elsif other.minute == @minute\n if other.second < @second\n return true\n elsif other.second == @second\n return other.millis < @millis\n end\n end\n end\n false\n end", "def <=>(other)\n if start_time < other.start_time\n 1\n elsif start_time > other.start_time\n -1\n elsif start_time == other.start_time\n 0\n end\n end", "def ended?\n end_time < Time.now.utc\n end", "def cover?(other)\n return false unless other.is_a?(Date)\n\n other = other.day_precision\n\n case\n when unknown_start?\n max.day_precision! == other\n when unknown_end?\n min.day_precision! == other\n when open_end?\n min.day_precision! <= other\n else\n min.day_precision! <= other && other <= max.day_precision!\n end\n end", "def is_correct_time? #:doc:\n if(self.endTime && self.startTime && (self.endTime<=>self.startTime)==-1)\n errors.add([:starTime,:endTime],\"Attenzione l'ora di inizio è piu grande dell'ora di fine\")\n end\n end", "def period_ended_after_start\n invalid = false\n if period_started_at.present? and period_ended_at.present? and not period_ended_at > period_started_at\n errors.add( :period_ended_at, :end_before_start )\n invalid = true\n end\n invalid\n end", "def end_time_after_start_time\n return if end_time.blank? || start_time.blank?\n\n if end_time < start_time\n errors.add(:end_time, \"must be after the start time\")\n end\n end", "def <=>(other) range_start <=> other.range_start end", "def covers?(time)\n start_time <= time && time < end_time\n end" ]
[ "0.7183758", "0.7144173", "0.67917067", "0.65259176", "0.6431983", "0.6379019", "0.63504124", "0.62452084", "0.6174968", "0.61451834", "0.61020887", "0.6082297", "0.6017058", "0.5959709", "0.5951678", "0.5940407", "0.59185785", "0.5914104", "0.5893243", "0.58691216", "0.5868814", "0.5867228", "0.58246183", "0.58033276", "0.5802938", "0.57893395", "0.57878226", "0.5782726", "0.5769736", "0.5766296" ]
0.76555544
0
Returns true if the moment begins after the other one ends. If given a numeric value it will be treated like instantaneous moment in time. other object that implements end, or a numeric value.
def after?(other) time = other.is_a?(Numeric) ? other : other.end self.begin >= time end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def before?(other)\n time = other.is_a?(Numeric) ? other : other.begin\n self.end <= time\n end", "def ends_before_it_begins?\n end_on? && end_on <= start_on\n end", "def during?(other)\n if other.is_a? Numeric\n other_begin = other_end = other\n else\n other_begin, other_end = other.begin, other.end\n end\n\n self_begin, self_end = self.begin, self.end\n\n # Check if either of the two items begins during the\n # span of the other\n other_begin <= self_begin && self_begin <= other_end ||\n self_begin <= other_begin && other_begin <= self_end\n end", "def after?(other)\n if other.hour < @hour\n return true\n elsif other.hour == @hour\n if other.minute < @minute\n return true\n elsif other.minute == @minute\n if other.second < @second\n return true\n elsif other.second == @second\n return other.millis < @millis\n end\n end\n end\n false\n end", "def in_range?(point)\n #point = TimeCode.new(point)\n if point < @place.milliseconds\n return false\n elsif point > (@place.milliseconds + @end_point.milliseconds)\n return false\n else \n return true\n end\n end", "def ended?\n end_time < Time.now.utc\n end", "def ended?\n return(self.ends_at < Time.now)\n end", "def end_at_later_than_start_at\n\t\t\tif self.is_active == true and self.start_at > self.end_at\n\t\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ===(ts)\n ts >= start && ts < finish\n end", "def later?(timestamp)\n ends_at && timestamp > ends_at\n end", "def within_time_period?\n return true unless start_time || end_time\n\n if start_time && end_time\n (start_time..end_time).cover? Time.current\n elsif start_time\n Time.current >= start_time\n elsif end_time\n Time.current <= end_time\n end\n end", "def ends_after_start\n unless end_time.nil? || start_time.nil?\n errors[:end_time] << \"can't be before start time\" if end_time < start_time\n end\n end", "def correct?\n starts_at < ends_at && starts_at.to_date == ends_at.to_date\n end", "def after?(other)\n self.hsec > other.hsec\n end", "def passed?\n (self.ends_at < Time.zone.now) && !((self.ends_at.to_date.eql?(Time.zone.now.to_date)) && self.ends_at.strftime('%H%M').eql?(\"0000\"))\n end", "def match?(freetime)\n freetime.start.between?(self.start, self.end) || freetime.end.between?(self.start, self.end)\n end", "def must_end_after_it_starts\n if ends_before_it_begins?\n errors.add(:end_on, \"must be after the observance starts\")\n end\n end", "def after?(time)\n self.convert > time.convert\n end", "def is_ended(datetime=nil)\n unless datetime\n datetime = Time.zone.now\n end\n \n if self.end_date < datetime\n return true\n else\n return false\n end\n end", "def end_time_after_start_time\n if self.end_time && self.end_time < self.start_time\n self.errors.add(:end_time, \"The end time must be after the start time\")\n end\n end", "def after?(time)\n start_time > time\n end", "def after?(time)\n start_time > time\n end", "def ends_after_it_starts\n if !starts_before_it_ends?\n errors.add(:start_time, 'must be before the end time')\n end\n end", "def in_time_range?(start, ending)\n effective_trigger = effective_trigger_time\n\n if key?('DURATION')\n duration = DateTimeParser.parse_duration(self['DURATION'])\n repeat = self['REPEAT'].to_s.to_i\n repeat = 1 if repeat == 0\n\n occurrence = effective_trigger\n return true if start <= occurrence && ending > occurrence\n\n repeat.times do |_i|\n occurrence += duration\n return true if start <= occurrence && ending > occurrence\n end\n return false\n else\n start <= effective_trigger && ending > effective_trigger\n end\n end", "def cover?(other)\n return false unless other.is_a?(Date)\n\n other = other.day_precision\n\n case\n when unknown_start?\n max.day_precision! == other\n when unknown_end?\n min.day_precision! == other\n when open_end?\n min.day_precision! <= other\n else\n min.day_precision! <= other && other <= max.day_precision!\n end\n end", "def overlaps?(other)\n # overlap == start < finish' AND start' < finish\n self.first <= other.actual_last and other.first <= self.actual_last\n end", "def pairing_ended?\n end_pairing_on.nil? ? false : (end_pairing_on < DateTime.now)\n end", "def relevant_time?\n\t\tself.start < Time.now && self.end >Time.now \n\tend", "def past?\n begins.to_time < Time.now\n end", "def ended?\n ended_at.present?\n end" ]
[ "0.69329554", "0.6912016", "0.679041", "0.67262584", "0.6632929", "0.6557125", "0.6335588", "0.6330379", "0.62694275", "0.6241053", "0.6166797", "0.6164158", "0.6160886", "0.61426437", "0.6140008", "0.6132952", "0.61105585", "0.6083559", "0.606514", "0.6059327", "0.60477036", "0.60477036", "0.60467434", "0.6042294", "0.6036612", "0.6006637", "0.5970324", "0.5956501", "0.5951196", "0.5940194" ]
0.77604973
0
Returns a new moment in the intersection other object that implements both begin and end.
def intersect(other) begin_at = self.begin >= other.begin ? self.begin : other.begin end_at = self.end <= other.end ? self.end : other.end begin_at <= end_at ? self.class.new(begin_at..end_at) : nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def intersection_with(other)\n r1,r2 = matched_range_types(self, other)\n max_begin = [r1.begin,r2.begin].max\n min_end = [r1.end, r2.end ].min\n excl = ( r1.end == min_end && \n r1.respond_to?(:exclude_end?) && r1.exclude_end?\n ) ||\n ( r2.end == min_end && \n r2.respond_to?(:exclude_end?) && r2.exclude_end?\n )\n unless max_begin > min_end\n Range.new(max_begin, min_end, excl).extend(DateTimeRange)\n end\n end", "def intersect(other_interval)\n if self.end <= other_interval.start || other_interval.end <= start\n nil\n else\n Interval.new([start, other_interval.start].max, [self.end, other_interval.end].min)\n end\n end", "def merge(other)\n if include?(other.begin) || other.include?(self.begin)\n cmp = self.begin <=> other.begin\n if cmp < 0\n min = self.begin\n excl_begin = exclude_begin?\n elsif cmp > 0\n min = other.begin\n excl_begin = other.exclude_begin?\n else\n min = self.begin\n excl_begin = exclude_begin? && other.exclude_begin?\n end\n\n cmp = self.end <=> other.end\n if cmp > 0\n max = self.end\n excl_end = self.exclude_end?\n elsif cmp < 0\n max = other.end\n excl_end = other.exclude_end?\n else\n max = self.end\n excl_end = exclude_end && other.exclude_end?\n end\n\n MinMaxRange.create(excl_begin ? GtRange.new(min) : GtEqRange.new(min), excl_end ? LtRange.new(max) : LtEqRange.new(max))\n elsif exclude_end? && !other.exclude_begin? && self.end == other.begin\n # Adjacent, self before other\n from_to(self, other)\n elsif other.exclude_end? && !exclude_begin? && other.end == self.begin\n # Adjacent, other before self\n from_to(other, self)\n elsif !exclude_end? && !other.exclude_begin? && self.end.next(:patch) == other.begin\n # Adjacent, self before other\n from_to(self, other)\n elsif !other.exclude_end? && !exclude_begin? && other.end.next(:patch) == self.begin\n # Adjacent, other before self\n from_to(other, self)\n else\n # No overlap\n nil\n end\n end", "def intersection(another_transmembrane_domain_defintion)\n res = (@start..@stop).to_a & (another_transmembrane_domain_defintion.start..another_transmembrane_domain_defintion.stop).to_a\n res.empty? ? nil : (res.first..res.last)\n end", "def intersection(range)\n # Return self if nil (the other range has no restrictions) or if it matches the other range (they are equivalent)\n return self.clone if range.nil?\n return self.clone if eql?(range)\n\n # Figure out which range starts later (the more restrictive one)\n if low <= range.low\n earlier_start = self\n later_start = range\n else\n earlier_start = range\n later_start = self\n end\n \n # Return nil if there is no common time (the two ranges are entirely disjoint)\n return nil unless later_start.contains?(earlier_start.high)\n \n # Figure out which ranges ends earlier (the more restrictive one)\n if high >= range.high\n earlier_end = self\n later_end = range\n else\n earlier_end = range\n later_end = self\n end\n\n Range.new(\"TS\", later_start.low.clone, earlier_end.high.clone, nil)\n end", "def intersection(other)\n [first, other.begin].max..[last, other.end].min\n end", "def merge(other)\n Range.new([first, other.begin].min, [last, other.end].max)\n end", "def arel_tt_intersect(instant, range_end)\n arel_intersect(:ttstart_at, :ttend_at, instant, range_end)\n end", "def intersection(another_segment)\n return TestHalfEdge.he_intersection(@start,@ending,another_segment.start,\n another_segment.ending)\n end", "def intersect(other)\n new(to_ary & other)\n end", "def intersect(other)\n Intersection.new(self, other)\n end", "def intersects?(*args)\n other = coerce_range(*args)\n raise ArgumentError, \"#{self.begin.class} expected, received #{other.begin.class}\" unless other.begin.kind_of?(self.begin.class)\n\n if other.instant?\n self.begin <= other.begin and other.end < self.end\n else\n other.begin < self.end and self.begin < other.end\n end\n end", "def overlaps?(other)\n start <= other.end_date && other.start <= self.end_date\n end", "def intersection(other)\n raise ArgumentError, \"value must be a #{self.class.name}\" unless other.is_a?(VersionRange)\n result = @ranges.map { |range| other.ranges.map { |o_range| range.intersection(o_range) } }.flatten\n result.compact!\n result.uniq!\n result.empty? ? EMPTY_RANGE : VersionRange.new(result, nil)\n end", "def overlaps?(another)\n (start_date - another.end_date) * (another.start_date - end_date) >= 0\n end", "def during?(other)\n if other.is_a? Numeric\n other_begin = other_end = other\n else\n other_begin, other_end = other.begin, other.end\n end\n\n self_begin, self_end = self.begin, self.end\n\n # Check if either of the two items begins during the\n # span of the other\n other_begin <= self_begin && self_begin <= other_end ||\n self_begin <= other_begin && other_begin <= self_end\n end", "def test_range_overlap_for_intersecting_ranges\n segment = basic_segment\n segment.instance_variable_set(:@start_time, 1.0)\n segment.instance_variable_set(:@end_time, 3.0)\n\n assert_in_delta(1.0, segment.send(:range_overlap, 2.0..4.0))\n end", "def time_intersection(start_a, finish_a, start_b, finish_b)\r\n\t # If one interval finishes before the other starts, intersection is zero.\r\n\t if finish_a < start_b or finish_b < start_a\r\n\t return 0\r\n\t else\r\n\t # Otherwise, intersection goes from the maximum start time to minimum finish time.\r\n\t return ([finish_a, finish_b].min - [start_a, start_b].max) / 1.hours\r\n\t end\r\n\t end", "def intersection(range)\n cmp = self.begin <=> range.end\n if cmp > 0\n nil\n elsif cmp == 0\n exclude_begin? || range.exclude_end? ? nil : EqRange.new(self.begin)\n else\n cmp = range.begin <=> self.end\n if cmp > 0\n nil\n elsif cmp == 0\n range.exclude_begin? || exclude_end? ? nil : EqRange.new(range.begin)\n else\n cmp = self.begin <=> range.begin\n min = if cmp < 0\n range\n elsif cmp > 0\n self\n else\n self.exclude_begin? ? self : range\n end\n\n cmp = self.end <=> range.end\n max = if cmp > 0\n range\n elsif cmp < 0\n self\n else\n self.exclude_end? ? self : range\n end\n\n if !max.upper_bound?\n min\n elsif !min.lower_bound?\n max\n else\n MinMaxRange.new(min, max)\n end\n end\n end\n end", "def slice(other)\n fail TypeError unless like_duration?(other)\n return nil unless overlap?(other)\n s_time = @start_time < other.start_time ? other.start_time : @start_time\n e_time = other.end_time < @end_time ? other.end_time : @end_time\n Duration.new(s_time, e_time)\n end", "def overlaps?(other)\n # overlap == start < finish' AND start' < finish\n self.first <= other.actual_last and other.first <= self.actual_last\n end", "def overlaps?(other)\n \t((start_date - other.end_date) * (other.start_date - end_date)) >= 0\n \tend", "def intersection(*args)\n other = coerce_range(*args)\n sorted = [self, other].sort\n\n return nil if self.class.compare(sorted[0].end, sorted[1].begin) < 0\n\n ARange[sorted[1].begin, self.class.min(sorted[1].end, sorted[0].end)]\n end", "def ==(other)\n (other.is_a? Interval) && (@start == other.start && @end == other.end)\n end", "def tt_intersect(instant=Time.zone.now, range_end=nil)\n where(arel_tt_intersect(instant, range_end))\n end", "def intersection_of(range_a, range_b)\n range_a, range_b = [range_a, range_b].sort_by(&:begin)\n return if range_a.end < range_b.begin\n heads_and_tails = [range_a.begin, range_b.begin, range_a.end, range_b.end].sort\n middle = heads_and_tails[1..-2]\n middle[0]..middle[1]\n end", "def before?(other)\n time = other.is_a?(Numeric) ? other : other.begin\n self.end <= time\n end", "def arel_vt_intersect(instant, range_end)\n arel_intersect(:vtstart_at, :vtend_at, instant, range_end)\n end", "def intersection(range)\n int_a = (self.to_a & range.to_a) \n int_a.empty? ? nil : Range.new(int_a.min, int_a.max)\n end", "def arel_intersect(start_column, end_column, start_or_instant_or_range=nil, range_end=nil)\n table = self.arel_table\n if range_end\n table[start_column].lt(range_end).and(table[end_column].gt(start_or_instant_or_range))\n elsif Range === start_or_instant_or_range\n table[start_column].lt(start_or_instant_or_range.db_end).and(table[end_column].gt(start_or_instant_or_range.db_begin))\n else\n start_or_instant_or_range ||= InfinityLiteral\n table[start_column].lteq(start_or_instant_or_range).and(table[end_column].gt(start_or_instant_or_range))\n end\n end" ]
[ "0.68953633", "0.6721276", "0.63657665", "0.6201355", "0.60844624", "0.59996974", "0.5921518", "0.57193214", "0.57067823", "0.56914407", "0.5688982", "0.5675749", "0.5675407", "0.56711304", "0.5626685", "0.5622666", "0.56155986", "0.5612014", "0.5581967", "0.5567293", "0.556119", "0.55401355", "0.54999083", "0.5493106", "0.54011935", "0.5389759", "0.5358917", "0.53210884", "0.5320932", "0.53114265" ]
0.6799138
1
Create a new DepositReceipt using the Response object returned by the server. ===Parameters response:: the response object returned by the request connection:: a Sword2Ruby::Connection object
def initialize(response, connection) @location = response.header["location"] @status_code = response.code @status_message = response.message if response.body #If a receipt was returned, parse it begin #ensure that there are not parse errors. If there are, warn, rather then raise @entry = ::Atom::Entry.parse(response.body) @has_entry = true @entry.http = connection rescue Exception => message @has_entry = false $stderr.puts "ERROR: An error occured processing the Response XML: #{message}" rescue StandardError => error @has_entry = false $stderr.puts "WARN: The deposit was successful, but there was an issue with Response XML. It could be missing. (#{error})" end else #if the receipt was not returned, try and retrieve it if @location @entry = ::Atom::Entry.parse(connection.get(@location).body) @has_entry = true else #Otherwise, there is no receipt (e.g. for a delete) @has_entry = false @entry = nil end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n # if there are any line items, they should all be valid.\n validate_line_items\n\n # make the API call\n # response = Docdata.client.call(:create, xml: create_xml)\n # response_object = Docdata::Response.parse(:create, response)\n if response_object.success?\n self.key = response_object.key\n end\n\n # set `self` as the value of the `payment` attribute in the response object\n response_object.payment = self\n response_object.url = redirect_url\n\n return response_object\n end", "def create_response(response)\r\n\r\n#\r\n#\tSetup default response values.\r\n#\r\n message = nil\r\n authorization = nil\r\n success = false\r\n exception = nil\r\n#\r\n#\tExtract key elements from the response.\r\n#\r\n reasonCode = response.Get(RocketGate::GatewayResponse::REASON_CODE);\r\n message = @@response_codes[('r' + reasonCode).to_sym] || \"ERROR - \" + reasonCode\r\n responseCode = response.Get(RocketGate::GatewayResponse::RESPONSE_CODE);\r\n if ((responseCode != nil) && (responseCode == \"0\"))\r\n success = true; # Transaction succeeded\r\n authorization = response.Get(RocketGate::GatewayResponse::TRANSACT_ID);\r\n else\r\n exception = response.Get(RocketGate::GatewayResponse::EXCEPTION);\r\n end\r\n\r\n#\r\n#\tExtract values that are not dependent up success/failure.\r\n#\r\n avsResponse = response.Get(RocketGate::GatewayResponse::AVS_RESPONSE)\r\n cvv2Response = response.Get(RocketGate::GatewayResponse::CVV2_CODE)\r\n fraudResponse = response.Get(RocketGate::GatewayResponse::SCRUB_RESULTS)\r\n\r\n#\r\n#\tCreate the response object.\r\n#\r\n card_hash = response.Get(RocketGate::GatewayResponse::CARD_HASH)\r\n Response.new(success, message, {:result => responseCode, :exception => exception, :card_hash => card_hash},\r\n :test => test?,\r\n :authorization => authorization,\r\n :avs_result => {:code => avsResponse},\r\n :cvv_result => cvv2Response,\r\n :fraud_review => fraudResponse\r\n )\r\n end", "def commit\n data = parse(post)\n Freemium.log_test_msg(\"RESPONSE\\n data: #{data.inspect}\")\n # from BT API: 1 means approved, 2 means declined, 3 means error\n success = data['response'].to_i == 1\n @response = Freemium::Response.new(success, data)\n @response.billing_key = data['customer_vault_id']\n @response.message = data['responsetext']\n return self\n end", "def create_from_response(response, user_id)\n save_from_response(response, user_id)\n stripe_account = stripe_user_account_details\n save_user_account_details(stripe_account) if stripe_account\n end", "def create\n @response = Response.new(params[:response])\n\n respond_to do |format|\n if @resp.save\n flash[:notice] = 'Response was successfully created.'\n format.html { redirect_to(response_url(@questionnaire, @resp)) }\n format.xml { render :xml => @resp, :status => :created, :location => @resp }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @resp.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @receipt = Receipt.new(receipt_params)\n\n respond_to do |format|\n if @receipt.save\n deposit_check = DepositCheck.find_by_receipt_id(@receipt.id)\n if deposit_check\n @receipt.update_attributes(:deposit_check_id => deposit_check.id)\n elsif @receipt.receipt_type.present? && @receipt.receipt_type.type_value == \"check\"\n depositCheck = DepositCheck.create(receipt_id: @receipt.id, status: \"open\", receipt_type: @receipt.receipt_type.type_value, check_identifier: @receipt.receipt_check_code, active: 1)\n @receipt.update_attributes(:deposit_check_id => depositCheck.id)\n end\n format.html { redirect_to @receipt, notice: 'Receipt was successfully created.' }\n format.json { render json: @receipt, status: :created, location: @receipt }\n else\n format.html { render action: \"new\" }\n format.json { render json: @receipt.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_response(request)\n response = Response.new\n end", "def purchase\n response = GATEWAY.purchase(price_in_cents, credit_card, purchase_options)\n transactions.create!(:action => \"purchase\", :amount => price_in_cents, :response => response)\n #cart.update_attribute(:purchased_at, Time.now) if response.success?\n response.success?\n end", "def call!\n verify!\n if valid?\n Receipt.new(@response)\n else\n VerificationFailure.new(Google::Apis::Error.new('Malformed response'))\n end\n rescue Google::Apis::Error => e\n VerificationFailure.new(e)\n end", "def create\n #PaypalCallback object sends the raw post request to paypal and expects to get VERIFIED back\n response = PaypalCallback.new(params, request.raw_post, ENV[\"PAYPAL_POST_URL\"])\n\n #check that the payment says completed & paypal verifies post content\n if response.completed? && response.valid?\n @transaction = Transaction.find(params[:invoice]) #invoice is a pass through variable that gets embedded in the encrpyted paypal form and we get it back here\n Payment.create(:params => params.to_unsafe_h, :transaction_id => @transaction.id, :amount => params['payment_gross'], :confirmed => true)\n else\n #TODO maybe send out some type of alert to an admin\n end\n head :ok\n end", "def create\n params_hash = {\n 'x_login' => @x_login,\n 'x_trans_key' => @x_trans_key,\n 'x_invoice' => invoice,\n 'x_amount' => amount,\n 'x_iduser' => iduser,\n 'x_bank' => bank,\n 'x_country' => country,\n 'x_sub_code' => sub_code,\n 'type' => response_type\n }\n\n message_to_control = \"#{invoice}D#{amount}P#{iduser}A\"\n\n sha256 = OpenSSL::Digest::SHA256.new\n control = OpenSSL::HMAC.hexdigest(sha256, [@secret_key].pack('A*'), [message_to_control].pack('A*'))\n control = control.upcase\n\n params_hash['control'] = control\n params_hash['x_currency'] = currency if currency\n params_hash['x_description'] = description if description\n params_hash['x_cpf'] = cpf if cpf\n params_hash['x_return'] = return_url if return_url\n params_hash['x_confirmation'] = confirmation_url if confirmation_url\n\n astro_curl(@astro_urls['create'], params_hash)\n end", "def commit(action, xml)\n headers = { 'Content-Type' => 'application/x-qbmsxml',\n 'Content-length' => xml.size.to_s }\n \n # Post to server\n url = get_post_url\n @request = xml\n data = ssl_post(url, xml, headers)\n \n response = parse(action, data)\n message = message_from(response)\n \n # Post Processing - Create the Response object\n case action\n \n when 'session_ticket'\n @response = Response.new(success?(response), message, response, \n :test => test?,\n :authorization => response[:session_ticket]\n )\n @response\n \n else\n @response = Response.new(success?(response), message, response, \n :test => test?,\n :authorization => response[:transaction_id],\n :cvv_result => cvv_result(response),\n :avs_result => avs_result(response)\n ) \n end\n end", "def unpack(response)\n return OTPResponse.new(response)\n end", "def create_response(response, first_response=nil)\n message = message_from(response)\n\n # This allows the second response to grab the auth info from the first\n first_response ||= response\n\n Response.new(!response.has_key?(:ErrCode), message, response,\n :test => test?,\n # The AccessPass and AccessID are used for all alterations to a\n # transaction, so we store that as the authorization instead of TranID\n :authorization => \"#{first_response[:AccessID]}-#{first_response[:AccessPass]}\"\n )\n end", "def postContractPaymentSuccess( contract_id, payment_date, amount, currency, response)\n params = Hash.new\n params['contract_id'] = contract_id\n params['payment_date'] = payment_date\n params['amount'] = amount\n params['currency'] = currency\n params['response'] = response\n return doCurl(\"post\",\"/contract/payment/success\",params)\n end", "def purchase\n response = GATEWAY.purchase(self.price * 100, credit_card)\n transactions.create!(:price => self.price, :response => response)\n self.transaction_number = response.subscription_id if response.respond_to? :subscription_id\n self.status = response.success?\n create_transaction if self.status\n self.save\n end", "def commit(request, options)\n requires!(options, :soap_action)\n \n\t response = parse(ssl_post(test? ? TEST_URL : LIVE_URL, build_request(request, options),\n\t {\"SOAPAction\" => options[:soap_action],\n\t \"Content-Type\" => \"text/xml; charset=utf-8\" }))\n \n # puts response.inspect if test?\n \n\t success = response[:transaction_result][:status_code] == \"0\"\n\t message = response[:transaction_result][:message]\n authorization = success ? [ options[:order_id], response[:transaction_output_data][:cross_reference], response[:transaction_output_data][:auth_code] ].compact.join(\";\") : nil\n \n IridiumResponse.new(success, message, response, \n :test => test?, \n :authorization => authorization,\n :avs_result => { :code => response[:avsCode] },\n :cvv_result => response[:cvCode],\n :three_d_secure => response[:transaction_result][:status_code] == \"3\",\n :pa_req => (response[:transaction_output_data][:three_d_secure_output_data][:pa_req] rescue \"\"),\n :md => (response[:transaction_output_data][:cross_reference] rescue \"\"),\n :acs_url => (response[:transaction_output_data][:three_d_secure_output_data][:acsurl] rescue \"\")\n )\n end", "def process(amount, action, response_body, options={})\n result = Paygate::Response.new(false, amount, \"debit\", options)\n response = Hash.from_url_params(response_body)\n if response['Len'] && response['Data']\n length = response[:Len].to_i\n encrypted_text = response['Data']\n raw_text = Blowfish.decrypt(encrypted_text, length)\n \n puts \"-> raw response \" + raw_text\n \n content = Hash.from_url_params(raw_text)\n\n status = case content['Status']\n when /FAILED/ then false\n when /OK/ then true\n else\n false\n end\n \n result = Paygate::Response.new(status, amount, action, \n {:trans_id => content['TransID'], :pay_id => content['PayID'], :x_id => content['XID'],\n :description => content['Description'], :code => content['Code'], :m_id => content['mid']})\n end\n result\n end", "def create\n @payment_receipt = PaymentReceipt.new(params[:payment_receipt])\n\n respond_to do |format|\n if @payment_receipt.save\n flash[:notice] = 'PaymentReceipt was successfully created.'\n format.html { redirect_to(@payment_receipt) }\n format.xml { render :xml => @payment_receipt, :status => :created, :location => @payment_receipt }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @payment_receipt.errors, :status => :unprocessable_entity }\n end\n end\n end", "def purchase\n if express_token.include?(\"paykey=AP\")\n\n else\n\n #processes payment for express payment and on site with credit card.\n response = process_purchase\n #creates a transaction to store info from express payment and paywith Credit card\n transactions.create!(:action => \"purchase\", :amount => price_in_cents, :response => response)\n #cart.update_attribute(:purchased_at, Time.now) if response.success?\n response.success?\n end\n end", "def relay_response\n sim_response = AuthorizeNet::SIM::Response.new(params)\n if sim_response.success?(AUTHORIZE_NET_CONFIG['api_login_id'], AUTHORIZE_NET_CONFIG['merchant_hash_value'])\n render :text => sim_response.direct_post_reply(\n url_for(:controller => self.controller_name, :action => 'receipt', :only_path => false, \n :gateway => OPTIONS[:gateways][:authorize_net]), \n :include => true)\n else\n # return back to purchase page - will display error message there\n render :text => sim_response.direct_post_reply(\n url_for(:controller => self.controller_name, :action => 'purchase', :only_path => false, \n :order_id => params[:x_invoice_num], :failure => true), \n :include => true)\n end\n end", "def create\n @money_receipt = MoneyReceipt.new(params[:money_receipt])\n\n respond_to do |format|\n if @money_receipt.save\n format.html { redirect_to @money_receipt, notice: 'Money receipt was successfully created.' }\n format.json { render json: @money_receipt, status: :created, location: @money_receipt }\n else\n format.html { render action: \"new\" }\n format.json { render json: @money_receipt.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_receipt(atom)\n form_data = { application: @application_name }\n @hive_party.post \"/atoms/#{atom.id}/receipts\", form_data\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create(options = nil)\n request = Request.new(@client)\n path = \"/products\"\n data = {\n \"name\"=> @name, \n \"amount\"=> @amount, \n \"currency\"=> @currency, \n \"metadata\"=> @metadata, \n \"request_email\"=> @request_email, \n \"request_shipping\"=> @request_shipping, \n \"return_url\"=> @return_url, \n \"cancel_url\"=> @cancel_url\n }\n\n response = Response.new(request.post(path, data, options))\n return_values = Array.new\n \n body = response.body\n body = body[\"product\"]\n \n \n return_values.push(self.fill_with_data(body))\n \n\n \n return_values[0]\n end", "def create\n @response = Response.new(params[:response])\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render json: @response, status: :created, location: @response }\n else\n format.html { render action: \"new\" }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_with client, @_resource = CreditContractService.new.create(client, credit_contract_params)\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def postContractPaymentFailure( contract_id, failure_reason, payment_date, amount, currency, response)\n params = Hash.new\n params['contract_id'] = contract_id\n params['failure_reason'] = failure_reason\n params['payment_date'] = payment_date\n params['amount'] = amount\n params['currency'] = currency\n params['response'] = response\n return doCurl(\"post\",\"/contract/payment/failure\",params)\n end" ]
[ "0.65508574", "0.63620955", "0.5800771", "0.57577014", "0.5671645", "0.5627099", "0.5625024", "0.5623702", "0.5616438", "0.56050193", "0.5576714", "0.5552487", "0.5539559", "0.5533249", "0.55321395", "0.5527547", "0.54709053", "0.5457693", "0.54208577", "0.54120314", "0.53963953", "0.53866845", "0.5373385", "0.53537667", "0.53485984", "0.53387886", "0.53323513", "0.532688", "0.532688", "0.5322689" ]
0.6373854
1
Gives the formatted output of specified bid. Params: bid: business id (String) cat: optional category (String) If specified, then return from existing query Else fire a new query to find business info of bid Example: ys.business_summary("momsgrilledcheesetruckvancouver", "food") or ys.business_summary("momsgrilledcheesetruckvancouver")
def business_summary(bid, *cat) if cat.empty? search_by_bid(bid) else b_index = @response[cat.first].businesses.find_index{|b| b.id == bid} @response[cat.first].businesses[b_index] end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def job_summary\n summary = \"#{self.title} - \"\n\n if self.avg_bid\n summary += \"#{self.avg_bid}\"\n elsif self.budget\n summary += \"#{self.budget}\"\n elsif self.budget_range\n summary += \"#{self.budget_range.join(\" - \")}\"\n end\n summary\n end", "def fact_display(category)\n puts \"\\n\"\n puts fact_parser(category)\n end", "def s_summary_for_identities(s_language)\n s_out=nil\n case s_language\n when $kibuvits_lc_et\n s_out=\"\\n\"+\n \"Käsk kõikgi kasutusvalmis bdmfunktsioonide kuvamiseks:\\n\"+\n \"\\n\"+\n \" breakdancemake ls\\n\"+\n \"\\n\"+\n \"Andes argumendiks \\\"--inactive\\\", kuvatakse loendis vaid \\n\"+\n \"bdmfunktsioone, mis deklareerivad endi toimimis-eeldused \\n\"+\n \"täitmata olevana. Käsu näide:\\n\"+\n \"\\n\"+\n \" breakdancemake \"+@s_bdmcomponent_name+\" --inactive\\n\"+\n \"\\n\"\n else # probably s_language==\"uk\"\n s_out=\"\\n\"+\n \"A command for displaying a list of bdmroutines that are ready for use:\\n\"+\n \"\\n\"+\n \" breakdancemake ls\\n\"+\n \"\\n\"+\n \"Argument \\\"--inactive\\\" triggers a mode, where \\n\"+\n \"the list of bdmroutines consists of only those bdmroutines that \\n\"+\n \"declare that their requirements are not met. Command example:\\n\"+\n \"\\n\"+\n \" breakdancemake \"+@s_bdmcomponent_name+\" --inactive\\n\"+\n \"\\n\"\n end # case s_language\n return s_out\n end", "def business_summary(lat, lon, bname)\n ret = {\n hours: nil,\n formatted_hours: nil\n }\n return ret if @client.nil?\n\n radius = 100 # improve result to get the correct one\n latlng = lat.to_s + ',' + lon.to_s\n response = @client.search_venues(ll: latlng, radius: radius, query: bname)\n if response.venues.length == 0\n response = @client.search_venues(ll: latlng, query: bname)\n end\n\n if response.venues.length > 0\n hours = @client.venue_hours(response.venues[0].id)\n sum = @client.venue(response.venues[0].id)\n\n ret = {\n hours: hours.hours,\n formatted_hours: sum.hours\n } unless hours.nil? || sum.nil?\n end\n ret\n end", "def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category\n\"SELECT projects.category, SUM(pledges.amount)\nFROM pledges\nINNER JOIN projects\nON pledges.project_id = projects.id \nWHERE projects.category = 'books';\"\nend", "def generate_rdf_catlink(b,ty)\n ul = \"http://catalog.library.cornell.edu/catalog/#{id}\"\n # if no elect access data, 'description' field.\n b.dc(:description,ul)\n end", "def businesses_category\n options = params.except(:controller, :action)\n tag = options.delete(:tag) if options.has_key? :tag\n\n @businesses = Business.where(category: params[:cat]).order_by(:name.asc)\n @businesses = @businesses.where(:services => /#{tag}/) if tag.present?\n @businesses = @businesses.page(params[:page]).per(30)\n\n # if @businesses.any?\n # @starts_with = params[:starts_with] || @businesses.map(&:name).sort.first.downcase[0]\n # @paginated_businesses = @businesses.order_by(\"name ASC\").select { |b| b.name.downcase.starts_with?(@starts_with) }\n # else\n # @paginated_businesses = []\n # end\n\n @template = BusinessCategoryTemplate.where(category: params[:cat]).first\n\n @random_services = Business.random_services(20, params[:cat])\n\n @page_title = params[:cat]\n\n respond_to do |format|\n format.html{ render layout: 'front' }\n format.js\n end\n end", "def summarize\n print \"# of asks: #{ask_count}\\n# of bids: #{bid_count}\\nAsk volume: #{ask_volume.to_s('F')}\\nBid volume: #{bid_volume.to_s('F')}\\n\"\n $stdout.flush\n end", "def condition_summary(label, post)\n burdens = post.conditions.order(:category).limit(5)\n burden_point = 0\n burdens.each do |burden|\n burden_point += burden.point\n end\n burden_result = \"\"\n burden_class = \"\"\n if burden_point >= 20 && burden_point <= 36\n burden_result = \"注意\"\n burden_class = \"danger\"\n elsif burden_point >= 37 && burden_point <= 84\n burden_result = \"ふつう\"\n burden_class = \"warning\"\n elsif burden_point >= 85 && burden_point <= 100\n burden_result = \"良好\"\n burden_class = \"info\"\n else\n burden_result = \"なし\"\n end\n\n motivations = post.conditions.order(:category).reverse_order.limit(5)\n motivation_point = 0\n motivations.each do |motivation|\n motivation_point += motivation.point\n end\n motivation_result = \"\"\n motivation_class = \"\"\n if motivation_point >= 20 && motivation_point <= 44\n motivation_result = \"低\"\n motivation_class = \"danger\"\n elsif motivation_point >= 45 && motivation_point <= 76\n motivation_result = \"中\"\n motivation_class = \"warning\"\n elsif motivation_point >= 77 && motivation_point <= 100\n motivation_result = \"高\"\n motivation_class = \"info\"\n else\n motivation_result = \"なし\"\n end\n\n result = {}\n\n if label == \"detail\"\n result = {\n burden: { class: burden_class, title: burden_result },\n motivation: { class: motivation_class, title: motivation_result }\n }\n return result\n end\n\n if burden_result == \"注意\" && motivation_result == \"低\"\n result = {\n class: \"exhausted\",\n title: \"ヘトヘト\",\n image: \"danger.png\",\n subtitle: \"心身ともに限界の状態\",\n description: \"\"\n }\n elsif burden_result == \"注意\" && (motivation_result == \"中\" || motivation_result == \"低\")\n result = {\n class: \"aggressive\",\n title: \"ギリギリ\",\n image: \"warning.png\",\n subtitle: \"ギリギリな状態\",\n description: \"\"\n }\n elsif (burden_result == \"ふつう\" || burden_result == \"良好\") && motivation_result == \"低\"\n result = {\n class: \"gloomy\",\n title: \"モヤモヤ\",\n image: \"warning.png\",\n subtitle: \"モヤモヤな状態\",\n description: \"\"\n }\n elsif (burden_result != \"注意\" && motivation_result != \"低\") &&\n (burden_result != \"なし\" && motivation_result != \"なし\")\n result = {\n class: \"vivacious\",\n title: \"イキイキ\",\n image: \"info.png\",\n subtitle: \"仕事に打ち込めている状態\",\n description: \"\"\n }\n else\n result = {\n class: \"nothing\",\n title: \"未回答\",\n image: \"blank.png\",\n subtitle: \"こころチェックは行われておりません\",\n description: \"質問に回答して自分のこころの状態を確認しましょう。\"\n }\n end\n\n case label\n when \"class\"\n return result[:class]\n when \"title\"\n return result[:title]\n when \"image\"\n return result[:image]\n when \"subtitle\"\n return result[:subtitle]\n when \"description\"\n return result[:description]\n else\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 summary(db)\n\tif $table_exists\n\t\tall_items = db.execute(\"SELECT * FROM items\")\n\t\ttotal = 0\n\t\tall_items.each do |item|\n\t\t\tputs \"\\n#{item['id']}) #{item['name']} - #{item['calories']} calories\"\n\t\t\ttotal += item['calories']\n\t\tend\n\t\tputs \"You have consumed a total of #{total} calories so far\"\n\telse\n\t\tputs \"There are no items in your table.\"\n\tend\nend", "def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category\n\"SELECT Projects.category, SUM(Pledges.amount) FROM Projects JOIN Pledges ON Pledges.project_id = Projects.id WHERE Projects.category = 'books';\"\nend", "def result_summary\n options = { style: 'font-size: 25px;' }\n summary = if matches_exist?\n [bold_tag(pluralize(result_count, 'result'), options), filter_text]\n else\n [\n bold_tag(@query, options),\n 'not found -',\n pluralize(result_count, 'similar result'),\n filter_text\n ]\n end\n safe_join(summary, ' ')\n end", "def summary_detail\n Classifieds::Listing.format_cols([@title, @mileage, @price], SUMMARY_COL_FORMATS)\n end", "def summary(include_item_specifics = false)\n string = []\n string << title.ljust(80)\n string << \"[#{status.to_s}]\".capitalize.rjust(15)\n\n if has_variations?\n string << \"\\n #{variations.count} Variations:\"\n variations.each do |variation|\n string << \"\\n #{variation[:sku]}: \"\n string << \"#{variation[:quantity_available].to_s.rjust(3)} @ #{(variation[:current_price].symbol + variation[:current_price].to_s).rjust(6)}\"\n string << \" #{variation[:quantity_listed].to_s.rjust(2)} listed, #{variation[:quantity_sold].to_s.rjust(2)} sold\"\n end\n else\n string << \"\\n \"\n string << \"#{quantity_available.to_s} @ \"\n string << \"#{current_price.symbol}#{current_price.to_s}\"\n if best_offer? # Cannot have best offer on variations\n string << ' with Best Offer'\n string << \" #{best_offer_auto_accept_price.symbol}#{best_offer_auto_accept_price}\" if best_offer_auto_accept_price\n string << \" | #{best_offer_minimum_accept_price.symbol}#{best_offer_minimum_accept_price}\" if best_offer_minimum_accept_price\n end\n end\n\n if promotional_sale?\n details = promotional_sale\n starts = details[:start_time]\n ends = details[:end_time]\n original_price = promotional_sale[:original_price]\n string << \"\\n \"\n string << 'ON SALE NOW!' if on_sale_now?\n string << 'was on sale' if Time.now.utc > ends\n string << 'sale scheduled' if Time.now.utc < starts\n string << \" original price #{original_price.symbol}#{original_price.to_s}\"\n string << \" #{starts.strftime('%H:%M %A')}\"\n string << \" until #{ends.strftime('%H:%M %A')}\"\n end\n string << \"\\n\"\n\n string << \"#{quantity_sold.to_s.rjust(4)} sold\"\n if quantity_sold > 0 && status == :completed\n days = (end_time - start_time).round.to_i\n if days > 1\n string << \" in #{days} days\"\n else\n hours = ((end_time.to_time - start_time.to_time) / 1.hour).round\n string << \" in #{hours} hours\"\n end\n end\n\n string << \", #{watch_count} watchers, #{hit_count} page views.\"\n string << \"\\n\"\n\n string << \" SKU: #{sku} Photos: #{photo_urls.count} eBay ID: \"\n string << \"#{relist_parent_id} <= \" unless relist_parent_id.nil?\n string << \"#{ebay_item_id}\"\n string << \" => #{relist_child_id}\" unless relist_child_id.nil?\n\n string << \"\\n \"\n if gtc?\n date_time = (Time.now.utc < end_time) ? Time.now.utc : end_time\n days = (date_time - start_time).round.to_i\n if days > 1\n string << \"GTC [#{days} days]\"\n else\n hours = ((date_time.to_time - start_time.to_time) / 1.hour).round\n string << \"GTC [#{hours} hours]\"\n end\n\n else\n string << \"#{duration} Day\"\n end\n string << \" #{category_1_path.join(' -> ')}\"\n\n string << \"\\n \"\n string << \"#{start_time.strftime('%l:%H%P %A %-d %b').strip} until #{end_time.strftime('%l:%H%P %A %-d %b').strip}\"\n\n if include_item_specifics\n item_specifics.each_pair do |key, value|\n string << \"\\n#{key.rjust(30)} : #{value}\"\n end\n end\n\n string.join\n end", "def bid_for_game(bid, game, pool_user, top_or_bottom)\n pic = pool_user.pics.for_game(game.children.empty? ? game : game.send(top_or_bottom))\n content = if game.children.empty?\n partial = render(:partial => \"bid\", :locals => {:bid => bid,\n :game => game,\n :pool_user => pool_user,\n :pic => pic})\n content_tag :div, partial, :class => 'firstRoundBid bid', :id => dom_id(bid)\n else\n pic_div(pic, game, pool_user, bid)\n end\n content_tag :td, content\n end", "def summary\n divider = \"-\" * 60\n \"#{divider}\\n#{title}\\n#{divider}\\nReleased: \" +\n \"#{release_date.strftime(\"%d %b %Y\")}\\n#{divider}\\n#{plot}\\n#{divider}\" +\n \"\\nCast: #{cast}\\n#{divider}\\n#{rating_summary}\\n\"\n end", "def on_bid(bid)\r\n warn \"Bid \" + bid.to_s\r\n end", "def full_info(db)\r\n info = db.execute(\"SELECT stocks2.company_name,stocks2.stock_ticker,stocks2.stock_price,stocks2.stock_exchange,stocks1.recommendation FROM stocks2 JOIN stocks1 ON stocks2.recommendation_id = stocks1.id;\")\r\n puts \"\"\r\n info.each do |category|\r\n puts \"\r\n Company Name : #{category['company_name']} \r\n Stock Ticker : #{category['stock_ticker']}\r\n Stock Price : #{category['stock_price']}\r\n Stock Exchange: #{category['stock_exchange']}\r\n Rating : #{category['recommendation']}\"\r\n \r\n end\r\n\r\nend", "def get_contact_detail(business, category)\n contact_details.find_by(business: business, category: category)\n end", "def get_category_by_id_with_http_info(budget_id, category_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: CategoriesApi.get_category_by_id ...'\n end\n # verify the required parameter 'budget_id' is set\n if @api_client.config.client_side_validation && budget_id.nil?\n fail ArgumentError, \"Missing the required parameter 'budget_id' when calling CategoriesApi.get_category_by_id\"\n end\n # verify the required parameter 'category_id' is set\n if @api_client.config.client_side_validation && category_id.nil?\n fail ArgumentError, \"Missing the required parameter 'category_id' when calling CategoriesApi.get_category_by_id\"\n end\n # resource path\n local_var_path = '/budgets/{budget_id}/categories/{category_id}'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'category_id' + '}', category_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['bearer']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'CategoryResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: CategoriesApi#get_category_by_id\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def summary\n #render unless @output\n @summary\n end", "def offer_display( hotel_name, offer_available , normal_rate, normal_tax )\n o_from, o_to, o_rate = offer_available.start, offer_available.end , offer_available.rate.to_i \n visit_time_period = ( @to - @from ).to_i + 1\n puts \"\\n\\n****Amazing choice, you are walking in during a special season**** \n '#{offer_available.name.upcase}' from #{o_from.strftime(\"%m/%d/%Y\")} till #{o_to.strftime(\"%m/%d/%Y\")} at #{hotel_name}\"\n bill = calculate_bill( hotel_name, visit_time_period, o_to, o_from, o_rate, normal_rate, normal_tax )\n puts \"\\nStay at #{hotel_name} \\n From : #{from.strftime(\"%m/%d/%Y\")} \\t\\t\\t To : #{to.strftime(\"%m/%d/%Y\")} (including offer)\\n TOTAL : #{bill.to_i}\"\n end", "def by_category\n @category = Category.roots.find_by_slug(params[:category])\n raise ListingException, \"missing category\" if @category.blank?\n @subcategory = @category.children.find_by_slug(params[:subcategory]) if params[:subcategory].present?\n terms = [ListingFilter.category(@subcategory.present? ? @subcategory.id : @category.id), ListingFilter.state('active')]\n query = {filter: {bool: {must: terms}}, sort: {id: \"desc\"}}\n @listings = Listing.search(query).page(page).per(per).records\n\n @subcategories = @category.children.with_listings\n\n @title = [@category.name, @subcategory.try(:name)].compact.join(\" : \") + \" | Category\"\n\n respond_to do |format|\n format.html { render(action: :index, layout: !request.xhr?) }\n end\n end", "def list_cats\n Cat.all.each_with_index do |kitty, i| \n puts \"\\n#{i + 1}. #{kitty.name} 🐈\"\n ##### if no owner\n if kitty.owner.nil?\n puts \"Breed: #{kitty.breed} | Color: #{kitty.color.capitalize}\"\n puts \"Food preference: #{kitty.favorite_food.capitalize} | Gets along with other cats? #{kitty.temperament.to_s.capitalize}\"\n puts \"\\n----------------------------------------------------------------------------\"\n ##############\n else\n puts \"Owner: #{kitty.owner.name}\"\n puts \"Breed: #{kitty.breed} | Color: #{kitty.color.capitalize}\"\n puts \"Food preference: #{kitty.favorite_food.capitalize} | Gets along with other cats? #{kitty.temperament.to_s.capitalize}\"\n puts \"\\n----------------------------------------------------------------------------\"\n end\n end\n end", "def category_totals(db, user_name, number)\r\n\tretrieve_totals = '\r\n\tSELECT categories.name, SUM(amount) FROM expenses\r\n\tJOIN users ON expenses.user_id = users.id\r\n\tJOIN categories ON expenses.category_id = categories.id\r\n\tWHERE categories.id = ?\r\n\tAND users.name = ?'\r\n\ttotals = db.execute(retrieve_totals, [number, user_name])[0]\r\nend", "def cat_stats \n puts \"#{self.name}, age #{self.age}, color #{self.color}\"\n end", "def find_summaries_by_brand(brand_id)\n @request = setup_request \"#{@@resource_url}s\"\n @request.query = { brandId: brand_id }\n @request\n end", "def report_table(output, amount = 10, options = {}, &block)\n \n output.title(options[:title])\n \n top_categories = @categories.sort { |a, b| yield(b[1]) <=> yield(a[1]) }.slice(0...amount)\n output.table({:title => 'Category', :width => :rest}, \n {:title => 'Hits', :align => :right, :highlight => (options[:sort] == :hits), :min_width => 4}, \n {:title => 'Cumulative', :align => :right, :highlight => (options[:sort] == :cumulative), :min_width => 10}, \n {:title => 'Average', :align => :right, :highlight => (options[:sort] == :average), :min_width => 8},\n {:title => 'Min', :align => :right, :highlight => (options[:sort] == :min)}, \n {:title => 'Max', :align => :right, :highlight => (options[:sort] == :max)}) do |rows|\n \n top_categories.each do |(cat, info)|\n rows << [cat, info[:hits], \"%0.02fs\" % info[:cumulative], \"%0.02fs\" % (info[:cumulative] / info[:hits]),\n \"%0.02fs\" % info[:min], \"%0.02fs\" % info[:max]]\n end \n end\n\n end", "def ticket_summary(ticket)\n summary = [ ticket.category.blank? ? t(:other) : t(ticket.category) ]\n if @view != \"completed\"\n if @view == \"pending\" && ticket.user != current_user\n summary << t(:ticket_from, ticket.user.full_name)\n elsif @view == \"assigned\"\n summary << t(:ticket_from, ticket.assignee.full_name)\n end\n summary << \"#{t(:related)} #{ticket.asset.name} (#{ticket.asset_type.downcase})\" if ticket.asset_id?\n summary << if ticket.bucket == \"due_asap\"\n t(:ticket_due_now)\n elsif ticket.bucket == \"due_later\"\n t(:ticket_due_later)\n else\n l(ticket.due_at.localtime, :format => :mmddhhss)\n end\n else # completed\n summary << \"#{t(:related)} #{ticket.asset.name} (#{ticket.asset_type.downcase})\" if ticket.asset_id?\n summary << t(:ticket_completed_by,\n :time_ago => distance_of_time_in_words(ticket.completed_at, Time.now),\n :date => l(ticket.completed_at.localtime, :format => :mmddhhss),\n :user => ticket.completor.full_name)\n end\n summary.join(', ')\n end" ]
[ "0.5467923", "0.5224961", "0.49876085", "0.4917161", "0.48378083", "0.48229358", "0.47968322", "0.478096", "0.47712913", "0.47397572", "0.47370204", "0.470562", "0.46837315", "0.46562493", "0.46222448", "0.4577659", "0.4577659", "0.45538095", "0.45360425", "0.45171073", "0.45078343", "0.4504375", "0.44912973", "0.44905052", "0.44663203", "0.44603816", "0.44601896", "0.4457553", "0.44430724", "0.44253856" ]
0.82252073
0
render the opening hours for event date
def show_opening_hours(times, formatted_times, event_date) result = 'Not Open Today' event_day = transformToFourSquareDay(event_date.in_time_zone.wday) times.each_with_index do |time, index| unless time.days.index(event_day).nil? result = formatted_times[index].open[0].renderedTime end end result end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @open_hours = Hash.new\n @place.open_times.each do |schedule|\n @open_hours[schedule.day] = \"#{schedule.open_time.strftime('%l:%M %P')} - #{schedule.close_time.strftime('%l:%M %P')}\"\n end\n end", "def opening_hour\n 11 # 11am\n end", "def opening_hour\n 11\n end", "def opening_hours\n hours = @data[:godziny_pracy]\n keys = {weekdays: :dni_robocze, saturdays: :soboty, sundays: :niedz_i_sw}\n Hash[\n keys.map do |h, x|\n value = unless hours[x].nil?\n [hours[x][:godziny].to_s, hours[x][:uwagi].to_s]\n end\n\n [h, value]\n end\n ]\n end", "def time_range_for(open_time, close_time)\n content_tag :span, class: 'opening-hours' do\n \"#{hour_content_for(open_time, 'opens-at')} - \" \\\n \"#{hour_content_for(close_time, 'closes-at')}\".html_safe\n end\n end", "def render_time_span event\n\t\t# return time.strftime(\"%c\")\n\t\ts = render_date( event.starts_at ) + ' ' + render_time( event.starts_at );\n\t\ts << ' <span class=\"slash\">/</span> '\n\t\tif event.ends_at\n\t\t\tif event.starts_at.month == event.ends_at.month and event.starts_at.year == event.ends_at.year\n\t\t\t\ts << render_time( event.ends_at )\n\t\t\telse\n\t\t\t\ts << render_date( event.ends_at ) + ' ' + render_time( event.ends_at )\n\t\t\tend\n\t\telse\n\t\t\ts << \"N/A\"\n\t\tend\n\t\t\n\t\treturn s.html_safe;\n\tend", "def grouped_open_hours\n\n open_hours = []\n start_day = nil\n end_day = nil\n current_period = nil\n\n standard_hours.sort.each_with_index do |o, i|\n if not o.open?\n period = \"Stengt\"\n else\n period = I18n.l(o.open_time, format: :time) + \" - \" + I18n.l(o.close_time, format: :time)\n end\n\n # Track day\n if start_day == nil\n start_day = o.day\n current_period = period\n end\n\n # Previous group ended, add it\n if period != current_period\n day = I18n.t(\"days.#{start_day}\")\n if end_day != nil\n day += \" - \" + I18n.t(\"days.#{end_day}\")\n end\n # Hverdager custom string\n if start_day == \"monday\" and end_day == \"friday\"\n day = \"Hverdager\"\n end\n open_hours.append([day, current_period])\n current_period = period\n start_day = o.day\n end_day = nil\n end\n\n # Update period end\n if start_day != o.day\n end_day = o.day\n end\n\n # Last day closes period\n if i >= standard_hours.count - 1\n day = I18n.t(\"days.#{start_day}\")\n if end_day != nil\n day += \" - \" + I18n.t(\"days.#{o.day}\")\n end\n open_hours.append([day, current_period])\n end\n\n end\n\n open_hours\n end", "def show_start_date(event)\n if event.start_at - 2.hours<= Time.now ##### - 2 ore per via dell'utc. Brutto - riparare.\n \"<strong><em>Event started</em></strong>\".html_safe\n else\n event.start_at.to_formatted_s(:short)\n #DateTime.now.to_s + '-' +event.start_at.to_s\n end\n end", "def hour_table\n content_tag :div, :class => \"day_div\" do\n content_tag :table, :class => \"day_table\" do\n header + time_body\n end\n end\n end", "def happy_hour\n event_display(\"It's HAPPY HOUR! Everybody let's loose.\")\n group_event_hash_creator({soft_skills: 2, wellbeing: 2})\n end", "def hours_for(hours)\n return 'closed' if hours.blank?\n\n hours.reduce '' do |memo, time_range|\n midnight = Time.current.midnight\n start_time = midnight.since(time_range.begin).strftime(TIME_FORMAT).strip\n end_time = midnight.since(time_range.end).strftime(TIME_FORMAT).strip\n\n memo + \"#{memo.empty? ? '' : ', '}#{start_time} to #{end_time}\"\n end\n end", "def show_end_date(event)\n #if (((event.end_at).to_s).slice(0..9)).to_i < (((DateTime.now).to_s).slice(0..9)).to_i\n if event.end_at - 2.hours< DateTime.now\n \"<strong><em>and closed.</em></strong>\".html_safe\n else\n event.end_at.to_formatted_s(:short)\n end\n end", "def index\n @open_hours = OpenHour.all\n end", "def hour_cell(half_hour)\n if half_hour % 2 == 0\n content_tag :td, :class => \"day_hour_cell\", \n :width => \"1%\", :rowspan => 2 do\n if (half_hour/2 == 0)\n ''\n elsif (half_hour/2 < 12)\n (half_hour/2).to_s + 'am'\n elsif (half_hour/2 == 12)\n 'Noon'\n elsif (half_hour/2 > 12)\n ((half_hour/2) - 12).to_s + 'pm'\n end\n end\n else\n nil\n end\n end", "def opening_time\n opening_time = Time.new(2020, 10, 07, @opening_time[0..1], @opening_time[3..4])\n opening_time.strftime(\"%k:%M\")\n end", "def labor_hours\n font \"Helvetica\"\n fill_color \"555555\"\n text \"Hours Log\", align: :center, size: 12, style: :bold\n fill_color \"000000\"\n table([\n [\"Worked By\", \"Date\", \"Clock in\", \"Clock out\", \"Labor time\", \"Down time\"],\n [\"\",\"\",\"\",\"\",\"\",\"\"],\n [\"\",\"\",\"\",\"\",\"\",\"\"],\n [\"\",\"\",\"\",\"\",\"\",\"\"],\n [\"\",\"\",\"\",\"\",\"\",\"\"]\n ], :header => true,\n :position => :center,\n :column_widths => [187, 79, 79, 79, 53, 53],\n :cell_style => {:font => \"Helvetica\", :size => 12, :height => 35, :align => :center}\n )\n end", "def hour_events(selected_day, hour, events)\n h = hour.split(\":\")\n hour_end = \"#{h[0]}:59\"\n events.select { |e| e.start_time.to_date == selected_day && (e.start_time.to_time.strftime(\"%H:%M\") >= hour) && (e.start_time.to_time.strftime(\"%H:%M\") < hour_end) }\n end", "def hours\n \n end", "def time_rows\n rows = []\n (0..NUM_HALF_HOURS-1).each do |half_hour|\n cols = []\n row = content_tag :tr do\n cols << hour_cell(half_hour)\n cols << minute_cell(half_hour)\n (0..(num_days-1)).each do |day|\n cols << event_cells(half_hour,day)\n end\n cols.join.html_safe\n end\n rows << row\n end\n rows.join.html_safe\n end", "def holiday_schedule_content_for(schedule)\n content_tag :section do\n \"#{date_range_for(schedule.start_date, schedule.end_date)}: \" \\\n \"#{holiday_hours(\n schedule.closed, schedule.opens_at, schedule.closes_at\n )}\".html_safe\n end\n end", "def day\n @client = Client.new\n @title = @current_user.name\n @view = 'day'\n # TODO is Date.parse in current time zone? If not add.\n @date = params[:date].nil? ? Date.current : Date.parse(params[:date])\n # TODO: brakeman is warning of security problem with this line\n @nav_title = @date.strftime(NAV_TITLE[@view.to_sym])\n # TODO: should employees stay or go?\n @employees = [1]\n\n @appointments_by_hour = Hash.new\n r = Appointment.where(time: @date.in_time_zone.beginning_of_day..@date.in_time_zone.end_of_day).order(:time).includes(:client)\n r.each do |appointment| #.order(:time).group_by(&:time)\n k = appointment.time.hour\n if @appointments_by_hour.has_key?(k)\n @appointments_by_hour[k].push(appointment)\n else\n @appointments_by_hour[k] = [appointment]\n end\n end\n\n render 'index'\n end", "def render_events(events)\n output = ''\n last_date = Date.parse('1970-1-1')\n events.each do |event|\n \n week, calendar_page = '',''\n \n #unless last_date.strftime('%W') == event.start_date.strftime('%W')\n # #week = render_week(event.start_date)\n #end\n #unless last_date.day == event.start_date.day\n # calendar_page = render_calendar_page(event.start_date)\n #end\n \n #output += render(:partial => 'events/event',:locals => {:event=>event, :week=>week, :calendar_page=>calendar_page})\n \n #last_date = event.start_date\n \n end\n output\n end", "def reporthelp_decorated_hours( actual, potential )\n class_name = actual < 0 ? 'overrun' : 'no_overrun'\n output = \"<strong><span class=\\\"#{ class_name }\\\">#{ apphelp_terse_hours( actual ) }</span> / \"\n class_name = potential < 0 ? 'overrun' : 'no_overrun'\n output << \"<span class=\\\"#{ class_name }\\\">#{ apphelp_terse_hours( potential ) }</span></strong>\"\n\n return output.html_safe()\n end", "def display_event_time(event, day)\n time = event.start_at\n if !event.all_day and time.to_date == day\n # try to make it display as short as possible\n format = (time.min == 0) ? \"%l\" : \"%l:%M\"\n t = time.strftime(format)\n am_pm = time.strftime(\"%p\") == \"PM\" ? \"p\" : \"\"\n t += am_pm\n %(<span class=\"ec-event-time\">#{t}</span>)\n else\n \"\"\n end\n end", "def opening(day)\n Time.now.utc.midnight\n .advance(seconds: opening_second(day)).strftime('%H:%M')\n end", "def hour() end", "def all_day_events\n w = (90.0/num_days).to_i\n rows = []\n (1..(@all_day_max)).each do |row|\n cols = []\n c1 = content_tag :td, :width => \"8%\", :colspan => \"2\", \n :class => \"day_header\" do\n '' \n end\n cols << c1\n (0..(num_days-1)).each do |day|\n if @events_all_day[day].size >= row\n event = @events_all_day[day][row-1]\n col = content_tag :td, \n :height => \"15px\",\n :overflow => \"hidden\",\n :style => \"width: #{w}%\", :width => \"#{w}%\",\n :class => \"day_appointment \" + calb_class(event.calendar, user) do\n content_tag :a, :href => \"/events/#{event.id}/edit\", \n :title => \"#{event.title}\",\n :data => {:toggle => \"popover\", \n :content => \"#{event.where}#{event.when}#{event.my_notes}\",\n :html => \"true\",\n :trigger => \"hover\",\n :placement => \"left\",\n :remote => true },\n :class => \"event-popover\" do\n content_tag :div, :class => \"hide_extra\" do\n self.event_day_text(event,1)\n end\n end\n end\n else\n col = content_tag :td, \n :max => {:height => \"15px\"},\n :style => \"width: #{w}%\", :width => \"#{w}%\",\n :class => \"day_free_time\" do\n ''\n end\n end\n cols << col\n end\n row = content_tag :tr do\n cols.join.html_safe\n end\n rows << row\n end\n rows.join.html_safe\n end", "def open?\n return false if close_today?\n today = self.time_tables.find_by(day_of_week: Time.now.wday)\n (today.opened_at...today.closed_at).include?(Time.now.hour)\nend", "def render_events(events)\n output = ''\n last_date = Date.parse('1970-1-1')\n events.each do |event|\n \n week, calendar_page = '',''\n \n unless last_date.strftime('%W') == event.start_date.strftime('%W')\n week = render_week(event.start_date)\n end\n unless last_date.day == event.start_date.day\n calendar_page = render_calendar_page(event.start_date)\n end\n \n output += render(:partial => 'events/event',:locals => {:event=>event, :week=>week, :calendar_page=>calendar_page})\n \n last_date = event.start_date\n \n end\n output\n end", "def announce_closing_time(hours)\n closing_time = Time.new(2020, 10, 07, @opening_time) + hours*60*60\n \"#@name will be closing at #{closing_time.strftime('%l:%M%p')}\"\n end" ]
[ "0.7583415", "0.68261546", "0.67819184", "0.67529577", "0.6543452", "0.6395733", "0.63855106", "0.6383688", "0.63061786", "0.62769926", "0.62262607", "0.62031305", "0.6105163", "0.6105075", "0.6087681", "0.606036", "0.60447145", "0.60320646", "0.6014234", "0.60035425", "0.5996917", "0.597093", "0.59433234", "0.591778", "0.59135103", "0.5889401", "0.5866576", "0.58456755", "0.5815175", "0.5813061" ]
0.78061634
0
GET /quizfinals/1 GET /quizfinals/1.xml
def show @quizfinal = Quizfinal.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @quizfinal } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @questions = @quiz.questions.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def new\n @quizfinal = Quizfinal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quizfinal }\n end\n end", "def index\n @scores = (@user || @quiz).scores\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @scores }\n end\n end", "def index\n @quiz_results = current_student.quiz_results\n @unfiltered_quizzes = current_student.classroom.teacher.quizzes\n @quizzes = Quiz.TakeableQuizzes(@unfiltered_quizzes, @quiz_results)\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end", "def show\n @complete_quiz = serve_complete_quiz_sorted(@quiz)\n @section = @quiz.section\n @course = @quiz.section.course\n @next_checkpoint = get_next_checkpoint(@quiz)\n puts @next_checkpoint.to_json\n end", "def index\n @quizzes = Quiz.all \n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @quizzes }\n end\n end", "def index\n @assessment_end_chapter_quizzes = AssessmentEndChapterQuiz.page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json:@assessment_end_chapter_quizzes }\n end\n end", "def index\n if params[:quiz_id]\n @quiz = Quizzes::Quiz.find(params[:quiz_id])\n @quizzes_questions = @quiz.questions\n else\n @quizzes_questions = Quizzes::Question.all\n end\n end", "def index\n @quizzes = Quiz.all\n end", "def index\n @quizzes = Quiz.all\n end", "def index\n @quizzes = Quiz.all\n end", "def index\n @quizzes = Quiz.all\n end", "def index\n @quizzes = Quiz.all\n end", "def index\n @questions = @page.questions.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def myquizze_results\n @current_user = get_logged_user\n if @quizze_instance = @current_user.get_latest_quizze_instance\n @quizze = @quizze_instance.get_quizze\n @sorted_affinities = @quizze_instance.sorted_affinities\n @explanations, @hash_dimension2answers, @hash_question_idurl2min_max_weight = @quizze_instance.get_explanations(@current_knowledge, @sorted_affinities)\n else\n redirect_to(\"/quizzes\") # select a quizz first !\n end\n end", "def index\n @questionnaires = Questionnaire.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questionnaires }\n end\n end", "def show\n @assessment_end_chapter_quiz = AssessmentEndChapterQuiz.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json:@assessment_end_chapter_quiz }\n end\n end", "def index\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questionnaires }\n end\n end", "def index\n @questions = Question.find(:all)\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def show\n @quiz = Quiz.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @quiz }\n end\n end", "def index\n @questions = Question.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def index\n @questions = Question.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def index\n @quiz = Quiz.all\n end", "def questions\n @response = self.class.get(\"/data/2.5/forecast\", @options)\n end", "def index\n @course = Course.find(params[:course_id])\n @questions = @course.questions.current.due + @course.questions.current.pending.find(:all, :order => :next_datetime, :limit => 200)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def show\r\n @evaluation = Evaluation.find(params[:id])\r\n @responses = Response.find_all_by_Evaluation_id params[:id]\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.xml { render :xml => @evaluation }\r\n end\r\n end", "def quiz_get\r\n # allow receiving all parameters\r\n params.permit!\r\n\r\n # response format pre-defined\r\n result = {:str_uid => nil, :obj_quizprop => nil, :arr_items => nil }\r\n\r\n begin\r\n target_quiz = Mongodb::BankQuizQiz.find_by(_id: params[:str_rid])\r\n result[:str_uid] = params[:str_uid]\r\n result[:obj_quizprop] = target_quiz\r\n result[:arr_items] = target_quiz.quiz_detail\r\n rescue Exception => ex\r\n # do nothing for current \r\n end\r\n\r\n result_json = Common::Response.exchange_record_id(result.to_json)\r\n render :text=>Common::Response.format_response_json(result_json,Common::Response.get_callback_type(params))\r\n end", "def index\n @quizzes = Quiz.all\n @questions\n @count\n end", "def show\n render json: @quiz\n end", "def index\n @quizzes_answers = Quizzes::Answer.all\n end" ]
[ "0.6879233", "0.6555892", "0.624725", "0.60998327", "0.60942304", "0.6057913", "0.6044179", "0.6004726", "0.6002623", "0.6002623", "0.6002623", "0.6002623", "0.6002623", "0.5977035", "0.59098697", "0.5880287", "0.5877415", "0.5857726", "0.5853135", "0.5852244", "0.58369017", "0.58369017", "0.58070505", "0.58044636", "0.5794394", "0.57830036", "0.57805014", "0.57555896", "0.57504606", "0.573551" ]
0.7151089
0
GET /quizfinals/new GET /quizfinals/new.xml
def new @quizfinal = Quizfinal.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @quizfinal } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @quizfinal = Quizfinal.new(params[:quizfinal])\n\n respond_to do |format|\n if @quizfinal.save\n format.html { redirect_to(@quizfinal, :notice => 'Quizfinal was successfully created.') }\n format.xml { render :xml => @quizfinal, :status => :created, :location => @quizfinal }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @quizfinal.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @qa = Qa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @qa }\n end\n end", "def new\n @qa = Qa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @qa }\n end\n end", "def new_rest\n @entry_answer = EntryAnswer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @entry_answer }\n end\n end", "def new_rest\n @question_localized = QuestionLocalized.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question_localized }\n end\n end", "def new\n @quest = Quest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quest }\n end\n end", "def new\n @question = @page.questions.new\n session[:breadcrumbs].add \"New\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end", "def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @question }\n end\n end", "def new\n @estoques = Estoque.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @estoques }\n end\n end", "def new_rest\n @answer_localized = AnswerLocalized.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @answer_localized }\n end\n end", "def new\n @quarter = Quarter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quarter }\n end\n end", "def new\n @quay = Quay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quay }\n end\n end", "def new\n @question = Question.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end", "def new\n @quest_template = QuestTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quest_template }\n end\n end", "def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end", "def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end", "def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end", "def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end", "def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end", "def faq_new\n @article = Article.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @article }\n end\n end", "def new\n @questao = Questao.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @questao }\n end\n end", "def new\n @questionnaire = Questionnaire.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @questionnaire }\n end\n end", "def new\n @qualification = Qualification.new\n @qlist = Qualification.first.self_and_descendants\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @qualification }\n end\n end", "def new\n @predicition = Predicition.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @predicition }\n end\n end", "def new\n @answer = @question.answers.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @answer }\n end\n end", "def new\n @quiz_center_quiz = Quiz.new\n breadcrumbs.add I18n.t(\"helpers.titles.#{current_action}\", :model => Model_class.model_name.human), new_quiz_center_quiz_path\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @quiz_center_quiz }\n end\n end", "def show\n @quizfinal = Quizfinal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @quizfinal }\n end\n end", "def new\n @trial = Trial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @trial }\n end\n end", "def new\n @final_service = FinalService.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @final_service }\n end\n end", "def new\n @tutorials = Tutorials.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tutorials }\n end\n end" ]
[ "0.6976906", "0.66912985", "0.66912985", "0.66715384", "0.6649722", "0.66490513", "0.6539322", "0.65380245", "0.6515356", "0.649198", "0.6486526", "0.64579654", "0.64514726", "0.64479655", "0.64467806", "0.64467806", "0.64467806", "0.64467806", "0.64467806", "0.6429536", "0.6414627", "0.6407872", "0.64072573", "0.6396484", "0.63877004", "0.6387471", "0.6383955", "0.6368983", "0.6365816", "0.6349218" ]
0.7759686
0
POST /quizfinals POST /quizfinals.xml
def create @quizfinal = Quizfinal.new(params[:quizfinal]) respond_to do |format| if @quizfinal.save format.html { redirect_to(@quizfinal, :notice => 'Quizfinal was successfully created.') } format.xml { render :xml => @quizfinal, :status => :created, :location => @quizfinal } else format.html { render :action => "new" } format.xml { render :xml => @quizfinal.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @quiz = current_user.quizzes.build(quiz_params)\n\n @quiz.questions.each do |q|\n if q.question_type == \"free_answer\"\n q.answers = []\n end\n end\n\n puts @quiz.questions\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to current_user, notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @quizfinal = Quizfinal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quizfinal }\n end\n end", "def create\r\n @evaluation = Evaluation.new(params[:evaluation])\r\n @answers = @evaluation.responses\r\n\r\n respond_to do |format|\r\n if @evaluation.save && @answers.each{|a| a.save }.all?\r\n format.html { redirect_to(@evaluation, :notice => 'Evaluation was successfully created.') }\r\n format.xml { render :xml => @evaluation, :status => :created, :location => @evaluation }\r\n else\r\n format.html { render :action => \"new\" }\r\n format.xml { render :xml => @evaluation.errors, :status => :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @quiz = Quiz.new(quiz_params)\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to @quiz, notice: \"Quiz was successfully created.\" }\n format.json { render :show, status: :created, location: @quiz }\n\t\tmy_array = []\n\t\tmy_array << @quiz.option1\n\t\tmy_array << @quiz.option2\n\t\tmy_array << @quiz.option3\n\t\tmy_array << @quiz.option4\n\t\t\n\t\tcorrect_respo = my_array[@quiz.correct_response.to_i - 1]\n\t\t@quiz.correct_response_text = correct_respo\n\t\t@quiz.save\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to @quiz, notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to @quiz, notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz_center_quiz = Quiz.new(params[:quiz])\n\n respond_to do |format|\n if @quiz_center_quiz.save\n format.html { redirect_to [:quiz_center,@quiz_center_quiz], notice: 'Quiz was successfully created.' }\n format.json { render json: @quiz_center_quiz, status: :created, location: @quiz_center_quiz }\n else\n format.html { render action: \"new\" }\n format.json { render json: @quiz_center_quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(current_question: 1)\n @question = Question.find(@quiz.current_question)\n @response = Response.new\n respond_to do |format|\n if @quiz.save\n cookies[:finished_quiz] = false\n format.js\n else\n format.js { flash[:alert] = 'There was a problem creating quiz.' }\n end\n end\n end", "def create\n\t\t\tquiz = Quiz.new(quiz_params)\n\t\t\tif quiz.save\n\t\t\t\tcurrent_instructor.quizzes << quiz\n\t\t\t\trender json: { id: quiz.id }, status: 201\n\t\t\telse\n\t\t\t\trender json: { error: quiz.errors }, status: 422\n\t\t\tend\n\t\tend", "def destroy\n @quizfinal = Quizfinal.find(params[:id])\n @quizfinal.destroy\n\n respond_to do |format|\n format.html { redirect_to(quizfinals_url) }\n format.xml { head :ok }\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to new_question_path, notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create # rubocop:disable Metrics/AbcSize\n @quiz = @topic.quizzes.build(quiz_params)\n respond_to do |format|\n if @quiz.save\n format.html {\n redirect_to discipline_topic_quiz_path(@discipline, @topic, @quiz), notice: 'Quiz was successfully created.'\n }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n #@result = @quiz.result.build()\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to quizzes_path, notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz_free_answer = QuizFreeAnswer.new(quiz_free_answer_params)\n\n respond_to do |format|\n if @quiz_free_answer.save\n format.html { redirect_to @quiz_free_answer, notice: \"Quiz free answer was successfully created.\" }\n format.json { render :show, status: :created, location: @quiz_free_answer }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @quiz_free_answer.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = User.find(params[:id])\n @user.answer_ids = params[:answers]\n\n unless (StudentsQuiz.find_by(student_id: params[:id], publication_id: params[:quiz][:id]))\n respond_to do |format|\n format.json { render json: { marks: @user.answer_quiz(params[:answers], params[:quiz][:id]), total_marks: Publication.find(params[:quiz][:id]).quiz.marks.to_f } }\n end\n else\n respond_to do |format|\n format.json { render json: { errors: \"You have answered before\" }, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quizzes_answer = Quizzes::Answer.new(quizzes_answer_params)\n\n respond_to do |format|\n if @quizzes_answer.save\n format.html { redirect_to @quizzes_answer, notice: 'Answer was successfully created.' }\n format.json { render :show, status: :created, location: @quizzes_answer }\n else\n format.html { render :new }\n format.json { render json: @quizzes_answer.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to new_temp_question_path(:qid => @quiz.id), notice: 'Quiz temporarily created. Proceed with adding Questions for your Quiz'}\n format.json { render action: 'show', status: :created, location: @quiz }\n else\n format.html { render action: 'new' }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n questions_arr.each do |i|\n question = Question.new(question_params(i))\n choices_arr(i).each do |j|\n choice = Choice.new(choice_params(j))\n choice.save\n question.choices << choice\n end\n @quiz.questions << question\n end\n\n if @quiz.save\n User.find(params[:user_id]).quizzes << @quiz\n render json: @quiz, status: :created, location: @quiz\n else\n render json: @quiz.errors, status: :unprocessable_entity\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n\n respond_to do |format|\n if @quiz.save\n @quiz.refrence_id = @quiz.id\n @quiz.save\n format.json { render json: @quiz.show_full_details }\n else\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pub_quiz_answer = PubQuizAnswer.new(pub_quiz_answer_params)\n\n respond_to do |format|\n if @pub_quiz_answer.save\n format.html { redirect_to '/days/23', notice: 'Your pub quiz answers were successfully submitted! Ask Sarah to mark them...' }\n format.json { render :show, status: :created, location: @pub_quiz_answer }\n else\n format.html { render :new }\n format.json { render json: @pub_quiz_answer.errors, status: :unprocessable_entity }\n end\n end\n end", "def quiz_params\n params.require(:quiz).permit(:missao_id, :nome, :descricao, :usuario_curso_id, :finalizado)\n end", "def create\n @kidsquiz105 = Kidsquiz105.new(kidsquiz105_params)\n\n respond_to do |format|\n if @kidsquiz105.save\n format.html { redirect_to @kidsquiz105, notice: 'Kidsquiz105 was successfully created.' }\n format.json { render :show, status: :created, location: @kidsquiz105 }\n else\n format.html { render :new }\n format.json { render json: @kidsquiz105.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n #render :json => params[:quiz_answer]\n #return\n @quiz=Quiz.find(params[:quiz_id])\n\n\n @quiz_answer = QuizAnswer.new(quiz_answer_params)\n\n @question=Question.find(params[:quiz_answer][:question_id])\n #render :json => @quiz.questions\n #return\n\n @next_question = (@quiz.questions.map(&:id) - current_user.quiz_answers.map(&:question_id) - [@question.id])\n #render :json => @quiz.questions\n #return\n\n\n respond_to do |format|\n if @quiz_answer.save\n\n #puts \"check next question #{@next_question}\"\n if @next_question == []\n current_user.current_route = \"/my_dashboard\"\n current_user.save!\n #redirect_to snazzmeup_path,:alert=>\"Successfully given quiz response\"\n redirect_to quiz_review_path(@quiz.id), :alert=>\"Successfully given quiz response\"\n return\n else\n @next_question = @next_question[0]\n current_user.current_route = \"/take_test/#{@quiz.id}/#{@next_question}\"\n current_user.save!\n end\n\n format.html { redirect_to take_test_path(@quiz.id,@next_question)}\n format.json { render action: 'show', status: :created, location: @quiz_answer }\n\n else\n format.html { redirect_to take_test_path(@quiz.id, @question.id), notice: 'Howdy!! You need to select one option.' }\n format.json { render json: @quiz_answer.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @survey_quiz = Survey::Quiz.new(survey_quiz_params)\n authorize @survey_quiz\n\n respond_to do |format|\n if @survey_quiz.save\n format.html { redirect_to [:new, @survey_quiz, :question], notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @survey_quiz }\n else\n format.html { render :new }\n format.json { render json: @survey_quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = @quiz.questions.new(params[:question])\n\n respond_to do |format|\n @question.save\n if @question.errors.blank?\n flash[:notice] = 'Question was successfully created.'\n format.html { redirect_to(quiz_questions_path(@quiz)) }\n format.xml { render :xml => @question, :status => :created, :location => @question }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(params[:quiz])\n\n if @quiz.save\n redirect_to @quiz, notice: 'Quiz was successfully created.'\n else\n render action: \"new\"\n end\n end", "def create\n #@errors = {}\n if params[ :quiz_id ] && params[ :user_id ]\n# lead_answer_id = params[ :lqa ]\n# if lead_answer_id.blank? && !params[ :questions ].blank?\n# params[ :questions ].each_pair do |qid,aid|\n# if QuizQuestion.find_by_id( qid ).quiz_phase.position == 0\n# lead_answer_id = aid\n# end\n# end\n# end\n \n @quiz_instance = QuizInstance.create(\n :quiz_id => params[ :quiz_id ],\n :user_id => nil,\n :quiz_instance_uuid => @@uuid_generator.generate( :compact ),\n :lead_answer_id => nil,\n :partner_user_id => params[ :user_id ]\n )\n\n if !params[ :questions ].blank?\n params[ :questions ].each_pair do |qid,aid_list|\n aid_list.split( ',' ).each do |aid|\n answer_text=''\n answer_text = params[ :answer ][aid.to_s] unless params[ :answer ].blank? || params[ :answer ][aid.to_s].blank?\n UserQuizAnswer.create( :quiz_answer_id => aid, :user_id => ( @user ? @user.id : nil ), :quiz_instance_id => @quiz_instance.id, :user_answer_text_response => answer_text )\n end\n end\n end\n\n qiid_cookie_write @quiz_instance.quiz_instance_uuid\n\n if @quiz_instance\n # no more POST / Redirect, so we have to revert to this sort of mess.\n # now we need to set up all the data we'll need to render the first\n # phase of the quiz.\n previous_quiz_phase = QuizPhase.first(:conditions => ['quiz_id = ? and position = 0', @quiz_instance.quiz_id])\n begin\n if params[:lqa]\n next_phase_id = QuizAnswer.find(params[:lqa]).next_quiz_phase_id\n else\n next_phase_id = QuizAnswer.find(params[:questions][previous_quiz_phase.branch_question_id.to_s]).next_quiz_phase_id\n end\n @quiz_phase = QuizPhase.find(next_phase_id)\n rescue\n @quiz_phase = QuizPhase.first(:conditions => ['quiz_id = ? and position = 1', @quiz_instance.quiz_id])\n end\n @quiz = @quiz_instance.quiz\n @quiz_page = 1\n\n # also build the resume URI if we have previous instances of this\n # quiz from this user. resume URI is based on the LAST instanced\n # opened.\n load_previous_quiz_instance\n\n @total_quiz_questions = QuizQuestion.count(\n :conditions => [ 'quizzes.id = ? and quiz_questions.active = 1', @quiz.id ],\n :joins => { :quiz_phase => :quiz }\n )\n\n render :file => 'quiz_instances/show.xml'\n\n else\n @errors[ 'quiz' ] = [\n 'Internal Service Error. Unable to create quiz instance.',\n #'We are unable to start your quiz at this time.',\n 500 ]\n\n end\n else\n if !params[ :quiz_id ]\n @errors[ 'quiz_id' ] = [\n 'Required parameter Quiz ID not provided',\n #'Please select a quiz to continue.',\n 400 ]\n end\n\n if !params[ :user_id ]\n @errors[ 'user_id' ] = [\n 'Required parameter User ID not provided.',\n #'Please select a quiz to continue.',\n 400 ]\n end\n #render :text => \"You must supply a quiz id in order to create an open quiz instance.\", :status => 400\n end\n\n if @errors.size != 0\n #if params[ :format ] = 'xml'\n render 'errors.xml.builder'#, :status => @error_code\n #end\n end\n end", "def update\n @quizfinal = Quizfinal.find(params[:id])\n\n respond_to do |format|\n if @quizfinal.update_attributes(params[:quizfinal])\n format.html { redirect_to(@quizfinal, :notice => 'Quizfinal was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @quizfinal.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n\n if @quiz.save\n redirect_to @quiz, notice: 'Assignment was successfully created.'\n else\n render :new\n end\n end", "def create\n @quiz = Quiz.new(quiz_params.merge(topic: Topic.first))\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to topic_quiz_path(@quiz, @quiz.topic), notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: topic_quiz_path(@quiz, @quiz.topic) }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.62818843", "0.6116551", "0.594172", "0.5826549", "0.5798797", "0.5798797", "0.57557464", "0.57401633", "0.57390344", "0.57379067", "0.573764", "0.5734384", "0.5725366", "0.57071906", "0.5662066", "0.5657221", "0.56321794", "0.56226844", "0.55699563", "0.5538775", "0.55363804", "0.5484901", "0.5466479", "0.5455078", "0.54484874", "0.54092854", "0.5402332", "0.5385048", "0.53760624", "0.5369521" ]
0.7016726
0
PUT /quizfinals/1 PUT /quizfinals/1.xml
def update @quizfinal = Quizfinal.find(params[:id]) respond_to do |format| if @quizfinal.update_attributes(params[:quizfinal]) format.html { redirect_to(@quizfinal, :notice => 'Quizfinal was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @quizfinal.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @quiz = Quiz.find(params[:id])\n \n respond_to do |format|\n if @quiz.update_attributes(params[:quiz])\n format.html { redirect_to @quiz, notice: 'Quiz was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to quizzes_path, notice: 'Quiz was successfully updated.' }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to quizzes_path, notice: 'Quiz was successfully updated.' }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to @quiz, notice: 'Quiz was successfully updated.' }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to @quiz, notice: 'Quiz was successfully updated.' }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to @quiz, notice: 'Quiz was successfully updated.' }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to current_user, notice: 'Quiz was successfully updated.' }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @quiz_center_quiz = Quiz.find(params[:id])\n\n respond_to do |format|\n if @quiz_center_quiz.update_attributes(params[:quiz])\n format.html { redirect_to [:quiz_center,@quiz_center_quiz], notice: 'Quiz was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @quiz_center_quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to @quiz, notice: 'Quiz was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html {\n redirect_to discipline_topic_quiz_path(@discipline, @topic, @quiz), notice: 'Quiz was successfully updated.'\n }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz.update(quiz_params)\n format.html { redirect_to @quiz, notice: 'Quiz atualizado com sucesso!' }\n format.json { render :show, status: :ok, location: @quiz }\n else\n format.html { render :edit, @current_usuario => current_usuario }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = @quiz.questions.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n flash[:notice] = 'Question was successfully updated.'\n format.html { redirect_to(quiz_questions_path(@quiz)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quizzes_answer.update(quizzes_answer_params)\n format.html { redirect_to quiz_assessments_path(@quizzes_answer.assessment.quiz) }\n format.json { render :show, status: :ok, location: @quizzes_answer }\n else\n format.html { render :edit }\n format.json { render json: @quizzes_answer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @survey_quiz.update(survey_quiz_params)\n format.html { redirect_to @survey_quiz, notice: 'Quiz was successfully updated.' }\n format.json { render :show, status: :ok, location: @survey_quiz }\n else\n format.html { render :edit }\n format.json { render json: @survey_quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def single_quiz_update\r\n #allow receiving all parameters\r\n params.permit!\r\n #response format pre-defined\r\n result = {\"str_id\" => nil, :status => \"\", :message => \"\" }\r\n begin\r\n current_quiz = Mongodb::BankQuizQiz.find_by(id: params[:str_id])\r\n current_quiz.save_quiz(params)\r\n result[:str_id]=current_quiz._id\r\n flash[:notice] = I18n.t(\"quizs.messages.update.success\" , :id => current_quiz._id)\r\n result[:status] = 200\r\n result[:message] = I18n.t(\"quizs.messages.update.success\", :id => current_quiz._id)\r\n rescue Exception => ex\r\n result[:status] = 500\r\n result[:message] = I18n.t(\"quizs.messages.update.fail\", :id => current_quiz._id)\r\n ensure\r\n render json: result.to_json\r\n end\r\n end", "def update\n @quiz = Quiz.find(params[:id])\n\n if @quiz.update(published: params[:quiz_status])\n head :no_content\n else\n render json: @quiz.errors, status: :unprocessable_entity\n end\n end", "def update\n @quiz = Quiz.find(params[:id])\n\n if @quiz.update_attributes(params[:quiz])\n redirect_to @quiz, notice: 'Quiz was successfully updated.'\n else\n render action: \"edit\"\n end\n end", "def update\n respond_to do |format|\n if @quizzes_question.update(quizzes_question_params)\n if params[:commit] =~ /add/i\n format.html { redirect_to edit_quiz_question_path(@question.quiz, @question) }\n else\n format.html { redirect_to quiz_questions_path(@question.quiz), notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @quizzes_question }\n end\n else\n format.html { render :edit }\n format.json { render json: @quizzes_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n answer = current_user.answers.create!(quiz: @quiz, correctness: (params[:answer].to_i > 0) )\n\n respond_to do |format|\n format.html { redirect_to topic_quiz_path(@quiz, @quiz.topic), notice: 'Your answer is saved.' }\n format.json { render :show, status: :ok, location: topic_quiz_path(@quiz, @quiz.topic) }\n end\n end", "def update\n @question = Question.find(params[:id])\n @quiz = Quiz.find(params[:id])\n if @quiz.update(quiz_params)\n flash[:success] = \"Quiz updated\"\n redirect_to @quiz\n else\n render 'edit'\n end\n end", "def update\n @recommend_recommend_quiz = Recommend::RecommendQuiz.find(params[:id])\n\n respond_to do |format|\n if @recommend_recommend_quiz.update_attributes(params[:recommend_recommend_quiz])\n format.html { redirect_to @recommend_recommend_quiz, notice: 'Recommend quiz was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @recommend_recommend_quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @questions_quiz.update(questions_quiz_params)\n format.html { redirect_to @questions_quiz, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n format.js { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @questions_quiz.errors, status: :unprocessable_entity }\n format.js { head :unprocessable_entity }\n end\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n @article=Article.find(@quiz.article_id)\n @course=Course.find(@article.course_id)\n temp=@course.totalQuizzes+1\n # @course.update(:totalQuizzes, temp)\n Course.update({totalQuizzes: temp})\n\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to :controller => 'articles', :action => 'index', notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @quizfinal = Quizfinal.find(params[:id])\n @quizfinal.destroy\n\n respond_to do |format|\n format.html { redirect_to(quizfinals_url) }\n format.xml { head :ok }\n end\n end", "def edit_question\n\t\t\tquizzes = current_instructor.quizzes\n\t\t\t@found = 0\n\t\t\tquizzes.each do |quiz|\n\t\t\t\tif(quiz.questions.exists?(:id => params[:question_id]))\n\t\t\t\t\t@found = @found + 1\n\t\t\t\tend \n\t\t\tend\n\t\t\tif (@found > 0)\n\t\t\t\tquestion = Question.find(params[:question_id])\n\t\t\t\tif (question.update(question_params))\n\t\t\t\t\trender json: { success: true, data: { :question => question }, info:{} }, status: 200\n\t\t\t\telse\n\t\t\t\t\trender json: { error: question.errors }, status: 422 \n\t\t\t\tend\t\n\t\t\telse\n\t\t\t\trender json: { error:\"Question is not found\" }, status: 422\n\t\t\tend\n\t\tend", "def update\n @questions = Question.all\n @categories = [\"Learning from Labs\", \"Lab Instructor\", \"Lab Space and Equipment\", \"Time Required to Complete Labs\", \"Lecture Section Instructor\"]\n respond_to do |format|\n if @survey.update(survey_params)\n format.html { redirect_to @survey, notice: 'Survey was successfully submitted.' }\n format.json { render :show, status: :ok, location: @survey }\n\n # Update 'completed' attribute to true\n submission = Survey.find_by(survey_ID: @survey.survey_ID)\n submission.update(status: true)\n\n # Increment 'completed' attribute for section\n @section = Section.find_by(class_num: @survey.class_num)\n @section.update(completed: @section.completed + 1)\n\n\n else\n format.html { render :edit }\n format.json { render json: @survey.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quiz_default.update(quiz_default_params)\n format.html { redirect_to @quiz_default, notice: 'Quiz default was successfully updated.' }\n format.json { render :show, status: :ok, location: @quiz_default }\n else\n format.html { render :edit }\n format.json { render json: @quiz_default.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to quiz_path(@question.subsection_id), notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quizfinal = Quizfinal.new(params[:quizfinal])\n\n respond_to do |format|\n if @quizfinal.save\n format.html { redirect_to(@quizfinal, :notice => 'Quizfinal was successfully created.') }\n format.xml { render :xml => @quizfinal, :status => :created, :location => @quizfinal }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @quizfinal.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.json { render :json => 'Question updated OK' }\n format.xml { head :ok }\n else\n format.json { render :json => @question.errors }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
[ "0.6406944", "0.6379716", "0.6379716", "0.6319763", "0.6319763", "0.6319763", "0.62618005", "0.6256499", "0.6218256", "0.62137145", "0.6209631", "0.6190479", "0.61281127", "0.6124844", "0.6062926", "0.6047397", "0.60464764", "0.60291994", "0.60224915", "0.5940452", "0.58794665", "0.587508", "0.5872997", "0.585676", "0.5850939", "0.5841874", "0.5797439", "0.578372", "0.57690126", "0.5767989" ]
0.6989084
0
DELETE /quizfinals/1 DELETE /quizfinals/1.xml
def destroy @quizfinal = Quizfinal.find(params[:id]) @quizfinal.destroy respond_to do |format| format.html { redirect_to(quizfinals_url) } format.xml { head :ok } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @quiz.destroy\n\n head :no_content\n end", "def deletepublish\n @question = Publishquiz.find(:all, :conditions=>\"question_id=\"+params[:question]+\" and quiz_id=\"+session[:quizid])\n @question[0].destroy\n\n respond_to do |format|\n format.html { redirect_to(questions_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @question = @quiz.questions.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to(quiz_questions_url(@quiz)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz = Quiz.find(params[:id])\n @quiz.destroy\n\n respond_to do |format|\n format.html { redirect_to quizzes_url }\n format.json { head :ok }\n end\n end", "def destroy\n @quiz_center_quiz = Quiz.find(params[:id])\n @quiz_center_quiz.destroy\n\n respond_to do |format|\n format.html { redirect_to quiz_center_quizzes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html {\n redirect_to discipline_topic_quizzes_path(@discipline, @topic), notice: 'Quiz was successfully destroyed.'\n }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz = Quiz.find(params[:id])\n @quiz.destroy\n\n redirect_to quizzes_url\n end", "def destroy\n @survey_quiz.destroy\n respond_to do |format|\n format.html { redirect_to survey_quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @qa = Qa.find(params[:id])\n @qa.destroy\n\n respond_to do |format|\n format.html { redirect_to(qas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @qa = Qa.find(params[:id])\n @qa.destroy\n\n respond_to do |format|\n format.html { redirect_to(qas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to lesson_url(current_lesson), notice: \"Quiz was successfully deleted.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz_default.destroy\n respond_to do |format|\n format.html { redirect_to quiz_defaults_url, notice: 'Quiz default was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @recommend_recommend_quiz = Recommend::RecommendQuiz.find(params[:id])\n @recommend_recommend_quiz.destroy\n\n respond_to do |format|\n format.html { redirect_to recommend_recommend_quizzes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @quiz = Quiz.find(params[:id])\n @quiz.destroy\n redirect_to admin_panel_quizzes_path\n end", "def destroy\n @quiz.destroy\n flash[:success] = \"Quiz deleted\"\n redirect_to request.referrer || root_url\n end", "def destroy\n @exam = Exam.find(params[:id])\n @exam.destroy\n\n respond_to do |format|\n format.html { redirect_to(exams_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @questionnaire = Questionnaire.find(params[:id])\n @questionnaire.destroy\n\n respond_to do |format|\n format.html { redirect_to questionnaires_url }\n format.xml { head :ok }\n end\n end", "def destroy\n @quiz_answer.destroy\n respond_to do |format|\n format.html { redirect_to quiz_answers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @survey_answer = SurveyAnswer.find(params[:id])\n @survey_answer.destroy\n\n respond_to do |format|\n format.html { redirect_to(survey_answers_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @quizzes_question.destroy\n respond_to do |format|\n format.html { redirect_to quiz_questions_url(@quiz), notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def single_quiz_delete\r\n #allow receiving all parameters\r\n params.permit!\r\n #response format pre-defined\r\n @result = {\"str_id\" => nil, :status => \"\", :message => \"\" }\r\n begin\r\n current_quiz = Mongodb::BankQuizQiz.where(:_id => params[\"str_id\"]).first\r\n current_id = current_quiz._id.to_s\r\n current_quiz.destroy_quiz\r\n flash[:notice] = I18n.t(\"quizs.messages.delete.success\" , :id => current_id)\r\n @result[:status] = 200\r\n @result[:message] = I18n.t(\"quizs.messages.delete.success\", :id => current_id)\r\n rescue Exception => ex\r\n @result[:status] = 500\r\n @result[:message] = I18n.t(\"quizs.messages.delete.fail\", :id => current_id)\r\n # ensure\r\n # render json: result.to_json\r\n end\r\n end" ]
[ "0.71384156", "0.70924664", "0.70029634", "0.6929543", "0.688979", "0.688554", "0.68545747", "0.6792162", "0.67401", "0.6714703", "0.67134297", "0.67134297", "0.6704211", "0.6704139", "0.66968465", "0.66964006", "0.66964006", "0.66964006", "0.66964006", "0.66964006", "0.66964006", "0.66964006", "0.6694385", "0.659416", "0.6582916", "0.6572996", "0.6554617", "0.6544857", "0.65369993", "0.65256655" ]
0.7536592
0
POST /tx_royalties POST /tx_royalties.json
def create @tx_royalty = TxRoyalty.new(tx_royalty_params) respond_to do |format| if @tx_royalty.save format.html { redirect_to @tx_royalty, notice: 'Tx royalty was successfully created.' } format.json { render :show, status: :created, location: @tx_royalty } else format.html { render :new } format.json { render json: @tx_royalty.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_tx_royalty\n @tx_royalty = TxRoyalty.find(params[:id])\n end", "def create\n @nursery_table = NurseryTable.new(nursery_table_params)\n\n respond_to do |format|\n if @nursery_table.save\n format.html { redirect_to @nursery_table, notice: \"Nursery table was successfully created.\" }\n format.json { render :show, status: :created, location: @nursery_table }\n else\n format.html { render :new }\n format.json { render json: @nursery_table.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tx = Tx.new(tx_params)\n\n respond_to do |format|\n if @tx.save\n format.html { redirect_to @tx, notice: 'Tx was successfully created.' }\n format.json { render :show, status: :created, location: @tx }\n else\n format.html { render :new }\n format.json { render json: @tx.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tenacity = current_user.tenacities.new(tenacity_params)\n\n respond_to do |format|\n if @tenacity.save\n format.html { redirect_to @tenacity, notice: 'Tenacity was successfully created.' }\n format.json { render action: 'show', status: :created, location: @tenacity }\n else\n format.html { render action: 'new' }\n format.json { render json: @tenacity.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @tx_royalty.destroy\n respond_to do |format|\n format.html { redirect_to tx_royalties_url, notice: 'Tx royalty was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def createCharities\n\tcharity_list = [\"Direct Relief\", \"Catholic Medical Mission Board\", \"MAP International\", \"United Nations Foundation\", \"The Rotary Foundation of Rotary International\", \"Samaritan's Purse\", \"Institute of International Education\", \"International Rescue Committee\", \"Compassion International\", \"United States Fund for UNICEF\"]\n\tcharity_list.each do |charity|\n\t\tRestClient.post 'http://api.reimaginebanking.com/merchants?key=e0486a76005721ee6d86b140eaea2a40', { \"name\": \"#{charity}\"}.to_json, :content_type => :json, :accept => :json\n\tend\nend", "def buyTickets\n nt1 = Integer(params[:nt1])\n nt2 = Integer(params[:nt2])\n nt3 = Integer(params[:nt3])\n\n # Checks if the user deserves a free ticket\n promo = (nt1 + nt2 + nt3) >= 10? 1 : 0;\n\n ActiveRecord::Base.transaction do\n # type 1 tickets with promotion\n (nt1 + promo).times do\n Ticket.create(\n ticket_type: 1,\n uuid: SecureRandom.uuid,\n user_id: params[:id])\n end\n\n #type 2 tickets\n nt2.times do\n Ticket.create(\n ticket_type: 2,\n uuid: SecureRandom.uuid,\n user_id: params[:id])\n end\n\n #type 3 tickets\n nt3.times do\n Ticket.create(\n ticket_type: 3,\n uuid: SecureRandom.uuid,\n user_id: params[:id])\n end\n end\n\n render json: {\n :status => 0,\n :msg => :ok}\n end", "def test_new_rent\n quote_details = SAMPLE_QUOTE_DETAILS.deep_dup\n quote_details['fixed_price_services_requested']['price'] = 1200\n params_hash = {\n udprn: '123456',\n services_required: SAMPLE_SERVICES_REQUIRED,\n payment_terms: SAMPLE_PAYMENT_TERMS,\n quote_details: quote_details.to_json\n }\n first_params_hash = params_hash.deep_dup\n first_params_hash[:quote_details] = SAMPLE_QUOTE_DETAILS.to_json\n post :new_quote_for_property, first_params_hash\n prev_quote_count = Agents::Branches::AssignedAgents::Quote.count\n post :new, params_hash\n assert_response 200\n assert_equal Agents::Branches::AssignedAgents::Quote.count, (prev_quote_count + 1)\n end", "def create\n @equipo_torneos = EquiposTorneos.new(equipos_torneos_params)\n \n if @equipo_torneos.save\n \n else\n render json: @equipo_torneos.errors, status: :unprocessable_entity\n end\n end", "def tx_royalty_params\n params.require(:tx_royalty).permit(:quarter, :start_date, :end_date, :sent_date, :sold, :cost, :percentage, :sent, :extra_i, :extra_b, :extra_s, :sales_report)\n end", "def create\n @tyre = Tyre.new(tyre_params)\n respond_to do |format|\n if @tyre.save\n format.html { redirect_to (:back), notice: 'Treno pneumatici inserito.' }\n format.json { render json: @tyre, status: :created, location: @tyre, content_type: 'text/json' }\n else\n format.html { render action: 'new' }\n format.json { render json: @tyre.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @notadedebito = Notadedebito.find(params[:notadedebito_id])\n @renglon_notadebito = @notadedebito.renglon_notadebitos.create(params[:renglon_notadebito])\n\n respond_to do |format|\n if @renglon_notadebito.save\n format.html { redirect_to @notadebito, notice: 'Renglon notadebito was successfully created.' }\n format.json { render json: @renglon_notadebito}\n else\n format.html { render action: \"new\" }\n format.json { render json: @renglon_notadebito.errors}\n end\n end\n end", "def create\n @tyre = Tyre.new(tyre_params)\n respond_to do |format|\n if @tyre.save\n format.html { redirect_to @tyre, notice: 'Tyre was successfully created.' }\n format.json { render :show, status: :created, location: @tyre }\n else\n format.html { render :new }\n format.json { render json: @tyre.errors, status: :unprocessable_entity }\n end\n end\n end", "def tx_params\n params.require(:tx).permit(:txhash, :txdata)\n end", "def add_tenant_circle(args = {}) \n post(\"/tenantcircles.json/\", args)\nend", "def test_create_transaction\n params = {\n bank_transaction: {\n bank_account_id: 1,\n date: Time.local(2012, 4, 16),\n amount: 55\n }\n }\n\n post '/api/banks/1/transactions', params\n data = ActiveSupport::JSON.decode last_response.body\n\n assert last_response.successful?\n assert_match('application/json', last_response.content_type)\n assert BankTransaction.find(data['id'])\n end", "def create\n\n if request.request_parameters.nil? || request.request_parameters[:hash].nil?\n render json: {:status => 'missing hash'}, status: :bad_request\n return\n end\n\n #remove hash from post params\n post_params = request.request_parameters\n post_params.delete('hash')\n\n logger.debug \"HASH_BASE: \" + post_params.to_param\n logger.debug \"BASE HASHED: \" + Digest::SHA1.hexdigest(post_params.to_param)\n logger.debug \"HASH VALUE: \" + params[:hash]\n\n #if Digest::MD5.hexdigest(post_params.to_param) != params[:hash]\n # render json: {:status => 'wrong hash'}, status: :forbidden\n # return\n #end\n\n # create shop transaction\n #@shop_special_offers_transaction = Shop::SpecialOffersTransaction.new\n\n special_offer = Shop::SpecialOffer.find_by_external_offer_id(params[:offerID])\n if special_offer.nil? # there is no special offer for this id, callback was sent based on a regular credit offer\n render json: {:status => 'regular offer processed'}, status: :created\n return\n end\n\n character = Fundamental::Character.find_by_identifier(params[:partnerUserID])\n if character.nil?\n render json: {:status => 'character not found'}, status: :not_found\n return\n end\n\n ActiveRecord::Base.transaction(:requires_new => true) do\n\n @shop_special_offers_transaction = Shop::SpecialOffersTransaction.find_or_create_by_character_id_and_external_offer_id(character.id, special_offer.external_offer_id)\n @shop_special_offers_transaction.lock!\n\n if !@shop_special_offers_transaction.paid?\n @shop_special_offers_transaction.state = Shop::Transaction::STATE_PAID\n @shop_special_offers_transaction.paid_at = Time.now\n end\n\n # create shop_transaction event\n unless @shop_special_offers_transaction.save\n render json: @shop_special_offers_transaction.errors, status: :unprocessable_entity\n return\n end\n\n # create unredeemed purchase if not exists\n if @shop_special_offers_transaction.purchase.nil?\n @shop_purchase = @shop_special_offers_transaction.create_purchase({\n character_id: character.id,\n external_offer_id: special_offer.external_offer_id,\n })\n end\n end\n\n # answer with 201\n render json: {:status => 'created'}, status: :created\n end", "def create\n @royalty_detail = RoyaltyDetail.new(royalty_detail_params)\n\n respond_to do |format|\n if @royalty_detail.save\n format.html { redirect_to @royalty_detail, notice: 'Royalty detail was successfully created.' }\n format.json { render :show, status: :created, location: @royalty_detail }\n else\n format.html { render :new }\n format.json { render json: @royalty_detail.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tyre = Tyre.new(tyre_params)\n\n respond_to do |format|\n if @tyre.save\n format.html { redirect_to @tyre, notice: 'Tyre was successfully created.' }\n format.json { render :show, status: :created, location: @tyre }\n else\n format.html { render :new }\n format.json { render json: @tyre.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tx_royalty.update(tx_royalty_params)\n format.html { redirect_to @tx_royalty, notice: 'Tx royalty was successfully updated.' }\n format.json { render :show, status: :ok, location: @tx_royalty }\n else\n format.html { render :edit }\n format.json { render json: @tx_royalty.errors, status: :unprocessable_entity }\n end\n end\n end", "def enviar_transaccion(trx,idfactura)\n begin\n logger.debug(\"...Inicio enviar transaccion\")\n info = InfoGrupo.where('id_banco= ?',trx['destino']).first\n url = 'http://integra'+info[:numero].to_s+'.ing.puc.cl/api/pagos/recibir/'+trx[0]['_id'].to_s\n #url = 'http://localhost:3000/api/pagos/recibir/'+trx['_id'].to_s\n request = Typhoeus::Request.new(\n url,\n method: :get,\n params:{\n idfactura: idfactura\n },\n headers: { ContentType: \"application/json\"})\n response = request.run\n logger.debug(\"...Fin enviar transaccion\")\n return {:validado => true, :trx => trx}\n rescue => ex\n Applog.debug(ex.message,'enviar_transaccion')\n return {:validado => false, :trx => trx}\nend\nend", "def generate_json\n @array = []\n Rental.all.each do |rental|\n @actions = []\n Action.all.each do |action|\n action.rental_id = rental.id\n @actions.push(who: action.who, type: action.type, amount: action.amount)\n end\n @array.push(\n id: rental.id,\n actions: @actions\n )\n end\n JSON.pretty_generate(rentals: @array)\nend", "def create\n @tutorial = current_user.tutorials.create(tutorial_params) \n @tutorial.transactions.create(user_id: @tutorial.user_id, amount: params[:amount], currency: \"USD\", status: \"pending\")\n # base_url = (Rails.env == \"development\") ? 'http://localhost:3000' : 'http://www.etcty.com'\n\n # @response = EXPRESS_GATEWAY.setup_purchase((params[:amount].to_i*100),\n # return_url: base_url+complete_order_tutorial_path(@tutorial, locale: I18n.locale) ,\n # cancel_return_url: base_url,\n # currency: \"USD\"\n # )\n\n # redirect_to EXPRESS_GATEWAY.redirect_url_for(@response.token)\n redirect_to complete_order_tutorial_path(@tutorial, locale: I18n.locale)\n end", "def create\n @tenure = Tenure.new(tenure_params)\n\n if @tenure.save\n audit(@tenure, current_user)\n render json: @tenure, status: :created\n else\n render json: @tenure.errors, status: :unprocessable_entity\n end\n end", "def create\n @torneo = Torneo.new(params[:torneo])\n\n respond_to do |format|\n if @torneo.save\n format.html { redirect_to @torneo, notice: 'Torneo was successfully created.' }\n format.json { render json: @torneo, status: :created, location: @torneo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @torneo.errors, status: :unprocessable_entity }\n end\n end\n end", "def user_transactions\n user_deposits = get_user_deposits\n user_withdrawals = get_user_withdrawals\n json_response({:user_transactions => @user_transactions, :user_deposits => user_deposits, :user_withdrawals => user_withdrawals})\n end", "def push_transactions\n AirdropMint.push_transactions_for_pending_rewards(user)\n end", "def create\n @ntransaction = Ntransaction.new(ntransaction_params)\n\n respond_to do |format|\n if @ntransaction.save\n format.html { redirect_to @ntransaction, notice: 'Ntransaction was successfully created.' }\n format.json { render :show, status: :created, location: @ntransaction }\n else\n format.html { render :new }\n format.json { render json: @ntransaction.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_gen1_account(name) \n\n account_create = {\n \"location\"=> \"centralus\",\n \"tags\"=> {\n \"test_key\"=> \"test_value\"\n },\n \"identity\"=> {\n \"type\"=> \"SystemAssigned\"\n },\n \"properties\"=> {\n \"encryptionState\"=> \"Enabled\",\n \"encryptionConfig\"=> {\n \"type\"=> \"ServiceManaged\",\n },\n \"firewallState\"=> \"Disabled\",\n \"firewallRules\"=> [\n \n ],\n \"trustedIdProviderState\"=> \"Disabled\",\n \"trustedIdProviders\"=> [\n \n ],\n \n \"newTier\"=> \"Consumption\",\n \"firewallAllowAzureIps\"=> \"Enabled\"\n }\n }\n\n response = HTTParty.put(\"https://management.azure.com/subscriptions/#{subscriptionId}/resourceGroups/#{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/#{name}?api-version=2016-11-01\", {\n\n body: account_create.to_json,\n\n headers: {\n \"Authorization\" => \"Bearer #{bearerToken}\",\n \"Content-Type\" => 'application/json', \n \"Accept\" => '*/*',\n \"Cache-Control\" => 'no-cache',\n \"Connection\" => 'keep-alive',\n \"cache-control\" => 'no-cache'\n },\n \n verify: true,\n })\n\n return JSON.parse response.read_body\n end", "def postTransaction(useridgiving, useridreceiving, amount)\n parameters={useridgiving: useridgiving.to_i, useridreceiving: useridreceiving.to_i, amount: amount.to_f, state: \"initial\"}\n options = {\n :body => parameters.to_json,\n :headers => {\n 'Content-Type' => 'application/json'\n }\n }\n results = HTTParty.post(\"http://192.168.99.101:4050/transactions\", options) # create initial state\n return results\n end" ]
[ "0.54714036", "0.54399854", "0.5437694", "0.5325699", "0.52982235", "0.5285133", "0.52319324", "0.5192158", "0.51804006", "0.517087", "0.5062961", "0.5050815", "0.50407493", "0.5037304", "0.5034825", "0.5026073", "0.502575", "0.5019938", "0.50164884", "0.5010504", "0.4964461", "0.4954883", "0.49469092", "0.49358845", "0.492991", "0.48990422", "0.4897281", "0.48961392", "0.48886532", "0.48805642" ]
0.6244218
0
PATCH/PUT /tx_royalties/1 PATCH/PUT /tx_royalties/1.json
def update respond_to do |format| if @tx_royalty.update(tx_royalty_params) format.html { redirect_to @tx_royalty, notice: 'Tx royalty was successfully updated.' } format.json { render :show, status: :ok, location: @tx_royalty } else format.html { render :edit } format.json { render json: @tx_royalty.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update\n keystone.update_tenant({:id=>params[:id],:name=>params[:name],:description=>params[:description],:enabled=>params[:enabled]})\n respond_to do |format|\n format.html { redirect_to tenants_path, :notice => 'Tenant was successfully updated.' }\n format.json { head :ok }\n end\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def jsonapi_update!(attributes)\n assign_jsonapi_attributes(attributes)\n save!\n end", "def update\n respond_to do |format|\n if @tx.update(tx_params)\n format.html { redirect_to @tx, notice: 'Tx was successfully updated.' }\n format.json { render :show, status: :ok, location: @tx }\n else\n format.html { render :edit }\n format.json { render json: @tx.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tyre.update(tyre_params)\n format.html { redirect_to @tyre, notice: 'Tyre was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @tyre.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tyre.update(tyre_params)\n format.html { redirect_to @tyre, notice: 'Tyre was successfully updated.' }\n format.json { render :show, status: :ok, location: @tyre }\n else\n format.html { render :edit }\n format.json { render json: @tyre.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tyre.update(tyre_params)\n format.html { redirect_to @tyre, notice: 'Tyre was successfully updated.' }\n format.json { render :show, status: :ok, location: @tyre }\n else\n format.html { render :edit }\n format.json { render json: @tyre.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @taxinomy = Taxinomy.find(params[:id])\n\n respond_to do |format|\n if @taxinomy.update_attributes(params[:taxinomy])\n format.html { redirect_to @taxinomy, notice: 'Taxinomy was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @taxinomy.errors, status: :unprocessable_entity }\n end\n end\n end", "def UpdateTicket params = {}\n \n APICall(path: 'tickets.json',method: 'PUT',payload: params.to_json)\n \n end", "def update\n @tgl_row = TglRow.find(params[:id])\n\n respond_to do |format|\n if @tgl_row.update_attributes(params[:tgl_row])\n format.html { redirect_to @tgl_row, notice: 'Tgl row was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @tgl_row.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tottle.update(tottle_params)\n format.html { redirect_to @tottle, notice: 'Tottle was successfully updated.' }\n format.json { render :show, status: :ok, location: @tottle }\n else\n format.html { render :edit }\n format.json { render json: @tottle.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @table = Table.find(params[:id])\n\n respond_to do |format|\n if @table.update_attributes(params[:table].permit(:name, :notes, :x, :y, :table_type, :guest_ids => []))\n format.html { redirect_to @table, notice: 'Table was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @table.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @trophy.update(trophy_params)\n format.html { redirect_to @trophy, notice: 'Trophy was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @trophy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @royalty_detail.update(royalty_detail_params)\n format.html { redirect_to @royalty_detail, notice: 'Royalty detail was successfully updated.' }\n format.json { render :show, status: :ok, location: @royalty_detail }\n else\n format.html { render :edit }\n format.json { render json: @royalty_detail.errors, status: :unprocessable_entity }\n end\n end\n end", "def test_update\n #Again the delete feature from ActiveResource does not work out of the box.\n #Using custom delete function\n puts \"--create a new account--\"\n new_acct = Salesforce::Rest::Account.new(:Name => \"test numero uno\", :BillingStreet=> \"Fairway Meadows\",\n :BillingState => \"NY\", :ShippingCity => \"New York\")\n resp = new_acct.save()\n\n assert (resp.code == 201)\n j = ActiveSupport::JSON\n @sf_oid = j.decode(resp.body)[\"id\"]\n puts \"New Object created: id -> \" + @sf_oid\n\n puts \"--update that new account--\"\n serialized_json = '{\"BillingState\":\"WA\"}'\n #http = Net::HTTP.new(@rest_svr_url, 443)\n http = Net::HTTP.new('na7.salesforce.com', 443)\n http.use_ssl = true\n \n class_name = \"Account\"\n path = \"/services/data/v21.0/sobjects/#{class_name}/#{@sf_oid}\"\n headers = {\n 'Authorization' => \"OAuth \"+ @oauth_token,\n \"content-Type\" => 'application/json',\n }\n code = serialized_json\n\n \n req = Net::HTTPGenericRequest.new(\"PATCH\", true, true, path, headers)\n\n resp = http.request(req, code) { |response| }\n assert !resp.nil?\n\n puts resp.to_s\n end", "def update\n @trenton = Trenton.first\n\n respond_to do |format|\n if @trenton.update_attributes(params[:trenton])\n format.html { redirect_to about_path, notice: 'Page was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @trenton.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @specialty = Specialty.find(params[:id])\n\n if @specialty.update(specialty_params)\n head :no_content\n else\n render json: @specialty.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @ty.update(ty_params)\n format.html { redirect_to @ty, notice: 'Tie was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ty.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Company.update(params[\"id\"], params[\"company\"])\n end", "def update_tenant_maintenance_window(args = {}) \n id = args['id']\n temp_path = \"/tenants.json/maintenance/{tenantId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"tenantId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def patch!\n request! :patch\n end", "def update\n @kitty = Kitty.find(params[:id])\n\n respond_to do |format|\n if @kitty.update_attributes(params[:kitty])\n format.html { redirect_to @kitty, notice: 'Kitty was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @kitty.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company_royalty_detail.update(company_royalty_detail_params)\n format.html { redirect_to @company_royalty_detail, notice: 'Company royalty detail was successfully updated.' }\n format.json { render :show, status: :ok, location: @company_royalty_detail }\n else\n format.html { render :edit }\n format.json { render json: @company_royalty_detail.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @taxirequest = Taxirequest.find(params[:id])\n\n respond_to do |format|\n if @taxirequest.update_attributes(params[:taxirequest])\n format.html { redirect_to @taxirequest, notice: 'Taxirequest was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @taxirequest.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n record = TaxRule.find(params[:id])\n record.update_attributes(params[:record])\n \n respond_to do |format|\n format.html\n format.json {\n render json: {}\n }\n end\n end", "def update\n @transport_subsidy = TransportSubsidy.find(params[:id])\n\n respond_to do |format|\n if @transport_subsidy.update_attributes(params[:transport_subsidy])\n format.html { redirect_to @transport_subsidy, notice: 'Transport subsidy was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @transport_subsidy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @stationeryrequest = Stationeryrequest.find(params[:id])\n #\n @stationeryrequest.hotelsuppliesrequests.each do |hotelsuppliesrequests|\n \n end\n\n respond_to do |format|\n if @stationeryrequest.update_attributes(params[:stationeryrequest])\n format.html { redirect_to @stationeryrequest, notice: 'Stationeryrequest was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stationeryrequest.errors, status: :unprocessable_entity }\n end\n end\n end", "def activo_update\n respond_to do |format|\n activo = params[:laboratorio][:activo]\n id = params[:id]\n Laboratorio.where(id: id).update_all(activo: activo )\n msg = { :status => \"ok\", :message => \"Actualizado!\" }\n format.json { render :json => msg }\n end\n end", "def update\n @supermarket = Supermarket.find(params[:id]) \n respond_to do |format|\n if @supermarket.update(supermarket_params)\n format.json { render json: @supermarket, status: :ok }\n end\n end\n end" ]
[ "0.62943965", "0.60849637", "0.6049723", "0.6012433", "0.60094583", "0.599696", "0.59247404", "0.59247404", "0.5910482", "0.58935946", "0.58715343", "0.58249366", "0.5807028", "0.57657635", "0.57637554", "0.57625145", "0.5741435", "0.57221586", "0.57115334", "0.5698711", "0.5694656", "0.5693336", "0.56892157", "0.56885934", "0.5673038", "0.5656697", "0.56519866", "0.56381327", "0.56351405", "0.5632996" ]
0.65436316
0
DELETE /tx_royalties/1 DELETE /tx_royalties/1.json
def destroy @tx_royalty.destroy respond_to do |format| format.html { redirect_to tx_royalties_url, notice: 'Tx royalty was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @taxinomy = Taxinomy.find(params[:id])\n @taxinomy.destroy\n\n respond_to do |format|\n format.html { redirect_to taxinomies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tx.destroy\n respond_to do |format|\n format.html { redirect_to txes_url, notice: 'Tx was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ty.destroy\n respond_to do |format|\n format.html { redirect_to ties_url }\n format.json { head :no_content }\n end\n end", "def destroy\n record = TaxRule.find(params[:id])\n record.trash\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @tantosha.destroy\n # @tantosha.delete\n respond_to do |format|\n format.html { redirect_to tantoshas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @transaction.destroy\n respond_to do |format|\n format.html { redirect_to txns_url }\n format.json { head :no_content }\n end\n end", "def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end", "def 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 @tangent.destroy\n respond_to do |format|\n format.html { redirect_to tangents_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tramite = Tramite.find(params[:id])\n @tramite.destroy\n\n respond_to do |format|\n format.html { redirect_to tramites_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @kota_stone.destroy\n respond_to do |format|\n format.html { redirect_to kota_stones_url }\n format.json { head :no_content }\n end\n end", "def delete_from_entzumena\n headline = Headline.where({:source_item_type => params[:source_item_type], :source_item_id => params[:source_item_id]}).first\n if headline.destroy\n render :json => true, :status => 200\n else\n render :json => false, :status => :error\n end\n end", "def destroy\n @tx_land_grants_efn.destroy\n respond_to do |format|\n format.html { redirect_to tx_land_grants_efns_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @taxirequest = Taxirequest.find(params[:id])\n @taxirequest.destroy\n\n respond_to do |format|\n format.html { redirect_to taxirequests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tyre.destroy\n respond_to do |format|\n format.html { redirect_to tyres_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @annex = Annex.find(params[:id])\n @annex.destroy\n\n respond_to do |format|\n format.html { redirect_to annexes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tgl_row = TglRow.find(params[:id])\n @tgl_row.destroy\n\n respond_to do |format|\n format.html { redirect_to tgl_rows_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @trx_detail = TrxDetail.find(params[:id])\n @trx_detail.destroy\n\n respond_to do |format|\n format.html { redirect_to trx_details_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tenacity.destroy\n respond_to do |format|\n format.html { redirect_to tenacities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @taxi = Taxi.find(params[:id])\n @taxi.destroy\n\n respond_to do |format|\n format.html { redirect_to taxis_url }\n format.json { head :ok }\n end\n end", "def destroy\n @tx = Tx.find(params[:id])\n @tx.destroy\n\n respond_to do |format|\n format.html { redirect_to(txes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @uriy.destroy\n respond_to do |format|\n format.html { redirect_to uriys_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @settlement = Settlement.find(params[:id])\n @settlement.destroy\n\n respond_to do |format|\n format.html { redirect_to settlements_url }\n format.json { head :ok }\n end\n end", "def destroy\n @treq = Treq.find(params[:id])\n @treq.destroy\n\n respond_to do |format|\n format.html { redirect_to treqs_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Alien.delete(params[\"id\"])\n end", "def destroy\n @tyre.destroy\n respond_to do |format|\n format.html { redirect_to tyres_url, notice: 'Tyre was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @tyre.destroy\n respond_to do |format|\n format.html { redirect_to tyres_url, notice: 'Tyre was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @client_transaction = ClientTransaction.find(params[:id])\n @client_transaction.destroy\n\n respond_to do |format|\n format.html { redirect_to client_transactions_url }\n format.json { head :ok }\n end\n end" ]
[ "0.69922584", "0.67290103", "0.6700421", "0.6593997", "0.6592825", "0.6568502", "0.6514311", "0.65118545", "0.64996123", "0.64974964", "0.6488371", "0.6486171", "0.64776325", "0.6474538", "0.64739525", "0.6469212", "0.6465902", "0.64630824", "0.6461225", "0.6441688", "0.64366096", "0.6430274", "0.6420032", "0.6386318", "0.63676625", "0.6324627", "0.63243127", "0.63192064", "0.63192064", "0.629762" ]
0.7028019
0
Given a grade_hash and assignment number, return the average score for that assignment. Note that Ruby counts arrays from 0, but we are referring to them as 110.
def assignment_average_score(grade_hash, assignment_num) assignment = grade_hash.map do |key, value| value[assignment_num - 1] end sum = assignment.reduce do |sum, x| sum += x end sum / assignment.length end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def assignment_average_score(grade_hash, assignment_num)\n a = []\n grade_hash.values.each { |dude| a.push(dude[assignment_num - 1]) }\n sum = a.sum\n average = sum/a.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n assignment_score = grade_hash.map do |key, value|\n value [assignment_num - 1]\n end\n total = assignment_score.reduce do |total, grade|\n total += grade\n end\n total / assignment_score.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n assignment = grade_hash.map {|x| x[1][assignment_num-1]}\n average = assignment.reduce{|x,n| x += n}/assignment.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n sum = 0\n grade_hash.each do |key, value|\n sum += grade_hash[key][assignment_num - 1]\n end\n average = sum / grade_hash.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n grade_hash\n .map {|key, value| value[assignment_num - 1]}\n .reduce(:+) / grade_hash.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n grade_hash\n .map { |key, value| value[assignment_num -1] }\n .reduce(:+) / grade_hash.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n marks = assignment_scores(grade_hash, assignment_num)\n marks.sum / marks.length\nend", "def assignment_average_score(grade_hash, assignment_score)\n sum = 0\n grade_hash.each do |key, value|\n sum += value[assignment_score - 1]\n end\n average = sum / grade_hash.keys.length\n average\nend", "def assignment_average_score(grade_hash, assignment_num)\n sum, n = 0, 0\n grade_hash.each do |k,v|\n n += 1\n sum += v[assignment_num-1]\n end\n return sum/n\nend", "def assignment_average_score(grade_hash, assignment_num)\n (grade_hash.values.transpose[assignment_num - 1].reduce { |acc, num| acc + num }.to_f / 10).floor\nend", "def assignment_average_score(data, assignment)\n all_scores = data.values.map do |scores|\n scores[assignment - 1]\n end\n (all_scores.sum)/(all_scores.length)\nend", "def average_assignment_score\n assignment_average_scores.inject(:+).to_f/num_assignments\n rescue ZeroDivisionError\n 0\n end", "def assignment_score(grade_hash, student, assignment_num)\n score = grade_hash[student][assignment_num - 1]\nend", "def assignment_score(grade_hash, student, assignment_num)\n grade_hash[student][assignment_num - 1]\nend", "def assignment_score(grade_hash, student, assignment_num)\n grade_hash[student][assignment_num - 1]\nend", "def assignment_score(grade_hash, student, assignment_num)\n grade_hash[student][assignment_num - 1]\nend", "def assignment_score(grade_hash, student, assignment_num)\n grade_hash[student][assignment_num - 1]\nend", "def assignment_score(grade_hash, student, assignment_num)\n grade_hash[student][assignment_num - 1]\nend", "def assignment_scores(grade_hash, assignment_num)\n grade_hash.map {|key, value| value[assignment_num - 1]}\nend", "def assignment_scores(grade_hash, assignment_num)\n a = []\n grade_hash.values.each { |name| a.push(name[assignment_num - 1]) }\n a\nend", "def get_average assignment_num\n assignment = Assignment.find_by(number: assignment_num)\n actual_attachments = assignment.corrections\n\n if assignment.finished_mandatory_stages?\n average = 0\n size = 0\n actual_attachments.each do |a|\n if (a.score != -1) \n average += a.score\n size += 1\n end\n end\n\n average = (average/size).round(2)\n return average\n end\n end", "def assignment_score(grade_hash, name, assignment_number)\n grade_hash[name][assignment_number - 1]\nend", "def assignment_scores(grade_hash, assignment_num)\n grade_hash.map do |key, value|\n grade_hash[key][assignment_num - 1]\n end\nend", "def assignment_score(grade_hash, student, assignment_num)\n return grade_hash[student][assignment_num-1]\nend", "def assignment_scores(grade_hash, assignment_num)\n grade_hash.map do |key, value|\n value[assignment_num - 1]\n end\nend", "def assignment_scores(grade_hash, assignment_num)\n grade_hash.map do | key, value |\n value[assignment_num - 1]\n end\nend", "def assignment_score(grade_hash, student, assignment_num)\n grade_hash[student][assignment_num-1]\nend", "def assignment_scores(grade_hash, assignment_num)\n grade_hash.map do |key, value|\n value [assignment_num - 1]\n end\nend", "def assignment_scores(grade_hash, assignment_num)\n grade_hash.values.transpose[assignment_num - 1]\nend", "def averages(grade_hash)\n grade_hash.transform_values{|v| v.inject(:+)/v.length}\n # hash = {}\n # grade_hash.map do |name, grades|\n # score = 0\n # grades.each do |grade|\n # score += grade\n # end\n # average = score/grades.length\n # hash[name] = average\n # end\n # hash\n # sum = 0\n # grade_hash.each { |x| sum += x }\n # average = sum/grade_hash.length\nend" ]
[ "0.90744793", "0.9064256", "0.9055889", "0.8990212", "0.89789546", "0.8959268", "0.8909102", "0.8855201", "0.8777874", "0.873241", "0.8277006", "0.78221184", "0.76975167", "0.7590457", "0.7590457", "0.7590457", "0.7590457", "0.7590457", "0.7585181", "0.75823367", "0.7519535", "0.7503891", "0.74788344", "0.7477136", "0.74676967", "0.7462081", "0.7453236", "0.74475414", "0.7427919", "0.7420519" ]
0.9109685
0
Return a hash of students and their average score. TIP: To convert an array like [[:indiana, 90], [:nevada, 80]] to a hash, use .to_h. Also look at Hashtransform_values.
def averages(grade_hash) averages = grade_hash.map do |key, value| total = 1 sum = grade_hash[key].reduce do |sum, grade| total += 1 sum += grade end avg = sum / total [key, avg] end averages.to_h end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def averages(grade_hash)\n student_average_array = grade_hash.map do |key, value|\n average = value.sum / value.length\n [key, average]\n end\n student_average_array.to_h\nend", "def class_average(grade_hash) \n sum = 0\n students = grade_hash.keys.length\n scores = grade_hash.values.length\n total_scores = students * scores\n grade_hash.each do |key, value|\n sum += value.reduce(:+)\n end\n average = sum / total_scores\n average\nend", "def class_average(grade_hash)\n sum = 0\n grade_hash.values.each { |student| student.each {|grades| sum += grades }}\n average = sum/(grade_hash.length**2)\nend", "def averages(grade_hash)\n grade_hash.transform_values{|v| v.inject(:+)/v.length}\n # hash = {}\n # grade_hash.map do |name, grades|\n # score = 0\n # grades.each do |grade|\n # score += grade\n # end\n # average = score/grades.length\n # hash[name] = average\n # end\n # hash\n # sum = 0\n # grade_hash.each { |x| sum += x }\n # average = sum/grade_hash.length\nend", "def averages(grade_hash)\n grade_hash\n .transform_values { |scores| scores.reduce(:+) / scores.length }\nend", "def averages(grade_hash)\n grade_hash.transform_values { |marks| marks.inject {|sum, n| sum + n } / marks.length }\nend", "def averages(grade_hash)\n grade_hash.transform_values{|nums| nums.reduce(:+) / nums.size}\nend", "def show\n @students = Student.joins(:subjects)\n .select('students.name, students.email, students.age, students.gender, students.opinion, subjects.id as subject_id')\n .select('exam_results.name as exam_result_name, subjects.name as subject_name, exam_results.score')\n .select('CAST((exam_results.score / subjects.max_score) * 100 as int) as ratio')\n .where(id: params[:id])\n .order(id: :asc)\n\n avg_result = Student.joins(:subjects)\n .select('subjects.id as subject_id')\n .select('CAST(AVG(exam_results.score) as int) as avg_score') \n .select('MAX(exam_results.score) as max_score')\n .select('MIN(exam_results.score) as min_score')\n .group('subjects.id')\n .order('subjects.id')\n @score_hash = {}\n avg_result.each do |avg_res|\n h = Hash.new\n h[:avg_score] = avg_res.avg_score\n h[:max_score] = avg_res.max_score\n h[:min_score] = avg_res.min_score \n @score_hash[avg_res.subject_id] = h\n end\n end", "def score\n return nil if scores.count == 0\n average = Hash.new(0)\n scores.each_with_index do |score, num|\n Score::METRICS.each do |metric|\n average[metric] = (average[metric] * num + score.try(metric))/(num + 1.0)\n end\n end\n ret = {score: average}\n return JSON.generate ret\n end", "def averages(grade_hash)\n grade_hash.transform_values{ |num| num.reduce(:+) / num.length }\nend", "def class_average(grade_hash)\n averages = averages(grade_hash)\n sum = 0\n\n averages.map do |key, value|\n sum += value\n end\n\n sum / averages.length\nend", "def class_average(grade_hash)\n class_array = grade_hash.map do |k,v|\n averages v\n end\n averages class_array\nend", "def class_average(grade_hash)\n averages(grade_hash)\n .map {|key, value| value}\n .reduce(:+) / grade_hash.length\nend", "def averages(grade_hash)\n grade_hash.transform_values {|nums| nums.reduce(:+)/nums.size}\nend", "def get_average\n record_hash = {}\n record_hash['avg_cat1'] = course_ratings.average(:cat1) || 0\n record_hash['avg_cat2'] = course_ratings.average(:cat2) || 0\n record_hash['avg_cat3'] = course_ratings.average(:cat3) || 0\n record_hash['avg_cat4'] = course_ratings.average(:cat4) || 0\n record_hash['avg_cat5'] = course_ratings.average(:cat5) || 0\n record_hash['total_reviews'] = course_ratings.length\n return record_hash\n end", "def class_average(grade_hash)\n sum, n = 0, 0\n grade_hash.each do |k,array|\n array.each do |grade|\n n += 1\n sum += grade\n end\n end\n return sum/n\nend", "def class_average(grade_hash)\n scores = averages(grade_hash)\n result = 0\n scores.each {|k,v| result += v}\n result /= scores.length\nend", "def class_average(grade_hash)\n averages(grade_hash).map { |key, value| value }\n .reduce(:+) / grade_hash.length\nend", "def class_average(grade_hash)\n averages(grade_hash).values.reduce(:+) / grade_hash.length\nend", "def top_students(grade_hash, number_of_students)\n # Loop through hash\n top_students_array = grade_hash.map do |key, value|\n # find average for each student\n average = value.sum / value.length\n # put into array of key, score\n [key, average]\n end\n puts top_students_array\n # turn into hash\n top_students_hash = top_students_array.to_h\n # sort hash\n top_students_sorted = top_students_hash.sort_by do |a, b| \n -b\n end\n # map keys\n sorted_student_array = top_students_sorted.map do |key, value|\n key\n end\n # return top student names in array\n result = sorted_student_array.take(number_of_students)\n result\nend", "def class_average(grade_hash)\n averages(grade_hash).map{|k, v| v}.inject {|sum, n| sum + n } / grade_hash.length\nend", "def max_min_avg(arr)\n hash = {'max': arr.max, 'min': arr.min}\n sum = 0\n for i in arr\n sum += i\n end\n hash['avg'] = sum / arr.length\n return hash\nend", "def assignment_average_score(grade_hash, assignment_score)\n sum = 0\n grade_hash.each do |key, value|\n sum += value[assignment_score - 1]\n end\n average = sum / grade_hash.keys.length\n average\nend", "def average_score\n grades.average(:score) || 0\n end", "def top_students(grade_hash)\n averages(grade_hash)\n .to_a\n .sort_by { |student| -student[1] }\n .map { |student| student[0] }\nend", "def final_letter_grades(grade_hash)\n letter_grade_array = grade_hash.map do |key, value|\n average = value.sum / value.length\n letter_grade = letter_grade(average)\n [key, letter_grade]\n end\n letter_grade_array.to_h\nend", "def assignment_average_score(grade_hash, assignment_num)\n marks = assignment_scores(grade_hash, assignment_num)\n marks.sum / marks.length\nend", "def average_score\n return nil if metrics.empty?\n totals = grades.includes(:subject).group_by(&:subject).map { |_, grades|\n grades.sum(&:weighted_score) }\n return 0 if totals.empty?\n totals.sum.to_f / totals.length\n end", "def assignment_average_score(grade_hash, assignment_num)\n grade_hash\n .map { |key, value| value[assignment_num -1] }\n .reduce(:+) / grade_hash.length\nend", "def get_avggrades(hash)\n sumgrades = 0\n hash[:grades].each do |grade|\n if grade.to_s != 'A'\n sumgrades += grade.to_f\n else\n sumgrades +=1\n end\n end\n sumgrades / hash[:grades].length\nend" ]
[ "0.75408834", "0.6999593", "0.6975018", "0.6857092", "0.67606515", "0.6746337", "0.67069304", "0.6706569", "0.6653787", "0.66253716", "0.6592403", "0.6546863", "0.6479477", "0.64764684", "0.6473728", "0.6455564", "0.6446884", "0.6432308", "0.63847697", "0.6352908", "0.6348777", "0.6347496", "0.6346822", "0.6306684", "0.62991005", "0.6298196", "0.6278536", "0.6275793", "0.6257728", "0.6254255" ]
0.7046247
1
Returns a UserManager object specific to OS X
def get_user_manager() return(Users::OSXUserManager.new()) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_user_manager()\n\t\t\t\treturn(Users::OpenBSDUserManager.new())\n\t\t\tend", "def [](name)\n handle = system.run(:search, \"user\", name, nil, @keyring)\n return nil if handle == -1\n\n system.get(:read, handle)\n end", "def identifier_for(scheme)\n identifiers.by_scheme_name(scheme, 'User')&.first\n end", "def get_user(name)\n file = \"#{@@path_to_user_plists}/#{name}.plist\"\n user = NSMutableDictionary.dictionaryWithContentsOfFile(file)\n end", "def enum_users\n\tos = @client.sys.config.sysinfo['OS']\n\tusers = []\n\tuser = @client.sys.config.getuid\n\tpath4users = \"\"\n\tsysdrv = @client.fs.file.expand_path(\"%SystemDrive%\")\n\n\tif os =~ /7|Vista|2008/\n\t\tpath4users = sysdrv + \"\\\\users\\\\\"\n\t\tprofilepath = \"\\\\AppData\\\\Local\\\\VMware\\\\\"\n\telse\n\t\tpath4users = sysdrv + \"\\\\Documents and Settings\\\\\"\n\t\tprofilepath = \"\\\\Application Data\\\\VMware\\\\\"\n\tend\n\n\tif user == \"NT AUTHORITY\\\\SYSTEM\"\n\t\tprint_status(\"Running as SYSTEM extracting user list..\")\n\t\t@client.fs.dir.foreach(path4users) do |u|\n\t\t\tuserinfo = {}\n\t\t\tnext if u =~ /^(\\.|\\.\\.|All Users|Default|Default User|Public|desktop.ini|LocalService|NetworkService)$/\n\t\t\tuserinfo['username'] = u\n\t\t\tuserinfo['userappdata'] = path4users + u + profilepath\n\t\t\tusers << userinfo\n\t\tend\n\telse\n\t\tuserinfo = {}\n\t\tuservar = @client.fs.file.expand_path(\"%USERNAME%\")\n\t\tuserinfo['username'] = uservar\n\t\tuserinfo['userappdata'] = path4users + uservar + profilepath\n\t\tusers << userinfo\n\tend\n\treturn users\nend", "def system_user\n # By convention, the first user is always the system user.\n User.find_by_id(1)\n end", "def enum_users(os)\n\tusers = []\n\tuser = @client.sys.config.getuid\n\tpath4users = \"\"\n\tsysdrv = @client.fs.file.expand_path(\"%SystemDrive%\")\n\n\tif os =~ /Windows 7|Vista|2008/\n\t\tpath4users = sysdrv + \"\\\\users\\\\\"\n\t\tpath2purple = \"\\\\AppData\\\\Roaming\\\\\"\n\telse\n\t\tpath4users = sysdrv + \"\\\\Documents and Settings\\\\\"\n\t\tpath2purple = \"\\\\Application Data\\\\\"\n\tend\n\n\tif user == \"NT AUTHORITY\\\\SYSTEM\"\n\t\tprint_status(\"Running as SYSTEM extracting user list..\")\n\t\t@client.fs.dir.foreach(path4users) do |u|\n\t\t\tuserinfo = {}\n\t\t\tnext if u =~ /^(\\.|\\.\\.|All Users|Default|Default User|Public|desktop.ini|LocalService|NetworkService)$/\n\t\t\tuserinfo['username'] = u\n\t\t\tuserinfo['userappdata'] = path4users + u + path2purple\n\t\t\tusers << userinfo\n\t\tend\n\telse\n\t\tuserinfo = {}\n\t\tuservar = @client.fs.file.expand_path(\"%USERNAME%\")\n\t\tuserinfo['username'] = uservar\n\t\tuserinfo['userappdata'] = path4users + uservar + path2purple\n\t\tusers << userinfo\n\tend\n\treturn users\nend", "def user\n @user ||= ENV[\"USER\"].presence || Utils.safe_popen_read(\"/usr/bin/whoami\").chomp\n end", "def user\n @user ||= ENV[\"USER\"].presence || Utils.safe_popen_read(\"/usr/bin/whoami\").chomp\n end", "def user\n @user ||= User.find_by_user_key('system')\n return @user if @user\n @user = User.create!(Devise.authentication_keys.first => 'system')\n end", "def os_user\n @os_user\n end", "def get_brew_user_id\n brew_command_parse_response(\"call getLoggedInUser\")['id']\n end", "def getuid\n\t\trequest = Packet.create_request('stdapi_sys_config_getuid')\n\t\tresponse = client.send_request(request)\n\t\treturn response.get_tlv_value(TLV_TYPE_USER_NAME)\n\tend", "def get_user(name)\n @file = \"/private/var/db/dslocal/nodes//#{resource[:dslocal_node]}/users/#{name}.plist\"\n NSMutableDictionary.dictionaryWithContentsOfFile(@file)\n end", "def manager\n users(:jolly)\n end", "def user(user_name)\n OctocatHerder::User.fetch(user_name, connection)\n end", "def user\n datastore['POP2USER']\n end", "def system_user\n User.find_by_name(\"DanbooruBot\") || User.admins.first\n end", "def user_from_omniauth\n IdentifierScheme.for_users.each do |scheme|\n omniauth_hash = session.fetch(\"devise.#{scheme.name}_data\", {})\n next if omniauth_hash.empty?\n\n return ::User.from_omniauth(scheme_name: scheme.name, omniauth_hash: omniauth_hash)\n end\n nil\n end", "def user_get(name)\n execute(\"id -P #{name}\") do |result|\n fail_test \"failed to get user #{name}\" unless /^#{name}:/.match?(result.stdout)\n\n yield result if block_given?\n result\n end\n end", "def manager\n\t\t\treturn nil if @entry.manager.nil?\n\t\t\tUser.find_by_distinguishedName(@entry.manager.to_s)\n\t\tend", "def default_user\n u = User.find_or_create_by_oauth2(default_oauth2_hash)\n create_user_shop(u)\n u\n end", "def to_app_user\n raise MissingUIDError unless auth_hash.uid\n Kracken.config.user_class.find_or_create_from_auth_hash(auth_hash)\n end", "def to_app_user\n raise MissingUIDError unless auth_hash.uid\n Kracken.config.user_class.find_or_create_from_auth_hash(auth_hash)\n end", "def get_system_user\n User.where('first_name = ? AND last_name = ?', 'system', 'user').first\n end", "def username\n if @username.nil?\n if os_type(:nice, :not_extended) == 'Solaris'\n @username = @platform.exec(\"/usr/ucb/whoami\").strip\n else\n @username = @platform.exec(\"whoami\").strip\n end\n end\n \n @username\n end", "def create_user\n command = compile_command(\"useradd\") do |useradd|\n useradd << universal_options\n useradd << useradd_options\n end\n\n run_command(:command => command)\n\n # SmartOS locks new users by default until password is set\n # unlock the account by default because password is set by chef\n if check_lock\n unlock_user\n end\n end", "def unix_uid; end", "def user\n return ENV['USER']\n end", "def identifier_for(scheme)\n user_identifiers.where(identifier_scheme: scheme).first\n end" ]
[ "0.7198863", "0.60888714", "0.6008444", "0.5792694", "0.5770028", "0.57068527", "0.5622561", "0.56057274", "0.56057274", "0.5598461", "0.555754", "0.5548709", "0.549404", "0.5439386", "0.54292023", "0.5417345", "0.5417284", "0.53819966", "0.5378019", "0.5377998", "0.53777564", "0.5349299", "0.5337736", "0.5337736", "0.53226376", "0.5316259", "0.5300218", "0.5293247", "0.526461", "0.52596813" ]
0.8112664
0
adds a user to the system. If userinfo is a string then it will add the named user with an optional uid. If userinfo is an actual UserInfo object then uid is ignored and everything possible will be used from userinfo (or generated if not supplied)
def add_user(userinfo, password=nil, uid=nil) newuser = UserInfo.new() newuser.username = nil newuser.uid = nil newuser.gid = nil newuser.fullname = nil newuser.shell = nil newuser.homedir = nil if(userinfo.respond_to?(:username)) if(userinfo.username == nil) raise(BadUsernameError, "No username given") end newuser.username = userinfo.username newuser.uid = userinfo.uid newuser.gid = userinfo.gid newuser.fullname = userinfo.fullname newuser.shell = userinfo.shell newuser.homedir = userinfo.homedir else newuser.username = userinfo.to_s() newuser.uid = uid end Cfruby.controller.attempt("Adding user \"#{newuser.username}\"", 'destructive') { if(newuser.uid == nil) lastuid = `/usr/bin/nidump passwd . | /usr/bin/cut -d: -f3 | /usr/bin/sort -n | /usr/bin/tail -n 1` newuser.uid = lastuid.to_i() + 1 if(newuser.uid == 0) raise(AddUserError, "Error generating new uid") end end if(newuser.gid == nil) newuser.gid = newuser.uid end `/usr/bin/niutil -create . /users/#{newuser.username}` `/usr/bin/niutil -createprop . /users/#{newuser.username} passwd` `/usr/bin/niutil -createprop . /users/#{newuser.username} gid #{newuser.gid.to_i()}` `/usr/bin/niutil -createprop . /users/#{newuser.username} uid #{newuser.uid.to_i()}` `/usr/bin/niutil -createprop . /users/#{newuser.username} shell #{newuser.shell.to_s()}` `/usr/bin/niutil -createprop . /users/#{newuser.username} home "#{newuser.homedir.to_s()}"` `/usr/bin/niutil -createprop . /users/#{newuser.username} realname "#{newuser.fullname.to_s()}"` `/usr/bin/niutil -createprop . /users/#{newuser.username} _shadow_passwd` # make the home directory if(newuser.homedir != nil and !File.exist?(newuser.homedir.to_s())) FileUtils.mkdir_p(newuser.homedir.to_s()) end # set the password if(password != nil) set_password(newuser.username, password) end } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def user_add argv = {}\n\t\tfkv\t\t\t= {}\n\t\tfkv[:name]\t= argv[:name]\n\t\tfkv[:level]\t= argv[:level]\n\t\tfkv[:tag]\t= argv[:tag] if argv[:tag]\n\n\t\t# if the username is existed\n\t\t_throw Sl[:'the user is existed'] if user_has? fkv[:name]\n\n\t\t# password\n\t\trequire \"digest/sha1\"\n\t\tfkv[:salt] \t= _random 5\n\t\tfkv[:pawd] \t= Digest::SHA1.hexdigest(argv[:pawd] + fkv[:salt])\n\n# \t\tSdb[:user].insert(f)\n\t\tdata_submit :user_info, :fkv => fkv, :uniq => true\n\n\t\tuid = Sdb[:user_info].filter(:name => fkv[:name]).get(:uid)\n\t\tuid ? uid : 0\n\tend", "def _user_add argv = {}\n\t\tf\t\t\t\t= {}\n\t\tf[:tag]\t\t\t= argv[:tag] if argv.include?(:tag)\n\t\tf[:salt] \t\t= _random 5\n\n\t\t#username\n\t\t_throw Sl[:'the user is existing'] if _user? f[:name]\n\t\tf[:name] \t\t= argv[:name]\n\n\t\t#password\n\t\trequire \"digest/sha1\"\n\t\tf[:pawd] \t\t= Digest::SHA1.hexdigest(argv[:pawd] + f[:salt])\n\n# \t\tSdb[:user].insert(f)\n\t\t_submit :_user, :fkv => f, :uniq => true\n\t\tuid = Sdb[:_user].filter(:name => f[:name]).get(:uid)\n\t\tuid ? uid : 0\n\tend", "def _user_add f = {}\n\t\tf[:salt] \t\t= _random_string 5\n\t\tf[:created] \t= Time.now\n\n\t\trequire \"digest/sha1\"\n\t\tf[:pawd] \t\t= Digest::SHA1.hexdigest(f[:pawd] + f[:salt])\n\n\t\t_throw L[:'the user is existing'] if _user? f[:name]\n\n\t\tDB[:_user].insert(f)\n\t\tuid = DB[:_user].filter(:name => f[:name]).get(:uid)\n\t\tuid ? uid : 0\n\tend", "def add_user(name)\n\t@users << {:name => name}\n end", "def add_user(api_level, username, password, type, pin = nil, options = nil)\n payload = { username: username, password: password, type: type }\n\n payload[:pin] = pin if pin\n payload[:options] = options.is_a?(Hash) ? JSON.generate(options) : options if options\n\n res = Connection.post(api_level, payload)\n User.build(res, api_level)\n end", "def add_user(name, value)\n self.class.post(\"/users/#{name}\",\n body: value,\n headers: {\n 'Content-Type' => 'application/json; charset=UTF-8',\n Connection: 'keep-alive',\n Accept: 'application/json, text/plain, */*'\n })\n end", "def add_user(user)\n @users[user.name] = user\n end", "def add_user(user) # rubocop:disable Metrics/AbcSize\n cmd_args = [\"'#{user.name}'\"]\n cmd_args.unshift \"--home '#{user.homedir}'\" if user.homedir\n if user.shell\n cmd_args.unshift \"--shell '#{user.shell}'\"\n elsif user.is_system\n cmd_args.unshift \"--shell '/usr/sbin/nologin'\"\n end\n cmd_args.unshift \"--gid '#{user.group}'\" if user.group\n cmd_args.unshift '--system' if user.is_system\n\n # Collapse the cmd_args array into a string that can be used\n # as an argument to `useradd`\n useradd_args = cmd_args.join \"\\s\"\n\n # Collapse the cmd_args array into a string that can be used\n # as an argument to `usermod`; If this is a system account,\n # then specify it as such for user addition only (strip\n # --system from usermod_args)\n usermod_args = (cmd_args - [\"--system\"]).join \"\\s\"\n\n return <<-HERE.undent\n if getent passwd '#{user.name}' > /dev/null 2>&1; then\n /usr/sbin/usermod #{usermod_args}\n else\n /usr/sbin/useradd #{useradd_args}\n fi\n HERE\n end", "def add_user(uid: nil, all: false, params: {})\n raise ArgumentError, 'UID is required' unless uid\n raise ArgumentError, 'Given is required' unless params[:givenname]\n raise ArgumentError, 'Surname is required' unless params[:sn]\n raise ArgumentError, 'Common is required' unless params[:cn]\n\n # Remove empty values from the string\n params.compact!\n\n # We can create a list of params then convert them to hash before passing them to the\n # library. This can be done using value.to_h\n api_post(method: 'user_add', item: uid, params: params)\n end", "def addUser(stat,typ,email,pwhash)\n @conn.exec_prepared(\"add_user\",[stat,typ,email,pwhash])\n end", "def registerUser(name, usernumber)\n # puts (\"adding user\")\n @users.store(name, usernumber)\n end", "def addUser(id, username)\n @conn.exec_prepared(\"insert_user\", [id, username])\n end", "def add_user(username, uid)\n uid = Integer(uid)\n\n %x(sudo useradd -s /bin/bash -u #{uid} -m #{Shellwords.escape(username)})\n\n case $?.exitstatus\n when 0\n home_dir = Shellwords.escape(Etc.getpwnam(username).dir)\n \n #FileUtils.chmod(0771, home_dir)\n %x(sudo chmod 0771 #{home_dir})\n\n RightScale::Log.info \"User #{username} created successfully\"\n else\n raise SystemConflict, \"Failed to create user #{username}\"\n end\n end", "def user_add(username, password,\n config = Hash.new)\n default_config = {\n :add_user => true,\n :password => password,\n :comment => \"\",\n :use_mail => true,\n :use_ftp => false,\n :use_file_sharing => false,\n :mail_quota => 200, # in MB\n :virus_check => false,\n :spam_filter => false\n }\n\n user_setting(username,\n default_config.merge(config))\n end", "def add_user(user_name, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'AddUser'\n\t\targs[:query]['UserName'] = user_name\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :comments\n\t\t\targs[:query]['Comments'] = optional[:comments]\n\t\tend\n\t\tself.run(args)\n\tend", "def sign_up(name:, user_name:)\n user_name = user_name.downcase\n return SYNTAX_ERROR if include_punctuation?(user_name)\n return TOO_LONG_ERROR if too_long?(user_name)\n return TOO_SHORT_ERROR if too_short?(user_name)\n\n @user_class.add(name: name, user_name: user_name)\n end", "def add_user(user)\n self.users.create(id: user.id)\n end", "def add_user(user)\r\n\t\tsend(\"ADC\",\"FL N=#{user.name} F=#{user.safenick}\")\r\n\t\tsend(\"ADC\",\"AL N=#{user.name} F=#{user.safenick}\")\r\n\t\t## XXX changes recorded locally by ADD msg back\r\n\t\treturn 1\r\n\tend", "def add_user(user)\n user_hash[user.nick]=user unless user_hash.has_key?(user.nick)\n end", "def add_user(email, options={})\n raise NotImplementedError, \"Please implement this in your concrete class\"\n end", "def create_user\n command = compile_command(\"useradd\") do |useradd|\n useradd << universal_options\n useradd << useradd_options\n end\n\n run_command(:command => command)\n\n # SmartOS locks new users by default until password is set\n # unlock the account by default because password is set by chef\n if check_lock\n unlock_user\n end\n end", "def add_user(user)\n # NB: system users aren't supported on solaris 10\n # Solaris 10 also doesn't support long flags\n cmd_args = [\"'#{user.name}'\"]\n cmd_args.unshift \"-g '#{user.group}'\" if user.group\n cmd_args.unshift \"-d '#{user.homedir}'\" if user.homedir\n if user.shell\n cmd_args.unshift \"-s '#{user.shell}'\"\n elsif user.is_system\n # Even though system users aren't a thing, we can still disable the shell\n cmd_args.unshift \"-s '/usr/bin/false'\"\n end\n\n user_args = cmd_args.join(\"\\s\")\n\n return <<-HERE.undent\n if getent passwd '#{user.name}' > /dev/null 2>&1; then\n /usr/sbin/usermod #{user_args}\n else\n /usr/sbin/useradd #{user_args}\n fi\n HERE\n end", "def add_user(uid, user_set, provider = \"database\")\n user = ::User.find_by(provider: provider, uid: uid)\n user = create_user(uid, provider) if user.nil?\n user_set << user\n user\n end", "def create_user(user)\n log(\"Creating LDAP user: #{user['first']}\")\n \n params = {\n :first => user['first'],\n :last => user['last'],\n :username => user['username'],\n :uid => find_uid(@config[:userdn], { :low => 10000, :high => 12000 })[:values].to_s,\n :passwd => crypt3(user['password']),\n :lmpasswd => lm_hash(user['password']),\n :ntpasswd => nt_hash(user['password']),\n :time => Time.now.to_i.to_s\n }\n \n new_user = JSON.parse(\n @config[:templates][:user].result(binding),\n :symbolize_names => true\n )\n \n # TBD: wrap the add call\n add(\n {:name => \"localuser\", :ip => \"127.0.0.1\"},\n new_user[:dn],\n new_user[:attributes]\n )\n end", "def add_user(username, params)\n\t\t\t\t@session['datastore'][username] = params\n\t\t\tend", "def add_user(opts)\n opts[:domain] = name\n GoodData::Domain.add_user(opts)\n end", "def create_user(uid, params={})\n params.merge!(default_params)\n params['pio_uid'] = uid\n extract_latlng(params)\n @connection.post(:users, params).body\n end", "def add user, pin = nil\n command = aqhbci <<-CMD\n adduser \\\n --tokentype=#{user.tokentype} \\\n --context=#{user.context} \\\n --bank=#{user.bank} \\\n --user=#{user.userid} \\\n --server=#{user.server} \\\n --username=#{user.name} \\\n --hbciversion=#{user.hbciversion}\n CMD\n stdin, stdout, stderr, wait_thr = Open3.popen3(command.strip)\n success = wait_thr.value.success?\n\n if pin && success\n with_secure_pin user, pin do |f|\n sysid_command = aqhbci(\"getsysid --user=#{user.userid}\", \"--pinfile=#{f.path.strip}\").strip\n stdin, stdout, stderr, wait_thr = Open3.popen3(sysid_command)\n wait_thr.join\n success = success && wait_thr.value.success?\n end\n end\n return success\n end", "def add(user)\n\t\t\tkparams = {}\n\t\t\t# The new user\n\t\t\tclient.add_param(kparams, 'user', user);\n\t\t\tclient.queue_service_action_call('user', 'add', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend", "def add(name, ugid, homedir)\n fail 'user already exists' if include?(name)\n syscmd(\"groupadd -g #{ugid} #{name}\")\n syscmd(\"useradd -u #{ugid} -g #{ugid} -d #{homedir} -c #{COMMENT} #{name}\")\n exclusively { users[name] = ugid }\n end" ]
[ "0.6709862", "0.66529197", "0.65704066", "0.6562995", "0.6540822", "0.6536096", "0.64775956", "0.646284", "0.6413204", "0.62673825", "0.6208891", "0.62046283", "0.6183421", "0.6132607", "0.612488", "0.6114278", "0.60543376", "0.604756", "0.6017779", "0.6005402", "0.6004883", "0.5993273", "0.5976102", "0.5970397", "0.59584147", "0.5922507", "0.5917305", "0.5894634", "0.5892693", "0.5877783" ]
0.7701631
0
deletes a group from the system
def delete_group(group) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete_group(group)\n\t\t\t\tgroupname = nil\n\t\t\t\tif(group.respond_to(:groupname))\n\t\t\t\t\tgroupname = group.groupname\n\t\t\t\telse\n\t\t\t\t\tgroupname = group\n\t\t\t\tend\n\n\t\t\t\t`pw groupdel #{groupname}`\n\t\t\tend", "def remove_group(group)\n self.groups.destroy group \n end", "def delete_group\n @mailing_list_group.destroy if @ok\n render 'update_list'\n end", "def delete_group(group_id)\n\t\tself.group_list.delete(group_id)\n\t\tself.update_attribute(:group_list, self.group_list)\n\tend", "def delete_group(id)\n delete(\"groups/#{id}\")\n end", "def destroy\n @group = GROUP.first_or_get(params[:id])\n @group.current_user = current_user\n @group.destroy if @group\n\n respond_to do |format|\n flash[:notice] = 'Group was successfully deleted.'\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def group_destroy(group)\n if(group.persisted?)\n request(\n :path => \"/groups/#{group.id}\",\n :method => :delete,\n :expects => 204\n )\n true\n else\n false\n end\n end", "def delete_group(uuid)\n Uploadcare::Group.delete(uuid)\n end", "def destroy\n Group.rebuild! if nil.|Group.find(:first).rgt\n\t @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def delete_group\r\n if request.post?\r\n @group=Group.find_by_id(params[:id], :conditions=>['account_id = ?',session[:account_id]])\r\n if @group.nil?\r\n flash[:error] = \"Invalid action.\"\r\n else\r\n flash[:success]= \"Group \" + @group.name + \" was deleted successfully \"\r\n @group.destroy\r\n @group_devices = Device.find(:all, :conditions=>['group_id=?',@group.id])\r\n for device in @group_devices\r\n device.icon_id =\"1\"\r\n device.group_id = nil\r\n device.save\r\n end\r\n end\r\n end\r\n redirect_to :action=>\"groups\"\r\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n redirect_to groups_path\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n redirect_to groups_path\n end", "def remove_group\n create_group.tap do |r|\n r.action(:remove)\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n head :no_content\n end", "def deleteGroup _args\n \"deleteGroup _args;\" \n end", "def perform_destroy\n api.group_destroy(self)\n end", "def remove_group!( group )\n save if remove_group( group )\n end", "def remove_group(group)\r\n\t\tsend('RMG', group.info[:guid])\r\n\t\t## XXX save changes locally?\r\n\t\treturn 1\r\n\tend", "def deleteGroup( group_id)\n params = Hash.new\n params['group_id'] = group_id\n return doCurl(\"delete\",\"/group\",params)\n end", "def delete(group_id)\n if expired?(@begin_time)\n @auth = get_auth(@api_key)\n end\n Log.debug(\"#{@base_url}#{@get_post_delete_url}#{group_id}\")\n user_group = RestClient.delete \"#{@base_url}#{@get_post_delete_url}#{group_id}\", header\n end", "def destroy\n @group.destroy\n\n head :no_content\n end", "def destroy\n Group.delete_groups_and_acls([id])\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_groups_url) }\n format.xml { head :ok }\n end\n end", "def remove_group(name)\n visit 'groups'\n click_link name\n\n page.accept_alert do\n click_button 'group_delete'\n end\n end", "def delete_group(client, options)\n if options[:directory].nil? or options[:group].nil?\n puts \"Missing arguments\"\n return\n end\n\n groups = client.groups\n group = groups.get options[:group]\n group.delete\n puts \"Group deleted.\"\n return\nend", "def destroy\n @current_user.quit_group(@group)\n respond_to do |format|\n format.html { redirect_to groups_path }\n format.json { head :no_content }\n end\n end", "def group_delete(attribs, dir_info)\n attribs = group_record_name_alternatives(attribs)\n\n check_critical_attribute( attribs, :record_name )\n\n command = {action: 'delete', scope: 'Groups', attribute: nil, value: nil}\n user_attrs = attribs.merge(command)\n\n dscl( user_attrs, dir_info )\n end", "def delete(group)\n url = build_url(group)\n response = rest_delete(url)\n response.return!\n end", "def delete_group \n Group.destroy(params[:id])\n\n respond_to do |format|\n format.html {redirect_to dashboard_path}\n end\n end", "def destroy\n @group.destroy\n redirect_to groups_url, notice: \"Group was successfully destroyed.\" \n end" ]
[ "0.81135666", "0.8026677", "0.78762484", "0.785122", "0.7840326", "0.782046", "0.7813519", "0.78107667", "0.78070587", "0.7798556", "0.77900004", "0.77900004", "0.7717208", "0.77116877", "0.7702755", "0.7689944", "0.7679747", "0.76643753", "0.7656285", "0.76086736", "0.7602931", "0.7597023", "0.75968003", "0.7591555", "0.7585153", "0.75813186", "0.75794965", "0.75740016", "0.756574", "0.75606596" ]
0.87497646
1
Returns a PackageList object that contains key value pairs for every installed package where the key is the package name and the value is a PackageInfo object
def installed_packages() installedpackagelist = `#{@finkbin} list -i` installedpackages = PackageList.new() installedpackagelist.each_line() { |line| linearr = line.split() installedpackages[linearr[1]] = PackageInfo.new() installedpackages[linearr[1]].name = linearr[1] installedpackages[linearr[1]].version = linearr[2] installedpackages[linearr[1]].description = linearr[3] installedpackages[linearr[1]].installed = true } return(installedpackages) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def installed_packages()\n\t\t\t\tpackages = PackageList.new()\n\t\t\t\tpackageregex = /^([^ ]+)-([^- ]+)\\s+(.*)$/\n\n\t\t\t\tinstalledpackageslist = `/usr/sbin/pkg_info`\n\t\t\t\tinstalledpackageslist.each_line() { |line|\n\t\t\t\t\tline.strip!()\n\t\t\t\t\tmatch = packageregex.match(line)\n\t\t\t\t\tif(match != nil)\n\t\t\t\t\t\tname = match[1]\n\t\t\t\t\t\tversion = match[2]\n\t\t\t\t\t\tdescription = match[3]\n\n\t\t\t\t\t\tpackages[name] = PackageInfo.new()\n\t\t\t\t\t\tpackages[name].name = name\n\t\t\t\t\t\tpackages[name].version = version\n\t\t\t\t\t\tpackages[name].description = description\n\t\t\t\t\tend\n\t\t\t\t}\n\n\t\t\t\treturn(packages)\n\t\t\tend", "def packages()\n\t\t\t\tpackages = installed_packages()\n\n\t\t\t\tpackagelist = `#{@finkbin} list -n`\n\n\t\t\t\tpackagelist.each_line() { |line|\n\t\t\t\t\tlinearr = line.split()\n\t\t\t\t\tpackages[linearr[0]] = PackageInfo.new()\n\t\t\t\t\tpackages[linearr[0]].name = linearr[0]\n\t\t\t\t\tpackages[linearr[0]].version = linearr[1]\n\t\t\t\t\tpackages[linearr[0]].description = linearr[2]\n\t\t\t\t}\n\n\t\t\t\treturn(packages)\n\t\t\tend", "def installed_packages()\n\t\t\t\treturn(PackageList.new())\n\t\t\tend", "def packages\n ::Packages::Package.all\n end", "def packages()\n\t\t\t\treturn(PackageList.new())\n\t\t\tend", "def list_packages\n res = []\n out = Aptly::runcmd \"aptly mirror show -with-packages #{@name.quote}\"\n Aptly::parse_indented_list out.lines\n end", "def packages\n return @packages if @packages\n\n @packages = resolve_packages.map do |pkg|\n next if ignored?(pkg)\n\n package_set = pkg.kind_of? Autoproj::InstallationManifest::PackageSet\n pkg = pkg.to_h\n local_dir = if package_set\n pkg[:raw_local_dir]\n else\n pkg[:importdir] || pkg[:srcdir]\n end\n\n Autoproj::Daemon::PackageRepository.new(\n pkg[:name] || pkg[:package_set],\n pkg[:vcs],\n package_set: package_set,\n local_dir: local_dir,\n ws: ws\n )\n end.compact\n @packages\n end", "def get_packages(adb_opts = {})\n packages = []\n run_adb_shell(\"pm list packages -f\", adb_opts) do |pout|\n pout.each do |line|\n @log.debug(\"{stdout} #{line}\") unless @log.nil?\n parts = line.split(\":\")\n if (parts.length > 1)\n info = parts[1].strip.split(\"=\")\n package = AndroidAdb::Package.new(info[1], info[0]);\n packages << package;\n end\n end\n end\n return packages\n end", "def installed_packages(hostname = '')\n report = {}\n Server.where(\"last_checkin > ?\", LAST_CHECKIN).find_each do |server|\n next if hostname != '' && server.hostname != hostname\n report[server.hostname] = {}\n\n # Go through each package. In some cases (gems) there may be multiple\n # versions of a package on the machine.\n server.installed_packages.each do |package|\n name = package.name\n provider = package.provider\n\n # Create data structure if we've not yet encountered this provider or\n # package.\n if !report[server.hostname].key?(provider)\n report[server.hostname][provider] = {}\n report[server.hostname][provider][name] = []\n elsif !report[server.hostname][provider].key?(name)\n report[server.hostname][provider][name] = []\n end\n\n # Add the version.\n report[server.hostname][provider][name] << package.version\n end\n end\n\n report\n end", "def packages\n manifest.each_with_object({}) do |(src, package_name), hsh|\n next if src.nil? || src.empty?\n hsh[package_name] ||= []\n hsh[package_name] << File.join(Licensed::Git.repository_root, src)\n end\n end", "def resolve_packages\n installation_manifest =\n Autoproj::InstallationManifest.from_workspace_root(ws.root_dir)\n installation_manifest.each_package.to_a +\n installation_manifest.each_package_set.to_a\n end", "def existing_packages\n paths_by_app = Dir[File.join(config[:packages_dir], '*', '*.{tar.gz,json}')].group_by { |path|\n path.split(File::SEPARATOR)[-2]\n }\n\n Hash[\n paths_by_app.map { |app, paths|\n names_by_base = paths.group_by do |path|\n File.basename(path).sub(/\\.(?:tar\\.gz|json)\\z/, '')\n end\n\n packages = names_by_base.flat_map { |base, names|\n names.map do |name|\n (\n name.end_with?(\".tar.gz\") &&\n names.find { |_| _.end_with?(\".json\") } &&\n base\n ) || nil\n end\n }.compact\n\n [app, packages.sort]\n }\n ]\n end", "def packages\n @packages ||= []\n end", "def packages\n @packages ||= []\n end", "def packages\n FileList[package_path('.*')]\n end", "def package_manifest()\n res = []\n @items.each do |item|\n sources = item[:sources]\n sources = [ sources ] unless sources.kind_of?(Array)\n sources.each do |src|\n # TODO - want to split into multiple packages\n #if pkg == :main\n # next unless item[:dest] =~ /(LIB|BIN)DIR/\n #elsif pkg == :devel\n # next unless item[:dest] =~ /(INCLUDE|MAN)DIR/\n #else\n # throw \"bad pkg type\"\n #end\n dst = expand_dir(item[:dest])\n if item[:rename].nil?\n dst += '/' + src\n else\n dst += '/' + item[:rename]\n end\n dst.gsub!(/^\\/usr\\/local\\//, '/usr/') # KLUDGE: only true when making an RPM or DEB\n res.push dst\n end\n end\n res.join \"\\n\"\n end", "def search_packages(pattern)\n packages = RailsPwnerer::Base.all_packages\n Hash[packages.select { |key, value|\n pattern.kind_of?(Regexp) ? (pattern =~ key) : key.index(pattern)\n }.map { |key, value|\n # apt-cache search sometimes leaves version numbers out\n # Update the cache with version numbers.\n if value.nil?\n info = RailsPwnerer::Base.package_info_hash(\n Kernel.`(\"apt-cache show #{key}\"))\n packages[key] = value = info['Version']\n end\n [key, value]\n }]\n end", "def package_list(packages, version)\n packages[:base].to_a.join(' ') + ' ' + packages[version].to_a.join(' ')\n end", "def package_info(package_name)\n # return the package hash if it's in the brew info hash\n return brew_info[package_name] if brew_info[package_name]\n\n # check each item in the hash to see if we were passed an alias\n brew_info.each_value do |p|\n return p if p[\"full_name\"] == package_name || p[\"aliases\"].include?(package_name)\n end\n\n {}\n end", "def installed_gems\n gems = []\n\n cmd = [attributes.gem_binary, 'list', '-l']\n cmd << '--prerelease' if attributes.prerelease\n\n run_command(cmd).stdout.each_line do |line|\n next unless /\\A([^ ]+) \\(([^\\)]+)\\)\\z/ =~ line.strip\n\n name = $1\n versions = $2.split(', ')\n gems << { name: name, versions: versions }\n end\n gems\n rescue Backend::CommandExecutionError\n []\n end", "def packages\n packages = []\n @repositories.each do |repo|\n repo_packages = repo.packages\n repo_packages.map { |p| packages.push(p) } unless repo_packages.empty?\n end\n packages\n end", "def packages\n Autoproj.warn_deprecated \"use #each_package instead\"\n each_package.to_a\n end", "def packages\n return @package_manager if @package_manager\n\n @package_manager = Rosh::PackageManager.new(@name)\n @package_manager.add_observer(self)\n\n @package_manager\n end", "def installed_packages()\n\t\t\tend", "def package_list(packages, version)\n Array(packages[:base]).join(' ') + ' ' + Array(packages[version]).join(' ')\n end", "def packages\n JSON.parse(package_metadata_command).values.flatten\n rescue JSON::ParserError => e\n message = \"Licensed was unable to parse the output from 'pnpm licenses list'. JSON Error: #{e.message}\"\n raise Licensed::Sources::Source::Error, message\n end", "def packages\n @packages ||= client.list_packages('duo-openvpn').response\n end", "def read_facts_packages_installed(packages)\n packages_installed = {}\n packages.each do |package, opts|\n packages_installed[package] = check_package_installed(package, opts)\n end\n\n packages_installed\nend", "def apt_installed_packages\n @apt_installed_packages ||= Puppet::Type.type(:package).provider(:apt).instances.map(&:name)\n end", "def listpackages\n packages = []\n\n @repository.categories.each do |category|\n Architecture.dataset(category).each do |entry|\n source = Architecture.new(entry[:architecture], entry[:component], entry[:suitename], category)\n source.files.each do |fullname|\n package = Package.new(fullname, entry[:suitename], entry[:component])\n packages << {\n :fullname => fullname,\n :category => category,\n :basename => File.basename(fullname),\n :controlfile => package.controlfile,\n :component => entry[:component],\n :suitename => entry[:suitename],\n :architecture => entry[:architecture]\n }\n end\n end\n if category.eql? \"stage\"\n Component.dataset(category).each do |entry|\n source = Component.new(entry[:component], entry[:suitename], category)\n source.files.each do |fullname|\n package = Package.new(fullname, entry[:suitename], entry[:component])\n packages << {\n :fullname => fullname,\n :category => category,\n :basename => File.basename(fullname),\n :controlfile => package.controlfile,\n :component => entry[:component],\n :suitename => entry[:suitename],\n :architecture => \"unknown\"\n }\n end\n end\n end\n end\n packages\n end" ]
[ "0.80759007", "0.7899198", "0.78053594", "0.7105834", "0.7072685", "0.65679485", "0.6447896", "0.644356", "0.64097327", "0.63171613", "0.62918484", "0.62847143", "0.62681496", "0.62681496", "0.62100494", "0.6203782", "0.61494905", "0.6145633", "0.61325514", "0.6079028", "0.60596275", "0.6046588", "0.6046274", "0.6041563", "0.6030203", "0.60279053", "0.5996872", "0.59677655", "0.5949257", "0.5946036" ]
0.8095609
0
Verify the number of items in a cart
def verify_cart_shopping_cart_size(count) cart_page = MemberManagement::Page::Cart.new $browser @soft_asserts.verify { expect(cart_page.shopping_cart_rows.size).to eq count } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_enough\r\n \tProduct.find(@cart_item.product_id).count - @cart_item.count >= 0\r\n end", "def test_total_number_of_products\n cart = ShoppingCart.new(\"King Soopers\", \"30items\")\n product1 = Product.new(:paper, 'toilet paper', 3.70, '10')\n product2 = Product.new(:meat, 'chicken', 4.50, '2')\n product3 = Product.new(:paper, 'tissue paper', 1.25, '1')\n cart.add_product(product1)\n cart.add_product(product2)\n cart.add_product(product3)\n\n assert_equal 13, cart.test_total_number_of_products\n end", "def test_it_can_count_items_per_id\n assert_equal 475, @sa.item_count_per_merchant_id.count\n end", "def test_adds_up_in_quanttity\n\t\tcart = Cart.new\n\t\t3.times { cart.add_item 1 }\n\n\t\tassert_equal cart.items.length, 1 #solo un item\n\t\tassert_equal cart.items.first.quantity, 3 #varias unidades del mismo item\n\tend", "def count_items\n @items.size\n end", "def cart_products_count\n count = 0\n CartProduct.all.each do |product|\n if product.user_id.to_s == logged_in.to_s\n count += 1\n end\n end\n return count\n end", "def add_to_cart\n @item = Item.find(params[:id].to_i)\n\n if current_user\n check_if_item_exists_in_cart(current_cart, @item, params[:redirect_to])\n @items_count = current_cart.items.count\n else\n check_if_item_exists_in_cart(guest_cart, @item, params[:redirect_to])\n @items_count = guest_cart.count\n end\n \n render plain: @items_count\n end", "def get_total_products_number_in_cart\n if self.cart.line_items.length == 0\n total_products_number_in_cart = 0\n else\n total_products_number_in_cart = self.cart.line_items.sum{|li| li.quantity}\n end\n end", "def increase_items_count\n # ensure count cannot go above 5\n s_id = params[:product_id].to_s\n return if session[:shopping_cart][s_id]['quantity'].to_i >= 5\n\n session[:shopping_cart][s_id]['quantity'] =\n session[:shopping_cart][s_id]['quantity'].to_i + 1\n\n @product = Product.find(params[:product_id].to_i)\n calculate_order_total\n end", "def items_count\n counter = 0\n self.line_items.each do |item|\n counter += item.quantity\n end\n counter\n end", "def has_items?\n\t\tget_cart_items.size > 0\n\tend", "def count_tested\n return self.tested_products.size\n end", "def count\n @item_list.size\n end", "def item_count\n @items.length \n end", "def count_items(cart)\n\tcart.each do |item|\n\t\titem.each do |name, data|\n\t\t\tdata[:count] += 1\n\t\tend\n\tend\n\tcart.uniq\n\t# deletes duplicates of the same object\nend", "def num_times_applies(cart_items)\n num_items_matched = cart_items.map do |cart_item|\n item_matches?(cart_item.item) ? cart_item.quantity : 0\n end.inject(:+)\n\n num_discounts = num_items_matched / quantity\n\n if repeating?\n num_discounts\n else\n if num_discounts > 0 then 1 else 0 end\n end\n end", "def product_tot_purchases(array_item)\n\tarray_item[\"purchases\"].length\nend", "def num_items()\n items ? items.length : 0\n end", "def count\r\n items.size\r\n end", "def success\n if session[:purchased_item] == '0'\n @items = items_from_cart\n session.delete(:cart)\n else\n item = Product.find(session[:purchased_item])\n @items = []\n @items << { name: item.name, price: item.price, image: item.product_images[0].image.url(:thumb), quantity: session[:quantity] }\n end\n @sum = 0\n @count = 0\n @items.each do |item|\n @sum += item[:price] * item[:quantity].to_i\n @count += item[:quantity].to_i\n end\n end", "def count_items\n order.items.sum(:quantity)\n end", "def test_return_line_items_total\n # Create a cart and add some products.\n a_cart = Order.new\n a_cart.add_product(items(:red_lightsaber), 2)\n a_cart.add_product(items(:blue_lightsaber), 4)\n \n assert_equal a_cart.line_items_total, a_cart.total\n end", "def cart_check\n puts \"cart checking\"\n \n sleep(2)\n mini_cart_text.click\n wait_for_spinner\n sleep(2)\n puts @prod2 = cartpage_productname.text.downcase\n if(@prod1 == @prod2)\n puts \"product is added to the cart: PASS\"\n else\n puts \"product is not added to the cart: FAIL\" # cart is invalid ie when items in the cart are sold out \n end\n end", "def increment_item_count(cart, item_name)\n index = 0\n while index < cart.length do\n current_item = cart[index]\n if ( current_item[:item] == item_name )\n current_item[:count] += 1\n end\n index += 1\n end\n cart\nend", "def item_count\n @items.length\n end", "def test_add_to_cart_success\n @product = items(:holy_grenade)\n post :add_to_cart, :id => @product.id\n assert_redirected_to :action => :checkout\n cart = assigns(:order)\n assert_equal 1, cart.items.length\n end", "def item_count\n\t\tquery(\"* marked:'quantityText'\", :text)[0]\n\tend", "def items_count\n counter = 0\n self.line_items.each do |item|\n if item.sellable && item.sellable.respond_to?(:quantity)\n counter += item.sellable.quantity\n else\n counter += 1\n end\n end\n counter\n end", "def get_number_of_items_in_basket\n while @page.find(:div_id,'basket_nav').has_selector?(:span_id,'miniBKQty', :minimum => 2) do\n sleep 0.5\n end\n\n result = @page.find(:div_id,'basket_nav').find(:span_id,'miniBKQty').text\n fail \"\\nERROR: Cannot find the number of items in the Basket\" if (result.match /\\D+/) || (result == nil)\n return result[/(\\d+)/,1].to_i\n end", "def total_items\n @cart_items.sum{|k,v| v}\n end" ]
[ "0.7695009", "0.7646764", "0.7120267", "0.7101367", "0.70408505", "0.7012105", "0.69946086", "0.6973096", "0.6850829", "0.68255", "0.6794664", "0.67872214", "0.6746678", "0.67196035", "0.6682283", "0.6675873", "0.6674071", "0.66703767", "0.66640747", "0.66620374", "0.6657565", "0.6654753", "0.6636471", "0.66243505", "0.66200686", "0.6610464", "0.6586834", "0.6557381", "0.65548646", "0.65325004" ]
0.8143284
0
Verify the grand total of a cart
def verify_cart_shopping_cart_grand_total(total) cart_page = MemberManagement::Page::Cart.new $browser @soft_asserts.verify { expect(cart_page.grand_total.text).to eq total } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def grand_total\n total = 0\n return total if session[:cart].empty? # skip if cart empty...\n session[:cart].each do |item_id, quantity|\n info = {item_id: item_id, quantity: quantity}\n order_item = OrderItem.new(info)\n total += order_item.subtotal\n end\n total\nend", "def checkout(cart, coupons)\n grand_total = 0 \n final_purchases = consolidate_cart(cart)\n apply_coupons(final_purchases, coupons)\n apply_clearance(final_purchases)\n index = 0 \n while index < final_purchases.length\n grand_total += (final_purchases[index][:price] * final_purchases[index][:count])\n index += 1\n end\n if grand_total > 100\n grand_total = (grand_total *0.9).round(2)\n end\n grand_total\nend", "def checkout(cart, coupons)\n \n #binding.pry\n \n #use same cart to apply all the different discounts onto otherwise it wont be totaled\n \n \n cart_output = consolidate_cart(cart)\n apply_coupons(cart_output, coupons)\n apply_clearance(cart_output)\n \n grand_total = 0\n\n #binding.pry\n cart_output.each do |item_name, item_details|\n \n #have to get price AND count otherwise items aren't charged repeatedly\n grand_total += item_details[:price] * item_details[:count]\n \n end\n \n #binding.pry\n \n if grand_total > 100.00\n grand_total = ( grand_total * (0.90) ).round(2)\n end \n #binding.pry\n \n grand_total\nend", "def test_return_total_price\n # Create a cart and add some products.\n a_cart = Order.new\n a_cart.add_product(items(:red_lightsaber), 2)\n a_cart.add_product(items(:blue_lightsaber), 4)\n assert_equal a_cart.items.length, 2\n\n total = 0.0\n for item in a_cart.items\n total += (item.quantity * item.unit_price)\n end\n\n assert_equal total, a_cart.total\n end", "def cart_total_price\n total = 0\n self.cart_items.each do |cart_item|\n total += cart_item.sub_total\n end\n total\n end", "def test_return_line_items_total\n # Create a cart and add some products.\n a_cart = Order.new\n a_cart.add_product(items(:red_lightsaber), 2)\n a_cart.add_product(items(:blue_lightsaber), 4)\n \n assert_equal a_cart.line_items_total, a_cart.total\n end", "def grand_total\n order_lines.inject(Money.new(0)) { |grand_total, line| grand_total + line.total_price }\n end", "def checkout(cart, coupons)\n #call the consolidate to get the count item first\n new_cart = consolidate_cart(cart)\n #apply coupon to the new cart\n apply_coupons(new_cart, coupons)\n #apply clearance after discount from coupon\n apply_clearance(new_cart)\n\ntotal = 0\n new_cart.each do |name, hash|\n total += (hash[:price] * hash[:count])\n #binding.pry\n end\n\nif total >= 100\n total *= 0.9\n end\n\n total\nend", "def checkout(cart, coupons)\n new_cart = consolidate_cart(cart)\n new_cart = apply_coupons(new_cart, coupons)\n new_cart = apply_clearance(new_cart)\n\n total = 0\n new_cart.each do |item|\n total += item[:price] * item[:count]\n end\n\n if total >= 100\n total = total - total*0.10\n end\n\n total\nend", "def cart_total\r\n\t\ttotal = 0\r\n\t\tfor item in @cart_items\r\n\t\t\ttotal = total + @products[item].to_f\r\n\t\tend\r\n\t\ttotal\r\n\tend", "def calc_cart_total\n @cart_total = 0\n #This will determine the cart total\n @user_cart.each do |product|\n @cart_total = @cart_total + product[:price]\n end\n puts \"Your cart will cost you $#{@cart_total.round(2)} currently.\"\nend", "def checkout(cart, coupons)\n cart = consolidate_cart(cart)\n cart = apply_coupons(cart, coupons)\n cart = apply_clearance(cart)\n total = 0\n cart.each do |item|\n total += item[:price] * item[:count]\n end\n if total > 100\n total = (total * 0.90).round(2)\n end \n total\nend", "def checkout(cart, coupons)\n total = 0\n base_cart = consolidate_cart(cart)\n cart_with_coupons = apply_coupons(base_cart, coupons)\n final_cart = apply_clearance(cart_with_coupons)\n final_cart.each do |item, attribute_hash|\n total += attribute_hash[:price] * attribute_hash[:count]\n end\n if total > 100\n total *= 0.90\n end\n total\nend", "def cart_total\n total = 0\n cart.each do |product_id, details|\n if p = Product.find_by(id: product_id)\n total += p.price_cents * details['quantity'].to_i\n end\n end\n total\n end", "def cart_total\n total = 0\n cart.each do |product_id, details|\n if p = Product.find_by(id: product_id)\n total += p.price_cents * details['quantity'].to_i\n end\n end\n total\n end", "def checkout(cart, coupons)\n cons_cart = consolidate_cart(cart)\n coup_cart = apply_coupons(cons_cart, coupons)\n clearance_cart = apply_clearance(coup_cart)\n\n cart_total = 0\n clearance_cart.each do |item, value|\n cart_total += clearance_cart[item][:price] * clearance_cart[item][:count]\n end\n if cart_total > 100\n cart_total = (cart_total * 0.9)\n end\n cart_total\nend", "def cart_total\n total = 0\n cart.each do |pId, info|\n if (prod = Product.find_by(id: pId))\n total += prod.price * info[\"Num\"].to_i\n end\n end\n total\n end", "def checkout(cart, coupons)\n total = 0\n tidyCart = consolidate_cart(cart)\n coupon_cart = apply_coupons(tidyCart, coupons)\n clearance_cart = apply_clearance(coupon_cart)\n clearance_cart.each do |food, data|\n total += data[:price] * data[:count]\n end\n if total > 100\n total = total * 0.9\n end\n total\nend", "def test_total\n assert_equal @order.total, (@order.line_items_total + @order.shipping_cost)\n end", "def total\n cart_value = 0\n self.line_items.each do |line_item|\n cart_value += line_item.value\n end\n cart_value\n end", "def checkout(cart, coupons)\n cart = consolidate_cart(cart)\n cart = apply_coupons(cart, coupons)\n cart = apply_clearance(cart)\n total = 0\n cart.each do |key, value|\n total += value[:price] * value[:count]\n end\n total > 100.00 ? total -= total * 0.10 : total\n return total\nend", "def checkout(cart, coupons)\n i=0\n total=0\n total_cart = consolidate_cart(cart)\n apply_coupons(total_cart, coupons)\n apply_clearance(total_cart)\n\n while i < total_cart.length do\n total += total_cart[i][:price] * total_cart[i][:count]\n i += 1\n\n end\n if total >= 100\n total *= 9/10.to_f\n end\ntotal.round(2)\nend", "def total\n self.inject(0) { |t, calculator| t + (calculator.active? ? calculator.price(@cart) : 0) }\n end", "def checkout(cart, coupons)\n #Consolidate cart...\n consolidated_cart = consolidate_cart(cart)\n # Apply coupons...\n coupons_applied = apply_coupons(consolidated_cart, coupons)\n #Apply clearance...\n final_cart = apply_clearance(coupons_applied)\n #start cart total at zero\n cart_total = 0\n #calculate the cost of the cart...\n final_cart.each do |item, attributes|\n item_total = attributes[:price] * attributes[:count]\n cart_total = cart_total + item_total\n end\n final_total = cart_total.round(2)\n # If the final_tota is > 100...\n if final_total > 100\n final_total *= 0.9\n end\n final_total\nend", "def total\n apply_rules(subtotal).round\n end", "def checkout(cart, coupons)\n new_cart = consolidate_cart(cart)\n couponed_cart = apply_coupons(new_cart,coupons)\n clearance_cart = apply_clearance(couponed_cart)\n i = 0\n total = 0\n while i < couponed_cart.length\n total += (couponed_cart[i][:price]*couponed_cart[i][:count])\n i += 1\n end\n if total > 100\n total = (total - total*0.10)\n end\n total\nend", "def checkout(cart, coupons)\n consolidated_cart = consolidate_cart(cart)\n couponed_cart = apply_coupons(consolidated_cart, coupons)\n final_cart = apply_clearance(couponed_cart)\n\n total = 0\n counter = 0\n while counter < final_cart.length\n total += final_cart[counter][:price] * final_cart[counter][:count]\n counter += 1\n end\n if total > 100\n total -= (total * 0.1)\n end\n total\nend", "def total #, quantity=1)\t# quantity optional\n\t\tCashRegister.clear_cart\n\t\t@total\n\tend", "def total_before_tax\n total = 0\n @cart_items.each do |item|\n total += item.price\n end\n return total\n end", "def total_price(cart)\n cart.sum {|item| item.price} \n end" ]
[ "0.7530609", "0.7195634", "0.69279855", "0.67688847", "0.67515534", "0.6719154", "0.67072517", "0.66930723", "0.6683159", "0.6647998", "0.6621847", "0.65928036", "0.6582012", "0.6557325", "0.6557325", "0.65564126", "0.65373236", "0.65272146", "0.652469", "0.6506421", "0.64641654", "0.64614207", "0.6453027", "0.64149076", "0.6413269", "0.6374877", "0.6358645", "0.63550425", "0.63350445", "0.63222367" ]
0.85869753
0
=begin Returns nil if no category is disabled, array of disabled ids otherwise. =end
def disabled_options(categories, &block) categories.inject([]) do |disabled, c| if yield(c) disabled else disabled << c.id end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def allowed_category_ids\n @allowed_category_ids ||=\n begin\n unrestricted = Category.where(read_restricted: false).pluck(:id)\n unrestricted.concat(secure_category_ids)\n end\n end", "def disabled_categories(card)\n card_benefits = []\n card.benefits.each{|b| card_benefits << b.category}\n card_benefits & categories\n end", "def disabled_checks_by_category\n checks = REXML::XPath.first(@xml, '//VulnerabilityChecks/Disabled')\n checks ? checks.elements.to_a('VulnCategory').map { |c| c.attributes['name'] } : []\n end", "def all_category_ids\n end", "def category_ids\n @new_category_ids or super\n end", "def category_ids\n (categories.length > 0) ? categories.map{|c| c.id}.join(', ') : 'NULL'\n end", "def category_ids\n (categories.length > 0) ? categories.map{|c| c.id}.join(', ') : 'NULL'\n end", "def potential_categories\n if categories.length > 0\n Category.all(:conditions => \"id NOT IN (#{category_ids})\")\n else\n Category.all\n end\n end", "def category_ids\n # {{{\n if !@category_ids then\n @category_ids = User_Category.select_values(User_Category.category_id) { |cid|\n cid.where(User_Category.user_group_id == (user_group_id))\n }.to_a.flatten.map { |c| c.to_i }\n end\n return @category_ids\n end", "def enabled_component_ids\n enabled_components.select(&:can_be_disabled?).map(&:key).map(&:to_s)\n end", "def enabled\n h.params[:categories]&.include?(to_param)\n end", "def disableable_components_ids\n @disableable_components_ids ||= disableable_components.map(&:key).map(&:to_s)\n end", "def readable_category_ids\n # {{{\n if !@readable_category_ids then\n parent_group_ids = []\n if respond_to?(:parent_groups) then\n parent_group_ids = parent_groups.map { |g| g.user_group_id }\n end\n if is_registered? then\n @readable_category_ids = Category.select_values(Category.category_id) { |c| \n c.where((Category.public_readable == 't') |\n (Category.registered_readable == 't') |\n (Category.category_id.in(User_Category.select(User_Category.category_id) { |ucid|\n ucid.where((User_Category.user_group_id.in(parent_group_ids + [ user_group_id ])) &\n (User_Category.read_permission == 't'))\n })\n ))\n }.to_a.flatten.map { |cid| cid.to_i }.uniq\n else\n @readable_category_ids = Category.select_values(Category.category_id) { |c| \n c.where((Category.public_readable == 't') |\n (Category.category_id.in(User_Category.select(User_Category.category_id) { |ucid|\n ucid.where((User_Category.user_group_id.in(parent_group_ids + [ user_group_id ])) &\n (User_Category.read_permission == 't'))\n })\n ))\n }.to_a.flatten.map { |cid| cid.to_i }.uniq\n end\n end\n @readable_category_ids\n end", "def enabled_component_ids\n @enabled_component_ids ||= begin\n components = @settable.user_enabled_components - @settable.undisableable_components\n components.map { |c| c.key.to_s }\n end\n end", "def category_ids\n self.associated_categories.collect{ |c| c.id }\n end", "def writeable_category_ids\n # {{{\n if !@writeable_category_ids then\n if is_admin? then\n @writeable_category_ids = Category.select_values(:category_id) { |cat_id|\n cat_id.order_by(:is_private, :desc)\n cat_id.order_by(:category_name, :asc)\n }.to_a.flatten.map { |c| c.to_i }\n else\n parent_group_ids = []\n if respond_to?(:parent_groups) then\n parent_group_ids = parent_groups.map { |g| g.user_group_id }\n end\n if is_registered? then\n @writeable_category_ids = Category.select { |c| \n c.where((Category.public_writeable == 't') | \n (Category.registered_writeable == 't') |\n (Category.category_id.in(User_Category.select(User_Category.category_id) { |ucid|\n ucid.where((User_Category.user_group_id.in(parent_group_ids + [ user_group_id ])) &\n (User_Category.write_permission == 't'))\n })\n ))\n }.to_a.flatten.map { |c| c.category_id }.uniq\n else\n @writeable_category_ids = Category.select { |c| \n c.where((Category.public_writeable == 't') |\n (Category.category_id.in(User_Category.select(User_Category.category_id) { |ucid|\n ucid.where((User_Category.user_group_id.in(parent_group_ids + [ user_group_id ])) &\n (User_Category.write_permission == 't'))\n })\n ))\n }.to_a.flatten.map { |c| c.category_id }.uniq\n end\n end\n end\n @writeable_category_ids\n end", "def enabled_checks_by_category\n checks = REXML::XPath.first(@xml, '//VulnerabilityChecks/Enabled')\n checks ? checks.elements.to_a('VulnCategory').map { |c| c.attributes['name'] } : []\n end", "def category_options\n Category.all.map { |c| [c.categoryName,c.id]}\n end", "def disableable_component_collection\n @settable.disableable_components.map { |c| [c.display_name, c.key.to_s] }.sort\n end", "def active_cate_ids\n self.products.group_by(&:cate_id).keys.sort\n end", "def get_active_recipe_ids\n users_recipes.find_all {|ur| ur.active}.map {|ur| ur.recipe_id}\n end", "def find_category\n @category = Category.enabled.find(params[:category_id])\n end", "def category_ids(categories)\n #This can accept an array or a single id\n categories = [categories] unless categories.class == Array\n bb_products = []\n categories.each do |category|\n category = ProductCategory.trim_retailer(category)\n product_infos = get_shallow_product_infos(category, english = true, use_cache = true)\n product_infos.select! { |product_info| product_info[\"isVisible\"] != false } \n bb_products += product_infos.map{ |p| BBproduct.new(:id => p[\"sku\"], :category => category) }\n end\n bb_products\n end", "def category_enum\n Category.all.collect {|p| [ p.name, p.id ] }\n end", "def categories\n []\n end", "def enabled\n select(&:enabled?)\n end", "def category_ids\n ActiveRecord::Base.connection.select_values( \"SELECT DISTINCT c.id from categories as c, movie_user_categories as muc\n where muc.category_id = c.id and muc.movie_id = #{self.id}\" ).map(&:to_i)\n end", "def get_disabled_alternatives(d)\n return d.get_disabled_alternatives\n end", "def enabled_components\n Course::ControllerComponentHost.find_enabled_components(disableable_components, settings)\n end", "def disableable_components\n available_components\n end" ]
[ "0.72495514", "0.6695797", "0.6615539", "0.6526112", "0.6428358", "0.6337903", "0.6337903", "0.6321957", "0.631769", "0.62648225", "0.62408394", "0.6220884", "0.6177829", "0.61465245", "0.61342263", "0.60905063", "0.59337986", "0.56674916", "0.5656138", "0.56436366", "0.56195486", "0.5575564", "0.5557728", "0.5546695", "0.55461925", "0.5516888", "0.5443367", "0.54401934", "0.5394769", "0.535142" ]
0.72378576
1
Installs required repositories as project's submodules.
def install_submodules if agree( (["OK to add git submodules to your application?", "If you select 'No' here some of the fuctionality can be lost", "\n" ] + SUBMODULES.values).join "\n" ) SUBMODULES.each do |path, submodule| run "git submodule add #{submodule} config/deploy/#{path}" end else say "OK. Skipping submodules" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setup\n default_repository.update_submodules(:recursive => true)\n true\n end", "def install!\n each_module do |repo|\n\n print_verbose \"\\n##### processing module #{repo[:name]}...\"\n\n module_dir = File.join(module_path, repo[:name])\n\n unless File.exists?(module_dir)\n case\n when repo[:git]\n install_git module_path, repo[:name], repo[:git], repo[:ref]\n when repo[:archive]\n install_archive module_path, repo[:name], repo[:archive]\n else\n abort('only the :git and :archive provider are currently supported')\n end\n else\n print_verbose \"\\nModule #{repo[:name]} already installed in #{module_path}\"\n end\n end\n end", "def install\n install_gems(dependencies)\n end", "def install\n bin.install \"git-subtree.sh\" => \"git-subtree\"\n end", "def install\n system \"cmake\", \"-S\", \".\", \"-B\", \"build\", *std_cmake_args\n system \"cmake\", \"--build\", \"build\"\n system \"cmake\", \"--install\", \"build\"\n end", "def install\n # ENV.deparallelize # if your formula fails when building in parallel\n\n # Remove unrecognized options if warned by configure\n system \"git init && git submodule init && git submodule update\"\n bin.install \"install-dot-files\"\n end", "def install_git(nr)\n install_git_packages\n checkout_path = clone_git_repo(nr)\n install_gem(nr, checkout_path)\n end", "def install(*modules)\n collection = DotModule::Collection.new(Dir.pwd)\n if modules.size.zero?\n modules = case ask(\"#{collection}\\nNo module argument passed. Install (c)ore/(a)ll/(n)one? [n]:\").downcase\n when 'a'\n collection.modules\n when 'c'\n collection.core_modules\n else #none\n []\n end\n end\n collection.install_modules(modules)\n end", "def install_modules(outputter, force: false, resolve: true)\n assert_project_file(config.project)\n\n if config.project.modules.empty? && resolve\n outputter.print_message(\n \"Project configuration file #{config.project.project_file} does not \"\\\n \"specify any module dependencies. Nothing to do.\"\n )\n return true\n end\n\n installer = Bolt::ModuleInstaller.new(outputter, pal)\n\n installer.install(config.project.modules,\n config.project.puppetfile,\n config.project.managed_moduledir,\n config.module_install,\n force: force,\n resolve: resolve)\n end", "def install\n Core.install(gem_name: gem_name, base: base, **options)\n Badges.install(gem_name: gem_name, base: base, **options)\n Travis.install(gem_name: gem_name, base: base, **options)\n end", "def setup\n install_latest_ruby\n\n install_global_gems\n end", "def install\n mkdir \"build\" do\n system \"cmake\", \"-DSPECIFY_RPATH=ON\", *std_cmake_args, \"..\"\n system \"make\"\n system \"make\", \"install\"\n end\n end", "def install\n system \"cmake\", \".\", *std_cmake_args\n system \"make\", \"install\"\n end", "def install_project_modules(project, config, force, resolve)\n assert_project_file(project)\n\n if project.modules.empty? && resolve != false\n outputter.print_message(\n \"Project configuration file #{project.project_file} does not \"\\\n \"specify any module dependencies. Nothing to do.\"\n )\n return 0\n end\n\n installer = Bolt::ModuleInstaller.new(outputter, pal)\n\n ok = outputter.spin do\n installer.install(project.modules,\n project.puppetfile,\n project.managed_moduledir,\n config,\n force: force,\n resolve: resolve)\n end\n\n ok ? 0 : 1\n end", "def install\n cd_and_sh( pkg_dir, install_commands )\n end", "def install\n args = std_cmake_args\n system \"cmake\", \".\", *args\n system \"make install\"\n end", "def install(specs, path, moduledir, config = {}, force: false, resolve: true)\n @outputter.print_message(\"Installing project modules\\n\\n\")\n\n if resolve != false\n specs = Specs.new(specs, config)\n\n # If forcibly installing or if there is no Puppetfile, resolve\n # and write a Puppetfile.\n if force || !path.exist?\n @outputter.print_action_step(\"Resolving module dependencies, this might take a moment\")\n\n # This doesn't use the block as it's more testable to just mock *_spin\n @outputter.start_spin\n puppetfile = Resolver.new.resolve(specs, config)\n @outputter.stop_spin\n\n # We get here either through 'bolt module install' which uses the\n # managed modulepath (which isn't configurable) or through bolt\n # project init --modules, which uses the default modulepath. This\n # should be safe to assume that if `.modules/` is the moduledir the\n # user is using the new workflow\n @outputter.print_action_step(\"Writing Puppetfile at #{path}\")\n if moduledir.basename.to_s == '.modules'\n puppetfile.write(path, moduledir)\n else\n puppetfile.write(path)\n end\n # If not forcibly installing and there is a Puppetfile, assert\n # that it satisfies the specs.\n else\n puppetfile = Puppetfile.parse(path)\n puppetfile.assert_satisfies(specs)\n end\n end\n\n # Install the modules.\n install_puppetfile(path, moduledir, config)\n end", "def reinit_submods\n # add back in our submodules\n `git submodule init`\n `git submodule update`\n\n # ensure we checkout master (cause it'll default to headless)\n `git --git-dir=#{self.submods}/.git checkout master`\n end", "def install\n each { |m| m.install }\n end", "def _install\n args = Array.new\n # If the project contains a makefile, it is a candidate for a derivative build.\n # In such case, protect 'libraries', 'modules' and 'themes' subdirectories\n # from deletion.\n if component.makefile\n args << '-f' << 'P /libraries/***' # this syntax requires rsync >=2.6.7.\n args << '-f' << 'P /modules/***'\n args << '-f' << 'P /profiles/***'\n args << '-f' << 'P /themes/***'\n end\n if component.drupal?\n args = Array.new\n args << '-f' << 'R /profiles/default/***' # D6\n args << '-f' << 'R /profiles/minimal/***' # D7\n args << '-f' << 'R /profiles/standard/***' # D7\n args << '-f' << 'R /profiles/testing/***' # D7\n args << '-f' << 'P /profiles/***'\n args << '-f' << 'R /sites/all/README.txt'\n args << '-f' << 'R /sites/default/default.settings.php'\n args << '-f' << 'P /sites/***'\n end\n args << '-a'\n args << '--delete'\n component.ignore_paths.each { |p| args << \"--exclude=#{p}\" }\n dst_path = platform.local_path + platform.dest_path(component)\n dont_debug { dst_path.mkpath }\n args << component.local_path.to_s + '/'\n args << dst_path.to_s + '/'\n begin\n runBabyRun 'rsync', args\n rescue => ex\n odie \"Installing or updating #{component.name} failed: #{ex}\"\n end\n end", "def install\n print_title('Redmine installing')\n\n Dir.chdir(root) do\n # Gems can be locked on bad version\n FileUtils.rm_f('Gemfile.lock')\n\n # Install new gems\n bundle_install\n\n # Generate secret token\n rake_generate_secret_token\n\n # Ensuring database\n rake_db_create\n\n # Load database dump (if was set via CLI or attach on package)\n load_database_dump\n\n # Migrating\n rake_db_migrate\n\n # Plugin migrating\n rake_redmine_plugin_migrate\n\n # Install easyproject\n rake_easyproject_install if easyproject?\n end\n end", "def install_git_packages\n at_compile_time do\n package 'git'\n end\n end", "def install\n args = std_cmake_args+ %W[\n -DCMAKE_MODULE_PATH=#{HOMEBREW_PREFIX}/share/cmake/Modules\n ]\n system \"cmake\", \".\", *args\n system \"make install\"\n end", "def install\n args = std_cmake_args\n\n system \"cmake\", \".\", *args\n system \"make\", \"install\"\n prefix.install \"install_manifest.txt\"\n end", "def install\n# Dependency tracking only, uncomment this section only if you know what you\n# are doing!\n#\n# mkdir 'build'\n# cd 'build' do\n# system \"cmake .. #{std_cmake_parameters}\"\n# system \"make package\"\n# end\nend", "def install(confirmation_needed = true)\n self.class.install(@repo,confirmation_needed)\n end", "def install\n # system \"./configure\", \"--disable-debug\", \"--disable-dependency-tracking\",\n \"--prefix=#{prefix}\"\n # system \"cmake . #{std_cmake_parameters}\"\n # system \"make install\" # if this fails, try separate make/make install steps\n # system \"cp -r lib samples #{prefix}\"\n prefix.install Dir[ '*' ]\n end", "def checkout # :nodoc:\n cache\n\n unless File.exist? install_dir then\n system @git, 'clone', '--quiet', '--no-checkout',\n repo_cache_dir, install_dir\n end\n\n Dir.chdir install_dir do\n system @git, 'fetch', '--quiet', '--force', '--tags', install_dir\n\n success = system @git, 'reset', '--quiet', '--hard', @reference\n\n success &&=\n system @git, 'submodule', 'update',\n '--quiet', '--init', '--recursive' if @need_submodules\n\n success\n end\n end", "def install!\n refresh_file_accessors\n prepare_pod_groups\n add_source_files_references\n add_frameworks_bundles\n add_vendored_libraries\n add_resources\n add_developer_files unless sandbox.development_pods.empty?\n link_headers\n end", "def install(env); end" ]
[ "0.7257783", "0.717883", "0.69483876", "0.6726392", "0.6612064", "0.66022974", "0.6493901", "0.6469494", "0.6429483", "0.64015096", "0.63634706", "0.63346946", "0.63188875", "0.6310473", "0.62054867", "0.6160013", "0.6154139", "0.61529773", "0.60734534", "0.6068954", "0.6065911", "0.60533273", "0.6052606", "0.6031074", "0.5984311", "0.59363955", "0.59218025", "0.58989865", "0.58837277", "0.5880021" ]
0.75199455
0
Create deploy rb file
def create_deploy @@tpl = CapistranoDeployGenerator.source_root empty_directory "config/deploy" say <<-EOF config/deploy.rb generator This menu will help you creating deployment configuration file deploy.rb for Capistrano. It is safe to acceppt defulat values for most or all questions. Just hit Enter if default is provided. All values can be changed later in the file itself or you can re-run generator again. EOF template "deploy.rb.erb", "config/deploy.rb" @stages.each do |stage| template "staging.rb.erb", "config/deploy/#{stage}.rb" end say "Please edit manually configuration of the multi-staging files:" @stages.map { |x| say "./confg/deploy/#{x}.rb\n"} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n deploy\n end", "def gen_deploy(deploy_id, slug_url, config)\n require 'erb'\n require 'shellwords'\n template = ERB.new(File.read(File.join(data_dir, 'deploy.bash.erb')))\n template.result(binding)\n end", "def create\n GITHUB.create_deployment(\n @project.repository_path,\n @deploy.job.commit,\n payload: {\n deployer: @deploy.user.attributes.slice(\"id\", \"name\", \"email\"),\n buddy: @deploy.buddy&.attributes&.slice(\"id\", \"name\", \"email\"),\n },\n environment: @stage.name,\n description: @deploy.summary,\n production_environment: @stage.production?,\n auto_merge: false, # make deployments on merge commits not produce Octokit::Conflict and do not merge PRs\n required_contexts: [], # also create deployments when commit statuses show failure (CI failed)\n accept: \"application/vnd.github.ant-man-preview+json\" # special header so we can use production_environment field\n )\n end", "def build_deploy_info_file\n\n deploy_info = get_deploy_info.to_yaml\n info_filepath = \"#{self.scripts_path}/info\"\n\n @shell.make_file info_filepath, deploy_info\n\n @shell.symlink info_filepath, \"#{self.root_path}/info\"\n end", "def deploy\n system %Q[ssh -lroot \"#{server}\" <<'EOF'\n \tcat >\"#{remote_script_name}\" <<'EOS'\n#{generate}EOS\nchmod +x \"#{remote_script_name}\"\nsource \"#{remote_script_name}\"\nEOF\n ]\n end", "def generate_deploy_files\n template_name = (self.name == 'vagrant') ? 'vagrant' : \"environment\"\n # Generate capistrano specific steps recipes\n Bebox::PROVISION_STEPS.each do |step|\n generate_file_from_template(\"#{Bebox::FilesHelper.templates_path}/project/config/deploy/steps/#{step}.erb\", \"#{self.project_root}/config/environments/#{name}/steps/#{step}.rb\", {})\n end\n # Generate capistrano recipe for environment\n generate_file_from_template(\"#{Bebox::FilesHelper.templates_path}/project/config/deploy/#{template_name}.erb\", \"#{self.project_root}/config/environments/#{name}/deploy.rb\", {nodes: nil, environment: self.name})\n end", "def action_deploy\n notifying_block do\n directory new_resource.path do\n owner new_resource.owner\n group new_resource.group\n mode '755'\n end\n end\n end", "def deploy()\n release = create_release_name()\n\n write_deploy_version_file()\n\n DirectorySync.sync(server, from_dir, cache_dir, server[:deployer])\n copy_cache_dir_to_release(release)\n\n symlink_shared_directories(release)\n\n send_scripts()\n run_script(:before, release)\n symlink_release_dir(release)\n run_script(:after, release)\n end", "def action_create\n\n install_prerequisites\n\n node.set['pedant'][new_resource.variant]['etc_dir'] = new_resource.config_dir\n\n directory new_resource.config_dir do\n owner new_resource.user\n group new_resource.group\n mode \"0755\"\n recursive true\n end\n\n source_dir = \"#{new_resource.checkout_dir}/#{new_resource.variant}\"\n\n git new_resource.variant do\n destination source_dir\n repository \"git@github.com:opscode/#{new_resource.variant}.git\"\n revision new_resource.revision\n user new_resource.git_user\n end\n\n node.set['pedant'][new_resource.variant]['dir'] = \"/srv/#{new_resource.variant}\"\n\n link node['pedant'][new_resource.variant]['dir'] do\n to source_dir\n end\n\n template \"#{new_resource.config_dir}/pedant_config.rb\" do\n source new_resource.config_template\n owner new_resource.user\n group new_resource.group\n mode \"0644\"\n variables(new_resource.variables)\n end\n\n execute \"bundle install\" do\n cwd node['pedant'][new_resource.variant]['dir']\n # user \"opscode\"\n end\n\nend", "def deploy!\n write_previous_revision\n update_repository\n write_revision\n end", "def create_app()\n file=File.open(\"app.rb\", \"w\")\n file.puts(\"require 'bundler'\")\n file.puts(\"Bundler.require\")\n file.puts(\"\")\n file.puts(\"require_relative 'lib/...'\")\n file.close\n create_readme()\nend", "def negroku\n File.join(File.dirname(__FILE__), 'negroku', 'deploy.rb')\nend", "def create_deployment_manifest\n cloud_properties = { \"instance_type\" => \"m1.small\", \"availability_zone\" => \"us-east-1e\" }\n cloud_properties[\"persistent_disk\"] = flags[:disk] if flags[:disk]\n cloud_properties[\"static_ips\"] = ip_addresses\n manifest = Bosh::Gen::Models::DeploymentManifest.new(name, director_uuid, release_properties, cloud_properties)\n manifest.jobs = job_manifests\n create_file manifest_file_name, manifest.to_yaml, :force => flags[:force]\n end", "def create\n create_checkpoints\n create_config_base\n generate_deploy_files\n generate_hiera_template\n end", "def deploySite\n verifyOS\n timeDate = Time.new\n vConfig(CONFIG['configWebsite'])\n read_json(CONFIG['configWebsite'])\n compileP = @parse_json_config['deploy']['compile']['built']\n branchBuilt = @parse_json_config['deploy']['branch']['built']\n msgCommit = @parse_json_config['deploy']['github']['config']['commit']\n if compileP == \"yes\"\n system_commands(\"rake build\")\n end\n # enter_folder(\"./_site\") # DEPRECATED\n add_repo_git(SITEDIR)\n add_remoteurl(SITEDIR)\n pull_execute(branchBuilt, SITEDIR)\n system_commands(\"echo Deploy source files. Wait ...\")\n git_checkout(branchBuilt, SITEDIR)\n system_commands(\"cd #{SITEDIR}; git add .\")\n system_commands(\"cd #{SITEDIR}; git commit -m \\\"#{msgCommit} - #{timeDate.inspect}\\\"\")\n system_commands(\"cd #{SITEDIR}; git push origin -u #{branchBuilt}\")\n\n end", "def custom_capify(data={}, config=nil)\n # defaults\n data[:server_url] = \"\"\n data[:branch] = \"master\"\n\n FileUtils.mkdir_p AppDirectory.deploy\n\n build_capfile\n\n deploy_rb = AppDirectory.config.join('deploy.rb')\n build_template(\"templates/deploy.rb.erb\", deploy_rb, binding)\n\n FileUtils.mkdir_p AppDirectory.tasks\n\n puts I18n.t :capified, scope: :negroku\n\n end", "def deploy\n cmd = \"deploy #{@resource[:source]} --name=#{@resource[:name]}#{runtime_name_param_with_space_or_empty_string}\"\n if @resource[:runasdomain]\n cmd = append_groups_to_cmd(cmd, @resource[:servergroups])\n end\n cmd = \"#{cmd} --force\" if force_deploy?\n display_lines 100\n bring_up 'Deployment', cmd\n @resource[:name]\n end", "def create_deployment_manifest\n cloud_properties = {\n \"instance_type\" => \"m1.small\",\n }\n cloud_properties[\"persistent_disk\"] = flags[:disk] if flags[:disk]\n cloud_properties[\"static_ips\"] = ip_addresses\n director_uuid = Bosh::Gen::Models::BoshConfig.new.target_uuid\n manifest = Bosh::Gen::Models::DeploymentManifest.new(\n name, director_uuid,\n release_properties, cloud_properties, default_properties)\n manifest.jobs = job_manifests\n create_file manifest_file_name, manifest.to_yaml, :force => flags[:force]\n end", "def create_node_manifest(manifest_path, master_certname, node_def_name='default')\n manifest = File.read(manifest_path)\n\n site_pp = <<-MANIFEST\nfilebucket { 'main':\n server => '#{master_certname}',\n path => false,\n}\n\nFile { backup => 'main' }\n\nnode default {\n\n#{manifest}\n}\nMANIFEST\n\n return site_pp\nend", "def do_deploy()\n require 'digest/md5'\n require 'aws-sdk'\n require 'progressbar'\n require 'simple-cloudfront-invalidator'\n require 'yaml'\n\n # Validation check for environment variables\n if (!ENV['AWS_S3_BUCKET'] ||\n !ENV['AWS_ACCESS_KEY_ID'] ||\n !ENV['AWS_SECRET_ACCESS_KEY'] ||\n !ENV['AWS_CLOUDFRONT_DIST_ID'] ||\n !ENV['AWS_HOST_NAME'] )\n puts(\"The below required environment variable(s) have not been defined.\\n\"\\\n \"Without them, the Deploy process cannot complete.\\n\"\\\n \"Please verify that they have been correctly defined.\")\n puts(\" * AWS_S3_BUCKET\") if (!ENV['AWS_S3_BUCKET'])\n puts(\" * AWS_ACCESS_KEY_ID\") if (!ENV['AWS_ACCESS_KEY_ID'])\n puts(\" * AWS_SECRET_ACCESS_KEY\") if (!ENV['AWS_SECRET_ACCESS_KEY'])\n puts(\" * AWS_CLOUDFRONT_DIST_ID\") if (!ENV['AWS_CLOUDFRONT_DIST_ID'])\n puts(\" * AWS_HOST_NAME\") if (!ENV['AWS_HOST_NAME'])\n exit()\n end\n\n puts(\"========================================\")\n puts(\"Beginning Deploy Process...\")\n\n # Capture Hugo's config.yaml while we're in the same directory\n config_file = YAML.load_file('config.yaml')\n\n # Make sure we actually loaded a file, and didn't just set `config_file` to\n # the string \"config.yaml\".\n if (config_file == \"config.yaml\")\n Kernel.abort(\"ERROR: Could not find 'config.yaml'. Are you running Rake \"\\\n \"from the correct directory?\")\n end\n\n # Move into the Hugo destination directory, so file names are only prefixed\n # with \"./\"\n Dir.chdir(File.join(Dir.pwd, \"#{$hugo_dest}\"))\n\n # Generate a list of every file in $hugo_dest, and `map` them into the form,\n # [[\"«file_name»\", \"«md5sum»\"], ... ]\n puts(\" Aggregating Local Hash List...\")\n local_file_list = Dir[\"./**/*\"]\n .select { |f| File.file?(f) }\n .sort_by { |f| f }\n .map { |f|\n # The file names have a leading `./`. Strip those.\n [f[2..-1], Digest::MD5.file(f).hexdigest] }\n\n\n # Open up a connection to our S3 target bucket\n puts(\" Opening S3 Connection...\")\n aws_bucket = Aws::S3::Bucket.new(ENV['AWS_S3_BUCKET'], {\n :region => \"us-east-1\",\n :access_key_id => ENV['AWS_ACCESS_KEY_ID'],\n :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],\n })\n\n # Fetch all objects from the remote, and `map` them into the form,\n # [[\"«file_name»\", \"«md5sum»\"], ... ]\n puts(\" Fetching Remote Object List (this may take up to ~30 seconds)...\")\n aws_file_list = aws_bucket\n .objects()\n .sort_by { |objs| objs.key }\n .map { |objs|\n # the etag (which is the md5sum) is wrapped in double-quotes. Strip those\n # by 'translating' them into empty strings.\n [objs.key, objs.etag.tr('\"','')] }\n\n\n # Now that we have the two lists, we need to compare them and generate the\n # list of files we need to upload, and the list of files we need to delete.\n # To do this, we're going to use some brute force.\n puts(\" Comparing Object Hashes...\")\n new_list = []\n updated_list = []\n delete_list = []\n lcl_i = 0\n aws_i = 0\n lcl_len = local_file_list.length\n aws_len = aws_file_list.length\n progress = ProgressBar.new(\" Hash check\", lcl_len)\n while true\n # Check if we've reached the end of either list and should break\n break if (lcl_i == lcl_len || aws_i == aws_len)\n lcl_file_name = local_file_list[lcl_i][0]\n aws_file_name = aws_file_list[aws_i][0]\n\n # Compare the file/object names\n case lcl_file_name <=> aws_file_name\n when 0 # File names are identical\n # Compare md5sums. If they don't match, add the file to the updated list.\n if (local_file_list[lcl_i][1] != aws_file_list[aws_i][1])\n updated_list.push(lcl_file_name)\n end\n # In either case, increment both index variables\n lcl_i += 1; progress.inc\n aws_i += 1\n when -1 # Local file name sorts first...\n # The local file doesn't exist on AWS. Add it to the new list.\n new_list.push(lcl_file_name)\n # And only increment the local index variable.\n lcl_i += 1; progress.inc\n when 1 # AWS object name sorts first...\n # The AWS object doesn't (or no longer) exist in the locally built\n # artifacts. Schedule it for deletion.\n delete_list.push(aws_file_name)\n # And only increment the aws index variable.\n aws_i += 1\n end\n end\n\n # If we're not at the end of the local file list, we need to add any new files\n # to the new list.\n while (lcl_i < lcl_len)\n new_list.push(local_file_list[lcl_i][0])\n lcl_i += 1; progress.inc\n end\n\n # If we're not at the end of the aws object list, we need to add those file to\n # the delete list.\n while (aws_i < aws_len)\n delete_list.push(aws_file_list[aws_i][0])\n aws_i += 1\n end\n progress.finish\n\n upload_list = updated_list + new_list\n\n puts(\" Hash Check complete\")\n puts(\" #{new_list.length} new files, and #{updated_list.length} updated..\")\n puts(\" #{upload_list.length} files need to be uploaded to the remote\")\n puts(\" #{delete_list.length} files need to be deleted from the remote\")\n current_time = Time.now.getutc.to_s.gsub(\" \",\"_\")\n File.open(\"new_file_list-#{current_time}.txt\", \"w+\") do |f|\n f.puts(new_list)\n end\n File.open(\"updated_file_list-#{current_time}.txt\", \"w+\") do |f|\n f.puts(upload_list)\n end\n File.open(\"deleted_list-#{current_time}.txt\", \"w+\") do |f|\n f.puts(delete_list)\n end\n\n\n # Upload the files in the upload updated and new lists, and delete the files\n # in the delete list.\n if (upload_list.length > 0)\n puts(\" Uploading files...\")\n progress = ProgressBar.new(\" Uploads\", upload_list.length)\n upload_list.each { |obj_path|\n #TODO: Generate a log of the uploaded files?\n #TODO: Error checking.\n #TODO: Stop publishing read/write.\n aws_bucket.put_object({\n acl: \"public-read-write\",\n key: obj_path,\n body: File.open(obj_path)\n })\n progress.inc\n }\n progress.finish\n else\n puts(\" No files to upload...\")\n end\n\n if (delete_list.length > 0)\n delete_list.each_slice(1000).with_index do |slice, index|\n index_from = index * 1000\n index_to = ((index+1)*1000) < delete_list.length ? ((index+1)*1000) : delete_list.length\n puts(\" Requesting Batch Delete for objects #{index_from}-#{index_to}...\")\n # Generate a Aws::S3::Types::Delete hash object.\n delete_hash = {\n delete: {\n objects: slice.map{ |f| { key: f } },\n quiet: false\n }\n }\n #TODO: Generate a log of the deleted files?\n begin\n response = aws_bucket.delete_objects(delete_hash)\n rescue Exception => e\n require 'pp'\n Kernel.abort(\"ERRROR: Batch Deletion returned with errors.\\n\"\\\n \" Delete Hash Object:\\n\"\\\n \"#{pp(delete_hash)}\\n\"\\\n \" Error message:\\n\"\\\n \"#{e.message}\")\n end\n if (response.errors.length > 0)\n require 'pp'\n Kernel.abort(\"ERRROR: Batch Deletion returned with errors\\n\"\\\n \" Delete Hash Object:\\n\"\\\n \"#{pp(delete_hash)}\\n\"\\\n \" Response Object:\\n\"\\\n \"#{pp(response)}\")\n end\n end\n else\n puts(\" No files to delete...\")\n end\n\n # Fetch and rewrite the S3 Routing Rules to make sure the 'latest' of every\n # project correctly re-route.\n puts(\" Configuring S3 Bucket Website redirect rules...\")\n\n # Open an S3 connection to the Bucket Website metadata\n aws_bucket_website = Aws::S3::BucketWebsite.new(ENV['AWS_S3_BUCKET'], {\n :region => \"us-east-1\",\n :access_key_id => ENV['AWS_ACCESS_KEY_ID'],\n :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],\n })\n\n # Build the routing rules based on the config.yaml's 'project_descripts'. One\n # routing rule per project.\n routing_rules = []\n config_file['params']['project_descriptions'].each do |project, description|\n path = description['path']\n archived_path = description['archived_path']\n ver = description['latest']\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{archived_path}/latest/\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{archived_path}/latest\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{path}/latest/\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{path}/latest\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n end\n #TODO: We need to implement some way of adding arbitrary routing rules. Maybe\n # add a section in config.yaml that's just a JSON string that we parse?\n riak_path = config_file['params']['project_descriptions']['riak_kv']['path']\n riak_ver = config_file['params']['project_descriptions']['riak_kv']['latest']\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"riakee/latest/\" },\n :redirect => { :replace_key_prefix_with => \"#{riak_path}/#{riak_ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"riakee/latest\" },\n :redirect => { :replace_key_prefix_with => \"#{riak_path}/#{riak_ver}\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"riakts/\" },\n :redirect => { :replace_key_prefix_with => \"riak/ts/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n\n new_website_configuration = {\n :error_document => {:key => \"404.html\"},\n :index_document => aws_bucket_website.index_document.to_hash,\n :routing_rules => routing_rules\n }\n\n aws_bucket_website.put({ website_configuration: new_website_configuration })\n\n # Invalidate any files that were deleted or modified.\n cf_client = SimpleCloudfrontInvalidator::CloudfrontClient.new(\n ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'],\n ENV['AWS_CLOUDFRONT_DIST_ID'])\n invalidation_list = updated_list + delete_list\n if (invalidation_list.length == 0)\n puts(\" No files to invalidate...\")\n elsif (invalidation_list.length < 500)\n # The invalidation list is sufficiently short that we can invalidate each\n # individual file\n invalidation_list.each_slice(100).with_index do |slice, index|\n index_from = (index*100)\n index_to = ((index+1)*100) < delete_list.length ? ((index+1)*100) : delete_list.length\n puts(\" Sending Invalidation Request for objects #{index_from}-#{index_to}...\")\n cf_report = cf_client.invalidate(slice)\n end\n else\n # The invalidation list is large enough that we should skip getting charged\n # and invalidate the entire site.\n puts(\" Sending Invalidation Request for the entire site (\\\"/*\\\")...\")\n cf_report = cf_client.invalidate(['/*'])\n end\n\n puts(\"\")\n puts(\"Deploy Process Complete!\")\n puts(\"========================================\")\nend", "def create_deployment_file(host, provision_id, provision_name)\n ssh_key = try_read_file(host['connection']['public_key'])\n config = Base64.strict_encode64(host['configuration'].to_yaml)\n\n Nokogiri::XML::Builder.new do |xml|\n xml.HOST do\n xml.NAME \"provision-#{SecureRandom.hex(24)}\"\n xml.TEMPLATE do\n xml.IM_MAD host['im_mad']\n xml.VM_MAD host['vm_mad']\n xml.PM_MAD host['provision']['driver']\n xml.PROVISION do\n host['provision'].each do |key, value|\n if key != 'driver'\n xml.send(key.upcase, value)\n end\n end\n xml.send('PROVISION_ID', provision_id)\n xml.send('NAME', provision_name)\n end\n if host['configuration']\n xml.PROVISION_CONFIGURATION_BASE64 config\n end\n xml.PROVISION_CONFIGURATION_STATUS 'pending'\n if host['connection']\n xml.PROVISION_CONNECTION do\n host['connection'].each do |key, value|\n xml.send(key.upcase, value)\n end\n end\n end\n if host['connection']\n xml.CONTEXT do\n if host['connection']['public_key']\n xml.SSH_PUBLIC_KEY ssh_key\n end\n end\n end\n end\n end\n end.doc.root\n end", "def deploySource\n verifyOS\n timeDate = Time.new\n vConfig(CONFIG['configWebsite'])\n read_json(CONFIG['configWebsite'])\n branchSource = @parse_json_config['deploy']['branch']['source']\n msgCommit = @parse_json_config['deploy']['github']['config']['commit']\n add_repo_git(\".\")\n add_remoteurl(\".\")\n pull_execute(branchSource, \".\")\n git_checkout(branchSource, \".\")\n system_commands(\"echo Deploy source files. Wait ...\")\n system_commands(\"git add .\")\n system_commands(\"git commit -m \\\"#{msgCommit} - #{timeDate.inspect}\\\"\")\n system_commands(\"git push origin -u #{branchSource}\")\n end", "def config_creates_file(_new_resource)\n return 'Makefile'\n end", "def config_creates_file(_new_resource)\n return 'Makefile'\n end", "def create_migration_file\n migration_template \"migration.rb\", \"db/evolver/migrations/#{file_name}.rb\"\n end", "def install\n run \"bundle exec backup generate:config --config-path=config/backup\" unless File.exists?(\"config/backup/config.rb\")\n template \"general.rb\", \"config/backup/models/general.rb\"\n if File.exists? \".env\"\n append_file \".env\" do\n File.read(File.expand_path(find_in_source_paths('env.env')))\n end\n else\n template \"env.env\", \".env\"\n end\n run \"bundle exec wheneverize .\" unless File.exists?(\"config/schedule.rb\")\n append_file \"config/schedule.rb\" do\n File.read(File.expand_path(find_in_source_paths('schedule.rb')))\n end\n end", "def deploy\n @operation = \"Deploy\"\n build_env = project[:build_env] || \"\"\n\n prepare_local_dir do\n run_cmd \"cap -q deploy #{build_env}\"\n run_cmd \"cap -q deploy:migrate #{build_env}\"\n run_cmd \"cap -q deploy:cleanup #{build_env}\"\n end\n end", "def setup_files\n create_application_rb\n create_production_rb\n end", "def deploy_application\n deploy(selfdir + \"app\")\n end", "def create_template_dot_rb\n\tsystem('touch template.rb')\n\tfile = File.open('template.rb', 'w')\n\tfile.puts(\"require 'pry'\")\n\tfile.puts(\"require 'dotenv'\")\n\tfile.puts('')\n\tfile.puts(\"Dotenv.load('.env')\")\n\tfile.close\nend" ]
[ "0.6970038", "0.6962869", "0.6623345", "0.65806484", "0.65737057", "0.65652597", "0.6427499", "0.6423631", "0.6407566", "0.6308319", "0.62779796", "0.6220729", "0.62163943", "0.616739", "0.616618", "0.61655045", "0.61511856", "0.61434823", "0.61416054", "0.614039", "0.6121951", "0.6121501", "0.61026096", "0.61026096", "0.6098765", "0.60593575", "0.6058807", "0.605616", "0.60469824", "0.60440457" ]
0.7492605
0
Select version for :rvm_ruby_string Read `rvm list` and set as default rvm version that is current now.
def ruby_version default = %x{ rvm current}.strip items = %x{ rvm ls strings }.split.compact ruby = menu_with_default "RVM Ruby version to use for deployment:", items,default ruby = ask "Enter alternative RVM Ruby string: " if ruby =~ /Other/ ruby end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def determine_rvm_ruby_if_not_given\n if node['rvm_passenger']['rvm_ruby'].nil?\n rvm_ruby = node['rvm']['default_ruby']\n rvm_ruby += \"@passenger\" unless rvm_ruby == \"system\"\n\n node.set['rvm_passenger']['rvm_ruby'] = rvm_ruby\n Chef::Log.debug(%{Setting node['rvm_passenger']['rvm_ruby'] = } +\n %{\"#{node['rvm_passenger']['rvm_ruby']}\"})\n end\n end", "def prompt_ruby_version\n if yes?(\"Are you using RVM?\")\n # rubocop:disable Metrics/LineLength\n if yes?(\"Would you like to create a RVM gemset, #{@app_name}, for this app?[y|yes] \")\n # rubocop:enable Metrics/LineLength\n template('rvmrc.tt','.rvmrc', {app_name: @app_name})\n else\n puts \"Using the default gemset\"\n run(\". ${rvm_path:-$HOME/.rvm}/environments/default\")\n end\n end\n end", "def ruby_version(v)\n @ruby_version = v\n end", "def rvm_ruby\n @@env.expanded_name.match(/([\\w\\-\\.]+)/)[1]\n end", "def get_rbvm(arg = nil, existing = nil)\n if arg.nil?\n rbvm = new(ENV['rbvm_ruby_specification'])\n else \n rbvm = new(arg, existing)\n if !rbvm.valid?\n if ENV['rbvm_ruby_specification']\n ruby_str = ENV['rbvm_ruby_specification'].split(env.gemset_separator)[0]\n else\n ruby_str = new('default').ruby_string\n end\n rbvm = new(\"#{ruby_str}#{env.gemset_separator}#{arg}\", existing)\n end\n end\n return rbvm\n end", "def reset_rvm\n @@env.use!(@@rvm_original_env)\n end", "def maglev_using_rvm\n ENV['rvm_path'] != \"\" && (/^maglev/ =~ ENV['rvm_ruby_string']) == 0\nend", "def maglev_using_rvm\n ENV['rvm_path'] != \"\" && (/^maglev/ =~ ENV['rvm_ruby_string']) == 0\nend", "def initialize(str = nil, existing = nil)\n\n @system_ruby = false\n self.env_output = {}\n str = get_alias(str)\n\n case str\n when 'system'\n @system_ruby = true\n return\n\n when '', nil\n if existing\n # find version from existing rubies\n @interpreter, @version, @patchlevel, @gemset =\n parse_ruby_string(get_existing_ruby(config_db(\"interpreter\")))\n else\n @interpreter = config_db(\"interpreter\")\n @version = config_db(interpreter, \"version\")\n @patchlevel = config_db(interpreter, version, \"patchlevel\")\n end\n\n else\n @interpreter, @version, @patchlevel, @gemset = parse_ruby_string(str)\n\n if interpreter.nil? && version\n case version\n when /^1\\.(8\\.[6-7]|9\\.[1-3])$/\n @interpreter = \"ruby\"\n when /^1\\.[3-6].*$/\n @interpreter = \"jruby\"\n when /^1\\.[0-2]\\.\\d$/\n @interpreter = \"rbx\"\n when /^\\d*$/\n @interpreter = \"maglev\"\n when /^0\\.8|nightly$/\n @interpreter = \"macruby\"\n end\n elsif interpreter.nil? && version.nil?\n log(\"Ruby string not understood: #{str}\", \"debug\")\n end\n\n if !interpreters.include?(interpreter)\n log(\"Invalid ruby interpreter: #{interpreter}\", \"debug\")\n end\n\n if existing\n i, v, p, g = parse_ruby_string(get_existing_ruby(str))\n @version ||= v\n @patchlevel ||= p\n else\n @version ||= config_db(interpreter, \"version\")\n @patchlevel ||= config_db(interpreter, version, \"patchlevel\")\n end\n end\n\n # TODO use existing to pick suitable ruby if specified\n\n @ruby_string = \"#{interpreter}\"\n @ruby_string += \"-#{version}\" if version\n if patchlevel\n if interpreter == \"ruby\"\n @patchlevel.delete!('p')\n @ruby_string += \"-p#{patchlevel}\"\n else\n @ruby_string += \"-#{patchlevel}\"\n end\n end\n\n @ruby_home = File.join(env.path, \"rubies\", ruby_string)\n @gem_base = File.join(env.gems_path, ruby_string)\n if gemset\n @gem_home = \"#{gem_base}#{env.gemset_separator}#{gemset}\"\n else\n @gem_home = gem_base\n end\n @global_gem_home = \"#{gem_base}#{env.gemset_separator}global\"\n @gem_path = \"#{gem_home}:#{global_gem_home}\"\n\n # TODO why aren't some interpreters in config/known?\n if !known?\n log(\"Unknown ruby specification: #{str} -> #{ruby_string}. Proceeding...\", \"debug\")\n end\n if !valid?\n reset\n @ruby_string = str\n log(\"Invalid ruby specificiation: #{str}\", \"debug\")\n return\n elsif existing && !installed?\n reset\n @ruby_string = str\n log(\"No installed ruby with specificiation: #{str}\", \"debug\")\n return\n end\n end", "def runtime_version(arg = nil)\n set_or_return(:runtime_version, arg, kind_of: [String])\n end", "def default_version=(v)\n @default_version = v\n end", "def version_from_ruby_version_file\n shell_return = run_shell(\"cat .ruby-version\")\n shell_return.nil? ? nil : shell_return.stdout\n end", "def ruby_version=(value)\n normalize_version(value).tap do |version|\n @ruby_version = @options['ruby_version'] = version\n @ruby_parser = parser_for_version version\n end\n end", "def list_default\n normalize rvm(:list, :default, :string).stdout\n end", "def latest_mri_ruby\n \"ruby-3.2\"\n end", "def ruby_version\n @ruby_version ||= begin\n version = @options['ruby_version'] || RUBY_VERSION\n normalize_version version\n end\n end", "def set_version(version)\n file_sub(GEMSPEC, /(\\.version\\s*=\\s*).*/, \"\\\\1'#{version}'\")\n file_sub(VERSION_RB, /^(\\s*VERSION\\s*=\\s*).*/, \"\\\\1'#{version}'\")\nend", "def vbox_version\n command=\"#{@vboxcmd} --version\"\n shell_results=shell_exec(\"#{command}\",{:mute => true})\n version=shell_results.stdout.strip.split(/[^0-9\\.]/)[0]\n return version\n end", "def path_to_bin_rvm(options={})\n result = File.join(rvm_bin_path, \"rvm\")\n result << \" #{options[:with_ruby]} do\" if options[:with_ruby]\n result\n end", "def choose_version(version)\n if version =~ /(\\d+)\\.(\\d+)\\.(\\d+)/\n major = $1\n minor = $2\n patch = $3\n if config[:major]\n major = major.to_i + 1\n minor = 0\n patch = 0\n end\n if config[:minor]\n minor = minor.to_i + 1\n patch = 0\n end\n patch = patch.to_i + 1 if config[:patch]\n version = \"#{major}.#{minor}.#{patch}\"\n Chef::Log.debug(\"New version is #{version}\")\n else\n Chef::Log.error(\"Version is in a format I cannot auto-update\")\n exit 1\n end\n version\n end", "def read_ruby_version vim\n script = %{require \"rbconfig\"; print File.join(RbConfig::CONFIG[\"bindir\"], RbConfig::CONFIG[\"ruby_install_name\"])}\n version = `#{vim} --nofork --cmd 'ruby #{script}' --cmd 'q' 2>&1 >/dev/null | grep -v 'Vim: Warning'`.strip\n version unless version.empty? or version.include?(\"command is not available\")\nend", "def read_ruby_version vim\n script = %{require \"rbconfig\"; print File.join(RbConfig::CONFIG[\"bindir\"], RbConfig::CONFIG[\"ruby_install_name\"])}\n version = `#{vim} --nofork --cmd 'ruby #{script}' --cmd 'q' 2>&1 >/dev/null | grep -v 'Vim: Warning'`.strip\n version unless version.empty? or version.include?(\"command is not available\")\nend", "def v string\n Gem::Version.create string\n end", "def v string\n Gem::Version.create string\n end", "def read_version\n # The version string is usually in one of the following formats:\n #\n # * 4.1.8r1234\n # * 4.1.8r1234_OSE\n # * 4.1.8_MacPortsr1234\n #\n # Below accounts for all of these.\n\n # Note: We split this into multiple lines because apparently \"\".split(\"_\")\n # is [], so we have to check for an empty array in between.\n output = execute(\"--version\")\n if output =~ /vboxdrv kernel module is not loaded/\n raise Vagrant::Errors::VirtualBoxKernelModuleNotLoaded\n elsif output =~ /Please install/\n # Check for installation incomplete warnings, for example:\n # \"WARNING: The character device /dev/vboxdrv does not\n # exist. Please install the virtualbox-ose-dkms package and\n # the appropriate headers, most likely linux-headers-generic.\"\n raise Vagrant::Errors::VirtualBoxInstallIncomplete\n end\n\n parts = output.split(\"_\")\n return nil if parts.empty?\n parts[0].split(\"r\")[0]\n end", "def ruby_version\n lockfile_next_version = Bundler::LockfileParser.new(lockfile_path.read).ruby_version\n\n if lockfile_next_version\n lockfile_next_version.chomp.sub(\"(\", \"\").sub(\")\", \"\").sub(/(p-?\\d+)/, ' \\1').split.join(\"-\")\n else\n super\n end\n end", "def ruby_version\n @ruby_version ||= begin\n version_ = parse(::RUBY_VERSION, :standard)\n if version_.release_type == :final\n version_ = version_.change({:patchlevel => ::RUBY_PATCHLEVEL},\n :patchlevel_required => true, :patchlevel_delim => '-p')\n end\n version_\n end\n end", "def run_rvm_or(command_rvm, command_else = \"true\")\n parallel do |session|\n command_else = reformat_code(command_else)\n if Capistrano.const_defined?(:RvmMethods)\n # command_with_shell is defined in RvmMethods so rvm/capistrano has to be required first\n command_rvm = command_with_shell(reformat_code(command_rvm), fetch(:rvm_shell, \"bash\"))\n rvm_role = fetch(:rvm_require_role, nil)\n if rvm_role # mixed\n session.when \"in?(:#{rvm_role})\", command_rvm\n session.else command_else\n else # only rvm\n session.else command_rvm\n end\n else # no rvm\n session.else command_else\n end\n end\n end", "def setterminalappversion(value)\r\n setvalue(SVTags::TERMINAL_APP_VERSION, value)\r\n end", "def get_virtualbox_version\n\tbegin\n\t\tif windows?\n\t\t\tver = `\"%ProgramFiles%\\\\Oracle\\\\VirtualBox\\\\VBoxManage\" -v 2>NULL`\n\t\telse\n\t\t\tver = `VBoxManage -v 2>/dev/null`\n\t\tend\n\trescue\n\t\tver = ''\n\tend\n\tver.gsub(/r.*/m, '')\nend" ]
[ "0.66422695", "0.6213907", "0.5680196", "0.5555658", "0.5547382", "0.54722476", "0.543302", "0.543302", "0.53790027", "0.53758854", "0.5360697", "0.53086525", "0.5272826", "0.52290076", "0.52015257", "0.5130147", "0.5121873", "0.50862586", "0.5070931", "0.505345", "0.5048456", "0.5048456", "0.5033644", "0.5033644", "0.49787855", "0.4967031", "0.4958055", "0.49530685", "0.49431023", "0.49297264" ]
0.7684294
0
marble 1 is a special case as only two marbles in circle therefore current_marble now points to new marble and vice versa
def handle_one(new_marble) @current_marble.next_marble = new_marble @current_marble.previous_marble = new_marble new_marble.next_marble = @current_marble new_marble.previous_marble = @current_marble @current_marble = new_marble end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_blinds\n @active_players[0].current_bet = @small_blind_value\n @active_players[1].current_bet = @big_blind_value\n @table_current_bet = @active_players[1].current_bet\n @pot_size += @active_players[0].current_bet + @active_players[1].current_bet\n @committed += @pot_size\n @active_players.rotate!(2)\nend", "def spot_mate(mate)\n @fish.direction = @fish.move_towards(mate)\n @fish.status = Pursuing\n @fish.target = mate\n end", "def insert_marble(turn, board)\n\n score = 0\n if turn % 23 == 0\n board = board_skip(board, -7)\n board[:previous][:next] = board[:next]\n board[:next][:previous] = board[:previous]\n marble = board[:value]\n score = turn + marble\n board = board[:next]\n else\n board = board_skip(board, 1)\n new_board = {previous: board, next: board[:next], value: turn}\n board[:next][:previous] = new_board\n board[:next] = new_board\n board = new_board\n\n end\n\n return board, score\nend", "def do_mill\r\n # - - - - - - - - - - - - - - - - - - \r\n max_diam = 4.95\r\n max_radius = max_diam / 2\r\n shaft_support_diam = 0.55\r\n beg_diam = shaft_support_diam\r\n shaft_diameter = 1.0 / 4.0\r\n beg_corr_width = 0.2\r\n growth_factor = 0.09 # 0.12 #0.15 #0.25\r\n degree_increment = 30\r\n wall_thick = 0.015\r\n sweep = 45.0\r\n curr_radius = beg_diam / 2\r\n curr_degree = 0.0\r\n curr_corr_width = beg_corr_width\r\n degree_inc = 4.0\r\n inner_adj_factor = 1.2 #0.8 #0.7 #0.9 #1.2 #2.7 #2.1\r\n material_thickness = 1.0\r\n outer_radius_beg = curr_radius + curr_corr_width\r\n\r\n aCircle = CNCShapeCircle.new(mill,x,y)\r\n aCircle.mill_pocket(x, y, 1.0, depth,shaft_support_diam)\r\n mill.retract() # mill whole for entrance \r\n # of gases from prior chamber but leave\r\n # shaft support area\r\n\r\n aCircle.mill_pocket(x, y, shaft_diameter, 0 - material_thickness.abs)\r\n mill.retract() # mill hole for the shaft\r\n\r\n\r\n\r\n while true\r\n end_degree = curr_degree + sweep\r\n end_corr_width = curr_corr_width + (curr_corr_width * growth_factor)\r\n\r\n outer_radius_end = curr_radius + end_corr_width\r\n\r\n inner_rad_end = curr_radius + (curr_radius * growth_factor * inner_adj_factor)\r\n\r\n inner_adj_factor = inner_adj_factor * 0.97\r\n\r\n arc_segment_pocket_adv(mill, x,y,\r\n curr_radius, \r\n outer_radius_beg,\r\n curr_degree,\r\n inner_rad_end, \r\n outer_radius_end, \r\n end_degree, \r\n 0,\r\n depth,\r\n degree_inc)\r\n\r\n curr_degree += sweep\r\n curr_corr_width = end_corr_width\r\n\r\n curr_radius = inner_rad_end\r\n\r\n outer_radius_beg = outer_radius_end\r\n\r\n if (outer_radius_end > max_radius)\r\n break\r\n end #if\r\n\r\n\r\n\r\n\r\n end #while\r\n end", "def update_mate(_mate, _edge, _val)\n m = _mate\n\n # add no edge\n return m if _val == 0\n\n # ad an edge\n a = _edge[0]\n b = _edge[1]\n\n if m.mate[a] == nil && m.mate[b] == nil # a, b are new terminal\n m.mate[a] = b\n m.mate[b] = a\n elsif m.mate[a] == nil # a is a new terminal\n t = m.mate[b]\n m.mate[a] = t\n m.mate[t] = a if m.mate[t] != nil\n m.mate[b] = 0\n elsif m.mate[b] == nil # b is a new terminal\n t = m.mate[a]\n m.mate[b] = t\n m.mate[t] = b if m.mate[t] != nil\n m.mate[a] = 0\n else # a, b, are not a new terminal\n t = m.mate[a]\n s = m.mate[b]\n m.mate[a] = 0\n m.mate[b] = 0\n m.mate[s] = t if m.mate[s] != nil\n m.mate[t] = s if m.mate[t] != nil\n end\n\n return m\n end", "def maybe_promote\n if @color == :black && @position[0] == 0\n @king = true\n elsif @color == :red && @position[0] == 7\n @king = true\n end\n end", "def mate(mate)\n @mate_count += 1\n @status = Idle\n @target = nil\n @virility = 0\n return mate.lay_egg\n end", "def mill_fan_pocket(mill, cent_x, cent_y, in_radius,in_beg_deg, in_end_deg, out_radius, out_beg_deg, out_end_deg, pBeg_z, pEnd_z, bit_adjust = false, auto_retract=true, mill_outer_edge=false)\r\n# # # # # # # # # # # # # # # # # # # \r\n # start as center and \r\n \r\n #print \"(mill_fan_pocket_s cent_x=\", cent_x, \" cent_y=\", cent_y, \" in_radius=\", in_radius, \" in_beg_deg=\", in_beg_deg, \" in_end_deg=\", in_end_deg, \" out_radius=\", out_radius, \" out_beg_deg=\", out_beg_deg, \" out_end_deg=\", out_end_deg, \" pBeg_z = \", pBeg_z, \"pEndZ=\", pEnd_z, \" bit_adjust=\", bit_adjust, \" auto_retract=\", auto_retract, \")\\n\"\r\n \r\n if (pBeg_z > 0)\r\n pBeg_z = 0 - pBeg_z\r\n end\r\n if (pEnd_z > 0)\r\n pEnd_z = 0 - pEnd_z\r\n end\r\n \r\n if (in_end_deg < in_beg_deg)\r\n in_end_deg = in_beg_deg\r\n end\r\n \r\n if (out_end_deg < out_beg_deg)\r\n out_end_deg = out_beg_deg\r\n end\r\n \r\n cent_x += 0.0\r\n cent_y += 0.0\r\n \r\n if (bit_adjust == true)\r\n in_radius += mill.bit_diam\r\n out_radius -= mill.bit_radius\r\n end \r\n if (in_radius > out_radius)\r\n out_radius = in_radius\r\n end\r\n \r\n pass_inc = degrees_for_distance(out_radius, mill.cut_inc*2.0)\r\n \r\n curr_in_deg = in_beg_deg\r\n curr_out_deg = out_beg_deg\r\n last_in_deg = -99\r\n cnt = 0\r\n \r\n tSpeed = mill.speed()\r\n tCutDepthInc = mill.cut_depth_inc()\r\n tPlungSpeed = mill.plung_speed()\r\n mill.set_speed(tSpeed * 0.8)\r\n mill.set_cut_depth_inc(tCutDepthInc * 0.8)\r\n mill.set_plung_speed(tPlungSpeed * 0.5)\r\n while (true)\r\n cnt += 1\r\n \r\n arc_to_radius(mill, cent_x, cent_y, in_radius, \r\n curr_in_deg, out_radius, curr_out_deg,\r\n pBeg_z, pEnd_z)\r\n \r\n mill.set_speed(tSpeed * 1.8)\r\n mill.set_cut_depth_inc(tCutDepthInc * 1.0) \r\n mill.set_plung_speed(tPlungSpeed)\r\n\r\n \r\n if (curr_in_deg == in_end_deg) && (curr_out_deg == out_end_deg)\r\n break\r\n else \r\n curr_in_deg += (pass_inc * 0.3)\r\n curr_out_deg += pass_inc\r\n if (curr_out_deg > out_end_deg)\r\n curr_out_deg = out_end_deg\r\n end\r\n if (curr_in_deg > in_end_deg)\r\n curr_in_deg = in_end_deg\r\n end \r\n end #else \r\n end # while \r\n \r\n if (mill_outer_edge == true)\r\n arc_radius(mill, cent_x, cent_y, out_radius, \r\n out_beg_deg, out_end_deg,\r\n pBeg_z, pEnd_z)\r\n end\r\n \r\n mill.set_speed(tSpeed)\r\n mill.set_cut_depth_inc(tCutDepthInc)\r\n mill.set_plung_speed(tPlungSpeed)\r\n if (auto_retract == true)\r\n mill.retract()\r\n end\r\n \r\n\r\nend", "def update_turning_ball\n @ball.update_anim\n end", "def nxt_meat\n\t# Get the index of the next meat\n\ttmp_index = ($meat.index(get_meat) + 1).modulo($meat.length)\n\t\n\t# Move to the next meat pair\n\t$cur_meat = $meat[tmp_index]\nend", "def update_circle(circle)\n circle.update(part_of_bingo: true)\n end", "def set_original_value(left_bank, right_bank, boat, m, c)\n boat.in_left_bank = !boat.in_left_bank\n if boat.in_left_bank == true\n left_bank.m_no += m\n left_bank.c_no += c\n right_bank.m_no -= m\n right_bank.c_no -= c\n else\n right_bank.m_no += m\n right_bank.c_no += c\n left_bank.m_no -= m\n left_bank.c_no -= c\n end\nend", "def check_for_mate\n if @board.in_checkmate?( match.next_to_move )\n match.active = false\n match.winner = (match.next_to_move==:white ? match.player2 : match.player1)\n match.save\n end\n end", "def current_player_effect\n # Retire 1 au nombre de cartes a piocher du joueur en cours\n if @current_player.draw_card_count >= 1\n @current_player.draw_card_count -= 1\n end\n # Enleve une carte mixed de la main du joueur en cours\n @current_player.cards.delete_at(@current_player.cards.index(\"lock_down\"))\n end", "def work\n unmark_circles_part_of_bingo\n check_marked_circles\n @card.update(num_bingos: get_num_bingos)\n @card.num_bingos\n end", "def update_last_used_marble(id, event, name, marble, bot)\n if(marble.eql?(\"\"))\n event.respond \"<@#{event.author.id}>, which marble did #{name} use?\\nIf I don't confirm, try again.\"\n last_marble = \"\"\n cancel = false\n while(last_marble.eql? \"\")\n # wait a minute for a reply\n reaction_event = bot.add_await!(Discordrb::Events::MessageEvent, {timeout: 60})\n # check for timeout\n if reaction_event\n # make sure the message is by who we asked\n if reaction_event.author.id.eql?(event.author.id)\n # remove all spaces and symbols, matching card_stats format\n\t\t\t\t\t# temp disable of this if: allows any field for last card used\n if true || @card_stats[reaction_event.content.gsub(/[^\\w\\d]/, \"\").capitalize] > 0\n # filter out newlines from the response\n last_marble = reaction_event.content.gsub(\"\\n\", \"\") \n else\n event.respond \"No marble found matching #{reaction_event.content}. Please try again.\"\n end\n end\n else\n event.respond \"Timed out.\"\n last_marble = \"unknown\"\n end\n end\n else\n last_marble = marble\n end\n event.respond \"Set last used marble for #{name } to #{last_marble}!\"\n # need to get marbles to be able to recreate the file\n marbles = \"\"\n File.open(\"#{get_tourney_dir(id)}/#{name}.record\", \"r\") do |f|\n marbles = f.read.split(\"\\n\")[1].gsub(/(Entered cards: )|,/,\"\")\n end\n # split string into array [\"marble1\", \"marble2\", ...]\n marbles = marbles.split\n # recreate the record file string, with a new line indicating last used marble\n new_file_string = create_file_string(name, marbles)\n new_file_string << \"\\nLast used marble: #{last_marble}\"\n File.open(\"#{get_tourney_dir(id)}/#{name}.record\", \"w\") do |f|\n f.puts(new_file_string)\n end\nend", "def set_makrana_marble\n @makrana_marble = MakranaMarble.find(params[:id])\n end", "def current_clown; end", "def current_clown; end", "def as_blue\n @blue += 1\n end", "def set_next_meat(mtt)\n\t# Check if the next meat to eat is valid\n\t#check_meat(mtt)\n\t\n\t$cur_meat = mtt\nend", "def prev_actor_command()\n @actor_index += $game_party.members.size - 1\n @actor_index %= $game_party.members.size\n $scene = Scene_Status.new(@actor_index)\n end", "def do_mill_s(tmp_depth)\r\n # - - - - - - - - - - - - -\r\n tmp_max_diam = @diam\r\n if (@cutter_comp == true)\r\n tmp_max_diam -= @mill.bit_radius\r\n end #if\r\n if @pocket_flat == false\r\n curr_diam = tmp_max_diam\r\n # we only need on circle \r\n # rather than spiraling\r\n else\r\n curr_diam = bit_radius\r\n end #if\r\n while true\r\n mill_polygon(\r\n mill = @mill,\r\n cent_x = @x,\r\n cent_y = @y,\r\n diam = curr_diam,\r\n no_sides = @num_sides,\r\n depth = tmp_depth,\r\n cutter_comp = false)\r\n if (curr_diam == tmp_max_diam)\r\n # we are done milling because\r\n # we got an exact match on\r\n # our target diameter\r\n break\r\n end\r\n curr_diam += mill.cut_increment\r\n if (curr_diam > tmp_max_diam)\r\n curr_diam = tmp_max_diam\r\n end #if\r\n end #while\r\n end", "def next_man(current_man_kill, kill_step, population)\n (current_man_kill + kill_step) % population\nend", "def add_first_mate\n @player3 = Cruiser.new self, 0x990000ff\n @player3.warp_to 400, 400\n \n @controls << Controls.new(self, @player3,\n Gosu::Button::KbLeft => :left,\n Gosu::Button::KbRight => :right,\n Gosu::Button::KbUp => :full_speed_ahead,\n Gosu::Button::KbDown => :reverse,\n Gosu::Button::Kb0 => :revive\n )\n \n @players << @player3\n \n register @player3\n end", "def prev_actor\n @actor_index += $game_party.members.size - 1\n @actor_index %= $game_party.members.size\n $scene = Scene_Status.new(@actor_index)\n end", "def kick_bomb(bomb)\n bomb_manager.getBomb(bomb).moveTo(@new_x, @new_y)\n #or bomb.moveTo(:direction)\n end", "def pocketed? args, ball\n ball_center_x = ball[:x] + args.state.ball_diameter / 2\n ball_center_y = ball[:y] + args.state.ball_diameter / 2\n pocket_radius = args.state.pocket_diameter / 2\n args.state.pockets.each do |pocket|\n # add pocket radius to get to the cetner of the pocket\n dist = (((ball_center_x - (pocket[0] + pocket_radius)) ** 2) + ((ball_center_y - (pocket[1] + pocket_radius)) ** 2)) ** (1/2)\n if dist < pocket_radius\n case ball[:type]\n\n # if eight ball pocketed, win if the player pocketed all other balls\n when 8\n args.state.player1_type ||= 0\n # get the player's type\n if args.state.player == 0\n player_type = args.state.player1_type\n else\n player_type = 1 - args.state.player1_type\n end\n # if all of the player's group have been pocketed, win. Otherwise lose and reset.\n if player_type == 0 && args.state.pocketed_solids == 7\n args.state.won = true\n elsif player_type == 1 && args.state.pocketed_stripes == 7\n args.state.won = true\n else\n reset args\n end\n\n # if cueball pocketed, scratch and set it invisible \n when \"cueball\"\n if args.state.movement_mode != \"scratch\"\n args.state.movement_mode = \"scratch\"\n cueball = args.state.cueball\n cueball[:velX] = 0\n cueball[:velY] = 0\n cueball[:path] = \"sprites/invisible.png\"\n end\n \n # otherwise, it's a stripe or solid, so put it in the list of balls pocketed this turn.\n # if it was the called ball and pocket, this was a successful call\n else\n args.state.sunk = true\n args.state.pocketed_this_turn << ball\n args.state.balls.delete(ball)\n if args.state.called_shot\n called_pocket = args.state.called_pocket[0] == pocket[0] && args.state.called_pocket[1] == pocket[1]\n called_ball = args.state.called_ball[0] == ball[:ball_number]\n if called_ball && called_pocket\n args.state.successful_call = true\n args.state.called_pocket[4] = \"sprites/pocket.png\"\n ball[:path] = \"sprites/ball#{args.state.called_ball[0]}.png\"\n end\n end\n end\n end\n end\nend", "def do_mill()\r\n # - - - - - - - - - - - - - - - - - - - -\r\n #print \"(mill arc segment pocket pBeg_angle=\", pBeg_angle, \" pEnd_angle=\", pEnd_angle, \" pDepth = \", pDepth, \" @pDepth=\", @pDepth, \")\\n\"\r\n check_parms()\r\n bit_radius_half = bit_radius / 2\r\n beg_mid_radius = (beg_min_radius + beg_max_radius) / 2.0\r\n end_mid_radius = (end_min_radius + end_max_radius) / 2.0\r\n cut_inc = mill.cut_inc\r\n\r\n curr_depth = beg_depth\r\n if (curr_depth < 0)\r\n curr_depth = 0\r\n end #if\r\n \r\n lbeg_min_radius = beg_min_radius + mill.bit_radius\r\n lbeg_max_radius = beg_max_radius + mill.bit_radius\r\n \r\n if (mill.cz < beg_depth)\r\n mill.retract(beg_depth)\r\n end #if\r\n \r\n #mill.retract()\r\n while (true) # depth \r\n # print \"(mill arc pocket curr_depth=\", curr_depth, \" depth=\", depth, \")\\n\" \r\n cibr = beg_mid_radius - mill.cut_inc\r\n cier = end_mid_radius - mill.cut_inc\r\n cmbr = beg_mid_radius + mill.cut_inc\r\n cmer = end_mid_radius + mill.cut_inc \r\n while(true) # radius\r\n next_depth = curr_depth - (mill.cut_depth_inc)\r\n if (next_depth < depth)\r\n next_depth = depth\r\n degree_per_step = 7.0 \r\n else\r\n degree_per_step = 1.0\r\n end\r\n \r\n \r\n if (cibr < beg_min_radius)\r\n cibr = beg_min_radius\r\n end #if\r\n \r\n if (cier < end_min_radius)\r\n cier = end_min_radius\r\n end # if\r\n \r\n if (cmbr > beg_max_radius)\r\n cmbr = beg_max_radius\r\n end\r\n \r\n if (cmer > end_max_radius)\r\n cmer = end_max_radius\r\n end #if\r\n \r\n #cp = calc_point_from_angle(pcx,pcy, pBeg_angle, cibr) \r\n #mill.move(cp.x, cp.y)\r\n #mill.plung(pDepth)\r\n \r\n \r\n \r\n changing_radius_curve(mill, \r\n pcx = x,\r\n pcy = y,\r\n pBeg_radius = cibr,\r\n pBeg_angle = beg_angle, \r\n pBeg_z = curr_depth, \r\n pEnd_radius = cier, \r\n pEnd_angle = end_angle,\r\n pEnd_z = next_depth, \r\n pDegrees_per_step=degree_per_step, \r\n pSkip_z_LT=nil, \r\n pSkip_z_GT=nil,\r\n pAuto_speed_adjust= false)\r\n \r\n #changing_radius_curve(mill, \r\n # pcx = x,\r\n # pcy = y,\r\n # pBeg_radius = cier,\r\n # pBeg_angle = end_angle , \r\n # pBeg_z = next_depth, \r\n # pEnd_radius = cibr, \r\n # pEnd_angle = beg_angle,\r\n # pEnd_z = next_depth, \r\n # pDegrees_per_step=degree_per_step, \r\n # pSkip_z_LT=nil, \r\n # pSkip_z_GT=nil,\r\n # pAuto_speed_adjust= false) \r\n \r\n \r\n #changing_radius_curve(mill, \r\n # pcx = x,\r\n # pcy = y,\r\n # pBeg_radius = cmbr,\r\n # pBeg_angle = beg_angle, \r\n # pBeg_z = curr_depth, \r\n # pEnd_radius = cmer, \r\n # pEnd_angle = end_angle,\r\n # pEnd_z = next_depth, \r\n # pDegrees_per_step=degree_per_step, \r\n # pSkip_z_LT=nil, \r\n # pSkip_z_GT=nil,\r\n # pAuto_speed_adjust= false)\r\n #mill.retract(curr_depth)\r\n changing_radius_curve(mill, \r\n pcx = x,\r\n pcy = y,\r\n pBeg_radius = cmer,\r\n pBeg_angle = end_angle , \r\n pBeg_z = next_depth, \r\n pEnd_radius = cmbr, \r\n pEnd_angle = beg_angle,\r\n pEnd_z = next_depth, \r\n pDegrees_per_step=degree_per_step, \r\n pSkip_z_LT=nil, \r\n pSkip_z_GT=nil,\r\n pAuto_speed_adjust= false) \r\n \r\n #changing_arc(mill, x,y,cibr, beg_angle, cier, end_angle, curr_depth, degree_inc) # mill increasing\r\n #mill.retract()\r\n #changing_arc(mill, x,y,cmer, end_angle, cmbr, beg_angle, curr_depth, degree_inc)\r\n #mill.retract() # mill decreasing\r\n \r\n if ((cibr <= beg_min_radius) &&\r\n (cier <= end_min_radius) &&\r\n (cmbr >= beg_max_radius) &&\r\n (cmer >= end_max_radius))\r\n break\r\n end \r\n \r\n cibr -= cut_inc\r\n cier -= cut_inc\r\n cmbr += cut_inc\r\n cmer += cut_inc\r\n end #while radius\r\n \r\n if (next_depth == depth)\r\n break\r\n else\r\n curr_depth -= mill.cut_depth_inc\r\n if (curr_depth < depth)\r\n curr_depth = depth\r\n end\r\n end #else\r\n \r\n end #while depth\r\n \r\n\r\n end", "def player_position_look_update; end" ]
[ "0.5436185", "0.5421149", "0.53781796", "0.53616744", "0.5361203", "0.5359358", "0.5338134", "0.53157", "0.52958596", "0.5275918", "0.5248879", "0.52173704", "0.5212314", "0.5205426", "0.51766604", "0.516871", "0.51524657", "0.5149014", "0.5149014", "0.51384526", "0.5106753", "0.5092491", "0.5090094", "0.50898546", "0.5089407", "0.50625885", "0.4990236", "0.49618363", "0.49410087", "0.49336755" ]
0.7370659
0
marble with a number divisble by 23 is also a special case
def handle_divisible_by_23(player) player.score += @number marble_to_remove = @current_marble.previous_marble 6.times { marble_to_remove = marble_to_remove.previous_marble } marble_to_remove.previous_marble.next_marble = marble_to_remove.next_marble marble_to_remove.next_marble.previous_marble = marble_to_remove.previous_marble player.score += marble_to_remove.number @current_marble = marble_to_remove.next_marble end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mod11(number); end", "def boredFriends(n)\n n.to_i % 9\nend", "def featured(integer)\n return \"Error: There is no possible number that fulfills those requirements\" if integer >= 9_876_543_210\n counter = integer + 1\n counter += 1 until counter % 7 == 0 && counter.odd?\n \n loop do\n return counter if counter.digits.uniq.size == counter.digits.size\n counter += 14\n end\nend", "def featured(number)\n number += 1\n\n until number % 7 == 0 && number.odd?\n number += 1\n end\n\n loop do\n if number.digits.uniq == number.digits\n return number\n else\n number += 14\n end\n break if number.digits.size > 10\n end\n\n \"Error\"\nend", "def featured(i) # found digits method but only works > v2.4 so...\n i = i - i % 7\n loop do\n i += 7\n list = []\n x = i\n while x > 0 do\n list.unshift(x % 10)\n x /= 10\n end\n if list.length > 9; return \"There is no possible number that fulfills those requirements\" end\n if list == list.uniq; break end\n end \n i\nend", "def featured(integer)\n return \"There is no possible number that fulfills those requirements\" if \n integer >= 9_876_543_210\n integer += 1\n until integer % 7 == 0 && integer.odd? && integer.digits.uniq! == nil\n integer += 1\n end\n integer\nend", "def brut_force_solution\n (1...1000).inject(0){|sum, digit| ((digit % 3 == 0) || (digit % 5 == 0)) ? sum += digit : sum}\nend", "def persistence(n)\n count = 0\n while n > 9 do\n n = n.digits.inject(:*)\n count += 1\n end\n count\nend", "def multisum(number)\n (0..number).select { |num| num % 3 == 0 || num % 5 == 0 }.inject(:+)\nend", "def always_three_again(number)\n\tnumber = (((number + 5) * 2 - 4) / 2 - number).to_s\n\t\nend", "def featured(num)\n divisor = num / 7\n count = 1\n total = 0\n\n until (count > divisor) && (total.odd? && total > num) \n total = count * 7\n count += 1\n end\n\n loop do\n number_chars = total.to_s.split('')\n return total if number_chars.uniq == number_chars\n total += 7\n break if num >= 9_876_543_210\n end\n\n 'There is no possible number that fulfills those requirements'\nend", "def kidmod10(base); end", "def featured2(number)\n number += 1\n number += 1 until number.odd? && number % 7 == 0\n\n loop do\n number_chars = number.to_s.split('')\n return number if number_chars.uniq == number_chars\n number += 14\n break if number >= 9_876_543_210\n end\n\n 'There is no possible number that fulfills those requirements.'\nend", "def p206\n re = /1.2.3.4.5.6.7.8.9.0/\n max = Math.sqrt(1929394959697989990).floor\n\n # Round since only squares of multiples of 30 and 70 end with 9_0 (e.g. 900)\n i = round_up Math.sqrt(1020304050607080900).floor, 100\n while i < max\n p30 = (i+30) ** 2\n p70 = (i+70) ** 2\n\n if re === \"#{p30}\"\n return \"#{i+30}^2 = #{p30}\"\n elsif re === \"#{p70}\"\n return \"#{i+70}^2 = #{p70}\"\n end\n\n i += 100\n end\nend", "def fizzbuzz\n# Set counter to 0\n count = 0\n# Count from 0-100, increments of one\n 100.times do\n count = count + 1\n# If the count is modulo 15 return Fizzbuzz\n if count % 15 == 0\n puts \"#{count} fizzbuzz\"\n puts count.to_s + \" fizzbuzz\"\n# if the count is moudulo 3 return Fizz\n elsif count % 3 == 0\n puts \"#{count} fizz\"\n#if the count is modulo 5 return buzz\n elsif count % 5 == 0\n puts \"#{count} buzz\"\n#All other numbers show a 0\n else\n puts count\n end\n end\nend", "def solution(number)\n mul3 = (number - 1) / 3\n mul5 = (number - 1) / 5\n mul15 = (number - 1) / 15\n\n (3 * mul3 * (mul3 + 1) + 5 * mul5 * (mul5 + 1) - 15 * mul15 * (mul15 + 1)) / 2\nend", "def main\n max = 10 ** 9 + 7\n all = 1\n zero = 1\n nine = 1\n zn = 1\n N.times.each do\n all = all * 10 % max\n zero = zero * 9 % max\n nine = nine * 9 % max\n zn = zn * 8 % max\n end\n return (all - zero - nine + zn) % max\nend", "def calculate_check_digit\n sum = digits.first(12).each_with_index.sum do |digit, index|\n index.even? ? digit : (digit * 3)\n end\n remainder = sum % 10\n remainder.zero? ? remainder : (10 - remainder)\n end", "def mult(numero)\n numero.even? ? (numero * 8) : (numero * 9)\nend", "def multisum(number)\n (1..number).select { |multiple| multiple % 3 == 0 || multiple % 5 == 0 }.inject(:+)\nend", "def holes(number)\n holes_per_number = { 0 => 1, 1 => 0, 2 => 0, 3 => 0, 4 => 1, 5 => 0, 6 => 1, 7 => 0, 8 => 2,\n 9 => 1 }\n number.digits.inject(0) { |sum, digit| sum + holes_per_number[digit] }\nend", "def MultiplicativePersistence(num)\n count = 0\n\n while num > 9\n num = num.to_s.split(\"\").map{|i| i.to_i}.inject(:*)\n count += 1\n end\n\n count\nend", "def add_digits(number)\r\n total = 0\r\n number.to_s.split(\"\").each do |n|\r\n total += n.to_i\r\n end\r\n if total.to_s.length > 1\r\n div_by_3(@total)\r\n end\r\n total\r\nend", "def featured(number)\n featured = 0\n loop do \n number += 1\n if number % 7 == 0 &&\n number.odd? &&\n number.to_s.length == number.to_s.chars.uniq.length\n featured = number\n break\n end\n if number.to_s.length > 10\n puts \"Invalid\"\n featured = 0\n break\n end\n end\n featured\nend", "def decent_number(n)\n\tleft = 0\n\tright = 0\n\t(n+1).times do |i|\n\t\tleft = n - i \n\t\tright = n - left\n\t#\tputs \"#{left}%3 = #{left%3} | #{right}%5 = #{right%5}\"\n\t\tbreak if left % 3 == 0 && right % 5 == 0\n\tend\n\t#puts \"**l = #{left} r = #{right}\"\n\n\tif left % 3 == 0 && right % 5 == 0\n\t\tfives = \"5\"*left\n\t\tthrees = \"3\"*right\n\t\tputs fives+threes\n\telse\n\t\tputs -1\n\tend\nend", "def featured(num)\n num += 1\n num += 1 until num.odd? && (num % 7).zero?\n loop do\n return num if num.to_s.chars.size == num.to_s.chars.uniq.size\n num += 14\n break if num > 9_876_543_210\n end\n 'There is no possible number that fulfills those requirements'\nend", "def replace_weight(_test_digits)\n return modulus_weight\n end", "def double_digits\n times_by_2.map do |number|\n if number > 9\n number - 9\n else\n number\n end\n end\nend", "def modulo_of(fraction); end", "def remainder(val); end" ]
[ "0.6814094", "0.6470916", "0.6395678", "0.6326531", "0.6210623", "0.61861664", "0.6173682", "0.6048399", "0.6030718", "0.6029157", "0.60267454", "0.60078794", "0.6000571", "0.5995168", "0.5977118", "0.5974164", "0.59646076", "0.59559613", "0.59425193", "0.5923453", "0.5922196", "0.59173346", "0.59096587", "0.5907872", "0.59063125", "0.5898338", "0.5885429", "0.58846575", "0.58838737", "0.5879681" ]
0.69315016
0
You are given a map in form of a twodimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: Input: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Output: 16 Explanation: The perimeter is the 16 yellow stripes in the image below:
def island_perimeter(grid) perimeter = 0 last_row = grid.length - 1 grid.each_with_index do |row, row_idx| row.each_with_index do |col, col_idx| last_col = row.length - 1 if col == 1 if row_idx == 0 perimeter += 1 else perimeter += 1 if grid[row_idx - 1][col_idx] == 0 end if col_idx == 0 perimeter += 1 elsif row[col_idx - 1] == 0 perimeter += 1 end if col_idx == last_col perimeter += 1 elsif row[col_idx + 1] == 0 perimeter += 1 end if row_idx == last_row perimeter += 1 elsif grid[row_idx + 1][col_idx] == 0 perimeter += 1 end end end end perimeter end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def max_area_of_island(grid)\n area = 0\n (0...grid.size).each do |i|\n (0...grid[0].size).each do |j|\n area = [area, island_area(grid, i, j)].max if grid[i][j] == 1\n end\n end\n area\nend", "def perimeter\n\n return @side_len * 4\n\n end", "def problem(p=1000)\n max = 0\n perimeter = 3\n (p/2..p).each do |i|\n count = 0\n (1..i/2).each do |c|\n sq = c**2\n (((c-1)/2).floor..c-1).each do |b|\n count += 1 if [Math::sqrt(sq-b**2),b,c].sum == i\n end\n end\n if count > max\n max = count \n perimeter = i\n end\n end\n perimeter\n end", "def max_area_of_island(grid)\n return 0 if grid.empty?\n w, h = grid[0].length, grid.length\n max = 0\n (0...h).each do |i|\n (0...w).each do |j|\n if grid[i][j] == 1\n max = [max, search(grid, i, j)].max\n end\n end\n end\n max\nend", "def perimeter\n return @side_length * 4\n end", "def perimeter(length,width)\n (2 * length) + (2 * width)\nend", "def perimeter\n\t\treturn @side_length * 4\n\tend", "def calc_perimeter(len, wid)\n\tperim = (len + wid) * 2\n\treturn perim\nend", "def perimeter\n\t\t4 * @side_length\n\tend", "def measure map, x, y \n if map[x][y] != 'land' || x >= 6 || y >= 6 #Ensures water, counted land, and coordinates\n return 0 #off the grid aren't counted.\n end\n \n size = 1\n map[x][y] = 'counted land' #Marks the starting tile as something bedsides Land. Every tile surrounding the starting tile becomes the \"new starting tile\" as the the recursion happens.\n \n size = size + measure(map, x-1, y-1) #Each of these lines is run again and again until\n size = size + measure(map, x, y-1) #a non-land square is encountered. \n size = size + measure(map, x+1, y-1) #That's the recursive part.\n size = size + measure(map, x-1, y)\n size = size + measure(map, x+1, y)\n size = size + measure(map, x-1, y+1)\n size = size + measure(map, x, y+1)\n size = size + measure(map, x+1, y+1)\n \n size\nend", "def area_or_perimeter(l , w)\n if l === w\n (l * w)\n else \n 2*(l+w)\n end\nend", "def perimeter(length, width)\r\n 2 * (length + width)\r\nend", "def perimeter(length, width)\n return (2 * (length + width))\nend", "def block_perimeter\n\t\t(0..width).each do |i| \n\t\t\t@cells[i][0].type \t\t\t\t= Cell::BLOCKED\n\t\t\t@cells[i][height].type \t= Cell::BLOCKED\n\t\tend\n\t\t(0..height).each do |j| \n\t\t\t@cells[0][j].type \t\t\t\t= Cell::BLOCKED\n\t\t\t@cells[width][j].type \t= Cell::BLOCKED\n\t\tend\n\tend", "def block_perimeter\n (0..width).each do |i|\n @cells[i][0].type = Cell::BLOCKED\n @cells[i][height].type = Cell::BLOCKED\n end\n (0..height).each do |j|\n @cells[0][j].type = Cell::BLOCKED\n @cells[width][j].type = Cell::BLOCKED\n end\n end", "def getPerimeter\n\t\t@length + @width + @height\n\tend", "def getPerimeter\n\t\t@length + @width + @height\n\tend", "def perimeter(length, width)\n p = (2 * (length + width))\n return p\nend", "def check_map(map)\n\t\tways = Array2D.new(@width, @height, -1)\n\t\t@width.times do |x|\n\t\t\t@height.times do |y|\n\t\t\t\tpoint = Point.new(x, y)\n\t\t\t\tways[point] = 0 if ! map[point]\n\t\t\tend\n\t\tend\n\t\tways[@center] = 1\n\n\t\tnew_cells = true\n\t\tstep = 2\n\t\twhile new_cells\n\t\t\tnew_cells = false\n\t\t\t@width.times do |x|\n\t\t\t\t@height.times do |y|\n\t\t\t\t\tpoint = Point.new(x, y)\n\t\t\t\t\tif map[point]\n\t\t\t\t\t\tways[point] = -1\n\t\t\t\t\telsif ways[point] == 0\n\t\t\t\t\t\tif ways[point.up] == step - 1\n\t\t\t\t\t\t\tways[point] = step\n\t\t\t\t\t\t\tnew_cells = true\n\t\t\t\t\t\tend\n\t\t\t\t\t\tif ways[point.down] == step - 1\n\t\t\t\t\t\t\tways[point] = step\n\t\t\t\t\t\t\tnew_cells = true\n\t\t\t\t\t\tend\n\t\t\t\t\t\tif ways[point.left] == step - 1\n\t\t\t\t\t\t\tways[point] = step\n\t\t\t\t\t\t\tnew_cells = true\n\t\t\t\t\t\tend\n\t\t\t\t\t\tif ways[point.right] == step - 1\n\t\t\t\t\t\t\tways[point] = step\n\t\t\t\t\t\t\tnew_cells = true\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tstep += 1\n\t\tend\n\n\t\t@width.times do |x|\n\t\t\t@height.times do |y|\n\t\t\t\tpoint = Point.new(x, y)\n\t\t\t\treturn false if ways[point] == 0\n\t\t\tend\n\t\tend\n\t\ttrue\n\tend", "def getAreas\n self.removeInfinites\n totals = Hash.new(0)\n self.dims[0].times do |i|\n self.dims[1].times do |j|\n totals[@grid[i][j]] += 1\n end\n end\n totals[-1] = 0\n totals\n end", "def perimeter\n return @perimeter if defined?(@perimeter)\n\n @perimeter = 0.0\n (0...vertices.length).each do |i|\n @perimeter += vertices[i - 1].distance(vertices[i])\n end\n\n @perimeter\n end", "def solution(n)\n r = (n**0.5).floor\n (1..r).reduce(Float::INFINITY) do |perimeter, h|\n n % h == 0 ? [perimeter, 2 * (h + n / h)].min : perimeter\n end\nend", "def continent_size world, x, y\nif world[y][x] != 'land' # => false, true, true, true, false, true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true\n# Either it's water or we already counted it,\n# but either way, we don't want to count it now.\nreturn 0 # => 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\nend\n# So first we count this tile...\nsize = 1 # => 1, 1, 1\nworld[y][x] = 'counted land' # => \"counted land\", \"counted land\", \"counted land\"\n# Each time the program his a tile marked 'land' it updates that tile\n# so it is no longer 'land' but 'counted land', meaning the next time the\n# program hits that tile it will no longer be equal to 'land' and therefore\n# is not double counted.\n\n# ...then we count all of the neighboring eight tiles\n# (and, of course, their neighbors by way of the recursion).\n#\n# The best way to think of this is that each time the program hits a land tile\n# it starts spiraling around that tile until it finds another land tile and\n# each time it finds another land tile it starts again from that second land tile\n# and so on and son on until it has counted all the land tiles and their neighbors\n# that joined the starting tile.\n#\nsize = size + continent_size(world, x-1, y-1) # => 1, 1, 1\nsize = size + continent_size(world, x , y-1) # => 1, 1, 1\nsize = size + continent_size(world, x+1, y-1) # => 1, 1, 1\nsize = size + continent_size(world, x-1, y ) # => 1, 1, 3\nsize = size + continent_size(world, x+1, y ) # => 1, 1, 3\nsize = size + continent_size(world, x-1, y+1) # => 1, 1, 3\nsize = size + continent_size(world, x , y+1) # => 1, 2, 3\nsize = size + continent_size(world, x+1, y+1) # => 1, 2, 3\nsize # => 1, 2, 3\nend", "def empty_neighbors (cell_x, cell_y, radius)\n empty_neighbors = 0\n x = cell_x - radius\n while(x <= cell_x + radius)\n y = cell_y - radius\n while(y <= cell_y + radius)\n if(is_within_map?(x, y) && !is_solid?(x, y))\n empty_neighbors += 1\n end\n y += 1\n end\n x += 1\n end\n return empty_neighbors\n end", "def number_cells\n n = 1\n for row in 0...height\n for col in 0...width\n cell = self[row, col]\n west, north, east, south = DIRS.map{|dx, dy| self[row + dx, col + dy] and self[row + dx, col + dy].empty }\n if cell.empty and ((!west and east) or (!north and south))\n cell.number = n\n n += 1\n end\n end\n end\n end", "def get_perimeter\n\t\tputs \"The perimeter of the circle is #{@radius * @radius * @pi}\"\n\tend", "def area\n\n return @side_len * @side_len\n\n\n end", "def perimeter_of_smallest_side(dimensions)\n dimensions.sort!\n (dimensions[0] * 2) + (dimensions[1] * 2)\nend", "def compute\n perimeter = 1000\n (1..(perimeter+ 1)).each do |a|\n ((a + 1)..(perimeter + 1)).each do |b|\n c = perimeter - a - b\n return (a * b * c).to_s if (a * a + b * b == c * c)\n end\n end\nend", "def perimeter radius\n puts radius * radius * PI\n end" ]
[ "0.6814274", "0.6799362", "0.6797749", "0.67271286", "0.66586167", "0.6527267", "0.64951104", "0.6465987", "0.6462515", "0.64554954", "0.6418304", "0.640568", "0.6385987", "0.63442063", "0.61950076", "0.6160231", "0.6160231", "0.6101672", "0.6100375", "0.6069833", "0.6045466", "0.5948127", "0.5922729", "0.5851142", "0.5798876", "0.57919484", "0.57800585", "0.57794726", "0.57742465", "0.57597417" ]
0.85463613
0
Provides an Enumerator of each of the "origin" points for each calling state enables you to jump anywhere back up the processor stack
def originchain Enumerator.new do |y| callchain.each do |cs| y.yield cs.origin if cs.origin end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def callstack\n @callstack.dup\n end", "def callers\n Rubinius::VM.backtrace(1, true).map &(method(:setup_binding_from_location).\n to_proc)\n end", "def next states\n raise \"Must be implemented by subclass\"\n end", "def return_stack\n return @state[:fiber][:return_stack]\n end", "def enumerate_around(start_x, start_y, func, i = 0)\n movements = {\n DIRECTION_NORTH: [ 0, -1],\n DIRECTION_NORTHEAST: [ 1, -1],\n DIRECTION_EAST: [ 1, 0],\n DIRECTION_SOUTHEAST: [ 1, 1],\n DIRECTION_SOUTH: [ 0, 1],\n DIRECTION_SOUTHWEST: [-1, 1],\n DIRECTION_WEST: [-1, 0],\n DIRECTION_NORTHWEST: [-1, -1]\n }\n\n movements.each do |direction, movements|\n x, y, points = start_x + movements[0], start_y + movements[1], []\n until (x < 0 or x > 7) or (y < 0 or y > 7) or (i != 0 && points.length == i)\n points << [x, y]\n x += movements[0]\n y += movements[1]\n end\n func.call(points, direction)\n end\n end", "def current_frame\n @callstack.top\n end", "def each_frame\n rewind\n if block_given?\n loop {yield next_frame}\n else\n return self.to_enum(:each_frame)\n end\n rescue StopIteration => e\n end", "def known_states; end", "def known_states; end", "def known_states; end", "def pos() @current end", "def get_method_for_next_state\n if end_of_layer_stack?\n # check next superclass\n top_of_composition_stack!\n advance_current_class!\n get_method_for_this_state\n else\n if end_of_runtime_layer_superclass_hierarchy?\n advance_runtime_layer!\n get_method_for_this_state\n else\n advance_current_layer!\n get_method_for_this_state\n end\n end\n end", "def peek_current_state\n peek_state.last || @current_state\n end", "def backtrack\n # get pixel movement rate\n pix = $BlizzABS.pixel\n # current x, y, target x, y and resulting path\n cx, cy, x, y, result = @tx, @ty, 0, 0, []\n # find the way back from destination to start\n loop do\n # change current coordinates\n cx, cy = cx - x, cy - y\n # stop if reached corrected start position\n break if cx == @sx && cy == @sy\n # add movement command\n pix.times {result.unshift(Cache::TDirs[@closed[cx, cy]])}\n # track back next node\n x, y = Cache::DirOffsets[@closed[cx, cy]]\n end\n # modify found path if pixel movement is being used\n modify(result) if pix > 1\n # return result\n return result\n end", "def callsites\n Enumerator.new do |ss|\n blocks.each { |b|\n b.callsites.each { |cs|\n ss << cs\n }\n }\n end\n end", "def go_to_origin\n @next_floor = @origin_floor\n puts \"Elevator #{@id} going back to origin...\"\n go_to_next_floor()\n end", "def next_state(move)\n # Fill this in. Sample code:\n # # Is this the easiest way to create a new copy of the position?\n # next_position = Marshal.load(Marshal.dump(position))\n # player = state[:player]\n # < define resulting position as next_position >\n # next_player = opponent(player)\n # { :position => next_position, :player => next_player}\n end", "def each_reachable_state\n each_touch_reachable_state { |r| yield r }\n each_clap_reachable_state { |r| yield r }\n end", "def execState\n findNextState\n current_state = @state_list[@state][@transition]\n\n @transition = eval \"#{@state}\"\n @history.push @state\n\n @finished = @state == :finish\n end", "def next_states\n possible = []\n # possible states going up\n possible += next_states_in_dir(1) if @elevator != 3\n # possible states going down only make sense if there are actually some items available at lower floors\n items_lower = @floors[0...@elevator].map { |floor| floor.length }.sum\n possible += next_states_in_dir(-1) if (@elevator != 0) && (items_lower > 0)\n\n return possible\n end", "def curr_ins\n if @memory[@ip]\n @memory[@ip]\n else\n raise RuntimeError, \"Instruction is nil\"\n end\n end", "def caller\n []\n end", "def origin; end", "def origin; end", "def origin; end", "def current_offset; end", "def evaluate call_stack_bindings\n case action\n when :CAPTURE\n evaluate_snapshot_point call_stack_bindings\n when :LOG\n evaluate_logpoint call_stack_bindings[0]\n end\n end", "def caller(start=1) end", "def starting_position; end", "def loc; end" ]
[ "0.5630945", "0.5609247", "0.55288976", "0.55179125", "0.54613316", "0.5414991", "0.54092085", "0.5361391", "0.5361391", "0.5361391", "0.53527975", "0.5329069", "0.52959716", "0.5263768", "0.5251513", "0.5220042", "0.5189601", "0.5176043", "0.5175107", "0.5133826", "0.5124845", "0.51184905", "0.5110994", "0.5110994", "0.5110994", "0.5106966", "0.50931305", "0.50867105", "0.5069905", "0.5067987" ]
0.67780435
0
Clears calling state information all the way up the processor stack, removing any stored command blocks and allow the current fiber to expire
def reset_states #called by return to clear internal block stack callchain.each do |c| c.instance_exec do # go to the front of the line! @command_block = @previous_command_blocks.first || @command_block @previous_command_blocks = [] @current_state = nil end end nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clearState()\n\t\t\t@_previous_state = @_state\n\t\t\t@_state = nil\n\t\tend", "def clear\n current_state.clear\n end", "def clear_state\n @state.clear\n self\n end", "def emptyStateStack()\n\t\t\t@_state_stack = []\n\t\tend", "def clear\n @stack.clear\n end", "def clear\n\t\t@stack.clear\n\tend", "def clear()\n @mutex.synchronize {\n each_object &destroy_block\n @idle_list = []\n @active_list = {}\n }\n end", "def clear\r\n # Map ID where the Interpreter was started\r\n @map_id = 0\r\n # Event ID in the map that is currently running the Interpreter\r\n @event_id = 0\r\n # If the Interpreter is waiting for a message\r\n @message_waiting = false\r\n # If the Interpreter is waiting for events to complete their mouve_rotue\r\n @move_route_waiting = false\r\n # If the Interpreter is waiting for a specific event to complete its moves\r\n @move_route_waiting_id = nil\r\n # ID of the variable where the Interpreter should put the Input key value\r\n @button_input_variable_id = 0\r\n # Number of frame the Interpreter has to wait until next execution\r\n @wait_count = 0\r\n # Sub Interpreters\r\n @child_interpreter = nil\r\n # Branches (condition, choices etc...)\r\n @branch = {}\r\n end", "def interpreter_reset\r\n @data_stack = Array.new\r\n @ctrl_stack = Array.new\r\n @start_time = Time.now\r\n end", "def reset_state\n @state = nil\n end", "def clear()\n shutdown()\n @flows = {}\n _clear()\n end", "def discard\n @args = nil\n @block = nil\n end", "def clean\n reset_states rescue nil\n set_executed_commands rescue nil\n end", "def wipe_state\r\n @modes = nil\r\n @online = false\r\n end", "def reset\n @caller_context_padding = 2\n @has_at_exit_report = true\n @alert_frequency = 1\n end", "def reset!\n @was_hooked = false\n @calls = []\n clear_method!\n true\n end", "def clear()\n @VAR_STACK.clear()\n end", "def clear_context\n @current_context = nil\n end", "def clear!\n Thread.current[LOCAL_KEY] = nil\n end", "def reset\n total_calls.clear\n total_success_calls.clear\n total_failed_calls.clear\n end", "def reset\n @perms = []\n @depends = []\n @next_blocks = []\n @clobbers = []\n @offset = nil\n @state = nil\n @once = false\n @references = 0\n @used_references = 0\n @generated = false\n end", "def clear\n LOCK.synchronize do\n @hooks = nil\n @applied = nil\n @logger = nil\n end\n end", "def clear_without_hooks\n\n @without_hooks = true\n\n clear\n \n @without_hooks = false\n \n return self\n \n end", "def reset\n @loaded = false\n @slots = [nil]*SlotCount\n @pending_actions = []\n end", "def reset\n @context = nil\n end", "def clear\n @names = {}\n @processes = []\n end", "def clean\n Thread.current[:__cms_original_content] = nil\n Thread.current[:__cms_active_page] = nil\n Thread.current[:__cms_stack] = nil\n Thread.current[:__content_node_stack] = nil\n Thread.current[:__content_iterator_stack] = nil\n Thread.current[:__content_iterator_stack_key] = nil\n end", "def reset\n @last_eval_line = nil\n @process_queue.clear\n end", "def reset!\n @path_stack = []\n @stack = []\n @stacks = Hash.new { |hsh, k| hsh[k] = Stack.new }\n @text = nil\n end", "def reset\n @callbacks = []\n @closebacks = []\n end" ]
[ "0.66350883", "0.6593083", "0.65637594", "0.6478789", "0.6474248", "0.6441193", "0.63991374", "0.6367419", "0.634529", "0.623296", "0.6094306", "0.60536474", "0.6046544", "0.6021877", "0.60117996", "0.5998626", "0.59270877", "0.5915975", "0.59143186", "0.5894127", "0.5888125", "0.5863436", "0.5838931", "0.58327764", "0.5824153", "0.5815293", "0.5805471", "0.5781007", "0.5779752", "0.5760595" ]
0.70401466
0
Sets the executed commands to the current match, and clears the current command
def set_executed_commands (@executed_commands << @current_command.shift) if @current_command @current_command = nil nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset_commands\n @commands = {}\n end", "def clear\n @commands.clear\n nil\n end", "def clear\r\n @commands.clear\r\n nil\r\n end", "def clear\n registered_commands.each(&:terminate)\n registered_commands.clear\n\n self\n end", "def clear_commands\n @@commands = HELP_COMMAND.dup\n end", "def flush_commands\n @cmd_time = nil\n @on_line_block.call(@cmds.join(' ')) unless @cmds.empty?\n @cmds = []\n end", "def reset_for_next_command\n # self.args, self.switches, self.options = [], [], {}\n self.output, self.capture = false, false\n end", "def clean\n reset_states rescue nil\n set_executed_commands rescue nil\n end", "def clear_matches\n buffer_current.clear_matches Buffer::DO_DISPLAY\n end", "def execute\n command = lines.map(&:to_s).join(\"\\n\")\n\n reset!\n\n clear\n\n Vedeu.trigger(:_command_, command)\n\n command\n end", "def reset\n self.cmd_string = ''\n self.clear\n self.dcase_hash.clear\n end", "def refresh\n @commands.each_with_index { |command, index| set_command(index, command, true) }\n end", "def clear_all!\n @commands_and_opts.clear\n self\n end", "def cleanup_commands\n @cleanup_commands ||= []\n end", "def unset_command\n [grep_cmd, '&&', unset_cmd].join(' ')\n end", "def reset_states\n #called by return to clear internal block stack\n callchain.each do |c|\n c.instance_exec do\n # go to the front of the line!\n @command_block = @previous_command_blocks.first || @command_block\n @previous_command_blocks = []\n @current_state = nil\n end\n end\n nil\n end", "def reset\n @prev_pos = @pos = 0\n @match = nil\n self\n end", "def reset!\n self.command = :reset\n end", "def set_commands; end", "def unregister_commands\n Bot::Commands.delete_for self\n end", "def set_commands\n super\n @commands['clear'] = ConsoleCommand_Clear.new(self)\n @commands['confirm'] = ConsoleCommand_Confirm.new(self)\n end", "def update_command\n while @commands.size > 0 && proccess_command(@commands[0])\n @commands.shift\n end\n end", "def set_command\n [grep_cmd, '&&', replace_cmd, '||', append_cmd].join(' ')\n end", "def set_executed_command_chain\n #return the executed commmands up our call stack\n callchain.each do |c|\n c.instance_eval do \n set_executed_commands \n end\n end\n nil\n end", "def reset_command_attrs!\n self.class.command_attrs.each do |attr|\n write(attr, nil)\n end\n end", "def clean!\n for duplicate in duplicates.map{|duplicate| duplicate[0]}\n @commands.delete_if{ |i| i[0] == duplicate}\n @commands << [duplicate, ENV[duplicate]]\n end\n end", "def reset_all\n clear_commands\n reset_colors\n @app_info = nil\n @app_exe = nil\n @verbose_parameters = true\n @@default_method = nil\n @@class_cache = {}\n end", "def reset_robot\n @commands_array = []\n @next_command_index = 0\n\n # Robot robot should not move before getting PLACEd.\n @is_placed = false\n\n # Start at origin, looking EAST.\n @face = FACES.keys[0]\n @location = {:x=>0, :y=>0}\n end", "def commands\n load_commands unless @commands\n @commands\n end", "def rehash\n @system_commands = {}\n end" ]
[ "0.72802174", "0.69715756", "0.6921162", "0.6899576", "0.67995304", "0.66166204", "0.66074824", "0.6394295", "0.6302413", "0.6277184", "0.6210286", "0.6200497", "0.61861986", "0.6070227", "0.5985217", "0.5894447", "0.5892646", "0.58780646", "0.581509", "0.57787395", "0.57729864", "0.5729315", "0.57096696", "0.56921965", "0.55760914", "0.5539972", "0.55361146", "0.55324477", "0.55155534", "0.5513942" ]
0.75172997
0
Resets all states, sets the executed commands to whatever the last execution was and supresses any error encountered while doing so. Basically, this reset's the processor tree in the event of an unrecoverable error
def clean reset_states rescue nil set_executed_commands rescue nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset_states\n #called by return to clear internal block stack\n callchain.each do |c|\n c.instance_exec do\n # go to the front of the line!\n @command_block = @previous_command_blocks.first || @command_block\n @previous_command_blocks = []\n @current_state = nil\n end\n end\n nil\n end", "def interpreter_reset\r\n @data_stack = Array.new\r\n @ctrl_stack = Array.new\r\n @start_time = Time.now\r\n end", "def reset\n logger.debug \"Resetting executer state\"\n @stdout = ''\n @stderr = ''\n @success = nil\n @pid = nil\n end", "def reset\n @last_eval_line = nil\n @process_queue.clear\n end", "def reset\r\n interpreter_reset\r\n compiler_reset\r\n end", "def reset_for_next_command\n # self.args, self.switches, self.options = [], [], {}\n self.output, self.capture = false, false\n end", "def reset!\n executions.reset\n end", "def reset_commands\n @commands = {}\n end", "def reset(*)\n super.tap do\n __debug_sim('*** RESET WORKFLOW STATE ***')\n end\n end", "def reset\n @cpt = 0\n @errors = 0\n @stopped = false\n end", "def reset\n @cursor = Point.new(0, 0)\n @delta = Point.new(0, 1)\n @stores = Code::FINAL_CONSONANTS.times.map do |consonant|\n case consonant\n when 21 then Queue.new # ㅇ\n when 27 then Port.new # ㅎ\n else Stack.new\n end\n end\n @selected_store = @stores[0]\n @finished = false\n end", "def reset_error_history\n command(:reseterror => 1)\n end", "def reset_error_history\n command(:reseterror => 1)\n end", "def reset_for_next_execute!\n @stmt_api.reset!\n @stmt_api.clear_bindings!\n @blobs_to_write.clear\n end", "def reset_all\n clear_commands\n reset_colors\n @app_info = nil\n @app_exe = nil\n @verbose_parameters = true\n @@default_method = nil\n @@class_cache = {}\n end", "def reset!\n self.command = :reset\n end", "def reset\n info \"\\n\\n------------ RESET ------------\\n\"\n # ExecApp.killAll ## NOTE: do we want to kill of the started RC on reset ???\n resetState\n RMCommunicator.instance.reset\n end", "def reset\n @pc_x = 0\n @pc_y = 0\n @step_no = 0\n @dir = RIGHT\n # The stack is an INTEGER stack. Any characters are pushed as their ASCII value\n @stack = Stack.new\n @stringmode = false\n @running = true\n end", "def reset\n @perms = []\n @depends = []\n @next_blocks = []\n @clobbers = []\n @offset = nil\n @state = nil\n @once = false\n @references = 0\n @used_references = 0\n @generated = false\n end", "def reset!\n @path_stack = []\n @stack = []\n @stacks = Hash.new { |hsh, k| hsh[k] = Stack.new }\n @text = nil\n end", "def reset_state\n @state = nil\n end", "def reset\n\t\tdo_send('ARST 2')\n\tend", "def reset\n until (@stacksize <= 1)\n pop # retrieve graphics states until we get to the default state\n end\n push # push the retrieved pristine default state back onto the stack\n end", "def reset\n self.cmd_string = ''\n self.clear\n self.dcase_hash.clear\n end", "def error_reset\n @@state.delete(@server)\n end", "def reset() end", "def set_executed_commands\n (@executed_commands << @current_command.shift) if @current_command\n @current_command = nil\n nil\n end", "def reset\n @messages = []\n @error = nil\n @status = :ready\n end", "def reset_state\n @children = nil\n @logdev = nil\n @loglvl = nil\n end", "def reset\n @stack = []\n @current_scope = @current_scope.parent until @current_scope.type == Scope::TYPE_MAIN\n @lexer.reset\n end" ]
[ "0.80025375", "0.7073982", "0.697908", "0.69403046", "0.68863666", "0.67731696", "0.6762559", "0.6689466", "0.66473293", "0.6631749", "0.65968025", "0.6556052", "0.6556052", "0.6553712", "0.65450704", "0.6507576", "0.6444732", "0.64360845", "0.6431891", "0.6430986", "0.64291096", "0.6385119", "0.63728714", "0.6316931", "0.62834346", "0.62302977", "0.62187415", "0.62098414", "0.620827", "0.6205652" ]
0.79191566
1
Parse an File article to parse and create a new article Returns a hash containing all values of an article
def parse_article_from_file article_file_name article_values = {} article_values[:content] = '' article_values[:introduction] = '' article_values[:tags] = [] article_values[:authors] = [] article_values[:title] = '' article_values[:date] = nil article_values[:updated_at] = nil next_is = '' puts "Parsing: #{article_file_name}" File.open(File.join(ARTICLE_PATH, article_file_name), 'r') do |article_file| article_file.each_line do |line| next if line.blank? ##### Checking what next line will be # Detect date if line.include?(DATE_DELIMITER) next_is = 'date' # Detect updated_at date elsif line.include?(UPDATED_AT_DELIMITER) next_is = 'updated_at' # Detect introduction elsif line.include?(INTRODUCTION_DELIMITER) next_is = 'introduction' # Detect content elsif line.include?(CONTENT_DELIMITER) next_is = 'content' elsif line.include?(TAGS_DELIMITER) next_is = 'tags' elsif line.include?(TITLE_DELIMITER) next_is = 'title' elsif line.include?(AUTHORS_DELIMITER) next_is = 'authors' else case(next_is) when 'date' then article_values[:date] = Time.zone.parse(line.strip) when 'updated_at' then article_values[:updated_at] = Time.zone.parse(line.strip) when 'introduction' then article_values[:introduction] << line.strip when 'content' then article_values[:content] << line when 'title' then article_values[:title] << line.strip when 'authors' then line.strip.split(',').each do |author| author.strip! # Removing eventual spaces at the begining or at the end article_values[:authors] << Author.where(:name => author).first unless Author.where(:name => author).empty? end when 'tags' then line.strip.split(',').each do |tag_name| tag_name.strip! # Removing eventual spaces at the begining or at the end # If the tag exists, add it to the list of tags if Tag.where(:name => tag_name).empty? article_values[:tags] << Tag.create(:name => tag_name) else article_values[:tags] << Tag.where(:name => tag_name).first end end end end end end return article_values end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_summary(fname)\n hash={}\n # Read file\n File.open(fname,'r') do |f|\n # Loop over line\n f.each_line do |line|\n line.chomp!\n index,content = line.split(/\\s*==\\s*/)\n hash[index] = content # index:id, content:path\n end\n end\n return hash\nend", "def read_slide(fname)\n hash={}\n File.open(fname,'r') do |f|\n f.each_line do |line|\n line.chomp!\n a1,a2 = line.split(/\\s*==\\s*/)\n hash[a1] = a2 # a1:id, a2:path\n end\n end\n hash\nend", "def parse_into_hash(file_content)\n # apt-history file is seperated by double new line\n file_sections = file_content.split(\"\\n\\n\")\n\n # split the sections by line within them\n file_sections.map! { |section| section.split(\"\\n\") }\n\n # split each line of the sections by : seperator\n file_sections.map! do |section|\n section.map! do |line|\n line.partition(\": \").values_at(0, 2) # we don't need the seperator\n end\n section.to_h # Now make a hash of key-value pairs from 2-D array\n end\n end", "def digestFile(filename)\n\tfh = File.open(filename)\n\tarray = String.new\n\tpreparse = true\n\tfh.each_line do |line|\n\t\tif preparse\n\t\t\tif line =~ /\\{/\n\t\t\t\tpreparse = false\n\t\t\t\tarray << line\n\t\t\tend\n\t\telse\n\t\t\t#Sub numberlongs\n\t\t\tif line.include? \"NumberLong\\(\"\n\t\t\t\tline.slice!(/NumberLong\\(/)\n\t\t\t\tline.slice!(/\\)/)\n\t\t\tend\n\n\t\t\t#ObjectId(\"4ef4af0963389003f300c2e7\"),\n\t\t\tif line.include? \"ObjectId\"\n\t\t\t\tline = line.gsub(\"ObjectId\\(\\\"\", \"\\\"ObjectId\\(\")\n\t\t\t\tline = line.gsub(\"\\\"\\)\", \"\\)\\\"\")\n\t\t\tend\n\n\t\t\t#Timestamp(10000, 27),\n\t\t\tif line.include? \": Timestamp\\(\"\n\t\t\t\tline = line.gsub(\"Timestamp\\(\", \"\\\"Timestamp\\(\")\n\t\t\t\tline = line.gsub(\"\\)\", \"\\)\\\"\")\n\t\t\tend\n\t\t\t#ISODate(\"2012-01-26T00:00:00Z\")\n\t\t\tif line.include? \": ISODate\\(\\\"\"\n\t\t\t\tline = line.gsub(\"ISODate\\(\\\"\", \"\\\"ISODate\\(\")\n\t\t\t\tline = line.gsub(\"\\\"\\)\", \"\\)\\\"\")\n\t\t\tend\n #BinData\n if line.include? \": BinData\\(\"\n line = line.gsub(\"BinData\\(\", \"\\\"BinData\\(\")\n line = line.gsub(\"\\\"\\)\", \"\\)\\\"\")\n line = line.gsub(\",\\\"\", \",\")\n end\n if line.include? \"\\\" : \\/\"\n line = line.gsub(\"\\\" : \\/\", \"\\\" : \\\"\\/\")\n line = line.gsub(\"\\/,\", \"\\/\\\",\")\n end\n\t\t\tif line !~ /bye/\n\t\t\t array << line\n\t\t\tend\n\t\tend\n\tend\n\tfh.close\n\tdoc = Yajl::Parser.parse(array)\n\treturn doc\nend", "def read\n return unless File.exist?(filename)\n\n name = DEFAULT_NAME\n save = Hash.new{ |h,k| h[k.to_s] = {} }\n\n File.read(filename).lines.each do |line|\n if md = /^\\[(\\w+)\\]$/.match(line)\n name = md[1]\n end\n if md = /^(\\w+)\\s+(.*?)$/.match(line)\n save[name][md[2]] = md[1]\n end\n end\n\n save.each do |name, digest|\n @saved[name] = digest\n end\n end", "def hash \n @hash ||= CobraVsMongoose.xml_to_hash(file_content)\n end", "def parse_file\n #needs begin rescue exception handling \n \tbegin \n \t\traise FileNotFoundException.new(\"File not Found\") unless File.exists?(@file_path)\n\t\n \t\tFile.open(@file_path).slice_before(@delimiter).each do |chunk|\n \t\t\tchunk.reject! {|item| item =~ @delimiter }\n \t\ttitle = chunk.shift\n \t\tif @title_hash.has_key?(title)\n \t\t\t@title_hash[title] = @title_hash[title] << chunk \n \t\telse\n \t\t p chunk\n \t\t\t@title_hash[title] = chunk\n \t\tend \t\t\n \t\tend\n \t\t\n \trescue FileNotFoundException => e\n \t\tp e.message\n \tend\n\t\n end", "def read_articles_from(file)\n articles = []\n\n CSV.foreach(file, headers: true) do |row|\n article = {\n title: row[\"title\"],\n description: row[\"description\"],\n url: row[\"url\"],\n points: row[\"points\"],\n posted_by: row[\"posted_by\"] || \"anonymous\",\n time_posted: row[\"time_posted\"],\n comments: row[\"comments\"]\n }\n articles << article\n end\n\n articles\nend", "def process(line)\n # parse values\n article_id, attribute_key, attribute_value = parse_line(line)\n\n article_id = parse_article_id(article_id)\n attribute_value = parse_attribute_value(attribute_value)\n attribute_key = parse_attribute_key(attribute_key)\n\n # check if is a new article\n if @article.id_specific != article_id\n @article = Entity.new\n @article.id = ID::parse(article_id)\n @article.id_specific = article_id\n @changed = true\n else\n @changed = false\n end\n\n # add attributes to article\n if not @article.attributes.has_key? attribute_key\n @article.attributes[attribute_key] = []\n end\n\n @article.attributes[attribute_key] << attribute_value\n return @article\n end", "def read_articles\n JSON.parse(File.read(\"articles.json\"))\nend", "def initialize file_path\n md = file_path.match(/(\\d{4}-\\d{2}-\\d{2}-?(\\d{2}-\\d{2})?)-(\\w*)-([\\w-]*)/)\n\n unless md.nil?\n @date = Date.parse(md[1])\n @tags = md[4].split \"-\"\n end\n\n File.open(file_path) do |file|\n\n @title = \"\"\n @title = file.readline until md = @title.match(/^#+(.*)/) \n @title = md[1]\n\n if (md = @title.match /^\\[(.*)\\]\\((.*)\\)/)\n @title = md[1] \n @link = md[2]\n @type = :link\n else\n @type = :post\n end\n\n @content = Maruku.new(file.read).to_html\n @slug = @title.downcase.gsub(/[^\\w\\s]/, \"\").gsub /\\s+/, \"-\"\n @permalink = \"#{@slug}.html\"\n end\n end", "def get_file_details(file_name)\n fd = {}\n \n # Looping through the file and updating the name and url variable with the new data\n # and then finally adding them to the hash table\n File.readlines(file_name).each do |line|\n \n data = line.split(\" \")\n puts data[2]\n name = data[0]\n url = data[2]\n\n fd[name] = url\n end\n puts fd\n return fd\nend", "def interpret(d)\n article = Article.new\n\n if d['headline'] != []\n if !d['headline']['main'].nil?\n article.title = d['headline']['main']\n elsif !d['headline']['name'].nil?\n article.title = d['headline']['name']\n end\n end\n if article.title.nil?\n article.title = 'n/a'\n end\n\n article.source = @source\n article.pub_date = !(d['pub_date'].eql? '') ? (DateTime.parse d['pub_date']) : nil\n\n byline = (d['byline'] != []) ? d['byline']['original'] : 'n/a'\n article.author = (byline[0..2] == 'By ') ? byline[3..byline.size] : byline\n\n article.link = !(d['web_url'].eql? '') ? d['web_url'] : 'n/a'\n article.summary = !(d['snippet'].eql? '') ? d['snippet'] : 'n/a'\n\n # an article may contain several images\n image = []\n if d['multimedia'] != []\n url = 'http://www.nytimes.com/'\n img = d['multimedia']\n img.each { |i| (i['type'] == 'image') ? image << (url + i['url']) : 'n/a' }\n else\n image << 'n/a'\n end\n article.image = image.join(',')\n\n article\n end", "def parse_feed(options={})\n document = read_from_file(filename)\n document.extend Hashie::Extensions::DeepFetch\n recommendations = document.deep_fetch('ObjectList', 'Article') { nil }\n\n Array(recommendations).each do |item|\n doi = item['Doi']\n # sometimes doi metadata are missing\n break unless doi\n\n # turn classifications into array with lowercase letters\n classifications = item['Classifications'] ? item['Classifications'].downcase.split(\", \") : []\n\n year = Time.zone.now.year\n month = Time.zone.now.month\n\n recommendation = { 'year' => year,\n 'month' => month,\n 'doi' => doi,\n 'f1000_id' => item['Id'],\n 'url' => item['Url'],\n 'score' => item['TotalScore'].to_i,\n 'classifications' => classifications,\n 'updated_at' => Time.now.utc.iso8601 }\n\n # try to get the existing information about the given article\n data = get_result(db_url + CGI.escape(doi))\n\n if data['recommendations'].nil?\n data = { 'recommendations' => [recommendation] }\n else\n # update existing entry\n data['recommendations'].delete_if { |recommendation| recommendation['month'] == month && recommendation['year'] == year }\n data['recommendations'] << recommendation\n end\n\n # store updated information in CouchDB\n put_alm_data(db_url + CGI.escape(doi), data: data)\n end\n end", "def parse_file\n filename = full_path_from_edict_file(@config[\"filename\"])\n ### Get all the line into memory\n file_obj = File.new(filename, \"r\")\n file_obj.each do |line|\n @added_lines.push line\n end\n end", "def read_data(fname)\n ents=[]\n if ( File.exist?(fname) )\n File.open(fname,'r') do |f|\n f.each_line do |line|\n line.chomp!\n a1,a2,a3,a4,a5,a6 = line.split(/\\s*==\\s*/)\n hash={}\n hash[\"1\"] = a1\n hash[\"2\"] = a2\n hash[\"3\"] = a3\n hash[\"4\"] = a4\n hash[\"5\"] = a5\n hash[\"6\"] = a6\n ents.push(hash)\n end\n end\n end\n ents\nend", "def get_ensmart_hash\n omim2ensp=Hash.new\n infile=File.new('mart_export2.txt','r')\n infile.each_line{|line|\n line.chomp!\n match_data=line.split(\" \")\n omim2ensp[match_data[1]]=match_data[0]\n }\n return omim2ensp\nend", "def diphot_metadata_to_h\n File.open(@qualified_filename, 'r') do |fd|\n diff = fd.readline.chomp\n reference = fd.readline.chomp\n @obj_metadata = { 'diff' => diff, 'reference' => reference }\n end\n end", "def parse_page_file(file_path)\n \n result = {}\n metadata = []\n remaining = ''\n \n File.open(file_path) do |file|\n \n while (not file.eof?)\n line = file.readline \n if match = line.match(/\\w*:\\s[\\w|\\s]*/)\n metadata.push(line)\n else\n remaining << line if not line.match(/^\\n|\\n\\r$/)\n break\n end\n end \n \n remaining << file.read # Reads the rest of the document\n\n result = {}\n \n if metadata and metadata.length > 0 \n result = YAML::load(metadata.join)\n end\n \n result.store(:body, remaining) if remaining\n \n end \n \n return result \n \n end", "def fetch_articles(url)\n req = open(url)\n response_body = req.read\n articles_json = JSON.parse(response_body)\n articles_array = articles_json[\"articles\"]\n last_articles = []\n articles_array.each do |a|\n article = Article.find_by(title:a[\"title\"])\n unless article #check if article is already in the database\n author = a[\"author\"].blank? ? a[\"source\"][\"name\"] : a[\"author\"]\n article = Article.new(title:a[\"title\"],author: author,source:a[\"source\"][\"name\"],url:a[\"url\"],date:a[\"publishedAt\"],content:a[\"content\"] || \"no content available\",image:a[\"urlToImage\"],description:a[\"description\"])\n article.publication_list.add(a[\"source\"][\"id\"])\n # extractor = Phrasie::Extractor.new\n # tagging = extractor.phrases(a[\"content\"],occur:1)\n # tags = tagging.each{|p|p[0]}\n # article.theme_list.add(tags)\n article.save!\n end\n end\nend", "def interpret(d)\n article = Article.new\n article.title = !d['webTitle'].nil? ? d['webTitle'] : 'n/a'\n article.source = @source\n article.pub_date = !d['webPublicationDate'].nil? ? (DateTime.parse d['webPublicationDate']) : nil\n article.author = !d['fields']['byline'].nil? ? d['fields']['byline'] : 'n/a'\n article.link = !d['webUrl'].nil? ? d['webUrl'] : 'n/a'\n\n re = /<(\"[^\"]*\"|'[^']*'|[^'\">])*>/\n summary = !d['fields']['body'].nil? ? d['fields']['body'] : 'n/a'\n summary.gsub!(re, '')\n article.summary = summary[0...126] + '...'\n\n article.image = !d['fields']['thumbnail'].nil? ? d['fields']['thumbnail'] : 'n/a'\n article\n end", "def initialize(path)\n @path = path\n articles = {}\n begin\n docs = Psych.load_stream(File.open(path, \"r\"), path)\n if docs[0] == {version: VERSION}\n articles = docs[1] || {}\n end\n rescue StandardError\n # Ignore this, pretend like the path doesn't exist (and indeed\n # it may not). I hope StandardError is the right place in the\n # exception hierarchy for me to catch here.\n end\n @stats, @related = {}, {}\n articles.each_pair do |article_path, article_info|\n article_stat, related = article_info.values_at(:stat, :related)\n @stats[article_path] = article_stat if article_stat\n @related[article_path] = related if related\n end\n end", "def parse_multifile(filename: \"\", type: \"old\")\r\n !filename.empty? ? file = File.binread(filename) : return\r\n case type\r\n when \"old\"\r\n file.split(\"\\n\").map(&:strip).reject(&:empty?).map{ |m|\r\n title = m.split('#')[0][1..-1] rescue \"\"\r\n author = \"Metanet Software\"\r\n map = parse_map(data: m.split(\"#\")[1], type: \"old\") rescue {tiles: [], objects: []}\r\n {title: title, author: author, tiles: map[:tiles], objects: map[:objects]}\r\n }\r\n else\r\n print(\"ERROR: Incorrect type (old).\")\r\n return 0\r\n end\r\nend", "def scrape_article\n\n url='http://www.theage.com.au/rssheadlines/political-news/article/rss.xml'\n puts url\n open(url) do |rss|\n\n feed = RSS::Parser.parse(rss)\n\n #For each article gather the relevent information and put it in the article\n feed.items.each do |item|\n\n temp_article=Article.new\n temp_article.author=item.author\n temp_article.title=item.title\n # input was in form of several paragraphs in html format\n # the code splits the paragraphs to arrays so only the relevent\n # text is displayed\n temp_article.summary = item.description.split('</p>')[1]\n temp_article.images=get_http(item.description.split('</p>')[0].split('><')[1])\n\n temp_article.source=AgeImporter.source_name\n temp_article.link=item.link\n temp_article.date=item.pubDate.to_date\n\n\n\n if(temp_article.date <= @end && temp_article.date>=@start && is_unique(temp_article))\n # if article is with the start and end date insert into array and is unique\n\n temp_article.save\n\n\n end\n\n end\n\n\n\n\n end\n end", "def parse_multifile(filename: \"\", type: \"old\")\n !filename.empty? ? file = File.binread(filename) : return\n case type\n when \"old\"\n file.split(\"\\n\").map(&:strip).reject(&:empty?).map{ |m|\n title = m.split('#')[0][1..-1] rescue \"\"\n author = \"Metanet Software\"\n map = parse_map(data: m.split(\"#\")[1], type: \"old\") rescue {tiles: [], objects: []}\n {title: title, author: author, tiles: map[:tiles], objects: map[:objects]}\n }\n else\n print(\"ERROR: Incorrect type (old).\")\n return 0\n end\nend", "def process_article(art)\n this_pub = {}\n \n # if not table of figure or equation remove reference\n # a.zip(b) zipped lists\n both = art.xpath('//xref/@ref-type').zip(art.xpath('//xref'))\n both.each do |tag,elem| \n if tag.text != 'table' || tag.text != 'fig' || tag.text != 'fn' || tag.text != 'sec' || tag.text != 'disp-formula'\n elem.remove\n end\n end\n\n jrn_meta = art / \"article/front/journal-meta\"\n this_pub[:jrn_id] = (jrn_meta / \"journal-id[journal-id-type='nlm-ta']\").text\n art_meta = art / \"/article/front/article-meta\"\n\n this_pub[:pmid] = (art_meta / \"article-id[pub-id-type='pmid']\").text\n\n this_pub[:pmcid] = (art_meta / \"article-id[pub-id-type='pmc']\").text\n# this_pub[:doi] = (art_meta / \"article-id[pub-id-type='doi']\").text\n\n # title\n title_node = (art_meta / \"title-group/article-title\")\n \n # SDB Note 8/2016\n # Turns out that some of the article titles include footnotes or super/subscripts which occurred at the end of a title, \n # which are represented by embedded tags (e.g. <fn> or something like that),and calling .text on the title node was \n # including those (and messing stuff up in the process).\n # We thought that we only needed to worry about tags at the end of titles, and so for trec CDS 2016 we just used the first child node and called it good.\n # This turned out to be insufficient- in the latest PMC release, there are titles with italic text (cf. PMC1079931),\n # and the approach below fails in these cases. \n # TODO: a more robust title-parsing algorithm\n \n if title_node.children.size > 1\n this_pub[:title] = title_node.children.first.text.strip\n else\n this_pub[:title] = title_node.text.strip\n end\n\n # pub_year\n # if ppub, use that; else use collection\n ppub = (art_meta / \"pub-date[pub-type='ppub']/year\").text\n epub = (art_meta / \"pub-date[pub-type='epub']/year\").text\n year = nil\n if ppub.strip.length > 0\n year = ppub.strip\n else\n year = epub.strip\n end\n this_pub[:year] = year \n\n # abstract (if present)\n abst_node = art_meta / \"abstract\"\n \n this_pub[:abstract] = {}\n if abst_node.length == 0\n this_pub[:abstract][:full] = \"\"\n elsif (abst_node / \"sec\").size > 0 # structured abstract (inc. section headings)\n abstract_full = \"\" \n # go through each section, and get the parts out in some kind of order\n (abst_node / \"sec\").each do |s|\n # rm furmulas\n s.search('//p/disp-formula').each do |node|\n node.remove\n end \n s.search('//p/inline-formula').each do |node|\n node.remove\n end\n s.search('//title/disp-formula').each do |node|\n node.remove\n end\n s.search('//title/inline-formula').each do |node|\n node.remove\n end\n ti = (s / \"title\").text.strip\n body = (s / \"p\").text.strip\n # clean leftovers of xref\n body = body.gsub(/\\(-*\\)/, \"\")\n body = body.gsub(/\\[,*\\]/, \"\")\n body = body.gsub(/\\[-*\\]/, \"\")\n body = body.gsub(/\\(,*\\)/, \"\")\n ti = ti.gsub(/\\[-*\\]/, \"\")\n ti = ti.gsub(/\\(,*\\)/, \"\")\n ti = ti.gsub(/\\(-*\\)/, \"\")\n ti = ti.gsub(/\\[,*\\]/, \"\")\n abstract_full << ti << \"\\n\"\n abstract_full << body << \"\\n\"\n end\n this_pub[:abstract][:full] = abstract_full.strip\n end\n if (abst_node / \"p\").size > 0 # unstructured abstract\n abstract_full = this_pub[:abstract][:full].to_s\n (abst_node / \"p\").each do |s|\n s.search('//disp-formula').each do |node|\n node.remove\n end\n s.search('//inline-formula').each do |node|\n node.remove\n end\n abs = s.text.strip\n abs = abs.gsub(/\\[-*\\]/, \"\")\n abs = abs.gsub(/\\(,*\\)/, \"\")\n abs = abs.gsub(/\\(-*\\)/, \"\")\n abs = abs.gsub(/\\[,*\\]/, \"\")\n abstract_full << abs << \"\\n\"\n end\n this_pub[:abstract][:full] = abstract_full\n else\n STDERR.puts \"Other format found: \" + (art_meta / \"article-id[pub-id-type='pmc']\").text\n this_pub[:abstract][:full] = \"\"\n end\n \n # now do body- similar deal\n this_pub[:body] = {}\n body_node = art / \"/article/body\"\n \n if (body_node / \"sec\").size > 0\n body_full = \"\"\n (body_node / \"sec\").each do |s|\n # rm xref\n # rm furmulas\n s.search('//p/disp-formula').each do |node|\n node.remove\n end\n s.search('//p/inline-formula').each do |node|\n node.remove\n end\n s.search('//title/disp-formula').each do |node|\n node.remove\n end\n s.search('//title/inline-formula').each do |node|\n node.remove\n end\n s.search('//fig/caption/p/disp-formula').each do |node|\n node.remove\n end\n s.search('//fig/caption/p/inline-formula').each do |node|\n node.remove\n end\n s.search('//table-wrap/table-wrap-foot/p/disp-formula').each do |node|\n node.remove\n end\n s.search('//table-wrap/table-wrap-foot/p/inline-formula').each do |node|\n node.remove\n end\n s.search('//table-wrap/table-wrap-foot/fn/disp-formula').each do |node|\n node.remove\n end\n s.search('//table-wrap/table-wrap-foot/fn/inline-formula').each do |node|\n node.remove\n end\n\n ti = (s / \"title\").text.strip\n body = (s / \"p\").text.strip\n fig_cap = (s / \"fig/caption/p\").text.strip\n tbl_cap = (s / \"table-wrap/table-wrap-foot/p\").text.strip\n tbl_fn = (s / \"table-wrap/table-wrap-foot/fn\").text.strip\n\n # clean leftovers of xref\n ti = ti.gsub(/\\[-*\\]/, \"\")\n ti = ti.gsub(/\\(,*\\)/, \"\")\n ti = ti.gsub(/\\(-*\\)/, \"\")\n ti = ti.gsub(/\\[,*\\]/, \"\")\n body = body.gsub(/\\[-*\\]/, \"\")\n body = body.gsub(/\\(,*\\)/, \"\")\n body = body.gsub(/\\(-*\\)/, \"\")\n body = body.gsub(/\\[,*\\]/, \"\")\n fig_cap = fig_cap.gsub(/\\[-*\\]/, \"\")\n fig_cap = fig_cap.gsub(/\\(,*\\)/, \"\")\n fig_cap = fig_cap.gsub(/\\(-*\\)/, \"\")\n fig_cap = fig_cap.gsub(/\\[,*\\]/, \"\")\n tbl_cap = tbl_cap.gsub(/\\[-*\\]/, \"\")\n tbl_cap = tbl_cap.gsub(/\\(,*\\)/, \"\")\n tbl_cap = tbl_cap.gsub(/\\(-*\\)/, \"\")\n tbl_cap = tbl_cap.gsub(/\\[,*\\]/, \"\")\n tbl_fn = tbl_fn.gsub(/\\[-*\\]/, \"\")\n tbl_fn = tbl_fn.gsub(/\\(,*\\)/, \"\")\n tbl_fn = tbl_fn.gsub(/\\(-*\\)/, \"\")\n tbl_fn = tbl_fn.gsub(/\\[,*\\]/, \"\")\n body_full << ti << \"\\n\"\n body_full << body << \"\\n\"\n body_full << fig_cap << \"\\n\"\n body_full << tbl_cap << \"\\n\"\n body_full << tbl_fn << \"\\n\"\n end\n this_pub[:body][:full] = body_full.strip\n end\n\n if (body_node / \"p\").size > 0 # found the sec and p can coexist 2660466.nxml\n body_full = this_pub[:body][:full].to_s\n (body_node / \"p\").each do |s|\n s.search('//disp-formula').each do |node|\n node.remove\n end\n s.search('//inline-formula').each do |node|\n node.remove\n end\n body = s.text.strip\n body = body.gsub(/\\[-*\\]/, \"\")\n body = body.gsub(/\\(,*\\)/, \"\")\n body = body.gsub(/\\(-*\\)/, \"\")\n body = body.gsub(/\\[,*\\]/, \"\")\n body_full << body << \"\\n\"\n end\n this_pub[:body][:full] = body_full \n else\n STDERR.puts \"Serious weirdness in body: \"+ (art_meta / \"article-id[pub-id-type='pmc']\").text\n end\n \n \n return this_pub\nend", "def parse(file_path) \n doc = Nokogiri.parse(File.read(file_path))\n \n lib_node = doc.xpath(\"/plist/dict\")[0]\n lib_metadata = {}\n lib_node.xpath(\"key\").each do |key_node|\n key_sym = key_node.content.downcase.gsub(/ +/,'_').to_sym\n lib_metadata[key_sym] = key_node.next.content\n end\n self.persistent_id = lib_metadata[:library_persistent_id]\n \n track_nodes = doc.xpath(\"/plist/dict/dict/dict\")\n track_nodes.each do |track_node|\n song_metadata = {}\n track_node.xpath(\"key\").each do |key_node|\n key_sym = key_node.content.downcase.gsub(/ +/,'_').to_sym\n song_metadata[key_sym] = key_node.next.content\n end\n track_persistent_id = song_metadata[:persistent_id]\n track = Track.find_by_persistent_id(track_persistent_id)\n if track.nil?\n track = Track.new\n track.parse(song_metadata)\n end\n self.tracks << track\n end\n end", "def create_content(file)\n if @config.key?(self.class.name)\n config = @config[self.class.name]\n end\n config['instagram_tags'] ||= ''\n @tags = \"\\n\\n#{config['instagram_tags']}\\n\" unless config['instagram_tags'] == ''\n file_name = file\n file_read = File.readlines(file_name)\n \n file_read.each do |item|\n item.strip()\n end\n \n #\n # This is to assume that the file reads like this:\n # File URL\n # Instagram comment\n # Date posted\n #\n image_url = file_read[0]\n\n if image_url.match('ift.tt')\n \t image_url = Net::HTTP.get_response(URI.parse(image_url))['location']\n end\n\n image_caption = file_read[1]\n date_posted = Time.parse(file_read[-1])\n\n options = {}\n options['datestamp'] = date_posted.utc.iso8601\n options['starred'] = false\n options['uuid'] = %x{uuidgen}.gsub(/-/,'').strip\n options['content'] = \"## Instagram Photo\\n\\n#{image_caption}#{@tags}\"\n \n sl = DayOne.new\n sl.save_image(image_url,options['uuid']) if image_url\n sl.to_dayone(options)\n end", "def simple_parse(filename)\n hash = {}\n data = File.open(filename) do |io| \n # this makes it work with ruby 1.9:\n io.set_encoding(\"ASCII-8BIT\") if io.respond_to?(:set_encoding)\n io.read \n end\n data.split(/\\r?\\n/).select {|v| v =~ /^[a-z]/}.each do |line|\n if line =~ /([^\\s]+)\\s*=\\s*([^;]+)\\s*;?/\n hash[$1.dup] = $2.rstrip\n end\n end\n hash\nend", "def parse_publications_file\n # Each xml file has multiple items\n # Each Item contains the following elements\n # properties\n # md-records -> md-record -> publication\n # components (= files)\n # relations\n # resources\n # Open publications xml file\n pub_xml = File.open(metadata_file) { |f| Nokogiri::XML(f) }\n\n # Each xml file has multiple items\n pub_xml.xpath('/root/item').each do |item|\n # Set defaults\n work_id = nil\n attributes = {}\n files = []\n files_ignored = []\n files_missing = []\n remote_files = []\n error = nil\n\n # Get attributes\n attributes = get_properties(item)\n attributes.merge!(get_metadata(item))\n\n # Get files\n files_list = get_components(item)\n files = files_list[0]\n files_ignored = files_list[1]\n files_missing = files_list[2]\n\n if debug\n log_progress(metadata_file, work_id, @collection, files, files_ignored, files_missing, attributes, error)\n next\n end\n\n # Import publication\n begin\n # Set work id to be same as the id in metadata\n work_id = attributes[:id] unless attributes.fetch(:id, nil).blank?\n h = Importers::HyraxImporter.new('Publication', attributes, files, remote_files, nil, work_id)\n h.import\n rescue StandardError => exception\n error = exception.backtrace\n end\n\n # log progress\n log_progress(metadata_file, work_id, @collection, files, files_ignored, files_missing, attributes, error)\n end\n end" ]
[ "0.6494359", "0.63364494", "0.62164885", "0.6094187", "0.6040543", "0.60125065", "0.5938195", "0.5930174", "0.5889644", "0.58068806", "0.57830125", "0.5779054", "0.5774223", "0.5760144", "0.5736633", "0.5717503", "0.571302", "0.56807023", "0.5664533", "0.5653263", "0.56181455", "0.5613793", "0.5603108", "0.5600982", "0.55994725", "0.55879354", "0.55803466", "0.55490845", "0.55480087", "0.5544791" ]
0.7126961
0
The initialization method takes two arguments that were entered on the command line. There must be exactly one energy file and one power file. They can be named anything (note: without spaces) and be entered in any order. === Attributes +filename1+ The first file read from the command line arguments +filename2+ The second file read from the command line arguments
def initialize filename1, filename2 @filename = [filename1, filename2] # boolean vasriables to help track which file is read first @parsed_energy = false @parsed_power = false # keeps track of the number of files read in @file_count = 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize(args = {})\n @file = args[:file] if args[:file]\n @dictionary = args[:dictionary] if args[:dictionary]\n end", "def initialize(args = {})\n @path = args[:path]\n @freq = args[:frequency]\n @fs = args[:fs]\n @seconds = args[:seconds]\n @amplitude = args[:amplitude]\n @filename = args[:filename]\n\n @path ||= './'\n @freq ||= 440.0\n @fs ||= 44100.0\n @seconds ||= 0.25\n @amplitude ||= 0.9\n @filename ||= 'test'\n @tone = []\n\n @twoPI = (2 * Math::PI)\n end", "def parse_arguments\n @arguments = ARGV.collect { |arg| arg.strip }\n @filename = Pathname.new(@arguments.first)\n end", "def initialize args\n\n @watch = args[:file].to_s\n @watch_full = Pathname.new(@watch).realpath\n\n\n @run = args[:exec].to_s\n @delay = args[:delay].to_i\n\n self.inform\n\n end", "def initialize(args)\n @filename = args.fetch(:filename, nil)\n @yamlstring = args.fetch(:yamlstring, nil)\n \n unless defined?(@filename) || defined?(@string)\n raise InitializationError.new \"you must give me a filename or a string of YAML to get started\"\n end\n\n \n \n \n end", "def initialize filename, options = {}\n @files = []\n @options = CommandLineOptions.new.merge options\n @filename = filename\n end", "def initialize(options = {})\n @filename = options[:file]\n @ledger = options[:bin] || 'ledger'\n end", "def initialize(args=ARGV)\n @args = args\n end", "def initialize(_filename=DEFAULT_STORE_FILENAME,args={})\n @filename = _filename\n super(args)\n end", "def init_file=(_arg0); end", "def initialize mainfilename, adjustment, newfilename # defining methods \n\t\t@main_file = mainfilename # initialized instance variables\n\t\t@adjustment_Time = adjustment\n\t\t@new_file_name = newfilename\n\tend", "def initialize(args={})\n @robinhood_file_path = args[:robinhood_file_path]\n @pids_dir_path = args[:pids_dir_path]\n @log_dir_path = args[:log_dir_path]\n end", "def initialize(filename, highway_attributes)\n\t\t@filename = filename\n\t\t@highway_attributes = highway_attributes \n\tend", "def initialize(filename, highway_attributes)\n\t\t@filename = filename\n\t\t@highway_attributes = highway_attributes \n\tend", "def initialize filename\n\t\t@filename = filename\n\tend", "def initialize(*args)\n return self if args.empty?\n parsed_args = args.first.is_a?(Hash) ? args.first : parse_string_args(args)\n\n self.executable = parsed_args[:executable]\n self.arguments = parsed_args[:arguments]\n end", "def initialize(filename=nil, options={})\n if filename.is_a?(Hash)\n options = filename\n filename = nil\n end\n @filename = filename\n @escapefunc = options[:escapefunc] || ESCAPE_FUNCTION\n @preamble = options[:preamble] == true ? \"_buf = #{init_buf_expr()}; \" : options[:preamble]\n @postamble = options[:postamble] == true ? \"_buf.to_s\" : options[:postamble]\n @args = nil # or array of argument names\n convert_file(filename) if filename\n end", "def initialize(args={})\n @file = args[:file]\n filepath = args[:filepath]\n unless @file || !filepath\n @file = ::File.open(filepath)\n end\n string = args[:string]\n unless @file || !string\n @file = StringIO.new(string, 'r')\n end\n post_initialize(args)\n end", "def initialize(*args)\n @input_files = nil\n @input_string = nil\n if args[0].is_a?(String)\n @input_string = args.shift\n elsif args[0].is_a?(Array)\n @input_files = args.shift.join(' ')\n end\n @options = args || []\n @option_string = nil\n @binary_output = false\n @writer = 'html'\n end", "def parse_arguments\n\toptions = {}\n\t\n\toptparse = OptionParser.new do|opts| \n\t\t# Set a banner, displayed at the top \n\t\t# of the help screen. \n\t\topts.banner = \"Usage: ruby #{$0} [options] file1 file2...\"\n\n\t\t#Figure out the framerate\n\t\toptions[:framerate] = DEFAULT_FRAMERATE\n\t\trates = [23.976, 23.98, 24, 25, 29.97, 30, 50, 59.94, 60]\n\t\topts.on('-f', '--framerate RATE', Float, \"The framerate of your sequence. Defaults to #{DEFAULT_FRAMERATE}. Acceptable rates: #{rates}\") do |fr|\n\t\t\tif !rates.include?(fr)\n\t\t\t\tputs \"Invalid framerate. Must be one of: #{rates}.\".red\n\t\t\t\texit\n\t\t\tend\n\t\t\toptions[:framerate] = fr\n\t\tend\n\n\t\t# This displays the help screen, all programs are\n\t\t# assumed to have this option. \n\t\topts.on( '-h', '--help', 'Display this screen' ) do\n\t\t\tputs opts\n\t\t\texit\n\t\tend\n\n\tend\n\n\t#Parse the options we've set above.\n\t#Whatever is left goes into ARGV\n\toptparse.parse!\n\n\t#XML requirements. Timebase is the round number closest to the framerate\n\ttimebase = options[:framerate].round\n\tntsc = \"FALSE\"\n\n\t#NTSC is true if the true framerate is not a round number\n\t#NTSC should be true if the framerate does not match the timebase\n\tif timebase != options[:framerate]\n\t\tntsc = \"TRUE\"\n\tend\n\n\toptions[:timebase] = timebase\n\toptions[:ntsc] = ntsc\n\n\tif ARGV.length == 0\n\t\tputs \"No files listed.\".red\n\t\texit\n\tend\n\n\t#Parse out the remaining files\n\toptions[:files] = Array.new(ARGV)\n\t \n\treturn options\nend", "def initialize(filename, highway_attributes)\n @filename = filename\n @highway_attributes = highway_attributes\n end", "def initialize(argv)\n @metadata_files, @new_files, @existing_files = nil, nil, nil\n @invalid_metadata_files = []\n @invalid_packages = []\n @argv = argv\n @options = {}\n @exception = nil\n end", "def read_arguments\n\tif (ARGV.length() < 2)\n\t\traise ArgumentError, \"Invalid number of arguments, \\n correct usage 'ruby ./661561-project-one.rb <input_file> <regression_type>'\"\n\tend\n\t\n\tfilename = ARGV[0]\n\tregression_type = ARGV[1]\n\n\tif !(VALID_REGRESSIONS.include? regression_type)\n\t\traise ArgumentError, 'Regression type is not valid.'\t\n\tend\n\n\treturn filename, regression_type\n\nend", "def initialize\n if valid_arguments?\n @directory = ARGV[0]\n @modification_factor = parse_number(ARGV[1])\n @cancellaction_factor = parse_number(ARGV[2])\n else\n raise \"Wrong input! directroy: #{ARGV[0]}, modification_factor: #{ARGV[1]}, cancellaction_factor: #{ARGV[2]}.\n Please pass arguments in such order: directory name (string), modification factor (integer or float),\n cancellaction factor (integer or float), for example: ruby run.rb directory_name 1 0.4\"\n end\n end", "def loadFile _args\n \"loadFile _args;\" \n end", "def initialize(options)\n options.each { |k, v| self.send :\"#{k}=\", v }\n self.file = File.expand_path file\n end", "def initialize(fileName_vars)\n @fileName_vars = fileName_vars\n end", "def initialize(args)\n @mapping = parse_mapping(args[:mapping])\n\n @include_custom = args[:include_custom]\n @zip_output = args[:zip_output]\n\n SUPPORTED_HSDS_MODELS.each do |model|\n var_name = \"@\" + model\n instance_variable_set(var_name, [])\n end\n\n set_file_paths(args)\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make an argument for the variable name\n variable_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable_name', true)\n variable_name.setDisplayName('Enter Variable Name.')\n variable_name.setDescription('Valid values can be found in the eplusout.rdd file after a simulation is run.')\n args << variable_name\n\n # make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency.')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n # make an argument for the key_value\n key_value = OpenStudio::Measure::OSArgument.makeStringArgument('key_value', true)\n key_value.setDisplayName('Enter Key Name.')\n key_value.setDescription('Enter * for all objects or the full name of a specific object to.')\n key_value.setDefaultValue('*')\n args << key_value\n\n env = OpenStudio::Measure::OSArgument.makeStringArgument('env', true)\n env.setDisplayName('availableEnvPeriods')\n env.setDescription('availableEnvPeriods')\n env.setDefaultValue('RUN PERIOD 1')\n args << env\n\n args\n end", "def initialize(*args)\n @input, @environment, @options = case args.first\n when String, IO, StringIO\n Tools.varargs(args, [args.first.class, Environment, Hash])\n else\n Tools.varargs(args, [String, Environment, Hash])\n end\n @options = self.class.const_get(:DEFAULT_OPTIONS).merge(@options || {}) \n end" ]
[ "0.66584355", "0.6502084", "0.6448523", "0.64272475", "0.63824004", "0.63743436", "0.6274756", "0.61309105", "0.6094136", "0.6092415", "0.60270983", "0.59857047", "0.59672195", "0.59672195", "0.59642786", "0.5949158", "0.5925788", "0.5911889", "0.59115976", "0.5908731", "0.58641624", "0.5849565", "0.5833926", "0.5804739", "0.5789172", "0.5789141", "0.5784576", "0.5769078", "0.5762419", "0.57587713" ]
0.76575315
0
A method to parse the data originally from the energy file and calculate the amount of time that past respresented by the data and total energy outputted (and assign them to variables)
def parse_energy energy_hash = parse_hash # total energy produced temp_array = [] temp_array = energy_hash.to_a # runtime in hours @energy_run_time = (temp_array[temp_array.length - 1][0] - temp_array[0][0])/3600.0 # energy in Wh @energy_amount = (temp_array[temp_array.length - 1][1] - temp_array[0][1]) # if the program parsed energy before power, do power now @parsed_energy = true read_file unless @parsed_power output_report end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accumulated_power_used\n power_total = 0.0\n\n begin\n (1..3).each do |ipdp|\n (1..4).each do |eg|\n power_reading = @xml.xpath(\"//XMLdata//info8_IPDP#{ipdp}_eg#{eg}\")[0].content.to_f\n #$stderr.puts \"Power Reading Phase #{ipdp} Socket #{eg} Energy #{power_reading}KJ\"\n power_total += power_reading\n end\n end\n return power_total/3600.0\n \n rescue #If something is wrong with the data\n return 0.0\n end\n end", "def get_total_time_list(filename)\n to_return = []\n lines = File.open(filename, \"rb\") {|f| f.read.split(/\\n+/)}\n lines.each do |line|\n kernel_start = 0.0\n kernel_end = 0.0\n # The lines we're interested in shouldn't contain any letters, just numbers\n next if line =~ /[a-zA-Z]/\n values = line.split.map {|v| v.to_f}\n to_return << [values[0], values[3]]\n end\n to_return\nend", "def parse_hash\n \thash = {}\n \t# Remove the first five lines of the file\n \ttemp_array = @readin[5, @readin.length]\n \t# Split the input at the semicolon: the left hand side is a timestamp and the right hand side\n \t# is the value (either power in W, or energy in Wh depending on the file type).\n \t# This is committed to a hash with time as the key and the W/Wh as the value.\n \ttemp_array.each do |s|\n \t\tk,v = s.split(/;/)\n \t\t# the Aurora reports time as seconds since 1/1/0000 and Ruby reports time utilizing an epoch\n \t\t# that began on 1/1/1970. The time stamp is adjusted for the time in seconds between these\n \t\t# two dates.\n \t\thash[Time.at(k.to_i - 62167104000)] = v.to_f\n \tend\n \treturn hash\n end", "def parse(filename, resolution)\n # first, parse everything into data\n data = [[0, 0, 0, 0, 0]]\n t_start = nil\n File.read(filename).each_line do |l|\n begin\n t = DateTime.parse(l[0...20])\n if t_start.nil?\n t_start = t \n end\n\n t_sec_now = ((t - t_start)*24*60*60).to_i\n\n t_sec_now = (t_sec_now / resolution) * resolution\n\n while data.last[0] + resolution < t_sec_now\n data.push data.last.clone\n data.last[0] += resolution\n end\n\n m = /UpdateTip:.*height=(\\d+) .* tx=(\\d+) .* cache=(.*)MiB\\((\\d+)txo/.match(l)\n if m\n height = m[1]\n tx = m[2]\n cache_MiB = m[3]\n cache_tx = m[4]\n\n # overwrite when second has not changed\n if (data.last[0] == t_sec_now)\n data.pop\n end\n data.push [t_sec_now, height, tx, cache_MiB, cache_tx]\n else\n if (data.last[0] != t_sec_now)\n data.push(data.last.clone)\n end\n data.last[0] = t_sec_now\n end\n rescue => e\n STDERR.puts \"'#{l.strip}': #{e}\"\n end\n end\n\n\n t_next = 0\n data.each do |d|\n if d[0] != t_next\n raise \"t_next does not match!\"\n end\n t_next += resolution\n yield d\n end\nend", "def get_kernel_time(filename)\n to_return = 0.0\n data = JSON.parse(File.open(filename, \"rb\") {|f| f.read})\n data[\"times\"].each do |t|\n next if !t.include?(\"kernel_times\")\n values = t[\"kernel_times\"]\n to_return += values[1] - values[0]\n end\n to_return\nend", "def processing_times\n total = ab_output.match(/Total:\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)/)\n ninety = ab_output.match(/ 90%\\s+([0-9.]+)/)\n ninetyfive = ab_output.match(/ 95%\\s+([0-9.]+)/)\n [total[1], total[2], total[4], ninety[1], ninetyfive[1], total[5]]\n end", "def get_source_energy_array(eplustbl_path)\n # DLM: total hack because these are not reported in the out.osw\n # output is array of [source_energy, source_eui] in kBtu and kBtu/ft2\n result = []\n File.open(eplustbl_path, 'r') do |f|\n while line = f.gets\n if /\\<td align=\\\"right\\\"\\>Total Source Energy\\<\\/td\\>/.match?(line)\n result << /\\<td align=\\\"right\\\"\\>(.*?)<\\/td\\>/.match(f.gets)[1].to_f\n result << /\\<td align=\\\"right\\\"\\>(.*?)<\\/td\\>/.match(f.gets)[1].to_f\n break\n end\n end\n end\n\n result[0] = result[0] * 947.8171203133 # GJ to kBtu\n result[1] = result[1] * 0.947817120313 * 0.092903 # MJ/m2 to kBtu/ft2\n\n return result[0], result[1]\n end", "def read_energy(zone_path)\n read_first_line(File.join(zone_path, ENERGY_FILE_NAME)).to_i\nend", "def energy\n return @data.inject(0.0){|sum,x| sum + (x * x)}\n end", "def parse\n input_data.each do |filename, data|\n rowdata_template = OpenStruct.new\n @preprocess_block.call(filename, rowdata_template) if @preprocess_block\n\n arrived_at_table_data = false\n\n data.split(\"\\r\\n\").each do |line|\n next if line.strip.empty? # Skip blank and whitespace lines\n\n if !arrived_at_table_data\n next if line =~ /\\ACreated by SunData/ # Skip created by line\n if date_match = line.match(/\\A(\\d\\d\\d\\d-\\d\\d-\\d\\d)\\t\\tLocal time is (GMT.\\d+ Hrs)/)\n rowdata_template.date = date_match[1]\n rowdata_template.timezone = date_match[2]\n end\n\n if sunscan_match = line.match(/\\ASunScan probe (v.*)/)\n rowdata_template.sunscan_version = sunscan_match[1]\n end\n\n if matches = line.scan(/\\s*([^\\t:]+)\\s*:\\s*([^\\t:]+)/)\n matches.flatten.map(&:strip).each_slice(2) do |key, value|\n next if value.nil? || value.empty?\n rowdata_template[key.downcase.gsub(\" \", \"_\")] = value\n end\n end\n\n # Once we hit the table hearder we can start processing tabular data.\n # The header is two lines long because of the formatting.\n next if line =~ /\\ATime\\tPlot\\t/\n arrived_at_table_data = true and next if line =~ /\\s+mitted\\s+ent/\n\n\n else\n rowdata = rowdata_template.dup\n table_line = line.split(\"\\t\")\n rowdata.time = table_line[0]\n rowdata.plot = table_line[1]\n rowdata.sample = table_line[2]\n rowdata.transmitted = table_line[3]\n rowdata.spread = table_line[4]\n rowdata.incident = table_line[5]\n rowdata.beam = table_line[6]\n rowdata.zenith_angle = table_line[7]\n rowdata.lai = table_line[8]\n rowdata.notes = table_line[9]\n # Only record output data once the full line data has been captured.\n output_data << rowdata\n end\n end\n end\n end", "def updateTime\n\n # Cleanup phase\n @timestamps << @activestamps.map {|s| s.to_f}\n\n t1, t2, t3, t4, cfs, cfd = @activestamps\n @log.debug \"t1: #{t1.to_f}, \"\\\n \"t2: #{t2.to_f}, \"\\\n \"t3: #{t3.to_f}, \"\\\n \"t4: #{t4.to_f}, \"\\\n \"cfs: #{cfs.to_f}, \"\\\n \"cfd: #{t4.to_f}\"\n\n # Calculate link delay and average link delay\n delay = ((t2 - t1) + (t4 - t3) - cfs - cfd) / BigDecimal.new(2)\n @delay << (delay.to_f > 0 ? delay : delay * -1)\n delay_avg = @delay[-1]\n if @delay_avg[-1]\n one = BigDecimal.new(1)\n delay_avg = ALPHA * @delay_avg[-1] + (one - ALPHA) * @delay[-1]\n end\n @delay_avg << delay_avg\n\n # Calculate phase error and average phase_error\n @phase_error << ((t2 - t1) - (t4 - t3) - cfs + cfd) / BigDecimal.new(2)\n\n # Calculate average phase error if multiple data points exists\n avg = @phase_error[-1]\n if @phase_err_avg[-1]\n one = BigDecimal.new(1)\n avg = ALPHA * @phase_err_avg[-1] + (one - ALPHA) * @phase_error[-1]\n end\n @phase_err_avg << avg\n\n # Calculate frequency error\n distance = -2\n if @timestamps[distance]\n ot1 = @timestamps[distance][0]\n ot2 = @timestamps[distance][1]\n ode = @delay_avg[distance].to_f\n de = @delay_avg.last.to_f\n ocfs = @timestamps[distance][4].to_f\n error = (t1.to_f - ot1)/((t2.to_f + de + cfs.to_f)-(ot2 + ode + ocfs))\n # Do some hard filtering of data\n if error < 2 && error > 0.5\n @freq_error << error\n else\n puts \"ERROR ERROR ERROR ERROR \" + error.to_s # Why?\n @freq_error << @freq_error[-1] || 1\n end\n end\n\n # Calculate average frequency error if multiple data points exists\n if @freq_error[-1] && @flipflop - 1 < @flipflopeach\n @freq_err_avg << @freq_err_avg.last\n elsif @freq_error[-1]\n avg = @freq_error[-1]\n if @freq_err_avg[-1]\n one = BigDecimal.new(1)\n avg = ALPHA_F * @freq_err_avg[-1] + (one - ALPHA_F) * @freq_error[-1]\n end\n @freq_err_avg << avg\n end\n\n # TODO: Update system\n @log.info \"Delay: #{@delay.last.to_f} \\t\" \\\n \"Delay_avg: #{@delay_avg.last.to_f} \\t\" \\\n \"phase_err: #{@phase_error.last.to_f} \\t\"\\\n \"phase_err_avg: #{@phase_err_avg.last.to_f}, \\t\"\\\n \"freq_err: #{@freq_error.last.to_f} \\t\"\\\n \"freq_err_avg: #{@freq_err_avg.last.to_f}\"\n\n # Adjust phase\n adjOffset(@phase_err_avg.last.to_f) if @flipflop < @flipflopeach\n\n # Adjust frequency when we have some point of measurement and when we can\n # actually make adjustments in the flipflop thing.\n if @freq_err_avg[-10] && @flipflop >= @flipflopeach\n adjFreq(@freq_err_avg.last.to_f)\n end\n\n # Final cleanup\n @activestamps.fill(nil,0,4)\n\n # Adjust flipflop\n @flipflop = (@flipflop + 1) % (2 * @flipflopeach)\n end", "def report_data\n EnergyConsume.average_temperature_timeline.each_with_object([]) do |data, report|\n year, month, temperature = data\n item = {\n name: \"#{year}/#{month}\",\n temperature: temperature.round(1).to_s,\n }\n report << item\n end\n end", "def parse_power\n \tpower_hash = parse_hash\n \t@max_power = power_hash.values.max\n \t@min_power = power_hash.values.min\n \t@parsed_power = true\n \tread_file unless @parsed_energy\n end", "def preprocess_data\n # select all points where a time value is present\n @time_points = @track_points.select { |p| !p.time.nil? }\n\n # compute total time in seconds\n @total_time = @time_points.last.time - @time_points.first.time rescue 0\n\n # computes point distances for a sequence of track points\n @point_distances = compute_point_distances(@track_points) # in meters\n @total_distance = compute_total_distance(@point_distances) # in meters\n @accumulated_point_distances = compute_accumulated_distances(@point_distances) # in meters\n\n # computes time points distances for a sequence of time points\n @time_point_distances = compute_point_distances(@time_points) # in meters\n @total_distance_for_time_points = compute_total_distance(@time_point_distances) # in meters\n @accumulated_time_point_distances = compute_accumulated_distances(@time_point_distances) # in meters\n end", "def count_time(relevant_line)\n t0 = 0\n time_between = []\n relevant_line.each do |n|\n t1 = Time.parse(n)\n d = t1 - t0\n t0 = t1\n time_between << d\n end\n time_between\nend", "def parse(text)\n\n # get lat, lon, gmt\n regex = /\\{(N|S)\\s*([0-9]*).\\s*([0-9]*)'\\}\\s*\\{(E|W)\\s*([0-9]*).\\s*([0-9]*)'\\}\\s*\\{GMT\\s*(.*)\\s*Hours\\}/\n match_data = text.match(regex)\n if match_data.nil?\n puts \"Can't find lat/lon/gmt\"\n return\n else\n\n @lat = match_data[2].to_f + (match_data[3].to_f)/60.0\n if match_data[1] == 'S'\n @lat = -@lat\n end\n\n @lon = match_data[5].to_f + (match_data[6].to_f)/60.0\n if match_data[4] == 'W'\n @lon = -@lon\n end\n\n @gmt = match_data[7]\n end\n\n # get elevation\n regex = /Elevation --\\s*(.*)m (above|below) sea level/\n match_data = text.match(regex)\n if match_data.nil?\n puts \"Can't find elevation\"\n return\n else\n @elevation = match_data[1].to_f\n if match_data[2] == 'below'\n @elevation = -@elevation\n end\n end\n\n\n\n\n\n\n\n # get heating and cooling degree days\n cdd10Regex = /-\\s*(.*) annual \\(standard\\) cooling degree-days \\(10.*C baseline\\)/\n match_data = text.match(cdd10Regex)\n if match_data.nil?\n puts \"Can't find CDD 10\"\n else\n @cdd10 = match_data[1].to_f\n end\n\n hdd10Regex = /-\\s*(.*) annual \\(standard\\) heating degree-days \\(10.*C baseline\\)/\n match_data = text.match(hdd10Regex)\n if match_data.nil?\n puts \"Can't find HDD 10\"\n else\n @hdd10 = match_data[1].to_f\n end\n\n cdd18Regex = /-\\s*(.*) annual \\(standard\\) cooling degree-days \\(18.3.*C baseline\\)/\n match_data = text.match(cdd18Regex)\n if match_data.nil?\n puts \"Can't find CDD 18\"\n else\n @cdd18 = match_data[1].to_f\n end\n \n hdd18Regex = /-\\s*(.*) annual \\(standard\\) heating degree-days \\(18.3.*C baseline\\)/\n match_data = text.match(hdd18Regex)\n if match_data.nil?\n puts \"Can't find HDD 18\"\n else\n @hdd18 = match_data[1].to_f\n end\n \n \n # Design Stat\tColdestMonth\tDB996\tDB990\tDP996\tHR_DP996\tDB_DP996\tDP990\tHR_DP990\tDB_DP990\tWS004c\tDB_WS004c\tWS010c\tDB_WS010c\tWS_DB996\tWD_DB996\t\n # \tUnits\t{}\t{�C}\t{�C}\t{�C}\t{}\t{�C}\t{�C}\t{}\t{�C}\t{m/s}\t{�C}\t{m/s}\t{�C}\t{m/s}\t{deg}\t\n # \tHeating\t12\t-7\t-4\t-13.9\t1.1\t-5\t-9.6\t1.7\t-2.9\t14.2\t5.9\t11.9\t6.8\t2.9\t100\n #use regex to get the temperatures\n regex = /\\s*Heating(\\s*\\d+.*)\\n/\n match_data = text.match(regex)\n if match_data.nil?\n puts \"Can't find heating design information\"\n else\n # first match is outdoor air temps\n \n heating_design_info_raw = match_data[1].strip.split(/\\s+/)\n\n # have to be 14 data points\n if heating_design_info_raw.size != 15\n puts \"Can't find cooling design info, found #{heating_design_info_raw.size}\"\n end\n\n # insert as numbers\n heating_design_info_raw.each do |value| \n @heating_design_info << value.to_f \n end\n #puts @heating_design_info\n end\n \n regex = /\\s*Cooling(\\s*\\d+.*)\\n/ \n match_data = text.match(regex)\n if match_data.nil?\n puts \"Can't find cooling design information\"\n else\n # first match is outdoor air temps\n \n design_info_raw = match_data[1].strip.split(/\\s+/)\n\n # have to be 14 data points\n if design_info_raw.size != 32\n puts \"Can't find cooling design info, found #{design_info_raw.size} \"\n end\n\n # insert as numbers\n design_info_raw.each do |value| \n @cooling_design_info << value \n end\n #puts @cooling_design_info\n end\n \n regex = /\\s*Extremes\\s*(.*)\\n/\n match_data = text.match(regex)\n if match_data.nil?\n puts \"Can't find extremes design information\"\n else\n # first match is outdoor air temps\n \n design_info_raw = match_data[1].strip.split(/\\s+/)\n\n # have to be 14 data points\n if design_info_raw.size != 16\n #puts \"Can't find extremes design info\"\n end\n\n # insert as numbers\n design_info_raw.each do |value| \n @extremes_design_info << value \n end\n #puts @extremes_design_info\n end\n \n \n\n\n #use regex to get the temperatures\n regex = /Daily Avg(.*)\\n/\n match_data = text.match(regex)\n if match_data.nil?\n puts \"Can't find outdoor air temps\"\n else\n # first match is outdoor air temps\n monthly_temps = match_data[1].strip.split(/\\s+/)\n\n # have to be 12 months\n if monthly_temps.size != 12\n puts \"Can't find outdoor air temps\"\n end\n\n # insert as numbers\n monthly_temps.each { |temp| @monthly_dry_bulb << temp.to_f }\n #puts \"#{@monthly_dry_bulb}\"\n end\n\n # now we are valid\n @valid = true\n end", "def read_temperature\n begin\n temperature_array = []\n @notifier.watch(@filepath,:modify) do\n temperature_array = FasterCSV.read(@filepath) #TODO:read on the last line of the csv\n temperature = temperature_array.last[1].to_f\n patient_identifier= temperature_array.last[0]\n location = temperature_array.last[3]\n save_in_openmrs = false\n #TODO: Get/Set patient_identifier for this reading\n if temperature > 37.8 && temperature < 38.0\n puts \"/**********Saving Fever Temperature to OPD database********\"\n puts \"Temp=> #{temperature.to_s} AND Patient Identifier =>#{patient_identifier}\"\n save_in_openmrs = true\n elsif temperature > 38.0\n puts \"/**********Saving High Fever to OPD database***********\" #save in opd\n puts \"Temp=> #{temperature.to_s} AND Patient Identifier =>#{patient_identifier}\"\n save_in_openmrs = true\n else\n puts \"No Fever\"\n end\n\n if(save_in_openmrs)\n openmrs_save(location, temperature) #store the values in OpenMRS\n end\n\n temperature_record = TemperatureRecord.new()\n temperature_record.patient_identifier = patient_identifier\n temperature_record.temperature = temperature\n temperature_record.status = 'open'\n temperature_record.location_id = location #assuming the machine will provide location information\n temperature_record.save #save temperature\n end\n @notifier.run\n rescue Exception => e\n puts \"An error occured whilst executing\"\n puts e.message\n #puts e.backtrace.inspect\n end\n end", "def build_enphase_energy_data(start_time, end_time, response)\n body_json = JSON.parse(response.body)\n eel = build_enphase_energy_lifetime(body_json) \n build_enphase_energy_lifetime_daily_readings(eel, body_json)\n build_data_harvest(start_time, end_time, response)\n \n total_end_time = Time.now.to_f\n build_job(start_time, total_end_time)\n end", "def parse\n line = @io.gets until md = /\\ATime before run:\\s+(?<time>.*)\\Z/.match(line)\n return unless md\n @db.date_time ||= DateTime.parse(md[:time])\n super\n @db[\"lparstat_out\"] = @db[\"lparstat_sum\"]\n end", "def cache_statistics data\n self.start_date = DateTime.parse data.first[:timestamp]\n self.duration = DateTime.parse(data.last[:timestamp]).to_time - DateTime.parse(data.first[:timestamp]).to_time\n calculate_distance\n self.min_speed = data.map{|p| p[:speed]}.min\n self.max_speed = data.map{|p| p[:speed]}.max\n self.min_height = data.map{|p| p[:alt]}.min\n self.max_height = data.map{|p| p[:alt]}.max\n save\n end", "def parse\n\t\tfile = File.new(@filename, \"r\")\n\t\tline = file.gets.chomp\n\t\twhile !line.nil?\n\t\t\tif line =~ /(Underflow|Overflow)/ #if exception\n\t\t\t\tline =~ /Overflow/ ? overflow = true : overflow = false\n\t\t\t\tidentifier = line[/[0-9][0-9]*/] #get exception identifier\n\t\t\t\tline = file.gets.chomp\t\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /The constraints are unsat/\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /KLEE: WARNING:/\t\t\t\t\n\t\t\t\t# For a given identifier, there can me multiple warnings of a potential \n\t\t\t\t# overflow/underflow, store only the last one.\n\t\t\t\t# By creating a new array, previous values are overwritten\n\t\t\t\tvalues = []\n\t\t\t\twhile line =~ /^arr[0-9]/\t#if arr value\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\t\t#~ puts \"#{identifier}: #{line}\"\t#debugging\n\t\t\t\t\tvalues.push line #store value as sring with no regard to type (rational, float, integer)\t\t\t\t\t\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\tend\n\t\t\t\tif not values.empty? #if some arr values were found, store them\t\t\t\t\t\n\t\t\t\t\toverflow ? @overflow[\"#{identifier}\"] = values : @underflow[\"#{identifier}\"] = values\n\t\t\t\tend\n\t\t\telse \n\t\t\t\tline = file.gets #if not exception warning\n\t\t\tend\n\t\tend #iterate over lines in file\n\tend", "def response_by_days\n selected_files.each do |file_name|\n key = file_name[0,6]\n next if @by_day[key]\n result = [key, 0, 0, 0]\n File.readlines(file_name).each do |line|\n next unless line.match 'Completed 200 OK in'\n time = $'.split('ms').first.strip.to_i\n result[1] += 1\n result[2] += time\n end\n# average \n result[3] += result[2]/result[1]\n p result\n @by_day[key] = result\n end\nend", "def day_stats\n days = Array.new(7){0}\n @file.each do |line|\n date = line[:regdate].split(\" \")\n date = Date.strptime(date[0],\"%m/%d/%y\")\n days[date.wday.to_i] += 1\n end\n days.each_with_index{ |counter, days| puts \"#{days}: #{counter}\"}\n\n end", "def read_data\n @temperature = t\n @humidity = h\n [@temperature, @humidity]\n end", "def calculate_data(time)\n yDot = InitYVel - 9.8 * time\n x = InitXVel * time\n y = InitYVel * time - 0.5 * 9.8 * time * time\n\n [x, InitXVel, y, yDot]\nend", "def get_data\n\t\tdata = {}\n\n\t\treads = 0\n\t\terrors = 0\n\t\twhile true do\n\t\t\t\n\t\t\tbegin\n\t\t\t\tread()\n\t\t\t\n\t\t\t\t# Have we gathered enough data yet\n\t\t\t\tif @collected.include?(\"GGA\") && @collected.include?(\"RMC\") && reads > 5\n\t\t\t\t\tbreak\n\t\t\t\telsif reads > 25\n\t\t\t\t\traise \"Could not gather enough data from the GPS. Perhaps the NMEA data is corrupt. Did you specifiy the correct serial device?\"\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\treads += 1\n\t\t\t\terrors = 0\n\t\t\trescue\n\t\t\t\terrors += 1\n\t\t\t\tif errors > 5\n\t\t\t\t\traise $!\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\tend\n\n\t\treturn @data\n\tend", "def obtainTrips(contents)\n\n # variable to hold the list of trips\n trips = []\n\n # for every line...\n contents.each do |line|\n\n # use regex to ensure the line matches\n captures = /^Trip ([A-Za-z]{1,64}) ([0-2]\\d):(\\d\\d) ([0-2]\\d):(\\d\\d) (\\d{1,3}\\.?\\d?)$/.match(line)\n\n # safety check, ensure the capture isn't nil\n if captures.nil?\n next\n end\n\n # if the regex capture has a length of at least 6:\n #\n # * driver\n # * start time - HH\n # * start time - MM\n # * end time - HH\n # * end time - MM\n # * average speed \n #\n if captures.length < 6\n next\n end\n\n # safety check, ensure this actually resembles a 24 hour clock\n if captures[2].to_i > 23 || captures[4].to_i > 23 ||\n captures[3].to_i > 59 || captures[5].to_i > 59\n next\n end\n\n # Obtain the current time\n t = Time.now\n\n # Assemble a start time\n start_time = Time.local(t.year, t.day, t.month, captures[2], captures[3])\n\n # Assemble an end time\n end_time = Time.local(t.year, t.day, t.month, captures[4], captures[5])\n\n # Throw a warning if the start time is *after* the end time,\n # but skip on to the next element...\n if start_time > end_time\n puts \"\\nWarning: Improper start / end time detected!\"\n puts \"--------------------------------------------\"\n puts line\n puts \"--------------------------------------------\\n\"\n next\n end\n\n # assemble the trip array\n trip = {:driver => captures[1],\n :start_time => start_time,\n :end_time => end_time,\n :average_speed => 0,\n :miles_driven => captures[6].to_f}\n\n # attempt to calculate the average speed\n start_minutes = (captures[2].to_i * 60) + captures[3].to_i\n end_minutes = (captures[4].to_i * 60) + captures[5].to_i\n total_time_in_minutes = end_minutes - start_minutes\n if total_time_in_minutes <= 0\n next\n end\n trip[:average_speed] = trip[:miles_driven] * 60 / total_time_in_minutes\n\n # discard trips with speed < 5mph or speed > 100mph\n if trip[:average_speed] < 5 || trip[:average_speed] > 100\n next\n end\n\n # add the trip to the list of trips\n trips.push(trip)\n end\n\n # send back the list of trips\n return trips\nend", "def parse_times_and_items\n @item_counts.sort.each do |item_count|\n items = item_count[1] # returns hash\n time = item_count[0].strftime(\"%I:%M\")\n @times.push(time)\n\n str = \"\"\n items.sort.each do |sub_arr|\n item = sub_arr[0]\n quantity = sub_arr[1]\n item = item.pluralize if quantity > 1\n str.concat(\"#{quantity} #{item}, \")\n end\n @items.push(str.slice(0...-2))\n\n end\n end", "def time_file (doc2, estimate)\n\n#Hash to store the count of [Next], [Submit], etc.\n\tcounthash = Hash.new\n\tcounthash[\"[Next]\"] = 0\n\tcounthash[\"[Submit]\"] = 0\n\n#TO DO: update so that it finds the search criteria from the entered keywords\n# Count the number of [Next]s, [Submit, Long]s\n# and multiply by the time assigned to each keyword\n\tdoc2.paragraphs.each do |p|\n\t\tcounthash[\"[Next]\"] += 6*p.to_s.scan(/(\\[(n|N)ext)|((n|N)ext\\])/).size\n\t\tcounthash[\"[Submit]\"] += estimate*p.to_s.scan(/\\[(S|s)ubmit/).size\n\tend\n\n#prints times associated with [Next], [Submit, *], etc.\n\treturn counthash\n\nend", "def get_raw_temperature_and_solar_data(station_name, start_date, end_date, max_temp, min_temp, max_solar)\n puts \"Getting data for #{station_name} between #{start_date} and #{end_date}\"\n data = {}\n (start_date..end_date).each do |date|\n puts \"Processing #{date} #{station_name}\"\n url = generate_single_day_station_history_url(station_name, date)\n puts \"HTTP request for #{url}\"\n header = []\n web_page = open(url){ |f|\n line_num = 0\n f.each_line do |line|\n line_components = line.split(',')\n if line_num == 1\n header = line_components\n elsif line_components.length > 2 # ideally I should use an encoding which ignores the <br> line ending coming in as a single line\n temperature_index = header.index('TemperatureC')\n solar_index = header.index('SolarRadiationWatts/m^2')\n datetime = DateTime.parse(line_components[0])\n temperature = !line_components[temperature_index].nil? ? line_components[temperature_index].to_f : nil\n solar_string = solar_index.nil? ? nil : line_components[solar_index]\n solar_value = solar_string.nil? ? nil : solar_string.to_f\n solar_value = solar_value.nil? ? nil : (solar_value < max_solar ? solar_value : nil)\n if !temperature.nil? && temperature <= max_temp && temperature >= min_temp # only use data if the temperature is within range\n data[datetime] = [temperature, solar_value]\n end\n end\n line_num += 1\n end\n }\n end\n puts \"got #{data.length} observations\"\n data\nend" ]
[ "0.6570041", "0.637124", "0.61529696", "0.6139952", "0.58971155", "0.5867482", "0.5836949", "0.58355427", "0.5834544", "0.5814748", "0.5706275", "0.5694727", "0.5685165", "0.5666351", "0.5652113", "0.5620736", "0.56060725", "0.55664074", "0.55598557", "0.5557295", "0.5511282", "0.5506291", "0.5466841", "0.5445944", "0.54373753", "0.5419068", "0.53997403", "0.5391724", "0.53585523", "0.53509647" ]
0.7527124
0
A method to parse the data originally from the power file and find the maximum power reading, minimum power reading, and assign them to class variables
def parse_power power_hash = parse_hash @max_power = power_hash.values.max @min_power = power_hash.values.min @parsed_power = true read_file unless @parsed_energy end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_energy\n \tenergy_hash = parse_hash\n \t# total energy produced\n \ttemp_array = []\n \ttemp_array = energy_hash.to_a\n \t# runtime in hours\n \t@energy_run_time = (temp_array[temp_array.length - 1][0] - temp_array[0][0])/3600.0\n \t# energy in Wh\n \t@energy_amount = (temp_array[temp_array.length - 1][1] - temp_array[0][1])\n\n \t# if the program parsed energy before power, do power now\n \t@parsed_energy = true\n \tread_file unless @parsed_power\n \toutput_report\n end", "def initialize\n self.temps = [0] * 110 # 110 = max temperature\n self.max, self.mode, self.num_rec_temps = [0, 0, 0]\n self.mean = 0.0\n self.min = 110\n end", "def get_min_and_max_stats\n @min_str = @str\n @min_dex = @dex\n @min_con = @con\n @min_mag = @mag\n @min_cha = @cha\n\n if level == 1\n @max_str = 18\n @max_dex = 18\n @max_con = 18\n @max_mag = 18\n @max_cha = 18\n else\n @max_str = 99\n @max_dex = 99\n @max_con = 99\n @max_mag = 99\n @max_cha = 99\n end\n @min_one_hand = @one_hand_prof\n @min_dual_wield = @dual_wield_prof\n @min_two_hand = @two_hand_prof\n @min_magic = @magic_prof\n @min_unarmed = @unarmed_prof\n end", "def parse\n\t\tfile = File.new(@filename, \"r\")\n\t\tline = file.gets.chomp\n\t\twhile !line.nil?\n\t\t\tif line =~ /(Underflow|Overflow)/ #if exception\n\t\t\t\tline =~ /Overflow/ ? overflow = true : overflow = false\n\t\t\t\tidentifier = line[/[0-9][0-9]*/] #get exception identifier\n\t\t\t\tline = file.gets.chomp\t\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /The constraints are unsat/\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /KLEE: WARNING:/\t\t\t\t\n\t\t\t\t# For a given identifier, there can me multiple warnings of a potential \n\t\t\t\t# overflow/underflow, store only the last one.\n\t\t\t\t# By creating a new array, previous values are overwritten\n\t\t\t\tvalues = []\n\t\t\t\twhile line =~ /^arr[0-9]/\t#if arr value\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\t\t#~ puts \"#{identifier}: #{line}\"\t#debugging\n\t\t\t\t\tvalues.push line #store value as sring with no regard to type (rational, float, integer)\t\t\t\t\t\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\tend\n\t\t\t\tif not values.empty? #if some arr values were found, store them\t\t\t\t\t\n\t\t\t\t\toverflow ? @overflow[\"#{identifier}\"] = values : @underflow[\"#{identifier}\"] = values\n\t\t\t\tend\n\t\t\telse \n\t\t\t\tline = file.gets #if not exception warning\n\t\t\tend\n\t\tend #iterate over lines in file\n\tend", "def parse_hash\n \thash = {}\n \t# Remove the first five lines of the file\n \ttemp_array = @readin[5, @readin.length]\n \t# Split the input at the semicolon: the left hand side is a timestamp and the right hand side\n \t# is the value (either power in W, or energy in Wh depending on the file type).\n \t# This is committed to a hash with time as the key and the W/Wh as the value.\n \ttemp_array.each do |s|\n \t\tk,v = s.split(/;/)\n \t\t# the Aurora reports time as seconds since 1/1/0000 and Ruby reports time utilizing an epoch\n \t\t# that began on 1/1/1970. The time stamp is adjusted for the time in seconds between these\n \t\t# two dates.\n \t\thash[Time.at(k.to_i - 62167104000)] = v.to_f\n \tend\n \treturn hash\n end", "def custom_load_pf\n # adjusted power factors from \"power factor data.xlsx\"\n new_pf = {\n 'pool_pump' => '0.87',\n 'responsive_loads' => '0.95',\n 'unresponsive_loads' => '0.95',\n 'lights' => '0.90', # this is interior lighting\n 'plugs' => '0.95',\n 'exterior' => '0.95'\n }\n find_by_class('house').each do |h|\n # note that for the sake of performance we're assuming\n # all the ZIPloads are nested under the house\n # If they were downstream in some other way we'd need\n # to use h.downstream, which is slower\n h.nested.each do |d|\n if d[:class] == 'ZIPload'\n new_pf.each do |load_type, pf|\n if d[:base_power].include? load_type\n d[:power_pf] = d[:current_pf] = d[:impedance_pf] = pf\n break\n end\n end\n end\n end\n end\n end", "def current_power_usage\n begin\n power_being_used = 0.0\n\n (1..3).each do |ipdp|\n (1..4).each do |ap|\n power_reading = @xml.xpath(\"//XMLdata//info8_IPDP#{ipdp}_ap#{ap}\")[0].content.to_f\n power_being_used += power_reading #in Watts\n end\n end\n \n return power_being_used/1000.0 #in KW\n\n rescue #If something is wrong with the data\n return 0.0\n end\n end", "def accumulated_power_used\n power_total = 0.0\n\n begin\n (1..3).each do |ipdp|\n (1..4).each do |eg|\n power_reading = @xml.xpath(\"//XMLdata//info8_IPDP#{ipdp}_eg#{eg}\")[0].content.to_f\n #$stderr.puts \"Power Reading Phase #{ipdp} Socket #{eg} Energy #{power_reading}KJ\"\n power_total += power_reading\n end\n end\n return power_total/3600.0\n \n rescue #If something is wrong with the data\n return 0.0\n end\n end", "def from_file line\n\t\tvals = line.split(\"-\")\n\t\t@type = vals[0].to_i\n\t\t@obj = vals[1]\n\t\tif vals[2] != nil\n\t\t\t@sensor = vals[2]\n\t\tend\n\t\tif vals[3] != nil\n\t\t\t@value = vals[3].to_f\n\t\tend\n\tend", "def readDataSingleSource(nameout)\n\t\t\tif nameout.include?(\".source\") == false\n\t\t\t\tnameout = nameout + \".source\"\n\t\t\tend\n\t\t\tdatautils = DataUtils.new\n\t\t\t#puts \"nameout: \" + nameout;\n\t\t\t@l = -1;\n\t\t\t@b = -1;\n\t\t\t@r = -1;\n\t\t\t@ell_a = -1;\n\t\t\t@ell_b = -1;\n\t\t\t@ell_phi = -1;\n\t\t\t\n\t\t\t@sicalc = 0\n\t\t\t@sicalc_error = 0\n\n\t\t\t#read upper limit\n\t\t\tindex2 = 0;\n\t\t\t@r = -1;\n\t\t\t@galcoeff = \"-1\"\n\t\t\t@galcoeff_err = \"-1\"\n\t\t\t@galcoeffzero = \"-1\"\n\t\t\t@galcoeffzero_err = \"-1\"\t\n\t\t\t@isocoeff = \"-1\"\n\t\t\t@isocoeff_err = \"-1\"\n\t\t\t@isocoeffzero = \"-1\"\n\t\t\t@isocoeffzero_err = \"-1\"\t\n\t\t\t@fitdata = \"-1, -1, -1, -1, -1, -1, -1\"\n\t\t\tFile.open(nameout).each_line do | line |\n\t\t\t\tindex2 = index2 + 1;\n\t\t\t\tlll = line.split(\" \")\n\t\t\t\tif index2.to_i == 15\n\t\t\t\t\t@label =lll[0];\n\t\t\t\t\t@fix =lll[1];\n\t\t\t\t\t@si_start = lll[2];\n\t\t\t\t\t@ulconflevel = lll[3];\n\t\t\t\t\t@srcconflevel = lll[4];\n\t\t\t\t\t@startL = lll[5];\n\t\t\t\t\t@startB = lll[6];\n\t\t\t\t\t@startFlux = lll[7];\n\t\t\t\t\t@lmin = lll[9];\n\t\t\t\t\t@lmax = lll[11];\n\t\t\t\t\t@bmin = lll[14];\n\t\t\t\t\t@bmax = lll[16];\n\t\t\t\tend\n\t\t\t\tif index2.to_i == 16\n\t\t\t\t\t@sqrtTS =lll[0];\n\t\t\t\tend\n\t\t\t\tif index2.to_i == 17\n\t\t\t\t\t@l_peak = lll[0];\n\t\t\t\t\t@b_peak = lll[1];\n\t\t\t\t\t@dist = lll[2];\n\t\t\t\tend\n\t\t\t\tif index2.to_i == 18\n\t\t\t\t\t@l = lll[0]\n\t\t\t\t\t@b = lll[1]\n\t\t\t\t\t@distellipse = lll[2];\n\t\t\t\t\t@r = lll[3];\n\t\t\t\t\t@ell_a = lll[4];\n\t\t\t\t\t@ell_b = lll[5];\n\t\t\t\t\t@ell_phi = lll[6];\n\t\t\t\t\t@fullellipseline = format(\"%.2f %.2f %.2f %.2f %.2f %.2f %.2f\", @l, @b, @distellipse, @r, @ell_a, @ell_b, @ell_phi)\n\t\t\t\tend\n\t\t\t\tif index2.to_i == 19\n\t\t\t\t\t@counts = lll[0]\n\t\t\t\t\t@counts_error = lll[1]\n\t\t\t\t\t@counts_error_p = lll[2]\n\t\t\t\t\t@counts_error_m = lll[3]\n\t\t\t\t\t@counts_ul = lll[4];\n\t\t\t\tend\n\t\t\t\tif index2.to_i == 20\n\t\t\t\t\t@flux = lll[0]\n\t\t\t\t\t@flux_error = lll[1]\n\t\t\t\t\t@flux_error_p = lll[2]\n\t\t\t\t\t@flux_error_m = lll[3]\n\t\t\t\t\t@flux_ul = lll[4];\n\t\t\t\t\t@exposure = lll[5]\n\t\t\t\tend\n\t\t\t\tif index2.to_i == 21\n\t\t\t\t\t@sicalc = lll[0]\n\t\t\t\t\t@sicalc_error = lll[1]\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif index2.to_i == 22\n\t\t\t\t\t@fit_cts = lll[0]\n\t\t\t\t\t@fit_fcn0 = lll[1]\n\t\t\t\t\t@fit_fcn1 = lll[2]\n\t\t\t\t\t@fit_edm0 = lll[3]\n\t\t\t\t\t@fit_edm1 = lll[4]\n\t\t\t\t\t@fit_iter0 = lll[5]\n\t\t\t\t\t@fit_iter1 = lll[6]\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif index2.to_i == 23\n\t\t\t\t\t@galcoeff = lll[0]\n\t\t\t\t\t@galcoeff_err = lll[1]\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif index2.to_i == 24\n\t\t\t\t\t@galcoeffzero = lll[0]\n\t\t\t\t\t@galcoeffzero_err = lll[1]\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif index2.to_i == 25\n\t\t\t\t\t@isocoeff = lll[0]\n\t\t\t\t\t@isocoeff_err = lll[1]\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif index2.to_i == 26\n\t\t\t\t\t@isocoeffzero = lll[0]\n\t\t\t\t\t@isocoeffzero_err = lll[1]\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif index2.to_i == 27\n\t\t\t\t\t@tstart = lll[0]\n\t\t\t\t\t@tstop = lll[1]\n\t\t\t\t\t\n\t\t\t\t\t@timestart_utc = @tstart\n\t\t\t\t\t@timestop_utc = @tstop\n\t\t\t\t\t@timestart_tt = datautils.time_utc_to_tt(@tstart);\n\t\t\t\t\t@timestop_tt = datautils.time_utc_to_tt(@tstop);\n\t\t\t\t\t@timestart_mjd = datautils.time_tt_to_mjd(@timestart_tt);\n\t\t\t\t\t@timestop_mjd = datautils.time_tt_to_mjd(@timestop_tt);\n\t\t\t\t\t\n\t\t\t\t\t#calcolo fase orbitale\n\t\t\t\t\t@orbitalphase = -1;\n\t\t\t\t\tif(@calcorbitalphase_period.to_f != 0)\n\t\t\t\t\t\ttimemjd = @timestart_mjd.to_f + (@timestop_mjd.to_f-@timestart_mjd.to_f)\n\t\t\t\t\t\t@orbitalphase = (timemjd.to_f - @calcorbitalphase_t0.to_f) / @calcorbitalphase_period.to_f;\n\t\t\t\t\t\t@orbitalphase = @orbitalphase.to_f - @orbitalphase.to_i;\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif index2.to_i == 28\n\t\t\t\t\t@energyrange = lll[0]\n\t\t\t\t\t@fovrange = lll[1]\n\t\t\t\t\t@albedo = lll[2]\n\t\t\t\t\t@binsize = lll[3] \n\t\t\t\t\t@expstep = lll[4] \n\t\t\t\t\t@phasecode = lll[5] \n\t\t\t\tend\n\t\t\tend\n\n\tend", "def read_trim_params\n # compensation parameter register mapping\n Calibration = Struct.new(\n # Register Address Register content Data type\n :dig_T1, # 0x88 / 0x89 dig_T1 [7:0] / [15:8] unsigned short\n :dig_T2, # 0x8A / 0x8B dig_T2 [7:0] / [15:8] signed short\n :dig_T3, # 0x8C / 0x8D dig_T3 [7:0] / [15:8] signed short\n :dig_P1, # 0x8E / 0x8F dig_P1 [7:0] / [15:8] unsigned short\n :dig_P2, # 0x90 / 0x91 dig_P2 [7:0] / [15:8] signed short\n :dig_P3, # 0x92 / 0x93 dig_P3 [7:0] / [15:8] signed short\n :dig_P4, # 0x94 / 0x95 dig_P4 [7:0] / [15:8] signed short\n :dig_P5, # 0x96 / 0x97 dig_P5 [7:0] / [15:8] signed short\n :dig_P6, # 0x98 / 0x99 dig_P6 [7:0] / [15:8] signed short\n :dig_P7, # 0x9A / 0x9B dig_P7 [7:0] / [15:8] signed short\n :dig_P8, # 0x9C / 0x9D dig_P8 [7:0] / [15:8] signed short\n :dig_P9, # 0x9E / 0x9F dig_P9 [7:0] / [15:8] signed short\n :dig_H1, # 0xA1 dig_H1 [7:0] unsigned char\n :dig_H2, # 0xE1 / 0xE2 dig_H2 [7:0] / [15:8] signed short\n :dig_H3, # 0xE3 dig_H3 [7:0] unsigned char\n :dig_H4, # 0xE4 / 0xE5[3:0] dig_H4 [11:4] / [3:0] signed short\n :dig_H5, # 0xE5[7:4] / 0xE6 dig_H5 [3:0] / [11:4] signed short\n :dig_H6, # 0xE7 dig_H6 signed char\n :t_fine\n )\n calib = [] \n\n # data addresses\n dig_t_reg = 0x88\n dig_p_reg = 0x8E\n dig_h_reg1 = 0xA1\n dig_h_reg2 = 0xE1\n \n data = read(dig_t_reg, 6)\n calib << ((data[1] << 8) | data[0]) # uint16_t dig_T1 [1][0] \n calib << int16(data[3], data[2]) # int16_t dig_T2 [3][2]\n calib << int16(data[5], data[4]) # int16_t dig_T3 [5][4]\n\n data = read(dig_p_reg, 18)\n calib << ((data[1] << 8) | data[0]) # uint16_t dig_P1 [1][0]\n calib << int16(data[3], data[2]) # int16_t dig_P2 [3][2]\n calib << int16(data[5], data[4]) # int16_t dig_P3 [5][4]\n calib << int16(data[7], data[6]) # int16_t dig_P4 [7][6]\n calib << int16(data[9], data[8]) # int16_t dig_P5 [9][8]\n calib << int16(data[11], data[10]) # int16_t dig_P6 [11][10]\n calib << int16(data[13], data[12]) # int16_t dig_P7 [13][12]\n calib << int16(data[15], data[14]) # int16_t dig_P8 [15][14]\n calib << int16(data[17], data[16]) # int16_t dig_P9 [17][16]\n\n data = read(dig_h_reg1, 1)\n calib << data[0] # uint8_t dig_H1 [0]\n \n data = read(dig_h_reg2, 7)\n calib << int16(data[1], data[0]) # int16_t dig_H2 [1],[0]\n calib << data[2] # uint8_t dig_H3 [2] \n\n # 109876543210 bit[11:0]\n # xxxxxxxx.... dig_H4_msb [11:4] [3]\n # ....xxxx dig_H4_lsb [3:0] [4]\n # xxxxxxxxxxxx dig_H4 [11:0] \n dig_H4_msb = (data[3] >> 4) & 0x0F\n dig_H4_lsb = ((data[3] << 4) & 0xF0) | (data[4] & 0x0F) \n calib << int16(dig_H4_msb, dig_H4_lsb) # int16_t dig_H4 [3][4]\n \n # 109876543210 bit[11:0]\n # xxxxxxxx.... dig_H5_msb [11:4] [5]\n # xxxx.... dig_H5_lsb [7:4] [4]\n # xxxxxxxxxxxx dig_H5 [11:0]\n dig_H5_msb = (data[5] >> 4) & 0x0F\n dig_H5_lsb = ((data[5] << 4) & 0xF0) | (data[4] >> 4) \n calib << int16(dig_H5_msb, dig_H5_lsb) # int16_t dig_H5 [4][5]\n \n calib << int8(data[6]) # int8_t dig_H6 [6]\n\n @calib = Calibration.new(*calib)\n end", "def initialize(class_data)\n @name = class_data.elements['className'].text\n @max_buildings_destroyed = class_data.elements['ibuildingsdestroyed'].text.to_i\n @max_captures = class_data.elements['ipointcaptures'].text.to_i\n @max_damage = class_data.elements['idamagedealt'].text.to_i\n @max_defenses = class_data.elements['ipointdefenses'].text.to_i\n @max_dominations = class_data.elements['idominations'].text.to_i\n @max_kill_assists = class_data.elements['ikillassists'].text.to_i\n @max_kills = class_data.elements['inumberofkills'].text.to_i\n @max_revenges = class_data.elements['irevenge'].text.to_i\n @max_score = class_data.elements['ipointsscored'].text.to_i\n @max_time_alive = class_data.elements['iplaytime'].text.to_i\n @play_time = class_data.elements['playtimeSeconds'].text.to_i\n end", "def read_file\n \t@readin = []\n file = File.open(@filename[@file_count], 'r')\n\t @readin = file.each.to_a\n\t # chop off the escaped characters (in this case: \\r\\n)\n @readin.map! {|s| s.chomp}\n # increment the file count\n @file_count += 1\n file.close\n # determine which file was read in\n # the files either have a \"W\" (for power) or \"Wh\" as the first line\n \tif @readin[0] =~ /Wh/\n \t\tparse_energy\n \telse @readin[0] =~ /W/\n \t\tparse_power\n \tend\n end", "def parse\n @meta = parse_meta\n @comments = parse_comments\n @sensors = parse_sensors\n @workout = parse_workout\n @intervals = parse_intervals\n @interval_samples = parse_interval_samples\n end", "def calculate(data)\n min_array = []\n max_array = []\n current_close = data[0].close\n\n length = 14\n if data.length < length\n length = data.length\n end\n\n for index in 0 ... length\n min_array << data[index].low\n max_array << data[index].hight\n end\n\n @min = min_array.min\n @max = max_array.max\n\n\n @k = (100 * ((current_close - @min) / (@max - @min))).round(2)\n\n # вычисляем d\n # @d = calculate_d(data)\n end", "def load_info\n info = File.readlines @dir+\"info\"\n @last_learnq = info[0].to_i\n @last_repq = info[1].to_i\n @last_exerq = info[2].to_i\n @last_category = info[3].to_i\n @exercises = info[4].split(\",\").collect! {|v| v.to_i}\n @rep_ex = info[4].to_i\n end", "def main\n\n if ARGV.length == 0 or ARGV[0] == \"-h\"\n puts \"makePWLfromCSV <file> where\n each line is a csv file\"\n exit\n end\n\n filename = ARGV[0]\n csvList = File.open(filename,\"r\")\n\n sample=1\n minRatio=0.0001\n\n while (!csvList.eof)\n line=csvList.gets.strip.chomp\n\n if line=~/^\\#/ \n #puts \"comment:#{line}\"\n next\n else\n #puts \"processing:#{line}\"\n filename=line\n end\n\n # \n # assuming file name is \n # config_process_voltage_temperature\n #\n base=File.basename(filename,\".csv\")\n arr=base.split(/_/)\n config=arr[1]\n process=arr[2]\n voltage=arr[3]\n temperature=arr[4]\n\n #arr.each{|item| puts item }\n #printf(\"%s,%s,%s\\n\",config,v,t)\n \n outFile = base + \".pwl\"\n\n out = File.open(outFile,\"w\")\n csv = File.open(filename,\"r\")\n puts \"opening \" + filename\n\n timeCurrentArr=Array.new\n j=0\n\n imin=1e9\n imax=0\n\n # \n # go through each line, store if\n # it is a line with comma and numbers\n #\n while (!csv.eof)\n data=csv.gets.strip.chomp\n #puts \"data line: \" + data\n\n if data=~/\\,/ then\n (t,i)=data.split(/,/)\n\n if is_num(t) and is_num(i) then \n #puts \"#{t} #{i} are numbers\" \n\n t=t.to_f\n i=i.to_f\n\n timeCurrentArr[j]=Array.new\n timeCurrentArr[j][0]=t\n timeCurrentArr[j][1]=i\n\n if i.abs>imax then\n imax=i.abs\n tmax=t\n indexMax=j\n end\n\n if i.abs<imin then\n imin=i.abs\n tmin=t\n indexMin=j\n end\n\n j+=1\n\n else\n #puts \"#{t} #{i} are not numbers\"\n end\n\n end\n end\n\n csv.close\n\n arrSize = timeCurrentArr.length\n puts \"arrSize: \" + arrSize.to_s + \" j:\" + j.to_s\n puts \"min: #{imin} at index #{indexMin}\"\n puts \"max: #{imax} at index #{indexMax}\"\n\n pwlArray=Array.new\n c=0\n\n # need to normalize the time to 0 as some\n # sims are offset in time\n initialTime=timeCurrentArr[0][0]\n initialCurrent=timeCurrentArr[0][0]\n\n #PWL waveform: (5E-12, -6.89266E-05)\n out.printf(\"PWL waveform: \")\n\n 0.upto(arrSize-1) do |j|\n\n check=(j.to_f/sample) \n\n #check to see if element of the array\n #is divisible by the sample size\n\n if check==check.to_i\n pwlArray[c]=Array.new\n t=timeCurrentArr[j][0]-initialTime\n\n # negate the data as the current is peaking negative\n i=-1 * timeCurrentArr[j][1]\n\n # after max value time is reached, make\n # sure ratio of the data indicates the\n # data is not essentially zero\n \n ratio = i.abs/imax\n #puts \"ratio: #{ratio} j:#{j} inxMax:#{indexMax} iabs:#{i.abs}\"\n if j<=indexMax then\n\n pwlArray[c][0]=t\n pwlArray[c][1]=i\n\n printf(\"(%.3e,%.3e)\\n\",t,i)\n out.printf(\"(%.3e,%.3e) \",t,i)\n\n c+=1\n\n elsif j>indexMax \n\n if ratio>minRatio then\n # keep on trucking\n #puts \"ratio ok:#{ratio}\"\n\n pwlArray[c][0]=t\n pwlArray[c][1]=i\n\n printf(\"(%.3e,%.3e)\\n\",t,i)\n out.printf(\"(%.3e,%.3e) \",t,i)\n\n c+=1\n else\n puts \"ratio low:#{ratio} at time #{t}\"\n end\n end\n end\n end\n \n out.printf(\"\\n\")\n out.close\n\n puts \"See: #{outFile}\"\n\n end\n\n csvList.close\nend", "def parse_sensors\n sensors = Array.new\n @data[7..12].map.with_index do |s,i|\n index = 7 + i\n zipped = @data[6].zip(@data[index])\n sensors[i] = WFSensor.new\n s.map.with_index do |e,n|\n case n\n when 0\n sensors[i].type = e\n when 1\n sensors[i].present = e \n when 2\n sensors[i].smrec = e\n when 3\n sensors[i].zeroavg = e\n when 4\n sensors[i].model = e \n end\n end\n end\n return sensors\n end", "def parse_sensor_data\n \n begin\n handled_messages = 0\n msg = \"\"\n\n while handled_messages < 100 do\n \n # output values\n messagetype = \"\"\n valuestring = \"\"\n\n msg = @serialport.read_nonblock(1)\n # search for valid start symbol, i.e. one of [h,v,q,a,p,l]\n if /[^hvqaplt]/.match(msg)\n # restart parsing process until a valid symbol is found\n # puts \"no valid messagetype found. got: #{msg}\"\n next\n end\n \n # assign messagetype\n messagetype = msg\n\n msg = @serialport.read_nonblock(1)\n # search for \" \"\n if /[^ ]/.match(msg)\n $logger.info(\"space missing after first byte. got: #{msg}\")\n next\n end\n ###\n msg = @serialport.read_nonblock(1)\n # search for a number or a \"-\"\n if /[^0-9|-]/.match(msg)\n \n next\n end\n \n valuestring = valuestring + msg\n ### \n # only allow 4 digit values to avoid infinite loop here.\n 4.times do \n msg = @serialport.read_nonblock(1)\n \n # search for a number or \"\\n\"\n if /[0-9]/.match(msg)\n valuestring = valuestring + msg\n else \n break \n end\n end\n ### \n \n # flush trailing \"\\n\" and \"\\r\"\n msg = @serialport.read_nonblock(1)\n \n # message parsing successful, invoke callback\n @callbackhandler.handle_sensor_event(messagetype, valuestring)\n\n handled_messages = handled_messages + 1\n end\n rescue EOFError\n # Finished processing the file\n \t $logger.error(\"EOFError while reading from the serial port\") \n rescue Exception => e\n $logger.error(\"exception caught: \" + e)\n end\n end", "def read_plex stream, fc, lcb, cbdata, dataclass\n cItems = (lcb-4)/(4+cbdata)\n cps = []\n items = []\n idx = fc\n ci = 0\n while ci < cItems+1\n cps << stream[idx..idx+3].unpack('l')[0]\n idx+=4\n ci+=1\n end\n ci=0\n if cbdata>0\n while ci < cItems\n item = dataclass.new\n item.read(stream[idx..idx+cbdata-1])\n idx+=cbdata\n items << item\n ci+=1\n end\n end\n return cps, items\n end", "def parse(data)\n\n # convert to utf-8\n data_utf8 = data.encode('UTF-8', :invalid => :replace, :replace => \"\")\n\n # split into nice rows\n rows = data_utf8.split(/\\r\\n?|\\n/)\n\n # to store units info\n units = {}\n\n # read values, store each doc in array\n docs = []\n\n rows.each do |row|\n doc = {}\n row.split(/\\s+|\\\\t+/).each_with_index do |value, index|\n if index < @@header.length\n name = @@header[index]\n if !value.nil? and !value.empty?\n # try to see if this can be a float\n begin\n value = Float(value.gsub(',', '.'))\n rescue ArgumentError\n end\n\n doc[name] = value\n end\n end\n end\n\n # point to our schema\n doc[\"schema\"] = \"http://api.npolar.no/schema/radiation-zeppelin-1.0-rc1\"\n\n docs << doc\n end\n\n docs\n end", "def parse\n\t\t\t\tdata = unpack(File.open(@filename, 'rb') {|io| io.read})\n\t\t\t\t@tunefile = BinReader.new.string_extractor(data, 12728)\n\t\t\t\tif @tunefile[/^[A-Z]:.*/] != @tunefile and File.extname(@tunefile) != \".LTQTune\"\n\t\t\t\t\t@tunefile = BinReader.new.string_extractor(data, 12872)\n end\n\t\t\t\tif @tunefile[/^[A-Z]:.*/] != @tunefile and File.extname(@tunefile) != \".LTQTune\"\n\t\t\t\t\t@tunefile = BinReader.new.string_extractor(data, 13750)\n\t\t\t\tend\n if @tunefile[/^[A-Z]:\\\\/].nil? or File.extname(@tunefile) != \".LTQTune\"\n raise StandardError, \"ParseError: Tunefile doesn't have a drive letter\"\n end\n\t\t\t\t@tunefile\n\t\t\t\tbegin \n\t\t\t\t raise StandardError, \"Failed to correctly parse method file for Tunefile location\" if @tunefile[/^[A-Z]:.*/] != @tunefile and File.extname(@tunefile) != \".LTQTune\"\n\t\t\t\trescue StandardError\n\t\t\t\t @tunefile = nil\n\t\t\t\t puts \"ParseError, skipping tunefile\"\n\t\t\t\tend\n\t\t\tend", "def load_info\n info = File.readlines @dir+\"info\"\n @last_quantity = info[0].chop\n @last_category = info[1].chop.to_i\n @exercises = info[2].chop.split(\",\")\n @last_repq = info[3].chop\n @rep_ex = info[4].chop\n end", "def read_attributes(data)\n count = data.read_vint\n count.times do\n usage = data.read_uint8\n case usage\n when 0x00, 0x02, 0x03, 0x30, 0xa1..0xaf\n @attributes << { usage: usage, data: data.read_hex(32) }\n when 0x20\n @attributes << { usage: usage, data: data.read_hex(20) }\n else\n # TODO: Parse into plain string?\n @attributes << { usage: usage, data: data.read_hex }\n end\n end\n end", "def construct\n @total_num_lines = File.readlines(@path).size\n tmp = {}\n prev = ''\n (@min..@total_num_lines).each { |i|\n if i > @max then\n tmp[i] = @lines[@max]\n else\n if !lines[i].nil? then\n tmp[i] = lines[i]\n prev = lines[i]\n else \n tmp[i] = prev\n end\n end\n }\n @lines = tmp\n end", "def load_ini\n last_file = nil\n last_speed = nil\n last_position = nil\n last_speeds = nil\n if File.exists? @ini_file\n File.open(@ini_file, \"r\") do |f|\n f.each do |line|\n last_file = line.sub(\"last_file=\", \"\").strip if line =~ /^last_file=/\n last_speed = line.sub(\"last_speed=\", \"\").strip.to_f if line =~ /^last_speed=/\n last_position = line.sub(\"last_position=\", \"\").strip.to_i if line =~ /^last_position=/\n if line =~ /^speeds=/\n last_speeds = line.sub(\"speeds=\", \"\").strip.split(\",\")\n last_speeds.map!{|s| s.to_f}\n end\n if line =~ /^partial_repeat=/\n @partial_repeat = line.sub(\"partial_repeat=\", \"\").strip\n if @partial_repeat == 'true'\n @partial_repeat = true\n else\n @partial_repeat = false\n end\n end\n @partial_duration = line.sub(\"partial_duration=\", \"\").strip.to_i if line =~ /^partial_duration=/\n end\n end\n end\n return last_file, last_speed, last_position, last_speeds\nend", "def parse\n # TODO: Try to convert lsynth parts, maybe flag parts that are troublesome for manual editing,\n # look up to see if I've stored a conversion from ldraw ID to Bricklink ID,\n # convert Ldraw color IDs to BL color IDs, etc.\n parts = {}\n temp_parts = []\n\n @lines.each_with_index do |line, i|\n # This will stop getting parts for the base model once a submodel is reached\n break if line.match(/0 FILE/) && i > 15\n\n @submodels << line.match(/\\w+\\.ldr/).to_s.downcase if line.match(/^1/) && line.match(/\\.ldr$/)\n @lsynthed_parts << line.gsub('0 SYNTH BEGIN', '').split if line =~ /^0 SYNTH BEGIN/\n next unless line.match(/^1/) && line.match(/.dat$/)\n\n part = line.match(/\\w+\\.dat/).to_s.gsub!('.dat', '')\n next if lsynth_part?(part)\n\n color = line.match(/^1\\s\\d+/).to_s.gsub!('1 ', '')\n bl_part = get_bl_part_number(part)\n temp_parts << [bl_part, color, part]\n end\n\n # Now go through all submodels to determine the parts belonging to the submodels\n temp_parts = handle_submodels(temp_parts)\n\n # Not yet functional\n # handle_lsynthed_parts(temp_parts)\n\n temp_parts.each do |info|\n if parts.key?(\"#{info[0]}_#{info[1]}\")\n parts[\"#{info[0]}_#{info[1]}\"]['quantity'] += 1\n else\n parts[\"#{info[0]}_#{info[1]}\"] = {}\n parts[\"#{info[0]}_#{info[1]}\"]['quantity'] = 1\n parts[\"#{info[0]}_#{info[1]}\"]['ldraw_part_num'] = info[2]\n end\n end\n\n parts\n end", "def read_data(file_object, data_group, time)\n # Convert to an object of class Tokfile::Ogyropsi if necessary\n file_object = file_object.internal_representation(time).to_ogyropsi unless file_object.kind_of? TokFile::Ogyropsi\n VARIABLES.each do |var|\n next unless in_data_group(data_group, var)\n varname = instance_varname(var)\n if data_group==\"all\"\n set(varname, file_object.send(varname)) if file_object.send(varname)\n else\n if file_object.send(varname)\n input = file_object.send(varname)\n case input\n when Integer, Float\n set(varname, input)\n when GSL::Vector\n case input.size\n when file_object.npsi\n #interp = GSL::Interp.alloc('cspline', file_object.npsi)\n #ep [file_object.psi.max, file_object.psi.min, @psi.max, @psi.min, 'end']\n #ep input\n #set(varname, interp.eval(file_object.psi, input, @psi))\n interp = GSL::ScatterInterp.alloc(:linear, [file_object.psi, input], false)\n set(varname, @psi.collect{|ps| interp.eval(ps)})\n end\n end\n end\n end\n\n end\n\n end", "def parse_input_file path, type\n begin\n ret = Hash.new\n file = File.new(path, \"r\")\n while (line = file.gets)\n arr=line.split(',')\n if type == \"base\"\n ret.merge!(arr[0] => arr[1].to_f)\n @base_prices = ret\n elsif\n ret.merge!(arr[0] => { :quantity => arr[1].to_f,:price=> arr[2].to_f } )\n @volume_prices = ret\n end\n end\n file.close\n end\n rescue => err\n puts \"Sorry, cannot open file: #{path}\"\nend", "def parse(filename, resolution)\n # first, parse everything into data\n data = [[0, 0, 0, 0, 0]]\n t_start = nil\n File.read(filename).each_line do |l|\n begin\n t = DateTime.parse(l[0...20])\n if t_start.nil?\n t_start = t \n end\n\n t_sec_now = ((t - t_start)*24*60*60).to_i\n\n t_sec_now = (t_sec_now / resolution) * resolution\n\n while data.last[0] + resolution < t_sec_now\n data.push data.last.clone\n data.last[0] += resolution\n end\n\n m = /UpdateTip:.*height=(\\d+) .* tx=(\\d+) .* cache=(.*)MiB\\((\\d+)txo/.match(l)\n if m\n height = m[1]\n tx = m[2]\n cache_MiB = m[3]\n cache_tx = m[4]\n\n # overwrite when second has not changed\n if (data.last[0] == t_sec_now)\n data.pop\n end\n data.push [t_sec_now, height, tx, cache_MiB, cache_tx]\n else\n if (data.last[0] != t_sec_now)\n data.push(data.last.clone)\n end\n data.last[0] = t_sec_now\n end\n rescue => e\n STDERR.puts \"'#{l.strip}': #{e}\"\n end\n end\n\n\n t_next = 0\n data.each do |d|\n if d[0] != t_next\n raise \"t_next does not match!\"\n end\n t_next += resolution\n yield d\n end\nend" ]
[ "0.6090547", "0.58828366", "0.5867111", "0.55441916", "0.548781", "0.54765326", "0.5422501", "0.53642905", "0.5346683", "0.5342109", "0.53296787", "0.532809", "0.5262677", "0.5226917", "0.52190655", "0.5205846", "0.52018166", "0.5182599", "0.5144276", "0.5141053", "0.5136983", "0.5129019", "0.5108548", "0.51036894", "0.5102087", "0.5100946", "0.5076566", "0.49982375", "0.49972656", "0.4979287" ]
0.78441226
0
A method to output a human readable report summarizing the data captured in the energy and power files. This method is called after the energy and power files have been parsed and the desired values calculated and comitted to variables.
def output_report # Have user indicate the type of renewable energy system that generated the file # The Aurora is type-agnostic: it only reports power and energy regardless of the type. # puts "Enter the number for the type of renewable production system?\n" puts "1.\tPV Solar\n" puts "2.\tThermal Solar\n" puts "3.\tOnshore Wind\n" puts "4.\tGeothermal\n" puts "5.\tHydroelectric\n" puts "6.\tBiomass\n" print "Your Choice: " warning = "" input = STDIN.gets.chomp case input.to_i when 1 @system_type = :PV_Solar when 2 @system_type = :Thermal_Solar when 3 @system_type = :Onshore_Wind when 4 @system_type = :Geothermal when 5 @system_type = :Hydroelectric when 6 @system_type = :Biomass else warning = "Invalid energy type give. Default is " @system_type = :PV_Solar end @carbon_savings = (@energy_amount / 1000.0) * (CO2_USGRID - ENERGY_TYPES[@system_type]) @ave_power = (@energy_amount / @energy_run_time).round(2) # Write a new output file. Note that this overwrites any existing file. output_file = File.open("Energy Report.txt", 'w+') text = create_text_report warning, TEXT_TEMPLATE output_file.write text output_file.close output_file = File.open("Energy Report.html", 'w+') html = create_text_report warning, HTML_TEMPLATE output_file.write html output_file.close puts "Created files: \"Engergy Report.txt\" and \"Engergy Report.html\"" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def report\n sprintf \"Number of paragraphs %d \\n\" <<\n \"Number of sentences %d \\n\" <<\n \"Number of words %d \\n\" <<\n \"Number of characters %d \\n\\n\" <<\n \"Average words per sentence %.2f \\n\" <<\n \"Average syllables per word %.2f \\n\\n\" <<\n \"Flesch score %2.2f \\n\" <<\n \"Flesh-Kincaid grade level %2.2f \\n\" <<\n \"Fog Index %2.2f \\n\",\n num_paragraphs, num_sentences, num_words, num_characters,\n words_per_sentence, syllables_per_word,\n flesch, kincaid, fog\n end", "def report\n output = \"#{@total}\\n\"\n output += \"#{@string}:\\n\"\n @dice_sets.each do |set|\n output += \"#{set.to_s}\\n\"\n end\n @mods.each do |mod|\n output += \"+\" if mod >= 0\n output += \"#{mod}\\n\"\n end\n \n output\n end", "def print_report\n sum = 0.0\n puts \"\\nSummary:\"\n puts '-'*8\n @days.each do |day|\n puts \"#{day[:day].strftime(\"%m/%d/%y\")}, %.2f hours\" % day[:hours]\n sum += day[:hours]\n end\n puts \"\\nTotal hours = %.2f\" % sum\n days = elapsed_days(@days[0][:day])\n puts \"Elapsed days = %d\" % days\n puts \"Average hrs per week = %.2f\" % (sum / (days / 7.0))\n puts\n end", "def stats_summary\n html = \"\"\n %w(inhale exhale cycle).each do |phase|\n %w(min max avg).each do |stat|\n time = format_time(self.meditations.map {|med| med.send(phase + \"_\" + stat)}.max)\n html += \"record #{phase} #{stat}: #{time}<br>\"\n end\n end\n html\n end", "def report\r\n\t\tputs \"Item Number #@@item_number\"\r\n\t\tputs \"Level : #@level\"\r\n\t\tputs \"Strength = #@strength\"\r\n\t\tputs \"Agility = #@agility\"\r\n\t\tputs \"Health = #@health\"\r\n\t\tputs \"Mana = #@mana\"\r\n\t\tputs\" \"\r\n\tend", "def report(properties)\n if (@short_report)\n tags = 0\n @stats.tagged_files.each {|line| tags += line[1] }\n known = 0\n @stats.known_exceptions.each {|line| known += line[1] }\n missing = 0\n @stats.missing_tags.each {|line| missing += line[1] }\n\n puts \"Licenser: scanned #{@stats.file_count} files in #{@stats.dir_count} directories.\"\n printf(\" Licensed files: %5d\\n\", tags)\n printf(\" Known exceptions: %5d\\n\", known)\n printf(\" Missing tags: %5d\\n\", missing)\n else\n puts \"Licenser: run completed at #{DateTime.now.strftime(\"%H:%M:%S on %b %d, %Y\")}\"\n puts \" scanned #{@stats.file_count} files in #{@stats.dir_count} directories.\"\n puts\n puts 'Licensed files'\n @stats.tagged_files.sort.each do |line|\n printf(\"%5d %s\\n\", line[1], line[0])\n end\n puts\n puts 'Known non-licensed files'\n @stats.known_exceptions.sort.each do |line|\n printf(\"%5d %s\\n\", line[1], line[0])\n end\n puts\n puts 'Missing tags'\n @stats.missing_tags.sort.each do |line|\n printf(\"%5d %s\\n\", line[1], line[0])\n end\n puts\n puts 'properties:'\n properties.each do |key, value|\n puts \" #{key} = #{value}\"\n end\n end\n end", "def output\n print_headings\n \n line_order.each do |line_name|\n stats = statistics[line_name]\n \n arr = [line_headings[line_name]] + column_order.collect {|col| stats[col]}\n print_line(arr)\n end\n \n print_separator\n print_summary\n end", "def verbose_report\n result = header\n result += \":\\n#{smell_list}\" if should_report\n result += \"\\n\"\n result\n end", "def report_results( timings )\n t = timings.first\n output.puts \n output.puts \" Total files read : #{\"%12d\" % t.value_stats.count}\"\n output.puts \" Total bytes read : #{\"%12d\" % t.value_stats.sum}\"\n output.puts \" Minimum filesize : #{\"%12d\" % t.value_stats.min}\"\n output.puts \" Average filesize : #{\"%16.3f\" % t.value_stats.mean}\"\n output.puts \" Maximum filesize : #{\"%12d\" % t.value_stats.max}\"\n output.puts \" Stddev of sizes : #{\"%16.3f\" % t.value_stats.stddev}\"\n output.puts\n\n output.puts [\"%28s\" % \"read order\", \"%20s\" % \"Elapsed time (sec)\", \"%22s\" % \"Read rate (bytes/sec)\" ].join(\" \")\n output.puts \"-\" * 72\n timings.each do |timing|\n p = [ ]\n p << \"%28s\" % timing.name\n p << \"%20.3f\" % timing.timed_stats.sum\n p << \"%22.3f\" % timing.rate\n output.puts p.join(\" \")\n end\n output.puts\n end", "def output_report\n\t\toutput_start\n\t\toutput_head\n\t\toutput_body_start\n\t\toutput_body\n\t\toutput_body_end\n\t\toutput_end\n\tend", "def print_report\n # total_bikes = @fleet.count \n # broken_bikes = @fleet.count {|b| b.is_broken?}\n # working_bikes = total_bikes-broken_bikes\n total_people = @people.count\n total_stations = @stations.count\n # show_stations = @stations.each do {|name, capacity| puts \"#{name}, #{capacity}\"}\n #tell me its name and capcity\n # puts \"Total bikes: #{total_bikes}\"\n # puts \"Broken bikes: #{broken_bikes}\"\n # puts \"Working bikes: #{working_bikes}\"\n puts \"Total people: #{total_people}\"\n # puts \"People with bikes: #{people_with_bikes}\"\n puts \"People without bikes #{people_without_bikes.count}\" \n puts \"Number of stations: #{total_stations}\" \n puts \"Stations:\"\n @stations.each do |station|\n puts \"#{station.name}, #{station.capacity}, #{station.bikes.count}\"\n end\n # result = \"total bikes #{total_bikes}\\n\" + \"broken bikes #{broken_bikes}\\n\" + \"working bikes #{working_bikes}\\n\"\n # result + \"total people #{total_people}\\n\" + \"people with bikes #{people_with_bikes}\\n\" + \"people without bikes #{people_without_bikes}\\n\" + \"number of stations #{total_stations}\\n\" + \"stations #{show_stations}\"\n end", "def report io = $stdout\n only = option[:only]\n\n data = analyze only\n\n io.puts \"Total score (lower is better) = #{self.total}\"\n\n if option[:summary] then\n io.puts\n\n self.summary.sort_by { |_,v| -v }.each do |file, score|\n io.puts \"%8.2f: %s\" % [score, file]\n end\n\n return\n end\n\n data.each_with_index do |item, count|\n prefix = \"%d) \" % (count + 1) if option[:number]\n\n match = item.identical? ? \"IDENTICAL\" : \"Similar\"\n\n io.puts\n io.puts \"%s%s code found in %p (mass%s = %d)\" %\n [prefix, match, item.name, item.bonus, item.mass]\n\n item.locations.each_with_index do |loc, i|\n loc_prefix = \"%s: \" % (?A.ord + i).chr if option[:diff]\n extra = \" (FUZZY)\" if loc.fuzzy?\n io.puts \" %s%s:%d%s\" % [loc_prefix, loc.file, loc.line, extra]\n end\n\n if option[:diff] then\n io.puts\n\n nodes = hashes[item.structural_hash]\n\n sources = nodes.map do |s|\n msg = \"sexp_to_#{File.extname(s.file).sub(/./, \"\")}\"\n self.respond_to?(msg) ? self.send(msg, s) : sexp_to_rb(s)\n end\n\n io.puts n_way_diff(*sources)\n end\n end\n end", "def report\n\t\t dir = \"./report/\"\n File.open(dir + \"method.mmd\", \"w\") do |f|\n f.puts \"# Methods #\"\n Dir[\"./experiments/*/*.rb\"].each do |desc|\n if File.basename(desc) == File.basename(File.dirname(desc)) + \".rb\"\n File.read(desc).split(\"\\n\").each do |line|\n if m = line.match(/^\\# (.+)/)\n f.puts m[1]\n else\n break\n end\n end\n f.puts\n f.puts\n end\n end\n end\n require 'csv'\n require \"yaml\"\n require File.dirname(__FILE__) + \"/stats\"\n CSV.open(dir + \"/data.csv\", \"w\") do |csv|\n data = {}\n Dir[\"./results/*/results.yaml\"].each do |res|\n d = YAML::load_file(res)\n da = {}\n d.each do |k, vals|\n da[k.to_s + \" mean\"], da[k.to_s + \" sd\"] = Stats::mean(vals), Stats::standard_deviation(vals)\n vals.each_with_index do |v, i|\n da[k.to_s + \" cv:\" + i.to_s] = v\n end\n end\n array_merge(data, da)\n end\n data.keys.map do |key| \n \t\t # calculate stats\n \t\t a = data[key]\n \t\t [key] + a\n \t\t end.transpose.each do |row|\n \t\t csv << row\n \t\t end\n end\n\t\t\n\t\tend", "def generate_report\n self.consume_stdin\n self.data_sorter\n\n @drivers.each do |driver|\n driver.total_duration\n driver.distance_calculator\n driver.average_speed\n end\n\n self.compile_report\n end", "def wrestler_output\n\n\t\tputs \"Name: #{self.values[:name]}\"\n\t\tputs \"Set: #{self.values[:set]}\"\n\t\tputs \"Singles Priority: #{self.values[:prioritys]}\"\n\t\tputs \"Tag Team Priority: #{self.values[:priorityt]}\"\n\t\tputs \"TT Probability: #{self.statistics[:tt_probability]}\"\n\t\tputs \"Card Rating: #{self.statistics[:total_card_rating]}\"\n\t\tputs \"OC Probability: #{self.statistics[:oc_probability]}\"\n\t\tputs \"Total Points-Per-Round: #{self.statistics[:total_card_points_per_round]}\"\n\t\tputs \"DQ Probability-Per-Round: #{self.statistics[:dq_probability_per_round]}\"\n\t\tputs \"P/A Probability-Per-Round: #{self.statistics[:pa_probability_per_round]}\"\n\t\tputs \"Submission Roll Probability-Per-Round: #{self.statistics[:sub_probability_per_round]}\"\n\t\tputs \"XX Roll Probability-Per-Round: #{self.statistics[:xx_probability_per_round]}\"\n\t\tputs \"Submission Loss Probability: #{self.points[:sub_prob]}\"\n\t\tputs \"Tag Team Save Probability: #{self.points[:tag_prob]}\"\n\t\tputs \"\\n\"\n\n\t\ttt_probability = \"%.1f\" % (self.statistics[:tt_probability] * 100) + \"%\"\n\t\tcard_rating = \"%.1f\" % self.statistics[:total_card_rating]\n\t\toc_probability = \"%.1f\" % (self.statistics[:oc_probability] * 100) + \"%\"\n\t\ttotal_card_points_per_round = \"%.3f\" % self.statistics[:total_card_points_per_round]\n\t\tdq_probability_per_round = \"%.1f\" % (self.statistics[:dq_probability_per_round] * 100) + \"%\"\n\t\tpa_probability_per_round = \"%.1f\" % (self.statistics[:pa_probability_per_round] * 100) + \"%\"\n\t\tsub_probability_per_round = \"%.1f\" % (self.statistics[:sub_probability_per_round] * 100) + \"%\"\n\t\txx_probability_per_round = \"%.1f\" % (self.statistics[:xx_probability_per_round] * 100) + \"%\"\n\t\t\n\t\tsub_prob = \"%.1f\" % (self.points[:sub_prob] * 100) + \"%\"\n\t\ttag_prob = \"%.1f\" % (self.points[:tag_prob] * 100) + \"%\"\n\n\t\tf = File.new('files/results.csv', 'a')\n\t\tf.write(\"#{self.values[:name]},#{self.values[:set]}, #{self.values[:prioritys]}, #{self.values[:priorityt]}, #{tt_probability}, #{card_rating}, #{oc_probability}, #{total_card_points_per_round}, #{dq_probability_per_round}, #{pa_probability_per_round}, #{sub_probability_per_round}, #{xx_probability_per_round}, #{sub_prob}, #{tag_prob}, \\n\")\n\t\tf.close\n\tend", "def endOfProgramReport\r\n puts \"###END OF PROGRAM REPORT###\"\r\n puts \"Values of declared variables\"\r\n i = 0\r\n while(i < @Declarations.length)\r\n puts @Declarations[i].to_s + \": \" + @DecValues[i].to_s\r\n i += 1\r\n end\r\n puts \"Value of regA: \" + @RegA.to_s\r\n puts \"Value of regB: \" + @RegB.to_s\r\n puts \"Value of PC: \" + @PC.to_s\r\n puts \"Value of zero bit: \" + @ZRBit.to_s\r\n puts \"Value of overflow bit: \" + @OFBit.to_s\r\n\r\n end", "def display_results\n\n title1 = sprintf(TITLE_ROW, \"METH\", \"PATH\", \"CALLED\", \"RESPONSE TIME(ms)\",\"\", \"\", \"\", \"\",\"\",\"\", \"DYNO\", \"MESSAGE\", \"SIZE\")\n puts(title1)\n printf(TITLE_ROW, \"\", \"\", \"Times\", \"Mean\",\" : \",\"Median\",\" : \",\"Mode\",\" : \", \"Range\", \"Busiest\", \"Average\", \"Max\")\n puts('-'*title1.length)\n @endpoints.each do | ep |\n if ep.called == 0 then\n printf(TITLE_ROW, ep.ep_method,ep.ep_path, \" Never\", \" \",\" : \",\" \",\" : \",\" \",\" : \", \" \", \" \", \" \", \" \")\n else\n printf(DATA_ROW,\n ep.ep_method,\n ep.ep_path,\n ep.called,\n ep.averages[:responses].mean,\n ep.averages[:responses].median,\n ep.averages[:responses].mode,\n ep.averages[:responses].range,\n ep.busiest_dyno,\n ep.averages[:bytes].mean,\n ep.averages[:bytes].hi)\n end\n end\n\n if @endpoints.unprocessed_lines > 0\n puts \"There were #{@endpoints.unprocessed_lines} Unprocessed Lines of data from #{@loglines} total lines in the log!\"\n else\n puts \"All #{@loglines} total lines in the log were processed!\"\n end\n end", "def print_report(products)\n \t\treport_string = \"\"\n \t\treport_string << \"Average Price: \" + average_price(products).to_s + \"$\\n\"\n\t\treport_string << \"Inventory by Brand:\\n\"\n\t\tbrands_hash = count_by_brand(products)\n\t\treport_string << print_hash(brands_hash)\n\t\treport_string << \"Inventory by Name:\\n\"\n\t\tnames_hash = count_by_name(products) \t\n\t\treport_string << print_hash(names_hash)\n\t\treport_string\n\tend", "def data_report(options={})\n puts \"\\n\\n\"\n puts \"**********************************\\n\"\n puts \"**********************************\"\n puts @last_log\nend", "def print_sales_report\n$report_file.puts \"\n ##### ######\n # # ## # ###### #### # # ###### ##### #### ##### #####\n # # # # # # # # # # # # # # # #\n ##### # # # ##### #### ###### ##### # # # # # # #\n # ###### # # # # # # ##### # # ##### #\n # # # # # # # # # # # # # # # # #\n ##### # # ###### ###### #### # # ###### # #### # # #\n********************************************************************************\n\"\nend", "def report(io = $stdout)\n io.puts \"%8.1f: %s\" % [total, \"flog total\"]\n io.puts \"%8.1f: %s\" % [average, \"flog/method average\"]\n\n return if option[:score]\n\n max = option[:all] ? nil : total * THRESHOLD\n if option[:group] then\n output_details_grouped io, max\n else\n output_details io, max\n end\n ensure\n self.reset\n end", "def print_products_report(toy_name,full_price,product_purchase_cnt,sales_sum,avg_price,avg_discount)\n $report_file.puts toy_name\n $report_file.puts \"*********************************\"\n $report_file.puts \"Retail price : #{full_price}\"\n $report_file.puts \"Product purchases: #{product_purchase_cnt}\"\n $report_file.puts \"Product Sales : #{sales_sum}\"\n $report_file.puts \"Average price : #{avg_price.round(2)}\"\n $report_file.puts \"Average Discount : $#{avg_discount.round(2)} \\n\\n\" \nend", "def display_report\n print \"#{@state} will lose #{predicted_deaths} people in this outbreak\"\n print \" and will spread across the state in #{speed_of_spread} months.\\n\\n\"\n end", "def raw_summary\n report = { \"version\" => { \"config\" => configuration_version, \"puppet\" => Puppet.version } }\n\n @metrics.each do |name, metric|\n key = metric.name.to_s\n report[key] = {}\n metric.values.each do |name, label, value|\n report[key][name.to_s] = value\n end\n report[key][\"total\"] = 0 unless key == \"time\" or report[key].include?(\"total\")\n end\n (report[\"time\"] ||= {})[\"last_run\"] = Time.now.tv_sec\n report\n end", "def summary\n @errors_file.write \"\\n =Summary=\"\n @errors_file.write \"\\n ==========================================================================================================\"\n @errors_file.write \"\\n API: #{@url}\"\n @errors_file.write \"\\n MSISDN: #{@MSISDN}\"\n @errors_file.write \"\\n Number of Requests: #{@number_of_requests-1}\"\n @errors_file.write \"\\n Number of Errors/Timeouts: #{@number_of_timeouts}\"\n @errors_file.write \"\\n Avg Response Time: #{@resonse_time/@total_number_of_requests}\"\n @errors_file.write \"\\n Max Response Time: #{@max_resonse_time}\"\n @errors_file.write \"\\n Max Response Time: #{@min_resonse_time}\"\n @errors_file.write \"\\n ==========================================================================================================\"\n summary_print\nend", "def html_report_stats\n @report << '<div id=\"title\"> General Statistics</div>'\n stat_tab = Ruport::Data::Table(%w[Stat Value])\n stat_tab << ['Number of servers Seen', @num_servers]\n stat_tab << ['Number of clients Seen', @num_clients]\n @num_by_cipher.each do |cipher, num|\n stat_tab << ['Encryption: ' + cipher, num]\n end\n @report << stat_tab.to_html\n @report << '<br /><br />'\n end", "def report\n table = Terminal::Table.new(headings: ['Basic', 'Result']) do |t|\n t << [\"Number of paragraphs\", number_of_paragraphs]\n t << [\"Number of sentences\", number_of_sentences]\n t << [\"Number of words\", number_of_words]\n t << [\"Number of characters\", number_of_characters]\n t << [\"Number of syllables\", number_of_syllables]\n\n t << :separator\n t << [\"Average words per sentence\", mean_of_words_per_sentence]\n t << [\"Average syllables per word\", mean_of_syllables_per_word]\n t << [\"Average syllables per content word\", syllables_per_content_word]\n\n t << :separator\n t << [\"Verbs Ocurrencies\", verb_incidence]\n t << [\"Nouns Ocurrencies\", noun_incidence]\n t << [\"Adjective Ocurrencies\", adjective_incidence]\n t << [\"Adverb Ocurrencies\", adverb_incidence]\n t << [\"Pronoun Ocurrencies\", pronoun_incidence]\n t << [\"Content Word Ocurrencies\", content_word_incidence]\n t << [\"Function Word Ocurrencies\", function_word_incidence]\n\n t << :separator\n t << [\"Flesch score\", flesch]\n end\n puts table\n end", "def report(io = $stdout)\n io.puts \"%8.1f: %s\" % [total_score, \"flog total\"]\n io.puts \"%8.1f: %s\" % [average, \"flog/method average\"]\n\n return if option[:score]\n\n if option[:group] then\n output_details_grouped io, threshold\n else\n output_details io, threshold\n end\n ensure\n self.reset\n end", "def print_products\n$report_file.puts \"\n\n | | | |\n _ __ _ __ ___ __| |_ _ ___| |_ ___\n| '_ \\\\| '__/ _ \\\\ / _` | | | |/ __| __/ __|\n| |_) | | | (_) | (_| | |_| | (__| |_\\\\__ \\\\\n| .__/|_| \\\\___/ \\\\__,_|\\\\__,_|\\\\___|\\\\__|___/\n| |\n|_|\n\t \t\t\t\t\t\t\t\t\t\"\nend", "def print_final_report\n puts; puts; puts \"=== FINAL DATABASE COUNTS ===\"\n puts; puts end_of_task_report\n puts; puts; puts \"=== BY SCHOOL ===\"\n puts by_school_report\n puts; AssessmentsReport.new.print_report\n end" ]
[ "0.69058824", "0.6702346", "0.65932405", "0.65494156", "0.6512902", "0.6418618", "0.64071625", "0.6316057", "0.62764263", "0.62680256", "0.625309", "0.62139255", "0.6195331", "0.6194943", "0.6151508", "0.6150987", "0.61461425", "0.61361474", "0.6134629", "0.6128694", "0.6116053", "0.61048144", "0.6104744", "0.60875326", "0.6085873", "0.6075412", "0.60726434", "0.6057692", "0.6052827", "0.6037963" ]
0.6865428
1
Returns all required details for the specified test.
def _test_details(test) suite_name = test.category test_name = test.name test_description = test.description test_name_key = "[#{test_name}] #{test_description}" [suite_name, test_name_key] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_test_info(test, target, project, machine, pool)\n handle_action_exceptions(__method__) do\n cmd_line = [\n \"gettestinfo '#{test}' '#{target}' '#{project}' '#{machine}' \"\\\n \"'#{pool}'\"\n ]\n cmd_line << 'json' if @json\n\n handle_return(@toolshck_ether.cmd(cmd_line.join(' ')))\n end\n end", "def info(test_id, options={})\n args = {testId: test_id}.merge(options)\n get('testinfo', args)\n end", "def test_info(tests_suite, test_name)\n tests_info.dig(tests_suite, test_name) || {}\n end", "def get_all_tests_info\n info = {}\n\n # A map of hint.id to the hint object\n info[:hints] = {}\n self.hints.each do |hint|\n info[:hints][hint.id] = hint\n end\n\n # A mapping of mistake.id to hint.id\n info[:hintmap] = {}\n\n # A list of testcases, each of which contains the testcase itself and a list of mistakes\n # associated with the testcase\n info[:testcases] = []\n testcases = self.tests\n testcases.each do |testcase|\n t = {}\n t[:testcase] = testcase\n\n t[:mistakes] = testcase.mistakes\n testcase.mistakes.each do |mistake|\n # Each testcase has its own mistakes, which have unique ids\n # Associate each of these ids with a hint\n info[:hintmap][mistake.id] = mistake.hint.id\n end\n\n info[:testcases] << t\n end\n\n return info\n end", "def initTestDetails\n @Type = nil\n @ProductID = nil\n @ToolID = nil\n @ScriptID = nil\n @TestName = 'unknown'\n @InstallTest = nil\n\n # Get the ID of the test, based on its class name\n lClassName = self.class.name\n if (lClassName.match(/^WEACE::Test::Install::.*$/) != nil)\n @InstallTest = true\n if (lClassName.match(/^WEACE::Test::Install::Master::.*$/) != nil)\n @Type = 'Master'\n else\n @Type = 'Slave'\n end\n lMatchData = lClassName.match(/^WEACE::Test::Install::Slave::Adapters::(.*)::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Adapters::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Adapters::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Listeners::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::Install::.*::Providers::(.*)$/)\n if (lMatchData == nil)\n log_debug \"Unable to parse test case name: #{lClassName}.\"\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID, @ToolID = lMatchData[1..2]\n end\n else\n @ProductID, @ToolID, @ScriptID = lMatchData[1..3]\n end\n else\n @InstallTest = false\n if (lClassName.match(/^WEACE::Test::Master::.*$/) != nil)\n @Type = 'Master'\n else\n @Type = 'Slave'\n end\n lMatchData = lClassName.match(/^WEACE::Test::Slave::Adapters::(.*)::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Adapters::(.*)::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Adapters::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Listeners::(.*)$/)\n if (lMatchData == nil)\n lMatchData = lClassName.match(/^WEACE::Test::.*::Providers::(.*)$/)\n if (lMatchData == nil)\n log_debug \"Unable to parse test case name: #{lClassName}.\"\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID = lMatchData[1]\n end\n else\n @ProductID, @ToolID = lMatchData[1..2]\n end\n else\n @ProductID, @ToolID, @ScriptID = lMatchData[1..3]\n end\n end\n end", "def test_info(project_name, plan_name, test_case_name)\n test_plan_id = test_plan_id(project_name, plan_name)\n test_cases = test_cases_for_test_plan(test_plan_id)\n\n test_cases.values.find do |test_case|\n test_case[:name] == test_case_name\n end\n end", "def show\n @tags = TestTag.with_diagnostic(@diagnostic)\n @profiles = @diagnostic.profiled_testings.group_by(&:test_profile)\n end", "def investigate\n puts \"\\nRequesting JSON from #{url} and testing\"\n tests.each_pair do |test, block|\n print \" - #{test}\\n\"\n check test, block\n end\n summary\n exit_status\n end", "def tests_info\n unless defined?(@tests_info_cache)\n @tests_info_cache =\n if File.exist?(@tests_info_file)\n JSON.parse(File.read(@tests_info_file)).map do |tests_suite_str, tests_suite_info|\n [\n tests_suite_str.to_sym,\n tests_suite_info.transform_values { |test_info| test_info.transform_keys(&:to_sym) }\n ]\n end.to_h\n else\n {}\n end\n end\n @tests_info_cache\n end", "def index\n @test_details = TestDetail.all\n end", "def show\n @test_results = @test_run.test_results\n end", "def extract_metadata_from_test(key)\n test = find_test(key)\n test_metadata = test.collect_metadata(true)\n extracted_metadata = {}\n BaseTest::METADATA_FIELDS.each do |field|\n field_hash = {}\n test_metadata.each { |tm| field_hash[tm[:test_method]] = tm[field] }\n extracted_metadata[field] = field_hash\n end\n extracted_metadata\n end", "def getFullStatus\n JSON.parse(@client[\"/LoadTest?loadTestId=#{@test_id}\"].get)[0].to_h\n end", "def test_stats(example)\n file_path = example.metadata[:file_path].gsub('./qa/specs/features', '')\n api_fabrication = ((example.metadata[:api_fabrication] || 0) * 1000).round\n ui_fabrication = ((example.metadata[:browser_ui_fabrication] || 0) * 1000).round\n\n {\n name: 'test-stats',\n time: time,\n tags: {\n name: example.full_description,\n file_path: file_path,\n status: example.execution_result.status,\n smoke: example.metadata.key?(:smoke).to_s,\n reliable: example.metadata.key?(:reliable).to_s,\n quarantined: quarantined(example.metadata),\n retried: ((example.metadata[:retry_attempts] || 0) > 0).to_s,\n job_name: job_name,\n merge_request: merge_request,\n run_type: run_type,\n stage: devops_stage(file_path),\n testcase: example.metadata[:testcase]\n },\n fields: {\n id: example.id,\n run_time: (example.execution_result.run_time * 1000).round,\n api_fabrication: api_fabrication,\n ui_fabrication: ui_fabrication,\n total_fabrication: api_fabrication + ui_fabrication,\n retry_attempts: example.metadata[:retry_attempts] || 0,\n job_url: QA::Runtime::Env.ci_job_url,\n pipeline_url: env('CI_PIPELINE_URL'),\n pipeline_id: env('CI_PIPELINE_ID'),\n merge_request_iid: merge_request_iid\n }\n }\n rescue StandardError => e\n log(:error, \"Failed to transform example '#{example.id}', error: #{e}\")\n nil\n end", "def diagnostic_test_details\n begin\n @project_id = params[:project_id]\n user_assigned = current_user.is_assigned_to_project(params[:project_id])\n @data_point = DiagnosticTestDetailDataPoint.new\n action = ''\n by_category = EfSectionOption.is_section_by_category?(params[:extraction_form_id], 'diagnostic_test_detail')\n if by_category\n @data = QuestionBuilder.get_questions(\"diagnostic_test_detail\", params[:study_id], params[:extraction_form_id], {:user_assigned => user_assigned, :is_by_diagnostic_test=>true, :include_total=>false})\n action = 'question_based_section_by_category'\n else\n action = 'question_based_section'\n @data = QuestionBuilder.get_questions(\"diagnostic_test_detail\", params[:study_id], params[:extraction_form_id], {:user_assigned => user_assigned})\n end\n # Now get any additional user instructions for this section\n @ef_instruction = EfInstruction.find(:first, :conditions=>[\"ef_id = ? and section = ? and data_element = ?\", params[:extraction_form_id].to_s, \"DIAGNOSTIC_TEST_DETAILS\", \"GENERAL\"])\n @ef_instruction = @ef_instruction.nil? ? \"\" : @ef_instruction.instructions\n\n render :action=>\"#{action}\", :layout=>false\n rescue Exception => e\n puts \"ERROR: #{e.message}\\n\\n#{e.backtrace}\\n\\n\"\n end\n end", "def details\n p '===== details ====='\n p \"Main TABLE: #{@main_t}\"\n p \"MAX_FREQUENCY_METRIX\"\n p @cache_mfx_table\n '===== details ====='\n end", "def list_details\n puts \"Name: \" + @name\n puts \"Description: \" + @details\n puts \"Exercise Time: \" + @duration\n end", "def show\n @product = Product.find(params[:id])\n @tests = @product.tests\n end", "def tests\n @tests ||= load_json(test_plan_path)&.fetch(:tests) if test_plan_path\n end", "def describe_tester(tester)\n return unless tester\n\n rows = []\n\n rows << [\"First name\", tester.first_name]\n rows << [\"Last name\", tester.last_name]\n rows << [\"Email\", tester.email]\n\n groups = tester.raw_data.get(\"groups\")\n\n if groups && groups.length > 0\n group_names = groups.map { |group| group[\"name\"][\"value\"] }\n rows << [\"Groups\", group_names.join(', ')]\n end\n\n if tester.latest_install_date\n rows << [\"Latest Version\", tester.full_version]\n rows << [\"Latest Install Date\", tester.pretty_install_date]\n end\n\n if tester.devices.length == 0\n rows << [\"Devices\", \"No devices\"]\n else\n rows << [\"#{tester.devices.count} Devices\", \"\"]\n tester.devices.each do |device|\n current = \"\\u2022 #{device['model']}, iOS #{device['osVersion']}\"\n\n if rows.last[1].length == 0\n rows.last[1] = current\n else\n rows << [\"\", current]\n end\n end\n end\n\n puts Terminal::Table.new(\n title: tester.email.green,\n rows: rows\n )\n end", "def show\r\n @phr = Phr.find(params[:phr_id])\r\n @test = @phr.tests.find(params[:id])\r\n end", "def inspect\n test_cases.each do |tc|\n puts tc.print\n end\n end", "def tests\n execution_variables['tests']\n end", "def testi_display_result\n\t\t\tputs testi_stats\n\t\tend", "def testtest_params\n params[:testtest]\n end", "def get_ab_tests(opts = {})\n @transporter.read(:GET, '/2/abtests', {}, opts)\n end", "def get_all_synthetics_tests\n request(Net::HTTP::Get, \"/api/#{API_VERSION}/synthetics/tests\", nil, nil, false)\n end", "def test_names\n line_tests.collect{|line_test| Test.find(line_test.test_id).name}.join(\", \")\n end", "def show\n @test_summary = TestSummary.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @test_summary }\n end\n end", "def show\n @subject_class = @test.subject_class\n @students = @test.subject_class.students.order(:name)\n @test_questions = @test.test_questions\n @test_question = TestQuestion.new\n @test_question.test_id = @test.id\n end" ]
[ "0.65954244", "0.64390916", "0.64280754", "0.6305013", "0.61831254", "0.6040682", "0.5949464", "0.5923676", "0.58873045", "0.5881611", "0.5852258", "0.5836551", "0.58081657", "0.57539564", "0.5749172", "0.57247925", "0.57119405", "0.5700864", "0.56797343", "0.5671683", "0.56606036", "0.5645506", "0.5644554", "0.56112236", "0.55710304", "0.5565417", "0.55558676", "0.5551861", "0.5547824", "0.55370104" ]
0.71877456
0
Method for the message 'finaliser_finished'.
def finaliser_finished(source, *args) @manager.allure_stop end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def finished\n @finished = true\n end", "def finalise\n end", "def finished?; @finished; end", "def finish\n end", "def after_finished\n end", "def finish\n #\n end", "def finished!\n t = Time.now.utc\n update_attribute(:finished_at, t)\n # Save errors counts\n if errs = error_messages\n BackupJobError.increment_errors_count(*errs)\n end\n backup_source.backup_complete!\n on_finish :errors => errs, :messages => messages\n end", "def finish\r\n #\r\n end", "def finished; end", "def finish_exec\n listener.finished_successfully\n end", "def finalize!\n @finalized = true\n self\n end", "def finish\n raise \"finish() Not Implemented on worker #{self.class.name}\"\n end", "def finish\n #\n end", "def finish\n @finish = true\n end", "def finish\n @Done = true \n end", "def finalize(success = true)\n committer.finalize(success)\n end", "def on_finished(&block)\n @finished_handler = block\n end", "def finalize(bool=true)\n update(:finalized => bool)\n end", "def action_complete() self.finished = true; end", "def finish()\n #This is a stub, used for indexing\n end", "def finalize(success = true)\n @committer.finalize(success) if @committer\n end", "def finalized; end", "def finished=(_arg0); end", "def finished_compressing\n %Q{Compressing done ...}\n end", "def finished?\n @finished\n end", "def finished?\n @finished\n end", "def finished?\n @finished\n end", "def finished?\n @finished\n end", "def did_finish\n collector.did_finish\n end", "def on_message_complete\n @finished = true\n end" ]
[ "0.6740235", "0.6725344", "0.6647908", "0.6572862", "0.6520311", "0.6501888", "0.64478314", "0.64406174", "0.64161104", "0.64066255", "0.6390644", "0.6384824", "0.63740396", "0.63680273", "0.635759", "0.63533556", "0.6322745", "0.630722", "0.62759674", "0.62667763", "0.6264785", "0.62559456", "0.6248033", "0.6226382", "0.6221926", "0.6221926", "0.6221926", "0.6221926", "0.6192723", "0.6177805" ]
0.71496
0
Method for the message 'runner_started'.
def runner_started(source, *args) @manager.allure_start end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run_started(current_run_status)\n update_run_status(current_run_status)\n\n disable_reporter_on_error do\n send_to_data_collector(\n Chef::DataCollector::Messages.run_start_message(current_run_status)\n )\n end\n end", "def start\r\n return if running?\r\n\r\n log(\"Starting Runner...\")\r\n run!\r\n end", "def report_start_run\n @run_status = Moto::Reporting::RunStatus.new\n @run_status.initialize_run\n\n @listeners.each do |l|\n l.start_run\n end\n end", "def start!\n return if started?\n\n self.status = \"started\"\n self.start = Time.now.to_s\n end", "def start_run\n # Abstract\n end", "def start_run\n # Abstract\n end", "def start!\n\t\t\t@started ||= Clock.now\n\t\tend", "def start_run; end", "def start\n @runner = Runner.new @options\n if @runner.nil?\n @raise [:task_has_failed]\n end\n notify_start\n run_all if @options[:all_on_start]\n end", "def start(commands, runner)\n end", "def starting?; event(:start).pending? end", "def start args\n change_value \"status\", \"started\", args\n 0\n end", "def start name\n TodoRunner.start = name\n end", "def started? # :nodoc:\n @started\n end", "def test_step_started(source, step_name, *args)\n test = source.test\n suite_name, test_name = _test_details(test)\n\n @manager.allure_start_step(suite_name, test_name, step_name)\n end", "def started?; end", "def started(build, listener)\n end", "def set_runner\n @runner = Runner.find(params[:id])\n end", "def set_runner\n @runner = Runner.find(params[:id])\n end", "def start\n start_message\n setup_options\n validate!\n setup_jobs\n boot_manager\n end", "def test_start_started_job\n job 'job'\n start 'job'\n start_message = start 'job'\n assert_message(\"Timeclock tried to start job 'job'.\n But 'job' is already started.\",\n start_message)\n end", "def start_message\n ActiveHook.log.info(\"* Worker #{@id} started, pid: #{@pid}\")\n end", "def started; end", "def start\n data = Storm::Base::SODServer.remote_call '/Server/start',\n :uniq_id => @uniq_id\n data[:started]\n end", "def player_started(player)\n output({\n :event => \"player_started\",\n :id => Events.generate_uuid,\n :timestamp => Events.timestamp,\n :name => player.name,\n :url => player.url,\n :pid => player.uuid\n })\n end", "def start\n @actions << :start\n end", "def before_start\n self.started_at = Time.now\n end", "def runner\n \nend", "def started?\n\t\tif self.timer == nil\n\t\t\treturn false\n\t\tend\n\t\treturn self.timer.status == \"--running--\"\n\tend", "def start\n\t\tself.sender.start\n\tend" ]
[ "0.67682904", "0.67403924", "0.63755655", "0.6341607", "0.63039285", "0.63039285", "0.62642443", "0.6197169", "0.6130598", "0.6123241", "0.6042088", "0.6020047", "0.5999254", "0.59421015", "0.59312004", "0.58903176", "0.58870727", "0.5860562", "0.5860562", "0.5837585", "0.5833759", "0.5821296", "0.57563174", "0.57517594", "0.5742321", "0.5732887", "0.5730888", "0.57244647", "0.56759983", "0.56672907" ]
0.75264776
0
Method for the message 'test_screenshot'.
def test_screenshot(source, file) test = source.test suite_name, test_name = _test_details(test) @manager.allure_add_attachment(suite_name, test_name, file: file) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def screenshot _value\n send_cmd(\"screenshot #{_value}\")\n end", "def take_screenshot\n $browser.screenshot.save \"#{$image_folder}#{$testcase}_#{@var2}.png\"\n @var2+=1\n end", "def default_screenshot(message)\n [\"./screenshot.jpg\", message]\n end", "def take_screenshot(_scenario)\n screenshot_dir = \"#{FigNewton.screenshot_directory}/#{$date_and_time}\"\n FileUtils.mkdir screenshot_dir unless File.directory? screenshot_dir\n encoded_img = @browser.driver.screenshot_as(:base64)\n embed(\"data:image/png;base64,#{encoded_img}\", 'image/png')\nend", "def test_step_screenshot(source, step_name, file)\n test = source.test\n suite_name, test_name = _test_details(test)\n\n @manager.allure_add_attachment(suite_name, test_name, file, step: step_name, title: File.basename(file))\n end", "def add_screenshot(scenario)\n nome = scenario.name.tr(' ', '_').downcase!\n captura = page.save_screenshot(\"log/screenshots/#{nome}.png\")\n attach(captura, 'image/png')\nend", "def take_screenshot(scenario)\r\n screen_name = \"log/screens/\" +scenario.name+\".png\"\r\n page.save_screenshot(screen_name) rescue nil\r\n embed(screen_name, 'image/png') rescue nil\r\nend", "def take_screenshot(scenario)\r\n scenario_name = \"#{scenario.name}_step\"\r\n sshot_name = \"log/screens/\" + scenario_name +\".png\"\r\n @browser.screenshot.save(sshot_name) rescue nil\r\n embed(sshot_name, 'image/png') rescue nil\r\nend", "def screenshot_small\n screenshot(:small)\n end", "def make_screenshot\n Logbook.step('Taking a screenshot of a result page')\n @browser.save_screenshot(\"screenshots/screenshot - #{Time.now.strftime('%Y-%m-%d %H-%M-%S')}.png\")\n end", "def take_screenshot(scenario)\n if scenario.failed?\n scenario_name = \"#{(convert_turkish_characters scenario.name)}\"\n scenario_name= scenario_name.split(\" \").join('-').delete(',')\n puts scenario_name\n time = Time.now.strftime(\"%H.%M-%m.%d.%Y\")\n time=time.to_s\n page.save_screenshot(File.absolute_path(\"features/screenshots/FAIL-#{time}-count-#{$screenshot_counter}-#{scenario_name[0..50]}.png\"))\n end\nend", "def screenshot(driver,sess_time,shot_num,descr)\n filename = \"shot-#{shot_num}-#{driver.current_url.sub(\"http://\",\"\").sub(\"admin:123@\",\"\").gsub(\"/\",\"-\")}-(#{descr})-#{sess_time}.png\"\n # driver.save_screenshot (\"shot-#{shot_num}-#{driver.current_url.sub(\"https://format-staging.com/\",\"\").gsub(\"/\",\"-\")}-(#{descr})-#{sess_time}.png\")\n driver.save_screenshot(filename)\n # puts (\" 📸 Shot #{shot_num} (#{driver.current_url})\")\n puts (\" 📸 #{filename}\")\n return 1\nend", "def snagScreenshot\n thing = waitForObject(@symbolicName)\n image = grabWidget(thing)\n format = \"PNG\"\n ssName = thing.name + \".\" + format\n ssLoc = Log.testLogLocation\n image.save(ssLoc + ssName, format)\n Log.AppendLog(\"Taking screenshot of: \" + @name + \" symbolicName: \" + @symbolicName + \" and saving to Location: \" + ssLoc)\n return ssName\n end", "def screenshot(name=\"screenshot\")\n page.driver.render(\"public/#{name}.jpg\",full: true)\n end", "def screenshot_large\n screenshot()\n end", "def take_failed_screenshot\n return unless failed? && supports_screenshot? && Capybara::Session.instance_created?\n\n take_screenshot\n metadata[:failure_screenshot_path] = relative_image_path if Minitest::Runnable.method_defined?(:metadata)\n end", "def screenshot\n @browser.save_screenshot(\"screenshot.png\")\n end", "def screenshot\n bridge.element_screenshot @id\n end", "def save_screenshot\n @suite.p \"-- CAPTURE SCREENSHOT ::\"\n begin\n screenshot_flag = true\n filename = (ENV['REPORTS_DIR'] + \"/\" + self.class.name + '.png')\n @suite.capture_screenshot(filename)\n @suite.p \"-- SCREENSHOT CAPTURED TO: {#{filename}}\"\n screenshot_flag = false\n rescue => e\n if screenshot_flag\n @suite.p \"FAILED TO CAPTURE SCREENSHOT: \"\n @suite.p e.inspect\n @suite.p e.backtrace\n end\n end\n end", "def screenshot_and_save_page\n Capybara::Screenshot.screenshot_and_save_page\nend", "def save_shot(screenshot)\n\t\t@browser.screenshot.save(screenshot)\n\tend", "def screenshot\n Screenshot.new self\n end", "def send_screenshot(event, map = nil, ret = false, page: nil, offset: nil)\n # Parse message parameters\n initial = page.nil?\n msg = fetch_message(event, initial)\n hash = parse_palette(event)\n msg = hash[:msg]\n h = map.nil? ? parse_highscoreable(msg, partial: true, mappack: true) : map\n nav = parse_nav(msg) || !initial\n \n # Multiple matches, send match list\n if h.is_a?(Array)\n format_level_matches(event, msg, page, initial, h, 'search')\n return\n end\n\n # Single match, retrieve screenshot\n #scores = scores.nav(offset.to_i)\n h = h.map if !h.is_a?(MappackHighscoreable)\n screenshot = Map.screenshot(hash[:palette], file: true, h: h)\n raise OutteError.new \"Failed to generate screenshot!\" if screenshot.nil?\n\n # Determine if screenshot needs to be spoiled\n spoiler = h.is_mappack? && h.mappack.code == 'ctp' && !(event.channel.type == 1 || event.channel.id == CHANNEL_CTP_SECRETS) ? true : false\n \n # Send response\n str = \"#{hash[:error]}Screenshot for #{h.format_name} in palette #{verbatim(hash[:palette])}:\"\n file = screenshot\n return [file, str, spoiler] if ret\n if nav\n # Attachments can't be modified so we're stuck for now\n send_message_with_interactions(event, str, nil, false, [file])\n else\n event << str\n event.attach_file(file, spoiler: spoiler)\n end\nrescue => e\n lex(e, \"Error sending screenshot.\", event: event)\nend", "def screenshot(filename)\n platform.screenshot(filename)\n end", "def screenshot path = '~/Desktop'\n capture_screen self, path\n end", "def screenshot(name)\n begin\n @screenshots[name] = @browser.screenshot.base64\n rescue StandardError => ex\n @logger.warn(\"Unable to take screenshot '#{name}' due to an error \"\\\n \"(#{ex.class}: #{ex})\")\n end\n end", "def png\n @driver.screenshot_as(:png)\n end", "def screenshot(project_id, screenshot_id)\n c_r Lokalise::Resources::Screenshot, :find, [project_id, screenshot_id]\n end", "def set_screenshot\n @screenshot = Screenshot.find(params[:id])\n end", "def compare_screenshots\n if COMPARE_SCREENSHOTS == 'True' && example_name\n # If there is a expected image then compare\n if FileTest.exists?(\"screenshots/expected/#{scenario_name}/#{example_name}/#{screenshot_id}.png\")\n FileUtils.mkdir(\"screenshots/diff/#{scenario_name}/#{example_name}\") unless FileTest.directory?(\"screenshots/diff/#{scenario_name}/#{example_name}\")\n compare_images(\"screenshots/actual/#{scenario_name}/#{example_name}/#{screenshot_id}.png\", \"screenshots/expected/#{scenario_name}/#{example_name}/#{screenshot_id}.png\",\n \"screenshots/diff/#{scenario_name}/#{example_name}/#{screenshot_id}.png\", image_difference_percentage_tolerance)\n end\n elsif COMPARE_SCREENSHOTS == 'True' && !example_name\n if FileTest.exists?(\"screenshots/expected/#{scenario_name}/#{screenshot_id}.png\")\n FileUtils.mkdir(\"screenshots/diff/#{scenario_name}\") unless FileTest.directory?(\"screenshots/diff/#{scenario_name}\")\n compare_images(\"screenshots/actual/#{scenario_name}/#{screenshot_id}.png\", \"screenshots/expected/#{scenario_name}/#{screenshot_id}.png\",\n \"screenshots/diff/#{scenario_name}/#{screenshot_id}.png\", image_difference_percentage_tolerance)\n end\n end\nend" ]
[ "0.7236884", "0.71927583", "0.7113932", "0.70880306", "0.70631313", "0.70532686", "0.704742", "0.70206857", "0.6987112", "0.6959128", "0.6921215", "0.6851582", "0.68442297", "0.68353575", "0.67949533", "0.6793308", "0.67815936", "0.6781188", "0.6768569", "0.67298394", "0.6664298", "0.66073906", "0.6583333", "0.6529601", "0.6482383", "0.6375325", "0.63547343", "0.6354439", "0.63511616", "0.63464814" ]
0.72908276
0
Method for the message 'test_step_screenshot'.
def test_step_screenshot(source, step_name, file) test = source.test suite_name, test_name = _test_details(test) @manager.allure_add_attachment(suite_name, test_name, file, step: step_name, title: File.basename(file)) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def take_screenshot(scenario)\r\n scenario_name = \"#{scenario.name}_step\"\r\n sshot_name = \"log/screens/\" + scenario_name +\".png\"\r\n @browser.screenshot.save(sshot_name) rescue nil\r\n embed(sshot_name, 'image/png') rescue nil\r\nend", "def take_screenshot\n $browser.screenshot.save \"#{$image_folder}#{$testcase}_#{@var2}.png\"\n @var2+=1\n end", "def take_screenshot(scenario)\n if scenario.failed?\n scenario_name = \"#{(convert_turkish_characters scenario.name)}\"\n scenario_name= scenario_name.split(\" \").join('-').delete(',')\n puts scenario_name\n time = Time.now.strftime(\"%H.%M-%m.%d.%Y\")\n time=time.to_s\n page.save_screenshot(File.absolute_path(\"features/screenshots/FAIL-#{time}-count-#{$screenshot_counter}-#{scenario_name[0..50]}.png\"))\n end\nend", "def add_screenshot(scenario)\n nome = scenario.name.tr(' ', '_').downcase!\n captura = page.save_screenshot(\"log/screenshots/#{nome}.png\")\n attach(captura, 'image/png')\nend", "def take_screenshot(scenario)\r\n screen_name = \"log/screens/\" +scenario.name+\".png\"\r\n page.save_screenshot(screen_name) rescue nil\r\n embed(screen_name, 'image/png') rescue nil\r\nend", "def make_screenshot\n Logbook.step('Taking a screenshot of a result page')\n @browser.save_screenshot(\"screenshots/screenshot - #{Time.now.strftime('%Y-%m-%d %H-%M-%S')}.png\")\n end", "def take_screenshot(_scenario)\n screenshot_dir = \"#{FigNewton.screenshot_directory}/#{$date_and_time}\"\n FileUtils.mkdir screenshot_dir unless File.directory? screenshot_dir\n encoded_img = @browser.driver.screenshot_as(:base64)\n embed(\"data:image/png;base64,#{encoded_img}\", 'image/png')\nend", "def test_screenshot(source, file)\n test = source.test\n suite_name, test_name = _test_details(test)\n\n @manager.allure_add_attachment(suite_name, test_name, file: file)\n end", "def screenshot _value\n send_cmd(\"screenshot #{_value}\")\n end", "def take_failed_screenshot\n return unless failed? && supports_screenshot? && Capybara::Session.instance_created?\n\n take_screenshot\n metadata[:failure_screenshot_path] = relative_image_path if Minitest::Runnable.method_defined?(:metadata)\n end", "def screenshot\n bridge.element_screenshot @id\n end", "def default_screenshot(message)\n [\"./screenshot.jpg\", message]\n end", "def screenshot_small\n screenshot(:small)\n end", "def snagScreenshot\n thing = waitForObject(@symbolicName)\n image = grabWidget(thing)\n format = \"PNG\"\n ssName = thing.name + \".\" + format\n ssLoc = Log.testLogLocation\n image.save(ssLoc + ssName, format)\n Log.AppendLog(\"Taking screenshot of: \" + @name + \" symbolicName: \" + @symbolicName + \" and saving to Location: \" + ssLoc)\n return ssName\n end", "def screenshot\n @browser.save_screenshot(\"screenshot.png\")\n end", "def save_screenshot\n @suite.p \"-- CAPTURE SCREENSHOT ::\"\n begin\n screenshot_flag = true\n filename = (ENV['REPORTS_DIR'] + \"/\" + self.class.name + '.png')\n @suite.capture_screenshot(filename)\n @suite.p \"-- SCREENSHOT CAPTURED TO: {#{filename}}\"\n screenshot_flag = false\n rescue => e\n if screenshot_flag\n @suite.p \"FAILED TO CAPTURE SCREENSHOT: \"\n @suite.p e.inspect\n @suite.p e.backtrace\n end\n end\n end", "def screenshot_and_save_page\n Capybara::Screenshot.screenshot_and_save_page\nend", "def failed(*args)\n begin\n CucumberCounters.error_counter += 1\n file_name = format('tmp/capybara/error_%03d.png',\n CucumberCounters.error_counter)\n Capybara.page.save_screenshot(file_name, full: true)\n Rails.logger.info(\"[Cucumber] Saved screenshot of error for #{ @scenario_name } to #{ file_name }\")\n rescue\n Rails.logger.info('[Cucumber] Cannot make screenshot of failure')\n end\n binding.pry if ENV['DEBUGGER']\n orig_failed(*args)\n end", "def screenshot(driver,sess_time,shot_num,descr)\n filename = \"shot-#{shot_num}-#{driver.current_url.sub(\"http://\",\"\").sub(\"admin:123@\",\"\").gsub(\"/\",\"-\")}-(#{descr})-#{sess_time}.png\"\n # driver.save_screenshot (\"shot-#{shot_num}-#{driver.current_url.sub(\"https://format-staging.com/\",\"\").gsub(\"/\",\"-\")}-(#{descr})-#{sess_time}.png\")\n driver.save_screenshot(filename)\n # puts (\" 📸 Shot #{shot_num} (#{driver.current_url})\")\n puts (\" 📸 #{filename}\")\n return 1\nend", "def save_shot(screenshot)\n\t\t@browser.screenshot.save(screenshot)\n\tend", "def screenshot(name=\"screenshot\")\n page.driver.render(\"public/#{name}.jpg\",full: true)\n end", "def save_screenshot(scenario)\n path = SCREENSHOTS_DIR\n\n # prepare dir\n FileUtils.mkdir(path) unless File.directory?(path)\n\n # prepare scenario name\n if scenario.instance_of?(Cucumber::Ast::OutlineTable::ExampleRow)\n scenario_name = scenario.scenario_outline.name.gsub(/[^\\w\\-]/, ' ')\n scenario_name << \"-Example#{scenario.name.gsub(/\\s*\\|\\s*/, '-')}\".chop\n else\n scenario_name = scenario.name.gsub(/[^\\w\\-]/, ' ')\n end\n\n # prepare filename\n filename = \"#{path}/#{scenario_name}.png\"\n\n # save screenshot\n Testing.browser.driver.save_screenshot(filename)\n\n # embed into HTML output\n embed(filename, 'image/png')\n end", "def screenshot_large\n screenshot()\n end", "def screenshot\n Screenshot.new self\n end", "def screenshot path = '~/Desktop'\n capture_screen self, path\n end", "def capture_screenshot\n screenshot_file = ScreenshotClient.capture(live_url, format: 'JPG')\n\n screenshot = WorkshopProjectScreenshot.new\n screenshot.file.attach(\n io: screenshot_file,\n filename: 'screenshot.jpg'\n )\n\n self.screenshot = screenshot\n end", "def take_screenshot(index, action)\n #-------------------------------------------------------------------------------------------------------------\n # save body au format text to fichier\n #-------------------------------------------------------------------------------------------------------------\n begin\n source_file = Flow.new(@home, index.to_s, action, Date.today, nil, \".txt\")\n source_file.write(@browser.body)\n\n rescue Exception => e\n @@logger.an_event.debug \"browser save body #{source_file.basename} : #{e.message}\"\n\n else\n @@logger.an_event.debug \"browser save body #{source_file.basename}\"\n\n end\n\n #-------------------------------------------------------------------------------------------------------------\n # prise d'un screenshot au format image\n #-------------------------------------------------------------------------------------------------------------\n [source_file.absolute_path, @browser.take_screenshot(Flow.new(@home, index.to_s, action, Date.today, nil, \".png\"))]\n\n end", "def set_screenshot\n @screenshot = Screenshot.find(params[:id])\n end", "def png\n @driver.screenshot_as(:png)\n end", "def add_image_from_rspec(argument, example, url_path)\n blob = caller.find{|i| i[ example.file_path.gsub(/:\\d*|^\\./,\"\") ]}\n file_with_line = blob.split(\":\")[0,2].join(\":\")\n\n filename = [example.description, argument, file_with_line, SecureRandom.hex(6) ].join(\" \").gsub(/\\W+/,\"_\") + \".jpg\"\n full_name = File.join(Poltergeist::ScreenshotOverview.target_directory, filename )\n FileUtils.mkdir_p Poltergeist::ScreenshotOverview.target_directory\n describe = example.metadata[:example_group][:description_args]\n @files << Screenshot.new({\n :url => url_path,\n :argument => argument,\n :local_image => filename,\n :full_path => full_name,\n :group_description => describe,\n :example_description => example.description,\n :file_with_line => file_with_line\n })\n full_name\n end" ]
[ "0.741501", "0.722639", "0.71233875", "0.71193415", "0.7058666", "0.7007076", "0.69928247", "0.6956237", "0.6861449", "0.6805622", "0.66489744", "0.66150814", "0.65824884", "0.6572377", "0.6568521", "0.65601975", "0.6518929", "0.64659345", "0.64314467", "0.6412075", "0.6382225", "0.6369663", "0.6302922", "0.62840974", "0.6218625", "0.6180217", "0.6159693", "0.6087979", "0.6013163", "0.6001154" ]
0.7754253
0
Method for the message 'test_step_started'.
def test_step_started(source, step_name, *args) test = source.test suite_name, test_name = _test_details(test) @manager.allure_start_step(suite_name, test_name, step_name) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def on_test_step_started(event)\n event.test_step.hook? ? handle_hook_started(event.test_step) : handle_step_started(event.test_step)\n end", "def start_test_step(step_result)\n return logger.error { \"Could not start test step, no test case is running\" } unless @current_test_case\n\n logger.debug { \"Starting test step: #{step_result.name}\" }\n step_result.start = ResultUtils.timestamp\n step_result.stage = Stage::RUNNING\n add_test_step(step_result)\n step_result\n end", "def test_case_started(event, desired_time = ReportPortal.now)\n test_case = event.test_case\n feature = test_case.feature\n if report_hierarchy? && !same_feature_as_previous_test_case?(feature)\n end_feature(desired_time) unless @parent_item_node.is_root?\n start_feature_with_parentage(feature, desired_time)\n end\n\n name = \"#{test_case.keyword}: #{test_case.name}\"\n description = test_case.location.to_s\n tags = test_case.tags.map(&:name)\n type = :STEP\n\n ReportPortal.current_scenario = ReportPortal::TestItem.new(name: name, type: type, id: nil, start_time: time_to_send(desired_time), description: description, closed: false, tags: tags)\n scenario_node = Tree::TreeNode.new(SecureRandom.hex, ReportPortal.current_scenario)\n @parent_item_node << scenario_node\n ReportPortal.current_scenario.id = ReportPortal.start_item(scenario_node)\n end", "def stepStart(description)\n executeScript($START_STEP_COMMAND, {:name => description})\n end", "def helper_start_test(message, encoded_message = nil)\n post '/start', { message: message }, session\n\n assert_equal 302, last_response.status\n assert_flash 'Time started.'\n assert_time_start(encoded_message || message)\n\n # follow redirect back to actions page\n get last_response['Location']\n\n assert_all_actions\n assert_displayed_flash 'Time started.'\n end", "def start_step(_step, _scenario)\n raise NotImplementedError.new \\\n \"#{self.class.name}#start_step must be implemented in subclass.\"\n end", "def start_test(test_status)\n # Abstract\n end", "def running_test_step; end", "def on_test_case_started(event)\n lifecycle.start_test_container(Allure::TestResultContainer.new(name: event.test_case.name))\n lifecycle.start_test_case(cucumber_model.test_result(event.test_case))\n end", "def test_started(source, *args)\n test = source.test\n suite_name, test_name = _test_details(test)\n\n metadata = test.metadata\n feature = metadata.fetch(:feature, nil)\n severity = metadata.fetch(:priority, :normal).to_sym\n\n @manager.allure_start_test(suite_name, test_name, {feature: feature, severity: severity})\n end", "def test_step; end", "def start_test(test_status, test_metadata)\n # Abstract\n end", "def step msg\n end", "def test_start_started_job\n job 'job'\n start 'job'\n start_message = start 'job'\n assert_message(\"Timeclock tried to start job 'job'.\n But 'job' is already started.\",\n start_message)\n end", "def getStarted\n if @dry_run\n nil\n else\n JSON.parse(@client[\"/LoadTest?loadTestId=#{@test_id}\"].get)[0].to_h['start_time']\n end\n end", "def before_step(step)\n @current_step = step\n end", "def test_steps; end", "def test_steps; end", "def testStep(description)\n warn 'testStep method is deprecated, please use stepStart or stepEnd commands instead.'\n executeScript($START_STEP_COMMAND, {:name => description})\n end", "def start_test_case(test_result)\n clear_step_context\n unless current_test_result_container\n return logger.error { \"Could not start test case, test container is not started\" }\n end\n\n logger.debug(\"Starting test case: #{test_result.name}\")\n test_result.start = ResultUtils.timestamp\n test_result.stage = Stage::RUNNING\n test_result.labels.push(ResultUtils.thread_label, ResultUtils.host_label, ResultUtils.language_label)\n current_test_result_container.children.push(test_result.uuid)\n @current_test_case = test_result\n end", "def first_step\n log(:start, :s1)\n do_step1\n log(:end, :s1)\n end", "def example_started(example)\n end", "def start_test(test)\n puts \"\\e[36mRunning test:\\e[0m \\e[37m#{test.name} Line: #{test.lineNumber}\\e[0m\"\n end", "def start\n start_thread\n wait(20) # This so that you wait until either the step is done or 20 seconds is up.\n # It doesn't have to wait the whole 20 seconds if the step finishes quickly.\n end", "def start args\n change_value \"status\", \"started\", args\n 0\n end", "def start\n @workflow[:started_at] = timeString\n end", "def communicate_started\n File.open(\"#{@options[:output_directory]}/started.job\", 'w') { |f| f << \"Started Workflow #{::Time.now} #{@options}\" }\n raise 'Missing required options' unless @options[:url] && @options[:datapoint_id] && @options[:project_id]\n send_status('Started')\n end", "def report_start_test(test_status)\n @listeners.each do |l|\n l.start_test(test_status)\n end\n end", "def start_traction(step_name)\n\n scriptstart_time = Time.now\n\nend", "def add_test_step(step_result)\n current_executable.steps.push(step_result)\n @step_context.push(step_result)\n step_result\n end" ]
[ "0.78443706", "0.7265559", "0.69461143", "0.6779474", "0.6705636", "0.66253597", "0.65640837", "0.6473037", "0.63924026", "0.63690907", "0.630477", "0.6283276", "0.61707425", "0.61632055", "0.6121647", "0.60662055", "0.6058857", "0.6058857", "0.6035354", "0.6026546", "0.593944", "0.5939035", "0.5918618", "0.587014", "0.5835612", "0.5820809", "0.578477", "0.5778077", "0.5751782", "0.5748528" ]
0.7653638
1
Method for the message 'test_step_finished'.
def test_step_finished(source, step_name, status = :passed, *args) test = source.test suite_name, test_name = _test_details(test) @manager.allure_stop_step(suite_name, test_name, step_name, status) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def on_test_step_finished(event)\n update_block = proc do |step|\n step.stage = Allure::Stage::FINISHED\n step.status = ALLURE_STATUS.fetch(event.result.to_sym, Allure::Status::BROKEN)\n end\n\n event.test_step.hook? ? handle_hook_finished(event.test_step, update_block) : handle_step_finished(update_block)\n end", "def stepEnd(message=nil)\n executeScript($END_STEP_COMMAND, {:message => message})\n end", "def on_test_run_finished(event)\n print_cucumber_failures\n end", "def test_finished(test_case, test_result)\n endpoint = DrbEndpoint.new(\"localhost:#{TestBase::DRUBY_REPORTER_PORT}\")\n reporter = endpoint.create_client(with_object: nil)\n reporter.report_test_finished(\"#{test_case.class}::test_#{test_result.name}\", test_result)\n end", "def end_step(_step_result, _scenario)\n raise NotImplementedError.new \\\n \"#{self.class.name}#end_step must be implemented in subclass.\"\n end", "def after_test_step(step,result)\n unless result.passed?\n # only the first non-passed step\n failed_step[:step] ||= step\n failed_step[:result] ||= result\n end\n end", "def after_test_step(test_step, result)\n #puts test_step.to_yaml\n puts \"after #{test_step.class} result is #{result}\"\n puts result.to_yaml\n #p result.kind_of? Cucumber::Core::Test::Result::Passed\n #p result.kind_of? Cucumber::Core::Test::Result::Skipped\n end", "def finish\n @test_output = @test_output.join.split(\"\\n\")\n @test_description = @test_output.shift\n end", "def on_test_case_finished(event)\n failure_details = cucumber_model.failure_details(event.result)\n status = ALLURE_STATUS.fetch(event.result.to_sym, Allure::Status::BROKEN)\n lifecycle.update_test_case do |test_case|\n test_case.stage = Allure::Stage::FINISHED\n test_case.status = event.result.failed? ? Allure::ResultUtils.status(event.result&.exception) : status\n test_case.status_details.flaky = event.result.flaky?\n test_case.status_details.message = failure_details[:message]\n test_case.status_details.trace = failure_details[:trace]\n end\n lifecycle.stop_test_case\n lifecycle.stop_test_container\n end", "def after_step(_step_result, _scenario)\n raise NotImplementedError.new \\\n \"#{self.class.name}#after_step must be implemented in subclass.\"\n end", "def end_test(test_status)\n # Abstract\n end", "def end_test(test_status)\n # Abstract\n end", "def after_finished\n end", "def finish\n end", "def test_finished(source, *args)\n test = source.test\n suite_name, test_name = _test_details(test)\n\n @manager.allure_stop_test(suite_name, test_name)\n end", "def done\n puts 'Done running tests'\n end", "def isFinished\n progressValue.isEqualToNumber(numberOfSteps)\n end", "def testing_end\n end", "def finish\n #\n end", "def finish\r\n #\r\n end", "def finished!\n t = Time.now.utc\n update_attribute(:finished_at, t)\n # Save errors counts\n if errs = error_messages\n BackupJobError.increment_errors_count(*errs)\n end\n backup_source.backup_complete!\n on_finish :errors => errs, :messages => messages\n end", "def action_complete() self.finished = true; end", "def finish\n #\n end", "def test_run_completed(test_run)\n report_results test_run\n end", "def finished?\n @step == @total_steps + 1\n end", "def finish\n @Done = true \n end", "def finish\n @finish = true\n end", "def mark_as_finished\n result = V1::StudyHour::MarkAsFinished.(params, current_user: @current_user)\n if result.success?\n render json: result['model'], status: :ok\n elsif result['result.policy.failure']\n render json: { 'errors': [] }, status: :unauthorized\n else\n render json: {\n 'errors': result['model'].errors.full_messages\n }, status: :unprocessable_entity\n end\n end", "def finish(value)\n @ole.Finish = value\n nil\n end", "def on_test_case_finished(event)\n # save only failed and not tagged with issue_pattern (e.g. @ISSUE-)\n if event.result.failed? && !event.test_case.tags.any? { |tag| tag.name.match?(/ISSUE/) }\n add_failure_to_rerun(event.test_case)\n end\n end" ]
[ "0.72463304", "0.7098731", "0.69635737", "0.6866173", "0.68358535", "0.67265135", "0.6671308", "0.6611195", "0.65640134", "0.6562804", "0.6551564", "0.6551564", "0.65425354", "0.64452374", "0.64396006", "0.6428594", "0.64111453", "0.6403335", "0.63919246", "0.63563377", "0.63522124", "0.632275", "0.63223374", "0.6318086", "0.61846447", "0.61419076", "0.6139143", "0.6132288", "0.61318064", "0.6110125" ]
0.7429429
0
Given a template id, derive (if available) the definition for the template. The definitions are stored in hqmfmodel/data_criteria.json.
def extract_definition_from_template_id found = false @template_ids.each do |template_id| # NOTE! (Adam 6/14): The following logic should absolutely be changed # when Bonnie CQL support goes production. The "try this then try # that" approach is an artifact of the template oids changing as of # MAT 5.3; we want to support measures exported using 5.3, but also # measures that were exported using previous versions of the MAT. # Try a lookup using the newer template oids. defs = HQMF::DataCriteria.definition_for_template_id(template_id, 'r2cql') # If the new template oids didn't work, try a lookup using the older # template oids. defs = HQMF::DataCriteria.definition_for_template_id(template_id, 'r2') unless defs if defs @definition = defs['definition'] @status = defs['status'].length > 0 ? defs['status'] : nil found ||= true else found ||= handle_known_template_id(template_id) end end found end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extract_definition_from_template_id\n found = false\n\n @template_ids.each do |template_id|\n defs = HQMF::DataCriteria.definition_for_template_id(template_id, 'r2')\n if defs\n @definition = defs['definition']\n @status = defs['status'].length > 0 ? defs['status'] : nil\n found ||= true\n else\n found ||= handle_known_template_id(template_id)\n end\n end\n\n found\n end", "def handle_known_template_id(template_id)\n case template_id\n when VARIABLE_TEMPLATE\n @derivation_operator = HQMF::DataCriteria::INTERSECT if @derivation_operator == HQMF::DataCriteria::XPRODUCT\n @definition ||= 'derived'\n @variable = true\n @negation = false\n when SATISFIES_ANY_TEMPLATE\n @definition = HQMF::DataCriteria::SATISFIES_ANY\n @negation = false\n when SATISFIES_ALL_TEMPLATE\n @definition = HQMF::DataCriteria::SATISFIES_ALL\n @derivation_operator = HQMF::DataCriteria::INTERSECT\n @negation = false\n else\n return false\n end\n true\n end", "def get(template_id)\n id = connection.rname_to_id(template_id, :template)\n all.select { |template| template.id == String(id) }.first\n end", "def get_template(template); end", "def template_get(id)\n check_id_or_raise id\n\n response = http_request :get, \"#{@base_url}/templates/#{id}.xml\", 200,\n { :params => { :provider_key => @provider_key } }\n\n doc = Nokogiri::XML(response.body)\n draft_node = doc.xpath('//draft')[0]\n published_node = doc.xpath('//published')[0]\n draft = draft_node ? draft_node.text : nil\n published = published_node ? published_node.text : nil\n if draft && !draft.empty?\n draft\n else\n published\n end\n end", "def template_details(template_id)\n @api.get(\"#{@api.path}/List/#{@id}/Templates/#{template_id}\")\n end", "def get_content_template(id)\n @client.raw('get', \"/content/templates/#{id}\")\n end", "def extract_definition_from_entry_type(entry_type)\n case entry_type\n when 'Problem', 'Problems'\n 'diagnosis'\n when 'Encounter', 'Encounters'\n 'encounter'\n when 'LabResults', 'Results'\n 'laboratory_test'\n when 'Procedure', 'Procedures'\n 'procedure'\n when 'Demographics'\n definition_for_demographic\n when 'Derived'\n 'derived'\n else\n fail \"Unknown data criteria template identifier [#{entry_type}]\"\n end\n end", "def delete_template( id )\n\t\t# for each template\n\t\t@templates.each do |key, template|\n\t\t\t# make sure the Template is removed from the part map\n\t\t\ttemplate.part_map.delete( id )\n\t\tend\n\t\t\n\t\t# remove Template from main Hash\n\t\t@templates.delete( id )\n\n\tend", "def build_from_template(template_id)\n template_detail = ProposalTemplateDetail.from_template(template_id)\n if template_detail.count > 0\n template_detail.each do |trans| \n self.proposal_details.build(:service_id => trans.service_id, :tier1_applicable => trans.tier1_applicable , :tier2_applicable => trans.tier2_applicable, :tier3_applicable => trans.tier3_applicable)\n end\n end\n end", "def retrieve_single_template( template_id )\n puts \"Retrieving template id #{template_id}.\"\n\n uri = URI(@config['endpoint'] + '/' + template_id)\n\n # Retrieve templates\n http = Net::HTTP.new( uri.host,uri.port )\n http.use_ssl = true\n request = Net::HTTP::Get.new( uri.request_uri )\n request.basic_auth(@primary_username, @primary_password)\n\n response = http.request( request )\n template = JSON.parse( response.body )\n end", "def retrieve(id, draft = nil)\n path = \"templates/#{id}\"\n query_params = draft.nil? ? {} : { draft: draft }\n @client.call(method: :get, path: path, query_values: query_params)\n end", "def details\n response = get \"/templates/#{template_id}.json\", {}\n Hashie::Mash.new(response)\n end", "def details\n response = CreateSend.get \"/templates/#{template_id}.json\", {}\n Hashie::Mash.new(response)\n end", "def update_definition(id, new_def)\n MinWords::DB[:defines]\n .where(id: id)\n .update(:definition_text => new_def)\n end", "def template_id=(template_id)\n pattern = Regexp.new(/^tmpl_[a-zA-Z0-9]+$/)\n if !template_id.nil? && template_id !~ pattern\n fail ArgumentError, \"invalid value for \\\"template_id\\\", must conform to the pattern #{pattern}.\"\n end\n\n @template_id = template_id\n end", "def details\n data = Storm::Base::SODServer.remote_call '/Storm/Template/details',\n :id => @id\n self.from_hash data\n end", "def create_template_view(template_id)\r\n # Prepare query url.\r\n _query_builder = Configuration.base_uri.dup\r\n _query_builder << '/template/view.json'\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare form parameters.\r\n _parameters = {\r\n 'TemplateId' => template_id\r\n }\r\n _parameters = APIHelper.form_encode_parameters(_parameters)\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = @http_client.post(\r\n _query_url,\r\n parameters: _parameters\r\n )\r\n BasicAuth.apply(_request)\r\n _context = execute_request(_request)\r\n validate_response(_context)\r\n\r\n # Return appropriate response type.\r\n _context.response.raw_body\r\n end", "def purchase_template(template_id)\n return false unless can_purchase_templates?\n\n # Copy data from Template\n template = GspTemplate.find(template_id)\n OrganizationTemplate.create :agency => template.agency, :description => template.description,\n :display_name => template.display_name, :frequency => template.frequency,\n :full_name => template.full_name, :objectives => template.objectives,\n :regulatory_review_name => template.regulatory_review_name,\n :purchased_by => self, :organization => self.organization,\n :tasks => template.tasks\n end", "def get_config_var_definitions(variable_id)\n path = \"/d2l/api/lp/#{$lp_ver}/configVariables/(#{variable_id}/definition\"\n _get(path)\n # returns Definition JSON data block\nend", "def extract_definition_from_type\n # If we have a specific occurrence of a variable, pull attributes from the reference.\n # IDEA set this up to be called from dc_specific_and_source_extract, the number of\n # fields changed by handle_specific_variable_ref may pose an issue.\n extract_information_for_specific_variable if @variable && @specific_occurrence\n\n if @entry.at_xpath('./cda:grouperCriteria')\n @definition ||= 'derived'\n return\n end\n # See if we can find a match for the entry definition value and status.\n entry_type = attr_val('./*/cda:definition/*/cda:id/@extension')\n handle_entry_type(entry_type)\n end", "def set_cf_template\n @cf_template = CfTemplate.find(params.require(:id))\n end", "def fetch_template_id\n finance_transaction_receipt_record.fee_receipt_template_id\n end", "def definition\n if element.blank?\n log_warning \"Content with id #{id} is missing its Element.\"\n return {}\n end\n element.content_definition_for(name) || {}\n end", "def extract_definition_from_type\n if @entry.at_xpath('./cda:grouperCriteria')\n @definition ||= 'derived'\n return\n end\n # See if we can find a match for the entry definition value and status.\n entry_type = attr_val('./*/cda:definition/*/cda:id/@extension')\n handle_entry_type(entry_type)\n end", "def get_template(template)\n xapi.VM.get_by_name_label(template).first\n end", "def get_template(template)\n xapi.VM.get_by_name_label(template).first\n end", "def template_attributes\n return if params[:template_id].blank?\n RecordTemplate.find(params[:template_id]).record_content\n end", "def get_report_template_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ReportApi.get_report_template ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling ReportApi.get_report_template\"\n end\n # resource path\n local_var_path = '/api/3/report_templates/{id}'.sub('{' + 'id' + '}', id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json;charset=UTF-8'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'ReportTemplate')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ReportApi#get_report_template\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def populate_template( template_id, imported_template )\n puts \"Populating new tempalte id: #{template_id}...\"\n\n uri = URI(@config['endpoint']+\"/#{template_id}/versions\")\n\n # Retrieve templates\n http = Net::HTTP.new( uri.host,uri.port )\n http.use_ssl = true\n request = Net::HTTP::Post.new( uri.request_uri, initheader = {'Content-Type:' => 'application/json'} )\n request.basic_auth(@secondary_username, @secondary_password)\n\n\n # If versions exist, transfer each to new template\n imported_template['versions'].each do |version|\n version.delete(\"id\")\n version.delete(\"user_id\")\n version.delete(\"template_id\")\n version.delete(\"updated_at\")\n\n puts \" Adding template version #{version['name']}...\"\n payload = version.to_json\n request.body = payload\n response = http.request( request )\n response_message = JSON.parse( response.body )\n end\n end" ]
[ "0.7172219", "0.671647", "0.55633885", "0.55622715", "0.5541252", "0.54860145", "0.5413437", "0.53947", "0.538259", "0.52642643", "0.51781964", "0.51762927", "0.51592124", "0.5121665", "0.5083822", "0.5062981", "0.5033205", "0.503175", "0.50142723", "0.49867183", "0.4978556", "0.49719268", "0.4945011", "0.49406764", "0.48582646", "0.4845741", "0.4845741", "0.48240736", "0.48106146", "0.48081523" ]
0.7399046
0