query
stringlengths
7
6.41k
document
stringlengths
12
28.8k
metadata
dict
negatives
listlengths
30
30
negative_scores
listlengths
30
30
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
PATCH/PUT /air_moistures/1 PATCH/PUT /air_moistures/1.json
def update respond_to do |format| if @air_moisture.update(air_moisture_params) format.html { redirect_to @air_moisture, notice: 'Air moisture was successfully updated.' } format.json { render :show, status: :ok, location: @air_moisture } else format.html { render :edit } format.json { render json: @air_moisture.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def update\n respond_to do |format|\n if @mile.update(mile_params)\n format.html { redirect_to @mile, notice: 'Mile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @ami = Ami.find(params[:id])\n\n respond_to do |format|\n if @ami.update_attributes(params[:ami])\n format.html { redirect_to @ami, notice: 'Ami was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ami.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @plate = Plate.find(params[:id])\n\n if @plate.update(params[:plate])\n head :no_content\n else\n render json: @plate.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @moon.update(moon_params)\n format.html { redirect_to @moon, notice: 'Moon was successfully updated.' }\n format.json { render :show, status: :ok, location: @moon }\n else\n format.html { render :edit }\n format.json { render json: @moon.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @soil_moisture.update(soil_moisture_params)\n format.html { redirect_to @soil_moisture, notice: 'Soil moisture was successfully updated.' }\n format.json { render :show, status: :ok, location: @soil_moisture }\n else\n format.html { render :edit }\n format.json { render json: @soil_moisture.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @mi = Mi.find(params[:id])\n\n respond_to do |format|\n if @mi.update_attributes(params[:mi])\n format.html { redirect_to @mi, notice: 'Mi was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mi.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @air.update(air_params)\n format.html { redirect_to @air, notice: 'Air was successfully updated.' }\n format.json { render :show, status: :ok, location: @air }\n else\n format.html { render :edit }\n format.json { render json: @air.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @precious_metal = PreciousMetal.find(params[:id])\n\n respond_to do |format|\n if @precious_metal.update_attributes(params[:precious_metal])\n format.html { redirect_to @precious_metal, :notice => 'Precious metal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @precious_metal.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @material_apoyo = MaterialApoyo.find(params[:id])\n\n respond_to do |format|\n if @material_apoyo.update_attributes(params[:material_apoyo])\n format.html { redirect_to @material_apoyo, notice: 'Material apoyo was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @material_apoyo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @moose = Moose.find(params[:id])\n\n respond_to do |format|\n if @moose.update_attributes(params[:moose])\n format.html { redirect_to @moose, notice: 'Moose was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @moose.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @capitol.update(capitol_params)\n format.html { redirect_to root_path, notice: 'Capitol was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @capitol.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @wi_mn_d_min_t_air.update(wi_mn_d_min_t_air_params)\n format.html { redirect_to @wi_mn_d_min_t_air, notice: 'Wi mn d min t air was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @wi_mn_d_min_t_air.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @apologetic.update(apologetic_params)\n format.html { redirect_to @apologetic, notice: 'Apologetic was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @apologetic.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @plate_photo = PlatePhoto.find(params[:id])\n\n respond_to do |format|\n if @plate_photo.update_attributes(params[:plate_photo])\n format.html { redirect_to @plate_photo, notice: 'Plate photo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @plate_photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @model = Model.find(params[:id])\n # @model.name = \"test\"\n @model.scale = 1\n respond_to do |format|\n if @model.update_attributes(params[:model])\n format.html { redirect_to @model, notice: 'Model was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @model.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @pictures = Picture.all.order(created_at: :desc)\n @picture.update(picture_params)\n render json: @pictures\n # head :no_content\n end", "def update\n @origami = Origami.find(params[:id])\n\n respond_to do |format|\n if @origami.update_attributes(params[:origami])\n format.html { redirect_to @origami, notice: 'Origami was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @origami.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @origami = Origami.find(params[:id])\n\n respond_to do |format|\n if @origami.update_attributes(params[:origami])\n format.html { redirect_to @origami, notice: 'Origami was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @origami.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @iso.update(iso_params)\n format.html { redirect_to @iso, notice: 'Iso was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @iso.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @airlin = Airlin.find(params[:id])\n\n respond_to do |format|\n if @airlin.update_attributes(params[:airlin])\n format.html { redirect_to @airlin, notice: 'Airlin was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @airlin.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @magzine = Magzine.find(params[:id])\n\n respond_to do |format|\n if @magzine.update_attributes(params[:magzine])\n format.html { redirect_to @magzine, notice: 'Magzine was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @magzine.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @imakoko.update(imakoko_params)\n format.html { redirect_to @imakoko, notice: 'Imakoko was successfully updated.' }\n format.json { render :show, status: :ok, location: @imakoko }\n else\n format.html { render :edit }\n format.json { render json: @imakoko.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @omim.update(omim_params)\n format.html { redirect_to @omim, notice: 'Omim was successfully updated.' }\n format.json { render :show, status: :ok, location: @omim }\n else\n format.html { render :edit }\n format.json { render json: @omim.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_attr\n #sanity checks \n @persona = current_persona\n @mediaset = @persona.mediasets.find(params[:id])\n \n respond_to do |format|\n @mediaset.update_attributes( params[:mediaset] )\n format.json{ respond_with_bip(@mediaset) }\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative.update(api_v1_initiative_params)\n format.html { redirect_to @api_v1_initiative, notice: 'Initiative was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @air_crew = AirCrew.find(params[:id])\n\n respond_to do |format|\n if @air_crew.update_attributes(params[:air_crew])\n format.html { redirect_to @air_crew, notice: 'Air crew was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @air_crew.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @magictown.update(magictown_params)\n format.html { redirect_to @magictown, notice: 'Magictown was successfully updated.' }\n format.json { render :show, status: :ok, location: @magictown }\n else\n format.html { render :edit }\n format.json { render json: @magictown.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @wi_mn_d_max_t_air.update(wi_mn_d_max_t_air_params)\n format.html { redirect_to @wi_mn_d_max_t_air, notice: 'Wi mn d max t air was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @wi_mn_d_max_t_air.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @air_quality = AirQuality.find(params[:id])\n\n if @air_quality.update(air_quality_params)\n head :no_content\n else\n render json: @air_quality.errors, status: :unprocessable_entity\n end\n end" ]
[ "0.6274479", "0.62224776", "0.6215002", "0.61873496", "0.6130231", "0.61201", "0.6114338", "0.60977507", "0.6090425", "0.6045212", "0.60351163", "0.60275054", "0.5998368", "0.59876174", "0.598102", "0.5971419", "0.596839", "0.59681946", "0.59681946", "0.59334207", "0.5931079", "0.5926054", "0.5922772", "0.59194225", "0.59192055", "0.5908444", "0.5906663", "0.5905482", "0.59016985", "0.5901429" ]
0.67266005
0
DELETE /air_moistures/1 DELETE /air_moistures/1.json
def destroy @air_moisture.destroy respond_to do |format| format.html { redirect_to air_moistures_url, notice: 'Air moisture was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 @soil_moisture.destroy\n respond_to do |format|\n format.html { redirect_to soil_moistures_url, notice: 'Soil moisture was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @ami = Ami.find(params[:id])\n @ami.destroy\n\n respond_to do |format|\n format.html { redirect_to amis_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @wi_mn_d_min_t_air.destroy\n respond_to do |format|\n format.html { redirect_to wi_mn_d_min_t_airs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @moonwalk.destroy\n respond_to do |format|\n format.html { redirect_to moonwalks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mou.destroy\n respond_to do |format|\n format.html { redirect_to mous_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mile.destroy\n respond_to do |format|\n format.html { redirect_to miles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mi = Mi.find(params[:id])\n @mi.destroy\n\n respond_to do |format|\n format.html { redirect_to mis_url }\n format.json { head :ok }\n end\n end", "def destroy\n @wi_mn_d_ave_t_air.destroy\n respond_to do |format|\n format.html { redirect_to wi_mn_d_ave_t_airs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mob.destroy\n respond_to do |format|\n format.html { redirect_to mobs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @moon.destroy\n respond_to do |format|\n format.html { redirect_to moons_url, notice: 'Moon was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @mystic.destroy\n respond_to do |format|\n format.html { redirect_to mystics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @agronomiaquimica = Agronomiaquimica.find(params[:id])\n @agronomiaquimica.destroy\n\n respond_to do |format|\n format.html { redirect_to agronomiaquimicas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @retroaspecto = Retroaspecto.find(params[:id])\n @retroaspecto.destroy\n\n respond_to do |format|\n format.html { redirect_to retroaspectos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @wi_mn_d_max_t_air.destroy\n respond_to do |format|\n format.html { redirect_to wi_mn_d_max_t_airs_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @imobiliaria = Imobiliaria.find(params[:id])\r\n @imobiliaria.destroy\r\n\r\n respond_to do |format|\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @mini_map_road = MiniMapRoad.find(params[:id])\n @mini_map_road.destroy\n\n respond_to do |format|\n format.html { redirect_to mini_map_roads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @areco = Areco.find(params[:id])\n @areco.destroy\n\n respond_to do |format|\n format.html { redirect_to arecos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n record = Asset.find(params[:id])\n record.destroy\n\n respond_to do |format| \n format.json { head :no_content }\n end\n end", "def destroy\n @medium_road = MediumRoad.find(params[:id])\n @medium_road.destroy\n\n respond_to do |format|\n format.html { redirect_to medium_roads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @humanidades3 = Humanidades3.find(params[:id])\n @humanidades3.destroy\n\n respond_to do |format|\n format.html { redirect_to humanidades3s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @moresmalltrial = Moresmalltrial.find(params[:id])\n @moresmalltrial.destroy\n\n respond_to do |format|\n format.html { redirect_to moresmalltrials_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @origami = Origami.find(params[:id])\n @origami.destroy\n\n respond_to do |format|\n format.html { redirect_to origamis_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @iso.destroy\n respond_to do |format|\n format.html { redirect_to isos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @midia.destroy\n\n respond_to do |format|\n format.html { redirect_to midias_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @remito = Remito.find(params[:id])\n @remito.destroy\n\n respond_to do |format|\n format.html { redirect_to remitos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @humanidades1 = Humanidades1.find(params[:id])\n @humanidades1.destroy\n\n respond_to do |format|\n format.html { redirect_to humanidades1s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @aucrecord.destroy\n respond_to do |format|\n format.html { redirect_to aucrecords_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" ]
[ "0.7003927", "0.70035815", "0.69732076", "0.695011", "0.6943842", "0.6917684", "0.6902483", "0.6899357", "0.6897867", "0.68952644", "0.68856806", "0.68581945", "0.6854098", "0.6851745", "0.6819654", "0.68140924", "0.68092847", "0.6798806", "0.679734", "0.678996", "0.6787179", "0.6777437", "0.6767187", "0.6764977", "0.6761482", "0.6756051", "0.67523766", "0.6728564", "0.6728012", "0.67244464" ]
0.72552097
0
show stops for line
def show_stops(lines, line1) lines.each do |line| if line[:lines] == line1 puts line[:stops] end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getLineStops (l)\n @lines[l][:stops]\nend", "def get_line_stops(lines, origin_line)\n lines[origin_line.to_sym]\nend", "def draw_line\n print H_SEP * columns\n end", "def list_stops(line)\n puts line\n return \"all the stops on a line\"\nend", "def draw_alt_line\n @dim.times do |i|\n if i.even?\n print draw_x\n else\n if @type == \"allx\"\n print draw_x\n elsif @type == \"alt\"\n print draw_dot\n end\n end\n end\n end", "def get_line_speed\n @line_show_fast = CP::CMS::TEXT_TYPE_OR_SKIP\n end", "def lines_tech_demo\n outputs.labels << [5, 500, \"Lines (x, y, x2, y2, r, g, b, a)\"]\n outputs.lines << [5, 450, 100, 450]\n outputs.lines << [5, 430, 300, 430]\n outputs.lines << [5, 410, 300, 410, state.tick_count % 255, 0, 0, 255] # red saturation changes\n outputs.lines << [5, 390 - state.tick_count % 25, 300, 390, 0, 0, 0, 255] # y position changes\n outputs.lines << [5 + state.tick_count % 200, 360, 300, 360, 0, 0, 0, 255] # x position changes\n end", "def display_lines(min, max); end", "def calculate_line(stop1, stop2)\n if @purple_line.include?(stop1) && @purple_line.include?(stop2)\n \"either\"\n elsif @purple_line.include?(stop1) && @blue_line_west.include?(stop2)\n \"blue\"\n elsif @purple_line.include?(stop1) && @red_line_only.include?(stop2)\n \"red\"\n elsif @red_line_only.include?(stop1)\n \"red\"\n elsif @blue_line_west.include?(stop1)\n \"blue\"\n end\n end", "def straight\n @line_type = '--'\n self\n end", "def get_stop_details(line)\nx = $subway_lines\n for i in x do\n if line == i[:line]\nline_details = i[:stops]\n end\nend\nline_details\nend", "def draw_line(number)\n @dim.times do |i|\n if i+1 == number || @dim-i == number\n print draw_x\n else\n print draw_dot\n end\n end\n end", "def draw_vertical(start_line, end_line, start_char)\n start_line.upto(end_line) do |line_idx| \n @lines[line_idx][start_char] = PATH_CHAR \n end\n end", "def timing_line(start, stop)\n\t\t@value = \"#{start.to_timing} --> #{stop.to_timing}\"\n\t\treturn self\n\tend", "def draw_line_markers\n return if @hide_line_markers\n\n (0..marker_count).each do |index|\n marker_label = (BigDecimal(index.to_s) * BigDecimal(@increment.to_s)) + BigDecimal(minimum_value.to_s)\n x = @graph_left + ((marker_label - minimum_value) * @graph_width / @spread)\n draw_marker_vertical_line(x, tick_mark_mode: true)\n\n unless @hide_line_numbers\n label = y_axis_label(marker_label, @increment)\n y = @graph_bottom + @label_margin + (labels_caps_height / 2.0) + 5 # 5px offset for tick_mark_mode\n text_renderer = Gruff::Renderer::Text.new(renderer, label, font: @marker_font)\n text_renderer.add_to_render_queue(0, 0, x, y, Magick::CenterGravity)\n end\n end\n end", "def draw_separation(x_start, y_start, y_min, y_max, x)\n @canvas.g.translate(x_start, y_start) do |lines|\n lines.styles(:stroke=>'#CCCCCC', :stroke_width=>1, :opacity=>0.05)\n lines.line(x, y_min, x, y_max)\n end\n end", "def get_stops (line, first_stop, last_stop)\n # puts \"line #{ line } stop #{ first_stop } -> stop #{ last_stop }\"\n first_index = lines[line.to_sym].index(first_stop)\n last_index = lines[line.to_sym].index(last_stop)\n if first_index <= last_index\n trip = lines[line.to_sym][first_index..last_index]\n else\n trip = lines[line.to_sym][last_index..first_index].reverse\n end\n trip.shift # remove first stop\n return trip\nend", "def divider_line\n lines - 2\n end", "def draw_lines\n @dim.times do |i|\n if @type.nil?\n draw_line(i+1)\n draw_edge\n puts\n elsif @type == \"allx\" || @type == \"alt\"\n draw_alt_line\n draw_edge\n puts\n end\n end\n end", "def stopGetter(stop_1, stop_2, line)\n if stop_1 > stop_2\n return line[stop_2..stop_1].reverse!\n else\n return line[stop_1..stop_2]\n end\nend", "def getting_stops on_line, on_stop, off_line, off_stop\n\tstops = []\n\n\tif is_same_line(on_line, off_line)\n\t\texit if on_line.index(on_stop) == on_line.index(off_stop) \n\t\t\t\n\t\tstops << (on_line[ on_line.index(on_stop)..on_line.index(off_stop) ]) \n\t\t\"you have to travel through: #{ stops.join(\" -> \") }\"\n\n\telse\n\t\tif is_left_to_union(on_line, on_stop, \"Union Square\")\n\t\t\tstops << on_line[on_line.index(on_stop)..on_line.index(\"Union Square\")]\n\n\t\telse\n\t\t\tstops << on_line[on_line.index(\"Union Square\")..on_line.index(on_stop)].reverse\n\t\tend\n\n\t\tif is_left_to_union(off_line, off_stop, \"Union Square\")\n\t\t\tstops << off_line[off_line.index(off_stop)..off_line.index(\"Union Square\")].reverse\n\n\t\telse\n\t\t\tstops << off_line[off_line.index(\"Union Square\")..off_line.index(off_stop)]\n\t\tend\n\n\t\t# delete \"Union Square\" from stops[1] as it is duplicate with stops[0]\n\t\tstops[1].shift\n\n\t\t\"You have to travel through: #{ stops[0].join(\" -> \") }\\n Change at: Union Square\\n Your travel continues through: #{ stops[1].join(\" -> \") }\\n The total number of stops you have to travel is: #{ stops.flatten.length }\"\n\tend\nend", "def curved\n @line_type = '..'\n self\n end", "def lineL_stations \n puts \"The list of stations for line L: \"\n puts \"[0] - 8th\"\n puts \"[1] - 6th\"\n puts \"[2] - Union Square\"\n puts \"[3] - 3rd\"\n puts \"[4] - 1st\"\nend", "def line_distance(lines, line, start, stop)\n\n\t# Find the distance and range between stops\n\tdistance = lines[line].index(stop) - lines[line].index(start)\n\trange = 1..distance \n\trange = distance..-1 if distance < 0\n\n\t# Create the list of stations\n\tstations_array = []\n\trange.each do |x|\n\t\t\tstations_array << lines[line][lines[line].index(start) + x]\n\tend\n\t\n\t# Reverse if needed\n\tstations_array.reverse! if distance < 0\n\n\treturn distance.abs, stations_array\nend", "def line_distance(lines, line, start, stop)\n\n\t# Find the distance and range between stops\n\tdistance = lines[line].index(stop) - lines[line].index(start)\n\trange = 1..distance \n\trange = distance..-1 if distance < 0\n\n\t# Create the list of stations\n\tstations_array = []\n\trange.each do |x|\n\t\t\tstations_array << lines[line][lines[line].index(start) + x]\n\tend\n\t\n\t# Reverse if needed\n\tstations_array.reverse! if distance < 0\n\n\treturn distance.abs, stations_array\nend", "def visible\n lines.map { |line| line[ox...(ox + bordered_width)] || '' }\n end", "def vertical_seperator x, y, y2\n [x, y, x, y2, 150, 150, 150]\n end", "def trip(line, start_stop, end_stop)\n trip_line = s_line(line)\n p trip_line\n start_index = trip_line.index(start_stop)\n end_index = trip_line.index(end_stop)\n stops = \"\"\n\n if start_index < end_index\n until start_index == end_index\n stops += trip_line[start_index]\n start_index += 1\n end\n else\n until start_index == end_index\n stops += trip_line[start_index]\n start_index -= 1\n end\n end\n return stops\nend", "def line_color\n :white_on_black\n end", "def show_total(lines, line1, stops1, line2, stops2)\n\tindex1 = []\n\tindex2 = []\n\n\t#get index for first stop\n\tlines.each do |line|\n\t\tif line[:lines] == line1\n\t\t\tindex1.push(line[:stops].index(stops1))\n\t\t\tif line1 == \"f\"\n\t\t\t\tindex1.push(line[:stops].index(\"herald_square\") + 1)\n\t\t\telse\n\t\t\t\tindex1.push(line[:stops].index(\"union_square\"))\n\t\t\tend\n\t\tend\n\tend\n\n\t#get index for second stop\n\tlines.each do |line|\n\t\tif line[:lines] == line2\n\t\t\tindex2.push(line[:stops].index(stops2))\n\t\t\tif line2 == \"f\"\n\t\t\t\tindex2.push(line[:stops].index(\"herald_square\") + 1)\n\t\t\telse\n\t\t\t\tindex2.push(line[:stops].index(\"union_square\"))\n\t\t\tend\n\t\tend\n\tend\n\n\t#calculate number of stops\n\tif index1[0] == index1[1]\n\t\tindex1 = 0\n\telse\n\t\tindex1 = (index1[0] - index1[1]).abs\n\tend\n\n\tif index2[0] == index2[1]\n\t\tindex2 = 0\n\telse\n\t\tindex2 = (index2[0] - index2[1]).abs\n\tend\n\n\tputs index1 + index2\nend" ]
[ "0.6607579", "0.6488185", "0.6245445", "0.6132525", "0.6111507", "0.6092206", "0.6056067", "0.5993023", "0.5974445", "0.59705985", "0.5965411", "0.59442824", "0.5943782", "0.59269977", "0.5841553", "0.58251005", "0.57955676", "0.57708865", "0.5755447", "0.57397103", "0.5696062", "0.56921333", "0.5668744", "0.56298214", "0.5627996", "0.5614481", "0.56113786", "0.5608781", "0.560668", "0.5599692" ]
0.6886917
0
Search through provided list of trips and filter optionally by service_id and route_id
def search_trips(trips, opts = {}) service_id = opts[:service_id] route_id = opts[:route_id] service_id ||= 'S1' valid_trips = trips.select { |trip| trip[:service_id].eql? service_id } trips_with_route = valid_trips.select{ |trip| if !route_id.nil? then trip[:route_id].eql? route_id else true end } trips_with_route.map {|trip| trip[:trip_id]} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def trips\n Trip.where(:route_id => self.route_id)\n end", "def trips\n Trip.where(:route_id => self.route_id)\n end", "def trips_by_route_id(route_id)\n get \"/gtfs/trips/routeid/#{route_id}\"\n end", "def trips\n Trip.all.filter do |trip|\n trip.listing == self\n end\n end", "def trips\n Trip.all.filter {|trip| trip.listing == self}\n\n end", "def getAllTripIds(route_id)\n trips_array = JSON.parse(File.read(TRIPS))\n all_trip_ids = []\n for trip in trips_array\n if trip[\"route_id\"] == route_id\n all_trip_ids << trip[\"trip_id\"]\n end\n end\n puts \"all_trip_ids is #{all_trip_ids[0, 10]}\"\n return getCurrentTrips(all_trip_ids)\n end", "def similar_trips\n Trip.where(destination_city: destination_city).where.not(id: id)\n end", "def search\n \n # Populate the @traveler variable\n get_traveler\n \n query = params[:query]\n query_str = query + \"%\"\n Rails.logger.debug query_str\n\n # This array will hold the list of matching places\n matches = [] \n # We create a unique index for mapping etc for each place we find\n counter = 0 \n \n # First search for matching names in my places\n rel = Place.arel_table[:name].matches(query_str)\n places = @traveler.places.active.where(rel)\n places.each do |place|\n matches << {\n \"index\" => counter,\n \"type\" => PLACES_TYPE,\n \"name\" => place.name,\n \"id\" => place.id,\n \"lat\" => place.location.first,\n \"lon\" => place.location.last,\n \"address\" => place.address,\n \"description\" => render_to_string(:partial => \"/shared/map_popup\", :locals => { :place => {:icon => 'icon-building', :name => place.name, :address => place.address} })\n }\n counter += 1\n end\n \n # Second search for matching address in trip_places. We manually filter these to find unique addresses\n rel = TripPlace.arel_table[:raw_address].matches(query_str)\n tps = @traveler.trip_places.where(rel).order(\"raw_address\")\n old_addr = \"\"\n tps.each do |tp|\n if old_addr != tp.raw_address\n matches << {\n \"index\" => counter,\n \"type\" => CACHED_ADDRESS_TYPE,\n \"name\" => tp.raw_address,\n \"id\" => tp.id,\n \"lat\" => tp.lat,\n \"lon\" => tp.lon,\n \"address\" => tp.raw_address,\n \"description\" => render_to_string(:partial => \"/shared/map_popup\", :locals => { :place => {:icon => 'icon-building', :name => tp.name, :address => tp.raw_address} })\n }\n counter += 1\n old_addr = tp.raw_address\n end \n end\n \n # Lastly search for matching names in the POI table\n rel = Poi.arel_table[:name].matches(query_str)\n pois = Poi.where(rel).limit(MAX_POIS_FOR_SEARCH)\n pois.each do |poi|\n matches << {\n \"index\" => counter,\n \"type\" => POI_TYPE,\n \"name\" => poi.name,\n \"id\" => poi.id,\n \"lat\" => poi.lat,\n \"lon\" => poi.lon,\n \"address\" => poi.address,\n \"description\" => render_to_string(:partial => \"/shared/map_popup\", :locals => { :place => {:icon => 'icon-building', :name => poi.name, :address => poi.address} })\n }\n counter += 1\n end\n \n respond_to do |format|\n format.js { render :json => matches.to_json }\n format.json { render :json => matches.to_json }\n end\n end", "def trips #<====== QUESTIONS: RETURNS NIL?\n Trip.all.select do |listings|\n if listings.listing == self\n listings\n end\n end\n end", "def trips\n Trip.all.select {|t| t.listing == self}\n end", "def trips\n Trip.all.select do |trip|\n trip.listing == self\n end\n\n end", "def matches(trip)\n if trip.to_work\n origin_dist = 8000\n destination_dist = 1000\n else\n origin_dist = 1000\n destination_dist = 8000\n end\n @matches = Trip.joins(:users).\n where(pools: { is_active: true}).\n where.not(users: { id: id}).\n where(\"users.driving_pref = 0 OR driving_pref != ?\", driving_pref).\n where(trips: {to_work: trip.to_work}).\n where(\"ST_NumGeometries(trips.waypoints) = 2\").\n where(\"ST_DWithin( ST_geometryN(trips.waypoints, 1)::geography , ?::geography, ? )\", trip.waypoints[0], origin_dist).\n where(\"ST_DWithin( ST_geometryN(trips.waypoints, 2)::geography , ?::geography, ? )\", trip.waypoints[1], destination_dist).\n limit(20)\n\n # This gets up to 20 trips where (in order):\n # - the match user is actively taking this trip\n # - the match user isn't the current user\n # - the match user is neutral driving_pref or opposite of current user\n # - the match trip has same \"to_work\" value as current trip\n # - the match trip is currently an individual trip (technically not checking this, just checking that trip only has 2 waypoints)\n # - the match trip's origin is within [origin_dist] of the current trip's origin (note the difference in indexing!)\n # - the match trip's destination is [destination_dist] 1km of the current trip's destination\n \n # ATM TIMES NEVER CONSIDERED ANYWHERE\n # SHOULD FILTER IN DB BASED ON TIME/LOCATIONS (POSSIBLY ORDER AND LIMIT), THEN ALSO COMPUTE COMPAT AND ORDER RESULTS SOMEHOW\n # SHOULD HAVE SOME WAY OF RELAXING IF NOT ENOUGH RESULTS / BEING MORE PICKY IF TOO MANY.\n # ALSO SHOULD PRIORITIZE EXISTING MATCHES SOMEWHERE SOMEHOW\n \n @matches = @matches.sort_by{|t| -compatibility(t.users.first)} #right now sorting by compatability with first user\n return @matches\n end", "def trips\n Trip.all.select {|trip| trip.listing == self}\n end", "def index\n find_exact_match_only = false\n if (params[:restaurant] or params[:location] )\n find_exact_match_only = true\n end\n if params[:featured] == '1' or params[:trip_location_id] == '0'\n @exact_match_count = 9 \n @message_with_trip_render = nil\n i = 0\n @trips = self.get_featured_trips(params, 3)\n else\n @trips, @exact_match_count, @message_with_trip_render = Trip.search(params, find_exact_match_only)\n end\n \n @trips, @exact_match_count, @message_with_trip_render = get_trips_filtered_by_landmarks(params, @trips, @message_with_trip_render, @exact_match_count)\n @locations = nil\n @restaurants = nil\n @traveler_types = nil\n trips_per_page_default = 3\n\n if (params[:trip_location_id] and params[:trip_location_id] != \"\" and (params[:page] == nil or params[:page] == \"1\"))\n # generate landmark of interest only for the initial trip search with location, not while paginating \n @locations = LocationDetail.search(params[:trip_location_id])\n @restaurants = RestaurantDetail.search(params[:trip_location_id])\n if (params[:traveler_type_id])\n @traveler_types = TravelerType.where(\"traveler_type_id IN (?)\", params[:traveler_type_id])\n end\n end\n \n # this can be simplified later\n page = !params[:page].blank? ? params[:page].to_i : 1\n @trips_per_page = !params[:per_page].blank? ? params[:per_page].to_i : trips_per_page_default\n @trips_per_page = (page <= 1) ? (@trips_per_page - 1) : @trips_per_page\n @exact_match_count = @exact_match_count - (page - 1) * @trips_per_page\n \n if params[:featured] != '1' and params[:trip_location_id] != '0'\n offset = (page == 1) ? 0 : ((page - 1) * @trips_per_page) - 1\n if [email protected]? and @trips.size % trips_per_page_default == 0\n # reset the trips per page as we are adding a dummy trip here\n @trips_per_page = trips_per_page_default \n @trips = @trips.unshift('wxyz')\n end\n @trips = @trips.paginate(:page => page != 1 ? params[:page] : \"1\", :per_page => @trips_per_page, :offset => offset) \n end\n \n respond_to do |format|\n if [email protected]?\n flash.now[:notice] = @message_with_trip_render\n format.html # index.html.erb\n format.js # index.js.erb\n format.json { render json: @trips }\n else\n format.html { redirect_to root_url() }\n end\n end\n end", "def trips\n Trip.all.select do |trip|\n trip.listing == self\n end\n end", "def trips\n Trip.all.select { |trip| trip.listing==self}\n end", "def trips()\n Trip.all().select() { | trip | trip.listing == self }\n end", "def trips\n Trip.all.select do |trip|\n trip.listing == self\n end\nend", "def trips\n @trips = Trip.all.select do |trip|\n trip.listing == self\n end\n end", "def trips_by_trip_id(trip_id)\n get \"/gtfs/trips/tripId/#{trip_id}\"\n end", "def find_trip\n @find_trip = Trip.where(\"id = #{params[:trip_id]}\")\n end", "def index\n # @locations = Location.all.where(:trip_id => @trip)\n @locations = Location.all.where(trip_id: @trip)\n @trip = Trip.find(params[:trip_id])\n end", "def trips\n arr = []\n Trips.all.each do |trip|\n if trip.listing == self\n arr << trip\n end\n end\n arr\n end", "def find_by_route\n @result = Array.new\n @distancias = Array.new\n\n @ride = Ride.order('id')\n if params[:radio] != '0'\n @ride.each do |p|\n distancia1 =Geocoder::Calculations.distance_between([params[:destLatitud],params[:destLongitud]], [p.destPointLat,p.destPointLong])\n distancia2 =Geocoder::Calculations.distance_between([params[:startLatitud],params[:startLongitud]], [p.startPointLat,p.startPointLong])\n if distancia1 <params[:radio].to_f && distancia2 <params[:radio].to_f\n @result.push(p)\n #@distancias.push(distancia1)\n end\n end\n # json_response={\n # result: @result,\n # distancias: @distancias\n # } \n respond_with @result , location: nil\n end\n if params[:radio] == '0'\n respond_with @ride,location: nil\n end \n #Ride.find_by_destPointLat_and_destPointLong(params[:latitud],params[:longitud])\n \n end", "def trips\n RideShare::Trip.find_all_for_rider(@id)\n end", "def filter_by_route\n array = []\n data.entry.arrivalsAndDepartures.each do |bus|\n time = OneBusAway::Utilities.convert_time bus.scheduledDepartureTime\n array << { bus.routeShortName => time }\n end\n array\n end", "def index\n search = TripSearch.new(search_params)\n trips = Trip.apply_scopes(\n search.start_location,\n search.driver_name,\n search.rider_name\n )\n\n render json: trips\n end", "def trips\n Trip.find_for_driver(@driver_id)\n end", "def trips\n Trip.all.select do |trip|\n if trip.guest == self\n trip\n end\n end\n end", "def trips \n trips_taken = Trip.all.select do |trip|\n trip.listing == self\n end\n end" ]
[ "0.6388643", "0.6388643", "0.60504746", "0.59264445", "0.58997303", "0.5855909", "0.58192116", "0.5799047", "0.57825017", "0.57342863", "0.57100093", "0.56728137", "0.567088", "0.5621909", "0.5620392", "0.5618179", "0.56052136", "0.5541512", "0.5539852", "0.5518571", "0.55021363", "0.5490308", "0.5483539", "0.54735476", "0.5440254", "0.54299796", "0.54281163", "0.541602", "0.54110116", "0.5393918" ]
0.8140789
0
Analyze the structure of the HTML document and score content blocks for likelihood of containing useful content
def analyze opt = DEFAULTS.clone opt.merge!(@options) @sections = [] factor = continuous = 1.0 body = '' score = 0 # The content is split into blocks of divs list = @raw_content.split(/<\/?(?:div)[^>]*>/) list.each do |block| next unless block block.gsub!(/\n/, '') # Ignore blocks that have no text next if has_only_tags?(block) # Each new block iterated over makes it less likely for it to belong # to the existing block continuous /= opt[:continuous_factor] if body.length > 0 # Clean up and strip block of html tags for scoring clean = clean_block(block) #clean = strip_tags(block) next if clean.length < opt[:min_length] # Calculate scores for clustering of blocks # c represents how probable it is for this block to be a content block c = (clean.length + clean.scan(opt[:punctuations]).length * opt[:punctuation_weight]) * factor # The further down the document we go (i.e. the more blocks we see), # the less likely they are to be valid content blocks factor *= opt[:decay_factor] # The not body rate represents how likely this is to be a junk block not_body_rate = block.scan(opt[:waste_expressions]).length # The block score is reduced if there is a not_body_rate c *= (opt[:no_body_factor] ** not_body_rate) if not_body_rate>0 # c1 represents how probable it is for this block to belong to the # existing block or if it is a new one c1 = c * continuous puts "----- #{c}*#{continuous}=#{c1} #{clean.length} \n\n" if opt[:debug] if c1 > opt[:threshold] # Treat continuous blocks as cluster body += block + "\n" score += c1 continuous = opt[:continuous_factor] elsif c > opt[:threshold] # Continuous block end @sections << { :body => body, :score => score } body = block + "\n" score = c continuous = opt[:continuous_factor] else # We drop blocks that don't have a high enough c score end end # Add the last block as we've finished iterating @sections << { :body => body, :score => score } if body # Sort the sections by score sorted_sections = @sections.sort_by { |section| section[:score] } # Convert to nokogiri representation for compatibility with the content method @content_candidates = sorted_sections.reverse.map { |section| Nokogiri::HTML(section[:body], nil, 'utf-8') } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def rate_content(content)\n contents = Hash.new\n for i in 0...content.size\n contents[\"#{i}\"] = 0.0\n\n # chceking if div does not contain whole document\n contents[\"#{i}\"] += -20 if content[i].to_s.lines.count > @@lines*0.95\n\n # rating contents for tags they contain\n contents[\"#{i}\"] += 0.3*content[i].xpath(\".//span\").size if content[i].xpath(\".//span\").size != 0\n contents[\"#{i}\"] += 2*content[i].xpath(\".//p\").size if content[i].xpath(\".//p\").size != 0\n contents[\"#{i}\"] += 0.5*content[i].xpath(\".//img\").size if content[i].xpath(\".//img\").size != 0\n contents[\"#{i}\"] += 1*content[i].xpath(\".//h3\").size if content[i].xpath(\".//h3\").size != 0\n contents[\"#{i}\"] += 0.6*content[i].xpath(\".//br\").size if content[i].xpath(\".//br\").size != 0\n contents[\"#{i}\"] += 0.4*content[i].xpath(\".//strong\").size if content[i].xpath(\".//strong\").size != 0\n contents[\"#{i}\"] += 0.4*content[i].xpath(\".//em\").size if content[i].xpath(\".//em\").size != 0\n contents[\"#{i}\"] += 0.5*content[i].xpath(\".//h2\").size if content[i].xpath(\".//h2\").size != 0\n contents[\"#{i}\"] += 0.4*content[i].xpath(\".//b\").size if content[i].xpath(\".//b\").size != 0\n contents[\"#{i}\"] += 0.2*content[i].xpath(\".//h1\").size if content[i].xpath(\".//h1\").size != 0\n contents[\"#{i}\"] += 2*content[i].xpath(\".//article\").size if content[i].xpath(\".//article\").size != 0\n\n #checking if div does not contain navigation links\n for j in 0...@@nav_links.size do\n contents[\"#{i}\"] += -2 if content[i].to_s.include? @@nav_links[j].to_s\n end\n\n end\n\n right_content = contents.max_by{|k,v| v}[0]\n\n cnt = content[right_content.to_i]\n clear(cnt)\n end", "def process_html\n benchmark \"Process HTML for #{self.url}\" do\n doc = Readability::Document.new(self.html)\n html = doc.html\n self.title = content_for_open_graph_tag('og:title', html) || doc.title\n self.description =\n content_for_open_graph_tag('og:description', html) ||\n content_for_meta_tag('name=\"description\"', html) ||\n html.xpath('//head/meta/@description', html).first.try(:content)\n image_url = content_for_open_graph_tag('og:image', html) || doc.images.first\n self.image_url = image_url if image_url =~ URI.regexp\n self.site_name = content_for_open_graph_tag('og:site_name', html) || get_url_domain.try(:humanize)\n self.content_html = doc.content.encode_from_charset!(doc.html.encoding)\n self.content = Nokogiri::HTML(self.content_html).text\n end\n self\n end", "def parse_page(doc)\n\t\t @hashes.tags_weights.each do |tag, weight|\n\t\t\t doc.xpath(\"//#{tag}\").each do |node|\n\t\t\t\t\tparse_node(node.text, weight) \n\t\t\t\tend\n\t\t end\n\t\t @hashes.special_tags_weights.each do |tag, desc_weight|\n\t\t \tdoc.xpath(\"//#{tag}\").each do |node|\n\t\t \t parse_node(node.attr(desc_weight[0]), desc_weight[1])\n\t\t \tend\n\t\t end\n\t\tend", "def parse_doc(doc)\n doc.xpath('//div[@class = \"z-list\"]').each do |node|\n\n story_content = Hash.new\n\n # get an array of the all the links\n links = Array.new\n node.xpath('./a').each do |link_node|\n links.push(link_node)\n end\n # the first link is the title\n story_content[\"title\"] = links[0].content\n\n # get story id\n url_split = links[0]['href'].split('/')\n story_content['ff_id'] = url_split[url_split.length-3]\n\n # the last link is reviews link or the author link\n last_link = links[links.length-1]\n # remove the link if its a review link\n if ((last_link.content <=> \"reviews\") == 0)\n # remove it and do it again\n links.pop()\n last_link = links[links.length-1]\n end\n\n # Set the author\n author_name = last_link.content\n author_url_split = last_link['href'].split('/')\n author_ff_id = author_url_split[author_url_split.length-2]\n story_content['author'] = generate_author(author_name, author_ff_id)\n\n # get the gray section (details)\n gray = \"\"\n node.xpath('./div//div').each do |div_node|\n gray=div_node.content\n # remove the node for the summary later\n div_node.remove\n end\n\n details = gray.split(\" - \")\n\n tags = Hash.new\n # split each of those by :\n count = 1\n story_content['reviews'] = '0'\n details.each do |detail|\n detail_split = detail.split(\":\")\n # If there is nothing in the second one that it isn't a set\n if(detail_split[1] != nil)\n story_content[detail_split[0].downcase] = detail_split[1].strip\n else# we need to do something differnt\n # complete status\n if ((detail_split[0] <=> \"Complete\") == 0)\n story_content['complete'] = true\n # language\n elsif count == 2\n story_content['language'] = detail_split[0]\n # Theme\n elsif count == 3\n story_content['theme'] = detail_split[0].split(\"/\")\n end\n\n # Main Characters\n if (count == details.length)\n if (details[details.length-1] <=> \"Complete\") != 0\n # story isn't complete characters are the last one (or published)\n detail_split = detail.split(\":\")\n if !detail_split[1] # Not published there are no characters\n story_content['characters'] = detail_split[0].split(\" & \")\n end\n else\n # story is complete characters are the second to last one\n detail_split = details[details.length-2].split(\":\")\n if !detail_split[1] # Not published there are no characters\n story_content['characters'] = details[details.length-2].split(\" & \")\n end\n end\n end\n\n # defaulting to false if complete isn't set\n if story_content['complete'] != true\n story_content['complete'] = false\n end\n end\n count+=1\n end\n\n # get the summary\n node.xpath('./div').each do |summary_node|\n story_content['summary'] = summary_node.content\n end\n\n generate_story(story_content)\nend\n\n\n\n#\n# Stores a datastructure with the list of the current ships\n#\ndef update_ships\n # A data structure to store the ships in\n\n ships = [\n [\"Brittana\", [\"Brittany P.\", \"Santana L.\"]],\n [\"Faberry\", [\"Quinn F.\", \"Rachel B.\"]],\n [\"Flanamotta\", [\"Rory F.\", \"Sugar\"]],\n [\"Sory\", [\"Rory F.\", \"Sam E.\"]],\n [\"Seblaine\", [\"Sebastian S.\", \"Blaine A.\"]],\n [\"Santofsky\", [\"D. Karofsky\", \"Santana L.\"]],\n [\"Bartie\", [\"Brittany P.\", \"Artie A.\"]],\n [\"Tike\", [\"Mike C.\", \"Tina C.\"]],\n [\"Pezberry\", [\"Santana L.\", \"Rachel B.\"]],\n [\"Pizes\", [\"Lauren Z.\", \"Puck\"]],\n [\"St. Berry\", [\"Jesse sJ.\", \"Rachel B.\"]],\n [\"Kill\", [\"Kurt H.\", \"Will S.\"]],\n [\"Puckurt\", [\"Kurt H.\", \"Puck\"]],\n [\"Artina\", [\"Tina C.\", \"Artie A.\"]],\n [\"Partie\", [\"Puck\", \"Artie A.\"]],\n [\"Blainofskyve\", [\"Blaine A.\", \"D. Karofsky\"]],\n [\"Klaine\", [\"Kurt H.\", \"Blaine A.\"]],\n [\"Hummelberry\", [\"Kurt H.\", \"Rachel B.\"]],\n [\"Furt\", [\"Kurt H.\", \"Finn H.\"]],\n [\"Pinn\", [\"Puck\", \"Finn H.\"]],\n [\"Samcedes\", [\"Sam E.\", \"Mercedes J.\"]],\n [\"Artcedes\", [\"Artie A.\", \"Mercedes J.\"]],\n [\"Finchel\", [\"Finn H.\", \"Rachel B.\"]],\n [\"Puckleberry\", [\"Puck\", \"Rachel B.\"]],\n [\"Wemma\", [\"Will S.\", \"Emma P.\"]]\n ]\n\n ships.each do |ship_data|\n ship = Ship.find_by_name(ship_data[0])\n\n # Make sure the ship doesn't already exist\n if !ship\n\n # create a new ship\n ship = Ship.new()\n ship.name = ship_data[0]\n ship.save\n\n # For each character in the ship\n ship_characters = ship_data[1]\n generate_log(\"Generating New Ship: #{ship_data[0]} between #{ship_data[1]}\")\n ship_characters.each do |ship_character|\n character = generate_character(ship_character)\n # Save the relationship\n relationship = Relationship.new()\n relationship.ship = ship\n relationship.character = character\n relationship.save\n\n end\n else\n ship.update_attributes(:name => ship_data[0])\n ship.save\n generate_log(\"Updating: #{ship_data[0]} between #{ship_data[1]}\")\n\n\n end\n end\nend\n\n\nend", "def process(content, uri, args = \"\")\n html_doc = Nokogiri::HTML(content) do |config| config.noerror end\n\n node = html_doc.xpath(\"//div[@class='markdown-body']\").first\n\n stamp(node, uri, 'github-wiki')\n\n if args.include?(\"reduce-headings\") then\n 5.downto(1) { |level|\n node.xpath(\"//h#{level}\").each { |heading_node|\n heading_node.name = \"h#{level+1}\"\n }\n }\n end\n\n node.to_s\n end", "def content(clean = false, index = 0)\n return @content[[clean, index]] if @content[[clean, index]]\n return '' if !@content_candidates || @content_candidates.empty?\n \n content_branch = content_at(index)\n orphans_to_remove = []\n \n #ap content_branch.to_html\n #exit\n \n # Go through every piece of the content and rip out sections that contain too many tags compared to words\n # This is usually indicative of \"widgets\" or link bar sections\n content_branch.css('*').each_with_index do |el, i|\n next unless el\n\n if el.name == \"h1\"\n el.remove\n next\n end\n\n if el.name == \"h2\" && content_branch.inner_html.scan('<h2').size == 1\n el.remove\n end\n\n # Remove elements that contain words but there are more tags than words overall\n # First, count the words\n #word_count = 0\n #el.traverse do |subel|\n # if subel.text? && subel.path !~ /\\/a\\// && subel.path !~ /\\/(h1|h2|h3|h4|h5|h6)\\//\n # word_count += (subel.text.downcase.scan(/[a-z]{4,}/) - META_WORDS).size\n # end\n #end\n #\n ## .. then count the tags\n #\n #inner_tags = el.inner_html.scan(/\\<\\w.*?\\>/).size\n #if word_count < inner_tags && inner_tags > 3 && word_count < 250\n # puts \"At #{el.name} #{el['id']} #{el['class']} containing '#{el.text[0..20]}' we have #{word_count} valid words to #{el.inner_html.scan(/\\<\\w.*?\\>/).size} tags\"\n # #puts \"Removing #{el.name} #{el['id']} #{el['class']} TOO MANY TAGS FOR WORDS\"\n # el.remove\n # next\n #end\n\n # If there are at least 2 words and a third of them are \"meta words,\" remove the element\n #inner_words = el.text.to_s.downcase.scan(/[a-z]{3,}/)\n #if BLOCK_OUTPUT_ELEMENTS.include?(el.name) && inner_words.size >= 2\n # if ((inner_words & META_WORDS).size >= (inner_words.size / 3))\n # el.remove\n # end\n #end\n\n if el.text && el.text.strip.length < 3 && !%w{img}.include?(el.name) && el.inner_html !~ /\\<img/\n el.remove\n next\n end\n\n if el.name == \"p\" && el.text !~ /(\\.|\\?|\\!|\\\"|\\')(\\s|$)/ && el.inner_html !~ /\\<img/\n el.remove\n next\n end\n\n # If the ID or class of the element contains a fatally bad word, get rid of it\n if (BAD_WORDS & (el['id'].to_s + ' ' + el['class'].to_s).downcase.scan(/[a-z]+/)).length > 0\n #puts \"Removing #{el.name} #{el['id']} #{el['class']} BAD\"\n el.remove\n next\n end\n end\n\n # If a title was found early in the result document but had text before it, remove that text - it's probably crap\n orphans_to_remove.each { |el| el.remove }\n \n # Clean up the HTML again - Nokogiri outputs it with full doctype and crap\n clean_html = strip(Sanitize.clean(content_branch.to_html, :elements => (clean ? BLOCK_OUTPUT_ELEMENTS : OUTPUT_ELEMENTS), :attributes => (clean ? OK_CLEAN_ATTRIBUTES : OK_ATTRIBUTES)))\n \n # If the content is desired as \"clean\" (i.e. plain-text), do some quick fix-ups\n if clean\n # Get rid of line break tags, make list items look nice, remove all other HTML tags, and clean up spaces and newlines\n clean_html.gsub!(/<br.*?>/, \"\\n\")\n clean_html.gsub!(/<li>/, '* ')\n clean_html.gsub!(/<\\w+>/, '')\n clean_html.gsub!(/<\\/\\w+>/, \"\\n\")\n clean_html.gsub!(/\\ +/, ' ')\n clean_html.gsub!(/^\\s+\\n/, \"\\n\")\n clean_html.gsub!(/\\n{2,}/, \"\\n\")\n clean_html.strip!\n end\n \n # If tags butt up against each other across lines, remove the line break(s)\n clean_html.gsub!(/\\>\\n+\\</, '><')\n\n # Get rid of images whose sources are relative (TODO: Make this optional)\n clean_html.gsub!(/\\<img .*?\\>/i) do |img_tag|\n img_tag =~ /\\Whttp/ ? img_tag : ''\n end\n\n # Remove empty tags\n clean_html.gsub!(/<(\\w+)><\\/\\1>/, \"\")\n\n # Just a messy, hacky way to make output look nicer with subsequent paragraphs..\n clean_html.gsub!(/<\\/(div|p|h1|h2|h3|h4|h5|h6)>/, '</\\1>' + \"\\n\\n\")\n \n @content[[clean, index]] = clean_html\n end", "def get_content2(node, total_text_length)\n text_length = node.text.length\n html_length = node.inner_html.length\n\n node.elements.sort {|n1, n2| n2.text.length <=> n1.text.length}.each do |element|\n total_text_ratio = element.text.length.to_f / total_text_length.to_f\n\n if total_text_ratio > 0.5\n get_content(element, total_text_length)\n end\n end\n\n node.inner_html\nend", "def doc_block_analysis(progress)\n total = @documents.size.to_f\n\n @blocks = @documents.each_with_index.map do |d, i|\n progress.call((i.to_f / total * 40.0).to_i + 40) if progress\n\n d.term_vectors.each_with_object do |(k, v), ret|\n next unless @word_list.include?(k)\n ret[k] = v[:tf]\n end\n end\n progress.call(80) if progress\n\n @block_stats = @documents.each_with_index.map do |d, i|\n progress.call((i.to_f / total * 20.0).to_i + 80) if progress\n\n {\n name: I18n.t('lib.frequency.block_count_doc',\n num: 1, total: 1, title: d.uid),\n types: d.term_vectors.size,\n tokens: d.term_vectors.map { |k, v| v[:tf] }.reduce(:+)\n }\n end\n end", "def parse_block_html; end", "def parse_codeblocks(html); end", "def run\n\t\t\t\tif save_file\n\t\t\t\t\tdoc = Nokogiri::HTML(open(@file,\"r\"))\n\t\t\t\t\tparse_page(doc)\n\t\t\t\t\tflush_page\n\t\t\t save_words\n\t\t\t end\n\t\t\tend", "def parse_html_files\n Find.find(Dir.getwd) do |file|\n if !File.directory? file and File.extname(file) == '.html'\n # exclude and skip if in a bad directory\n # we may be on an html file, but some we just do not want\n current = File.new(file).path\n\n # skip these folders entirely\n if current.match(/(blog|old|draft|archive|font)/i)\n next\n end\n\n # open file, pluck content out by its element(s)\n page = Nokogiri::HTML(open(file));\n\n # grab title\n title = page.css('title').text.to_s;\n title = strip_bad_chars(title)\n\n # for page title, destroy any pipes and MS pipes and return the first match\n title.sub!('Velir | ', '')\n\n # Grab hero title and tagline\n hero = page.css('article.type-centered h2').text\n hero_tagline = page.css('article.type-centered .type-hero').text\n\n # grab the body content\n body = page.css('.outer-wrapper .row .columns').to_html\n body = clean_body(body)\n\n # clean the file path\n path = File.new(file).path\n path.gsub! $base_path, \"/\"\n\n # if we have content, add this as a page to our page array\n if (body.length > 0)\n $count += 1\n puts \"Processing \" + title\n\n # insert into array\n data = {\n 'title' => title,\n 'path' => path,\n 'hero' => hero,\n 'hero_tagline' => hero_tagline,\n 'body' => body,\n }\n\n $pages.push data\n end\n end\n end\n\n write_csv($pages)\n report($count)\nend", "def execute\n\n logger = Logger.new(\"/dev/null\")\n logger.level = Logger::WARN\n log_adapter = JerichoLoggerAdapter.new(logger)\n\n\n Dir.glob('./**/*.{jsp,jspf}').each do |path|\n content = File.read(path)\n source = Source.new(content)\n source.setLogger(log_adapter)\n out = OutputDocument.new(source)\n\n tags = source.getAllStartTags\n tags.each do |tag|\n if applicable?(tag)\n process_tag(source, out, tag, path)\n end\n end\n SpacewalkHtmlClean.generate_diff(content, out, path)\n end\n end", "def prepare_html(content , page_type = 'N')\n #header\n 1.upto 5 do |no| content.gsub! /^(={#{no}}) (.*) (={#{no}})/ ,\"\\nh#{no+1}. \\\\2\\n\" end\n 1.upto 5 do |no| content.gsub! /^(={#{no}}) (.*)/ ,\"\\nh#{no+1}. \\\\2\\n\" end\n\n #list\n 1.upto 5 do |no| content.gsub! /^([ ]{#{no}})(\\*) ?(.*)/ ,\"#{'*'*no} \\\\3\" end\n 1.upto 5 do |no| content.gsub! /^([ ]{#{no}})(#) ?(.*)/ ,\"#{'#'*no} \\\\3\" end\n #content.gsub! /(\\*) v (.*)/ , \"\\\\1 -\\\\2-\"\n \n #block\n content.gsub! /^\\{\\{\\{/ , \"<pre>\" ; content.gsub! /^\\}\\}\\}/ , \"</pre>\"\n content.gsub! /^\\{\\{\\\"/ , \"<blockquote>\" ; content.gsub! /^\\\"\\}\\}/ , \"</blockquote>\"\n content.gsub! /^\\{\\{\\[/ , \"<math>\" ; content.gsub! /^\\]\\}\\}/ , \"</math>\"\n \n #concept & property\n content.gsub! /\\[\\[(.*?):=(.*?)\\]\\]/ , '\\1(\\2)'\n #content.gsub! /\\[\\[(.*?)[<>=].*?\\]\\]/ , \\\"\\\\1\\\":#{APP_ROOT}/page/\\\\1\" \n content.gsub! /\\[\\[(.*?)\\]\\]/ , \"\\\"\\\\1\\\":#{APP_ROOT}/entry/\\\\1\" if defined?(APP_ROOT)\n\n #comment\n content.gsub! PTN_COMMENT , \"\\\\1\"\n content.gsub! PTN_COMMENT_MULTILINE , \"\"\n if defined? SystemConfig\n SystemConfig.site_info.each do |e|\n content.gsub! /(\\s)#{e[1]}:/ , \"\\\\1#{e[2]}\"\n end\n content.gsub! SystemConfig.ptn_url_unnamed , \"\\\\1\\\"\\\\2\\\":\\\\2\"\n content.gsub! \"%ROOT%\" , APP_ROOT\n end\n \n #Process by page_type\n case page_type\n when 'N'\n math_list = content.scan( PTN_MATH ) ; math_list.each do |m|\n #content.gsub! \"$#{m[0]}$\" , latex_render(m[0])\n content.gsub! \"$#{m[0]}$\" , get_math_img(m[0])\n end\n math_block_list = content.scan( PTN_MATH_BLOCK ) ; math_block_list.each do |m|\n #content.gsub! \"#{m[0]}\" , latex_render(m[0])\n content.gsub! \"#{m[0]}\" , get_math_img(m[0])\n end\n when 'S'\n menu_list = content.scan( PTN_MENU ) ; menu_list.each do |m|\n menu_title = m[0] ; menu_target = m[1] ; menu_str = \"M{{#{menu_title}|#{menu_target}}}\"\n #$lgr.info \"#{menu_title} / #{menu_target}\"\n result = link_to_remote(menu_title , :url => { :action => 'menu' , :query => CGI.escape(menu_target) })\n content.gsub! menu_str , result\n end\n end\n #$lgr.info \"[prepare_html] \"+content\n query_list = content.scan( PTN_QUERY ) ; query_list.each do |q|\n query_type = q[0] ; query_content = q[1] ; query_str = \"#{query_type}{{#{query_content}}}\"\n case query_type\n when 'P'\n result = eval(\"find_page :display=>'|@title|@tags|@created_at|' ,\" + query_content )\n result = result.join(\"\\n\") if result.class == Array\n result = \"|_.Title|_.Tag|_.CreatedAt|\\n\"+result if query_content.scan(/:display/).size == 0\n #$lgr.info \"[prepare_html] Query : #{query_str} , #{result}\"\n content.gsub! query_str , result\n end\n end\n #content.gsub! SystemConfig.ptn_url , \"\\\"\\\\0\\\":\\\\0\"\n #???content.gsub!(SystemConfig.ptn_site) \"\\\"#{ApplicationController.SystemConfig(\\\\0)}\\\":\\\\0\"\n content\n end", "def process_markup()\n [title,content].each do |text|\n next if !text\n clear_webpage(text).scan(PTN_MARKUP).map{|e|e[0].split(PTN_ELEMENT_SEP)}.flatten.each do |element|\n #debug \"[process_markup] element: \"+element.inspect\n next if !element\n ptn = element.scan(PTN_METADATA)\n #debug \"[process_markup] ptn: \"+ptn.inspect\n if ptn.size > 0\n m[ptn[0][0].to_sym] = parse_value(ptn[0][1])\n else\n create_and_link(element, 'tag' , \"t\")\n #add_tags(element, \"m\")\n end\n end#scan\n end#each\n end", "def analyze\n analyze_text\n @analyzed = true\n nil\n end", "def process_html(document)\n\t\t\t\n\t\t\t# Add link and raw HTML to a hash as key/value\n\t\t\t# for later storage in database\n\t\t\tunless @raw_html.has_value?(document)\n\t\t \t\tprint \".\"\n\t\t \t\t@raw_html[@document.base_uri.to_s] = document\n\t\t\tend\n\t\t\t\t\n\t\tend", "def content\n div :id => 'doc3' do\n div :id => 'hd' do\n render_top_line\n h1 @page_title || 'Missing :page_title' \n end\n div :id => 'bd' do\n render_body\n end\n div :id => 'ft' do\n render_footer\n end\n end\n end", "def _HtmlBlockInTags\n\n _save = self.pos\n while true # choice\n _tmp = apply(:_HtmlAnchor)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockAddress)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockBlockquote)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockCenter)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockDir)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockDiv)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockDl)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockFieldset)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockForm)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockH1)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockH2)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockH3)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockH4)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockH5)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockH6)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockMenu)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockNoframes)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockNoscript)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockOl)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockP)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockPre)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockTable)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockUl)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockDd)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockDt)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockFrameset)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockLi)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockTbody)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockTd)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockTfoot)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockTh)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockThead)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockTr)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockScript)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_HtmlBlockHead)\n break if _tmp\n self.pos = _save\n break\n end # end choice\n\n set_failed_rule :_HtmlBlockInTags unless _tmp\n return _tmp\n end", "def process_overview_page(response_body)\n hash = {}\n\n if !response_body.nil?\n doc = Nokogiri.HTML(response_body)\n\n # default specs page url\n hash['specs_url_slug'] = nil\n x = doc.css('#ymm-nav-specs-btn').first\n hash['specs_url_slug'] = x['href'].split('/').last if !x.nil?\n\n # ranking - number\n hash['expert_ranking_number'] = nil\n x = doc.css('.primary-rank span').first\n hash['expert_ranking_number'] = x.text.gsub('#', '').to_i if !x.nil?\n\n # ranking - category\n hash['expert_ranking_category'] = nil\n x = doc.css('.primary-rank a').first\n hash['expert_ranking_category'] = x.text if !x.nil?\n\n # user reviews - rating\n hash['used_reviews_rating'] = nil\n x = doc.css('.user-reviews .star-actual').first\n hash['used_reviews_rating'] = (x['data-width'].to_i / 26) if !x.nil?\n\n # user reviews - number\n hash['used_reviews_number'] = nil\n x = doc.css('.user-reviews .total-review').first\n hash['used_reviews_number'] = x.text.to_i if !x.nil?\n\n # expert rating\n hash['expert_rating'] = Hash.new\n if !doc.css('.expert-ratings-block').nil?\n # - overall\n hash['expert_rating']['overview'] = nil\n x = doc.css('.expert-ratings-block .ratingNumber').first\n hash['expert_rating']['overview'] = x.text.to_f if !x.nil?\n\n doc.css('.expert-ratings-block table > tr').each do |row|\n key = @expert_ratings[row.css('td:eq(1)').text]\n if !key.nil?\n hash['expert_rating'][key] = nil\n rating = row.css('td:eq(2)').text\n hash['expert_rating'][key] = rating.to_i if !rating.nil? && rating != '' && rating.downcase != 'n/a'\n end\n end\n end\n\n # expert likes\n hash['expert_likes'] = []\n doc.css('#likes ul li').each do |item|\n hash['expert_likes'] << item.text\n end\n\n # expert dislikes\n hash['expert_dislikes'] = []\n doc.css('#dislikes ul li').each do |item|\n hash['expert_dislikes'] << item.text\n end\n\n # user price range\n hash['used_price_range'] = nil\n x = doc.css('.used-yrmd-price a').first\n hash['used_price_range'] = x.text if !x.nil?\n\n end\n\n return hash\nend", "def process_html(content)\n head, opener, tail = content.output.partition(OPENING_BODY_TAG_REGEX)\n body_content, *rest = tail.partition(\"</body>\")\n\n processed_markup = process_anchor_tags(body_content)\n\n content.output = String.new(head) << opener << processed_markup << rest.join\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 score\n @body.each_node(:lvasgn, *CONSIDERED_NODES).reduce(1) do |score, node|\n next score if !iterating_block?(node) || node.lvasgn_type?\n next score if node.csend_type? && discount_for_repeated_csend?(node)\n\n next 1 + score\n end\n end", "def html_reducer(html_doc)\n html_doc_chars = html_doc.strip.split(\"\")\n\n self_closing_tags = [\"area\",\"base\",\"br\",\"col\",\"embed\",\"hr\",\"img\",\"input\",\"link\",\"meta\",\"param\",\"source\",\"track\",\"wbr\",\"command\",\"keygen\",\"menuitem\"]\n reopenable_tags = [\"b\",\"i\",\"a\",\"font\",\"em\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"pre\",\"strong\",\"u\"]\n nestable_tags = [\"div\"]\n\n element_stack = [] # stack of open elements\n reduction = [] # results array\n buffer = \"\"\n\n while html_doc_chars.length > 0\n buffer << html_doc_chars.shift # get another char\n\n closing_script_regex = /<\\/script\\s*>\\z/i\n closing_script_match = buffer.match(closing_script_regex)\n\n closing_style_regex = /<\\/style\\s*>\\z/i\n closing_style_match = buffer.match(closing_style_regex)\n\n self_closing_tag_regex = /<[a-z][^>]*\\/\\s*>\\z/i\n self_closing_tag_match = buffer.match(self_closing_tag_regex)\n\n tag_regex = /<[a-z][^>]*>\\z/i\n tag_match = buffer.match(tag_regex)\n\n closing_tag_regex = /<\\/[a-z][^>]*>\\z/i\n closing_tag_match = buffer.match(closing_tag_regex)\n\n doctype_regex = /<!doctype\\s*[^>]*>\\z/i\n doctype_match = buffer.match(doctype_regex)\n\n comment_regex = /<!--.*?-->\\z/\n comment_match = buffer.match(comment_regex)\n\n # closing script tag\n if closing_script_match\n text = buffer.split(closing_script_regex).first.to_s.strip\n if text != \"\"\n element_stack.last.contents << text\n end\n buffer = \"\"\n element_stack.pop\n\n # closing style tag\n elsif closing_style_match\n text = buffer.split(closing_style_regex).first.to_s.strip\n if text != \"\"\n element_stack.last.contents << text\n end\n buffer = \"\"\n element_stack.pop\n\n # comment\n elsif comment_match\n contents = (element_stack.last&.contents) || reduction\n text = buffer.split(comment_regex).first.to_s.strip\n if text != \"\"\n contents << text\n end\n contents << comment_match.to_s\n\n buffer = \"\"\n\n # inside a script\n elsif tag_in_stack(element_stack,\"script\")\n # do nothing\n\n elsif tag_in_stack(element_stack,\"style\")\n # do nothing\n\n elsif buffer.include?(\"<!--\")\n # do nothing\n\n # self closing tag containing /> (doesn't get pushed to the stack)\n elsif self_closing_tag_match\n text = buffer.split(self_closing_tag_regex).first.to_s.strip\n contents = (element_stack.last&.contents) || reduction\n if text != \"\"\n contents << text\n end\n contents << HTML_element.from_string(self_closing_tag_match.to_s)\n buffer = \"\"\n \n # tag\n elsif tag_match\n text = buffer.split(tag_regex).first.to_s.strip\n contents = (element_stack.last&.contents) || reduction\n if text != \"\"\n contents << text\n end\n elem = HTML_element.from_string(tag_match.to_s)\n\n if !self_closing_tags.include?(elem.tag) # push to the stack\n # check whether nesting is possible\n if tag_in_stack(element_stack,elem.tag) && !nestable_tags.include?(elem.tag)\n tmp_stack = []\n while tag_in_stack(element_stack,elem.tag)\n tmp = element_stack.pop\n contents = (element_stack.last&.contents) || reduction\n if reopenable_tags.include?(tmp.tag) && (tmp.tag != elem.tag)\n tmp_stack << tmp\n end\n end\n \n contents << elem\n element_stack.push(elem)\n contents = (element_stack.last&.contents) || reduction\n while tmp_stack.length > 0\n new_elem = HTML_element.from_html_element(tmp_stack.pop)\n contents << new_elem\n element_stack.push(new_elem)\n contents = (element_stack.last&.contents) || reduction\n end\n else\n contents << elem\n element_stack.push(elem)\n end\n else\n contents << elem\n end\n\n buffer = \"\"\n\n # closing tag\n elsif closing_tag_match\n text = buffer.split(closing_tag_regex).first.to_s.strip\n contents = (element_stack.last&.contents) || reduction\n if text != \"\"\n contents << text\n end\n tag = HTML_element.tag_from_string(closing_tag_match.to_s)\n if tag_in_stack(element_stack, tag)\n tmp_stack = []\n until element_stack.last.tag == tag\n tmp = element_stack.pop\n if reopenable_tags.include?(tmp.tag) && (tmp.tag != tag)\n tmp_stack << tmp\n end\n end\n element_stack.pop\n contents = (element_stack.last&.contents) || reduction\n \n while tmp_stack.length > 0\n new_elem = HTML_element.from_html_element(tmp_stack.pop)\n contents << new_elem\n element_stack.push(new_elem)\n contents = (element_stack.last&.contents) || reduction\n end\n end\n buffer = \"\"\n\n # doctype (stack must be empty)\n elsif doctype_match\n text = buffer.split(doctype_regex).first.to_s.strip\n if text != \"\"\n reduction << text\n end\n reduction << doctype_match.to_s\n buffer = \"\"\n end\n end\n\n contents = (element_stack.last&.contents) || reduction\n contents << buffer\n\n reduction\nend", "def run\n reset!\n\n pages.each do |page|\n log.puts\n\n if page.respond_to?(:read)\n html = page.read\n elsif page.respond_to?(:call)\n result = instance_eval(&page)\n\n html = case result\n when String\n result\n else\n @agent.page.body\n end\n else\n begin\n html = fetch(page)\n rescue FetchError => e\n log.puts(e.message.red)\n next\n end\n end\n\n process!(html)\n end\n\n report\n\n selectors_to_review\n end", "def summary(content)\n content[0, content.index('<!-- more -->') || content.length]\nend", "def process_nodes(html_nodes, properties); end", "def stats\n\n # extract the content\n extract_content\n generate_titles\n\n rescue ActiveRecord::RecordNotFound\n\n not_found and return\n\n end", "def process_markdown_inside_elements(doc)\n # parse block-level markdown elements in these HTML tags\n block_tags = ['div']\n\n elts = []\n @fragment.each_element('//*[@markdown]') do |e|\n elts << e\n end\n\n d = @fragment.children.first\n if d && HTML_INLINE_ELEMS.include?(first_node_name)\n elts << d unless d.attributes['markdown']\n elts += span_descendents(d)\n end\n\n # find span elements or elements with 'markdown' attribute\n elts.each do |e|\n # should we parse block-level or span-level?\n how = e.attributes['markdown']\n e.attributes.delete('markdown')\n\n next if \"0\" == how # user requests no markdown parsing inside\n parse_blocks = (how == 'block') || block_tags.include?(e.name)\n\n # Select all text children of e\n e.texts.each do |original_text|\n s = CGI.escapeHTML(original_text.value)\n unless s.strip.empty?\n # TODO extract common functionality\n parsed = parse_blocks ? doc.parse_text_as_markdown(s) : doc.parse_span(s)\n # restore leading and trailing spaces\n padding = /\\A(\\s*).*?(\\s*)\\z/.match(s)\n parsed = [padding[1]] + parsed + [padding[2]] if padding\n\n el = doc.md_el(:dummy, parsed)\n\n new_html = \"<dummy>\"\n el.children_to_html.each do |x|\n new_html << x.to_s\n end\n new_html << \"</dummy>\"\n\n newdoc = REXML::Document.new(new_html).root\n\n p = original_text.parent\n newdoc.children.each do |c|\n p.insert_before(original_text, c)\n end\n\n p.delete(original_text)\n end\n end\n end\n end", "def test_stats\n assert @page != nil\n\n wc = @analyzer.word_count @view\n puts wc\n # word count from MS Word: 3.648 (including UI text from Mahara)\n assert_equal 3759, wc\n\n external_links = @analyzer.external_links @view\n puts \"external links: #{external_links.size}\"\n # external_links.each do |link|\n # puts \"> \" + link.uri.to_s\n # end\n\n images = @analyzer.images @view\n puts \"images: #{images.size}\"\n # images.each do |image|\n # puts \"> \" + image.to_s\n # end\n\n uploaded_images = @analyzer.uploaded_images @view\n puts \"uploaded_images: #{uploaded_images.size}\"\n\n wikipedia_images = @analyzer.images_from_domain(@view, \"wikipedia\")\n puts \"wikipedia_images: #{wikipedia_images.size}\"\n end" ]
[ "0.71152675", "0.61536187", "0.6008303", "0.5928885", "0.5910866", "0.58664024", "0.5846169", "0.5725032", "0.57192284", "0.55903924", "0.5530526", "0.5488424", "0.5479663", "0.547885", "0.54749924", "0.53934646", "0.5374359", "0.5365443", "0.5345734", "0.5332543", "0.5323156", "0.530436", "0.5293353", "0.52863777", "0.52744985", "0.52708143", "0.526835", "0.52598476", "0.5257839", "0.5255614" ]
0.7070175
1
Checks if the given block has only tags without text.
def has_only_tags?(block) block.gsub(/<[^>]*>/im, '').strip.length == 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def no_paragraph_tag?(text)\n text !~ /^\\<p/\n end", "def no_paragraph_tag?(text)\n text !~ /^\\<p/\n end", "def element_is_text?\n !self[:is_tag]\n end", "def should_spit_text?\n @tags_chain.size > 0 && \n #(not @text.empty?) &&\n [\"body\", \"p\", \"br\", \"b\", HTMLConvertor.ping_tag].include?(@tags_chain.last[:name])\n end", "def blank?(only_visible_tags = T.unsafe(nil)); end", "def delete_junk_breaks!(node)\n\t\t\tnode.children.reject! do |child|\n\t\t\t\tif child.is_a?(TagNode) and !node.is_a?(RootNode)\n\t\t\t\t\tif !child.children.empty?\n\t\t\t\t\t\tdelete_junk_breaks!(child)\n\t\t\t\t\t\tfalse\n\t\t\t\t\telsif child.tag_name == @schema.paragraph_tag_name\n\t\t\t\t\t\t# It's an empty paragraph tag\n\t\t\t\t\t\ttrue\n\t\t\t\t\telsif @schema.block_level?(node.tag_name) and child.tag_name == @schema.line_break_tag_name and node.children.last == child\n\t\t\t\t\t\t# It's a line break a the end of the block-level element\n\t\t\t\t\t\ttrue\n\t\t\t\t\telse\n\t\t\t\t\t\tfalse\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tfalse\n\t\t\t\tend\n\t\t\tend\n\t\t\tnode\n\t\tend", "def drop_text?(child)\n text = fetch_tag(:text)\n !child.allowed_child?(text)\n end", "def empty?(name, tag)\n get_text_content(name, tag, @klass) == \"\"\n end", "def clean_block(block)\n # Return empty block if it is a list of links\n return \"\" if is_link_list?(block)\n\n # Return empty block if it is a very link heavy block\n count = 0\n no_links = block.gsub(/<a\\s[^>]*>.*?<\\/a\\s*>/im){count+=1;''}.gsub(/<form\\s[^>]*>.*?<\\/form\\s*>/im, '')\n return \"\" if no_links.length < 20 * count\n\n strip_tags(no_links)\n end", "def body_has_meaningful_content?(body_elt)\n body_elt && body_elt.to_s != \"<body><p></p></body>\"\n end", "def delete_tag_if(&block); end", "def each_tag_not_in_layout(marc_item)\n layout_tags\n marc_item.marc.each_data_tags_present do |tag|\n yield tag if !layout_tags.include? tag\n end\n end", "def drop_text?(child); end", "def block?\n block_tag? || block_body? || document?\n end", "def block_is_template?(_)\n false\n end", "def delete_invalid_empty_tags!(node)\n\t\t\tnode.children.reject! do |child|\n\t\t\t\tif child.is_a?(TagNode)\n\t\t\t\t\tif child.children.empty? and [email protected]_may_be_empty?(child.tag_name)\n\t\t\t\t\t\ttrue\n\t\t\t\t\telse\n\t\t\t\t\t\tdelete_invalid_empty_tags!(child)\n\t\t\t\t\t\tfalse\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tnode\n\t\tend", "def does_not_contain(&block)\n [:does_not_contain, block]\n end", "def does_not_contain(&block)\n [:does_not_contain, block]\n end", "def remove_emptytext_below_blocknodes(nodes)\n nodes.each do |node|\n node.children.each {|c| c.unlink if c.text? and c.inner_text =~ /^\\s*$/ }\n end\nend", "def block_is_template?(block) \n block && (block_is_erb?(block) || (self.respond_to?(:block_is_haml?) && block_is_haml?(block)))\n end", "def block_is_template?(block) \n block && (erb_block?(block) || \n (self.respond_to?(:block_is_haml?) && block_is_haml?(block)))\n end", "def unwanted_tags?\n unwanted_tags = info.tags.keys - required_tags - [:encoder]\n return true if unwanted_tags.empty? || unwanted_tags == [:tyer]\n\n raise Aur::Exception::LintUnwantedTags, unwanted_tags.join(', ')\n end", "def block_is_template?(block)\n block && (block_is_erb?(block) || (self.respond_to?(:block_is_haml?) && block_is_haml?(block)))\n end", "def block_body?\n @value.is_a?(Liquid::BlockBody)\n end", "def empty?\n tag.empty?\n end", "def allowed_child?(tag); end", "def non_html_tags\n if context[:non_html_tags]\n DEFAULT_NON_HTML_TAGS | context[:non_html_tags]\n else\n DEFAULT_NON_HTML_TAGS\n end\n end", "def tags_empty?\n current_or_guest_user.owned_tags.empty?\n end", "def is_empty?(node)\n node.name != 'img' && node.name != 'br' &&\n (node.text? && node.text.strip.empty? || !node.text? && node.children.empty?)\n end", "def accept_block_quote block_quote\n tt_sections block_quote.text\n end" ]
[ "0.6701398", "0.6701398", "0.66280824", "0.63980025", "0.62248796", "0.6039487", "0.5998476", "0.58188146", "0.5800965", "0.5753922", "0.5720263", "0.57176304", "0.5709449", "0.5692271", "0.56789213", "0.565085", "0.5638347", "0.5638347", "0.56019056", "0.55812377", "0.55768764", "0.55555135", "0.5554158", "0.55251056", "0.5505462", "0.5487054", "0.54711896", "0.5442478", "0.5437566", "0.54366076" ]
0.86452794
0
Eliminates link heavy blocks and blocks that are lists of links and then returns block stripped of tags
def clean_block(block) # Return empty block if it is a list of links return "" if is_link_list?(block) # Return empty block if it is a very link heavy block count = 0 no_links = block.gsub(/<a\s[^>]*>.*?<\/a\s*>/im){count+=1;''}.gsub(/<form\s[^>]*>.*?<\/form\s*>/im, '') return "" if no_links.length < 20 * count strip_tags(no_links) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strip_links(html); end", "def strip_links(html); end", "def strip_links(html); end", "def remove_links(block)\n inline_block = block.gsub(LINK_PATTERN) do |s|\n url = URL_PATTERN.match(s)[2]\n extension = File.extname(url)\n /\\.js|\\.css/.match(extension) && !URI.parse(url).absolute? ? '' : s\n end\n inline_block\n end", "def unwrap_links(elements); end", "def strip_tag(*tags, &block)\n tags.each do |tag|\n gsub! Regexp.new(\"<\\s*#{tag}(?:\\s+[^>]*)*>(.*?)<\\s*\\/#{tag}\\s*>\", Regexp::IGNORECASE + Regexp:: MULTILINE) do\n if block\n \"#{$1}#{yield}\"\n else\n $1\n end\n end\n # check we don't have any malformed or nested instances left\n gsub! Regexp.new(\"<\\s*#{tag}(?:\\s+[^>]*)*>\", Regexp::IGNORECASE + Regexp:: MULTILINE), ''\n gsub! Regexp.new(\"<\\s*\\/#{tag}\\s*>\", Regexp::IGNORECASE + Regexp:: MULTILINE), ''\n end\n end", "def unlink!\n parse \n @tags.each do |tag|\n @doc.xpath(\"//a[ends_with(@href,'#{tag}')]\", EndsWithFilter.new).each do |element|\n element.swap(element.children)\n end\n end\n output = @doc.xpath(\"/#{@wrap_tag}/body/p\").inner_html\n output = @doc.xpath(\"/#{@wrap_tag}/body\").inner_html if output == \"\"\n output\n end", "def deblocked_content\n deblocked_content = []\n offset = 0\n block_number = 1\n self.status = :readable\n @good_blocks = 0\n link_number = 1\n llink_number = 1\n loop do \n # Process a link\n break if offset >= words.size\n bcw = words.at(offset)\n break if bcw.to_i == 0\n # debug \"link: offset: #{offset}(0#{'%o' % offset}): #{'%013o' % words.at(offset)}\"\n # debug \"preamble: offset: #{offset+1}(0#{'%o' % (offset+1)}): #{'%013o' % words.at(offset+1)}\"\n link_sequence_number = bcw.half_word[0].to_i\n raise BadBlockError, \"Link out of sequence at #{offset}(0#{'%o'%offset}): Found #{link_sequence_number}, expected #{link_number}. BCW #{'%013o' % bcw.to_i}\" \\\n unless link_sequence_number == link_number\n next_link = bcw.half_word[1].to_i + offset + 1\n # debug \"next link: #{'%013o' % next_link}\"\n preamble_length = words.at(offset+1).half_word[1].to_i\n offset += preamble_length\n loop do\n # debug \"llink: offset: #{offset}(0#{'%o' % offset}): #{'%013o' % words.at(offset)}\"\n break if offset >= words.size || offset >= next_link\n break if words.at(offset) == 0\n block_size = words.at(offset).byte(3)\n unless words.at(offset).half_word[0] == block_number\n # stop \"Bad block_number at #{'%013o' % (offset+content_offset)}: #{'%013o' % words.at(offset)}, block_number: #{block_number}\"\n if strict\n raise \"Llink out of sequence in #{location} at #{'%#o' % (offset+content_offset)}: expected #{'%07o' % block_number}; got #{file_content[offset].half_word[0]}\"\n else\n error \"Truncated before block #{block_number} at #{'%#o' % (offset+content_offset)}\"\n if block_number == 1\n self.status = :unreadable\n else\n self.status = :truncated\n end\n break\n end\n end\n deblocked_content += words[offset+1..(offset+block_size)].to_a\n offset += BLOCK_SIZE\n block_number += 1\n @good_blocks += 1\n end\n offset = next_link\n link_number += 1\n end\n @llink_count = link_number\n Bun::Words.new(deblocked_content)\n end", "def remove_emptytext_below_blocknodes(nodes)\n nodes.each do |node|\n node.children.each {|c| c.unlink if c.text? and c.inner_text =~ /^\\s*$/ }\n end\nend", "def remove_typepad_links\n results = @content.scan(/<a href=.*?<\\/a>/)\n\n results.each do |result|\n # if result contains an image with an image-full class\n if result =~ /image-full/\n temp = result.sub(/<a href=.*?>/, \"\").sub(/<\\/a>/, \"\")\n @content.sub!(result, temp)\n end\n end\n end", "def removePageRelatedTags(contents)\n regex = '(?:<br\\/>\\n)?(?:<hr\\/>\\n)?<a name=\\d+><\\/a>(<img src=\"list-\\d+_\\d+.jpg\"\\/?><br\\/>\\n)*\\d*(?:\\s<br\\/>\\n\\s<br\\/>)?\\n*'\n scan = contents.scan(/#{regex}/m)\n\n if scan.length == 92\n contents = contents.gsub(/#{regex}/m, '')\n else\n fail 'Did not find 92 page tags'\n end\n checkNoImgTags(contents)\n\n contents\n end", "def hide_html_blocks( str, rs )\n\t\t\[email protected] \"Hiding HTML blocks in %p\" % str\n\n\t\t\t# Tokenizer proc to pass to gsub\n\t\t\ttokenize = lambda {|match|\n\t\t\t\tkey = Digest::MD5::hexdigest( match )\n\t\t\t\trs.html_blocks[ key ] = match\n\t\t\t\[email protected] \"Replacing %p with %p\" % [ match, key ]\n\t\t\t\t\"\\n\\n#{key}\\n\\n\"\n\t\t\t}\n\n\t\t\trval = str.dup\n\n\t\t\[email protected] \"Finding blocks with the strict regex...\"\n\t\t\trval.gsub!( StrictBlockRegexp, &tokenize )\n\n\t\t\[email protected] \"Finding blocks with the loose regex...\"\n\t\t\trval.gsub!( LooseBlockRegexp, &tokenize )\n\n\t\t\[email protected] \"Finding hrules...\"\n\t\t\trval.gsub!( HruleBlockRegexp ) {|match| $1 + tokenize[$2] }\n\n\t\t\treturn rval\n\t\tend", "def strip_tags(html); end", "def strip_tags(html); end", "def strip_tags(html); end", "def strip_links\n gsub(%r{</?a.*?>}, \"\")\n end", "def delete_tag_if(&block); end", "def parse_block_html; end", "def convert_links\n\n # fetch leaf content\n c = self.content\n\n # regexps\n # url = /( |^)http:\\/\\/([^\\s]*\\.[^\\s]*)( |$)/\n tag_regex = /( |^)#(\\w+)( |$)/\n user_regex = /( |^)@(\\w+)( |$)/\n \n #TODO: make sure no one is typing javascript into the field **IMPORTANT**\n\n #replace #tags with links to that tag search\n while c =~ tag_regex\n c.gsub! \"##{$2}\", \"<a href='/leaves?tagged=#{$2}'>##{$2}</a>\"\n self.has_tags = true\n end\n\n #replace @usernames with links to that user, if user exists\n while c =~ user_regex\n user = $2\n if User.find(user)\n c.sub! \"@#{$2}\", \"<a href='/users/#{$2}'>@#{$2}</a>\"\n end\n end\n\n #replace urls with links\n #while c =~ url\n #name = $2\n #c.sub! /( |^)http:\\/\\/#{name}( |$)/, \" <a href='http://#{name}' >#{name}</a> \"\n #end\n\n self.content = c\n\n end", "def filterProviderOffer(links)\n useless_links = links.pop #take the offers\n links.delete(useless_links)\n links\n end", "def lstrip_html\n return if self.blank?\n\n m = self.match(/\\A(\\s*?[^<]|(.*?)>\\s*[^<])/) #Find first printing character\n return self unless m\n \n ldr = m[0]\n ldr_last = ldr.slice(ldr.size-1, ldr.size)\n ldr = ldr.slice(0,ldr.size-1) # portion up to the first printing character\n bdy = ldr_last + m.post_match # portion following the first printing character\n \n cln_ldr = ldr.gsub(/<p/mi, \"<span\")\n cln_ldr = cln_ldr.gsub(/<\\/p/mi, \"</span\")\n cln_ldr = cln_ldr.gsub(/<br(.*?)>/mi, \"\")\n \n m = bdy.match(/(\\A.*?)<p/mi)\n if !m\n bdy = bdy.sub(/<\\/p/mi, \"</span\") # change first closing </p> from an open <p> remaining from ldr\n else\n l = m.post_match\n f_cln = m[0].gsub(/<\\/p/mi, \"</span\") # change any closing </p> from and open <p> remaining from ldr\n bdy = f_cln + l \n end\n return cln_ldr + bdy \n end", "def prune_links\n links = []\n result = self.perform\n ft_links = result.ft_links\n ft_links.each do |ft_link|\n http = Curl.get(ft_link)\n doc = Nokogiri::HTML(http.body_str)\n link = doc.xpath('//*[@id=\"copy_paste_links\"]').children.first.to_s.chomp\n links.push link if link.empty? == false\n end\n links\n end", "def sanctify_liquid_tags(head); end", "def process_links!(source)\r\n links.each{ |l| source.gsub!(\"[[#{l}]]\", link(l)) }\r\n end", "def purify_html\n doc= Nokogiri::XML::DocumentFragment.parse(self.to_s)\n doc.search(\".//strong\").each do |e|\n e.swap \"<b>#{e.inner_html}</b>\"\n end\n doc.search(\".//h4\").each do |e|\n e.swap \"<b>#{e.inner_html}</b>\"\n end\n doc.search(\".//h3\").each do |e|\n e.swap \"<b>#{e.inner_html}</b>\"\n end\n doc.search(\".//h2\").each do |e|\n e.swap \"<b>#{e.inner_html}</b>\"\n end\n doc.search(\".//h1\").each do |e|\n e.swap \"<b>#{e.inner_html}</b>\"\n end\n\n doc.search(\".//em\").each do |e|\n e.swap \"<i>#{e.inner_html}</i>\"\n end\n\n doc.search(\".//ul\").each do |e|\n e.swap \"#{e.inner_html}\"\n end\n doc.search(\".//ol\").each do |e|\n e.swap \"#{e.inner_html}\"\n end\n doc.search(\".//li\").each do |e|\n e.swap \"<p>#{e.inner_html}</p>\"\n end\n doc.search(\".//span\").each do |e|\n e.swap \"#{e.inner_html}\"\n end\n\n doc.to_xml(:encoding => \"UTF-8\").gsub(/\\n/,\" \").gsub(/\\s+/,\" \")\n end", "def raw\n @raw ||= cleanup(parsed.search('//a/@href')).compact.uniq\n end", "def normalize(node)\n return normalize_str(node) if node.is_a?(String)\n\n html = node.dup\n\n remove_trackers! html\n remove_blacklisted_images! html\n remove_style_attrs! html\n wrap_stray_text! html\n move_stray_images! html\n\n blocks(html).each do |blk|\n if block?(blk)\n add_class blk, 'short' if blk.content.size < 50\n add_class blk, 'image' if image_paragraph?(blk)\n handle_duplicate_brs! blk\n fix_pseudo_headings! blk\n end\n end\n\n blocks(html).each do |blk|\n blk.remove if blank?(blk) # Not recursive\n end\n\n html\n end", "def strip_dangerous_html_tags(allowed_tags = 'a|span|strong|b|img|i|s|p|br|h1|h2|h3|h4|h5|h6|blockquote|footer', attributes = {'img' => ['src', 'alt'], 'a' => ['href', 'title', 'target']})\n if allowed_tags.present?\n Sanitize.fragment(self, {elements: allowed_tags.split('|'), attributes: attributes})\n else\n self.gsub('<', \"&lt;\").gsub('>', \"&gt;\")\n end\n end", "def strip_tags(html)\n # First we need to get rid of any embedded code.\n html = strip_embedded(html)\n\n # Remove comments\n html = html.gsub(/<!--.*?--\\s*>/m, \"\\xEF\\xBF\\xBC\")\n\n # SGML Declarations\n html = html.gsub(/<!.*?>/m, \"\\xEF\\xBF\\xBC\")\n\n # Remove script and css blocks\n html = html.gsub(/<script.*?>.*?<\\/script>/m, \"\\xEF\\xBF\\xBC\")\n html = html.gsub(/<style.*?>.*?<\\/style>/m, \"\\xEF\\xBF\\xBC\")\n\n # Strip html tags\n html = html.gsub(/<\\/? # opening tag with optional slash\n (\n [^<>\"'] | # match anything unquoted\n \".*?\" | # match double quotes…\n '.*?' # and single ones\n )* # any combination of the three\n > # close tag\n /xm, \"\\xEF\\xBF\\xBC\") # placeholder\n\n # Handle placeholders\n html = html.gsub(/^[ \\t]*\\xEF\\xBF\\xBC[ \\t]*(\\n|\\r|\\r\\n)/xm, '') # Remove lines with only tags\n html = html.gsub(/\\xEF\\xBF\\xBC/xm, '') # Remove other placeholders\n return html\nend", "def sanctify_liquid_tags(head)\n modified = false\n tag_names = head.scan(LIQUID_TAG_REGEX)\n tag_names.flatten!\n tag_names.reverse_each do |tag_name|\n next unless liquid_block?(tag_name)\n next if endtag_regex_stash(tag_name).match?(head)\n\n modified = true\n head << \"\\n{% end#{tag_name} %}\"\n end\n\n print_build_warning if modified\n head\n end" ]
[ "0.6566711", "0.6566711", "0.6566711", "0.6559199", "0.6457174", "0.63547766", "0.62854224", "0.6244661", "0.6109296", "0.6030028", "0.6029686", "0.59956944", "0.59488803", "0.59488803", "0.59488803", "0.5935917", "0.58676153", "0.5801457", "0.57909024", "0.5735019", "0.5731646", "0.57219553", "0.5698683", "0.56836814", "0.56191003", "0.56017244", "0.5511884", "0.5504162", "0.5497065", "0.5496051" ]
0.78719556
0
Determines whether a block is link list or not
def is_link_list?(st) if st =~ /<(?:ul|dl|ol)(.+?)<\/(?:ul|dl|ol)>/im listpart = $1 outside = st.gsub(/<(?:ul|dl)(.+?)<\/(?:ul|dl)>/imn, '').gsub(/<.+?>/mn, '').gsub(/\s+/, ' ') list = listpart.split(/<li[^>]*>/) list.shift rate = evaluate_list(list) outside.length <= st.length / (45 / rate) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def local_link?\n [1,2].include?(link_type)\n end", "def is_linktype?(); @type == GRT_LINKTYPE; end", "def link?\n !link.nil? && !link.empty?\n end", "def link?\n !link.nil? && !link.empty?\n end", "def linked?\n return BlizzABS::Alignments::LINKED_GROUPS.include?(@group)\n end", "def is_linkkeys?(); @type == GRT_LINKKEYS; end", "def is_block?\n get_metadata(:for_block)\n end", "def require_links?\n @require_links\n end", "def is_cms_block?\n %w(page field collection).member?(self.class.to_s.demodulize.underscore.split(/_/).first)\n end", "def list?\n children[0] && children[0].is_a?(List)\n end", "def linked?(cell)\n\t\[email protected]? cell\n\tend", "def symlink?\n type == :symlink\n end", "def is_link?\n self.type == 'Document::VirtualCollege' && !is_pdf?\n end", "def is_linked?\n\t\t\[email protected]?\n\t\tend", "def linked_in_hierarchy?(source, target)\n\t linked?(source, target) || (parent.linked?(source, target) if parent)\n\tend", "def inside_header?\n @anchor.tag_name == 'link'\n end", "def on_linode?\n linode != nil\n end", "def on_linode?\n linode != nil\n end", "def list?\n element_names == %w[list] and text_children.all?(&:blank?)\n end", "def blocks?\n [email protected]?\n end", "def list?\n false\n end", "def is_a_list?(file)\n !!(file =~ /list$/)\n end", "def visit_link?(link)\n @link_rules.accept?(link)\n end", "def symlink?(entry); end", "def linode?(node)\n node.key?('linode')\n end", "def link_is_fulltext?\n @link_is_fulltext\n end", "def links?\n !cases.empty? || !field_contacts.empty?\n end", "def ltype?\n return true\n end", "def symlink?\n case type\n when T_SYMLINK then true\n when T_UNKNOWN then nil\n else false\n end\n end", "def is_link?\n !child_question.nil?\n end" ]
[ "0.6915274", "0.66692495", "0.6214611", "0.6214611", "0.6208301", "0.6073194", "0.60092074", "0.59285074", "0.5898732", "0.58811426", "0.5844004", "0.58385414", "0.583644", "0.58260036", "0.581676", "0.58014876", "0.5760968", "0.5760968", "0.5759168", "0.5751555", "0.57247365", "0.5723962", "0.5705847", "0.56807524", "0.56600577", "0.56566054", "0.5633716", "0.56282634", "0.5604102", "0.55959004" ]
0.6971343
0
We might have to remove certain characters, but for now we just CGI.escape it and remove any periods
def clean_name(name) CGI.escape(name).gsub('.', '') end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sanitize(name)\n #name.gsub(\".\", \"_\").gsub(/<.+>/, \"\")\n name.gsub(\".\", \"_\").gsub(\"$\", \"_\")\nend", "def cgi_escape(input); end", "def safe(str)\n CGI.unescape(str)\n end", "def sanitize_as_filename\n self.gsub(/^.*(\\\\|\\/)/, '').transliterate.downcase.gsub(/[^a-z0-9\\. ]/, ' ').strip.gsub(/[ ]+/, '-')\n end", "def unescaped_html_without_soft_hyphens\n str = CGI.unescapeHTML IO.read(path)\n str.gsub! /&shy;/, ''\n str\n end", "def sanitize(text)\n text.squeeze\n text.capitalize!\n text.gsub!('&', '&amp;')\n text.gsub!('<', '&lt;')\n text.gsub!('>', '&gt;')\n return text\nend", "def escape_quotes(unfiltered)\n unfiltered.to_s.gsub(/'/, \"''\")\n end", "def escape_url(url)\n url.blank? ? nil : url.gsub(/\\./, '-dot-').gsub(/\\//, '-slash-')\n end", "def sanitize(name)\n name.gsub(\".\", \"_\")\nend", "def standardize\n # clean.delete(' ').delete('-').delete('.')\n clean.gsub(/[-\\s.#]/, '')\n end", "def filter_text(text)\n text = text.to_s\n text.gsub('&', '&amp;')\n text.gsub('\\'', '&#039;')\n text.gsub('\"', '&quot;')\n text.gsub('<', '&lt;')\n text.gsub('>', '&gt;')\n text\n end", "def html_escape(clean_me)\n clean_me.to_s.gsub(/[&\"<>]/) do |special|\n { '&' => '&amp;',\n '>' => '&gt;',\n '<' => '&lt;',\n '\"' => '&quot;' }[special]\n end\n end", "def sanitize_refpt1 refpt1\n refpt1.strip.gsub(\".\", \"\")\n end", "def esc(str)\n str = str.to_s.gsub(\"&\", \"&amp;\")\n str = str.gsub(\"\\\"\", \"&apos;\")\n str = str.gsub(\"\\\"\", \"&quot;\")\n str = str.gsub(\"<\", \"&lt;\")\n str.gsub(\">\", \"&gt;\")\nend", "def unescape_value(value)\n CGI.unescape(value)\n end", "def remove_special_characters(string)\n string.gsub(/[~\"'&#%]/, '-')\n end", "def sanitize(content)\n content.to_s.gsub(/[^\\w]/, '')\n end", "def sanitize_path(path)\n path.gsub(/\\.\\.(?=$|\\/)/, '') unless path.nil?\n end", "def h(str)\n CGI.unescape_html(str.to_s)\n .gsub('&', '&amp;')\n .gsub('\"', '&quot;')\n .gsub('<', '&lt;')\n .gsub('>', '&gt;')\n end", "def cleanup_pathname(path)\n return CGI.unescape(path).gsub(@music_root, '').gsub(%r{file:/+}, '').gsub(%r{^/+}, '')\n end", "def clean_query_string(q)\n ERB::Util.url_encode(q.gsub(/-|\\(|\\)|:/, \"\"))\n end", "def sanitize_filename(value)\n # get only the filename, not the whole path\n just_filename = value.gsub(/^.*(\\\\|\\/)/, '')\n # Finally, replace all non alphanumeric, underscore or periods with underscore\n just_filename.gsub(/[^\\w\\.\\-]/,'_') \n end", "def sanitized\n @filename.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: \"�\").strip.tr(\"\\u{202E}%$|:;/\\t\\r\\n\\\\\", \"-\")\n end", "def strip_non_word_characters!\n @raw.gsub!(/[^\\w\\ \\-.,]/, ' ')\n end", "def escape_value(value)\n CGI.escape(value.to_s).gsub('%20', '+')\n end", "def sanitize_tag(in_tag)\n in_tag.gsub(/[^\\w%=-\\\\+]+/,\"\")\n end", "def convert_string(text)\n CGI.escapeHTML text\n end", "def u(str)\n CGI.escape(str)\n end", "def safe_unescape!\n string = CGI.unescape(gsub('+', '%2B'))\n return self if self == string\n replace string\n ensure_safe!\n end", "def safe_encode value\n value = URI.encode_www_form_component(value).gsub(/\\+/,'%20').gsub(/\\*/,'%2A').gsub(/%7E/,'~')\n end" ]
[ "0.7022107", "0.666911", "0.6618527", "0.65766394", "0.64787436", "0.642227", "0.6407414", "0.63973", "0.6377207", "0.63030505", "0.629229", "0.6253363", "0.62434715", "0.6239274", "0.6201699", "0.61980134", "0.6189996", "0.615272", "0.61382097", "0.613641", "0.611482", "0.6099387", "0.6085387", "0.6081109", "0.60760653", "0.60755503", "0.6046031", "0.6036104", "0.6029338", "0.6006269" ]
0.74023795
0
createsa minimal openurl to make a new request to umlaut
def create_openurl(request, wh) metadata = request.referent.metadata co = OpenURL::ContextObject.new cor = co.referent cor.set_format(wh['record_type']) cor.add_identifier("info:oclcnum/#{wh['oclcnum']}") cor.set_metadata('aulast', metadata['aulast'] ) if metadata['aulast'] cor.set_metadata('aufirst', metadata['aufirst']) if metadata['aufirst'] cor.set_metadata('aucorp', metadata['aucorp']) if metadata['aucorp'] cor.set_metadata('title', wh['title']) link = @openurl_base + '?' + co.kev return link end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def openurl(url)\n runcmd 'openurl', url\n end", "def open_url\n opts = [config.oui_full_url]\n opts << { 'User-Agent' => config.user_agent } if config.user_agent\n open(*opts).read\n rescue OpenURI::HTTPError\n ''\n end", "def autoname_url(url)\n request('POST', @uri.request_uri, url)\n end", "def make_url(string)\n puts \"not implemented\"\nend", "def open url\r\n command 'open', url_arg(url)\r\n end", "def open url\r\n command 'open', url_arg(url)\r\n end", "def create url\n function = ''\n \n post_data = {}\n post_data[:url] = url\n\n request(@resource, function, nil, 'post', post_data)\n end", "def URI(url); end", "def new_http(uri); end", "def\tcreate_url(long_url)\n\t\t begin\n\t\t\t options = { :query => { :url => long_url, :api_key => @api_key } }\n result = HTTParty.post(@firefly_url + '/api/add', options)\n\n\t\t\t\tif result =~ /Permission denied/i\n raise \"Permission denied. Is your API Key set correctly?\" if result.status = 401\n\t\t\t\telse\n\t\t\t\t return result\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def ciao\n redirect_to '/' && return if params[:url].blank?\n @ua = {:action => UserAction.id_for('external_url'), :data => {:source => params[:source]}}\n url = Base64.decode64(params[:url])\n url = \"http://#{url}\" unless url.match(/https?:\\/\\//) != nil\n redirect_to url\n end", "def tinyurl(url)\n url = open(\"http://tinyurl.com/api-create.php?url=#{URI.escape(url)}\").read\n url == \"Error\" ? nil : url\n rescue OpenURI::HTTPError\n nil\n end", "def to(url); end", "def create_uri\n end", "def request_url(command, params)\n url = \"http://www.openaustralia.org/api/#{command}?key=#{@key}&output=xml\"\n params.each do |k,v|\n key = CGI::escape(k.to_s)\n value = CGI::escape(v.to_s)\n url += \"&#{key}=#{value}\"\n end\n url\n end", "def make_request(url)\n res = Typhoeus::Request.new(\n url,\n method: :get,\n headers: {\n \"Accept-Charset\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Accept-Language\" => \"en-US,en;q=0.9,pt;q=0.8\",\n \"X-Riot-Token\" => @api_key.to_s,\n \"User-Agent\": \"https://github.com/drish/rioter\"\n }\n ).run\n parse!(res)\n end", "def open_url(code)\n url = URL+code\n puts url\n open(url).read\n end", "def get(url); end", "def create_uri(url, parms)\n uri = URI(url)\n uri.query = URI.encode_www_form(parms)\n uri\nend", "def link() url; end", "def link() url; end", "def create_url\n\t\tif self.url.blank?\n\t\t\tself.url = self.title.downcase.gsub(/[^a-zA-Z0-9]+/, \"-\").chomp(\"-\")\n\t\tend\t\n\tend", "def make_url\n # This works for most of the twitter calls\n \"http://ws.audioscrobbler.com/2.0/?method=#{resource_path}&artist=#{identifier}&limit=100&page=#{page}&api_key=#{api_key}&format=json\"\n end" ]
[ "0.6623941", "0.65541255", "0.6551269", "0.64429736", "0.6367715", "0.6367715", "0.63302237", "0.6289301", "0.6288969", "0.62307286", "0.6196741", "0.6196741", "0.6196741", "0.6196741", "0.6196741", "0.6196741", "0.6196741", "0.617224", "0.6110351", "0.6063315", "0.60149294", "0.6001161", "0.596213", "0.5950352", "0.5916179", "0.58902544", "0.5886882", "0.5886882", "0.5853125", "0.58411855" ]
0.6584969
1
We just link to worldcat using the oclc number provided FIXME this might need special partial if we incorporate a cover image
def create_worldcat_widely_held(request, xml) # try to prevent circular links top_holding_info = get_widely_held_info(xml) return nil if circular_link?(request, top_holding_info) # http://www.worldcat.org/links/ most = top_holding_info['most'] title = top_holding_info['title'] oclcnum = top_holding_info['oclcnum'] link = 'http://www.worldcat.org/oclc/' << oclcnum cover_image_link = extract_cover_image_link(request, most) notes = "this author's most widely held work in WorldCat" if cover_image_link display_text = '<img src="' << cover_image_link << '" style="width:75px;"/>' notes = title << ' is ' << notes else display_text = title end request.add_service_response( :service=>self, :url=>link, :display_text=> display_text, :notes => notes, :service_type_value => :highlighted_link) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 category\n path = @path_remote.split('/')\n return path[3] # Could require changes depending on the structure of the maps repo\n end", "def catalog_generator(bib)\n QuickSearch::Engine::WORLD_CAT_DISCOVERY_API_ARTICLE_CONFIG['url_link'] +\n bib.oclc_number.to_s\n end", "def bookcover_oclc(document)\n if document['oclc_id_display'].nil?\n oclc_id = ''\n else\n oclc_id = document['oclc_id_display'][0]\n end\n return oclc_id\n end", "def url(item)\n 'http://mit.worldcat.org/oclc/' + \\\n item.xpath('oclcterms:recordIdentifier[not(@xsi:type)]').text.strip\n end", "def cover_url\n case self.category\n when \"Nutrition\"\n \"nutrition.jpeg\" \n when \"Activity\"\n \"activity.jpeg\"\n when \"Exercise\"\n \"exercise.jpeg\"\n when \"Rehabilitation\"\n \"rehabilitation.jpeg\"\n when \"Medication\"\n \"medications.jpeg\"\n else\n \"activity.jpeg\"\n end\n end", "def cloudinary_imgs_cara(key,instance)\n cl_image_tag(key, :quality=>\"auto\", :fetch_format=>:auto, :crop=>\"fit\", :class=>\"d-block mx-auto img-fluid rounded\", :alt=>\"#{instance.name}\")\n end", "def detail_link_to_searchworks(catkey)\n return if catkey.blank?\n\n tag.div(class: 'row') do\n tag.div(class: 'col-11 offset-1 col-md-10 offset-md-2') do\n link_to Settings.sw.url + catkey, rel: 'noopener', target: '_blank' do\n sul_icon(:'sharp-open_in_new-24px') + ' View in SearchWorks' # rubocop:disable Style/StringConcatenation\n end\n end\n end\n end", "def cover\n 'http://lorempixel.com/400/300/' + %W(abstract nightlife transport).sample + '?a=' + SecureRandom.uuid\n end", "def capsule_map_path(count, world)\n \"#{world.urls[:images]}/map/npczahl#{count}.gif\"\n end", "def create_openurl(request, wh)\n metadata = request.referent.metadata\n \n co = OpenURL::ContextObject.new\n cor = co.referent\n cor.set_format(wh['record_type'])\n cor.add_identifier(\"info:oclcnum/#{wh['oclcnum']}\")\n cor.set_metadata('aulast', metadata['aulast'] ) if metadata['aulast']\n cor.set_metadata('aufirst', metadata['aufirst']) if metadata['aufirst']\n cor.set_metadata('aucorp', metadata['aucorp']) if metadata['aucorp']\n cor.set_metadata('title', wh['title'])\n link = @openurl_base + '?' + co.kev\n return link\n end", "def opinion_url\n cl_hash[\"sub_opinions\"][0]\n end", "def cover_url\n [\"condition_headache.jpeg\",\"condition_chair.jpeg\",\"condition_time.jpeg\",\"condition_med.jpeg\"][rand(4)] \n end", "def cover\n \"http://lorempixel.com/100/150/\" +\n %w(abstract nightlife transport).sample +\n \"?a=\" + SecureRandom.uuid\n end", "def render_link_to_clio(args = {})\n scalar_value = !(args[:value].is_a? Array)\n clio_links = Array(args[:value]).map do |clio_id|\n link_label = \"#{args[:config].link_label || clio_id} <span class=\\\"fa fa-external-link\\\"></span>\".html_safe\n link_to(link_label, \"http://clio.columbia.edu/catalog/#{clio_id}\", target: '_blank')\n end\n scalar_value ? clio_links.first : clio_links\n end", "def url_for_co_hbrand_image(company)\n \"#{I18n.t('shf_medlemssystem_url')}/hundforetag/#{company.id}/company_h_brand\"\n end", "def view_lot_link\n \"#{app_config.urls['aurora_url_prefix']}/#{self.lot_num}\"\n end", "def link_to_ecoologic\n image = image_tag(Setting.ecoologic_link_image_url,\n {:alt => Setting.ecoologic_alt, :height => '64px'})\n url = Setting.ecoologic_link_url\n link_opts = {:title => Setting.ecoologic_link_title, :target => '_blank'}\n # :id => :ecoologic_link\n \n link_to image, url, link_opts\n end", "def museum_clue\n\t \tindex = rand(1..@museum_clues.length)\n\t \t@museum_clues[index]\n\t end", "def activate_c1; activate_cat(@category_window); end", "def cobrand_id\n @cobrand_id || YodleeApi.cobrand_id\n end", "def getWorldKitURL(location)\n url = \"http://worldkit.org/geocoder/rest/?city=\"\n city = location[/^([\\w ]+), ([\\w ]+)+$/, 1]\n state = location[/^([\\w ]+), ([\\w ]+)+$/, 2]\n city = city.gsub(' ', '+')\n state = STATE_ABBR[state]\n if state != nil\n url << city << ',' << state << ',' << 'US'\n return url\n else\n return nil\n end\n end", "def osk_c_lesson_src(screen, location)\n \n lesson_id = screen.get_named_widget(\"title\").text[/\\d+/]\n\n # Use COSMOS editor for editing/updating current source files \n if (location == \"SRC_EDIT_CURRENT\")\n \n src_file = screen.get_named_widget(\"current_src_file\").text\n src_pathfile = File.join(CfSat::TUTOR_FSW_SRC_DIR,src_file)\n Cosmos.open_in_text_editor(src_pathfile)\n \n else \n \n case location\n when \"SRC_VIEW_LESSON\"\n src_dir = File.join(CfSat::TUTOR_APP_DIR,'lesson',lesson_id.to_s,'manual')\n src_file = screen.get_named_widget(\"lesson_src_file\").text\n when \"SRC_VIEW_SOLUTION\"\n src_dir = File.join(CfSat::TUTOR_APP_DIR,'lesson',lesson_id.to_s,'solution')\n src_file = screen.get_named_widget(\"solution_src_file\").text\n else\n raise \"Error in screen definition file. Undefined cmd '#{cmd}' sent to osk_c_lesson_cmd()\"\n end\n\n src_pathfile = File.join(src_dir,src_file)\n Cosmos.run_process(\"ruby lib/OskTxtFileViewer -f '#{src_pathfile}'\")\n\n end # End \n \nend", "def image_url_imgly(link_url)\n image_url_redirect link_url, \"http://img.ly/show/full/\", \"\\r\\n\"\n end", "def set_cover_image(format)\n case format\n when \"Book\"\n return \"cornell/virtual-browse/book_cvr.png\"\n when \"Journal/Periodical\"\n return \"cornell/virtual-browse/journal_cvr.png\"\n when \"Manuscript/Archive\"\n return \"cornell/virtual-browse/manuscript_cvr.png\"\n when \"Map\"\n return \"cornell/virtual-browse/map_cvr.png\"\n when \"Musical Recording\"\n return \"cornell/virtual-browse/musical_recording_cvr.png\"\n when \"Musical Score\"\n return \"cornell/virtual-browse/musical_score_cvr.png\"\n when \"Non-musical Recording\"\n return \"cornell/virtual-browse/non_musical_cvr.png\"\n when \"Thesis\"\n return \"cornell/virtual-browse/thesis_cvr.png\"\n when \"Video\"\n return \"cornell/virtual-browse/video_cvr.png\"\n when \"Microform\"\n return \"cornell/virtual-browse/microform_cvr.png\"\n else\n return \"cornell/virtual-browse/generic_cvr.png\"\n end\n\n end", "def charcoal\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.charcoal(0.0, 1.0)\n img.write('public' + @photo.attachment_url)\n end", "def catalog_dcat()\n return uri(\"api/dcat.json\")\n end", "def set_cocktail\n @cocktail = Cocktail.find(params[:id])\n end", "def doc2dct_references(fgdc_url, doc)\n dct_references = {}\n\n ### 12 possible keys. \n ### Which ones are we able to provide?\n\n # Only Public content has been loaded into GeoServer.\n # Restricted content is only available via Direct Download.\n if @dc_rights == 'Public'\n # For Columbia, Raster data is NEVER loaded into GeoServer.\n layer_geom_type = doc2layer_geom_type(doc)\n if @provenance != 'Columbia' || layer_geom_type != 'Raster'\n # Web Mapping Service (WMS) \n dct_references['http://www.opengis.net/def/serviceType/ogc/wms'] =\n @geoserver_wms_url\n # Web Feature Service (WFS)\n dct_references['http://www.opengis.net/def/serviceType/ogc/wfs'] =\n @geoserver_wfs_url\n end\n end\n\n # International Image Interoperability Framework (IIIF) Image API\n # Direct download file\n if onlink = doc.at_xpath(\"//idinfo/citation/citeinfo/onlink\")\n if onlink.text.match /.columbia.edu/\n dct_references['http://schema.org/downloadUrl'] = onlink.text\n end\n end\n\n # This is unnecessary. GeoBlacklight will already display FGDC XML\n # in a prettily formatted HTML panel. And the HTML metadata isn't\n # downloadable - or anything else - in stock GeoBlacklight.\n # None of the OpenGeoBlacklight institutions bother with this.\n # # Full layer description\n # # Metadata in HTML\n # die \"No APP_CONFIG['display_urls']['html']\" unless APP_CONFIG['display_urls']['html']\n # dct_references['http://www.w3.org/1999/xhtml'] =\n # APP_CONFIG['display_urls']['html'] + \"/#{@key}.html\"\n\n # # Metadata in ISO 19139\n # dct_references['http://www.isotc211.org/schemas/2005/gmd/'] =\n # APP_CONFIG['display_urls']['iso19139'] + \"/#{@key}.xml\"\n # Metadata in FGDC\n dct_references['http://www.opengis.net/cat/csw/csdgm'] = fgdc_url\n # Metadata in MODS\n # ArcGIS FeatureLayer\n # ArcGIS TiledMapLayer\n # ArcGIS DynamicMapLayer\n # ArcGIS ImageMapLayer\n\n return dct_references.compact.to_json.to_s\n end", "def set_cocktail\n @cocktail = Cocktail.find(params[:cocktail_id])\n end" ]
[ "0.58421445", "0.57172924", "0.54939795", "0.54489636", "0.5408253", "0.5284518", "0.52164835", "0.5123847", "0.50671166", "0.50663817", "0.50655955", "0.5063098", "0.50439924", "0.5029098", "0.4994209", "0.49723473", "0.4956977", "0.4947813", "0.49284944", "0.49106896", "0.48817697", "0.4831853", "0.4822863", "0.48107657", "0.48104206", "0.4796979", "0.4793084", "0.47730216", "0.47540307", "0.47388938" ]
0.66617954
0
Create a new csv differ, this differ can then be used to create a split and a unified view. The raw csv strings are decoded and the csv header is extracted. If the table has more than 100 rows, a simplified version of the table will be rendered this will limit the performance hit of a very long table.
def initialize(generated, expected) @generated = CSV.parse((generated || '').lstrip, nil_value: '') @expected = CSV.parse((expected || '').lstrip, nil_value: '') @gen_headers, *@generated = @generated @gen_headers ||= [] @exp_headers, *@expected = @expected @exp_headers ||= [] @simplified_table = @generated.length > 100 || @expected.length > 100 @gen_header_indices, @exp_header_indices, @gen_headers, @exp_headers, @combined_headers = diff_header_indices(@gen_headers, @exp_headers) @diff = unless @simplified_table Diff::LCS.sdiff(@generated, @expected).map do |chunk| gen_result = chunk.old_element || [] exp_result = chunk.new_element || [] if chunk.action == '!' gen_result, exp_result = diff_arrays(gen_result, exp_result) else gen_result = gen_result.map { |el| CGI.escape_html el } exp_result = exp_result.map { |el| CGI.escape_html el } end Diff::LCS::ContextChange.new(chunk.action, chunk.old_position, gen_result, chunk.new_position, exp_result) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end", "def prepare_csv\n unparsed_file = File.open(csv.path)\n self.parsed_csv_string = \"\"\n string = unparsed_file.readlines()\n string.each_with_index do |line,i|\n parsed_line = line.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '').gsub(/,\\\"\\\"/,'')\n # for some reason the iRacing CSV file is buggy.\n unless parsed_line == \"\\n\"\n if i == 5 or i == 6\n parsed_line = parsed_line.gsub(/\\n/,\"\\r\\n\")\n end\n self.parsed_csv_string << parsed_line\n end\n end\n unparsed_file.close\n end", "def unified\n builder = Builder::XmlMarkup.new\n builder.table(class: 'unified-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(class: 'line-nr')\n builder.col(span: @combined_headers.length)\n end\n builder.thead do\n builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end", "def csv\n @csv_table ||= begin\n csv_raw = File.read(CSV_PATH)\n CSV.parse(csv_raw, headers: true)\n end\n\nend", "def test_s_parseAndCreate\n colSize = 8\n csvStr = \"foo,!!!foo!!!,!foo,bar!,!!!!!!,!!,,!\\r!,!\\r\\n!\\nNaHi,!!!Na!!!,!Na,Hi!,!\\r.\\n!,!\\r\\n\\n!,!!!!,!\\n!,!\\r\\n!\".gsub!('!', '\"')\n csvStrTerminated = csvStr + \"\\n\"\n\n myStr = csvStr.dup\n res1 = []; res2 = []\n idx = 0\n col, idx = CSV::parse_row(myStr, 0, res1)\n col, idx = CSV::parse_row(myStr, idx, res2)\n\n buf = ''\n col = CSV::generate_row(res1, colSize, buf)\n col = CSV::generate_row(res2, colSize, buf)\n assert_equal(csvStrTerminated, buf)\n\n parsed = []\n CSV::Reader.parse(csvStrTerminated) do |row|\n parsed << row\n end\n\n buf = ''\n CSV::Writer.generate(buf) do |writer|\n parsed.each do |row|\n\twriter.add_row(row)\n end\n end\n assert_equal(csvStrTerminated, buf)\n\n buf = ''\n CSV::Writer.generate(buf) do |writer|\n parsed.each do |row|\n\twriter << row\n end\n end\n assert_equal(csvStrTerminated, buf)\n end", "def parse_csv\n i=0\n output_matrix = []\n trim_return_carriage(fulltext).each_line do |line|\n 5.times { |i| avoid_commas_in_special_strings(line) }\n output_matrix << trim_line_ends(line).split(delimiter) unless i == 0\n i+=1\n end\n output_matrix.each do |rec|\n temp_hsh = {}\n (0..rec.size-1).each do |i|\n temp_hsh.merge! object_attributes[i] => rec[i]\n end\n @output_table_object << temp_hsh\n end\n\n output_table_object\n end", "def import_csv_smart\n \n end", "def import_csv_full\n \n end", "def initialize(delimited, cleanse_header: true, **args)\n @tabular = IOStreams::Tabular.new(**args)\n @delimited = delimited\n @cleanse_header = cleanse_header\n end", "def import_csv_new(csv_params:, \n table_name:, \n table_cols:)\n # using table name temp load the intial csv\n # and then updating the results back in.\n table_name_temp = table_name.to_s + \"_clone\"\n \n # 1. clone and load\n ###################\n self.clone_and_load(csv_params: csv_params, \n table_name: table_name, \n table_cols: table_cols)\n \n # 2. compare clone and orig table.\n ##################################\n \n # 3. \n \n return false\n end", "def convert\n STDERR.print \"\\nThis may take 10 minutes or more. Lines processed: \"\n line_in_count = 0\n\n # Create an object to store *all* lines of the *output* CSV\n @csv_out_data = FasterCSV.generate(FCSV_OUT_OPTS){|csv_out| \n\n # Iterate thru each *input* line\n FasterCSV.foreach(@in_file, FCSV_IN_OPTS) {|line_in|\n line_in_count += 1\n if line_in_count == 1\n self.class.verify_csv_in_headers(line_in.headers)\n @csv_out_headers = WILL_INCLUDE_INPUT_COLUMNS ? CSV_OUT_COLUMNS + CSV_IN_COLUMNS : CSV_OUT_COLUMNS\n end\n\n # Iterate thru each *output* column\n line_out = []\n @csv_out_headers.each_with_index{|col,i|\n csv_out << @csv_out_headers if line_in_count == 1 && i == 0\t# Header line\n\n case col\n when RmidItem, PrefixColOwner, PrefixColList\n line_out << line_in[col]\n when HdlItem\n line_out << get_handle_for_rmid(line_in[RmidItem])\n when HdlColOwner\n line_out << get_handle_for_collection_prefix(line_in[PrefixColOwner])\n when HdlColList\n if line_in[PrefixColList]\n prefixes = line_in[PrefixColList].split(VALUE_DELIMITER)\n handles = prefixes.inject([]){|a,prefix| a << get_handle_for_collection_prefix(prefix)}\n line_out << handles.join(VALUE_DELIMITER)\n else\n line_out << \"\"\n end\n end\n }\n csv_out << line_out\n STDERR.print \"#{line_in_count} \" if line_in_count % 200 == 0\n }\n }\n STDERR.puts \"; Total lines #{line_in_count} \"\n end", "def initialize(filename,\n col_sep: \",\",\n comment_starts: false,\n comment_matches: false,\n ignore_empty_lines: true,\n surrounding_space_need_quotes: false,\n quote_char: \"\\\"\",\n default_filter: Jcsv.optional,\n strings_as_keys: false,\n format: :list,\n headers: true,\n custom_headers: nil,\n chunk_size: 0,\n deep_map: false,\n dimensions: nil,\n suppress_warnings: false)\n \n @filename = filename\n @col_sep = col_sep\n @comment_starts = comment_starts\n @comment_matches = comment_matches\n @default_filter = default_filter\n @filters = false\n @strings_as_keys = strings_as_keys\n @headers = headers\n @custom_headers = custom_headers\n @ignore_empty_lines = ignore_empty_lines\n @format = format\n @surrounding_space_need_quotes = surrounding_space_need_quotes\n @quote_char = quote_char\n @chunk_size = (chunk_size == :all)? 1.0/0.0 : chunk_size\n @deep_map = (@format == :list)? false : deep_map\n @dimensions_names = dimensions\n @column_mapping = Mapping.new\n @suppress_warnings = suppress_warnings\n \n prepare_dimensions if dimensions\n\n # set all preferences. To create a new reader we need to have the dimensions already\n # prepared as this information will be sent to supercsv for processing.\n new_reader(set_preferences)\n\n # Dynamic class change without writing subclasses. When headers, extend this class\n # with methods that assume there is a header, when no headers, then extend this class\n # with methods that know there is no header. Could have being done with subclasses,\n # but this would all subclasses to have two subclasses one inheriting from the header\n # class and one inheriting from the headerless classes. In this way we reduce the\n # subclasses need.\n @headers? prepare_headers : (@custom_headers? set_headers(@custom_headers) :\n headerless)\n\n # if there are dimensions, then we need to prepare the mappings accordingly. With\n # dimensions defined, users cannot defined mappings.\n dimensions_mappings if dimensions\n \n end", "def open_csv(table)\n command = \"mdb-export -bstrip -D '%F %T' -d #{Shellwords.escape(delimiter)} #{file_name} #{table}\"\n Open3.popen3(command) do |stdin, stdout, stderr|\n yield CSV.new(stdout, col_sep: delimiter)\n end\n end", "def csvString\n resultColumns = self.generateResultColumns\n headers = resultColumns[:columns].keys\n # Start off instantiating the csv string with the header values\n csvString = headers.map{|s| self.filterValue(s)}.join(@options[:delimiter])\n\n # Now iterate over each row, sticking its value under each header\n (0..resultColumns[:maxRowIndex]).each do |rowIndex|\n csvString << \"\\r\\n\"\n csvString << headers.map{ |header|\n self.filterValue(resultColumns[:columns][header][rowIndex])\n }.join(@options[:delimiter])\n end\n return csvString\n end", "def convert\n # Create an object to store *all* lines of the *output* CSV\n @csv_out_data = FasterCSV.generate(FCSV_OUT_OPTS){|csv_out| \n\n # Iterate thru each *input* line\n line_in_count = 0\n FasterCSV.foreach(@in_file, FCSV_IN_OPTS) {|line_in|\n line_in_count += 1\n if line_in_count == 1\n self.class.verify_csv_in_headers(line_in.headers)\n # The output CSV shall be indentical to the input CSV but with\n # the COLUMN_ITEM_HANDLE replaced with COLUMN_ITEM_ID.\n @csv_out_headers = line_in.headers.deep_copy\n @index = @csv_out_headers.index(COLUMN_ITEM_HANDLE) # Index of column to be replaced\n @csv_out_headers[@index] = COLUMN_ITEM_ID\t# Replace this column in the header\n end\n\n # Iterate thru each *output* column\n line_out = []\n @csv_out_headers.each_with_index{|col,i|\n csv_out << @csv_out_headers if line_in_count == 1 && i == 0\t# Header line\n\n unless i == @index\n line_out << line_in[col]\n else\t\t\t\t\t\t# Replace with item_id\n h = DSpaceResource.new(line_in[COLUMN_ITEM_HANDLE], :item)\n if h && h.resource_id\n line_out << h.resource_id\t\t\t# The item_id corresponding to handle\n else\n STDERR.puts <<-MSG_HANDLE_LOOKUP.gsub(/^\\t*/, '')\n\t\tERROR: Either the handle '#{line_in[COLUMN_ITEM_HANDLE]}' was not found or it was\n\t\tfound but the corresponding item_id is NULL (eg. perhaps the item was\n\t\tdeleted from the database).\n MSG_HANDLE_LOOKUP\n exit ERROR_HANDLE_LOOKUP\n end\n end\n }\n csv_out << line_out\n }\n }\n end", "def extract_table_from_results_csv(csv_path)\n # ensure the expected result csv file exists\n raise \"File not found: #{csv_path}\" unless File.file?(csv_path)\n\n # create a csv file with the headings and last 2 rows\n output_path = csv_path.gsub(\".csv\", \".scale_extract.csv\")\n csv_name = File.basename(csv_path)\n result_name = csv_name.gsub(\".csv\", \"\")\n puts \"processing csv: #{csv_name}\"\n\n # TODO: extract into a separate method?\n contents = File.readlines(csv_path)\n\n # only include runs that didn't fail on the first iteration\n if contents.length > 2\n File.open(output_path, \"w\") do |f|\n f << contents[0]\n f << contents[-2]\n f << contents[-1]\n end\n\n # add the 2nd to last line to the success summary\n update_summary_csv(@summary_csv_path_success, \"#{result_name},#{contents[-2]}\")\n\n # add the last line to the fail summary\n update_summary_csv(@summary_csv_path_fail, \"#{result_name},#{contents[-1]}\")\n\n # csv2html\n csv2html(output_path)\n\n # table\n table = extract_table_from_csv2html_output(\"#{output_path}.html\")\n\n else\n puts \"This run failed on the first iteration; ignoring...\"\n puts\n table = nil\n end\n\n table\nend", "def initialize(csv_in_filename)\n @in_file = csv_in_filename\n @csv_out_headers = nil\n @index = nil\n @csv_out_data = nil\n convert\n end", "def create_csv_for_LLR(csv_data)\n\n csv_string = CSV.open(\"#{$basefile}LLR.csv\", \"wb\") do |csv|\n\n csv << csv_data.first.keys\n csv_data.each do |hash|\n csv << hash.values\n end\n end\n end", "def csv_export_chrono\n csv_string = CSV.generate do |csv|\n\n csv << [ \"Plaque\", \"Equipe\", \"Nom VTT\", \"Prenom VTT\", \"ADN VTT\", \"Nom Route\", \"Prenom Route\", \"ADN Route\", \"Categorie\"]\n\n Team.order_by(:plate).each do |t|\n cat = t.category\n next unless cat\n\n cname = cat.map { |v| v.capitalize }.join('-')\n csv << [ t.plate, t.name, \n t.vtt.profile.name.upcase, t.vtt.profile.surname.capitalize, t.vtt.profile.birth.year, \n t.route.profile.name.upcase, t.route.profile.surname.capitalize, t.route.profile.birth.year, cname]\n end\n end\n\n respond!(csv_string, 200, 'Content-Type' => 'text/csv')\n end", "def test_parse_headers\n tmpdbfile = Tempfile.new('tmp.db')\n args = [\"--header\", \n \"--source\", \"header_test.csv\", \n \"--save-to\", tmpdbfile.path, \n \"--ifs=\" \",\",\n \"--table-name\",\"header_test\"]\n Csvql.run(args)\n\n db = SQLite3::Database.new tmpdbfile.path\n headers_from_db = db.execute2('select * from header_test;')[0]\n headers_from_file = File.open('header_test.csv').each_line.first.gsub(/\\n/,'').split(',')\n\n #binding.pry\n assert_equal headers_from_db, headers_from_file\n end", "def render(truncate_after_bytes = nil)\n Tempfile.open(['csv']) do |tempfile|\n csv = CSV.new(tempfile)\n\n write_csv csv, until_condition: -> do\n truncate_after_bytes && tempfile.size > truncate_after_bytes\n end\n\n if block_given?\n yield tempfile\n else\n tempfile.rewind\n tempfile.read\n end\n end\n end", "def render_csv(csv, filename = nil)\n filename ||= params[:action]\n filename += '.csv'\n\n if request.env['HTTP_USER_AGENT'] =~ /msie/i\n headers['Pragma'] = 'public'\n headers[\"Content-type\"] = \"text/plain\"\n headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'\n headers['Content-Disposition'] = \"attachment; filename=\\\"#{filename}\\\"\"\n headers['Expires'] = \"0\"\n else\n headers[\"Content-Type\"] ||= 'text/csv'\n headers[\"Content-Disposition\"] = \"attachment; filename=\\\"#{filename}\\\"\"\n end\n\n render :layout => false, :text => csv\n end", "def export_csv\n export_string = \"#{@id},#{type_string},#{@name.gsub(/[\\,,\\s]/,\"\")},\"\n @details.each{|k,v| export_string << \"#{k}=#{v};\".gsub(/[\\,,\\s]/,\"\") }\n export_string\n end", "def export_csv\n export_string = \"#{@id},#{type_string},#{@name.gsub(/[\\,,\\s]/,\"\")},\"\n @details.each{|k,v| export_string << \"#{k}=#{v};\".gsub(/[\\,,\\s]/,\"\") }\n export_string\n end", "def convert_csv(original_csv)\n csv_options = {}\n csv_options[:col_sep] = option(:csv_col_sep) unless option(:csv_col_sep).blank?\n csv_options[:row_sep] = option(:csv_row_sep) unless option(:csv_row_sep).blank?\n csv_options[:quote_char] = option(:csv_quote_char) unless option(:csv_quote_char).blank?\n value_converter = option(:csv_value_proc)\n\n converted_csv = \"#{original_csv}.converting\"\n CSV.open(converted_csv, 'wb', csv_options) do |csv|\n CSV.foreach(original_csv) do |row|\n row = row.map{ |value| value.blank? ? '' : value_converter.call(value) } if value_converter\n csv << row\n end\n end\n FileUtils.remove(original_csv)\n FileUtils.move(converted_csv, original_csv)\n end", "def sonde_data_filter(iterator)\n cut_line(iterator)\n head1 = cut_line(iterator)\n head1_csv = CSV.parse(head1).flatten\n head1_csv.collect!{|str| str.strip}\n \n head2 = cut_line(iterator)\n head2_csv = CSV.parse(head2).flatten\n head2_csv.collect!{|str| str.strip}\n cut_line(iterator)\n \n merged_str = merge_headers(head1_csv, head2_csv, \" \", \"[\", \"]\")\n \n new_head = merged_str.join(',')\n new_head << \"\\r\\n\"\n new_iterator = new_head << iterator\n #puts new_iterator\n return new_iterator\n end", "def render_csv(options={})\n # Set filename to ultimately requested file by default, and force appending\n # of .csv\n filename = options[:filename]\n filename ||= CGI::escape(request.path.gsub(/^.*\\//, \"\"))\n filename += '.csv' unless filename =~ /\\.csv$/\n\n # String#index returns nil if no match is found\n if request.env['HTTP_USER_AGENT'].index(\"MSIE\")\n headers['Pragma'] = 'public'\n headers[\"Content-type\"] = \"text/plain\" \n headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'\n headers['Content-Disposition'] = \"attachment; filename=\\\"#{filename}\\\"\" \n headers['Expires'] = \"0\" \n else\n headers[\"Content-Type\"] ||= 'text/csv'\n headers[\"Content-Disposition\"] = \"attachment; filename=\\\"#{filename}\\\"\" \n end\n\n if block_given?\n require 'fastercsv'\n text = FasterCSV.generate do |csv|\n yield csv\n end\n render :text => text\n elsif data = options[:data]\n require 'fastercsv'\n text = FasterCSV.generate do |csv|\n data.each do |line|\n csv << line\n end\n end\n render :text => text\n else\n render :layout => false\n end\n\n end", "def fix_csv(old_csv)\n\t\told_csv.pop\n\t\tproper_headers(old_csv)\n\t\tCSV.open(\"public/ephemeral.csv\", 'wb') do |write_crude|\n\t\t\told_csv.each do |fix_csv|\n\t\t\t\twrite_crude << fix_csv\n\t\t\tend\n\t\tend\n\tend", "def initialize(line_reader, cleanse_header: true, **args)\n @tabular = IOStreams::Tabular.new(**args)\n @line_reader = line_reader\n @cleanse_header = cleanse_header\n end", "def csv_report\n tire_cols = params[:tire] || {}\n ar_cols = params[:activerecord] || {}\n assocs_to_include = params[:assoc][:include] || {}\n params[:assoc][:max] ||= {}\n klass = model_class.constantize\n @filename = \"#{model_class.humanize}.csv\"\n\n response.headers['Content-Type'] ||= 'text/plain'\n response.headers['Content-Disposition'] = \"attachment; filename=#{@filename}\"\n response.headers['Content-Transfer-Encoding'] = 'binary'\n response.headers['Last-Modified'] = Time.now.to_s\n\n # Right, try to define a header:\n header = []\n tire_cols.keys.each { |x| header.push(x.humanize) }\n ar_cols.keys.each { |x| header.push(x.humanize) }\n assocs_to_include.keys.each do |assoc|\n if params[:assoc][:max][assoc] == 'join' # Is a has_many with only one real column\n header.push params[:assoc][assoc.to_sym].keys.first\n elsif params[:assoc][:max][assoc] # has_many\n (1 .. (params[:assoc][:max][assoc].to_i)).each do |i|\n params[:assoc][assoc.to_sym].keys.each do |k|\n header.push(\"#{assoc.singularize.humanize} #{i} #{k.humanize}\")\n end\n end\n else # has_a\n params[:assoc][assoc.to_sym].keys.each do |k| # Each key requested from the associated record\n header.push \"#{assoc.humanize} #{k.humanize}\"\n end\n end\n end\n\n results = klass.search({ per: TireSearch::INFINITY }, 1, '')\n self.response_body = Enumerator.new do |y|\n results.each_with_index do |result, i|\n y << header.to_csv if i == 0\n\n line = []\n tire_cols.keys.each { |x| line.push(result[x]) }\n\n result = result.load if ar_cols.count > 0 || assocs_to_include.keys.count > 0\n\n ar_cols.keys.each { |x| line.push(result.send(x)) } if ar_cols.count > 0\n\n assocs_to_include.keys.each do |assoc|\n related = result.send(assoc)\n if params[:assoc][:max][assoc] == 'join' # Is a has_many with only one real column\n col = params[:assoc][assoc.to_sym].keys.first\n line.push related.map { |x| x.send(col) }.join(' // ')\n elsif params[:assoc][:max][assoc]\n (0 .. (params[:assoc][:max][assoc].to_i - 1)).each do |j|\n params[:assoc][assoc.to_sym].keys.each do |k|\n line.push(related[j] ? related[j].send(k) : nil)\n end\n end\n else\n params[:assoc][assoc.to_sym].keys.each do |k| # Each key requested from the associated record\n line.push related ? related.send(k) : nil\n end\n end\n end\n y << line.to_csv\n GC.start if i % 500 == 0\n end\n end\n end" ]
[ "0.6365711", "0.617779", "0.5809265", "0.5763582", "0.5737592", "0.57320434", "0.5729515", "0.567915", "0.5666242", "0.5646566", "0.56349075", "0.5598919", "0.55255604", "0.52926606", "0.5253105", "0.52371824", "0.52362704", "0.52265257", "0.5223451", "0.52117753", "0.51915354", "0.51705974", "0.51543504", "0.51543504", "0.51523006", "0.5148355", "0.51349586", "0.51270145", "0.5124126", "0.5118088" ]
0.63552666
1
Render a unified table view based on the data passed when creating the CsvDiffer instance.
def unified builder = Builder::XmlMarkup.new builder.table(class: 'unified-diff diff csv-diff') do builder.colgroup do builder.col(class: 'line-nr') builder.col(class: 'line-nr') builder.col(span: @combined_headers.length) end builder.thead do builder.tr do builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do builder.i(class: 'mdi mdi-18 mdi-file-account') end builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do builder.i(class: 'mdi mdi-18 mdi-file-check') end builder.th(colspan: @combined_headers.length) end builder.tr do builder.th(class: 'line-nr') builder.th(class: 'line-nr') builder << @combined_headers.join end end builder.tbody do if @simplified_table unified_simple_body builder else @diff.each do |chunk| is_empty, row = old_row chunk unless is_empty full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] } builder << %(<tr> <td class="line-nr">#{chunk.old_position + 1}</td> <td class="line-nr"></td> #{full_row.join} </tr>) end is_empty, row = new_row chunk next if is_empty full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] } builder << %(<tr> <td class="line-nr"></td> <td class="line-nr">#{chunk.new_position + 1}</td> #{full_row.join} </tr>) end end end end.html_safe end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end", "def render_table(rows, options = {})\n options = { :description => false }.merge options\n # Figure out the fields from the :model option\n if options[:model] && options[:fields].nil?\n options[:fields] = options[:model].default_field_order\n end\n # Figure out the fields from the first row\n if options[:fields].nil? && rows.first.class.respond_to?(:default_field_order)\n options[:fields] = rows.first.class.default_field_order\n end\n # Call to_row on all the rows\n rows = rows.map do |row|\n row.respond_to?(:to_row) ? row.to_row : row\n end\n # Call render_cell on all the cells\n rows.each do |row|\n # FIXME: default Api subclasses do not respond to #keys so specialising\n # #to_row is required to not break the following\n row.each_key do |k|\n row[k] = row[k].render_cell if row[k].respond_to? :render_cell\n end\n end\n if options[:s]\n # Simple output\n rows.each do |row|\n if options[:vertical]\n data options[:fields].map { |k| [k, row[k]].join(\"\\t\") }.join(\"\\n\")\n else\n data options[:fields].map { |k| row[k].is_a?(Array) ? row[k].join(\",\") : row[k] }.join(\"\\t\")\n end\n end\n elsif options[:vertical]\n # \"graphical\" table\n data ShowTable.render(rows, options)\n else\n data SimpleTable.render(rows, options)\n end\n end", "def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end", "def render\n raise \"tabular:: list is nil \" unless @list\n $log.debug \" render list:: #{@list.size} \"\n #$log.debug \" render list:1: #{@list} \"\n raise \"tabular:: columns is nil \" unless @columns\n buffer = []\n @separ = nil\n _guess_col_widths\n rows = @list.size.to_s.length\n #@rows = rows\n fmstr = _prepare_format\n $log.debug \"tabular: fmstr:: #{fmstr}\"\n $log.debug \"tabular: cols: #{@columns}\"\n #$log.debug \"tabular: data: #{@list}\"\n\n str = \"\"\n if @numbering\n str = \" \"*(rows+1)+@y\n end\n #str << fmstr % visible_column_names()\n str << convert_heading_to_text(visible_column_names(), fmstr)\n buffer << str\n #puts \"-\" * str.length\n buffer << separator if @use_separator\n if @list ## XXX why wasn't numbering done in _prepare_format ???? FIXME\n if @numbering\n fmstr = \"%#{rows}d \"+ @y + fmstr\n end\n #@list.each { |e| puts e.join(@y) }\n count = 0\n @list.each_with_index { |r,i| \n if r == :separator\n buffer << separator\n next\n end\n if @_hidden_columns_flag\n r = visible_columns(r)\n end\n if @numbering\n r.insert 0, count+1\n end\n #value = convert_value_to_text r, count\n value = convert_value_to_text r, fmstr, i\n buffer << value\n count += 1\n }\n end\n buffer\n end", "def render_table(arel)\n return if arel.first.nil?\n partial :table, :locals => {:model => arel.first.class, :arel => arel}\n end", "def table options = {} \n render_partial :table, template_locals(:table_row, options)\n end", "def generate_html\n\n # Return our to_string function if we aren't reconstructed yet\n return self.to_s if !@reconstructed_table\n\n # Create an HTML table\n html = \"<table style='border:1px solid black'>\\n\";\n\n # Loop over each row and create a new table row\n @reconstructed_table.each do |row|\n html += \"<tr>\\n\";\n\n # Loop over each column and place the cell value into a td\n row.each do |column|\n to_show = column\n to_show = \"&nbsp;\" if to_show == \"\"\n html += \"<td style='border:1px solid black'>#{to_show}</td>\\n\";\n end\n\n # Close the row\n html += \"</tr>\\n\";\n end\n\n # Close the table\n html += \"</table>\\n\";\n return html\n end", "def to_html(fields) \n output = []\n output << %(<table class=\"#{@options[:table_class]}\">)\n\n # Title\n if @options.has_key?(:title)\n output << %(<tr class=\"#{@options[:first_row_class]}\">)\n output << %(<th class=\"#{@options[:title_class]} #{@options[:first_row_class]} #{@options[:first_column_class]}\" colspan=\"#{fields.length}\">#{@options[:title]}</th>)\n output << %(</tr>)\n end\n\n # First row (header)\n output << %(<tr class=\"#{@options[:first_row_class]}\">)\n fields.each_with_index do |field, index|\n output << %(<th class=\"#{@options[:first_row_class]} #{column_classes(fields, index)}\">#{field}</th>)\n end\n output << \"</tr>\"\n\n @rows.each_with_index do |row, row_index|\n if block_given?\n yield_output = yield(row)\n\n data = []\n row_options = {}\n case yield_output\n when Array\n data = yield_output\n when Hash\n data = yield_output.delete(:data)\n row_options = yield_output\n else\n raise ArgumentError, \"TidyTable block expects an Array or Hash, but a #{yield_output.class} was returned.\"\n end\n\n row_classes = [row_index % 2 == 0 ? 'even': 'odd', row_options[:class]].select {|i| !i.nil?}.join(' ')\n output << %(<tr class=\"#{row_classes}\" #{\"id=\\\"#{row_options[:id]}\\\"\" if row_options.has_key?(:id)}>)\n data.each_with_index do |item, index|\n output << %(<td class=\"#{column_classes(data, index)}\">#{item}</td>)\n end\n else\n output << %(<tr class=\"#{row_index % 2 == 0 ? 'even': 'odd'}\">)\n fields.each_with_index do |field, index|\n output << %(<td class=\"#{column_classes(fields, index)}\">#{row.send(field.to_sym)}</td>)\n end\n end\n output << \"</tr>\"\n end\n output << \"</table>\"\n output.join\n end", "def format!\n tables.map { |t|\n SimpleReports::TableFormatter.new(t).format_table!\n }\n end", "def format_html\n formatted = \"<table summary=\\\"Tide tables with columns for time of day and tide height (in meters).\\\">\\n\\t<thead>\\n\\t\\t<tr><th scope=\\\"col\\\">Time</th><th scope=\\\"col\\\">Height</th></tr>\\n\\t</thead>\\n\"\n last_date = nil\n to_csv.each_line do |row|\n row = row.chomp.split(',')\n if row[0] != last_date\n formatted += \"\\t</tbody>\\n\" unless last_date.nil?\n formatted += \"\\t<tbody>\\n\\t\\t<tr><th scope=\\\"rowgroup\\\" colspan=\\\"2\\\">#{row[0]}</th></tr>\\n\"\n last_date = row[0]\n end\n formatted += \"\\t\\t<tr><td>#{row[1]}</td><td>#{row[2]}m</td></tr>\\n\"\n end\n formatted += \"\\t</tbody>\\n</table>\\n\"\n formatted\n end", "def render(model, data)\n \n CSVOutputFormat.new(model, data).run\n \n end", "def initialize(generated, expected)\n @generated = CSV.parse((generated || '').lstrip, nil_value: '')\n @expected = CSV.parse((expected || '').lstrip, nil_value: '')\n\n @gen_headers, *@generated = @generated\n @gen_headers ||= []\n @exp_headers, *@expected = @expected\n @exp_headers ||= []\n\n @simplified_table = @generated.length > 100 || @expected.length > 100\n\n @gen_header_indices, @exp_header_indices, @gen_headers, @exp_headers, @combined_headers = diff_header_indices(@gen_headers, @exp_headers)\n\n @diff = unless @simplified_table\n Diff::LCS.sdiff(@generated, @expected).map do |chunk|\n gen_result = chunk.old_element || []\n exp_result = chunk.new_element || []\n if chunk.action == '!'\n gen_result, exp_result = diff_arrays(gen_result, exp_result)\n else\n gen_result = gen_result.map { |el| CGI.escape_html el }\n exp_result = exp_result.map { |el| CGI.escape_html el }\n end\n Diff::LCS::ContextChange.new(chunk.action, chunk.old_position, gen_result, chunk.new_position, exp_result)\n end\n end\n end", "def table_for(value, options = {}, &block)\n view(value, options.merge(:as => :table), &block)\n end", "def draw()\n @vc.content_tag(:table) do\n @left = true\n @vc.capture do\n for col in columns do\n @vc.concat col.field(@record, self)\n end\n @vc.concat('<td colspan=3></td>'.html_safe) if !@left\n end\n end\n end", "def show_table\n build_html do\n if upd_apar_defs.length == 0\n div.upd_apar_defs do\n span \"Did not find any items matching request\"\n end\n else\n table.upd_apar_defs do\n thead do\n tr do\n th '#'\n [ \"Defect\", \"Apar\", \"PTF\", \"Abstract\",\n \"LPP\", \"VRMF\", \"Version\", \"Service Pack\" ].each do |header_label|\n th class: \"upd_apar_def-#{header_label.gsub(\" \", \"_\").downcase}\" do\n span class: \"upd_apar_defs_header_span\" do\n text header_label\n span class: \"sort sortable\" do\n end\n end\n end\n end\n end\n end\n tbody do\n # upd_apar_defs.each_with_index { |o, i| show_upd_apar_def(o,i) }\n end\n end\n end\n end\n end", "def render_table(data, separator = \" # \")\n column_width = data.group_by do |row|\n row.first.size\n end.max.first\n \"\".tap do |output|\n data.each do |row|\n output << \"%-#{column_width}s#{separator}%s\\n\" % row\n end\n end\n end", "def diff_template= table\n @diff_template = table\n end", "def show_table\n build_html do\n if paths.keys.length == 0\n div.which_filesets do\n span \"Did not find any shipped files matching #{path}\"\n end\n else\n table.which_filesets do\n thead do\n tr do\n th '#'\n th 'Path'\n th 'Lpp'\n end\n end\n tbody do\n index = 0\n paths.each_pair do |path, lpps|\n lpps.each do |lpp|\n tr do\n td index += 1\n td path\n td link_to(lpp, swinfo_get_path(lpp))\n end\n end\n end\n end\n end\n end\n end\n end", "def to_html\n html = \"<table class='bodyTable'><thead><th>Name</th><th>Lines</th><th>LOC</th><th>Classes</th><th>Methods</th><th>M/C</th><th>LOC/M</th></thead><tbody>\"\n i = 0\n results = self.result.split(/$/)\n bottom = 4 if ENV[\"RAILS_ROOT\"].present?\n bottom ||= 3\n top = bottom\n while !results[bottom].nil? and results[bottom][0..1] != \"\\n+\" do\n bottom = bottom + 1\n end\n lines = results[top..bottom-1]\n lines.each do |line|\n elements = line.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n html = html + \"<td style='text-align: right;'>#{elements[2]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[3]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[4]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[5]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[6]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[7]}</td>\"\n html = html + \"</tr>\"\n i = i + 1\n end\n total = results[bottom + 1]\n elements = total.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n [2,3,4,5,6,7].each do |j|\n html = html + \"<td style='text-align: right;'><strong>#{elements[j]}</strong></td>\"\n end\n html = html + \"</tr>\"\n html = html + \"</tbody></table>\"\n extra = results[bottom + 3]\n elements = extra.split(/:| /)\n @percent = (elements[3].strip.to_f * 100.0) / elements[1].strip.to_f\n return html\n end", "def apply_template\n apply_table_format_template(template.table)\n end", "def render\n @mark.table_begin(\"table-striped table-sm table-responsive table-hover\")\n generate_headers\n generate_rows\n @mark.table_end\n @mark.render\n end", "def generate_diff\n jsons = version_jsons.map { |j| pretty_json(j) }\n differ = Differ.send(diff_method, *jsons).format_as(:html)\n differ.gsub!('<ins', \"\\n<ins\") if diff_method == :diff_by_line\n @diff = sanitize(differ).html_safe\n end", "def table(records, &block)\n return if records.empty?\n rows = collect_rows(records, &block)\n col_widths = calculate_column_widths(rows)\n\n rows.each do |row|\n line = row.values.each_with_index.map do |value, col|\n value.to_s.ljust(col_widths[col])\n end.join(\" \").rstrip\n line = color.colorize(line, row.color) if row.color\n puts line\n end\n end", "def to_html\n %Q|<table border=1>\\n<caption>#@name</caption>\\n| + data.map { |row| '<tr>' + row.map { |v| '<td>' + CGI.escapeHTML(v.to_s) }.join }.join(\"\\n\") + \"\\n</table>\"\n end", "def output\n # This results in a hash of two-element arrays. The key is the header and\n # the value is an array of the header and formatted header. We do the\n # latter so the structure parallels the structure for rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n result += hline(widths) if loc_row.nil?\n next if loc_row.nil?\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end", "def mount_table(*args)\n return '' if args.empty?\n array = args.delete_at(0)\n header = '<tr><th>'+args.collect{|i| i.to_s.titlecase }.join('</th><th>')+'</th></tr>'\n lines = array.collect{|i| '<tr><td>'+i.join('</td><td>')+'</td></tr>' }.join\n \n <<-TABLE\n <table>\n <thead>#{header}</thead>\n <tbody style=\"text-align:left;\">\n #{lines}\n </tbody>\n </table>\n TABLE\n end", "def to_html \n PrettyDiff::HtmlGenerator.generate_diff(chunks)\n end", "def diff_template\n return @diff_template if defined?(@diff_template)\n diffbook = Workbook::Book.new_diff_template\n difftable = diffbook.sheet.table\n @diff_template ||= difftable\n end", "def show_table(name, table, table_hash, conditions = {}, delete = [])\n\t\t\t \tbegin\n\t\t\t\t\tdefault_columns = []\n\t\t\t\t\ttable_hash.each do |key, val|\n\t\t\t\t\t\tdefault_columns << key\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\tdelete.each do |i| ; default_columns.delete_if {|v| (v == i)} ; end\n\t\t\t\t\t\n\t\t\t\t\ttbl = Rex::Ui::Text::Table.new({'Header' => name, 'Columns' => default_columns})\n\t\t\t\t\t\n\t\t\t\t\tlen1 = table.length - 1\n\t\t\t\t\tlen2 = default_columns.length - 1\n\t\t\t\t\n\t\t\t\t\tfind_all(table, table_hash, conditions).each do |victim|\n\t\t\t\t\t\tline = []\n\t\t\t\t\t\tfor i in 0..len2\n\t\t\t\t\t\t\tline << victim[table_hash[default_columns[i]]].to_s\n\t\t\t\t\t\tend\n\t\t\t\t\t\ttbl << line\n\t\t\t\t\tend\n\t\t\t\t\t\t\t\n\t\t\t\t\tprint_line\n\t\t\t\t\tprint_line tbl.to_s\n\t\t\t\trescue\n\t\t\t\t\tprint_error(\"Error 9: #{$!}\") if (XSSF_MODE[0] =~ /^Debug$/i)\n\t\t\t\tend\n\t\t\tend", "def write_comparison_table(app, cm)\n \n row_num = 0 # TODO use same numbering for all rows\n \n [['context_1', 'context_2'], ['context_1', 'context_3']].each{|ctx_set|\n \n cm.add_row(\n {:text=>(cm.html?)?'<strong>Scenarios:</strong>':'Scenarios:', :colspan=>2},\n {:text=>ctx_set.inspect.to_s, :colspan=>20}\n )\n \n cm.add_row({:text=>'', :colspan=>4}, {:text=>'IIS', :colspan=>6}, {:text=>'Apache', :colspan=>9})\n cm.add_row({:text=>'', :colspan=>4}, {:text=>'Load Agents', :colspan=>2}, {:text=>'No WinCache', :colspan=>3}, {:text=>'WinCache', :colspan=>3}, {:text=>'No APC', :colspan=>3}, {:text=>'APC', :colspan=>3}, {:text=>'APC w/ IGBinary', :colspan=>3})\n cm.add_row('', 'OS', 'Physical', 'Virtual', 'Base', 'Test', 'Gain', 'Base', 'Test', 'Gain', 'Base', 'Test', 'Gain', 'Base', 'Test', 'Gain')\n \n cm.add_row('1', 'Win 2003 x86 SP2', '2', '8', '50', '100', '50%', '100', '50', '50%', '50', '100', '50%', '100', '50', '50%')\n \n cm.add_row(\n {:text=>(cm.html?)?'<strong>Windows INI:</strong>':'INI:', :colspan=>2},\n # TODO show INI\n {:text=>ctx_set.inspect.to_s, :colspan=>20}\n )\n cm.add_row(\n {:text=>(cm.html?)?'<strong>Linux INI:</strong>':'INI:', :colspan=>2},\n # TODO show INI\n {:text=>ctx_set.inspect.to_s, :colspan=>20}\n )\n \n \n \n }\n \n return cm\n end" ]
[ "0.6573815", "0.6189673", "0.5929262", "0.58629036", "0.5862575", "0.5783196", "0.5720341", "0.56802416", "0.56705254", "0.56525594", "0.5648546", "0.56348133", "0.56308836", "0.562267", "0.56099725", "0.55963296", "0.5580589", "0.55315", "0.5478361", "0.54780394", "0.5438503", "0.5403681", "0.5392545", "0.5340412", "0.5333245", "0.53215307", "0.5313247", "0.52665603", "0.52464", "0.5245737" ]
0.7310779
0
Render a split table view based on the data passed when creating the CsvDiffer instance. The split view renders two tables, that individually have a horizontal scrollbar.
def split builder = Builder::XmlMarkup.new builder.div do split_build_table(builder, @gen_headers, true) split_build_table(builder, @exp_headers, false) end.html_safe end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end", "def unified\n builder = Builder::XmlMarkup.new\n builder.table(class: 'unified-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(class: 'line-nr')\n builder.col(span: @combined_headers.length)\n end\n builder.thead do\n builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end", "def tabla_flota(list_flota)\n data = Array.new\n encabezado = make_table([ [{content: 'Placa', :width => 100, :size => 7},\n {content: 'Modelo', :width => 100, :size => 7},\n {content: 'Marca', :width => 100, :size => 7},\n {content: 'Año', :width => 60, :size => 7},\n {content: 'Serial de Carroceria', :width => 100, :size => 7}] ])\n table([\n [{content: \"\", :colspan => 7, :border_bottom_width => 0} ],\n [{content: \"\", :colspan => 1, :border_top_width => 0, :border_bottom_width => 0, :width => 30},\n {content: encabezado, :colspan => 5, :width => 460, background_color: 'd7d7d7'},\n {content: \"\", :colspan => 1,:border_top_width => 0, :border_bottom_width => 0, :width => 30}]\n ])\n list_flota.each_with_index do |vehiculos,index|\n data = make_table([ [{content: vehiculos.placa,:width => 100, :size => 7 },\n {content: vehiculos.modelo, :width => 100, :size => 7},\n {content: vehiculos.marca, :width => 100, :size => 7},\n {content: vehiculos.ano.to_s, :width => 60, :size => 7},\n {content: vehiculos.s_carroceria,:width => 100, :size => 7 }] ])\n\n table([\n [{content: \"\", :colspan => 1, :border_top_width => 0, :border_bottom_width => 0, :width => 30},\n {content: data, :colspan => 5, :width => 460},\n {content: \"\", :colspan => 1, :border_top_width => 0, :border_bottom_width => 0, :width => 30} ]\n\n ])\n if cursor <= 40\n table([\n [{content: \"\", :colspan => 7, :border_top_width => 0, :width => 520}]\n ])\n start_new_page\n flota list_flota.slice(index+1,list_flota.length), true if index+1 <= list_flota.length\n return\n end\n end\n\n table([\n [{content: \"\", :colspan => 7, :border_top_width => 0, :width => 520}]\n ])\n\n end", "def draw()\n @vc.content_tag(:table) do\n @left = true\n @vc.capture do\n for col in columns do\n @vc.concat col.field(@record, self)\n end\n @vc.concat('<td colspan=3></td>'.html_safe) if !@left\n end\n end\n end", "def render\n raise \"tabular:: list is nil \" unless @list\n $log.debug \" render list:: #{@list.size} \"\n #$log.debug \" render list:1: #{@list} \"\n raise \"tabular:: columns is nil \" unless @columns\n buffer = []\n @separ = nil\n _guess_col_widths\n rows = @list.size.to_s.length\n #@rows = rows\n fmstr = _prepare_format\n $log.debug \"tabular: fmstr:: #{fmstr}\"\n $log.debug \"tabular: cols: #{@columns}\"\n #$log.debug \"tabular: data: #{@list}\"\n\n str = \"\"\n if @numbering\n str = \" \"*(rows+1)+@y\n end\n #str << fmstr % visible_column_names()\n str << convert_heading_to_text(visible_column_names(), fmstr)\n buffer << str\n #puts \"-\" * str.length\n buffer << separator if @use_separator\n if @list ## XXX why wasn't numbering done in _prepare_format ???? FIXME\n if @numbering\n fmstr = \"%#{rows}d \"+ @y + fmstr\n end\n #@list.each { |e| puts e.join(@y) }\n count = 0\n @list.each_with_index { |r,i| \n if r == :separator\n buffer << separator\n next\n end\n if @_hidden_columns_flag\n r = visible_columns(r)\n end\n if @numbering\n r.insert 0, count+1\n end\n #value = convert_value_to_text r, count\n value = convert_value_to_text r, fmstr, i\n buffer << value\n count += 1\n }\n end\n buffer\n end", "def render_table(arel)\n return if arel.first.nil?\n partial :table, :locals => {:model => arel.first.class, :arel => arel}\n end", "def render_table(data, separator = \" # \")\n column_width = data.group_by do |row|\n row.first.size\n end.max.first\n \"\".tap do |output|\n data.each do |row|\n output << \"%-#{column_width}s#{separator}%s\\n\" % row\n end\n end\n end", "def rows(parts=@parts)\n \n @renderer.rows(parts)\n \n end", "def rows(parts, fields = [\n [\n \"Sub Assembly\",\n \"sub_assembly\" \n ],\n [ \n \"Part Name\", \n \"part_name\"\n ],\n [ \n \"Quantity\", \n \"quantity\"\n ],\n [ \n \"Width\",\n \"width\"\n ],\n [ \n \"Length\",\n \"length\"\n ],\n [ \n \"Thickness\", \n \"thickness\"\n ],\n [ \n \"Material\",\n \"material\"\n ]\n ])\n \n # TODO: Get the order of items in a list to be configurable somehow...\n \n html = <<-EOS\n \n <table>\n <thead>\n <tr>\n \n EOS\n \n # List each heading for the coumns based on the `fields` parameter.\n fields.each { |f|\n \n html += \"<th>#{f[0].to_s}</th>\"\n \n }\n\n \n html += <<-EOS\n \n </tr>\n </thead>\n <tbody>\n \n EOS\n \n if parts != nil\n \n all_rows = ''\n \n parts.each { |p| \n \n all_rows += row(p, fields)\n \n }\n \n puts \"[HTMLRenderer.rows] all_rows: #{all_rows}\" if $cutlister_debug\n \n html += all_rows.to_s\n \n else\n \n UI.messagebox \"Sorry, there are no parts to cutlist...\", MB_OK\n \n end\n \n html += <<-EOS\n \n </tbody>\n </table>\n \n EOS\n \n html += section_footer(parts)\n \n html\n \n end", "def render\n @mark.table_begin(\"table-striped table-sm table-responsive table-hover\")\n generate_headers\n generate_rows\n @mark.table_end\n @mark.render\n end", "def show_table\n build_html do\n if paths.keys.length == 0\n div.which_filesets do\n span \"Did not find any shipped files matching #{path}\"\n end\n else\n table.which_filesets do\n thead do\n tr do\n th '#'\n th 'Path'\n th 'Lpp'\n end\n end\n tbody do\n index = 0\n paths.each_pair do |path, lpps|\n lpps.each do |lpp|\n tr do\n td index += 1\n td path\n td link_to(lpp, swinfo_get_path(lpp))\n end\n end\n end\n end\n end\n end\n end\n end", "def set_up_table_view\n self.table_view\n _table_view = self.create_table_view_from_data(self.table_data)\n adjusted_frame = self.view.bounds\n adjusted_frame.size.width = app_delegate.panels.leftVisibleWidth\n _table_view.frame = adjusted_frame\n self.view = UIView.new\n self.view.addSubview(_table_view)\n end", "def table options = {} \n render_partial :table, template_locals(:table_row, options)\n end", "def index\n @splitters = Splitter.all\n end", "def render_table(rows, options = {})\n options = { :description => false }.merge options\n # Figure out the fields from the :model option\n if options[:model] && options[:fields].nil?\n options[:fields] = options[:model].default_field_order\n end\n # Figure out the fields from the first row\n if options[:fields].nil? && rows.first.class.respond_to?(:default_field_order)\n options[:fields] = rows.first.class.default_field_order\n end\n # Call to_row on all the rows\n rows = rows.map do |row|\n row.respond_to?(:to_row) ? row.to_row : row\n end\n # Call render_cell on all the cells\n rows.each do |row|\n # FIXME: default Api subclasses do not respond to #keys so specialising\n # #to_row is required to not break the following\n row.each_key do |k|\n row[k] = row[k].render_cell if row[k].respond_to? :render_cell\n end\n end\n if options[:s]\n # Simple output\n rows.each do |row|\n if options[:vertical]\n data options[:fields].map { |k| [k, row[k]].join(\"\\t\") }.join(\"\\n\")\n else\n data options[:fields].map { |k| row[k].is_a?(Array) ? row[k].join(\",\") : row[k] }.join(\"\\t\")\n end\n end\n elsif options[:vertical]\n # \"graphical\" table\n data ShowTable.render(rows, options)\n else\n data SimpleTable.render(rows, options)\n end\n end", "def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end", "def cut_fragments grouped_ops \n show {\n title \"Cut Out Fragments\"\n check \"Take out #{grouped_ops.length} 1.5 mL tubes and label accordingly: #{grouped_ops.map { |op| \"#{op.output(\"Fragment\").item}\" }.to_sentence}\"\n check \"Now, cut out the bands and place them into the 1.5 mL tubes according to the following table:\"\n table grouped_ops.start_table \n .custom_column(heading: \"Gel ID\") { |op| \"#{op.input(FRAGMENT).item}\" }\n .custom_column(heading: \"Row\") { |op| op.input(FRAGMENT).row + 1 }\n .custom_column(heading: \"Column\", checkable: true) { |op| op.input(FRAGMENT).column + 1 }\n .custom_column(heading: \"1.5 mL Tube ID\") { |op| \"#{op.output(FRAGMENT_OUT).item}\" }\n .custom_column(heading: \"Length\") { |op| op.output(FRAGMENT_OUT).sample.properties[\"Length\"] }\n .end_table\n }\n end", "def compare_view\n @tsd_file1 = 'heco14.TSD'\n @tsd_file2 = '13Q4.TSD'\n @series_name = params[:list_index].nil? ? params[:series_name] : @data_list.series_names[params[:list_index].to_i]\n\n @data1 = json_from_heroku_tsd(@series_name,@tsd_file1)\n\t\t@series1 = @data1 && Series.new_transformation(@data1['name']+'.'+@data1['frequency'], @data1['data'],\n Series.frequency_from_code(@data1['frequency'])).trim('2006-01-01','2017-10-01')\n\t\t@chg1 = @series1.annualized_percentage_change\n \n @data2 = json_from_heroku_tsd(@series_name,@tsd_file2)\n\t\t@series2 = @data2 && Series.new_transformation(@data2['name']+'.'+@data2['frequency'], @data2['data'],\n Series.frequency_from_code(@data2['frequency'])).trim('2006-01-01','2017-10-01')\n\t\t@chg2 = @series2.annualized_percentage_change\n\n @history_series = @series_name.ts.trim('2006-01-01','2017-10-01')\n @history_chg = @history_series.annualized_percentage_change\n end", "def mount_table(*args)\n return '' if args.empty?\n array = args.delete_at(0)\n header = '<tr><th>'+args.collect{|i| i.to_s.titlecase }.join('</th><th>')+'</th></tr>'\n lines = array.collect{|i| '<tr><td>'+i.join('</td><td>')+'</td></tr>' }.join\n \n <<-TABLE\n <table>\n <thead>#{header}</thead>\n <tbody style=\"text-align:left;\">\n #{lines}\n </tbody>\n </table>\n TABLE\n end", "def build_report_body\n draw_table(data, :width => 600)\n end", "def split_simple_body(builder, data, cls)\n gen_cols = data.transpose.map { |col| col.join(\"\\n\") }\n\n builder.tr do\n builder.td(class: 'line-nr') do\n builder << (1..data.length).to_a.join(\"\\n\")\n end\n gen_cols.each do |col|\n builder.td(class: cls) do\n builder << CGI.escape_html(col)\n end\n end\n end\n end", "def initialize(generated, expected)\n @generated = CSV.parse((generated || '').lstrip, nil_value: '')\n @expected = CSV.parse((expected || '').lstrip, nil_value: '')\n\n @gen_headers, *@generated = @generated\n @gen_headers ||= []\n @exp_headers, *@expected = @expected\n @exp_headers ||= []\n\n @simplified_table = @generated.length > 100 || @expected.length > 100\n\n @gen_header_indices, @exp_header_indices, @gen_headers, @exp_headers, @combined_headers = diff_header_indices(@gen_headers, @exp_headers)\n\n @diff = unless @simplified_table\n Diff::LCS.sdiff(@generated, @expected).map do |chunk|\n gen_result = chunk.old_element || []\n exp_result = chunk.new_element || []\n if chunk.action == '!'\n gen_result, exp_result = diff_arrays(gen_result, exp_result)\n else\n gen_result = gen_result.map { |el| CGI.escape_html el }\n exp_result = exp_result.map { |el| CGI.escape_html el }\n end\n Diff::LCS::ContextChange.new(chunk.action, chunk.old_position, gen_result, chunk.new_position, exp_result)\n end\n end\n end", "def build_report_body\n draw_table(data, :width => 700)\n end", "def rows\n render 'rows.html'\n end", "def show_table\n build_html do\n if upd_apar_defs.length == 0\n div.upd_apar_defs do\n span \"Did not find any items matching request\"\n end\n else\n table.upd_apar_defs do\n thead do\n tr do\n th '#'\n [ \"Defect\", \"Apar\", \"PTF\", \"Abstract\",\n \"LPP\", \"VRMF\", \"Version\", \"Service Pack\" ].each do |header_label|\n th class: \"upd_apar_def-#{header_label.gsub(\" \", \"_\").downcase}\" do\n span class: \"upd_apar_defs_header_span\" do\n text header_label\n span class: \"sort sortable\" do\n end\n end\n end\n end\n end\n end\n tbody do\n # upd_apar_defs.each_with_index { |o, i| show_upd_apar_def(o,i) }\n end\n end\n end\n end\n end", "def write_comparison_table(app, cm)\n \n row_num = 0 # TODO use same numbering for all rows\n \n [['context_1', 'context_2'], ['context_1', 'context_3']].each{|ctx_set|\n \n cm.add_row(\n {:text=>(cm.html?)?'<strong>Scenarios:</strong>':'Scenarios:', :colspan=>2},\n {:text=>ctx_set.inspect.to_s, :colspan=>20}\n )\n \n cm.add_row({:text=>'', :colspan=>4}, {:text=>'IIS', :colspan=>6}, {:text=>'Apache', :colspan=>9})\n cm.add_row({:text=>'', :colspan=>4}, {:text=>'Load Agents', :colspan=>2}, {:text=>'No WinCache', :colspan=>3}, {:text=>'WinCache', :colspan=>3}, {:text=>'No APC', :colspan=>3}, {:text=>'APC', :colspan=>3}, {:text=>'APC w/ IGBinary', :colspan=>3})\n cm.add_row('', 'OS', 'Physical', 'Virtual', 'Base', 'Test', 'Gain', 'Base', 'Test', 'Gain', 'Base', 'Test', 'Gain', 'Base', 'Test', 'Gain')\n \n cm.add_row('1', 'Win 2003 x86 SP2', '2', '8', '50', '100', '50%', '100', '50', '50%', '50', '100', '50%', '100', '50', '50%')\n \n cm.add_row(\n {:text=>(cm.html?)?'<strong>Windows INI:</strong>':'INI:', :colspan=>2},\n # TODO show INI\n {:text=>ctx_set.inspect.to_s, :colspan=>20}\n )\n cm.add_row(\n {:text=>(cm.html?)?'<strong>Linux INI:</strong>':'INI:', :colspan=>2},\n # TODO show INI\n {:text=>ctx_set.inspect.to_s, :colspan=>20}\n )\n \n \n \n }\n \n return cm\n end", "def to_html\n html = \"<table class='bodyTable'><thead><th>Name</th><th>Lines</th><th>LOC</th><th>Classes</th><th>Methods</th><th>M/C</th><th>LOC/M</th></thead><tbody>\"\n i = 0\n results = self.result.split(/$/)\n bottom = 4 if ENV[\"RAILS_ROOT\"].present?\n bottom ||= 3\n top = bottom\n while !results[bottom].nil? and results[bottom][0..1] != \"\\n+\" do\n bottom = bottom + 1\n end\n lines = results[top..bottom-1]\n lines.each do |line|\n elements = line.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n html = html + \"<td style='text-align: right;'>#{elements[2]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[3]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[4]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[5]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[6]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[7]}</td>\"\n html = html + \"</tr>\"\n i = i + 1\n end\n total = results[bottom + 1]\n elements = total.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n [2,3,4,5,6,7].each do |j|\n html = html + \"<td style='text-align: right;'><strong>#{elements[j]}</strong></td>\"\n end\n html = html + \"</tr>\"\n html = html + \"</tbody></table>\"\n extra = results[bottom + 3]\n elements = extra.split(/:| /)\n @percent = (elements[3].strip.to_f * 100.0) / elements[1].strip.to_f\n return html\n end", "def index\n @reports = Report.order(sort_column + \" \" + sort_diection) \n respond_to do |format|\n format.html\n format.json\n format.csv { send_data text: @clients.to_csv }\n format.xls\n format.pdf {render template: 'reports/reporte', pdf: 'Reporte', layout: 'pdf.html'}# header: { right: 'Página [page] de [topage]' }}\n end\n end", "def build_table (number)\n @main_table.each{|child| @main_table.remove(child)}\n if number<=3\n @main_table.n_columns = number\n @main_table.n_rows = 1\n i = 0\n while i<number\n text = @texts[i]\n scrolled = @scrolls[i]\n if text == nil\n scrolled = Gtk::ScrolledWindow.new\n text = Gtk::TextView.new\n text.name = \"txtNumber#{i+1}\"\n text.editable = false\n scrolled.name = \"scrollNumber#{i+1}\"\n scrolled.add(text)\n scrolled.show_all\n @texts[i] = text\n @scrolls[i] = scrolled\n end\n @main_table.attach(scrolled,i,i+1,0,1)\n @main_table.show_all\n i+=1\n end\n else\n @main_table.n_rows = 2\n @main_table.n_columns = (number+1)/2\n i = 0\n fil = col = 0\n while i<number\n text = @texts[i]\n scrolled = @scrolls[i]\n if text == nil\n scrolled = Gtk::ScrolledWindow.new\n text = Gtk::TextView.new\n text.name = \"txtNumber#{i+1}\"\n scrolled.name = \"scrollNumber#{i+1}\"\n scrolled.add(text)\n scrolled.show_all\n @texts[i] = text\n @scrolls[i] = scrolled\n end\n #Fils the first row. The fil variable acts like a controller. When it changes, the row has changed.\n if (col < @main_table.n_columns && fil == 0)\n @main_table.attach(scrolled,col,col+1,0,1)\n col+=1\n if col==@main_table.n_columns #All the columns have been filled. We change rows\n fil = 1; col = 0 #Restart the columns index\n end\n else #Second row statrs here\n @main_table.attach(scrolled,col,col+1,1,2)\n col+=1\n end\n @main_table.show_all\n i+=1\n end\n end\n end", "def show_tsd_super_table\n @data_list = DataList.find(params[:id])\n @all_tsd_files = JSON.parse(open(\"http://readtsd.herokuapp.com/listnames/json\").read)[\"file_list\"]\n @tsd_file = params[:tsd_file].nil? ? @all_tsd_files[0] : params[:tsd_file]\n render \"tsd_super_tableview\"\n end" ]
[ "0.7004308", "0.6201249", "0.56568396", "0.56285596", "0.55700326", "0.5349006", "0.5320473", "0.5285839", "0.52177036", "0.5211179", "0.5185852", "0.5173145", "0.5152573", "0.51514953", "0.5122979", "0.51103246", "0.5064794", "0.50607324", "0.5060666", "0.50437343", "0.50365657", "0.50286144", "0.5010977", "0.50001365", "0.49960423", "0.49601126", "0.4948589", "0.4929584", "0.49204382", "0.4912959" ]
0.65478545
1
Build one of the two tables of the split table view (see function 'split')
def split_build_table(builder, headers, is_generated_output) builder.table(class: 'split-diff diff csv-diff') do builder.colgroup do builder.col(class: 'line-nr') builder.col(span: headers.length) end builder.thead do if is_generated_output icon_cls = 'mdi-file-account' title = I18n.t('submissions.show.your_output') else icon_cls = 'mdi-file-check' title = I18n.t('submissions.show.expected') end builder.tr do builder.th(class: 'line-nr', title: title) do builder.i(class: %(mdi mdi-18 #{icon_cls})) end builder.th(title, colspan: headers.length) end builder.tr do builder.th(class: 'line-nr') builder << headers.join end end builder.tbody do if @simplified_table if is_generated_output split_simple_body(builder, @generated, 'del') else split_simple_body(builder, @expected, 'ins') end else @diff.each do |chunk| builder.tr do if is_generated_output is_empty, row = old_row(chunk) position = chunk.old_position else is_empty, row = new_row(chunk) position = chunk.new_position end builder << %(<td class="line-nr">#{position + 1 unless is_empty}</td>) builder << row.join end end end end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split\n builder = Builder::XmlMarkup.new\n\n builder.div do\n split_build_table(builder, @gen_headers, true)\n split_build_table(builder, @exp_headers, false)\n end.html_safe\n end", "def slice(table)\n head, body, array_h, array_b = 4.times.map { [] }\n index = 0\n first_column = 0\n second_column = 1\n\n (0...table.original_columns * table.original_rows).each do |col_index|\n row = table.rows[index]\n array_h += [row[first_column]]\n array_b += [row[second_column]]\n\n if col_index % table.original_columns == 2\n head << array_h\n body << array_b\n array_h, array_b = [], []\n end\n index += 1\n end\n [head, body]\n end", "def tables\n @tables ||= {:left => left_table, :right => right_table}\n end", "def apply_split( t1, t2 )\n return self.class.new( t1, t2 )\n end", "def working_items_table\n contract_info_tables = page.all(\"table.table-hover.table-bordered.table-striped\", visible: true)\n unless contract_info_tables[1].nil?\n return Helpers::OpsUiHelper::TableHelper.new(node: contract_info_tables[1])\n end\n Helpers::OpsUiHelper::TableHelper.new(node: contract_info_tables[0])\n end", "def build_table (number)\n @main_table.each{|child| @main_table.remove(child)}\n if number<=3\n @main_table.n_columns = number\n @main_table.n_rows = 1\n i = 0\n while i<number\n text = @texts[i]\n scrolled = @scrolls[i]\n if text == nil\n scrolled = Gtk::ScrolledWindow.new\n text = Gtk::TextView.new\n text.name = \"txtNumber#{i+1}\"\n text.editable = false\n scrolled.name = \"scrollNumber#{i+1}\"\n scrolled.add(text)\n scrolled.show_all\n @texts[i] = text\n @scrolls[i] = scrolled\n end\n @main_table.attach(scrolled,i,i+1,0,1)\n @main_table.show_all\n i+=1\n end\n else\n @main_table.n_rows = 2\n @main_table.n_columns = (number+1)/2\n i = 0\n fil = col = 0\n while i<number\n text = @texts[i]\n scrolled = @scrolls[i]\n if text == nil\n scrolled = Gtk::ScrolledWindow.new\n text = Gtk::TextView.new\n text.name = \"txtNumber#{i+1}\"\n scrolled.name = \"scrollNumber#{i+1}\"\n scrolled.add(text)\n scrolled.show_all\n @texts[i] = text\n @scrolls[i] = scrolled\n end\n #Fils the first row. The fil variable acts like a controller. When it changes, the row has changed.\n if (col < @main_table.n_columns && fil == 0)\n @main_table.attach(scrolled,col,col+1,0,1)\n col+=1\n if col==@main_table.n_columns #All the columns have been filled. We change rows\n fil = 1; col = 0 #Restart the columns index\n end\n else #Second row statrs here\n @main_table.attach(scrolled,col,col+1,1,2)\n col+=1\n end\n @main_table.show_all\n i+=1\n end\n end\n end", "def grab_table(table, space, language, onair, subspace,\n is_moderator: nil, is_focus_group: nil)\n table_id = nil\n table_id = table['id'] if not table.nil?\n if table.nil?\n if is_moderator != false or is_focus_group == true # Free or subspace or focus tables only.\n table = { 'participants' => [],\n 'joining_participants' => [],\n 'space' => space,\n 'language' => language,\n 'onair' => onair,\n 'subspace' => subspace,\n 'is_focus_group' => is_focus_group }\n table_id = get_hangout_id\n end\n end\n\n if not table_id.nil?\n # Add one user to free or subspace or focus table\n time_now = redis.time[0]\n table['joining_participants'].push(time_now)\n table['id'] = table_id\n update_table(table_id, space, table)\n end\n\n table\n end", "def table_of(things,opts={})\n kind = things.first.table_name\n # columns = things.first.visible_columns\n add_class_to_html_options(opts, kind)\n content_tag(\n :table,\n render(:partial => \"/#{kind}/table_row\", :collection => things),\n opts\n )\n end", "def split_old_bin(table, new_table, i, node, node_hash, forwarder); end", "def tabla_flota(list_flota)\n data = Array.new\n encabezado = make_table([ [{content: 'Placa', :width => 100, :size => 7},\n {content: 'Modelo', :width => 100, :size => 7},\n {content: 'Marca', :width => 100, :size => 7},\n {content: 'Año', :width => 60, :size => 7},\n {content: 'Serial de Carroceria', :width => 100, :size => 7}] ])\n table([\n [{content: \"\", :colspan => 7, :border_bottom_width => 0} ],\n [{content: \"\", :colspan => 1, :border_top_width => 0, :border_bottom_width => 0, :width => 30},\n {content: encabezado, :colspan => 5, :width => 460, background_color: 'd7d7d7'},\n {content: \"\", :colspan => 1,:border_top_width => 0, :border_bottom_width => 0, :width => 30}]\n ])\n list_flota.each_with_index do |vehiculos,index|\n data = make_table([ [{content: vehiculos.placa,:width => 100, :size => 7 },\n {content: vehiculos.modelo, :width => 100, :size => 7},\n {content: vehiculos.marca, :width => 100, :size => 7},\n {content: vehiculos.ano.to_s, :width => 60, :size => 7},\n {content: vehiculos.s_carroceria,:width => 100, :size => 7 }] ])\n\n table([\n [{content: \"\", :colspan => 1, :border_top_width => 0, :border_bottom_width => 0, :width => 30},\n {content: data, :colspan => 5, :width => 460},\n {content: \"\", :colspan => 1, :border_top_width => 0, :border_bottom_width => 0, :width => 30} ]\n\n ])\n if cursor <= 40\n table([\n [{content: \"\", :colspan => 7, :border_top_width => 0, :width => 520}]\n ])\n start_new_page\n flota list_flota.slice(index+1,list_flota.length), true if index+1 <= list_flota.length\n return\n end\n end\n\n table([\n [{content: \"\", :colspan => 7, :border_top_width => 0, :width => 520}]\n ])\n\n end", "def create_add_partner_table(options_table2)\n options_table2.raw.each do |row|\n case row[0].downcase\n when 'first name'\n first_name.set row[1]\n when 'last name'\n last_name.set row[1]\n when 'email'\n sleep 1\n email.set row[1]\n when 'date of birth'\n sleep 3\n dob.click\n dob.set row[1]\n sleep 1\n when 'gender'\n gender_dropdown.click\n sleep 2\n gender_select.each do |gen|\n gen.click if gen.text == row[1]\n end\n when 'partner info'\n sleep 2\n partner_information_dropdown.click\n partiner_info_select.each do |pi|\n pi.click if pi.text == row[1]\n end\n end\n end\n end", "def table; end", "def table; end", "def table; end", "def table; end", "def cut_fragments grouped_ops \n show {\n title \"Cut Out Fragments\"\n check \"Take out #{grouped_ops.length} 1.5 mL tubes and label accordingly: #{grouped_ops.map { |op| \"#{op.output(\"Fragment\").item}\" }.to_sentence}\"\n check \"Now, cut out the bands and place them into the 1.5 mL tubes according to the following table:\"\n table grouped_ops.start_table \n .custom_column(heading: \"Gel ID\") { |op| \"#{op.input(FRAGMENT).item}\" }\n .custom_column(heading: \"Row\") { |op| op.input(FRAGMENT).row + 1 }\n .custom_column(heading: \"Column\", checkable: true) { |op| op.input(FRAGMENT).column + 1 }\n .custom_column(heading: \"1.5 mL Tube ID\") { |op| \"#{op.output(FRAGMENT_OUT).item}\" }\n .custom_column(heading: \"Length\") { |op| op.output(FRAGMENT_OUT).sample.properties[\"Length\"] }\n .end_table\n }\n end", "def table_separation\n line = \"#{TABLE_COLUMN_LINE}|#{TABLE_COLUMN_LINE}\".dup\n line << \"|#{TABLE_COLUMN_LINE}\" if header_line_rate?\n line << \"|#{TABLE_COLUMN_LINE}\" if header_branch_rate?\n line << \"\\n\"\n end", "def splice_table(*tables)\n table = tables.shift\n tables.each do |new_table|\n table.each_with_index do |row, i|\n table[i] = row + new_table[i]\n end\n end\n table\nend", "def extract_tables(main)\n sections = main.split(\"[End of table] \\n\")\n tables = []\n sections.each do |section|\n flag = false\n table = \"\"\n section.lines do |line|\n flag = true if line =~ /^Table /\n table << line if flag\n end\n tables << table unless table.empty?\n end\n tables\n end", "def create_join_table_ele(filter, all_savings)\n filter.each_with_index do |contract, index|\n JoinTableEleSimulationContract.create(ele_simulation: self, ele_contract: contract, savings: all_savings[index])\n end\n end", "def show_table\n DATABASE.execute(\"SELECT * FROM split_checks;\")\nend", "def partial_table(ary, sep=',')\n indexes = []\n res = \"\"\n ary.each_with_index do |field, i|\n idx = @ocp_solution[:headers].find_index(field)\n if idx then\n indexes << idx\n else\n ary.delete_at i\n end\n end\n res << ary.join(sep) + \"\\n\"\n self.length.times do |i|\n res << indexes.inject([]) {|a,e| a << @ocp_solution[:data][e][i] }.join(sep) + \"\\n\"\n end\n return res\n end", "def render_table(arel)\n return if arel.first.nil?\n partial :table, :locals => {:model => arel.first.class, :arel => arel}\n end", "def bids_table(bids, game, pool_user, left_or_right)\n cells_for_bids = bids.map do |bid|\n if @printable\n bid_cells(bid, left_or_right)\n else\n bid_for_game bid, game, pool_user, cycle('top', 'bottom', :name => 'top_or_bottom')\n end\n end\n reset_cycle('top_or_bottom') unless @printable\n rows = cells_for_bids.map { |bid_cells| content_tag :tr, bid_cells }\n content_tag(:table, rows, :style => \"white-space: nowrap; border-collapse: collapse;\")\n end", "def table (b,rain_fall_type,year,ji,compare)\n if rain_fall_type == \"All\"\n hash_data = ji.map do |el|\n {title:el, field:el, sorter:\"string\", editor:true}\n end\n else\n if compare == \"None\"\n hash_data = [\n {title:\"Year\", field:\"Year\", sorter:\"string\", editor:true},\n {title:rain_fall_type, field:rain_fall_type, sorter:\"string\", editor:true},\n {title:\"Districts\", field:\"Districts\", sorter:\"string\", editor:true}\n ]\n else\n hash_data = [\n # {title:compare, field:compare, sorter:\"string\", editor:true},\n {title:\"Year\", field:\"Year\", sorter:\"string\", editor:true},\n {title:rain_fall_type, field:rain_fall_type, sorter:\"string\", editor:true},\n {title:\"Districts\", field:\"Districts\", sorter:\"string\", editor:true}\n ]\n end\n end\n data = {column: hash_data,data: b}\n return data\n end", "def _table; @table end", "def unified\n builder = Builder::XmlMarkup.new\n builder.table(class: 'unified-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(class: 'line-nr')\n builder.col(span: @combined_headers.length)\n end\n builder.thead do\n builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end", "def label_and_rehydrate\n show do\n title \"Label and rehydrate\"\n\n check \"Label each fragment tube with the ids shown in the Fragment Stock item ids column.\"\n check \"Rehydrate each fragment with the volume of TE shown in the Rehydrate column.\"\n\n table operations.start_table\n .input_sample(INPUT)\n .custom_column(heading: 'Names of inputs') {|op| op.input(\"Lyophilized Fragment\").sample.name}\n .output_item(STOCK)\n .custom_column(heading: \"Rehydrate (uL of TE)\", checkable: true) {|op| op.temporary[:water_vol]}\n .end_table\n end\n end", "def create_between_arm_table\n \t@selected_timepoints = params[:selected_timepoints]\n \t@selected_tp_array = @selected_timepoints.split(\"_\")\n \tsubgroup_id = params[:subgroup_id].nil? ? 0 : params[:subgroup_id]\n \t@subgroup = subgroup_id == 0 ? nil : OutcomeSubgroup.find(subgroup_id)\n \t@outcome_id = params[:outcome_id]\n \t@comparisons = OutcomeDataEntry.create_comparisons(\"between\",@selected_tp_array,@outcome_id,subgroup_id)\n \t@outcome = Outcome.find(@outcome_id)\n \t@project_id = params[:project_id]\n\t\t\n \t#-----------------------------------------\n \t# Data for the entry table\n \t#-----------------------------------------\n \t@outcome_id, @study_id,@extraction_form_id, @selected_tp_array, @timepoints, @OCDEs, \n\t\t@measures, @datapoints, @arms, @comparisons, @comparison_measures, @comparators, \n\t\t@all_comparators, @num_comparators, @comparison_datapoints, @wa_comparisons, @wa_measures, \n\t\t@wa_comparators, @wa_all_comparators, @wa_datapoints, @footnotes = OutcomeDataEntry.get_information_for_entry_table(@outcome,@subgroup,@selected_timepoints)\n\t\t\n\t\n\t render \"/outcome_data_entries/show_entry_table\"\n end", "def tnTableCreation(tableName)\n pk_list = @pkList.join(',')\n pk_list = \"#{pk_list},branch_name,node_name\"\n q = QueryBuilder.create_tbl(tableName, pk_list, \"select #{@pkSelect}, 0 as test_id,''::varchar(30) as node_name, ''::varchar(30) as branch_name, ''::varchar(5) as type from #{@fTable} f where 1 = 0\")\n # pp q\n DBConn.exec(q)\n\n # q=\"ALTER TABLE #{tableName} add column test_id int, add column node_name varchar(30), add column branch_name varchar(30), add column type varchar(5);\"\n # DBConn.exec(q)\n # [email protected](',')\n # # add index\n # q=\"create index ix_#{tableName}t on #{tableName} (#{pk},branch_name);\"\n # pp q\n # DBConn.exec(q)\n end" ]
[ "0.7009416", "0.56848836", "0.56125796", "0.555878", "0.54818606", "0.5472032", "0.5456454", "0.5423256", "0.5380515", "0.53663176", "0.53643316", "0.534272", "0.534272", "0.534272", "0.534272", "0.53099674", "0.52941924", "0.527488", "0.5260239", "0.5258009", "0.52463865", "0.5228339", "0.5227945", "0.5202998", "0.5174949", "0.5173078", "0.5169791", "0.51678216", "0.5160493", "0.51460415" ]
0.6669901
1
Build a simplified version of the unified table body This simplified view combines all rows in a column into 1 row with newlines. The columns are still separate, but the diff is less accurate.
def unified_simple_body(builder) gen_cols = @generated.transpose.map { |col| col.join("\n") } builder.tr do builder.td(class: 'line-nr') do builder << ([email protected]).to_a.join("\n") end builder.td(class: 'line-nr') builder << Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map do |idx| if idx.nil? '<td></td>' else %(<td class="del">#{CGI.escape_html gen_cols[idx]}</td>) end end.join end exp_cols = @expected.transpose.map { |col| col.join("\n") } builder.tr do builder.td(class: 'line-nr') builder.td(class: 'line-nr') do builder << ([email protected]).to_a.join("\n") end builder << Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map do |idx| if idx.nil? '<td></td>' else %(<td class="ins">#{CGI.escape_html exp_cols[idx]}</td>) end end.join end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unified\n builder = Builder::XmlMarkup.new\n builder.table(class: 'unified-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(class: 'line-nr')\n builder.col(span: @combined_headers.length)\n end\n builder.thead do\n builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end", "def build_table_body\n body =\n if data.column_names && !data.column_names.empty?\n data\n else\n data[1..-1]\n end\n body.each { |row| build_md_row(output, row) }\n end", "def build_table_body\n data.each_with_index do |row, i|\n output << \",\\n\" if i > 0 \n build_row(row)\n end\n output << \"\\n\"\n end", "def split_simple_body(builder, data, cls)\n gen_cols = data.transpose.map { |col| col.join(\"\\n\") }\n\n builder.tr do\n builder.td(class: 'line-nr') do\n builder << (1..data.length).to_a.join(\"\\n\")\n end\n gen_cols.each do |col|\n builder.td(class: cls) do\n builder << CGI.escape_html(col)\n end\n end\n end\n end", "def to_s\n string_to_add = \" with cells: \"\n @reconstructed_table.each do |row|\n string_to_add += \"\\n\\t#{row}\"\n end\n super + string_to_add\n end", "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end", "def to_s_v1\n output = \"+\" + \"---+\" * columns + \"\\n\"\n\n each_row do |row|\n top = \"|\"\n bottom = \"+\"\n\n row.each do |cell|\n cell = Cell.new(-1, -1) unless cell\n\n body = \" \" # <-- that's THREE (3) spaces!\n east_boundary = (cell.linked?(cell.east) ? \" \" : \"|\")\n top << body << east_boundary\n\n # three spaces below, too >>-------------->> >...<\n south_boundary = (cell.linked?(cell.south) ? \" \" : \"---\")\n corner = \"+\"\n bottom << south_boundary << corner\n end\n\n output << top << \"\\n\"\n output << bottom << \"\\n\"\n end\n\n output\n end", "def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n new_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n new_rows << nil if include_header_row? || grp_k.positive?\n # Compute group body\n grp_col = {}\n grp.each_with_index do |row, grp_row_k|\n new_row = {}\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n table.headers.each do |h|\n grp_col[h] ||= Column.new(header: h)\n grp_col[h] << row[h]\n istruct = format_at[location][h]\n new_row[h] = [row[h], format_cell(row[h], istruct,\n decorate: decorate)]\n end\n new_rows << [location, new_row]\n tbl_row_k += 1\n end\n # Compute group footers\n gfooters.each_pair do |label, gfooter|\n # Mark the beginning of a group footer\n new_rows << nil\n gfoot_row = {}\n first_h = nil\n grp_col.each_pair do |h, col|\n first_h ||= h\n gfoot_row[h] =\n if gfooter[h]\n val = col.send(gfooter[h])\n istruct = format_at[:gfooter][h]\n [val, format_cell(val, istruct, decorate: decorate)]\n else\n [nil, '']\n end\n end\n if gfoot_row[first_h].last.blank?\n istruct = format_at[:gfooter][first_h]\n gfoot_row[first_h] =\n [label, format_cell(label, istruct, decorate: decorate)]\n end\n new_rows << [:gfooter, gfoot_row]\n end\n end\n new_rows\n end", "def to_s_v2\n output = \"+\" + \"---+\" * columns + \"\\n\"\n\n each_row do |row|\n top = \"|\"\n bottom = \"+\"\n\n row.each do |cell|\n cell = Cell.new(-1, -1) unless cell\n\n body = \" #{contents_of(cell)} \"\n east_boundary = (cell.linked?(cell.east) ? \" \" : \"|\")\n top << body << east_boundary\n\n south_boundary = (cell.linked?(cell.south) ? \" \" : \"---\")\n corner = \"+\"\n bottom << south_boundary << corner\n end\n\n output << top << \"\\n\"\n output << bottom << \"\\n\"\n end\n\n output\n end", "def big_table\n # suppress_output\n # header title: 'Monkey Butt the wide, and annoying', width: 80, align: 'left', rule: false, color: 'blue', bold: false, timestamp: false\n table border: true do\n row color: 'blue' do\n column 'Player', width: 20, align: 'left', color: 'green'\n column 'Overall % correct', width: 30, align: 'left', color: 'green'\n end\n User.all.each do |user|\n row color: 'blue' do\n # binding.pry\n column \"#{user.name}\", width: 20, align: 'left', color: 'green'\n column \"#{user.total_average}%\", width: 20, align: 'left', color: 'green'\n end\n end\n # column 'ADDRESS', width: 30, padding: 5\n # column 'CITY', width: 15\n # end\n # row color: 'green', bold: true do\n # column 'caeser'\n # column '1 Appian Way'\n # column 'Rome'\n # end\n # row do\n # column 'Richard Feynman'\n # column '1 Golden Gate'\n # column 'Quantum Field'\n end\n\n # return capture_output\n end", "def output\n # If there are neither headers nor any rows in the table, return an\n # empty string.\n return '' if table.empty? && table.headers.empty?\n\n # This results in a hash of two-element arrays. The key\n # is the header and the value is an array of the header and formatted\n # header. We do the latter so the structure parallels the structure for\n # rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n if loc_row.nil?\n result += hline(widths)\n next\n end\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end", "def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end", "def generate_html\n\n # Return our to_string function if we aren't reconstructed yet\n return self.to_s if !@reconstructed_table\n\n # Create an HTML table\n html = \"<table style='border:1px solid black'>\\n\";\n\n # Loop over each row and create a new table row\n @reconstructed_table.each do |row|\n html += \"<tr>\\n\";\n\n # Loop over each column and place the cell value into a td\n row.each do |column|\n to_show = column\n to_show = \"&nbsp;\" if to_show == \"\"\n html += \"<td style='border:1px solid black'>#{to_show}</td>\\n\";\n end\n\n # Close the row\n html += \"</tr>\\n\";\n end\n\n # Close the table\n html += \"</table>\\n\";\n return html\n end", "def build_up_cells(cells, row)\n partial_cell = parse_row_to_partial_cell(row)\n\n partial_cell.each.with_index do |cell, index|\n if cells[index]\n cells[index] += \"#{cell.strip} \"\n else\n cells[index] = \"#{cell.strip} \"\n end\n end\n\n return cells\n end", "def to_s_corrected\n @cells.map { |row| row.join(' ') }.join(\"\\n\")\n end", "def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n out_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # NB: grp is an array of hashes, one for each row in the group.\n #\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n out_rows << nil if include_header_row? || grp_k.positive?\n # Format group body rows\n grp.each_with_index do |row, grp_row_k|\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n\n out_row = {}\n row.each_pair do |h, v|\n istruct = format_at[location][h]\n out_row[h] = [row[h], format_cell(row[h], istruct, decorate: decorate)]\n end\n out_rows << [location, out_row]\n tbl_row_k += 1\n end\n # Format group footers\n gfooters.each_pair do |label, gfooter|\n out_rows << nil\n gfoot_row = Hash.new([nil, ''])\n gfooter.to_h(grp_k).each_pair do |h, v|\n istruct = format_at[:gfooter][h]\n gfoot_row[h] = [v, format_cell(v, istruct, decorate: decorate)]\n end\n out_rows << [:gfooter, gfoot_row]\n end\n end\n out_rows\n end", "def to_s\n \n # Determine the column width\n col_width = data.last.last.to_s.length\n \n # Determine the table width\n table_width = ( col_width + 1 ) * data.length + 1\n \n # Convert 2D Array to String\n data.map { |row| '|' + row.map { |val| val.to_s.ljust( col_width ) }.join('|') + '|' }.join(\"\\n#{ '-' * table_width }\\n\")\n \n end", "def to_s\n # The widest item in the table is used to set the width of all the\n # columns.\n item_width = widest_item\n row_label_width = row_labels.map { |label| label.to_s.jlength }.max\n # Enumerate rows prepending column labels.\n ([col_labels] + self).zip([\" \"] + row_labels).map do |row, row_label|\n # Enumerate row items prepending row labels.\n ([sprintf(\"%-#{row_label_width}s\", row_label)] + row.map do |item|\n # Center each item in a space as wide as the widest column.\n item_to_s(item).center(item_width)\n end).join(\" \").rstrip\n end.join(\"\\n\")\n end", "def render_table(data, separator = \" # \")\n column_width = data.group_by do |row|\n row.first.size\n end.max.first\n \"\".tap do |output|\n data.each do |row|\n output << \"%-#{column_width}s#{separator}%s\\n\" % row\n end\n end\n end", "def row_to_s(row) # :nodoc:\n line = ' ' * indent\n last_cell = nil\n last_idx = nil\n row.each_with_index { |cell, idx|\n if (idx != 0)\n line << pad(' ', last_cell.to_s, last_idx)\n end\n # Limit wide cells\n if colprops[idx]['MaxChar']\n last_cell = cell.to_s[0..colprops[idx]['MaxChar'].to_i]\n line << style_table_field(last_cell, idx)\n else\n line << style_table_field(cell.to_s, idx)\n last_cell = cell\n end\n last_idx = idx\n }\n\n return line + \"\\n\"\n end", "def to_table\n result = Mortadella::Horizontal.new headers: @commit_attributes, dry: %w[BRANCH LOCATION]\n main_commits = @commits.delete 'main'\n main_commits.try(:keys).try(:each) do |sha|\n main_commits[sha]['LOCATION'] = main_commits[sha]['LOCATION'].to_sentence\n result << main_commits[sha].values\n end\n @commits.values.each do |branch_commits|\n branch_commits.values.each do |commit|\n commit['LOCATION'] = commit['LOCATION'].to_sentence\n result << commit.values\n end\n end\n result.table\n end", "def run\n migrated_body = @body.dup\n migrated_body.gsub!(/\\|[\\t ]*\\r?[\\n]/, \"|\\n\")\n migrated_body\n end", "def output\n # This results in a hash of two-element arrays. The key is the header and\n # the value is an array of the header and formatted header. We do the\n # latter so the structure parallels the structure for rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n result += hline(widths) if loc_row.nil?\n next if loc_row.nil?\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end", "def format_html\n formatted = \"<table summary=\\\"Tide tables with columns for time of day and tide height (in meters).\\\">\\n\\t<thead>\\n\\t\\t<tr><th scope=\\\"col\\\">Time</th><th scope=\\\"col\\\">Height</th></tr>\\n\\t</thead>\\n\"\n last_date = nil\n to_csv.each_line do |row|\n row = row.chomp.split(',')\n if row[0] != last_date\n formatted += \"\\t</tbody>\\n\" unless last_date.nil?\n formatted += \"\\t<tbody>\\n\\t\\t<tr><th scope=\\\"rowgroup\\\" colspan=\\\"2\\\">#{row[0]}</th></tr>\\n\"\n last_date = row[0]\n end\n formatted += \"\\t\\t<tr><td>#{row[1]}</td><td>#{row[2]}m</td></tr>\\n\"\n end\n formatted += \"\\t</tbody>\\n</table>\\n\"\n formatted\n end", "def table_separation\n line = \"#{TABLE_COLUMN_LINE}|#{TABLE_COLUMN_LINE}\".dup\n line << \"|#{TABLE_COLUMN_LINE}\" if header_line_rate?\n line << \"|#{TABLE_COLUMN_LINE}\" if header_branch_rate?\n line << \"\\n\"\n end", "def to_s\n\t\t# top border\n\t\toutput = \"+\" + \"---+\" * columns + \"\\n\"\n\n\t\teach_row do |row|\n\t\t\ttop = \"|\"\n\t\t\tbottom = \"+\"\n\n\t\t\trow.each do |cell|\n\t\t\t\t# create a dummy, if no cell present (used by special geometries)\n\t\t\t\tcell = Cell.new(-1, -1) unless cell\n\n\t\t\t\tbody = \" \" # 3 spaces\n\t\t\t\teast_boundary = (cell.linked?(cell.east) ? \" \" : \"|\")\n\t\t\t\ttop << body << east_boundary\n\n\t\t\t\tsouth_boundary = (cell.linked?(cell.south) ? \" \" : \"---\")\n\t\t\t\tcorner = \"+\"\n\t\t\t\tbottom << south_boundary << corner\n\t\t\tend\n\n\t\t\toutput << top << \"\\n\"\n\t\t\toutput << bottom << \"\\n\"\n\t\tend\n\n\t\toutput\n\tend", "def gentbl(t)\n colszs=[]\n t.each do |line|\n line.size.times do |i|\n elem = line[i]\n sz = elem.to_s.size\n colszs[i] = sz if !colszs[i] or colszs[i] < sz \n end \n end\n out = \"\"\n t.each do |line|\n line.size.times do |i|\n elem = line[i].to_s\n col = \" \" * colszs[i]\n elem.size.times do |j|\n col[j] = elem[j]\n end\n out += col + \" \"\n end\n out += \"\\n\"\n end\n return out\nend", "def table_content\n table activity_rows do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = ['DDDDDD', 'FFFFFF']\n self.column_widths = [65, 175, 75, 85, 75, 65]\n style(column(3), align: :right)\n style(column(4), align: :right)\n style(column(5), align: :right)\n end\n end", "def make_table(rows, sep_x = \"=\", sep_y = \"|\", sep_i = \"x\")\n text_rows = rows.select{ |r| r.is_a?(Array) }\n count = text_rows.map(&:size).max\n rows.each{ |r| if r.is_a?(Array) then r << \"\" while r.size < count end }\n widths = (0..count - 1).map{ |c| text_rows.map{ |r| r[c].to_s.length }.max }\n sep = widths.map{ |w| sep_i + sep_x * (w + 2) }.join + sep_i + \"\\n\"\n table = sep.dup\n rows.each{ |r|\n if r == :sep\n table << sep\n else\n r.each_with_index{ |s, i|\n table << sep_y + \" \" + (s.is_a?(Numeric) ? s.to_s.rjust(widths[i], \" \") : s.to_s.ljust(widths[i], \" \")) + \" \"\n }\n table << sep_y + \"\\n\"\n end\n }\n table << sep\n return table\nend", "def to_html\n html = \"<table class='bodyTable'><thead><th>Name</th><th>Lines</th><th>LOC</th><th>Classes</th><th>Methods</th><th>M/C</th><th>LOC/M</th></thead><tbody>\"\n i = 0\n results = self.result.split(/$/)\n bottom = 4 if ENV[\"RAILS_ROOT\"].present?\n bottom ||= 3\n top = bottom\n while !results[bottom].nil? and results[bottom][0..1] != \"\\n+\" do\n bottom = bottom + 1\n end\n lines = results[top..bottom-1]\n lines.each do |line|\n elements = line.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n html = html + \"<td style='text-align: right;'>#{elements[2]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[3]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[4]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[5]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[6]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[7]}</td>\"\n html = html + \"</tr>\"\n i = i + 1\n end\n total = results[bottom + 1]\n elements = total.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n [2,3,4,5,6,7].each do |j|\n html = html + \"<td style='text-align: right;'><strong>#{elements[j]}</strong></td>\"\n end\n html = html + \"</tr>\"\n html = html + \"</tbody></table>\"\n extra = results[bottom + 3]\n elements = extra.split(/:| /)\n @percent = (elements[3].strip.to_f * 100.0) / elements[1].strip.to_f\n return html\n end" ]
[ "0.7234448", "0.6947831", "0.69122547", "0.6492349", "0.64286786", "0.62928003", "0.62743044", "0.61191356", "0.6065495", "0.6048436", "0.60426545", "0.60366195", "0.6035253", "0.599704", "0.5990995", "0.5968515", "0.5957089", "0.5931741", "0.5895767", "0.588607", "0.5869061", "0.5857981", "0.5828909", "0.57773787", "0.57568854", "0.5748022", "0.57467926", "0.57126087", "0.5708198", "0.56958693" ]
0.7181176
1
Build a simplified version of the split table body This simplified view combines all rows in a column into 1 row with newlines. The columns are still separate, but the diff is less accurate.
def split_simple_body(builder, data, cls) gen_cols = data.transpose.map { |col| col.join("\n") } builder.tr do builder.td(class: 'line-nr') do builder << (1..data.length).to_a.join("\n") end gen_cols.each do |col| builder.td(class: cls) do builder << CGI.escape_html(col) end end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end", "def build_table_body\n data.each_with_index do |row, i|\n output << \",\\n\" if i > 0 \n build_row(row)\n end\n output << \"\\n\"\n end", "def unified_simple_body(builder)\n gen_cols = @generated.transpose.map { |col| col.join(\"\\n\") }\n builder.tr do\n builder.td(class: 'line-nr') do\n builder << ([email protected]).to_a.join(\"\\n\")\n end\n builder.td(class: 'line-nr')\n\n builder << Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map do |idx|\n if idx.nil?\n '<td></td>'\n else\n %(<td class=\"del\">#{CGI.escape_html gen_cols[idx]}</td>)\n end\n end.join\n end\n\n exp_cols = @expected.transpose.map { |col| col.join(\"\\n\") }\n builder.tr do\n builder.td(class: 'line-nr')\n builder.td(class: 'line-nr') do\n builder << ([email protected]).to_a.join(\"\\n\")\n end\n\n builder << Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map do |idx|\n if idx.nil?\n '<td></td>'\n else\n %(<td class=\"ins\">#{CGI.escape_html exp_cols[idx]}</td>)\n end\n end.join\n end\n end", "def unified\n builder = Builder::XmlMarkup.new\n builder.table(class: 'unified-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(class: 'line-nr')\n builder.col(span: @combined_headers.length)\n end\n builder.thead do\n builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end", "def build_table_body\n body =\n if data.column_names && !data.column_names.empty?\n data\n else\n data[1..-1]\n end\n body.each { |row| build_md_row(output, row) }\n end", "def table_separation\n line = \"#{TABLE_COLUMN_LINE}|#{TABLE_COLUMN_LINE}\".dup\n line << \"|#{TABLE_COLUMN_LINE}\" if header_line_rate?\n line << \"|#{TABLE_COLUMN_LINE}\" if header_branch_rate?\n line << \"\\n\"\n end", "def split\n builder = Builder::XmlMarkup.new\n\n builder.div do\n split_build_table(builder, @gen_headers, true)\n split_build_table(builder, @exp_headers, false)\n end.html_safe\n end", "def run\n migrated_body = @body.dup\n migrated_body.gsub!(/\\|[\\t ]*\\r?[\\n]/, \"|\\n\")\n migrated_body\n end", "def add_divider_row_to_table\n table << \" -\"\n size.times { table << '-----' }\n table << \"\\n\"\n end", "def render_table(data, separator = \" # \")\n column_width = data.group_by do |row|\n row.first.size\n end.max.first\n \"\".tap do |output|\n data.each do |row|\n output << \"%-#{column_width}s#{separator}%s\\n\" % row\n end\n end\n end", "def partial_table(ary, sep=',')\n indexes = []\n res = \"\"\n ary.each_with_index do |field, i|\n idx = @ocp_solution[:headers].find_index(field)\n if idx then\n indexes << idx\n else\n ary.delete_at i\n end\n end\n res << ary.join(sep) + \"\\n\"\n self.length.times do |i|\n res << indexes.inject([]) {|a,e| a << @ocp_solution[:data][e][i] }.join(sep) + \"\\n\"\n end\n return res\n end", "def to_s_v1\n output = \"+\" + \"---+\" * columns + \"\\n\"\n\n each_row do |row|\n top = \"|\"\n bottom = \"+\"\n\n row.each do |cell|\n cell = Cell.new(-1, -1) unless cell\n\n body = \" \" # <-- that's THREE (3) spaces!\n east_boundary = (cell.linked?(cell.east) ? \" \" : \"|\")\n top << body << east_boundary\n\n # three spaces below, too >>-------------->> >...<\n south_boundary = (cell.linked?(cell.south) ? \" \" : \"---\")\n corner = \"+\"\n bottom << south_boundary << corner\n end\n\n output << top << \"\\n\"\n output << bottom << \"\\n\"\n end\n\n output\n end", "def to_s\n string_to_add = \" with cells: \"\n @reconstructed_table.each do |row|\n string_to_add += \"\\n\\t#{row}\"\n end\n super + string_to_add\n end", "def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n new_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n new_rows << nil if include_header_row? || grp_k.positive?\n # Compute group body\n grp_col = {}\n grp.each_with_index do |row, grp_row_k|\n new_row = {}\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n table.headers.each do |h|\n grp_col[h] ||= Column.new(header: h)\n grp_col[h] << row[h]\n istruct = format_at[location][h]\n new_row[h] = [row[h], format_cell(row[h], istruct,\n decorate: decorate)]\n end\n new_rows << [location, new_row]\n tbl_row_k += 1\n end\n # Compute group footers\n gfooters.each_pair do |label, gfooter|\n # Mark the beginning of a group footer\n new_rows << nil\n gfoot_row = {}\n first_h = nil\n grp_col.each_pair do |h, col|\n first_h ||= h\n gfoot_row[h] =\n if gfooter[h]\n val = col.send(gfooter[h])\n istruct = format_at[:gfooter][h]\n [val, format_cell(val, istruct, decorate: decorate)]\n else\n [nil, '']\n end\n end\n if gfoot_row[first_h].last.blank?\n istruct = format_at[:gfooter][first_h]\n gfoot_row[first_h] =\n [label, format_cell(label, istruct, decorate: decorate)]\n end\n new_rows << [:gfooter, gfoot_row]\n end\n end\n new_rows\n end", "def to_html\n html = \"<table class='bodyTable'><thead><th>Name</th><th>Lines</th><th>LOC</th><th>Classes</th><th>Methods</th><th>M/C</th><th>LOC/M</th></thead><tbody>\"\n i = 0\n results = self.result.split(/$/)\n bottom = 4 if ENV[\"RAILS_ROOT\"].present?\n bottom ||= 3\n top = bottom\n while !results[bottom].nil? and results[bottom][0..1] != \"\\n+\" do\n bottom = bottom + 1\n end\n lines = results[top..bottom-1]\n lines.each do |line|\n elements = line.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n html = html + \"<td style='text-align: right;'>#{elements[2]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[3]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[4]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[5]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[6]}</td>\"\n html = html + \"<td style='text-align: right;'>#{elements[7]}</td>\"\n html = html + \"</tr>\"\n i = i + 1\n end\n total = results[bottom + 1]\n elements = total.split(/\\|/)\n html = html + \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}'>\"\n html = html + \"<td><strong>#{elements[1]}</strong></td>\"\n [2,3,4,5,6,7].each do |j|\n html = html + \"<td style='text-align: right;'><strong>#{elements[j]}</strong></td>\"\n end\n html = html + \"</tr>\"\n html = html + \"</tbody></table>\"\n extra = results[bottom + 3]\n elements = extra.split(/:| /)\n @percent = (elements[3].strip.to_f * 100.0) / elements[1].strip.to_f\n return html\n end", "def big_table\n # suppress_output\n # header title: 'Monkey Butt the wide, and annoying', width: 80, align: 'left', rule: false, color: 'blue', bold: false, timestamp: false\n table border: true do\n row color: 'blue' do\n column 'Player', width: 20, align: 'left', color: 'green'\n column 'Overall % correct', width: 30, align: 'left', color: 'green'\n end\n User.all.each do |user|\n row color: 'blue' do\n # binding.pry\n column \"#{user.name}\", width: 20, align: 'left', color: 'green'\n column \"#{user.total_average}%\", width: 20, align: 'left', color: 'green'\n end\n end\n # column 'ADDRESS', width: 30, padding: 5\n # column 'CITY', width: 15\n # end\n # row color: 'green', bold: true do\n # column 'caeser'\n # column '1 Appian Way'\n # column 'Rome'\n # end\n # row do\n # column 'Richard Feynman'\n # column '1 Golden Gate'\n # column 'Quantum Field'\n end\n\n # return capture_output\n end", "def drop_left\n tbl = self.class.new(\n 'Columns' => Array.new(self.rows.count+1,' '),\n 'Header' => self.header,\n 'Indent' => self.indent)\n (self.columns.count+1).times do |ti|\n row = self.rows.map {|r| r[ti]}.unshift(self.columns[ti]).flatten\n # insert our col|row break. kind of hackish\n row[1] = \"| #{row[1]}\" unless row.all? {|e| e.nil? || e.empty?}\n tbl << row\n end\n return tbl\n end", "def gentbl(t)\n colszs=[]\n t.each do |line|\n line.size.times do |i|\n elem = line[i]\n sz = elem.to_s.size\n colszs[i] = sz if !colszs[i] or colszs[i] < sz \n end \n end\n out = \"\"\n t.each do |line|\n line.size.times do |i|\n elem = line[i].to_s\n col = \" \" * colszs[i]\n elem.size.times do |j|\n col[j] = elem[j]\n end\n out += col + \" \"\n end\n out += \"\\n\"\n end\n return out\nend", "def parse_table\n return false unless after_block_boundary?\n\n saved_pos = @src.save_pos\n orig_pos = @src.pos\n table = new_block_el(:table, nil, nil, alignment: [], location: @src.current_line_number)\n leading_pipe = (@src.check(TABLE_LINE) =~ /^\\s*\\|/)\n @src.scan(TABLE_SEP_LINE)\n\n rows = []\n has_footer = false\n columns = 0\n\n add_container = lambda do |type, force|\n if !has_footer || type != :tbody || force\n cont = Element.new(type)\n cont.children, rows = rows, []\n table.children << cont\n end\n end\n\n until @src.eos?\n break unless @src.check(TABLE_LINE)\n if @src.scan(TABLE_SEP_LINE)\n if rows.empty?\n # nothing to do, ignoring multiple consecutive separator lines\n elsif table.options[:alignment].empty? && !has_footer\n add_container.call(:thead, false)\n table.options[:alignment] = @src[1].scan(TABLE_HSEP_ALIGN).map do |left, right|\n (left.empty? && right.empty? && :default) || (right.empty? && :left) ||\n (left.empty? && :right) || :center\n end\n else # treat as normal separator line\n add_container.call(:tbody, false)\n end\n elsif @src.scan(TABLE_FSEP_LINE)\n add_container.call(:tbody, true) unless rows.empty?\n has_footer = true\n elsif @src.scan(TABLE_ROW_LINE)\n trow = Element.new(:tr)\n\n # parse possible code spans on the line and correctly split the line into cells\n env = save_env\n cells = []\n @src[1].split(/(<code.*?>.*?<\\/code>)/).each_with_index do |str, i|\n if i.odd?\n (cells.empty? ? cells : cells.last) << str\n else\n reset_env(src: Kramdown::Utils::StringScanner.new(str, @src.current_line_number))\n root = Element.new(:root)\n parse_spans(root, nil, [:codespan])\n\n root.children.each do |c|\n if c.type == :raw_text\n f, *l = c.value.split(/(?<!\\\\)\\|/, -1).map {|t| t.gsub(/\\\\\\|/, '|') }\n (cells.empty? ? cells : cells.last) << f\n cells.concat(l)\n else\n delim = (c.value.scan(/`+/).max || '') + '`'\n tmp = +\"#{delim}#{' ' if delim.size > 1}#{c.value}#{' ' if delim.size > 1}#{delim}\"\n (cells.empty? ? cells : cells.last) << tmp\n end\n end\n end\n end\n restore_env(env)\n\n cells.shift if leading_pipe && cells.first.strip.empty?\n cells.pop if cells.last.strip.empty?\n cells.each do |cell_text|\n tcell = Element.new(:td)\n tcell.children << Element.new(:raw_text, cell_text.strip)\n trow.children << tcell\n end\n columns = [columns, cells.length].max\n rows << trow\n else\n break\n end\n end\n\n unless before_block_boundary?\n @src.revert_pos(saved_pos)\n return false\n end\n\n # Parse all lines of the table with the code span parser\n env = save_env\n l_src = ::Kramdown::Utils::StringScanner.new(extract_string(orig_pos...(@src.pos - 1), @src),\n @src.current_line_number)\n reset_env(src: l_src)\n root = Element.new(:root)\n parse_spans(root, nil, [:codespan, :span_html])\n restore_env(env)\n\n # Check if each line has at least one unescaped pipe that is not inside a code span/code\n # HTML element\n # Note: It doesn't matter that we parse *all* span HTML elements because the row splitting\n # algorithm above only takes <code> elements into account!\n pipe_on_line = false\n while (c = root.children.shift)\n next unless (lines = c.value)\n lines = lines.split(\"\\n\")\n if c.type == :codespan\n if lines.size > 2 || (lines.size == 2 && !pipe_on_line)\n break\n elsif lines.size == 2 && pipe_on_line\n pipe_on_line = false\n end\n else\n break if lines.size > 1 && !pipe_on_line && lines.first !~ /^#{TABLE_PIPE_CHECK}/o\n pipe_on_line = (lines.size > 1 ? false : pipe_on_line) || (lines.last =~ /^#{TABLE_PIPE_CHECK}/o)\n end\n end\n @src.revert_pos(saved_pos) and return false unless pipe_on_line\n\n add_container.call(has_footer ? :tfoot : :tbody, false) unless rows.empty?\n\n if table.children.none? {|el| el.type == :tbody }\n warning(\"Found table without body on line #{table.options[:location]} - ignoring it\")\n @src.revert_pos(saved_pos)\n return false\n end\n\n # adjust all table rows to have equal number of columns, same for alignment defs\n table.children.each do |kind|\n kind.children.each do |row|\n (columns - row.children.length).times do\n row.children << Element.new(:td)\n end\n end\n end\n if table.options[:alignment].length > columns\n table.options[:alignment] = table.options[:alignment][0...columns]\n else\n table.options[:alignment] += [:default] * (columns - table.options[:alignment].length)\n end\n\n @tree.children << table\n\n true\n end", "def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n out_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # NB: grp is an array of hashes, one for each row in the group.\n #\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n out_rows << nil if include_header_row? || grp_k.positive?\n # Format group body rows\n grp.each_with_index do |row, grp_row_k|\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n\n out_row = {}\n row.each_pair do |h, v|\n istruct = format_at[location][h]\n out_row[h] = [row[h], format_cell(row[h], istruct, decorate: decorate)]\n end\n out_rows << [location, out_row]\n tbl_row_k += 1\n end\n # Format group footers\n gfooters.each_pair do |label, gfooter|\n out_rows << nil\n gfoot_row = Hash.new([nil, ''])\n gfooter.to_h(grp_k).each_pair do |h, v|\n istruct = format_at[:gfooter][h]\n gfoot_row[h] = [v, format_cell(v, istruct, decorate: decorate)]\n end\n out_rows << [:gfooter, gfoot_row]\n end\n end\n out_rows\n end", "def make_table(rows, sep_x = \"=\", sep_y = \"|\", sep_i = \"x\")\n text_rows = rows.select{ |r| r.is_a?(Array) }\n count = text_rows.map(&:size).max\n rows.each{ |r| if r.is_a?(Array) then r << \"\" while r.size < count end }\n widths = (0..count - 1).map{ |c| text_rows.map{ |r| r[c].to_s.length }.max }\n sep = widths.map{ |w| sep_i + sep_x * (w + 2) }.join + sep_i + \"\\n\"\n table = sep.dup\n rows.each{ |r|\n if r == :sep\n table << sep\n else\n r.each_with_index{ |s, i|\n table << sep_y + \" \" + (s.is_a?(Numeric) ? s.to_s.rjust(widths[i], \" \") : s.to_s.ljust(widths[i], \" \")) + \" \"\n }\n table << sep_y + \"\\n\"\n end\n }\n table << sep\n return table\nend", "def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end", "def generate_list(table)\n\n table_rows = table.split('<tr>')\n table_rows.shift\n header_row = table_rows.shift.split('</td>')\n header_row.pop\n header_row.each do |header_col|\n puts \">>> \" + Sanitize.clean(header_col).strip\n end\n\n table_rows.each do |row|\n cols = row.split('</td>')\n cols.pop\n i = 0\n cols.each do |col|\n puts Sanitize.clean(header_row[i]).strip + \": \" + Sanitize.clean(col).strip\n i += 1\n end\n puts \"\\n\"\n end\n end", "def to_s_v2\n output = \"+\" + \"---+\" * columns + \"\\n\"\n\n each_row do |row|\n top = \"|\"\n bottom = \"+\"\n\n row.each do |cell|\n cell = Cell.new(-1, -1) unless cell\n\n body = \" #{contents_of(cell)} \"\n east_boundary = (cell.linked?(cell.east) ? \" \" : \"|\")\n top << body << east_boundary\n\n south_boundary = (cell.linked?(cell.south) ? \" \" : \"---\")\n corner = \"+\"\n bottom << south_boundary << corner\n end\n\n output << top << \"\\n\"\n output << bottom << \"\\n\"\n end\n\n output\n end", "def generate_html\n\n # Return our to_string function if we aren't reconstructed yet\n return self.to_s if !@reconstructed_table\n\n # Create an HTML table\n html = \"<table style='border:1px solid black'>\\n\";\n\n # Loop over each row and create a new table row\n @reconstructed_table.each do |row|\n html += \"<tr>\\n\";\n\n # Loop over each column and place the cell value into a td\n row.each do |column|\n to_show = column\n to_show = \"&nbsp;\" if to_show == \"\"\n html += \"<td style='border:1px solid black'>#{to_show}</td>\\n\";\n end\n\n # Close the row\n html += \"</tr>\\n\";\n end\n\n # Close the table\n html += \"</table>\\n\";\n return html\n end", "def to_table\n result = Mortadella::Horizontal.new headers: @commit_attributes, dry: %w[BRANCH LOCATION]\n main_commits = @commits.delete 'main'\n main_commits.try(:keys).try(:each) do |sha|\n main_commits[sha]['LOCATION'] = main_commits[sha]['LOCATION'].to_sentence\n result << main_commits[sha].values\n end\n @commits.values.each do |branch_commits|\n branch_commits.values.each do |commit|\n commit['LOCATION'] = commit['LOCATION'].to_sentence\n result << commit.values\n end\n end\n result.table\n end", "def build_up_cells(cells, row)\n partial_cell = parse_row_to_partial_cell(row)\n\n partial_cell.each.with_index do |cell, index|\n if cells[index]\n cells[index] += \"#{cell.strip} \"\n else\n cells[index] = \"#{cell.strip} \"\n end\n end\n\n return cells\n end", "def slice(table)\n head, body, array_h, array_b = 4.times.map { [] }\n index = 0\n first_column = 0\n second_column = 1\n\n (0...table.original_columns * table.original_rows).each do |col_index|\n row = table.rows[index]\n array_h += [row[first_column]]\n array_b += [row[second_column]]\n\n if col_index % table.original_columns == 2\n head << array_h\n body << array_b\n array_h, array_b = [], []\n end\n index += 1\n end\n [head, body]\n end", "def normalize(body)\n lines = body.split(\"\\n\")\n width = lines.first.length\n number_of_syms_to_wrap = (Dimensions::WIDTH - width) / 2\n syms_string = Citizen::DEAD * number_of_syms_to_wrap\n horiz_wrapped = lines.map { |line| syms_string + line + syms_string }\n\n matrix = horiz_wrapped.map { |row| row.split(\"\") }\n height = matrix.size\n\n number_of_row_wraps = (Dimensions::HEIGHT - height) / 2\n dead_row = (Citizen::DEAD * Dimensions::WIDTH).split(\"\")\n number_of_row_wraps.times do\n matrix = [dead_row] + matrix + [dead_row]\n end\n matrix.map(&:join).join(\"\\n\")\n end", "def block_textile_table( text ) \n text.gsub!( TABLE_RE ) do |matches|\n\n caption, id, tatts, fullrow = $~[1..4]\n tatts = pba( tatts, 'table' )\n tatts = shelve( tatts ) if tatts\n rows = []\n\n fullrow.\n split( /\\|$/m ).\n delete_if {|row|row.empty?}.\n each do |row|\n\n ratts, row = pba( $1, 'tr' ), $2 if row =~ /^(#{A}#{C}\\. )(.*)/m\n row << \" \"\n \n cells = []\n row.split( '|' ).each_with_index do |cell, i|\n next if i == 0\n \n ctyp = 'd'\n ctyp = 'h' if cell =~ /^_/\n\n catts = ''\n catts, cell = pba( $1, 'td' ), $2 if cell =~ /^(_?#{S}#{A}#{C}\\. ?)(.*)/\n\n catts = shelve( catts ) if catts\n cells << \"\\t\\t\\t<t#{ ctyp }#{ catts }>#{ cell.strip.empty? ? \"&nbsp;\" : row.split( '|' ).size-1 != i ? cell : cell[0...cell.length-1] }</t#{ ctyp }>\"\n end\n ratts = shelve( ratts ) if ratts\n rows << \"\\t\\t<tr#{ ratts }>\\n#{ cells.join( \"\\n\" ) }\\n\\t\\t</tr>\"\n end\n caption = \"\\t<p class=\\\"caption\\\">#{caption}</p>\\n\" if caption\n \"#{caption}\\t<table#{ tatts }>\\n#{ rows.join( \"\\n\" ) }\\n\\t</table>\\n\\n\"\n end\n end" ]
[ "0.703649", "0.66588366", "0.6583324", "0.65022963", "0.64263666", "0.6323259", "0.6167681", "0.60666615", "0.59544784", "0.58305293", "0.5770722", "0.5667127", "0.5666934", "0.5651298", "0.55769366", "0.55761003", "0.5564571", "0.5550563", "0.55431837", "0.54857373", "0.5461609", "0.54513556", "0.5439091", "0.5416425", "0.54039866", "0.5388373", "0.5383879", "0.5363153", "0.5339444", "0.5332976" ]
0.6910786
1
Wrap the row elements (cells) in html td tags. Determine what class to use based on the row chunk action. This way the row will be correctly formatted (eg. green background).
def new_row(chunk) new_class = { '-' => '', '+' => 'ins', '=' => 'unchanged', '!' => 'ins' }[chunk.action] [new_class.empty?, chunk.new_element.map { |el| %(<td class="#{new_class}">#{el}</td>) }] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def table_row_helper(cells, opts={})\n if cells[0] == :divider\n # this is not very nice..\n \"<tr><td colspan='#{cells[1]}' class='divider'><div></div></td></tr>\".html_safe\n else\n # Tried making this with content_tag but couldn't get the html_safe to work right... :S\n \"<tr>#{cells.compact.each_with_index.map{ |cell, i|\n # ... fixme\n if cell.is_a? Hash\n cell_content = ERB::Util.h(cell[:content])\n cell_opts = cell\n else\n cell_content = ERB::Util.h(cell)\n cell_opts = {}\n end\n classes = []\n classes << 'small_label' if i.even? && opts[:labels] && cells.length > 1\n classes << 'pre' if cell_opts[:pre]\n classes << 'tiny' if cell_opts[:tiny]\n classes << 'small' if cell_opts[:small]\n classes << 'bold' if cell_opts[:bold]\n classes << 'light' if cell_opts[:light]\n classes << 'superlight' if cell_opts[:superlight]\n\n styles = []\n styles << 'padding-left:2em' if i != 0 && i.even?\n # Yuck, this is nuts..\n \"<td\" +\n \"#{\" colspan='#{cell_opts[:colspan]}'\" if cell_opts[:colspan]}\" +\n \" style='#{safe_join(styles, ';')}'\" +\n \" class='#{safe_join(classes, ' ')}'\" +\n \">#{cell_content}\"+\n \"#{\"<br/><span class='small light'>#{cell_opts[:note]}</span>\" if cell_opts[:note]}\" + # even more hackery\n \"</td>\"\n }.join(\"\\n\")}</tr>\".html_safe\n end\n end", "def old_row(chunk)\n old_class = {\n '-' => 'del',\n '+' => '',\n '=' => 'unchanged',\n '!' => 'del'\n }[chunk.action]\n [old_class.empty?, chunk.old_element.map { |el| %(<td class=\"#{old_class}\">#{el}</td>) }]\n end", "def css_classes_for_row(); \"rsrcRow #{self.kind}row #{@tag}row\" end", "def css_classes_for_row(); \"rsrcRow #{self.kind}row #{@tag}row #{self.kind}Row #{@tag}Row\" end", "def game_td(game, left_or_right, row_span, &block)\n rowspan = 2 ** (row_span || (game.round.number - 1))\n concat content_tag(:td, capture(&block), :rowspan => rowspan, :align => left_or_right), block.binding\n end", "def status_row(checker)\n content_tag(:tr) do\n concat content_tag(:td, checker.name, style: status_style(checker))\n concat content_tag(:td, checker.value)\n concat status_cell(checker.status || t(:ok, scope: :status_cat))\n end\n end", "def split_simple_body(builder, data, cls)\n gen_cols = data.transpose.map { |col| col.join(\"\\n\") }\n\n builder.tr do\n builder.td(class: 'line-nr') do\n builder << (1..data.length).to_a.join(\"\\n\")\n end\n gen_cols.each do |col|\n builder.td(class: cls) do\n builder << CGI.escape_html(col)\n end\n end\n end\n end", "def event_cell event, colspan\n content_tag(:td, event.name, { :class => 'event', :rowspan => event.duration.to_s, :colspan => colspan.to_s })\n end", "def table_content\n # This makes a call to gift_rows and gets back an array of data that will \n # populate the columns and rows of a table I then included some styling to \n # include a header and make its text bold. I made the row background colors \n # alternate between grey and white Then I set the table column widths\n table gift_rows do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = ['DDDDDD', 'FFFFFF']\n self.column_widths = [180, 180, 180]\n end\n end", "def table_content\n table activity_rows do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = ['DDDDDD', 'FFFFFF']\n self.column_widths = [65, 175, 75, 85, 75, 65]\n style(column(3), align: :right)\n style(column(4), align: :right)\n style(column(5), align: :right)\n end\n end", "def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end", "def tr(row,options = {},*arrays)\n\t\t\traise ArgumentError,\"row must be Integer\" unless row.is_a? Integer\n\t\t\trow.times do |i|\n\t\t\t\tconcat(tag(\"tr\",options,true) + \"\\n\")\n\t\t\t\tif arrays[i].last == true\n num = arrays[i].size - 1\n\t\t\t\t\tarray = arrays[i][0...num]\n\t\t\t\t\tarray.each do |tcontent|\n\t\t\t\t\t\teval(\"t_th(tcontent)\")\n\t\t\t\t\t\tconcat(\"\\n\")\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tarrays[i].each do |tcontent|\n\t\t\t\t\t\teval(\"t_td(tcontent)\")\n\t\t\t\t\t\tconcat(\"\\n\")\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tconcat(\"</tr>\")\n\t\t\tend\n\t\tend", "def render\n res = { content: fields, data: { csv_row_index: @csv_row.row_index } }\n format.add_class res, row_css_classes\n res\n end", "def row(part, fields)\n \n # TODO: Add in notes, grain direction.\n html = \"<tr>\"\n\n fields.each { |f|\n \n # val = eval f[1] # Eval can be dangerous if passing something wrong into it...\n val = part[f[1]]\n \n # Check if the val is a float, so we can perform fraction conversion.\n if val.class == Float\n val = val.to_html_fraction(@round_dimensions)\n end\n\n puts \"[HTMLRenderer.row] row values: #{f[0]}, #{val}\\n\\n\" if $cutlister_debug\n \n html += \"<td>#{val.to_s}</td>\"\n \n }\n \n html += \"</tr>\"\n \n puts \"[HTMLRenderer.row] row html: #{html}\" if $cutlister_debug\n \n html\n \n end", "def task_row_tr_tag(task)\n class_name += \"selected\" if task.id == session[:last_task_id]\n class_name += \" unread\" if task.unread?(current_user)\n class_name += \" unassigned\" if task.users.count == 0\n\n return tag(:tr, {\n :id => \"task_row_#{ task.task_num }\",\n :class => class_name,\n :onclick => \"showTaskInPage(#{ task.task_num}); return false;\"\n }, true)\n end", "def ratio_260_280_td\n ratio_ok = \\\n object.class::RATIO_260_280_OK_RANGE.member? object.ratio_260_280\n ratio_warning = \\\n object.class::RATIO_260_280_WARN_RANGE.member? object.ratio_260_280\n\n cell_class = if ratio_ok\n ''\n elsif ratio_warning\n 'warning-highlight'\n else\n 'danger-highlight'\n end\n\n h.content_tag :td, object.ratio_260_280, class: cell_class\n end", "def create_row(ary, row_type = :tr, col_type = :td)\n inner = ary.inject('') do |output, value|\n output += \"<#{col_type}>#{value}</#{col_type}>\"\n end\n \"<#{row_type}>#{inner}</#{row_type}>\\n\"\nend", "def parse_cells(row)\n first = true\n while match?(:table_header, :table_data) || (first && !end?)\n cell = if match? :table_header\n Element.new(:th)\n else\n Element.new(:td)\n end\n if first\n if current.value == 2\n warning 'First cell on a new line should be \"|\" or \"!\" '\n end\n first = false\n elsif current.value != 2\n warning 'Inline cells should be \"||\" or \"!!\"'\n end\n advance if match?(:table_header, :table_data)\n cell = parse_attributes(cell)\n ## skip next tag since attributes were read\n advance if !cell.attributes.empty? && match?(:table_data, :table_header)\n contents = parse2(true)\n if contents.is_a? Array\n break if contents.empty?\n cell.add_children(*contents)\n else\n cell.add_child(contents)\n end\n advance(-1)\n first = true if match? :break\n advance\n ## Parse multi-line cell\n until end? || match?(:table_header, :table_data, :table_row, :table_end)\n if match? :break\n @line += current.value.length\n advance\n first = true\n redo\n end\n curr = @index\n p = parse2(true)\n if p.nil? && (curr == @index)\n error 'Unable to continue parsing table. Is this actually MediaWiki?'\n end\n break if p.is_a?(Array) && p.empty?\n cell.add_child(p)\n end\n row.add_child(cell)\n end\n row\n end", "def table_content\n table activity_rows do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = ['DDDDDD', 'FFFFFF']\n self.column_widths = [110, 175, 175, 80]\n end\n end", "def flat_table_row node\n td = Nokogiri::XML::Node.new( 'td', $document )\n td[:colspan] = 0\n td.children = node.clone\n tr = Nokogiri::XML::Node.new( 'tr', $document )\n tr.children = td\n tr[:class] = node.name\n\n newnode = node.replace tr\n return newnode\nend", "def from_table_row(row)\n if (row/\"td\").length == 7\n from_old_table_row row\n elsif (row/\"td\").length == 4\n from_new_table_row row\n end\n end", "def make_class(klass)\n %Q{\n <td class=\"class_item\" colspan=\"#{klass.intervals}\">\n <p>#{klass.name} - #{klass.location}</p>\n <p>#{klass.type}</p>\n </td>}\n end", "def cellClass\n ElementTableViewCell\n end", "def render_row row\n if row == :separator\n separator\n else\n Y + row.map_with_index do |cell, i|\n render_cell(cell, row_to_index(row, i))\n end.join(Y) + Y\n end\n end", "def render_cell(*)\n Capybara.string super\n end", "def pricing_cells(plans, l)\n plans.map{|plan|\n content = l.call(plan)\n content_tag(:td, content, class: [(current_user and current_user.plan == plan ? \"active\" : \"\"), (content == \"Y\" ? \"green\" : \"\")].join(\" \"))\n }.join.html_safe\n end", "def grid_row_css_class\n \"#{grid_row_model_type}-grid-item\"\n end", "def to_html(fields) \n output = []\n output << %(<table class=\"#{@options[:table_class]}\">)\n\n # Title\n if @options.has_key?(:title)\n output << %(<tr class=\"#{@options[:first_row_class]}\">)\n output << %(<th class=\"#{@options[:title_class]} #{@options[:first_row_class]} #{@options[:first_column_class]}\" colspan=\"#{fields.length}\">#{@options[:title]}</th>)\n output << %(</tr>)\n end\n\n # First row (header)\n output << %(<tr class=\"#{@options[:first_row_class]}\">)\n fields.each_with_index do |field, index|\n output << %(<th class=\"#{@options[:first_row_class]} #{column_classes(fields, index)}\">#{field}</th>)\n end\n output << \"</tr>\"\n\n @rows.each_with_index do |row, row_index|\n if block_given?\n yield_output = yield(row)\n\n data = []\n row_options = {}\n case yield_output\n when Array\n data = yield_output\n when Hash\n data = yield_output.delete(:data)\n row_options = yield_output\n else\n raise ArgumentError, \"TidyTable block expects an Array or Hash, but a #{yield_output.class} was returned.\"\n end\n\n row_classes = [row_index % 2 == 0 ? 'even': 'odd', row_options[:class]].select {|i| !i.nil?}.join(' ')\n output << %(<tr class=\"#{row_classes}\" #{\"id=\\\"#{row_options[:id]}\\\"\" if row_options.has_key?(:id)}>)\n data.each_with_index do |item, index|\n output << %(<td class=\"#{column_classes(data, index)}\">#{item}</td>)\n end\n else\n output << %(<tr class=\"#{row_index % 2 == 0 ? 'even': 'odd'}\">)\n fields.each_with_index do |field, index|\n output << %(<td class=\"#{column_classes(fields, index)}\">#{row.send(field.to_sym)}</td>)\n end\n end\n output << \"</tr>\"\n end\n output << \"</table>\"\n output.join\n end", "def render_row (class_prefix, key=nil, value=nil, tooltip=nil)\n\n row_id = if key\n \"r\" + (key.to_s + value.to_s).hash.to_s\n else\n nil\n end\n\n unless key\n key = \"&nbsp;\"\n value = \"&nbsp;\"\n end\n\n key = h(key)\n value = h(value) unless value.to_s[0, 1] == '<'\n\n s = \"\"\n s << \"<div\"\n s << \" class='#{class_prefix}_entry'\"\n\n if row_id\n s << \" id='#{row_id}'\"\n s << \" onmouseover=\\\"\"+omover(row_id, \"#{class_prefix}_entry_over\")+\"\\\"\"\n s << \" onmouseout=\\\"\"+omout(row_id, \"#{class_prefix}_entry_over\")+\"\\\"\"\n end\n\n s << \">\"\n s << \"<div class='#{class_prefix}_key'\"\n s << \" title='#{tooltip}'\" if tooltip\n s << \">#{key}</div>\"\n s << \"<div class='#{class_prefix}_value'>#{value}</div>\"\n s << \"<div style='clear:both;'></div>\"\n s << \"</div>\"\n\n s\n end", "def row(&block)\n @inside_row = true\n inner_html = @template.capture &block\n @inside_row = false\n\n @template.content_tag :div, inner_html, class: 'row'\n end" ]
[ "0.73626834", "0.6815915", "0.6682152", "0.66611123", "0.6319589", "0.6253161", "0.61102957", "0.6108904", "0.6099915", "0.60796154", "0.60580844", "0.60535693", "0.6032365", "0.5991391", "0.5962249", "0.5950943", "0.5949478", "0.58862174", "0.58611566", "0.5829479", "0.57268786", "0.5686156", "0.5679631", "0.56663907", "0.5663778", "0.56586933", "0.563722", "0.5583271", "0.55813235", "0.5568937" ]
0.75109816
0
Compare the table headers of the generated and expected table. The combined headers is the minimal set of headers that include the generated and expected headers (including duplicates). The indices arrays can be used to map the original input headers to the correct headers in the combined header list.
def diff_header_indices(generated, expected) counter = 0 gen_indices = [] exp_indices = [] gen_headers = [] exp_headers = [] combined_headers = [] Diff::LCS.sdiff(generated, expected) do |chunk| case chunk.action when '-' gen_indices << counter counter += 1 gen_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>) combined_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>) when '+' exp_indices << counter counter += 1 exp_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>) combined_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>) when '=' gen_indices << counter exp_indices << counter counter += 1 gen_headers << %(<th>#{CGI.escape_html chunk.old_element}</th>) exp_headers << %(<th>#{CGI.escape_html chunk.new_element}</th>) combined_headers << %(<th>#{CGI.escape_html chunk.new_element}</th>) when '!' gen_indices << counter counter += 1 gen_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>) combined_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>) exp_indices << counter counter += 1 exp_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>) combined_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>) end end [gen_indices, exp_indices, gen_headers, exp_headers, combined_headers] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def verify_header_names(key, models_columns, header)\n normalized_header = []\n\n got_error = false\n header.each_with_index do |h, i|\n logger.debug \"verify header: #{h}\"\n if h == \"id\"\n error(cur_sheet_name, 1, \"Header column #{h} not allowed, update not supported yet\")\n next\n end\n\n if h.nil?\t# ignore empty header\n normalized_header[i] = nil\n next\n else\n normalized_header[i] = normalize_header(h)\n end\n\n # see if heading is an attribute name, pseudo attribute,\n # fk_finder, refrerence id or reference to one\n # if so, put it in the models_columns :headers hash with header index\n header_is_known = false\n show_header_in_results = true\n models_columns.each_with_index do |mc, ci|\n\n # check for ambiguous header name\n if mc[:dups].has_key?(normalized_header[i])\nlogger.debug \"verify_header: ci: #{ci} found ambiguous header: #{normalized_header[i]}\"\n dup_index = mc[:dups][normalized_header[i]]\nlogger.debug \"verify_header: ci: #{ci} dup_index: #{dup_index}\"\n next if dup_index.nil?\n if dup_index == i\n header_is_known = true\n mc[:headers] << [normalized_header[i], i] # 0 based index\nlogger.debug \"header #{h} i: #{i} ci: #{ci} is_ambiguous_model_column mc[:headers]: #{mc[:headers]}\"\n break\n end\n next\n end\n\n if mc[:allowed_cols].include?(normalized_header[i])\n header_is_known = true\n mc[:headers] << [normalized_header[i], i] # 0 based index\nlogger.debug \"header #{h} is_model_column mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_pseudo_attr(mc[:model], normalized_header[i])\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_model_pseudo_attr mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_fk_finder_header(normalized_header[i], mc)\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_fk_finder mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_ref_def_header(normalized_header[i], mc[:model])\n header_is_known = true\n show_header_in_results = false\n @sheet_results[key][:_refs][(mc[:model]).name] = normalized_header[i]\n @sheet_results[key][:_ref_ids][normalized_header[i]] = {}\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_ref_def mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_ref_ref_header(normalized_header[i], mc)\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_ref_ref mc[:headers]: #{mc[:headers]}\"\n break\n end\n end\n if !show_header_in_results\n normalized_header.delete_at(i)\n end\n next if header_is_known\n\n # error if not recognized, but continue to gather all errors\n got_error = true\n error(cur_sheet_name, 1, \"Header name '#{h}' is not recognized for model(s) #{model_column_names(models_columns)}\")\n end\n return false if got_error\n\n#logger.debug \"mc[0][:headers]: #{models_columns[0][:headers]}\"\n#logger.debug \"mc[1][:headers]: #{models_columns[1][:headers]}\"\n\n @sheet_results[key][:header] = [\"id\"] + normalized_header.compact\n logger.debug \"Normalized header: key: #{key} #{@sheet_results[key][:header]}\"\n return true\nend", "def resolve_ambiguous_headers(models_columns, raw_header)\n return if models_columns.size < 2\n m0_cols = models_columns[0][:allowed_cols] - [\"id\", \"updated_by\", \"created_at\", \"updated_at\"]\n m1_cols = models_columns[1][:allowed_cols] - [\"id\", \"updated_by\", \"created_at\", \"updated_at\"]\n dup_names = []\n m0_cols.each do |n1|\n m1_cols.each do |n2|\n if n1 == n2\n dup_names << n1\n end\n end\n end\n#logger.debug \"resolve_ambiguous_headers found dup_names: #{dup_names}\"\n return if dup_names.empty?\n# normalize all headers\n header = raw_header.map {|h| normalize_header(h) }\n dup_names.each do |dn|\n#logger.debug \"resolve_ambiguous_headers handle dup_name: #{dn}\"\n fi = li = nil\n # find first instance of the dup name in header\n header.each_with_index do |h, i|\n if dn == h\n fi = i\n break\n end\n end\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} first index: #{fi}\"\n # next if the dup name is not used in the sheet\n next if fi.nil?\n # find last instance of the dup name in header\n header.reverse_each.with_index do |h, ri|\n if dn == h\n li = (header.size - 1) - ri\n break\n end\n end\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} last index: #{li}\"\n if fi == li\n # one instance of dup name\n m1_no_dups = models_columns[1][:allowed_cols] - dup_names\n first_m1_index = nil\n header.each_with_index do |h, i|\n if m1_no_dups.include?(h)\n # we foud the first non-ambiguous header of 2nd model\n first_m1_index = i\n break\n end\n end\n if first_m1_index.nil? || fi < first_m1_index\n # assign to the 1st model\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} assign to first\"\n models_columns[0][:dups][dn] = fi\n models_columns[1][:dups][dn] = nil\n else\n # assign to the 2nd model\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} assign to second\"\n models_columns[0][:dups][dn] = nil\n models_columns[1][:dups][dn] = fi\n end\n else\n#logger.debug \"resolve_ambiguous_headers assign dup_name: #{dn} first index: #{fi} last index: #{li}\"\n# two instances of dup name\n models_columns[0][:dups][dn] = fi\n models_columns[1][:dups][dn] = li\n end\n end\n end", "def ar_index_table_headers \n label_header= content_tag(:th, controller.ardata.labels[:label])\n \n # This will be used when adding the table rows.\n # it will contain, in the order in wich they are retrieved,\n # a true of false value depending on the presence of the label\n # for the table header. This means that a column can be disabled\n # simply by labeling it with an empty string (most usefull when the\n # label of the column comes from a method or a Proc that can enable/disable\n # the output given a set of conditions\n @display_current_ar_index_table_column= []\n \n headers= []\n \n controller.ardata.fields.for_index.each do |column, title|\n label= ar_get_index_label(title)\n \n if label && !label.strip.empty?\n headers << content_tag(:th, label) \n @display_current_ar_index_table_column << true\n else\n @display_current_ar_index_table_column << false\n end\n end\n \n colspan= ar_index_colspan\n \n \"<tr>\\n #{label_header}\" \\\n \"\\n #{headers.join(\"\\n \")}\" \\\n \"\\n #{colspan}\" \\\n \"\\n </tr>\"\n end", "def header_valid?(expected, actual)\n expected.intersection(actual) == expected\n end", "def get_ordered_headers\n headers = get_headers\n template_headers = get_template_headers\n ordered_headers = ['druid', 'sourceId']\n # Select only headers with values somewhere in the data\n template_headers.each {|th| ordered_headers << th if headers.include?(th)}\n ordered_headers\n end", "def headers_with_indexes\n @headers_with_indexes ||= headers.each_with_index.to_h\n end", "def build_table_header\n names = column_names(data)\n build_md_row(output, names)\n build_md_row(output, alignment_strings(names))\n end", "def merge_headers(head1, head2, sepr=\"\", open=\"\", close=\"\")\n merged_arr = head1.zip(head2) #merges 2 headers (arrays) together into a \"2D\" array\n \n merged_str = []\n #converts merged array into a string (with optional seperator and opening/closeing containers)\n merged_arr.each do |h1,h2|\n if (h1.empty? and h2.empty?)\n h3 = '\"\"' #empty double header cells should stay empty\n else\n h3 = h1 + sepr + open + h2 + close\n end\n merged_str << h3\n end\n return merged_str\n end", "def table_headings\n tableheadings = []\n print_layout.each do |section|\n row_cells = section[:row_cells]\n raise Error::AppError.new('table_headings', 'No Row Cells defined') if row_cells.nil?\n\n tableheadings += table_cell_headers(row_cells)\n end\n [tableheadings, tableheadings.count]\n end", "def check_duplicate_csv_headers(table)\n if table.headers.size != table.headers.uniq.size\n dups = table.headers.select{|e| table.headers.count(e) > 1 }\n Squib.logger.warn \"CSV duplicated the following column keys: #{dups.join(',')}\"\n end\n end", "def check_indexes(table)\n indexes = table_indexes(table)\n\n indexes.permutation(2).each_with_object([]) do |(source_index, target_index), response|\n next unless source_index.columns.start_with?(target_index.columns)\n\n if target_index.unique\n response << {\n index: source_index,\n result: \"#{source_index.name} has column(s) on the right side of unique index (#{target_index.name}). You can drop if low cardinality\",\n }\n else\n response << {\n index: target_index,\n result: \"#{target_index.name} is a left-prefix of #{source_index.name}\",\n }\n end\n end\n end", "def semanticize_table_headers!\n @document.tree.search('table tr:first td').each { |node| node.node_name = 'th' }\n end", "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end", "def header_array\n @columns.collect {|c|\n if @table[c]\n @table[c][:name].to_s\n else\n \"\"\n end\n }.compact\n end", "def columnheaders_unique?\r\n columnheaders_raw.length == columnheaders_raw.uniq.length\r\n end", "def csv_file_header_array\n\t\tScreeningDatumUpdate.expected_column_names\n\tend", "def prepare_header_cells(table_header)\n cells = @parser.find(table_header).find_children('tr').find_children(\n 'th'\n ).list_results\n cells.each do |cell|\n next unless Hatemile::Util::CommonFunctions.is_valid_element?(cell)\n\n @id_generator.generate_id(cell)\n cell.set_attribute('scope', 'col')\n end\n end", "def double_header(iterator)\n #p \"double_header iterator\", iterator\n head1 = cut_line(iterator) \n #p \"head1\", head1\n head1_csv = CSV.parse(head1).flatten \n #p \"head1_csv\", head1_csv\n head1_csv = nil_blank(head1_csv) \n #p \"head1_csv\", head1_csv\n head1_csv.collect!{|str| str.strip} #leading and trailing whitespace removed\n #p \"head1_csv\", head1_csv \n #puts \"\"\n \n head2 = cut_line(iterator) \n #p \"head2\", head2\n head2_csv = CSV.parse(head2).flatten \n #p \"head2_csv\", head2_csv\n head2_csv = nil_blank(head2_csv) \n #p \"head2_csv\", head2_csv\n head2_csv.collect!{|str| str.strip} #leading and trailing whitespace removed\n #p \"head2_csv\", head2_csv\n \n merged_arr = merge_headers(head1_csv, head2_csv, \" \", \"[\", \"]\")\n \n #Adds quotes around fields (helps avoid CSV parse bugs)\n if ($add_quotes == true)\n merged_arr.map! {|s| \"\\\"#{s}\\\"\" }\n end\n \n new_head = merged_arr.join(',') #creats string with \",\" as sperator\n new_head << \"\\r\\n\" #So CSV can parse headers\n new_iterator = new_head << iterator #combines new header with data\n return new_iterator\n end", "def fail_unless_header_complete(column_mappings)\n return unless header_lines > 0 && !header_valid?\n\n expected_names = column_names(column_mappings)\n received_names = @header_best_guess || []\n\n unexpected = received_names - expected_names\n missing = expected_names - received_names\n\n fail header_message_for(missing, unexpected)\n end", "def table_headers\n [\"Description\", \"Qty\", \"VAT\", \"Amount\"]\n end", "def build_formatted_headers(_widths = {})\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n map = {}\n table.headers.each do |h|\n istruct = format_at[:header][h]\n map[h] = [h, format_cell(h.as_string, istruct, decorate: decorate)]\n end\n map\n end", "def build_formatted_headers(_widths = {})\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n map = {}\n table.headers.each do |h|\n istruct = format_at[:header][h]\n map[h] = [h, format_cell(h.as_string, istruct, decorate: decorate)]\n end\n map\n end", "def row_headers\n use_row_headers ? rows.map(&:heading) : true\n end", "def headers\n columns.map(&:header)\n end", "def generate_header\n \"<table class='bodyTable'><thead><th>Testing element</th><th>Pass</th><th>Result</th><th>Time</th></thead><tbody>\"\n end", "def summary_table_headers(args={})\n\n\t\tif args[\"root\"] =~ /order/\n\t\t\t'\n\t\t\t\t<thead>\n\t\t <tr>\n\t\t <th>Name</th>\n\t\t <th>Result</th>\n\t\t <th>Units</th>\n\t\t <th>Range</th>\n\t\t <th>Inference</th>\n\t\t <th>Verified</th>\n\t\t <th>Options</th>\n\t\t </tr>\n\t\t </thead>\n\t\t\t'\n\t\telse\n\t\t\t'\n\t\t\t\t<thead>\n\t\t <tr>\n\t\t <th>Name</th>\n\t\t <th>LIS CODE</th>\n\t\t <th>Description</th>\n\t\t <th>Total Ranges</th>\n\t\t <th>Options</th>\n\t\t </tr>\n\t\t </thead>\n\t\t\t'\n\t\tend\n\tend", "def verify_column_headers\n \n unless (headers = get_spreadsheet.headers)\n # log an error if we can't get the metadata headers\n @verification_errors << BulkOps::Error.new({type: :bad_header, field: column_name}) \n end\n\n headers.each do |column_name|\n next if column_name.blank?\n column_name_redux = column_name.downcase.parameterize.gsub(/[_\\s-]/,\"\")\n # Ignore everything marked as a label\n next if column_name_redux.ends_with? \"label\"\n # Ignore any column names with special meaning in hyrax\n next if BulkOps::SPECIAL_COLUMNS.any?{|col| col.downcase.parameterize.gsub(/[_\\s-]/,\"\") == column_name_redux }\n # Ignore any columns speficied to be ignored in the configuration\n ignored = options[\"ignored headers\"] || []\n next if ignored.any?{|col| col.downcase.parameterize.gsub(/[_\\s-]/,\"\") == column_name_redux }\n # Column names corresponding to work attributes are legit\n next if Work.attribute_names.any?{|col| col.downcase.parameterize.gsub(/[_\\s-]/,\"\") == column_name_redux }\n @verification_errors << BulkOps::Error.new({type: :bad_header, field: column_name})\n end\n end", "def accept_table header, body, aligns\n widths = header.zip(body) do |h, b|\n [h.size, b.size].max\n end\n aligns = aligns.map do |a|\n case a\n when nil\n :center\n when :left\n :ljust\n when :right\n :rjust\n end\n end\n @res << header.zip(widths, aligns) do |h, w, a|\n h.__send__(a, w)\n end.join(\"|\").rstrip << \"\\n\"\n @res << widths.map {|w| \"-\" * w }.join(\"|\") << \"\\n\"\n body.each do |row|\n @res << row.zip(widths, aligns) do |t, w, a|\n t.__send__(a, w)\n end.join(\"|\").rstrip << \"\\n\"\n end\n end", "def headers_by_index(headers)\n result = Hash.new\n headers.each_with_index do |column, index|\n result[index] = column\n end\n result\nend", "def search_results_table_headers\n search_results_table.headers_text\n end" ]
[ "0.63184196", "0.6097423", "0.58528733", "0.5850958", "0.5802083", "0.5683103", "0.56407815", "0.5597162", "0.5579819", "0.55273336", "0.552548", "0.55186576", "0.55001485", "0.5480812", "0.54472744", "0.5439384", "0.54330105", "0.54320794", "0.5423372", "0.5401045", "0.53941834", "0.53941834", "0.5366319", "0.53516", "0.5330855", "0.5319299", "0.5299152", "0.52985775", "0.5294769", "0.52409434" ]
0.741105
0
register a timeout listener that will be called in given seconds (aprox). Returns a listener object that can be used with clear_timeout to remove the listener
def set_timeout(seconds, block) listener = { seconds: seconds, block: block, time: @time, target: @time + seconds } @timeout_listeners.push listener listener end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def timer(timeout,options={},&callback)\n bot.timer.add_timer(:timestamp=>Time.now+timeout.to_i, :requestor=>options[:requestor]||name,&callback)\n end", "def _add_timeout_arg(a_func, timeout)\n proc do |request, **kwargs|\n kwargs[:timeout] = timeout\n a_func.call(request, **kwargs)\n end\n end", "def timer_on (opts={})\n @timer.cancel unless @timer.nil?\n length = @timeout + (opts[:with_interval] ? @interval : 0)\n @timer = EventMachine::Timer.new(length) {\n scrap = @buf ? \" - #{@buf.flush}\" : ''\n @handler.logger.error \"timeout on #{@handler.name}\" + scrap\n @handler.logger.debug {\"pid #{get_pid}\"}\n close_connection()\n }\n end", "def add_timeout(seconds, &block)\n raise_not_implemented\n end", "def on_timeout=(callback)\n @timeout_callback = callback\n end", "def initialize(timeout=600)\n @holder = NameTimerHolder.new(timeout)\n end", "def add_timeout(interval, &block)\n @timer.add(interval, &block)\n end", "def on_timeout(options = {})\n timeout = options[:timeout] || 0.5\n\n sleep timeout\n\n yield\n end", "def timer\n rescuer do\n Timeout.timeout(ttl) { yield }\n end\n end", "def add_timeout(opts = {})\n @timeout = opts[:timeout] || @timeout\n opts.delete(:timeout)\n end", "def set_timeout_source\n %Q|\n var setTimeout = function(cb, delay) {\n var timer = Components.classes[\"@mozilla.org/timer;1\"].createInstance(Components.interfaces.nsITimer);\n timer.initWithCallback({notify:cb}, delay, Components.interfaces.nsITimer.TYPE_ONE_SHOT);\n return timer;\n };\n |\n end", "def schedule_timer(timeout)\n @scheduler.schedule_timer(timeout)\n end", "def timeout(seconds, &block)\n Timeout.timeout seconds, Pinglish::TooLong, &block\n end", "def timeout_after(time); end", "def invite_timeout\n run_on_invite_timeout_cbs\n end", "def idle_timeout=(timeout); end", "def timeout(sid, timeout, opts={}, &callback)\n # Setup a timeout if requested\n return unless sub = @subs[sid]\n\n auto_unsubscribe, expected = true, 1\n auto_unsubscribe = opts[:auto_unsubscribe] if opts.key?(:auto_unsubscribe)\n expected = opts[:expected] if opts.key?(:expected)\n\n EM.cancel_timer(sub[:timeout]) if sub[:timeout]\n\n sub[:timeout] = EM.add_timer(timeout) do\n unsubscribe(sid) if auto_unsubscribe\n callback.call(sid) if callback\n end\n sub[:expected] = expected\n end", "def timeout=(timeout=:default)\n @timeout = TIMEOUTS.member?(timeout) ? TIMEOUTS[timeout] : timeout\n NOTIFICATION[:set_timeout].call @notification, @timeout\n end", "def timeout=(timeout)\n @timeout = timeout\n end", "def enable_tunnel_timeouts\n @last_packet_time = Time.now\n @timeout_timer = EventMachine::PeriodicTimer.new(1.0) do\n check_tunnel_timeout\n end\n end", "def evict_timeout(timeout)\n @evict_timeout = timeout.to_i\n self\n end", "def add_timer(interval, callback=nil, &blk)\n @timers ||= {}\n timer = Timer.new(interval,callback,&blk)\n timer.on(:fired) do\n @timers.delete(timer.object_id)\n end\n timer.on(:cancelled) do\n @timers.delete(timer.object_id)\n end\n @timers[timer.object_id] = timer\n timer.object_id\n end", "def subscribe_with_timeout(timeout, *channels, &block); end", "def persistent_timeout(seconds); end", "def timeout!(*args, &block)\n Timeout::timeout(*args, &block)\n end", "def set_timeout(name, timeout)\n handle = system.run!(:search, \"user\", name, nil, @keyring)\n system.run!(:set_timeout, handle, timeout)\n end", "def ping()\n Timer.renew(@name, @timeout)\n end", "def timeout=(interval)\n @timer = NSTimer.scheduledTimerWithTimeInterval(interval,\n target: self,\n selector: :\"on_timeout_elapsed:\",\n userInfo: nil,\n repeats: false)\n end", "def timeout=(timeout)\n @timeout = timeout\n @socket_timeout = nil\n\n if @timeout.to_f > 0\n secs = @timeout.floor\n usecs = (@timeout - secs).floor * 1_000_000\n @socket_timeout = [secs, usecs].pack(\"l_2\")\n end\n end", "def subscribe_with_timeout(timeout, *channels, &block)\n _subscription(:subscribe_with_timeout, timeout, channels, block)\n end" ]
[ "0.6580678", "0.6283373", "0.6205954", "0.615535", "0.6121049", "0.6081951", "0.60530937", "0.5976984", "0.59044105", "0.5765276", "0.57223237", "0.5713267", "0.56706756", "0.5661123", "0.5660976", "0.5628078", "0.56160533", "0.5572752", "0.55707353", "0.5554352", "0.5530285", "0.5510299", "0.5484886", "0.54315037", "0.54153824", "0.5391603", "0.5389296", "0.5384841", "0.5382952", "0.53480583" ]
0.707152
0
Returns an array with two values, the first being a hash of edges with a number containing their class assignment, the second valud is a boolean which states whether or not the graph is a comparability graph Complexity in time O(d|E|) where d is the maximum degree of a vertex Complexity in space O(|V|+|E|)
def gamma_decomposition k = 0; comparability=true; classification={} edges.map {|edge| [edge.source,edge.target]}.each do |e| if classification[e].nil? k += 1 classification[e] = k; classification[e.reverse] = -k comparability &&= plexus_comparability_explore(e, k, classification) end end; [classification, comparability] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gamma_decomposition\r\n k = 0; comparability=true; classification={}\r\n edges.map {|edge| [edge.source,edge.target]}.each do |e|\r\n if classification[e].nil?\r\n k += 1\r\n classification[e] = k; classification[e.reverse] = -k\r\n comparability &&= gratr_comparability_explore(e, k, classification)\r\n end\r\n end; [classification, comparability]\r\n end", "def graph(hash_graph)\n next_node = 0\n result = [0]\n\n while next_node != 4\n next_node = hash_graph[next_node].first\n result << next_node\n end\n\n result\nend", "def hash\n @node.sort.push(@edge).hash\n end", "def graph(hash_graph)\n # write your code here\n next_node = 0\n result = [0]\n \n while next_node != 4\n next_node = hash_graph[next_node].first\n result << next_node\n end\n \n result\nend", "def describe_node(x)\n res = []\n @k.each_vertex do |y|\n if y.type == :positive and not x == y\n if @k[x,y] == :provable_true\n res << describe_edge(x,y)\n elsif @k[x,y.opposite] == :provable_true\n res << describe_edge(x,y.opposite)\n elsif @k[x,y]\n res << describe_edge(x,y)\n elsif @k[x,y.opposite]\n res << describe_edge(x,y.opposite)\n end\n end\n end\n \n res\n end", "def detect_cycle_in_graph(edges)\nend", "def get_in_degrees(graph)\n in_degrees = {}\n graph.keys.each { |vtx| in_degrees[vtx] = 0 }\n graph.values.each do |neighbors|\n neighbors.each do |neighbor|\n in_degrees[neighbor] += 1\n end\n end\n in_degrees\nend", "def connected_components(edges)\n vertex_hash = {}\n edges.each do |pair|\n pair.each do |vertex|\n unless vertex_hash[vertex]\n vertex_hash[vertex] = [[vertex]]\n end\n end\n inner_left = vertex_hash[pair[0][0]]\n inner_right = vertex_hash[pair[1][0]]\n inner_left = inner_right = (inner_left + inner_right)\n end\n component_set = Set.new\n vertex_hash.values.map do |value|\n component_set << Set.new(value[0]).to_a.map(:to_s)\n end\n component_set.to_a\nend", "def twoDArray(m,n)\n arr = Hash.new\n for m in 0..m\n for n in 0..n\n if m.gcd(n) == 1\n arr[[m,n]] = true\n else\n arr[[m,n]] = false\n end\n end\n end\n\n for m in 0..m\n for n in 0..n\n if arr[[m,n]] == true\n puts \"#{m} :m and #{n} :n\"\n end\n end\n end\nend", "def gratr_comparability_explore(edge, k, classification, space='')\r\n ret = gratr_comparability_explore_inner(edge, k, classification, :forward, space)\r\n gratr_comparability_explore_inner(edge.reverse, k, classification, :backward, space) && ret\r\n end", "def dfs\n visited = Hash.new(false)\n @v.each do |vertex| \n visited.merge(explore(vertex)) if !visited[vertex]\n end\n return visited\n end", "def checkNode()\n source_set = []\n neighbor_set = []\n $networks.each do |s, nb|\n source_set << s\n nb[\"neighbors\"].each do |s_, dist|\n neighbor_set << s_\n end\n end\n source_set.sort!\n source_set.uniq!\n neighbor_set.sort!\n neighbor_set.uniq!\n return source_set == neighbor_set\nend", "def get_adjacency_list\n max_index = find_max_index\n adjacency_list = [nil] * max_index\n @edges.each do |edg|\n from_value = edg.node_from.value\n to_value = edg.node_to.value\n if adjacency_list[from_value]\n adjacency_list[from_value] << [to_value, edg.value]\n else\n adjacency_list[from_value] = [[to_value, edg.value]]\n end\n end\n adjacency_list\n end", "def edges_for_node(node)\n Hash(@edges[node]).values\n end", "def hash\n ([graph_name] + operands).hash\n end", "def test_07\n @dg = DiGraph.new([0,0],[6,0],[6,8],[2,6],[8,8],[3,4],[3,2],[3,9],[9,4],[9,6],[4,3],[4,8])\n @paths = Hash.new\n @paths[0] = [0]\n @paths[6] = [0,8]\n @paths[2] = [6]\n @paths[8] = [8]\n @paths[3] = [4,2,9]\n @paths[9] = [4,6]\n @paths[4] = [3,8]\n @nodes = @paths.keys\n received_dg = @dg.strongly_connected_component_including_node(6);\n filled_dg = DiGraph.new(*fill(6));\n if (not filled_dg.equal?(received_dg))\n puts \"test_07 failed...\"\n puts \"DiGraph => #{@dg.to_s}\"\n puts \"node => 6\"\n puts \"expected => #{filled_dg.to_s}\"\n puts \"received => #{received_dg.to_s}\"\n end\n assert_equal(true,filled_dg.equal?(received_dg))\n end", "def initialize graph\n # Make the data entry easier with default hash values\n @graph = Hash.new{|h,k| h[k]=Vertex.new(k,[],false,nil,nil)}\n @rev = Hash.new{|h,k| h[k]=Vertex.new(k,[],false,nil,nil)}\n @t = 0\n @s = nil\n @f_times = []\n\n graph.each do |(v1,v2)|\n @graph[v1].neighbours << v2\n @graph[v2]\n @rev[v2].neighbours << v1\n @rev[v1]\n end\n\n # Set the hash back to its safe default\n @graph.default = @rev.default = nil\n return @graph\n end", "def graph_to_sets(graph)\n labels = {}\n graph.vertices.keys.each do |from|\n graph.adjacted_with(from).each { |to| labels[Pair.new(from, to)] = graph.get_edge_label(from, to) }\n end\n labels.to_set.sort_by { |elem| elem[1] }.to_h\n end", "def circular_graph?(array)\n\treturn false if array.size.zero?\n\tvisited = array.size.times.map{ |i| false }\n\tvisited[0] = true\n\n\tarray.each do |index|\n\t\tif index > array.size \n\t\t\treturn false\n\t\tend\n\n\t\tif visited[index]\n\t\t\treturn true\n\t\tend\n\n\t\tvisited[index] = true\n\tend\n\tfalse\nend", "def incident_edges v\n\t\ttemp_array = []\n\t\tfor i in 0..num_edges-1\n\t\t\tif @Edges[i].points[0] == v.label\n\t\t\t\ttemp_array << @Edges[i]\n\t\t\telsif @Edges[i].points[1] == v.label\n\t\t\t\ttemp_array << @Edges[i]\n\t\t\tend\n\t\tend\n\t\treturn temp_array\n\tend", "def in_use_graph\n graph = Graph.new\n\n index_to_vertex = build_index\n index_to_vertex.each do |(vrow, vcol), v|\n neighbours_in_use(vrow, vcol)\n .map { |index| index_to_vertex[index] }\n .each { |w| graph.add_edge(v, w) }\n end\n\n graph\n end", "def nodes_binary_value\n binary = '0' * @nodes.map(&:id).max\n\n @nodes.each do |node|\n binary[@nodes.count - node.id] = '1'\n end\n\n binary\n end", "def edges\n h = hedges\n v = vedges\n [ h[0], v[1], h[1], v[0] ]\n end", "def create_graph(arr)\n nodes = []\n (0...arr.size).each do |i|\n node = Node.new(i)\n nodes.push(node)\n end\n nodes.each_with_index do |node,i|\n arr[i].each {|val| node.connections.push(nodes[val])} \n end\n nodes\nend", "def create_graph(arr)\n nodes = []\n (0...arr.size).each do |i|\n node = Node.new(i)\n nodes.push(node)\n end\n nodes.each_with_index do |node,i|\n arr[i].each {|val| node.connections.push(nodes[val])} \n end\n nodes\nend", "def conn_graph_create(filename) \n ### Making the filename \n newfilename=make_filename(filename)\n\n tmpInpHash=Hash.new\n tmpOutHash=Hash.new\n commonSet = Array.new \n commonSet =commonSet.push(\"clk\") \n commonSet =commonSet.push(\"reset\") \n zero = '0'\n load_cycloHash() \n @block.each do |key,val|\n a = Array.new \n b = Array.new\n val.each_input() { |i| a.push(i)} \n tmpInpHash[key] = a\n val.each_output() { |x| b.push(x)}\n tmpOutHash[key] = b\n end # end for @block.....\n keys = @block.keys \n \n count = 0\n \n primaryKey = keys[count]\n ### connectivity hash -- where the modules are connected by common input port names\t\n @connInpHash = Hash.new { |k,v| v=Array.new}\n while (count <= keys.length) do\n for secondKey in 0... keys.length do\n tmp1 =Array.new\n tmpA = Array.new\n \n #### Uncomment the following 4 lines to get Input-Output connectivity \n # if (primaryKey != keys[secondKey]) then \n # if (tmpOutHash[primaryKey] & tmpInpHash[keys[secondKey]])then\n # tmp1 =tmpOutHash[primaryKey] & tmpInpHash[keys[secondKey]] ### Set intersection operator\n # end \n # end\n #### Uncomment the following 4 lines for Output-Output connetivity\n if (primaryKey != keys[secondKey] ) then \n if (tmpOutHash[primaryKey] & tmpOutHash[keys[secondKey]])then\n tmp1 =tmpOutHash[primaryKey] & tmpOutHash[keys[secondKey]]\n end \n end \n ####Uncomment the following 4 lines to get Input-Input connectivity \n #if (primaryKey != keys[secondKey])\n #if (tmpInpHash[primaryKey] & tmpInpHash[keys[secondKey]])then\n # tmp1 =tmpInpHash[primaryKey] & tmpInpHash[keys[secondKey]]\n #end \n #end\n ##### \n \n if (tmp1.length != 0 ) then \n tmpA = tmp1 - commonSet ## Set difference operator\n end\n if ( tmpA.length !=0 ) then \n @connInpHash[primaryKey] = @connInpHash[primaryKey].push(keys[secondKey])\n end # end of if\n end # end of for\n \n\n count = count+1\n primaryKey = keys[count] \n end # end of while\n @connInpHash.each{|h,k| puts h, k.inspect, \"\\n\"}\n #write_cyclo()\n write_und_file(newfilename) ## drawing undirected graphs\n end", "def get_graphhash(graphobj)\n graphhash = Hash[\n 'display' => graphobj.at_xpath(\"displayprio\").text,\n 'name' => graphobj.at_xpath(\"name\").text,\n 'yaxis' => graphobj.at_xpath(\"verticallabel\").text,\n 'datapoints' => graphobj.xpath('graphdatapoints/graphdatapoint'),\n ]\n\n return Hash[graphhash.sort]\n end", "def connected?\n is_visited = []\n dfs(0) { |v,w| is_visited[w] = true }\n 0.upto(vertices-1) { |i| return false unless is_visited[i] }\n true\n end", "def neighbors(vertex)\n neighbors = []\n @edges.each do |edge|\n neighbors.push edge.tar if edge.src == vertex\n end\n return neighbors.uniq\n end", "def graphs()\n accounts_sorted = sorted_keys_of(@graphs) { |x,y| x <=> y }\n\n values = []\n accounts_sorted.each do |account|\n values.push(get_graph_for(account))\n end\n \n return values\n end" ]
[ "0.65403706", "0.61264944", "0.5824513", "0.5689655", "0.5675924", "0.56293416", "0.55407304", "0.5478084", "0.54539037", "0.54467845", "0.5397665", "0.5392294", "0.5370198", "0.5340261", "0.5313673", "0.5300132", "0.52891475", "0.52799016", "0.5260608", "0.52445084", "0.5239871", "0.5212847", "0.52025455", "0.5199477", "0.5199477", "0.51886106", "0.51883453", "0.5187323", "0.5181668", "0.5161423" ]
0.6402958
1
Returns one of the possible transitive orientations of the UndirectedGraph as a Digraph
def transitive_orientation(digraph_class=Digraph) raise NotImplementError end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def transitive_orientation(digraph_class=Digraph)\r\n raise NotImplementError\r\n end", "def to_rgl_oriented\n RGL::ImplicitGraph.new do |g|\n g.vertex_iterator do |block|\n self.each_segment do |segment|\n [:+, :-].each do |orient|\n block.call([segment, orient].to_oriented_segment)\n end\n end\n end\n g.adjacent_iterator do |oriented_segment, block|\n s = segment(oriented_segment.segment)\n o = oriented_segment.orient\n s.links[:from][o].each do |l|\n os = [segment(l.to), l.to_orient].to_oriented_segment\n block.call(os)\n end\n o = oriented_segment.invert_orient\n s.links[:to][o].each do |l|\n os = [segment(l.from), l.from_orient].to_oriented_segment\n block.call(os.invert_orient)\n end\n end\n g.directed = true\n end\n end", "def to_undirected\n new_graph = NetworkX::Graph.new(@graph)\n @nodes.each { |u, attrs| new_graph.add_node(u, attrs) }\n @adj.each do |u, edges|\n edges.each { |v, attrs| new_graph.add_edge(u, v, attrs) }\n end\n new_graph\n end", "def to_undirected\n return self unless directed?\n AdjacencyGraph.new(Set, self)\n end", "def reverse\n new_graph = NetworkX::DiGraph.new(@graph)\n @nodes.each { |u, attrs| new_graph.add_node(u, attrs) }\n @adj.each do |u, edges|\n edges.each { |v, attrs| new_graph.add_edge(v, u, attrs) }\n end\n new_graph\n end", "def reverse\n return self unless directed?\n result = DirectedAdjacencyGraph.new\n each_vertex { |v| result.add_vertex v }\n each_edge { |u,v| result.add_edge(v, u) }\n result\n end", "def reverse\n reverseDiGraph = DiGraph.new\n @vertices.each {|x| adj(x).each { |y| reverseDiGraph.add_edge(y, x) } }\n reverseDiGraph\n end", "def undirected\n if directed?\n @undirected = true\n self.to_list\n end\n end", "def graph\n @g ||= GraphViz.new(:G, :type => :digraph)\n end", "def to_undirected(&edge_factory)\n edge_factory ||= Proc.new{ |e1, e2| UndirectedEdge.new(e1.from, e1.to) if e1 && e2 } \n\n edges = Set.new\n with_each_edge_and_inverse do |e, e_inverse|\n new_edge = edge_factory.call(e, e_inverse)\n edges.add(new_edge) if new_edge\n end\n\n UndirectedGraph.new.tap do |g|\n edges.each{ |e| g.add_edge(e) } \n end\n end", "def directed\n if undirected?\n @undirected = false\n self.to_list\n end\n end", "def rereverse_graph\n @a_matrix = ca_matrix\n read_vertices\n read_edges(0, 1)\n adj_lists\n end", "def undirected?\n @undirected ? true : false\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 alienlang(graph, in_degrees)\n g, deg, visited, solution = graph, in_degrees, 0, []\n\n # enqueue all vertices with an in-degree of 0\n queue = []\n deg.each do |k, v|\n if v == 0\n queue << k\n deg.delete(k)\n end\n end\n\n # until que is empty\n until queue.empty?\n solution << queue.shift\n visited += 1\n\n # traverse graph and remove edges\n parent = solution.last\n child = g[parent]\n # update in-degree count\n if deg.include?(child)\n deg[child] -= 1\n if deg[child] == 0 \n queue << child\n deg.delete(child)\n end\n end\n end\n\n g.length == visited ? solution : \"\"\nend", "def reversal\n result = self.class.new\n vertices.each { |vertex| result.add_vertex(vertex) }\n edges.each do |edge|\n newedge = edge.class.new(edge.target, edge.source, edge.label)\n result.add_edge(newedge)\n end\n result\n end", "def get_adjacency_list\n max_index = find_max_index\n adjacency_list = [nil] * max_index\n @edges.each do |edg|\n from_value = edg.node_from.value\n to_value = edg.node_to.value\n if adjacency_list[from_value]\n adjacency_list[from_value] << [to_value, edg.value]\n else\n adjacency_list[from_value] = [[to_value, edg.value]]\n end\n end\n adjacency_list\n end", "def topsort\n degree = {}\n zeros = []\n result = []\n\n # Collect each of our vertices, with the number of in-edges each has.\n @vertices.each do |name, wrapper|\n edges = wrapper.in_edges\n zeros << wrapper if edges.length == 0\n degree[wrapper.vertex] = edges\n end\n\n # Iterate over each 0-degree vertex, decrementing the degree of\n # each of its out-edges.\n while wrapper = zeros.pop do\n result << wrapper.vertex\n wrapper.out_edges.each do |edge|\n degree[edge.target].delete(edge)\n zeros << @vertices[edge.target] if degree[edge.target].length == 0\n end\n end\n\n # If we have any vertices left with non-zero in-degrees, then we've found a cycle.\n if cycles = degree.find_all { |vertex, edges| edges.length > 0 } and cycles.length > 0\n message = cycles.collect { |vertex, edges| edges.collect { |e| e.to_s }.join(\", \") }.join(\", \")\n raise Puppet::Error, \"Found dependency cycles in the following relationships: %s; try using the '--graph' option and open the '.dot' files in OmniGraffle or GraphViz\" % message\n end\n\n return result\n end", "def graph\n @graph ||= ordered_list.to_graph\n end", "def adjacency_list\n list = []\n list << self * 2 unless @parent == self * 2 or self * 2 > @@roof\n list << self / 2 unless self.odd? or @parent == self / 2\n list << self + 2 unless self + 2 > @@roof\n list\n end", "def nodes_upward\n LinkEnumerator.new :up, self\n end", "def to_dot\n dfa = to_cdfa\n dfa.depth\n dfa.order_states{|s,t| s[:depth] <=> t[:depth]}\n dfa.to_dot\n end", "def reverse_graph\n copy_graph # clone copy of old graph in cadj_lists, ca_matrix\n read_vertices\n read_edges(1, 0)\n @a_matrix = a_matrix.transpose\n end", "def make_adjlists(layout)\n layout.each do |edge|\n start = edge.village1\n ending = edge.village2\n color = edge.color\n type = edge.type_transit\n layout.each do |surround| \n if surround.village1 == ending && surround.village2 != start\n if surround.color == color || surround.type_transit == type\n edge.add_adjlist(surround)\n end\n end\n end\n end\nend", "def to_directed_graph(adapters)\n node_paths = {}\n adapters.each do |node|\n node_paths[node] = adapters.select{|other_node| other_node.between?(node+1, node+3)}\n end\n node_paths\nend", "def non_transitive\n triples = vertices.product(vertices, vertices)\n \n adjacent_triples = triples.select do |triple|\n adjacent_undirected(triple.first).include?(triple[1]) && adjacent_undirected(triple[1]).include?(triple.last)\n end\n \n adjacent_triples.reject do |triple|\n (adjacent_undirected(triple.first).include? triple.last) || (triple.first == triple.last)\n end\n end", "def to_graph(indent=nil)\n out = \"Parents:\\n\"\n self.parents.each { |parent| out << \" #{parent}\" }\n out << \"\\nObject: #{self.to_s}\\n\"\n out << \"Children:\\n\"\n self.children.each { |child| out << \" #{child}\" }\n out\n end", "def nodes_downward\n LinkEnumerator.new :down, self\n end", "def buildEdgeList graph, from, depth\n return [ ] if depth == 0\n to_list = graph.adjacent(from, {:direction => :out}).uniq\n ret = Set.new\n ret.merge(to_list.map { |to| [from, to] })\n to_list.each do |to|\n ret.merge(buildEdgeList graph, to, depth - 1)\n end\n ret\n end", "def kruskal\n # initialize\n rel = self.to_relations.sort{|a, b| a <=> b}\n index = []\n for i in 0 .. (rel.size - 1) do\n for j in (i + 1) .. (rel.size - 1) do\n if rel[i] == rel[j]\n index << j\n end\n end\n end\n index.sort{|x, y| y<=>x}.each do |i|\n rel[i, 1] = []\n end\n mst = []\n seen = Hash.new()\n @graph.each_key do |x|\n seen[x] = nil\n end\n i = 1\n # initialize end\n\n rel.each do |r|\n if seen[r.node[0]] == nil\n seen[r.node[0]] = 0\n end\n if seen[r.node[1]] == nil\n seen[r.node[1]] = 0\n end\n if seen[r.node[0]] == seen[r.node[1]] && seen[r.node[0]] == 0\n mst << r\n seen[r.node[0]] = i\n seen[r.node[1]] = i\n elsif seen[r.node[0]] != seen[r.node[1]]\n mst << r\n v1 = seen[r.node[0]].dup\n v2 = seen[r.node[1]].dup\n seen.each do |k, v|\n if v == v1 || v == v2\n seen[k] = i\n end\n end\n end\n i += 1\n end\n return Pathway.new(mst)\n end" ]
[ "0.6486657", "0.6296205", "0.62370664", "0.5971184", "0.57780004", "0.560419", "0.5532907", "0.54530483", "0.5427812", "0.5420133", "0.5372397", "0.5330243", "0.53203136", "0.53184295", "0.52453", "0.5230286", "0.52212965", "0.51883", "0.51729876", "0.51539457", "0.5146304", "0.5129516", "0.5091706", "0.5091101", "0.5083152", "0.5077685", "0.50724095", "0.5065348", "0.5045943", "0.50288254" ]
0.64383256
1
searches books.google.com for books by isbn. returns either a hash, or if given an object providing a from_hash(hash) method will fill it with the data. the object members must be named like the keys in the hash.
def search_by_isbn(isbn, object = nil) return nil if (isbn = isbn.gsub(/-/,"")).nil? @client = HTTPClient.new @book_hash = std_entry @isbn = isbn ol_hash = search_open_library isbndb_hash = search_isbndb gb_hash = search_google_books @book_hash.each {|k,v| @book_hash[k] = ol_hash[k] if @book_hash[k].blank? } @book_hash.each {|k,v| @book_hash[k] = isbndb_hash[k] if @book_hash[k].blank? } @book_hash.each {|k,v| @book_hash[k] = gb_hash[k] if @book_hash[k].blank? } if !object.nil? and object.respond_to? :from_hash puts @book_hash.inspect object.from_hash(@book_hash) object else @book_hash end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def book_by_isbn(isbn)\n\t\t\tresponse = request('/book/isbn', :isbn => isbn)\n\t\t\tHashie::Mash.new(response['book'])\t\t\t\t\n\t\tend", "def search_url\n \"http://books.google.com/books/feeds/volumes?q=ISBN#{ isbn }\"\n end", "def get_book( book_id )\n response = if book_id.to_s.length >= 10\n Amazon::Ecs.item_lookup( book_id, :id_type => 'ISBN', :search_index => 'Books', \n :response_group => 'Large,Reviews,Similarities,AlternateVersions' )\n else\n Amazon::Ecs.item_lookup( book_id, :response_group => 'Large,Reviews,Similarities' )\n end\n response.items.each do |item|\n binding = item.get('ItemAttributes/Binding')\n next if binding.match(/Kindle/i)\n return Book.new( item )\n end\n return nil\n end", "def book_by_title(title)\n\t\t\tresponse = request('/book/title', :title => title)\n\t\t\tHashie::Mash.new(response['book'])\n\t\tend", "def isbn(id, options={})\n perform_lookup('isbn', id, options)\n end", "def get_book( book_id )\n response = if book_id.to_s.length >= 10\n Amazon::Ecs.item_lookup( book_id, :id_type => 'ISBN', :search_index => 'Books', :response_group => 'Large,Reviews,Similarities' )\n else\n Amazon::Ecs.item_lookup( book_id, :response_group => 'Large,Reviews,Similarities' )\n end\n response.items.each do |item|\n binding = item.get('ItemAttributes/Binding')\n next if binding.match(/Kindle/i)\n return parse_item( item )\n end\n end", "def book(id)\n\t\t\tresponse = request('/book/show', :id => id)\n\t\t\tHashie::Mash.new(response['book'])\n\t\tend", "def book_by_author(author)\n\t\t\tresponse = request('/book/author', :author => author)\n\t\t\tHashie::Mash.new(response['book'])\n\t\tend", "def scrape_book_info(html)\n retval = {}\n html = restrict(html,\n /<div.+class\\s*=\\s*\"buying\".*?>\\s*<b/,\n %r{</div\\s*>})\n retval[:title] = scrape_title(html)\n retval[:authors] = scrape_authors(html)\n retval\nend", "def book_info_goodreads_library\n client = Goodreads::Client.new(Goodreads.configuration)\n results = client.book_by_title(params[:q]) if (params[:t] == \"title\" || params[:t].blank?)\n results = client.book_by_isbn(params[:q]) if params[:t] == \"isbn\"\n return results\n end", "def book_info_goodreads_library\n client = Goodreads::Client.new(Goodreads.configuration)\n results = client.book_by_title(params[:q]) if (params[:t] == \"title\" || params[:t].blank?)\n results = client.book_by_isbn(params[:q]) if params[:t] == \"isbn\"\n return results\n end", "def isbn\n @isbn\n end", "def data\n return @data if @data\n google_hash, data = to_hash, BookData.new\n\n data.creator = google_hash[:creator]\n data.date = google_hash[:date]\n data.description = google_hash[:description]\n data.format = google_hash[:format]\n data.id = google_hash[:id]\n data.identifier = google_hash[:identifier]\n data.language = google_hash[:language]\n data.publisher = google_hash[:publisher]\n\n if google_hash[:rating] && google_hash[:rating][:attributes]\n data.rating = google_hash[:rating][:attributes][:average].to_f\n data.rating_max = google_hash[:rating][:attributes][:max].to_f\n data.rating_min = google_hash[:rating][:attributes][:min].to_f\n end\n\n data.subject = google_hash[:subject].map { |s| s.split(/ [\\-\\/] /) }.flatten.map(&:strip).uniq.sort\n data.title = google_hash[:title].uniq.join(\" \")\n data.updated = google_hash[:updated]\n data.category = google_hash[:category]\n data.embeddability = google_hash[:embeddability][:value]\n data.open_access = google_hash[:openAccess][:value]\n data.viewability = google_hash[:viewability][:value]\n\n google_hash[:link].each do |link|\n href = link.is_a?(Hash) ? link[:attributes][:href] : link.last[:href]\n rel = link.is_a?(Hash) ? link[:attributes][:rel] : link.last[:rel]\n data.send(\"#{rel[/thumbnail|info|annotation|alternate|self/]}_url=\", href)\n end\n\n @data = data\n end", "def get_book_with_api(title)\n uri = URI.parse(URI.encode(\"https://www.googleapis.com/books/v1/volumes?q=#{title}\"))\n service = Books::ApiConnectService.new(uri)\n book_response = service.execute[\"items\"].first[\"volumeInfo\"]\n .select{ |key, value| key == \"title\" || key == \"description\" || key == \"publisher\" || key == \"publishedDate\" || key == \"imageLinks\"}\n @book_info_hash = book_response.inject({}) do |hash, (key, value)|\n if key.underscore == \"image_links\"\n hash[key.underscore] = book_response[\"imageLinks\"][\"smallThumbnail\"]\n else\n hash[key.underscore] = value\n end\n hash\n end\n end", "def return_book_hash_simple(book_title_str)\n for book_hash in @books\n if book_hash[:title] == book_title_str\n return book_hash\n end\n end\n return \"The book is not available\"\n end", "def isbn\n @isbn\n end", "def isbn\n @isbn\n end", "def book_info(book_title)\n for book in @books\n return book if book[:title] == book_title\n end\n return nil\n end", "def select_books(books_hash)\n books_keys = books_hash.keys\n counter = 0\n dzogchen_books = {}\n\n loop do\n break if counter == books_hash.size\n\n current_key = books_keys[counter]\n current_value = books_hash[current_key]\n\n if current_value == 'Dzogchen'\n dzogchen_books[current_key] = current_value\n end\n\n counter += 1\n end\n\n dzogchen_books\nend", "def search_book_by_name(book)\n url = \"https://www.googleapis.com/books/v1/volumes?q=#{URI::encode(book)}&key=#{get_access_key}\"\n\tres = JSON.load(RestClient.get(url))\n return res\t\nend", "def isbn; end", "def get_books\n unless self.scraped\n page = Nokogiri::HTML(open(self.url), nil, \"iso-8859-1\")\n item_elements = page.css(\".g-span7when-wide\")\n item_elements.each do |item|\n book_data = {}\n book_data[:title] = item.at_css(\".a-link-normal\").text.strip\n book_data[:author] = item.at_css(\".a-size-small\").text.split(\"by\")[-1].strip\n book_data[:price] = item.at_css(\".a-color-price\").text.strip\n book_data[:price] = \"N/A\" unless book_data[:price].include?(\"$\")\n book_data[:asin] = item.at_css(\".a-link-normal\")[\"href\"].split(\"/\")[2].strip.split(\"?\")[0]\n self.books << Book.new(book_data)\n end\n self.last_scraped = Time.now\n self.scraped = true\n end\n end", "def find_isbns(w)\n client = Openlibrary::Client.new\n found = 0\n missing = 0\n row = 2\n until (name = w[row, 2]).empty?\n isbn = w[row, 10]\n if isbn.empty?\n missing += 1\n last_name = name.split(',').first\n # search api breaks on punctuation, remove it, keep spaces\n title = w[row, 1].gsub(/([^\\w ])/, '')\n begin\n results = client.search({author: last_name, title: title})\n # some results do not have an isbn, so keep trying\n for r in results\n unless r.isbn.nil?\n isbn = r.isbn.first\n break\n end\n end\n puts '%-3s: %s | %s -> %s' % [row, last_name, title, isbn]\n found += 1 unless isbn.empty?\n w[row, 10] = isbn.to_s\n rescue Exception => e\n puts '%-3s: %s' % [row, e.message]\n end\n end\n row += 1\n end\n puts 'found %s, missing %s' % [found, missing]\nend", "def initialize(isbn)\n @isbn = isbn\n @query_url = Goodreads::Book.make_query_url(isbn)\n end", "def search_for_google_books(search_term)\n url = \"https://www.googleapis.com/books/v1/volumes?q=#{search_term}\"\n response = RestClient.get(url)\n hash = JSON.parse(response)\n hash[\"items\"]\nend", "def get_wishlist(email, stream)\n books = []\n\n # attempt to retrieve the wishlist\n uri = URI.parse(\"http://www.amazon.com/registry/search.html?type=wishlist&field-name=#{email}\")\n uri_path = \"#{uri.path}?#{uri.query}\"\n request = Net::HTTP::Get.new(uri_path)\n response = Net::HTTP.start(uri.host, uri.port) do |http|\n http.request(request)\n end\n wishlist_url = response['location']\n\n if wishlist_url.nil?\n stream << \"data: status: Cannot find the wishlist for #{email}\\n\\n\"\n stream << \"data: #{nil}\\n\\n\"\n stream.flush\n return\n else\n stream << \"data: status: Found the wishlist for #{email}\\n\\n\"\n end\n\n # the filter=3 is filter by books\n page = Nokogiri::HTML(open(\"#{wishlist_url}&layout=compact\"))\n # get the divs and parse out their title and author\n page.css('tbody[class=itemWrapper]').each do |part|\n link_with_isbn = part.css('span[class=\"small productTitle\"] a')\n link = link_with_isbn.length > 0 ? link_with_isbn.first : nil\n if link.nil?; next end\n\n # get the href attribute and try to get a match for the ISBN\n isbn_available = link.attr('href').match(/dp\\/([\\d\\w]+)\\//)\n if not isbn_available\n isbn_available = link.attr('href').match(/gp\\/product\\/([\\d\\w]+)[\\/\\?]/)\n end\n \n # did we get an ISBN?\n if isbn_available && isbn_available.captures.one?\n isbn = isbn_available.captures.pop\n title = link_with_isbn.text.strip\n books.push({ :title => title, :isbn => isbn, :url => link.attr('href') })\n end\n end\n\n books\nend", "def isbn(text)\n match = text.match(/^\\s*urn:isbn:([0-9]{13,13})\\s*$/)\n if match\n return match[1]\n end\n\n match = text.match(/^\\s*([0-9]{13,13})\\s*$/)\n if match\n return match[1]\n end\n\n nil\n end", "def get_book(search)\n\trequest_string = \"https://www.googleapis.com/books/v1/volumes?q=#{search.gsub(\" \",\"+\")}\"\n\t\n\tsample_uri = URI(request_string) #opens a portal to the data at that link\n\tsample_response = Net::HTTP.get(sample_uri) #go grab the data in the portal\n\tsample_parsedResponse = JSON.parse(sample_response) #makes data easy to read\n\tsample_parsedResponse[\"items\"]\nend", "def get_book_details(title)\n for book in @all_books\n return book if book[:title] == title\n end\n end", "def get_book(params = {})\n item = @items.detect{|i| i[params.keys.first] == params.values.first} || @items.detect{|i| i[\"volumeInfo\"][params.keys.first] == params.values.first}\n @book = BookItem.new(item: item)\n end" ]
[ "0.6751553", "0.6086912", "0.60364693", "0.5924739", "0.59067893", "0.57909685", "0.561289", "0.55804366", "0.55078435", "0.5490632", "0.5490632", "0.5488336", "0.5474147", "0.54411167", "0.5440768", "0.54307944", "0.54307944", "0.5427307", "0.5415426", "0.5379322", "0.5373496", "0.5354202", "0.5351856", "0.5340679", "0.5333322", "0.5260626", "0.52604705", "0.52411103", "0.52313846", "0.5179715" ]
0.7637749
0
Creates a new AESPipe object with the given _options_. If a _block_ is given, it will be passed the newly created AESPipe object. _options_ may contain the following keys: :mode:: The mode of the cipher, either :encrypt or :decrypt. Defaults to :encrypt. :block_size:: The blocksize to use with the cipher. Defaults to 4096. :key_size:: The keysize of the cipher. Defaults to 256. :iv:: The Initial Vector (IV) to use with the cipher. Defaults to 19070547872603305. :hash:: The hash to use with the cipher. Defaults to SHA256. :key:: The key to use with the cipher. :password:: If :key is not given, :password can be given. The password will be hashed and used as the key. AESPipe.new(:mode => :encrypt, :password => 'pants') do |aes| aes.cipher do |cipher| aes.process_output(output_file) do |output| aes.process_input(input_file) do |text| output << cipher.update(text) end output << cipher.final end end end
def initialize(options={},&block) @mode = options.fetch(:mode,:encrypt).to_sym @block_size = options.fetch(:block_size,DEFAULT_BLOCK_SIZE).to_i @key_size = options.fetch(:key_size,DEFAULT_KEY_SIZE).to_i @iv = options.fetch(:iv,DEFAULT_IV).to_s @hash = options.fetch(:hash,DEFAULT_HASH).to_s.downcase @key = if options[:key] options[:key].to_s elsif (password = options[:password]) begin Digest.const_get(@hash.upcase).hexdigest(password) rescue RuntimeError => e raise(InvalidHash,"invalid hash name #{@hash.dump}") end end yield self if block_given? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cipher\n aes = OpenSSL::Cipher::Cipher.new(\"aes-#{@key_size}-cbc\")\n\n case @mode\n when :encrypt\n aes.encrypt\n when :decrypt\n aes.decrypt\n else\n raise(InvalidMode,\"invalid mode #{@mode}\")\n end\n\n aes.key = @key\n aes.iv = @iv\n\n yield aes if block_given?\n return aes\n end", "def initialize(options, &block)\n super\n input_channel.register(self)\n @block = block if block\n end", "def pipe(&block)\n cmds = Commands.new(mode: :pipe)\n cmds.instance_eval(&block)\n self.!(cmds.to_a)\n end", "def initialize( application, options = {} )\n\n @application = application\n @options = options\n @cipher = OpenSSL::Cipher.new( DataCipher )\n @iv_cipher = OpenSSL::Cipher.new( InitializationVectorCipher )\n @digest = OpenSSL::Digest::Digest.new( DigestType )\n @session_stack = [ ]\n\n end", "def crypto(&block)\n @crypto = Crypto::Configuration.new(&block) if block_given?\n @crypto\n end", "def initialize(options={})\n @logging = options.fetch(:logging, false)\n @level = options.fetch(:level, :info)\n @store = options.fetch(:store, :memstore)\n @crypto = Crypto::Configuration.new\n\n yield self if block_given?\n end", "def cipher\r\n aes = OpenSSL::Cipher::AES.new(128, :CBC)\r\n aes.encrypt\r\n aes.key = key\r\n aes.iv = iv\r\n return aes\r\n end", "def from_block\n options = new\n dsl = ExecutionOptionsDSL.new(options)\n yield dsl\n options\n end", "def initialize(key,iv)\n \t\t\t\t@key = key\n \t\t\t\t@iv = iv\n \t\t\t\t@aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc')\n \t\t\t\[email protected] = key\n \t\t\t\[email protected] = iv\n \t\t\t\[email protected]\n \t\t\t\t@block = @aes.update(iv) << @aes.final\n \t\t\t\t@index = 0\n \t\t\tend", "def encrypt_with\n log!\n prepare\n\n if mode_options.empty?\n raise Error, \"Encryption could not be performed for mode '#{mode}'\"\n end\n\n yield \"#{utility(:gpg)} #{base_options} #{mode_options}\", \".gpg\"\n ensure\n cleanup\n end", "def encrypt!(block) \n Bes.new(material).encrypt block\n end", "def initialize(password, size=256, mode=\"cbc\")\n @password = password\n @size = size\n @mode = mode\n @cipher = OpenSSL::Cipher::Cipher.new(\"aes-#{size}-#{mode}\")\n end", "def aes_ecb_internal(mode, buffer, key)\n raise 'Buffer must be composed of 16-byte chunks' unless (buffer.size % 16).zero?\n cipher = OpenSSL::Cipher.new('AES-128-ECB')\n cipher.send(mode)\n cipher.key = key.pack('C*')\n cipher.padding = 0 # decryption will otherwise fail\n result = cipher.update(buffer.pack('C*')) + cipher.final\n result.unpack('C*')\nend", "def encrypt_with(name, &block)\n @encryptor = get_class_from_scope(Encryptor, name).new(&block)\n end", "def pipeline(context_name=nil, &block)\n if block\n options = context.fetch\n current_options = context.fetch(context_name)\n options.merge!(current_options) unless context_name.nil?\n ssh_options = _ssh_options(options.ssh_options)\n sshkit_wrapper(options, ssh_options).instance_exec(&block)\n end\n end", "def initialize_cipher_for(mode)\n @cipher.send mode\n @cipher.key = @config['key']\n @cipher.iv = @config['iv']\n end", "def initialize(options = {})\n @options = {:mode => :lines, :no_buffer => false}.merge(options)\n\n logger.info \"Initializing with options: #{@options.inspect}\"\n\n if @options[:mode] == :chars\n @reader = proc {|s| s.getc }\n else\n @reader = proc {|s| s.gets }\n end\n\n @mutex = Mutex.new\n reset\n end", "def protecting_encrypted_data(&block)\n with_encryption_context encryptor: ActiveRecord::Encryption::EncryptingOnlyEncryptor.new, frozen_encryption: true, &block\n end", "def pipeopts(context_name=nil, &block)\n unless block.nil?\n # evaluate pipopts DSL\n EnvironmentDSL.new(context_name, context).instance_exec(&block)\n else\n # return current context\n context.fetch(context_name)\n end\n end", "def initialize(options = {}, &block)\n\t\t \n\t\t\tyield self unless block == nil\n\t\tend", "def initialize\n @edit_distance = 3\n @cipher_spec = \"AES-256-CBC\"\n @padding_byte_size = 32\n end", "def block\n options.fetch(:block)\n end", "def initialize(options, &blk)\n @options = options\n @blk = blk\n end", "def initialize(symbol, options, &block)\n @symbol, @options, @block = symbol,options,block\n end", "def initialize(_options = {}, &block)\n yield self unless block.nil?\n end", "def add_options(&block)\n if options\n old_options = options\n self.options = proc do\n instance_exec(&old_options)\n instance_exec(&block)\n end\n else\n self.options = block\n end\n self\n end", "def initialize(options, &block)\n @template = options.fetch(:template)\n @seed = \"#{Process.pid}#{options.fetch(:seed, generate_seed).to_i}\"\n\n @env = (ENV_TEMPLATE % @seed).freeze\n @database = \"#{@template}_#{@seed}\".freeze\n\n execute(&block) unless block.nil?\n end", "def build_cipher(args={})\n cipher = OpenSSL::Cipher.new('AES-256-CBC')\n args[:decrypt] ? cipher.decrypt : cipher.encrypt\n iv = args[:iv]\n until(iv.length > 65)\n iv = iv * 2\n end\n key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(\n args[:key], CRYPT_SALT, CRYPT_ITER, CRYPT_KEY_LENGTH\n )\n cipher.iv = iv\n cipher.key = key\n cipher\n end", "def with_cipher\n return yield(init_cipher) unless cipher_reuse_enabled?\n\n with_reusable_cipher do |reusable_cipher|\n yield reusable_cipher\n end\n end", "def initialize(options={}, &block)\n if options[:size]\n options[:width] = options[:size][0]\n options[:height] = options[:size][1]\n end\n options = DefaultOptions.merge(options)\n\n @width = options[:width]\n @height = options[:height]\n @output = options[:filename] || 'test'\n @stacksize = 0\n @colorspace = CGColorSpaceCreateDeviceRGB() # => CGColorSpaceRef\n @autoclosepath = false\n\n case options[:type]\n when :pdf\n @filetype = :pdf\n # CREATE A PDF DRAWING CONTEXT\n # url = NSURL.fileURLWithPath(image)\n url = CFURLCreateFromFileSystemRepresentation(nil, @output, @output.length, false)\n pdfrect = CGRect.new(CGPoint.new(0, 0), CGSize.new(width, height)) # Landscape\n #@ctx = CGPDFContextCreateWithURL(url, pdfrect, nil)\n consumer = CGDataConsumerCreateWithURL(url);\n pdfcontext = CGPDFContextCreate(consumer, pdfrect, nil);\n CGPDFContextBeginPage(pdfcontext, nil)\n @ctx = pdfcontext\n when :image, :render\n # CREATE A BITMAP DRAWING CONTEXT\n @filetype = File.extname(@output).downcase[1..-1].intern if options[:type] == :image\n\n @bits_per_component = 8\n @colorspace = CGColorSpaceCreateDeviceRGB() # => CGColorSpaceRef\n #alpha = KCGImageAlphaNoneSkipFirst # opaque background\n alpha = KCGImageAlphaPremultipliedFirst # transparent background\n\n # 8 integer bits/component; 32 bits/pixel; 3-component colorspace; kCGImageAlphaPremultipliedFirst; 57141 bytes/row.\n bytes = @bits_per_component * 4 * @width.ceil\n @ctx = CGBitmapContextCreate(nil, @width, @height, @bits_per_component, bytes, @colorspace, alpha) # => CGContextRef\n when :context\n @ctx = options[:context]\n else\n raise \"ERROR: output file type #{ext} not recognized\"\n end\n\n # antialiasing\n CGContextSetAllowsAntialiasing(@ctx, true)\n\n # set defaults\n fill # set the default fill\n nostroke # no stroke by default\n strokewidth # set the default stroke width\n font # set the default font\n antialias # set the default antialias state\n autoclosepath # set the autoclosepath default\n quality(options[:quality]) # set the compression default\n push # save the pristine default default graphics state (retrieved by calling \"reset\")\n push # create a new graphics state for the user to mess up\n if block_given?\n case block.arity\n when 0\n send(:instance_eval, &block)\n else\n block.call(self)\n end\n end\n end" ]
[ "0.6165562", "0.5306818", "0.52144134", "0.51730794", "0.51517487", "0.51302695", "0.5126202", "0.49991134", "0.4973685", "0.49599954", "0.49546283", "0.49170345", "0.49100235", "0.49000397", "0.4895201", "0.4837976", "0.483294", "0.4815814", "0.47978482", "0.47694778", "0.4768197", "0.4747799", "0.47371092", "0.46493486", "0.46465865", "0.46460566", "0.46434987", "0.46324426", "0.46265042", "0.45899636" ]
0.64230424
0
Returns a new AES cipher object. If a _block_ is given it will be passed the newly created cipher.
def cipher aes = OpenSSL::Cipher::Cipher.new("aes-#{@key_size}-cbc") case @mode when :encrypt aes.encrypt when :decrypt aes.decrypt else raise(InvalidMode,"invalid mode #{@mode}") end aes.key = @key aes.iv = @iv yield aes if block_given? return aes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cipher\r\n aes = OpenSSL::Cipher::AES.new(128, :CBC)\r\n aes.encrypt\r\n aes.key = key\r\n aes.iv = iv\r\n return aes\r\n end", "def encrypt_with(name, &block)\n @encryptor = get_class_from_scope(Encryptor, name).new(&block)\n end", "def get_cipher\n OpenSSL::Cipher::Cipher.new('AES-256-CBC')\n end", "def encrypt!(block) \n Bes.new(material).encrypt block\n end", "def new_cipher(direction, password, salt)\n cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE)\n direction == :encrypt ? cipher.encrypt : cipher.decrypt\n cipher.key = encrypt_key(password, salt)\n cipher\n end", "def new_cipher(direction, passwd, options = {})\n check_platform_can_encrypt!\n cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE)\n case direction\n when :encrypt\n cipher.encrypt\n when :decrypt\n cipher.decrypt\n else\n raise \"Bad cipher direction #{direction}\"\n end\n cipher.key = encrypt_key(passwd, options)\n cipher\n end", "def with_cipher\n return yield(init_cipher) unless cipher_reuse_enabled?\n\n with_reusable_cipher do |reusable_cipher|\n yield reusable_cipher\n end\n end", "def build_cipher(args={})\n cipher = OpenSSL::Cipher.new('AES-256-CBC')\n args[:decrypt] ? cipher.decrypt : cipher.encrypt\n iv = args[:iv]\n until(iv.length > 65)\n iv = iv * 2\n end\n key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(\n args[:key], CRYPT_SALT, CRYPT_ITER, CRYPT_KEY_LENGTH\n )\n cipher.iv = iv\n cipher.key = key\n cipher\n end", "def decipher\r\n aes = OpenSSL::Cipher::AES.new(128, :CBC)\r\n aes.decrypt\r\n aes.key = key\r\n aes.iv = iv\r\n return aes\r\n end", "def crypto(&block)\n @crypto = Crypto::Configuration.new(&block) if block_given?\n @crypto\n end", "def initialize(key,iv)\n \t\t\t\t@key = key\n \t\t\t\t@iv = iv\n \t\t\t\t@aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc')\n \t\t\t\[email protected] = key\n \t\t\t\[email protected] = iv\n \t\t\t\[email protected]\n \t\t\t\t@block = @aes.update(iv) << @aes.final\n \t\t\t\t@index = 0\n \t\t\tend", "def initialize\n self.cipher = AesCipher.new\n end", "def initialize(options={},&block)\n @mode = options.fetch(:mode,:encrypt).to_sym\n @block_size = options.fetch(:block_size,DEFAULT_BLOCK_SIZE).to_i\n @key_size = options.fetch(:key_size,DEFAULT_KEY_SIZE).to_i\n @iv = options.fetch(:iv,DEFAULT_IV).to_s\n @hash = options.fetch(:hash,DEFAULT_HASH).to_s.downcase\n @key = if options[:key]\n options[:key].to_s\n elsif (password = options[:password])\n begin\n Digest.const_get(@hash.upcase).hexdigest(password)\n rescue RuntimeError => e\n raise(InvalidHash,\"invalid hash name #{@hash.dump}\")\n end\n end\n\n yield self if block_given?\n end", "def encrypt_with(name, &block)\n @encryptors << Backup::Encryptor.const_get(\n last_constant(name)\n ).new(&block)\n end", "def find_cipher(*args)\n fail ArgumentError, 'Unknown algorithm ' + algorithm unless args[0] == 'http://www.w3.org/2001/04/xmlenc#aes256-cbc'\n\n cipher = ::OpenSSL::Cipher.new('AES-256-CBC')\n cipher.decrypt\n cipher.padding = 0\n cipher.key = find_cipher_key(cipher, *args[1..4])\n cipher.iv = args[5]\n\n cipher\n end", "def initialize_cipher_for(mode)\n @cipher.send mode\n @cipher.key = @config['key']\n @cipher.iv = @config['iv']\n end", "def decryptAES128ECBblock(inputblock, keybytes)\n\tinput, key = bytearraytostring(inputblock), bytearraytostring(keybytes)\n\tdecipher = OpenSSL::Cipher::AES.new(128, 'ECB')\n\tdecipher.decrypt\n\tdecipher.key = key\n\tdecipher.padding = 0\n\treturn stringtobytearray(decipher.update(input) + decipher.final)\nend", "def without_encryption(&block)\n with_encryption_context encryptor: ActiveRecord::Encryption::NullEncryptor.new, &block\n end", "def cipher(key, iv, encrypt = true)\n mode = @modes[@mode] % (@key_len * 8)\n cipher = OpenSSL::Cipher.new(mode)\n encrypt ? cipher.encrypt : cipher.decrypt\n cipher.key = key\n cipher.iv = iv\n cipher\n end", "def client\n @client ||= ActiveSupport::MessageEncryptor.new(@key, cipher: 'aes-256-cbc')\n end", "def protecting_encrypted_data(&block)\n with_encryption_context encryptor: ActiveRecord::Encryption::EncryptingOnlyEncryptor.new, frozen_encryption: true, &block\n end", "def aes_ecb_internal(mode, buffer, key)\n raise 'Buffer must be composed of 16-byte chunks' unless (buffer.size % 16).zero?\n cipher = OpenSSL::Cipher.new('AES-128-ECB')\n cipher.send(mode)\n cipher.key = key.pack('C*')\n cipher.padding = 0 # decryption will otherwise fail\n result = cipher.update(buffer.pack('C*')) + cipher.final\n result.unpack('C*')\nend", "def initialize(context, offset = T.unsafe(nil), decrypter = T.unsafe(nil)); end", "def initialize(password, size=256, mode=\"cbc\")\n @password = password\n @size = size\n @mode = mode\n @cipher = OpenSSL::Cipher::Cipher.new(\"aes-#{size}-#{mode}\")\n end", "def local_cipher_obj\n @local_cipher_obj ||= begin\n kyc_salt_e = @user_extended_detail_obj.kyc_salt\n r = Aws::Kms.new('kyc', 'admin').decrypt(kyc_salt_e)\n throw 'Unable to decrypt data' unless r.success?\n\n kyc_salt_d = r.data[:plaintext]\n LocalCipher.new(kyc_salt_d)\n end\n end", "def aes_cbc_encrypt(buffer, key, iv)\n blocks = buffer.each_slice(key.size)\n previous_ciphertext_block = iv\n\n blocks.flat_map do |block|\n previous_ciphertext_block = aes_ecb_encrypt(\n xor_bytes(previous_ciphertext_block, block),\n key\n )\n\n previous_ciphertext_block\n end\nend", "def new_block_el(*args)\n el = Element.new(*args)\n if @block_ial\n el.options[:ial] = @block_ial\n @block_ial = nil\n end\n el\n end", "def initialize(cipher, key)\n raise \"Cipher block size must be #{BLOCK_SIZE}\" unless cipher.block_size == BLOCK_SIZE\n\n @cipher = cipher\n @cipher.encrypt\n @cipher.key = @key = key\n\n generate_subkeys\n reset\n end", "def build(salt = nil, iv = nil)\n cipher = OpenSSL::Cipher.new(arguments[:cipher] || DEFAULT_CIPHER)\n iv ? cipher.decrypt : cipher.encrypt\n key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(\n arguments[:key],\n salt,\n arguments.fetch(:iterations, CRYPT_ITER),\n arguments.fetch(:key_length, CRYPT_KEY_LENGTH)\n )\n cipher.iv = iv if iv\n cipher.key = key\n cipher\n end", "def initialize\n @edit_distance = 3\n @cipher_spec = \"AES-256-CBC\"\n @padding_byte_size = 32\n end" ]
[ "0.68026704", "0.6411067", "0.6362697", "0.6215968", "0.6100016", "0.60487854", "0.5936557", "0.5882147", "0.583795", "0.5776261", "0.5725184", "0.57234573", "0.56403446", "0.56391084", "0.5605318", "0.5602889", "0.5559221", "0.5432213", "0.53685135", "0.53601974", "0.5337855", "0.53339255", "0.5324883", "0.53210944", "0.52966166", "0.5275346", "0.51964843", "0.5177298", "0.51663786", "0.51585287" ]
0.7284387
0
Processes an input stream of the given _file_ and the specified _block_. If _file_ is not given +STDIN+ will be used instead. The specified _block_ will be passed each block of data from the stream. Once the _block_ has returned the input stream will be closed.
def process_input(file=nil) input = if file File.new(file.to_s) else STDIN end loop do text = input.read(@block_size) break unless text yield text end input.close return nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_input_stream(&block); end", "def read_file(block=0)\n Rula.log(Logger::DEBUG,\"Reading file #{filename} block #{block}\",self)\n return nil if(block >= @file_size)\n return nil if(block < 0)\n file_handle = File.open(@filename,'rb')\n file_handle.pos = block\n @previous_block_read = file_handle.pos\n data = file_handle.read(@@BLOCK_SIZE)\n @last_block_read = file_handle.pos\n Rula.log(Logger::DEBUG,\"Read #{data.length} bytes\",self)\n @file_eof = file_handle.eof\n return data\n ensure \n file_handle.close() unless file_handle.nil?\n end", "def read &block\n prep_read\n data = block_given? ?\n file_handle.each {|line| yield line } :\n file_handle.read\n @read_position = file_handle.pos\n data\n end", "def process_blocks(blocks); end", "def input_stream(input)\n if input.is_a?(IO)\n yield input\n else\n File.open(input, 'r') { |stream| yield stream }\n end\n end", "def read(block)\n @filemgr.read(block, @contents)\n end", "def process_input(file)\n if file == '-'\n read_stdin\n else\n call_write(\n process_input_file(load_data(Pathname.new(file)).split(\"\\n\"))\n )\n end\n end", "def handle_block(block_info) # :nodoc:\n if block_info.type == CONTROL_BLOCK\n read_control_block\n elsif block_info.type == DATA_BLOCK\n if !declared_stream?(block_info.index)\n Pocolog.warn \"found data block for stream #{block_info.index} but this stream has never been declared, seems Logfile is Corrupted. Skipping...\"\n end\n elsif block_info.type == STREAM_BLOCK\n read_stream_declaration\n end\n block_info.type\n end", "def parse(&block)\n # override block\n if block\n orig_block = self.callback_block\n self.callback_block = block\n end\n\n self.index = -1\n until file.eof? || self.done\n self.index += 1\n line = file.read(64)\n\n tail = line[44, 20]\n tail_data = tail ? parse_tail(tail) : {}\n\n parse_line(line, tail_data)\n end\n self.callback_block = orig_block if orig_block\n self.saved if self.debug || self.done\n end", "def each_input_line(&block)\n @input.each_line {|l| block.call l.chomp }\n end", "def pass_file_to_block(filename)\n File.open(filename, \"r\") do |infile|\n while (line = infile.gets)\n puts \"#{counter}: #{line}\"\n counter = counter + 1\n end\n end\n end", "def io(input = nil, output = nil, &block)\n orig_stdin, orig_stdout = $stdin, $stdout\n $stdin = File.new(input) if input\n $stdout = File.new(output, 'r+') if output\n return unless block\n\n yield\n $stdin, $stdout = orig_stdin, orig_stdout\n reset_io\n end", "def block\n (@blocks ||= Array.new) << Block.new\n @in_block = @blocks.last\n yield\n @in_block = nil\n end", "def process\n outs = []\n @infiles.each do |f|\n if f.instance_of? Hash\n dat = f[:block].(f[:file])\n if dat.instance_of? String\n out << dat + \"\\n\\n\"\n else\n fail TypeError, \"#{dat.class} returned, String expected\"\n end\n elsif f.instance_of? String\n outs << File.read(f)\n elsif f.instance_of? Array\n outs << f.map { |fn| File.read(fn) }\n else\n fail TypeError, \"Infile #{f.inspect} is not a hash nor a string nor an array!\"\n end\n end\n out = outs.join(\"\\n\\n\")\n if @block\n out = @block.(out)\n end\n if @outfile\n File.delete(@outfile) if File.exist? @outfile\n File.open(@outfile, 'w') do |f|\n f.write(out)\n end\n end\n out\n end", "def process_stdin\n process_file_handle($stdin)\n end", "def read(&block)\n @read_block = block\n end", "def open(file, &blk)\n encoding = file_encoding(file)\n mode = encoding.nil? ? \"r\" : \"rb:#{encoding}\"\n File.open(file, \"#{mode}\") do |f|\n while line = f.gets\n line = line.nil? ? nil : cook_line(line.encode(@encoding))\n blk.call(line)\n end\n end\n end", "def each_block(rewind = true, with_prologue = true)\n\t self.rewind if rewind\n\t while !eof?\n\t\tio = self.rio\n\t\tif @next_block_pos == 0 && with_prologue\n\t\t read_prologue\n\t\telse\n\t\t io.seek(@next_block_pos)\n\t\tend\n\n\t\t@data = nil\n\t\t@data_header.updated = false\n\n if !read_block_header\n next_io\n next\n end\n\n\t\tyield(@block_info)\n\t end\n\trescue EOFError\n\tend", "def input_handler\n STDIN.read.split(\"\\n\").each do |line|\n process_line(line)\n end\n end", "def process_input_file \n File.open(@file, 'r') do |f|\n f.each_line do |line|\n parse_line(line)\n end\n end\n end", "def next_block\n lines = []\n\n line = @fh.gets\n while !start_of_block?(line)\n line = @fh.gets\n return \"\" if @fh.eof?\n end\n\n while([email protected]? && !end_of_block?(line))\n lines << line.chomp\n line = @fh.gets\n end\n\n lines.join(\"\\n\")\n end", "def input(&block)\n return @input unless block_given?\n @input = Input.new\n @input.instance_eval(&block)\n end", "def each(&block)\n File.open(filepath, 'rb') do |io|\n while part = io.read(block_size)\n yield part\n end\n end\n end", "def each_chunk stream\n while !stream.eof?\n yield read_chunk stream\n end\n end", "def blocks_from_file(file)\n bytes = IO.binread(file)\n io = StringIO.new(bytes)\n blocks = []\n\n until io.eof?\n begin\n blocks << Block.new(io)\n rescue\n # ignore invalid blocks\n end\n end\n\n blocks\n end", "def readlines(&block)\n loop do\n if @lines.size < 3 && [email protected]?\n @lines << @f.readline\n elsif @lines.size == 0 && @f.eof?\n break\n else\n yield @lines.shift\n end\n end\n end", "def each_data_block(stream_index = nil, rewind = true, with_prologue = true)\n\t each_block(rewind) do |block_info|\n if handle_block(block_info) == DATA_BLOCK\n if !stream_index || stream_index == block_info.index\n yield(block_info.index)\n end\n end\n\t end\n\n\trescue EOFError\n\trescue\n\t if !rio\n\t\traise $!\n elsif !rio.closed?\n\t\traise $!, \"#{$!.message} at position #{rio.pos}\", $!.backtrace\n\t end\n\tend", "def process(&block); end", "def consume_simple_block(input = @tokens)\n start_token = input.current[:node]\n end_token = BLOCK_END_TOKENS[start_token]\n\n block = {\n :start => start_token.to_s,\n :end => end_token.to_s,\n :value => [],\n :tokens => [input.current]\n }\n\n block[:tokens].concat(input.collect do\n while token = input.consume\n break if token[:node] == end_token\n\n input.reconsume\n block[:value] << consume_component_value(input)\n end\n end)\n\n create_node(:simple_block, block)\n end", "def process_line(line, index, block_opened)\n @index = index + 1\n @block_opened = block_opened\n\n case line[0]\n when DIV_CLASS, DIV_ID\n render_div(line)\n when ELEMENT\n render_tag(line)\n when COMMENT\n render_comment(line)\n when SCRIPT\n sub_line = line[1..-1]\n if sub_line[0] == SCRIPT\n push_script(sub_line[1..-1].strip.dump.gsub('\\\\#', '#'), false)\n else\n push_script(sub_line, false)\n end\n when FLAT_SCRIPT\n warn(FLAT_WARNING) unless defined?(Test::Unit)\n push_flat_script(line[1..-1])\n when SILENT_SCRIPT\n sub_line = line[1..-1]\n unless sub_line[0] == SILENT_COMMENT\n mbk = mid_block_keyword?(line)\n push_silent(sub_line, !mbk)\n if (@block_opened && !mbk) || line[1..-1].split(' ', 2)[0] == \"case\"\n push_and_tabulate([:script])\n end\n end\n when FILTER\n name = line[1..-1].downcase\n start_filtered(options[:filters][name] || name)\n when DOCTYPE\n if line[0...3] == '!!!'\n render_doctype(line)\n else\n push_plain line\n end\n when ESCAPE\n push_plain line[1..-1]\n else\n push_plain line\n end\n end" ]
[ "0.64599484", "0.62070936", "0.60026777", "0.5932396", "0.5922345", "0.5884504", "0.5769879", "0.57655627", "0.57385254", "0.5722197", "0.56439584", "0.55800575", "0.5545476", "0.54967123", "0.54726946", "0.5436581", "0.540953", "0.5375816", "0.5365595", "0.5356251", "0.532082", "0.5319234", "0.53049445", "0.5292456", "0.5252452", "0.52446175", "0.5226809", "0.52203786", "0.5208386", "0.51898396" ]
0.73888326
0
Select instances by role, with optional name constraints. Select the "master" app instance: select_instances(app_master: true) Select the "master" db instance on a solo or multiinstance env: select_instances(solo: true, db_master: true) Select app, app_master, or utils (only if they are named resque or redis): select_instances(app_master: true, app: true, util: %w[resque redis]) Select all instances (same as the method instances): select_instances(all: true) See instances_by_role for a simpler interface.
def select_instances(options) instances_by_role(options.keys).select do |inst| # get the value of the string/symbol key that matches without losing nil/false values val = options.fetch(inst.role.to_sym) { options.fetch(inst.role.to_s, false) } case val when true, false then val when inst.name then true when nil, '' then [nil, ''].include?(inst.name) when Array then val.include?(inst.name) else false end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def instances_by_role(*roles)\n roles = roles.flatten.map(&:to_s)\n instances.select { |inst| roles.include?(inst.role.to_s) }\n end", "def get_instances_by_role(group, role)\n get_instances(group).select do |instance|\n if not instance.tags['role'].nil? and instance.ready?\n instance.tags.fetch('role', '').split(',').include? role\n end\n end\n end", "def instances_for_role(role, state = \"running\")\n instances_for_filter(\"tag:role\", role, state)\n end", "def get_instances(role: nil, username: nil, bastion: nil)\n puts \"Getting instances for role: #{role}\"\n servers = []\n instances_for_role(role).each do |res|\n res[:instances].each do |inst|\n servers << \"#{username}@#{inst[:private_ip_address]}\"\n end\n end\n\n puts \" - #{servers.join(', ')}\"\n servers\n end", "def get_role_instances(cloud_id, role_id)\n http_get_request(Scalarium.clouds_url+\"/#{cloud_id}/roles/#{role_id}/instances\")\n end", "def list_instances()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end", "def list_instances_detail()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances/detail\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end", "def instances(arg)\n case arg\n when Range\n minimum_instances arg.first\n maximum_instances arg.last\n when Fixnum\n minimum_instances arg\n maximum_instances arg\n when Hash\n nodes(arg)\n else\n raise SpecException.new(\"Don't know how to handle instances cloud input #{arg}\")\n end\n end", "def list_of_instances(keyp=nil)\n tmp_key = (keyp ? keyp : nil)\n \n unless @describe_instances\n tmpInstanceList = remote_base.describe_instances(options).select {|a| a if (tmp_key.nil? || tmp_key.empty? ? true : a[:keypair] == tmp_key) }\n has_master = !tmpInstanceList.select {|a| a[:name] == \"master\" }.empty? \n if has_master\n @describe_instances = tmpInstanceList\n else\n @id = 0\n running = select_from_instances_on_status(/running/, tmpInstanceList)\n pending = select_from_instances_on_status(/pending/, tmpInstanceList)\n terminated = select_from_instances_on_status(/shutting/, tmpInstanceList)\n \n running = running.map do |inst|\n inst[:name] = (@id == 0 ? \"master\" : \"node#{@id}\")\n @id += 1\n inst\n end.sort_by {|a| a[:index] }\n \n @describe_instances = [running, pending, terminated].flatten\n end\n end\n @describe_instances\n end", "def run_instances(num_vms, opts, roles, disks)\n # Make a copy (the options are a simple hash so shallow copy does the\n # trick) to not modify the original.\n options = opts.clone\n options['num_vms'] = num_vms.to_s\n\n uri = URI(\"http://#{@ip}:#{SERVER_PORT}/instances\")\n headers = {'Content-Type' => 'application/json',\n 'AppScale-Secret' => @secret}\n request = Net::HTTP::Post.new(uri.path, headers)\n\n request.body = JSON.dump(options)\n\n run_result = JSON.parse(make_call(request, uri))\n Djinn.log_debug(\"[IM] Run instances info says [#{run_result}]\")\n operation_id = run_result['operation_id']\n\n vm_info = {}\n loop {\n begin\n describe_result = describe_operation(operation_id)\n rescue Djinn::FailedNodeException => error\n Djinn.log_warn(\n \"[IM] Error describing run instances operation #{operation_id}. \" \\\n \"Error: #{error.message}\")\n next\n end\n Djinn.log_debug(\"[IM] Describe run operation has vm_info \" \\\n \"#{describe_result['vm_info'].inspect}.\")\n\n if describe_result['state'] == 'success'\n vm_info = describe_result['vm_info']\n break\n elsif describe_result['state'] == 'failed'\n raise AppScaleException.new(describe_result['reason'])\n end\n Kernel.sleep(SMALL_WAIT)\n }\n\n # ip:role:instance-id\n instances_created = []\n vm_info['public_ips'].each_index { |index|\n tmp_roles = roles[index]\n tmp_roles = 'open' if roles[index].nil?\n instances_created << {\n 'public_ip' => vm_info['public_ips'][index],\n 'private_ip' => vm_info['private_ips'][index],\n 'roles' => tmp_roles,\n 'instance_id' => vm_info['instance_ids'][index],\n 'disk' => disks[index],\n 'instance_type' => options['instance_type']\n }\n }\n\n instances_created\n end", "def list_instances token: nil\n execute do\n instances.list_instances(\n project_path,\n page_token: token\n )\n end\n end", "def instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving active instances\"\n fetch_instances\n end", "def active_instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving running instances\"\n fetch_instances ['ACTIVE']\n end", "def list_instances token: nil\n instances.list_instances parent: project_path, page_token: token\n end", "def fetch_instances(allow_states = nil, reject_states = nil)\n Egi::Fedcloud::Vmhound::Log.debug \"[#{self.class}] Retrieving instances: \" \\\n \"allow_states=#{allow_states.inspect} & \" \\\n \"reject_states=#{reject_states.inspect}\"\n return if allow_states && allow_states.empty?\n reject_states ||= []\n\n @vm_pool_ary ||= fetch_instances_batch_pool(@vm_pool)\n @vm_pool_ary.collect { |vm| fetch_instances_vm(vm, allow_states, reject_states) }.compact\n end", "def fetch_instance(shortname = :all, options = {})\n return instances if instances && !options[:force]\n\n fetch_stack\n unless instance_list\n self.instance_list = self.instances =\n aws_client.describe_instances(stack_id: stack[:stack_id])[:instances]\n end\n\n if shortname != :all\n fetch_layer(shortname, force: true)\n self.instances = []\n\n layers.each do |layer|\n instance = aws_client.describe_instances(\n layer_id: layer[:layer_id])\n self.instances << instance[:instances]\n end\n\n self.instances.flatten!\n end\n end", "def load_instances_and_volumes\n cluster_instances = cluster_config[:instances] or return\n cluster_instances.each do |role, instances_for_role|\n role = role.to_s\n instances_for_role.each_with_index do |instance_cfg, instance_idx|\n load_instance role, instance_idx, instance_cfg\n end\n end\n end", "def instances\n instances = []\n JSON.parse(resource['/instances'].get)[\"instances\"].each do |i|\n instances << Instance.new(i)\n end\n return instances\n end", "def instances_list\n return [] unless configured?\n\n @service.fetch_all do |token|\n @service.list_instances(@gcp_config['project'], @gcp_config['zone'], page_token: token)\n end.map(&:name)\n end", "def instance_list(next_token=nil)\n self.ec2_client.describe_instances(\n {\n filters: [\n {\n name: \"tag:Branch\",\n values: [\"*\"],\n },\n {\n name: \"instance-state-name\",\n values: [\"running\"],\n }\n ],\n next_token: next_token\n })\n end", "def select_from_instances_on_status(status=/running/, list=[])\n list.select {|a| a[:status] =~ status}\n end", "def get_instances(incl_stopped=false)\n \n instances = @ec2.describe_instances\n instances = instances.select { |x| x[:aws_groups].include? @group_name }\n \n if(instances.length == 0)\n raise CaTPAWS::EC2::Error::InstanceRetrieval, \"No instances found in this group\"\n end \n \n unless (incl_stopped)\n instances = instances.select {|x| x[:aws_state_code].to_i <= 16}\n end\n @instances = instances\n end", "def init_instances\n instances = []\n next_token = nil\n all_records_retrieved = false\n\n until all_records_retrieved\n response = @@client.describe_instances({\n next_token: next_token\n })\n next_token = response.next_token\n all_records_retrieved = next_token.nil? || next_token.empty?\n instances << response.reservations.map { |r| r.instances }\n end\n\n instances.flatten\n end", "def list_instances request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_list_instances_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Cloud::BareMetalSolution::V2::ListInstancesResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end", "def query_roles(options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.query_roles(@cluster, policy)\n end", "def instances\n IbmCloudRest.get \"#{@uri}/instances\"\n end", "def list_instances()\n response = dbreq(\"GET\",lbmgmthost,\"#{lbmgmtpath}/instances\",lbmgmtport,lbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end", "def find_multiple_nodes_by_role(role, stack, alternate=nil)\n if !node[:override_stacks].nil? && !node[:override_stacks][role].nil?\n stack = node[:override_stacks][role]\n puts \"stack override for #{role} found, using stack #{stack}\"\n end\n @nodes ||= find_stack(stack)\n matching_nodes = []\n @nodes.each { |stack_node|\n if stack_node[:roles] && stack_node[:roles].select{ |r| r[/#{role}/] }.size > 0\n matching_nodes << stack_node\n end\n }\n if matching_nodes.size == 0 && alternate\n Chef::Log.debug \"Unable to locate a #{role} machine in the '#{stack}' environment. Searching for alternate #{alternate} machine...\"\n @nodes.each { |stack_node|\n if stack_node[:roles] && stack_node[:roles].select{ |r| r[/#{alternate}/] }.size > 0\n matching_nodes << stack_node\n end\n }\n end\n # Fail if no node has been found in the stack\n raise \"The #{role} machine is either missing or corrupt in the #{stack} environment. This is okay, if the #{role} machine is not required.\" if matching_nodes.size == 0\n return matching_nodes\nend", "def describe_instances( options = {} )\n options = { :instance_id => [] }.merge(options)\n params = pathlist(\"InstanceId\", options[:instance_id])\n return response_generator(:action => \"DescribeInstances\", :params => params)\n end", "def kitchen_instances(regexp, config)\n instances = Kitchen::Config.new(config).instances\n instances = instances.get_all(Regexp.new(regexp)) unless regexp.nil? || regexp == 'all'\n raise Kitchen::UserError, \"regexp '#{regexp}' matched 0 instances\" if instances.empty?\n instances\n end" ]
[ "0.6815968", "0.6587964", "0.62072724", "0.60657895", "0.5951953", "0.5241145", "0.5208313", "0.51693743", "0.5148964", "0.514775", "0.5121972", "0.50967026", "0.50681746", "0.5068069", "0.5065728", "0.5056514", "0.5054837", "0.50277025", "0.5013069", "0.49788684", "0.49780062", "0.49554217", "0.49491054", "0.49381173", "0.4931816", "0.48795393", "0.48457736", "0.48455352", "0.4834382", "0.48181713" ]
0.69315934
0
Simple version of select_instances that only selects roles, not names instances_by_role(:app_master, :app) same instances_by_role(%w[app_master app]) same select_instances(app_master: true, app: true) same
def instances_by_role(*roles) roles = roles.flatten.map(&:to_s) instances.select { |inst| roles.include?(inst.role.to_s) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_instances(options)\n instances_by_role(options.keys).select do |inst|\n # get the value of the string/symbol key that matches without losing nil/false values\n val = options.fetch(inst.role.to_sym) { options.fetch(inst.role.to_s, false) }\n\n case val\n when true, false then val\n when inst.name then true\n when nil, '' then [nil, ''].include?(inst.name)\n when Array then val.include?(inst.name)\n else false\n end\n end\n end", "def get_instances_by_role(group, role)\n get_instances(group).select do |instance|\n if not instance.tags['role'].nil? and instance.ready?\n instance.tags.fetch('role', '').split(',').include? role\n end\n end\n end", "def instances_for_role(role, state = \"running\")\n instances_for_filter(\"tag:role\", role, state)\n end", "def get_instances(role: nil, username: nil, bastion: nil)\n puts \"Getting instances for role: #{role}\"\n servers = []\n instances_for_role(role).each do |res|\n res[:instances].each do |inst|\n servers << \"#{username}@#{inst[:private_ip_address]}\"\n end\n end\n\n puts \" - #{servers.join(', ')}\"\n servers\n end", "def filter_instances\n suites.product(platforms).select do |suite, platform|\n if !suite.includes.empty?\n suite.includes.include?(platform.name)\n elsif !suite.excludes.empty?\n !suite.excludes.include?(platform.name)\n else\n true\n end\n end\n end", "def get_role_instances(cloud_id, role_id)\n http_get_request(Scalarium.clouds_url+\"/#{cloud_id}/roles/#{role_id}/instances\")\n end", "def role_select\n @@Roles.list\n end", "def selectors\n find_related_frbr_objects( :is_selected_by, :which_roles?) \n end", "def query_roles(options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.query_roles(@cluster, policy)\n end", "def serversForCapRoles(roles)\n find_servers(:roles => roles).collect { |x| x.host }\nend", "def select_from_instances_on_status(status=/running/, list=[])\n list.select {|a| a[:status] =~ status}\n end", "def find_multiple_nodes_by_role(role, stack, alternate=nil)\n if !node[:override_stacks].nil? && !node[:override_stacks][role].nil?\n stack = node[:override_stacks][role]\n puts \"stack override for #{role} found, using stack #{stack}\"\n end\n @nodes ||= find_stack(stack)\n matching_nodes = []\n @nodes.each { |stack_node|\n if stack_node[:roles] && stack_node[:roles].select{ |r| r[/#{role}/] }.size > 0\n matching_nodes << stack_node\n end\n }\n if matching_nodes.size == 0 && alternate\n Chef::Log.debug \"Unable to locate a #{role} machine in the '#{stack}' environment. Searching for alternate #{alternate} machine...\"\n @nodes.each { |stack_node|\n if stack_node[:roles] && stack_node[:roles].select{ |r| r[/#{alternate}/] }.size > 0\n matching_nodes << stack_node\n end\n }\n end\n # Fail if no node has been found in the stack\n raise \"The #{role} machine is either missing or corrupt in the #{stack} environment. This is okay, if the #{role} machine is not required.\" if matching_nodes.size == 0\n return matching_nodes\nend", "def get_nodes_by_role(role, includeme=true, options={})\n options = {\n :search_string => role,\n :include_me => includeme,\n :order => [:role],\n :safe_deref => nil,\n :current_node => nil,\n :one_or_all => :all\n }.merge(options)\n opsit_search(options)\n end", "def find_roles *roles\n role_model.where(:name => roles.flatten)\n end", "def find_selected_elements(options, show_non_public = false)\n public_condition = show_non_public ? nil : ' AND elements.public = 1'\n if !options[:except].blank?\n condition = [\"elements.name NOT IN (?)#{public_condition}\", options[:except]]\n elsif !options[:only].blank?\n condition = [\"elements.name IN (?)#{public_condition}\", options[:only]]\n else\n condition = show_non_public.nil? ? nil : {:public => true}\n end\n return self.elements.find(:all, :conditions => condition, :limit => options[:count], :order => options[:random].blank? ? nil : \"RAND()\")\n end", "def where_user_and_role(user, alt_app_type = nil, alt_role_name = nil)\n where_clause = ''\n where_conditions = []\n if user\n where_clause += 'user_id = ?'\n where_conditions << user.id\n end\n\n app_type = alt_app_type || user&.app_type\n app_type_id = if app_type.is_a? Admin::AppType\n app_type.id\n else\n app_type\n end\n\n if alt_role_name\n rn = alt_role_name\n rn = [rn] unless rn.is_a? Array\n app_type_role_names = rn.map { |v| [app_type_id, v] }\n elsif user\n app_type_role_names = Admin::UserRole.active_app_roles(user, app_type: [app_type_id, nil])\n .select('app_type_id, role_name').distinct.order(app_type_id: :asc)\n .pluck(:app_type_id, :role_name)\n end\n\n if app_type_role_names&.present?\n app_type_role_names.each do |pair|\n where_clause += ' OR ' if where_clause.present?\n app_type_clause = if pair.first\n 'app_type_id = ?'\n else\n pair = [pair.last]\n 'app_type_id IS NULL'\n end\n where_clause += \"(#{app_type_clause} AND role_name = ?)\"\n where_conditions += pair\n end\n end\n\n where_clause += ' OR ' if where_clause.present?\n where_clause += \"(user_id IS NULL AND (role_name IS NULL OR role_name = ''))\"\n conditions = [where_clause] + where_conditions\n\n active.where(app_type_id: [app_type_id, nil]).where(conditions)\n\n end", "def roles(*select_roles, &block)\n if block_given?\n return yield(roles(*select_roles))\n end\n\n roles_set = Set.new select_roles.flatten.compact.map{|r| r.to_sym}\n if roles_set.empty? || roles_set.include?(:all)\n self\n else\n @cache[roles_set] ||= select { |server| server.matches_roles?(roles_set) }\n end\n end", "def roles(*select_roles, &block)\n if block_given?\n return yield(roles(*select_roles))\n end\n\n roles_set = Set.new select_roles.flatten.compact.map{|r| r.to_sym}\n if roles_set.empty? || roles_set.include?(:all)\n self\n else\n @cache[roles_set] ||= select { |server| server.matches_roles?(roles_set) }\n end\n end", "def roles\n @run_list.select do |rl|\n rl.start_with?('r_', 'p_', 'base_', 'os_', 'os-')\n end\n end", "def roles\n ::Syncano::QueryBuilder.new(self, ::Syncano::Resources::Role)\n end", "def index\n @app_instances = parent_organization.app_instances.active.where(\"updated_at.gt\" => Time.at(timestamp)).select do |i|\n # force owner assignment to avoid a refetch in ability can?(:access,i)\n i.owner = parent_organization\n can?(:access,i)\n end\n end", "def get_instances(incl_stopped=false)\n \n instances = @ec2.describe_instances\n instances = instances.select { |x| x[:aws_groups].include? @group_name }\n \n if(instances.length == 0)\n raise CaTPAWS::EC2::Error::InstanceRetrieval, \"No instances found in this group\"\n end \n \n unless (incl_stopped)\n instances = instances.select {|x| x[:aws_state_code].to_i <= 16}\n end\n @instances = instances\n end", "def for_role(*roles)\n sql = with_role_sql(roles) || ''\n sql += ' OR ' if sql.present?\n sql += \"(#{self.table_name}.roles_mask = 0) OR (#{self.table_name}.roles_mask IS NULL)\"\n where(sql)\n end", "def run_for_app_all_roles(*apps, &block)\n the_app = node[:zz][:app_name]\n the_role = node[:zz][:deploy_role]\n rails_env = node[:zz][:group_config][:rails_env]\n apps.each do |app|\n app_name = app.to_s\n if app_name == the_app\n block.call(the_app.to_sym, the_role.to_sym, rails_env.to_sym)\n end\n end\n end", "def get_settings_by_role(role, settings, includeme=true, options={})\n osops_search(\n search_string=role,\n one_or_all=:one,\n include_me=includeme,\n order=[:role],\n safe_deref=settings,\n current_node=nil,\n options\n )\n end", "def collaborators\n collab_roles = accepted_roles.for_name(\"collaborator\")\n User.find_by_sql(\"SELECT * FROM users INNER JOIN roles_users ON roles_users.user_id = users.id WHERE roles_users.role_id IN (12)\")\n end", "def list_of_instances(keyp=nil)\n tmp_key = (keyp ? keyp : nil)\n \n unless @describe_instances\n tmpInstanceList = remote_base.describe_instances(options).select {|a| a if (tmp_key.nil? || tmp_key.empty? ? true : a[:keypair] == tmp_key) }\n has_master = !tmpInstanceList.select {|a| a[:name] == \"master\" }.empty? \n if has_master\n @describe_instances = tmpInstanceList\n else\n @id = 0\n running = select_from_instances_on_status(/running/, tmpInstanceList)\n pending = select_from_instances_on_status(/pending/, tmpInstanceList)\n terminated = select_from_instances_on_status(/shutting/, tmpInstanceList)\n \n running = running.map do |inst|\n inst[:name] = (@id == 0 ? \"master\" : \"node#{@id}\")\n @id += 1\n inst\n end.sort_by {|a| a[:index] }\n \n @describe_instances = [running, pending, terminated].flatten\n end\n end\n @describe_instances\n end", "def filter_options(attr_class_option_ids)\n sql = %{\n SELECT DISTINCT CASE WHEN attributable_type=:product THEN\n attributable_id ELSE product_id END AS p_id\n FROM product_attributes pa\n JOIN attribute_options ao ON ao.id=pa.value_id\n LEFT JOIN product_search_products psp\n ON psp.search_product_id=attributable_id\n AND pa.attributable_type=:search_product\n WHERE attributable_type IN (:product, :search_product)\n AND value_type=:attribute_options\n AND ao.attribute_class_option_id IN (:attr_class_option_ids)\n }\n query = sanitize_sql_array [sql,\n {\n product: SitescanCommon::Product,\n search_product: SitescanCommon::SearchProduct,\n attribute_options: SitescanCommon::AttributeOption,\n attr_class_option_ids: attr_class_option_ids\n }]\n connection.select_values query\n end", "def select_cmux_support_role_types(roles)\n roles.select { |_, r| ROLE_PORT.keys.map.include?(r[:roleType]) }\n end", "def select\n @users ||= User.role_wise_users(params[:user][:role])\n authorize! :read, @user\n end" ]
[ "0.7207731", "0.6452275", "0.60056883", "0.5485831", "0.54808927", "0.54168063", "0.51426065", "0.50724375", "0.5028341", "0.50074726", "0.5005638", "0.5005568", "0.49344948", "0.4933732", "0.49306875", "0.49236944", "0.48968926", "0.48968926", "0.48505467", "0.48051736", "0.4785673", "0.47760373", "0.47462383", "0.47031164", "0.468809", "0.46542534", "0.4650864", "0.46432695", "0.46344516", "0.4626118" ]
0.66395384
1
Throws a POST request at the API to /add_instances and adds one instance to this environment. Usage example: api = EY::CloudClient.new(token: 'your token here') env = api.environment_by_name('your_env_name') env.add_instance(role: "app") env.add_instance(role: "util", name: "foo") Note that the role for an instance MUST be either "app" or "util". No other value is acceptable. The "name" parameter can be anything, but it only applies to utility instances. Note also that if you add a util instance, you must specify a name. This method will raise if you don't.
def add_instance(opts) unless %w[app util].include?(opts[:role].to_s) # Fail immediately because we don't have valid arguments. raise InvalidInstanceRole, "Instance role must be one of: app, util" end # Sanitize the name to remove whitespace if there is any if opts[:name] name = opts[:name].gsub(/\s+/, '') end if opts[:role] == 'util' unless name && name.length > 0 raise InvalidInstanceName, "When specifying a util instance you must also specify a name." end end request = { "role" => opts[:role], "name" => opts[:name] } request['snapshot_id'] = opts[:snapshot_id] if opts.key?(:snapshot_id) request['instance_size'] = opts[:instance_size] if opts.key?(:instance_size) # We know opts[:role] is right, name can be passed straight to the API. # Return the response body for error output, logging, etc. return api.post("/environments/#{id}/add_instances", :request => request) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_instance(instance)\n register_response = client.register_instances_with_load_balancer(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = register_response.instances.size\n puts \"Added #{instance.hostname} to ELB #{name}. Attached instances: #{remaining_instance_count}\".light_blue\n _wait_for_instance_health_check(instance)\n end", "def add_instance(params)\n Fog::Logger.deprecation(\n \"#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller(0..0)})[/]\"\n )\n params[:instance] = [params[:instance]] unless params[:instance] == Array\n service.add_instance_group_instances(params[:group], params[:zone], params[:instance])\n end", "def create_instance_for_env(instance)\n whitelist = [:instance_id, :instance_index, :name, :uris, :users, :version, :start, :runtime, :state_timestamp, :port]\n env_hash = {}\n whitelist.each {|k| env_hash[k] = instance[k] if instance[k]}\n env_hash[:limits] = {\n :fds => instance[:fds_quota],\n :mem => instance[:mem_quota],\n :disk => instance[:disk_quota],\n }\n env_hash[:host] = @local_ip\n env_hash.to_json\n end", "def add_environment(env)\n @environments << env\n end", "def put_instance(opts)\n opts = check_params(opts,[:instances])\n super(opts)\n end", "def create\n @environment = Environment.new(params[:environment])\n @environment.organization = current_user.organization\n @environment.user = current_user\n\n respond_to do |format|\n if @environment.save\n format.html { redirect_to @environment, notice: 'Instance record was successfully created.' }\n format.json { render json: @environment, status: :created, location: @environment }\n else\n format.html { render action: \"new\" }\n format.json { render json: @environment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_instance(options = {})\n body = Hash.new\n (body[:flavor_ref] = options[:flavor_ref]) or raise CloudDB::Exception::MissingArgument, \"Must provide a flavor to create an instance\"\n (body[:size] = options[:size]) or raise CloudDB::Exception::MissingArgument, \"Must provide a size to create an instance\"\n body[:name].upcase! if body[:name]\n response = dbreq(\"POST\",lbmgmthost,\"#{lbmgmtpath}/instances\",lbmgmtport,lbmgmtscheme,{},body.to_json)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n body = JSON.parse(response.body)['instance']\n return get_instance(body[\"id\"])\n end", "def create(name)\n object = new(name)\n @instances.push(object)\n object\n end", "def create\n @instance_name = InstanceName.new(params[:instance_name])\n\n respond_to do |format|\n if @instance_name.save\n flash[:notice] = 'InstanceName was successfully created.'\n format.html { redirect_to(@instance_name) }\n format.xml { render :xml => @instance_name, :status => :created, :location => @instance_name }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @instance_name.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_instance(security_groups, key, user_data, size, region)\n @instances = nil\n Instance.new(@@ec2.run_instances(id, 1, 1, security_groups, key, user_data, nil, size, nil, nil, region).first)\n end", "def create_instance project_id:, instance_id:\n # [START spanner_create_instance]\n # project_id = \"Your Google Cloud project ID\"\n # instance_id = \"Your Spanner instance ID\"\n\n require \"google/cloud/spanner\"\n require \"google/cloud/spanner/admin/instance\"\n\n instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin\n\n project_path = instance_admin_client.project_path project: project_id\n instance_path = instance_admin_client.instance_path project: project_id, instance: instance_id\n instance_config_path = instance_admin_client.instance_config_path project: project_id, instance_config: \"regional-us-central1\"\n\n job = instance_admin_client.create_instance parent: project_path,\n instance_id: instance_id,\n instance: { name: instance_path,\n config: instance_config_path,\n display_name: instance_id,\n node_count: 2,\n labels: { cloud_spanner_samples: \"true\" } }\n\n puts \"Waiting for create instance operation to complete\"\n\n job.wait_until_done!\n\n if job.error?\n puts job.error\n else\n puts \"Created instance #{instance_id}\"\n end\n # [END spanner_create_instance]\nend", "def add(environment)\n\t\t\tname = environment.name\n\t\t\t\n\t\t\tunless name\n\t\t\t\traise ArgumentError, \"Environment name is nil #{environment.inspect}\"\n\t\t\tend\n\t\t\t\n\t\t\tenvironment = environment.flatten\n\t\t\t\n\t\t\traise KeyError.new(\"#{name.inspect} is already set\", key: name) if @environments.key?(name)\n\t\t\t\n\t\t\t@environments[name] = environment\n\t\tend", "def create_instance\n create_instances(1).first\n end", "def create_instance(name, tasks, priority = 1, comment = nil)\n instance = Instance.new\n instance.name = name\n instance.priority = priority\n instance.comment = comment if comment\n if tasks.instance_of? Array\n instance.tasks = tasks\n else\n instance.tasks = [tasks]\n end\n\n res = ODPS.conn.post do |req|\n req.url \"projects/#{ODPS.current_project}/instances\"\n req.headers['Content-Type'] = 'application/xml'\n req.body = instance.serialize [String, ['Job'], 'Name', name],\n [String, ['Job'], 'Comment', comment],\n [String, ['Job'], 'Priority', priority],\n [Array, ['Job'], 'Tasks', instance.tasks.map { |t| REXML::Document.new t.to_xml }]\n end\n\n if res.status == 201\n instance.location = res['Location']\n instance\n end\n end", "def add(params)\n post 'add', params\n end", "def create_environment(options={})\n if option_settings = options.delete('OptionSettings')\n options.merge!(AWS.indexed_param('OptionSettings.member.%d', [*option_settings]))\n end\n if options_to_remove = options.delete('OptionsToRemove')\n options.merge!(AWS.indexed_param('OptionsToRemove.member.%d', [*options_to_remove]))\n end\n request({\n 'Operation' => 'CreateEnvironment',\n :parser => Fog::Parsers::AWS::ElasticBeanstalk::CreateEnvironment.new\n }.merge(options))\n end", "def add(params = {})\n perform_request 'Add', params\n end", "def create\n @instance = @provider.instances.new(params[:instance])\n @instance.state = \"Building\"\n respond_to do |format|\n if @instance.save\n @instance.create_instance(@provider.connect!)\n format.html { redirect_to cloud_provider_instance_path(@provider,@instance), notice: 'Instance was successfully created.' }\n format.json { render json: @instance, status: :created, location: @instance }\n else\n format.html { render action: \"new\" }\n format.json { render json: @instance.errors, status: :unprocessable_entity }\n end\n end\n end", "def add(*args)\n params = { name: nil, group: nil, length: 128, value: nil, force: false }\n case args.length\n when 1\n # add('foo')\n params[:name] = args.first\n when 2\n if args.all? { |a| a.is_a?(String) }\n # add('my_app', 'foo')\n params[:group], params[:name] = args\n elsif args[1].is_a?(Hash)\n # add('my_app', value: 'something')\n # add('foo', length: 50)\n params[:name] = args.first\n params.merge!(args[1])\n end\n when 3\n # add('my_app', 'foo', value: 'something')\n # add('my_app', 'foo', length: 50)\n params[:group], params[:name] = args[0], args[1]\n params.merge!(args[2])\n else\n raise ArgumentError, \"wrong number of arguments (given #{args.length}, expected 1-3)\"\n end\n\n add_from_params(params)\n end", "def aws_instance_create(opts)\n AWS::EC2::InstanceCollection.new.create(\n image_id: Rails.configuration.x.aws[Rails.configuration.x.aws['region']][\"ami_#{self.os}\"], \n private_ip_address: self.ip_address,\n key_name: Rails.configuration.x.aws['ec2_key_pair_name'],\n user_data: self.generate_init,\n instance_type: \"t2.small\",\n subnet: self.subnet.driver_id\n )\n end", "def add\n request('add').auth_required!\n end", "def create\n @instance_type = InstanceType.new(params[:instance_type])\n\n respond_to do |format|\n if @instance_type.save\n format.html { redirect_to @instance_type, notice: 'Instance type was successfully created.' }\n format.json { render json: @instance_type, status: :created, location: @instance_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @instance_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_environment environment\n @environments.merge! environment\n self\n end", "def create_db_instance(db_name, options={})\n \n if security_groups = options.delete('DBSecurityGroups')\n options.merge!(Fog::AWS.indexed_param('DBSecurityGroups.member.%d', [*security_groups]))\n end\n \n request({\n 'Action' => 'CreateDBInstance',\n 'DBInstanceIdentifier' => db_name,\n :parser => Fog::Parsers::AWS::RDS::CreateDBInstance.new,\n }.merge(options))\n end", "def create\n @instance = Instance.new(instance_params)\n\n respond_to do |format|\n if @instance.save\n format.html { redirect_to @instance, notice: 'Instance was successfully created.' }\n format.json { render :show, status: :created, location: @instance }\n else\n format.html { render :new }\n format.json { render json: @instance.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_ec2_instance(attrs)\n instance = ec2.instances.create(attrs)\n perform_instance_checks(instance)\n instance\n end", "def add(request_env)\n\t\t\treturn false unless valid?(request_env)\n\t\t\treturn false if spammer?(request_env['REMOTE_ADDR'])\n\t\t\treturn false if spam?(request_env)\n\t\t\tnu = clean(request_env)\n\t\t\tnu[:person_id] = person_id(nu)\n\t\t\tc = create(nu)\n\t\t\tc.id\n\t\tend", "def add_instance(instance)\n self.save unless self.persisted?\n instance.ie = self\n self.instances << instance\n instance.save && self.save\n end", "def create_resource(env)\n env[:ui].info(\"Creating machine\")\n\n config = env[:machine].provider_config\n vra = env[:vra]\n\n EntitledItemsCollection.fetch(env[:vra])\n .find_by_id(config.catalog_item_id)\n .request(cpus: config.cpus,\n memory: config.memory,\n requested_for: config.requested_for,\n subtenant_id: config.subtenant_id,\n lease_days: config.lease_days) { |req|\n config.extra_entries.types.each do |type|\n config.extra_entries.of_type(type).each do |k,v|\n req.set_parameter(k, type, v)\n end\n end\n }\n .join\n .machine\n end", "def create_pvm_instance(instance_hash)\n post(\"cloud-instances/#{guid}/pvm-instances\", instance_hash.to_json)\n end" ]
[ "0.5855038", "0.56592315", "0.5599796", "0.5410954", "0.54064155", "0.5356072", "0.5354687", "0.5354005", "0.5349306", "0.5331099", "0.5286285", "0.5285621", "0.5262432", "0.525653", "0.5237013", "0.5153389", "0.51446885", "0.5136719", "0.50980014", "0.50849426", "0.5069928", "0.5062697", "0.5023845", "0.50216913", "0.5018327", "0.50114477", "0.50065744", "0.496981", "0.49566677", "0.49395508" ]
0.74952036
0
Sends a request to the API to remove the instance specified by its "provisioned_id" (Amazon ID). Usage example: api = EY::CloudClient.new(token: 'token') env = api.environment_by_name('my_app_production') bad_instance = env.instance_by_id(12345) instance ID should be saved upon creation env.remove_instance(bad_instance) Warnings/caveats: + The API is responsible for actually removing this instance. All this does is send an appropriate request to the API. + You should look carefully at the API response JSON to see whether or not the API accepted or rejected your request. If it accepted the request, that instance should be removed as soon as possible. + Note that this is a client that talks to an API, which talks to an API, which talks to an API. Ultimately the IaaS provider API has the final say on whether or not to remove an instance, so a failure there can definitely affect how things work at every point down the line. + If the instance you pass in doesn't exist in the live cloud environment you're working on, the status should be rejected and thus the instance won't be removed (because that instance isn't there). This is important to keep in mind for scheduled/auto scaling; if for some reason the automatically added instance is removed before a "scale down" event that you might trigger, you may wind up with an unknown/unexpected number of instances in your environment. + Only works for app/util instances. Raises an error if you pass one that isn't valid.
def remove_instance(instance) unless instance raise ArgumentError, "A argument of type Instance was expected. Got #{instance.inspect}" end # Check to make sure that we have a valid instance role here first. unless %w[app util].include?(instance.role) raise InvalidInstanceRole, "Removing instances is only supported for app, util instances" end # Check to be sure that instance is actually provisioned # TODO: Rip out the amazon_id stuff when we have IaaS agnosticism nailed down unless instance.amazon_id && instance.provisioned? raise InstanceNotProvisioned, "Instance is not provisioned or is in unusual state." end response = api.post("/environments/#{id}/remove_instances", :request => { :provisioned_id => instance.amazon_id, :role => instance.role, :name => instance.name }) # Reset instances so they are fresh if they are requested again. @instances = nil # Return the response. return response end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_instance(instance)\n deregister_response = client.deregister_instances_from_load_balancer(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = deregister_response.instances.size\n puts \"Removed #{instance.hostname} from ELB #{name}. Remaining instances: #{remaining_instance_count}\".light_blue\n _wait_for_connection_draining\n end", "def delete_instance instance_id\n instances.delete_instance name: instance_path(instance_id)\n end", "def delete_instance instance_id\n execute do\n instances.delete_instance(\n instance_path(instance_id)\n )\n end\n end", "def delete_pvm_instance(instance_id)\n delete(\"cloud-instances/#{guid}/pvm-instances/#{instance_id}\")\n end", "def destroy\n @instance = @provider.instances.find(params[:id])\n InstanceOperations.terminate_instances(@provider.connect!, @instance)\n @instance.destroy\n redirect_to cloud_provider_path(@provider) \n end", "def destroy_instance(credentials, id)\n safely do\n terremark_client = new_client(credentials)\n return terremark_client.delete_vapp(id)\n end\nend", "def destroy \n ec2 = self.class.new_ec2(@resource.value(:user), @resource.value(:password))\n ec2.terminate_instances({:instance_id => @property_hash[:instance_id]})\n ec2.delete_security_group({:group_name => @resource.value(:name)})\n end", "def terminate_instance!(instance_id=nil)\n ec2.terminate_instances(:instance_id => instance_id)\n end", "def destroy\n @ec2_instance.destroy\n respond_to do |format|\n format.html { redirect_to ec2_instances_url, notice: 'Ec2 instance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def remove_instance(params)\n Fog::Logger.deprecation(\n \"#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller(0..0)})[/]\"\n )\n params[:instance] = [params[:instance]] unless params[:instance] == Array\n service.remove_instance_group_instances(params[:group], params[:zone], params[:instance])\n end", "def delete_instance(instance_name)\n return if !configured? || !instance_exists?(instance_name)\n\n @service.delete_instance(@gcp_config['project'], @gcp_config['zone'], instance_name)\n rescue StandardError => e\n @logger.error(e.message)\n end", "def destroy\n @instance_name = InstanceName.find(params[:id])\n @instance_name.destroy\n\n respond_to do |format|\n format.html { redirect_to(instance_names_url) }\n format.xml { head :ok }\n end\n end", "def terminate_instance(instance_id)\n return if instance_id.nil? || !configured?\n\n @client.terminate_instances(instance_ids: [instance_id])\n nil\n end", "def destroy!\n response = @connection.dbreq(\"DELETE\", @lbmgmthost, \"#{@lbmgmtpath}/instances/#{CloudDB.escape(@id.to_s)}\",@lbmgmtport,@lbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^202$/)\n true\n end", "def stop_pvm_instance(instance_id)\n post(\n \"cloud-instances/#{guid}/pvm-instances/#{instance_id}/action\",\n {\"action\" => \"stop\"}.to_json\n )\n end", "def destroy\n @instance = Instance.find(params[:id])\n @instance.destroy\n\n respond_to do |format|\n format.html { redirect_to(instances_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n response = get_request(URI.parse(\"http://\"+(sesh :donabe_ip)+\"/\"+(sesh :current_tenant)+\"/deployed_containers/\"+params[:id].to_s+\"/destroy_deployed.json\"), (sesh :current_token))\n json_respond response.body\n\n end", "def destroy\n @instance = Instance.find(params[:id])\n @instance.destroy\n\n respond_to do |format|\n format.html { redirect_to instances_url }\n format.json { head :no_content }\n end\n end", "def terminate_instance!(instance_id)\n instances.select {|a| a[:instance_id] == instance_id}[0][:status] = \"terminating\"\n end", "def destroy_existing(id, params={})\n request(params.merge(:_method => :delete, :_path => build_request_path(params.merge(primary_key => id)))) do |parsed_data, response|\n new(parse(parsed_data[:data]).merge(:_destroyed => true))\n end\n end", "def destroy_existing(id, params={})\n request(params.merge(:_method => method_for(:destroy), :_path => build_request_path(params.merge(primary_key => id)))) do |parsed_data, response|\n new(parse(parsed_data[:data]).merge(:_destroyed => true))\n end\n end", "def destroy\n requires :id\n service.delete_vpc(id)\n true\n end", "def delete_vm(instance_id)\n with_thread_name(\"delete_vm(#{instance_id}):v2\") do\n logger.info(\"Deleting instance '#{instance_id}'\")\n @cloud_core.delete_vm(instance_id) do |instance_id|\n @registry.delete_settings(instance_id) if @stemcell_api_version < 2\n end\n end\n end", "def delete\n results = submit_cmd('delete app instance',:db, \" -env #{self.belongs_to.env} -app_instance #{self.name}\")\n\n\t if ( results.to_s =~ /failure/i || results.to_s =~ /error/i)\n\t \t raise \"update attribute failed\" \n\t else\n\t \t self.belongs_to.appTemplates.delete(self)\n\t end\n\n end", "def stop()\n self.destroy()\n\n # Stop the EC2 instance\n $ec2.terminate_instances([self.id])\n end", "def delete_instance request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_delete_instance_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Longrunning::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end", "def destroy(params = {})\n client.delete(\"#{endpoint(params)}/#{attributes[:id]}\")\n end", "def deregister_container_instance(params={})\n request({\n 'Action' => 'DeregisterContainerInstance',\n :parser => Fog::Parsers::AWS::ECS::DeregisterContainerInstance.new\n }.merge(params))\n end", "def destroy(id, params = {})\n path = build_request_path(params.merge(primary_key => id))\n request(params.merge(:_method => :delete, :_path => path)) do |response|\n new(parse(response.body).merge(:_destroyed => true))\n end\n end", "def destroy\n @server_instance = ServerInstance.find(params[:id])\n @server_instance.destroy\n\n respond_to do |format|\n format.html { redirect_to server_instances_url }\n format.json { head :no_content }\n end\n end" ]
[ "0.6574653", "0.65076655", "0.64812964", "0.6419181", "0.6399379", "0.6380492", "0.62758684", "0.62361205", "0.6062782", "0.6051841", "0.60133886", "0.5980715", "0.59735763", "0.59555346", "0.5934122", "0.59037524", "0.5877481", "0.5844952", "0.579769", "0.5739661", "0.5731196", "0.5727702", "0.5724159", "0.57163566", "0.5682408", "0.5664854", "0.56568366", "0.56455773", "0.5643483", "0.56312937" ]
0.76562095
0
Get last weather update
def last_weather weathers.last end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def last_updated\n self.dig_for_datetime(\"lastUpdateOn\")\n end", "def last_update_at\n connection.get_metric_last_update_at(@id)\n end", "def last_updated_time\n data[:last_updated_time]\n end", "def current_weather_data\n get_weather[:currently]\n end", "def last_updated\n\t\tupdated_at\n\tend", "def last_sensor_reading\n render json: Sensor.all.map { |s| s.weather_datum.last }\n end", "def last_update\n Time.parse(@record.SystemModstamp)\n end", "def get_current_weather( lat, lng )\n\n # geo = Geocoder.search( request.remote_ip ) # Just in case for fallback plan ;)\n\n # p geo[ 0 ].latitude # Just in case for fallback plan ;)\n # p geo[ 0 ].longitude # Just in case for fallback plan ;)\n\n url = \"https://api.darksky.net/forecast/#{ Rails.application.secrets.DARK_SKY_SECRET }/\" + lat + \",\" + lng;\n options = { exclude: \"[minutesly,hourly]\", units: \"auto\" }\n\n response = HTTParty.get( url, :query => options )\n\n currently = {\n \"summary\": response[ \"currently\" ][ \"summary\" ],\n \"last_updated\": Time.at( response[ \"currently\" ][ \"time\" ] ).strftime( \"%a, %b %d, %H:%M\" ),\n \"icon\": response[ \"currently\" ][ \"icon\" ],\n \"temperature\": response[ \"currently\" ][ \"temperature\" ]\n }\n\n tomorrow = response[ \"daily\" ][ \"data\" ][ 1 ]\n tomorrow_weather = {\n \"summary\": tomorrow[ \"summary\" ],\n \"icon\": tomorrow[ \"icon\" ],\n \"min_temperature\": tomorrow[ \"temperatureMin\" ],\n \"max_temperature\": tomorrow[ \"temperatureMax\" ]\n }\n\n weather_summary = { \"currently\": currently, \"tomorrow\": tomorrow_weather }\n\n # Return weather summary\n weather_summary\n end", "def last_update\n \"none\"\n end", "def remote_last_updated_at\n require 'rexml/document'\n doc = REXML::Document.new(request('update'))\n Time.iso8601(doc.root.attributes['time'])\n end", "def last_update_date_time\n return @last_update_date_time\n end", "def last_update_date_time\n return @last_update_date_time\n end", "def last_update_date_time\n return @last_update_date_time\n end", "def last_update_date_time\n return @last_update_date_time\n end", "def last_updated\n time = self.updated_at\n if time < Time.now - (3600 * 24)\n time.strftime(\"%b %-d, %Y\")\n else\n time.strftime(\"%l:%M %p\")\n end\n end", "def latest_update\n\t\tlatest_update = updated_at\n\t\tplans.each do |plan|\n\t\t\tif plan.latest_update > latest_update then\n\t\t\t\tlatest_update = plan.latest_update\n\t\t\tend\n\t\tend\n\t\treturn latest_update\n\tend", "def last_update\n Time._load(index_time_dbm_file['last']) rescue \"none\"\n end", "def get_metric_last_update_at(_metric)\n raise \"Not implemented\"\n end", "def latest_ust\n self.delta_pack[\"latestUST\"]\n end", "def latest_update\n latest_update = updated_at\n phases.each do |phase|\n if phase.updated_at > latest_update then\n latest_update = phase.updated_at\n end\n end\n return latest_update\n end", "def latest_stored_update\n active_model_configurations\n .select(:updated_at)\n .reorder('')\n .order('updated_at desc nulls last')\n .limit(1)\n .pluck(:updated_at)\n .first\n end", "def last_updated_at\n if cache\n @last_updated_at ||= remote_last_updated_at\n else\n remote_last_updated_at\n end\n end", "def current_weather\n return $game_temp.in_battle ? @battle_weather : @weather\n end", "def last_updated_at\n RefreshReportingViews.last_updated_at_facility_daily_follow_ups_and_registrations\n end", "def weather\n @weather\n end", "def last_updated_date_time\n return @last_updated_date_time\n end", "def last_updated_date_time\n return @last_updated_date_time\n end", "def last_updated_date_time\n return @last_updated_date_time\n end", "def last_updated_date_time\n return @last_updated_date_time\n end", "def get_weather\n @single_city_data['weather']\n end" ]
[ "0.73394704", "0.7171134", "0.7029702", "0.7011882", "0.69019264", "0.68487895", "0.6818536", "0.6809728", "0.6807462", "0.6783188", "0.67661095", "0.67661095", "0.67661095", "0.67661095", "0.6732376", "0.65903205", "0.6580078", "0.65748245", "0.65702015", "0.65686506", "0.65564376", "0.65167266", "0.6493665", "0.64799863", "0.64652354", "0.64523613", "0.64523613", "0.64523613", "0.64523613", "0.64444023" ]
0.7867124
0
User get read access to device ( owner or public device)
def get_read_access( u) return (u == self.user) || (self.public) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_allowed?(user)\n true\n end", "def read_access_check\n resource_check('read')\n end", "def read_access_check\n resource_check('read')\n end", "def read_access_check\n resource_check('read')\n end", "def permits_read_acccess_for(user)\n end", "def readable?\n status_flag?(:kSecReadPermStatus)\n end", "def show\n authorize! :read, @admin_system_admin\n end", "def acl\n 'public-read'\n end", "def accountant_allow_read(permission)\n return accountant_right(permission) > 0\n end", "def dor_read_rights\n public_xml_doc.xpath('//rightsMetadata/access[@type=\"read\"]/machine/*').map(&:name)\n end", "def access\n if self.read_users.present?\n \"limited\"\n elsif self.read_groups.empty?\n \"private\"\n elsif self.read_groups.include? \"public\"\n \"public\"\n elsif self.read_groups.include? \"registered\"\n \"restricted\" \n else \n \"limited\"\n end\n end", "def can_read?([email protected])\n effective_acl.can_read?(user)\n end", "def standard_authorized_user_rights\n Lockdown::System.public_access + Lockdown::System.protected_access \n end", "def show\n \tauthorize! :read, @user\n end", "def can_read?(user)\n self == user\n end", "def can_read?(user)\n self == user\n end", "def can_read?(user)\n self == user\n end", "def reseller_allow_read(permission)\n return reseller_right(permission) > 0\n end", "def resource_access\n return @resource_access\n end", "def resource_access\n return @resource_access\n end", "def show\n authorize Reading\n end", "def read_permissions\n can :read, String do |pid|\n Rails.logger.debug(\"[READPERM] Checking from STRING\")\n test_read(pid)\n end\n\n can :read, [DRI::Batch] do |obj|\n Rails.logger.debug(\"[READPERM] Checking from Object\")\n test_read(obj.id)\n end\n\n\n can :read, SolrDocument do |obj|\n Rails.logger.debug(\"[READPERM] Checking from SolrDoc\")\n cache.put(obj.id, obj)\n test_read(obj.id)\n end\n end", "def gr_is_visible?\n eval_policy(:read_access)\n end", "def accountant_can_read?(permission)\n session[:usertype].to_s == 'accountant' and session[\"acc_#{permission}\".to_sym].to_i == 1\n end", "def can_read=(value)\n if value\n set_privileges('r', value)\n else\n self.privileges = nil\n end\n end", "def read_permitted?\n return (acting_user.administrator? || true)\n end", "def readable_by? user\n true\n end", "def is_read_only\n return @is_read_only\n end", "def can_read?\n can?('r')\n end", "def can_read?(profile)\n \n can_access?(profile, [2,6])\n \n end" ]
[ "0.6786784", "0.6721274", "0.6721274", "0.6721274", "0.6633686", "0.660852", "0.6447477", "0.6434396", "0.64334863", "0.6424191", "0.6318311", "0.61437434", "0.6141246", "0.6107873", "0.6100798", "0.6100798", "0.6100798", "0.6083467", "0.6074477", "0.6074477", "0.6059687", "0.6033634", "0.6011274", "0.59878945", "0.59744734", "0.59447944", "0.59082454", "0.59070736", "0.5906866", "0.58934635" ]
0.7119225
0
GET /album_genres/1 GET /album_genres/1.json
def show @album_genre = AlbumGenre.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @album_genre } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @song_genre = SongGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @song_genre }\n end\n end", "def album\n album = Album.find(params[:id])\n render json: album\n end", "def index\n @pictures = @album.pictures #JRD111115\n\n respond_to do |format|\n format.html #index.html.erb\n format.json { render json: @pictures}\n end\n end", "def new\n @album_genre = AlbumGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album_genre }\n end\n end", "def get_album album_id\n get(\"/albums/#{album_id}\")\n end", "def show\n @book_genre = BookGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @book_genre }\n end\n end", "def show\n @albumm = Albumm.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @albumm }\n end\n end", "def show\n @picture = @album.pictures.find(params[:id]) #JRD111115\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @picture}\n end\n end", "def show\n @album = Album.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album }\n end\n end", "def index\n @book_genres = BookGenre.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @book_genres }\n end\n end", "def albums\n if params[:artist_id]\n albums = Artist.find(params[:artist_id]).albums\n else\n albums = Album.all\n end\n render json: albums\n end", "def show\r\n @album = Album.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @album }\r\n end\r\n end", "def show\n @sub_genre = SubGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sub_genre }\n end\n end", "def get_genres\n \tRails.cache.fetch(\"tmdb/genres_list\", expires_in: 24.hours) do\n \t\taction = \"genre/movie/list\"\n \t\targument = \"&language=en-US\"\n\t\t\tresponse = call_api(action, argument)\n\t\t\t@result = Hash.new\n\t\t\tresponse[\"genres\"].each do |genre|\n\t\t\t\t@result[genre[\"id\"]] = genre[\"name\"]\n\t\t\tend\n\t\t\t@result\n\t\tend\n\tend", "def updategenres\n @album = Album.find(params[:id])\n album_param = params[:albums] \n album_param[:genres].each do |genre_id|\n genre = Genre.find(genre_id)\n @album.genres << genre \n end \n respond_to do |format|\n format.html { redirect_to(@album) }\n format.xml { head :ok }\n end \n end", "def getgenres(artist = \"\")\n @check = false\n @artist = RSpotify::Artist.search(artist).first\n unless @artist.nil? || @artist.genres.empty?\n session[:artist] = @artist.name\n session[:id] = @artist.id\n @check = true\n getimage\n end\nend", "def show\n @genre_type = GenreType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @genre_type }\n end\n end", "def resource\n\t\t@album\n\tend", "def show\n @album = Album.where(id: params[:id]).first\n if @album\n render json: @album, status: 200\n else\n return_not_found \n end\n end", "def show\n album = Album.includes(:album_images).find(params[:id])\n return_hash = album.attributes\n return_hash['album_images'] = album.album_images\n render json: return_hash\n end", "def image_list\n @images = Picture.where(album_id: params[:album_id])\n respond_to do |format|\n format.json { render json: @images.to_json(methods: [:path])}\n end\n end", "def index\n @album = Album.find(params[:album_id])\n @photos = @album.photos.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @photos }\n end\n end", "def show\n @album = Album.find(params[:id])\n @potential_songs = Song.where(:artist_id => @album.artist.id)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album }\n end\n end", "def show\n @album = Album.find(params[:id])\n render json: AlbumSerializer.new(@album)\n end", "def show\n\t\t@genre = Genre.find(params[:id])\n\t\t@books_of_genre = @genre.books.order(title: :asc).paginate(page: params[:page], per_page: 24)\n\t\trespond_to do |format|\n\t\t\tformat.html {}\n\t\t\tformat.json {}\n\t\t\tformat.js\n\t\tend\n\tend", "def index\n @galleries_albums = Galleries::Album.all\n end", "def show\n @grm_pic = GrmPic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @grm_pic }\n end\n end", "def index\n if params[:genre].blank?\n\t\t\t@albums = Album.all.order(\"created_at DESC\")\n\t\telse\n\t\t\t@genre_id = Genre.find_by(name: params[:genre]).id\n\t\t\t@albums = Album.where(:genre_id => @genre_id).order(\"created_at DESC\")\n\t\tend\n end", "def show\n @gen = Gen.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gen }\n end\n end", "def get_genres(options = {})\n object_from_response(GogoKit::PagedResource,\n GogoKit::CategoriesRepresenter,\n :get,\n get_root.links['viagogo:genres'].href,\n options)\n end" ]
[ "0.7151078", "0.7113311", "0.6989473", "0.68686765", "0.6833885", "0.6801455", "0.6775186", "0.67685854", "0.67642325", "0.6763039", "0.6731936", "0.66824716", "0.6646332", "0.66308904", "0.65979886", "0.65918297", "0.6586351", "0.6584316", "0.6570412", "0.65621275", "0.6561686", "0.6558717", "0.65530497", "0.65350634", "0.65341264", "0.6533274", "0.6532689", "0.6525548", "0.65214586", "0.65098643" ]
0.7639327
0
GET /album_genres/new GET /album_genres/new.json
def new @album_genre = AlbumGenre.new respond_to do |format| format.html # new.html.erb format.json { render json: @album_genre } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @album = Album.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album }\n end\n end", "def new\n @album = Album.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album }\n end\n end", "def new\n @song_genre = SongGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @song_genre }\n end\n end", "def new\n @album = Album.new\n\n respond_to do |format|\n format.html # new.html.erb\n #format.json { render json: @album }\n end\n end", "def create\n @album_genre = AlbumGenre.new(params[:album_genre])\n\n respond_to do |format|\n if @album_genre.save\n format.html { redirect_to @album_genre, notice: 'Album genre was successfully created.' }\n format.json { render json: @album_genre, status: :created, location: @album_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @album_genre.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\r\n\r\n @album = Album.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @album }\r\n end\r\n end", "def new\n @albumm = Albumm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @albumm }\n end\n end", "def new\n @album = Album.new\n @title = \"new\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @album }\n format.js {}\n end\n end", "def new\n @album = current_user.albums.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album }\n end\n end", "def new\n @genre_type = GenreType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @genre_type }\n end\n end", "def new\n @book_genre = BookGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_genre }\n end\n end", "def new\n @gen = Gen.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gen }\n end\n end", "def new\n @album_owned = AlbumOwned.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album_owned }\n end\n end", "def new\n @user_album = UserAlbum.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user_album }\n end\n end", "def new\n @album2photo = Album2photo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album2photo }\n end\n end", "def new\n @genotype = Genotype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @genotype }\n end\n end", "def new\n @album = Album.find(params[:album_id])\n @photo = Photo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @photo }\n end\n end", "def create\n @song_genre = SongGenre.new(params[:song_genre])\n\n respond_to do |format|\n if @song_genre.save\n format.html { redirect_to @song_genre, notice: 'Song genre was successfully created.' }\n format.json { render json: @song_genre, status: :created, location: @song_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @song_genre.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @photo = Photo.new\n @photo.album_id = params[:album_id]\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @photo }\n end\n end", "def new\n @sub_genre = SubGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sub_genre }\n end\n end", "def new\n @album = Album.find_by_slug(params[:album_id])\n @album_item = AlbumItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album_item }\n end\n end", "def new\n @album = Album.find(params[:album_id])\n @photo = Photo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @photo }\n end\n end", "def new\n @group = Group.find(params[:group_id])\n @album = @group.albums.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album }\n end\n end", "def new\n @song = Song.new\n @song.verses.build\n @song.regions.build\n\n @kinds = Kind.all()\n @regions = Region.all()\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @song }\n end\n end", "def new\n @album = Album.new\n @photo = @album.photos.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @photo }\n end\n end", "def new\n @gallery = Gallery.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @gallery }\n end\n end", "def new\n @gallery = Gallery.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @gallery }\n end\n end", "def new\n @photo = @allbum.photos.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @photo }\n end\n end", "def new\n @album = Album.new\n @genres = Genre.find(:all, :order => \"name\")\n @artists = Artist.find(:all, :order => \"name\")\n @movies = Movie.find(:all, :order => \"name\")\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @album }\n end\n end", "def new\n @grm_pic = GrmPic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @grm_pic }\n end\n end" ]
[ "0.7584945", "0.7584945", "0.7580584", "0.7531309", "0.7515149", "0.7432592", "0.74296856", "0.7324332", "0.7315353", "0.73125166", "0.7295713", "0.72591764", "0.7183082", "0.7149219", "0.7142825", "0.71232575", "0.7122416", "0.7118146", "0.71158403", "0.7112992", "0.70868117", "0.7082513", "0.7068391", "0.703753", "0.70282686", "0.70149976", "0.70149976", "0.7000354", "0.69996595", "0.69829655" ]
0.7940656
0
POST /album_genres POST /album_genres.json
def create @album_genre = AlbumGenre.new(params[:album_genre]) respond_to do |format| if @album_genre.save format.html { redirect_to @album_genre, notice: 'Album genre was successfully created.' } format.json { render json: @album_genre, status: :created, location: @album_genre } else format.html { render action: "new" } format.json { render json: @album_genre.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def updategenres\n @album = Album.find(params[:id])\n album_param = params[:albums] \n album_param[:genres].each do |genre_id|\n genre = Genre.find(genre_id)\n @album.genres << genre \n end \n respond_to do |format|\n format.html { redirect_to(@album) }\n format.xml { head :ok }\n end \n end", "def create_albums\n url = 'https://stg-resque.hakuapp.com/albums.json'\n uri = URI(url)\n response = Net::HTTP.get(uri)\n albums = JSON.parse(response)\n\n albums.each do |album|\n Album.create!(album.except('id'))\n end\nend", "def new\n @album_genre = AlbumGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album_genre }\n end\n end", "def create\n ActiveRecord::Base.transaction do\n @album = Album.create!(album_params)\n # 画像登録数が多くなるUIになったらSQLの負荷を減らすためにactiverecord-importを入れる\n # https://github.com/zdennis/activerecord-import\n params[:urls].each do |image_url|\n AlbumImage.create!(album_id: @album.id, url: image_url)\n end\n end\n\n render json: @album\n end", "def create\n @song_genre = SongGenre.new(params[:song_genre])\n\n respond_to do |format|\n if @song_genre.save\n format.html { redirect_to @song_genre, notice: 'Song genre was successfully created.' }\n format.json { render json: @song_genre, status: :created, location: @song_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @song_genre.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @galleries_album = Galleries::Album.new(galleries_album_params)\n @galleries_album.user = current_user\n respond_to do |format|\n if @galleries_album.save\n format.html { redirect_to @galleries_album, notice: 'Album was successfully created.' }\n format.json { render :show, status: :created, location: @galleries_album }\n else\n format.html { render :new }\n format.json { render json: @galleries_album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\t@genre = Genre.new(genre_params)\n\t\[email protected]_id = current_user.id\n\n\t\trespond_to do |format|\n\t\t\tif @genre.save\n\t\t\t\t@genres=Genre.where(\"user_id = ?\", current_user.id).order(\"name\")\n\t\t\t\t@genres = @genres.paginate(page: params[:page], per_page: 18)\n\t\t\t\tformat.html { redirect_to @genre; flash[:success]= 'Genre was successfully created.' }\n\t\t\t\tformat.json { render :show, status: :created, location: @genre }\n\t\t\t\tformat.js\n\t\t\telse\n\t\t\t\tformat.html { render :new }\n\t\t\t\tformat.json { render json: @genre.errors, status: :unprocessable_entity }\n\t\t\t\tformat.js\n\t\t\tend\n\t\tend\n\tend", "def album\n album = Album.find(params[:id])\n render json: album\n end", "def create\n @genre = current_profile.genres.build(genre_params)\n\n respond_to do |format|\n if @genre.save\n format.html { redirect_to @genre, notice: 'Genre was successfully created.' }\n format.json { render :show, status: :created, location: @genre }\n else\n format.html { render :new }\n format.json { render json: @genre.errors, status: :unprocessable_entity }\n end\n end\n end", "def album_params\n params.require(:album).permit(:gn_id, :artist, :title, :release_date, :track_count, :genre, :url)\n end", "def create\n @album = Album.new(allowed_params_album)\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render :show, status: :created, location: @album }\n else\n format.html { render :new }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @album = Album.new(params[:album])\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render json: @album, status: :created, location: @album }\n else\n format.html { render action: \"new\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @album = Album.new(params[:album])\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render json: @album, status: :created, location: @album }\n else\n format.html { render action: \"new\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @album = Album.new(params[:album])\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render json: @album, status: :created, location: @album }\n else\n format.html { render action: \"new\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def genres=(genres_from_response)\n @genres = Enceladus::Genre.build_collection(genres_from_response)\n end", "def album_params\n params.require(:album).permit(:name, :artist, :year, :genre)\n end", "def album_params\n params.require(:album).permit(:id, :title, :description, :artist, :image, :genre_id)\n end", "def show\n @album_genre = AlbumGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album_genre }\n end\n end", "def create\n @album = Album.new(album_params)\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render :show, status: :created, location: @album }\n else\n format.html { render :new }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @album = Album.new(album_params)\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render :show, status: :created, location: @album }\n else\n format.html { render :new }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @albumm = Albumm.new(params[:albumm])\n\n respond_to do |format|\n if @albumm.save\n format.html { redirect_to @albumm, notice: 'Albumm was successfully created.' }\n format.json { render json: @albumm, status: :created, location: @albumm }\n else\n format.html { render action: \"new\" }\n format.json { render json: @albumm.errors, status: :unprocessable_entity }\n end\n end\n end", "def genre_params\n params.require(:genre).permit(:name, :title, :parent_id, :section_id, :tracking_code)\n end", "def create\n set_genre\n @subgenre = @genre.subgenres.new(subgenre_params)\n respond_to do |format|\n if @subgenre.save\n format.html { redirect_to subgenres_link_url, notice: 'Subgenre was successfully created.' }\n format.json { render :show, status: :created, location: @subgenre }\n else\n format.html { render :new }\n format.json { render json: @subgenre.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @album = Album.new(album_params)\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: \"Album was successfully created.\" }\n format.json { render :show, status: :created, location: @album }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @album = Album.new(album_params)\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render action: 'show', status: :created, location: @album }\n else\n format.html { render action: 'new' }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # Hack? How to do this better...\n params[:song][:genre] = Genre.find(params[:song][:genre_id])\n params[:song].delete(:genre_id)\n params[:song][:artist] = @artist\n @song = Song.new(params[:song])\n\n respond_to do |format|\n if @song.save\n format.html { redirect_to [@artist, @song], notice: 'Song was successfully created.' }\n format.json { render json: @song, status: :created, location: @song }\n else\n format.html { render action: \"new\" }\n format.json { render json: @song.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @album_ownership = AlbumOwnership.new\n @album_ownership.album = @album\n @album_ownership.user = current_user\n\n unless @album_ownership.save\n render json: @album_ownership.errors, status: :unprocessable_entity\n end\n end", "def create\n @albumsix = Albumsix.new(albumsix_params)\n\n respond_to do |format|\n if @albumsix.save\n format.html { redirect_to @albumsix, notice: 'Albumsix was successfully created.' }\n format.json { render :show, status: :created, location: @albumsix }\n else\n format.html { render :new }\n format.json { render json: @albumsix.errors, status: :unprocessable_entity }\n end\n end\n end", "def album_params\n params.require(:album).permit(:album_name, :album_description, :image, :artist_id, :genre_id)\n end", "def album_params\n params.require(:album).permit(:title, :description, :genre, :cover, :artists)\n end" ]
[ "0.71542436", "0.6566338", "0.6526033", "0.6405078", "0.64028573", "0.63616914", "0.6355944", "0.63066816", "0.6290948", "0.62879986", "0.62090665", "0.62071955", "0.62071955", "0.62071955", "0.62004757", "0.6187991", "0.61867565", "0.6170445", "0.6166137", "0.6166137", "0.6165806", "0.6159553", "0.6159524", "0.6134924", "0.6134872", "0.61161005", "0.6109609", "0.6092883", "0.6085037", "0.6079114" ]
0.70034546
1
DELETE /album_genres/1 DELETE /album_genres/1.json
def destroy @album_genre = AlbumGenre.find(params[:id]) @album_genre.destroy respond_to do |format| format.html { redirect_to album_genres_url } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @album.destroy\n render json: @album\n end", "def destroy\n @album = Album.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :ok }\n end\n end", "def destroy\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album = Album.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album = Album.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album = Album.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album = Album.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album = Album.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { render json: { status: 200 } }\n end\n end", "def destroy\n\n @album = @user.albums.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @song_genre = SongGenre.find(params[:id])\n @song_genre.destroy\n\n respond_to do |format|\n format.html { redirect_to song_genres_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @galleries_album.destroy\n respond_to do |format|\n format.html { redirect_to galleries_albums_url, notice: 'Album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @albumsix.destroy\n respond_to do |format|\n format.html { redirect_to albumsixes_url, notice: 'Albumsix was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n \t@album = Album.find(params[:album_id])\n @photo = @album.photos.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :ok }\n end\n end", "def destroy\n @omdb_genre.destroy\n respond_to do |format|\n format.html { redirect_to omdb_genres_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url, notice: 'El album a sido removido satisfactoriamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @albumm = Albumm.find(params[:id])\n @albumm.destroy\n\n respond_to do |format|\n format.html { redirect_to albumms_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url, notice: 'Album erfolgreich gelöscht.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @albums = Album.all\n @album = Album.find(params[:id])\n @album.destroy\n \n respond_to do |format|\n format.html { redirect_to albums_url, notice: 'Album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n [email protected]\n @photo.destroy\n save_to_json\n respond_to do |format|\n format.html { redirect_to album_path(album), notice: 'Photo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @photo = Photo.find(params[:id])\n @album = @photo.album\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_album_url(@album) }\n format.json { head :no_content }\n end\n end", "def destroy\n @albumone.destroy\n respond_to do |format|\n format.html { redirect_to albumones_url, notice: 'Albumone was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @photoalbum = Photoalbum.find(params[:id])\n @photoalbum.destroy\n\n respond_to do |format|\n format.html { redirect_to photoalbums_url }\n format.json { head :ok }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url, notice: 'Album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url, notice: 'Album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url, notice: 'Album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to albums_url, notice: 'Album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.7602658", "0.7382387", "0.7377284", "0.736904", "0.736904", "0.736904", "0.736904", "0.736904", "0.7354127", "0.7354127", "0.7354127", "0.73396933", "0.731502", "0.7314097", "0.7297047", "0.72846013", "0.7272589", "0.7244382", "0.7243497", "0.72404754", "0.7213964", "0.7209626", "0.71523076", "0.71445185", "0.7136671", "0.7132829", "0.7129924", "0.7127969", "0.7127969", "0.7127969" ]
0.7826642
0
crear un metodo initialize que inicialice las variables de instancia "revenue" y "costs" a cero
def initialize @revenue = 0 @costs = 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize(discount = 0) #new optionally takes an employee discount on initialization\n @total = 0 #SETS AN INSTANCE VARIABLE @TOTAL ON INITIALIZATION TO ZERO\n @discount = discount # CashRegister ::new optionally takes an employee discount on initialization\n @items = [] #returns an array containing all items that have been added\n end", "def initialize(employee_discount = 0)\n # initialization\n @total = 0\n @discount = employee_discount\n # creates items array and last_transaction hash to keep track of items and\n # the last purchase made\n @items = []\n @last_transaction = {}\n end", "def initialize\n self.total_net_discount_price = 0\n self.percentage_discounted_price = 0\n self.every_hundred_discount_price = 0\n end", "def initialize(discount = 0) #sets an instance variable @total on initialization to zero\n @total = 0\n @discount = discount\n @items = [] #sets @items to an empty array\n @transactions = []\n end", "def init()\n\t$numCharges = 0\n\t$numGiftCards = 0\n\t$giftCardAmount = 0\n\t$discountPercentage = 0\n\t$total = 0\n\t$labor = 0\nend", "def initialize(discount=0)\n @total = 0.0\n @discount = discount\n @items = []\n @prices = []\n end", "def initialize(discount = 0) #Says what attributes each instance is born with\n @total = 0\n @discount = discount \n @item = []\n end", "def initialize(discount = 20)\n @total = 0\n @discount = discount\nend", "def initialize(initial_balance, initial_equity, initial_margin, lev, currcy)\n # Account position / status.\n @balance = initial_balance\n @equity = initial_equity\n @margin = initial_margin\n @leverage = lev\n @base_currency = currcy\n\n # Open and closed trades.\n @orders = []\n @positions = []\n @closed_positions = []\n end", "def initialize(discount=0)\n #total begin at 0\n @total = 0\n @discount = discount\n #creats an array to hold all the items\n @items = []\n end", "def initialize(discount = 0)\n @total = 0\n @discount = discount\n @items = []\n @price = []\n end", "def initialize(buyer, seller, commodity, quantity_traded, clearing_price)\n @buyer = buyer\n @seller = seller\n @commodity = commodity\n @quantity = quantity_traded\n @price = clearing_price\n end", "def initialize(options)\n @id = options[:id].to_i\n @year = options[:year].to_i\n @model = options[:model].to_s\n @engine = options[:engine].to_s\n @sale_price = options[:sale_price].to_i\n @mpg_city = options[:mpg_city].to_i\n @mpg_hwy = options[:mpg_hwy].to_i\n @maint_cost = options[:maint_cost].to_i\n @rpr_cost = options[:rpr_cost].to_i\n @ins_cost = options[:ins_cost].to_i\n @grade_fuel = options[:grade_fuel].to_s\n @regular = 2.79\n @mid_grade = 2.95\n @premium = 3.05\n @diesel = 2.85\n @annual_miles = 12000\n @years_to_keep = options[:years_to_keep].to_i\n end", "def initialize(discount = nil)\n #set instance variable @total on initialize to 0\n @total = 0\n @products = []\n\n if !(discount == nil)\n @discount = discount\n end\n end", "def initialize(discount = 0)\n @total = 0\n @discount = discount\n @items = []\n @transactions = []\n end", "def initialize (nombre, saturadas, monoinsaturadas, polinsaturadas, azucares, polialcoles, almidon, fibra, proteinas, sal)\n\t\t@nombre, @saturadas, @monoinsaturadas, @polinsaturadas, @azucares, @polialcoles, @almidon, @fibra, @proteinas, @sal = nombre, saturadas, monoinsaturadas, polinsaturadas, azucares, polialcoles, almidon, fibra, proteinas, sal\n\tend", "def initialize(cost, percent, guests)\n @cost = cost\n @percent = percent\n @guests = guests\n end", "def initialize\n @orders = Hash.new\n @price = 0.0\n @weight = 0.0\n end", "def init_custom_fields\n @growth_rate = [0.0] * 8\n @msp = 0\n @capacities = []\n end", "def initialize(options = {})\n initialize_options(options)\n @principal = principal_calculation\n @monthly_rate = @nominal_rate / 100 / 12\n end", "def initialize\n @funds = 1000\n end", "def initialize(name, cost)\n @name = name\n @cost = cost\n end", "def initialize(opts)\n super\n\n @full_load_hours = opts[:full_load_hours]\n @output_capacity_per_unit = opts[:output_capacity_per_unit]\n @availability = opts[:availability]\n @number_of_units = opts[:number_of_units]\n @fixed_costs_per_unit = opts[:fixed_costs_per_unit]\n @fixed_om_costs_per_unit = opts[:fixed_om_costs_per_unit]\n\n @load_curve = Curve.new(Array.new(Merit::POINTS, 0.0))\n @cost_strategy ||= CostStrategy.create(self, opts)\n end", "def initialize(discount = 0)\n @total = 0 # And these assign them generic argument name\n @discount = discount\n @items = []\n end", "def set_defaults\n self.min_service_life_months ||= 0\n self.replacement_cost ||= 0\n self.lease_length_months ||= 0\n self.rehabilitation_service_month ||= 0\n self.rehabilitation_labor_cost ||= 0\n self.rehabilitation_parts_cost ||= 0\n self.extended_service_life_months ||= 0\n self.min_used_purchase_service_life_months ||= 0\n self.cost_fy_year ||= current_planning_year_year\n end", "def init_calculation\n @gross_zone_residual_demands ||= GrossZoneResidualDemands.new\n end", "def initialize_attributes\n @total_positives = 0\n @total_negatives = 0\n @total_neutrals = 0\n super\n end", "def initialize(discount = nil)\n @total = 0\n @discount = discount\n @instance_items = []\nend", "def init_demand\n\t\t\n\t\t# building the sum of the demand values\n\t\tsum_values = 0\n\t\t(0..(@nbTSInOneDay - 1)).each do |ts|\n\t\t\tsum_values += getDemandAt(ts)\n\t\tend\n\t\t\n\t\t# cululated sum + normalization \n\t\tdemand = {}\n\t\t(0..(@nbTSInOneDay - 1)).each do |ts|\n\t\t\tdemand[ts] =\n\t\t\tif ts != 0\n\t\t\t\tdemand[ts - 1] + (getDemandAt(ts).to_f / sum_values)\n\t\t\telse\n\t\t\t\tgetDemandAt(ts).to_f / sum_values\n\t\t\tend\n\t\tend\n\t\t\n\t\treturn demand\n\tend", "def initialize(**opts)\n @price_over = opts[:price_over] || 0\n @basket_discount = opts[:basket_discount] || 0\n @product_code = opts[:product_code] || 0\n @product_quantity = opts[:product_quantity] || 0\n @new_price = opts[:new_price] || 0\n end" ]
[ "0.69509363", "0.69056004", "0.6743452", "0.67419595", "0.66899025", "0.6654327", "0.6624689", "0.6618325", "0.64908767", "0.6467", "0.6452923", "0.6414348", "0.6412228", "0.640696", "0.6346843", "0.6342039", "0.6328918", "0.6324803", "0.63179314", "0.63158774", "0.631197", "0.627904", "0.627619", "0.6276119", "0.62644845", "0.6255276", "0.6242002", "0.62324834", "0.62290126", "0.6212416" ]
0.8083272
0
crear un metodo "credit" que reciba un parametro "amount" y se lo sume a la variable de instancia "revenue"
def credit(amount) @revenue += amount end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def credit(postive_amount)\n Credit.create!(team: team,\n room_type: room_type,\n amount: postive_amount)\n end", "def credit *args\n warn_on_positional args\n\n options = args.last.is_a?(Hash) ? args.pop : {}\n amount = args[0] || options.fetch(:amount) { nil }\n description = args[1] || options.fetch(:description) { nil }\n appears_on_statement_as = args[3] || options.fetch(:appears_on_statement_as) { nil }\n \n if self.has_account?\n meta = args[2] || options.fetch(:meta) { nil }\n destination_uri = args[4] || options.fetch(:destination_uri) { self.uri }\n credit = self.account.credit(\n :amount => amount,\n :meta => meta,\n :description => description,\n :destination_uri => destination_uri,\n :appears_on_statement_as => appears_on_statement_as\n )\n else\n credit = Credit.new(\n :uri => self.credits_uri,\n :amount => amount,\n :description => description,\n :appears_on_statement_as => appears_on_statement_as\n )\n credit.save\n end\n\n credit\n end", "def credit(description, amount)\n\t\tadd_transaction(description, amount)\n\tend", "def credit(amount, description)\n super(amount, description) # Call and pass data to the original methods of the BankAccount\n charge_fee # And also charge a fee, add another transaction\n end", "def credit( amount_in_cents )\n resp = client.credit(\n token: payment.token,\n expires_at: payment.expires_at,\n amount: amount_in_cents.to_i.abs\n ).body\n user.credits.create!(\n amount_in_cents: amount_in_cents,\n description: I18n.t('transactions.credit'),\n metadata: resp.as_json\n )\n rescue BridgePay::ResponseError => ex\n raise CreditFailure.new( ex.response )\n end", "def credit amount, description=nil, meta={}\n self.account.credit(amount, description, meta, self.uri)\n end", "def create_credit(reimbursement, unpaid_amount, simulate)\n category = Spree::StoreCreditCategory.default_reimbursement_category(category_options(reimbursement))\n creditable = Spree::StoreCredit.new(store_credit_params(category, reimbursement, unpaid_amount))\n credit = reimbursement.credits.build(creditable: creditable, amount: unpaid_amount)\n simulate ? credit.readonly! : credit.save!\n credit\n end", "def do_credit!\n # user = User.where('id=? OR rfid=?', user_param.to_i, user_param).first\n user = User.find_by(id: user_param)\n BridgePayService.new( user ).credit( credit_amount )\n end", "def credit(amount = nil, options = {})\n execute(:credit, {:amount => amount || self.amount}.reverse_merge(options))\n end", "def credit amount, description=nil, meta={}, destination_uri=nil\n credit = Credit.new(\n :uri => self.credits_uri,\n :amount => amount,\n :meta => meta,\n :description => description,\n :destination_uri => destination_uri,\n )\n credit.save\n end", "def credit(amount, authorization, options={})\n adjust_and_save(amount.abs, :credit, {:authorization => authorization}.merge(options))\n end", "def give_shnack_credit(creditor_id, amount)\n @creditor = User.find(creditor_id)\n creditor.account_credit = creditor.account_credit + amount\n end", "def credit(amount, current_period)\n if balance.zero?\n \"You do not have a balance.\"\n else\n @balance -= amount\n calculate_interest(current_period, @txns.keys.last)\n save_txn(current_period, 'credit', amount, @balance)\n @ints << @interest\n get_balance\n end\n end", "def create\n @credit = Credit.new(params[:credit])\n \n @credit.amount = 0 if params[:credit][:amount].empty?\n current_credit = Credit.find_by_customer_id(session[:cust_id])\n \n authorise_amount @credit.amount\n\n if current_credit \n current_credit.amount += @credit.amount\n @credit = current_credit\n else\n @credit.customer_id = session[:cust_id]\n # @credit.save\n end\n\n\n\n\n respond_to do |format|\n if @credit.save\n format.html { redirect_to credits_url, notice: 'Credit was successfully created.' }\n format.json { render json: @credit, status: :created, location: @credit }\n else\n format.html { render action: \"new\" }\n format.json { render json: @credit.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_credit\n credit\n end", "def apply_freshbooks_credit!\n credit = [ self.organization.accounting_gateway.available_credits[:USD], self.invoice_balance ].min\n response = FreshBooks.account.payment.create({ payment: {\n invoice_id: self.freshbooks_invoice_id,\n client_id: self.organization.accounting_gateway.freshbooks_id,\n amount: credit,\n type: 'Credit'\n }})\n end", "def credit_description(amount)\n \"Credited Transaction where platform credit covers $#{(amount/100)} of the original $#{total} for transaction ID: #{id} -- #{user.email} just bought a #{item_bought.title} for $#{total}, from #{merchant.title}\"\n end", "def add_cash(amount)\n transaction = Transaction.new\n transaction.transaction_type_id = 1\n transaction.seller_id = self.id\n transaction.price = Setting.first.exchange_rate\n transaction.amount = amount\n transaction.save\n self.update_portfolio\n return transaction\n end", "def credit_amount\n sum( credits )\n end", "def add_credit\n#\t\tcurrent_user.update(balance: current_user.balance + params[:amount])\n\tend", "def credit!(amount)\n self.balance += parse_monetary_value(amount)\n self.store\n end", "def credit(credit_cents, payment_id, options)\n order_number = options[:originator].try(:payment).try(:order).try(:number)\n MollieLogger.debug(\"Starting refund for order #{order_number}\")\n\n begin\n amount = credit_cents / 100.0\n Mollie::Payment::Refund.create(\n payment_id: payment_id,\n amount: amount,\n description: \"Refund Spree Order ID: #{order_number}\",\n api_key: get_preference(:api_key)\n )\n MollieLogger.debug(\"Successfully refunded #{amount} for order #{order_number}\")\n ActiveMerchant::Billing::Response.new(true, 'Refund successful')\n rescue Mollie::Exception => e\n MollieLogger.debug(\"Refund failed for order #{order_number}: #{e.message}\")\n ActiveMerchant::Billing::Response.new(false, 'Refund unsuccessful')\n end\n end", "def credit(credit_cents, payment_id, options)\n order = options[:originator].try(:payment).try(:order)\n order_number = order.try(:number)\n order_currency = order.try(:currency)\n MollieLogger.debug(\"Starting refund for order #{order_number}\")\n\n begin\n Mollie::Payment::Refund.create(\n payment_id: payment_id,\n amount: {\n value: format_money(order.display_total.money),\n currency: order_currency\n },\n description: \"Refund Spree Order ID: #{order_number}\",\n api_key: get_preference(:api_key)\n )\n MollieLogger.debug(\"Successfully refunded #{order.display_total} for order #{order_number}\")\n ActiveMerchant::Billing::Response.new(true, 'Refund successful')\n rescue Mollie::Exception => e\n MollieLogger.debug(\"Refund failed for order #{order_number}: #{e.message}\")\n ActiveMerchant::Billing::Response.new(false, 'Refund unsuccessful')\n end\n end", "def credit(money, creditcard, options = {})\n if creditcard.is_a?(String)\n raise ArgumentError, \"Reference credits are not supported. Please supply the original credit card or use the #refund method.\"\n end\n\n form = {}\n add_invoice(form, options)\n add_creditcard(form, creditcard)\n add_address(form, options)\n add_customer_data(form, options)\n add_test_mode(form, options)\n commit(:credit, money, form)\n end", "def credit(range = nil)\n credit = (range == nil ? self.transactions : self.transactions.all(:date => range)).all(:amount.gt => 0).sum(:amount)\n credit == nil ? 0.0 : credit\n end", "def credit(money, identification, options = {})\n post = { :gateid => identification }\n\n commit('CREDIT', money, post)\n end", "def user_credit_params\n params.require(:user_credit).permit(:created_user_id, :purchased_user_id, :item_id, :credit)\n end", "def add_credit(amount)\n raise Transfer::NegativeAmountException if(amount < 0)\n self.lines.create(amount: self.balance + amount)\n self.balance += amount\n end", "def purchase(money, creditcard, options = {})\n post = {}\n add_invoice(post, options)\n add_creditcard(post, creditcard) \n add_address(post, creditcard, options) \n add_customer_data(post, options)\n add_duplicate_window(post)\n \n commit('SALE', money, post)\n end", "def buy_credits\n if request.post? || params[:PayerID]\n payment = params[:PayerID] ? current_user.credit_payments.where(payment_token: params[:token]).take : current_user.credit_payments.new(amount: params[:amount])\n make_payment_helper(payment, paypal_cancel_url: url_for(action: :index), success_msg: 'Credits successfully purchased!') do\n current_user.add_credits(payment.amount)\n end\n end\n end" ]
[ "0.70318425", "0.6715307", "0.6713559", "0.6667777", "0.664224", "0.6625338", "0.66235304", "0.6605122", "0.6574353", "0.6569881", "0.6449399", "0.6412946", "0.64040864", "0.63758034", "0.6359669", "0.63437325", "0.63192797", "0.63162225", "0.622324", "0.62189704", "0.6201884", "0.61342996", "0.61307937", "0.61200255", "0.6111858", "0.60955316", "0.608311", "0.60829103", "0.60605186", "0.60528064" ]
0.74697095
0
has many clients through appointments
def clients Appointments.all.collect do |appointment| appointment.client end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def client_appointments\n self.clients.map(&:appointments)\n end", "def create\n # Create new client object, with nested appointment object\n @client = Client.new(client_params)\n # Set the new appointment's user_id equal to the current_user's id. This completes the association\n # between the current user and client, with the appointment acting as a join table\n @client.appointments.update(user_id: current_user.id)\n if @client.save\n redirect_to client_path(@client)\n else\n redirect_to new_user_client_path(current_user), alert: \"Error(s): #{@client.errors.full_messages.join(', ')}.\"\n end\n end", "def appointments\n Appointment.all.filter { |appointment| appointment.provider_id == self.id || appointment.user_id == self.id}\n end", "def appointments\r\n Appointment.all.collect do\r\n\t\t\t|appt| appt if appt.doctor == self\r\n\t\tend\r\n\tend", "def appointments\n # 1. access the Appt's @@all variable\n # 2. from there, select only the appoints whose doctor is self\n Appointment.all.select{|appointment| appointment.doctor == self}\n end", "def appointments\n Appointment.all.collect do\n\t\t\t|appt| appt if appt.doctor == self\n\t\tend\n\tend", "def my_appointments(user)\n Appointment.where(user_id: user.id)\n end", "def appointments\n Appointment.all.select{|appointments| appointments.doctor == self}\n end", "def appointments\n Appointment.all.select {|appt| appt.patient == self}\n end", "def appointments\n Appointment.all(contact: to_s)\n end", "def appointments\n Appointment.all.select {|appointments| appointments.patient == self}\n end", "def appointments\n @appointments\n end", "def appointments\n @appointments\n end", "def appointments\n Appointment.all.select{|appointment| appointment.doctor == self}\n end", "def appointments\n Appointment.all.select {|appointment| appointment.patient == self}\n # Appointment.all.select {|appointment| appointment.doctor == self}\n end", "def appointments\n Appointment.all.select { |x| x.patient == self }\n end", "def appointments\n Appointment.all.select do |appointment| appointment.patient == self end\n end", "def appointments\n Appointment.all.select{|x| x.patient == self}\nend", "def appointments\n Appointment.all.select do |a|\n a.doctor == self\n end\n end", "def show\n @client = User.find(params[:id])\n if @client.role == 'client'\n @cases = CaseCounselorClient.where(\"client_id = '#{@client.id}'\")\n @appointments = @client.appointments.scoped\n @appointments = @client.appointments.between(params['start'], params['end']) if (params['start'] && params['end'])\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @appointments.to_json }\n end\n else\n redirect_to admin_dashboards_path\n end\n end", "def appointments\n Appointment.all.select do |appointment|\n appointment.patient == self\n end\n end", "def appointments\n Appointment.all.select do |appointment|\n appointment.patient == self\n end\n end", "def appointments\n Appointment.all.select{|appointment| appointment.patient == self}\nend", "def appointments\n Appointment.all.select { |appointment| appointment.patient == self }\nend", "def appointments\n Appointment.all.select do |appointment_instance|\n appointment_instance.doctor == self \n end\n end", "def appointments \n Appointment.all.select do |a|\n a.patient == self\n end\nend", "def appointments_attributes=(appointments_attributes)\n # If submitted client is valid\n if self.valid?\n appointments_attributes.values.each do |appointment_attributes|\n # Clients have only 1 associated appointment object. Instead of creating new objects\n # we simply update the date attribute once an appointment is completed\n if self.appointments.last != nil\n self.appointments.last.update(appointment_attributes)\n else\n # Create new appointment object and make it belong to new client\n appointment = Appointment.create(appointment_attributes)\n self.appointments << appointment\n end\n end\n end\n end", "def appointments\n Appointment.all.select {|appointment| appointment.doctor ==self}\nend", "def appointments(officer_id)\n client.get(\"officers/#{officer_id}/appointments/\")\n end", "def index\n client = find_client(request.headers[\"X-CLIENT-TOKEN\"], request.headers[\"X-CLIENT-EMAIL\"])\n @appointments = client.appointments.includes(:stylist).includes(:offerings).order(\"created_at DESC\")\n respond_to do |f|\n f.json {\n render :json => @appointments\n }\n end\n end" ]
[ "0.76485354", "0.68745774", "0.66267776", "0.65794945", "0.654963", "0.650973", "0.6493033", "0.6463341", "0.6451692", "0.64151096", "0.64056396", "0.638461", "0.638461", "0.63814384", "0.6379531", "0.63785684", "0.63550484", "0.63399714", "0.63325363", "0.63052034", "0.62588674", "0.62588674", "0.6256761", "0.6241458", "0.62396467", "0.6217512", "0.6207833", "0.6134103", "0.6115102", "0.6113828" ]
0.74405485
1
recursively crawls the parser rules and looks for elements that index values. Adds an empty index for each of these.
def setup_indexes rules if rules[:children] rules[:children].each_pair do |child_name,child_rules| if index = child_rules[:index] @indexes[index[:name]] = {} end setup_indexes(child_rules) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def match parser, index\r\n raise \"no children added to sequence\" unless @list\r\n each do |element|\r\n index = element.match parser, index\r\n return NO_MATCH unless index\r\n end\r\n report index\r\n end", "def first_nil_parse_index_assert\n idx = @children.index{|x| x.is_nil_parse? }\n if idx.nil?\n return @children.length\n end\n bad1 = (0..idx-1).map{|i|\n @children[i].is_nil_parse? ?\n [i,@children[i]] : nil\n }.compact\n bad2 = ([email protected]).map{|i|\n @children[i].is_nil_parse? ?\n nil : [i, @children[i]]\n }.compact\n bads = bad1 + bad2\n if bads.any? then no(\n \"found nil parses or non where we didn't expect to:\" <<\n \"i am #{short} and these are my bad children: \" << (\n bads.map{|b| \"at #{b[0]}: #{b[1].short}\"}.join(';')\n )\n ) end\n idx\n end", "def create_index\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 3 )\n return_value = CreateIndexReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n string_literal4 = nil\n __ID5__ = nil\n string_literal6 = nil\n __ID7__ = nil\n char_literal8 = nil\n __ID9__ = nil\n char_literal10 = nil\n __ID11__ = nil\n string_literal12 = nil\n\n tree_for_string_literal4 = nil\n tree_for_ID5 = nil\n tree_for_string_literal6 = nil\n tree_for_ID7 = nil\n tree_for_char_literal8 = nil\n tree_for_ID9 = nil\n tree_for_char_literal10 = nil\n tree_for_ID11 = nil\n tree_for_string_literal12 = nil\n\n begin\n root_0 = @adaptor.create_flat_list\n\n\n # at line 25:5: 'create index' ID 'on' ID '(' ID ( ',' ID )* ');'\n string_literal4 = match( CREATE_INDEX, TOKENS_FOLLOWING_CREATE_INDEX_IN_create_index_117 )\n\n tree_for_string_literal4 = @adaptor.create_with_payload( string_literal4 )\n root_0 = @adaptor.become_root( tree_for_string_literal4, root_0 )\n\n __ID5__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_120 )\n\n tree_for_ID5 = @adaptor.create_with_payload( __ID5__ )\n @adaptor.add_child( root_0, tree_for_ID5 )\n\n string_literal6 = match( T__16, TOKENS_FOLLOWING_T__16_IN_create_index_122 )\n __ID7__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_125 )\n\n tree_for_ID7 = @adaptor.create_with_payload( __ID7__ )\n @adaptor.add_child( root_0, tree_for_ID7 )\n\n char_literal8 = match( T__17, TOKENS_FOLLOWING_T__17_IN_create_index_127 )\n __ID9__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_130 )\n\n tree_for_ID9 = @adaptor.create_with_payload( __ID9__ )\n @adaptor.add_child( root_0, tree_for_ID9 )\n\n # at line 25:41: ( ',' ID )*\n while true # decision 3\n alt_3 = 2\n look_3_0 = @input.peek( 1 )\n\n if ( look_3_0 == T__18 )\n alt_3 = 1\n\n end\n case alt_3\n when 1\n # at line 25:42: ',' ID\n char_literal10 = match( T__18, TOKENS_FOLLOWING_T__18_IN_create_index_133 )\n __ID11__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_136 )\n\n tree_for_ID11 = @adaptor.create_with_payload( __ID11__ )\n @adaptor.add_child( root_0, tree_for_ID11 )\n\n\n else\n break # out of loop for decision 3\n end\n end # loop for decision 3\n string_literal12 = match( T__19, TOKENS_FOLLOWING_T__19_IN_create_index_140 )\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 3 )\n\n end\n \n return return_value\n end", "def scan_pages0( index, directory )\n unless index\n index = Page.new( File.join( directory, \"index.src\" ) )\n @root = index \n end\n \n @subdir_pages = get_nondir_pages( directory )\n @nondir_pages = get_subdir_pages( directory )\n \n @nondir_pages.each do |page_src|\n Page.new( page_src, index )\n end\n @subdir_pages.each do |page_src|\n page = Page.new( page_src, index )\n scan_pages( config, page, File.dirname( page_src ) )\n end\n end", "def build_index\n index = {}\n\n rules.each_with_index do |rule, idx|\n key = rule.key\n\n # Use this to make sure any duplicate entry uses the maximum index (i.e. last defined rule).\n index[key] = [ index[key], idx ].compact.max\n end\n index\n end", "def build_index(seed, depth)\r\n filename = \"index.csv\"\r\n \r\n # if depth is 0, scrape the seed, SET N TO Y, and stop. \r\n # if depth is greater than 0, go back to beginning of file\r\n # scrape each page, mark scraped, and append it to the index\r\n \r\n populate_index(scrape_page(seed)) \r\n \r\n # read index, rowid = $.\r\n # for each, check row[1] for y\r\n # if !y, scrape and append to index\r\n \r\n i = 1\r\n links = Set.new # AVOID DUPLICATE LINKS IN THE INDEX\r\n \r\n while i <= depth\r\n puts \"Scraping at DEPTH: i = #{i}\"\r\n CSV.foreach(filename, :headers => true) do |row| \r\n if row[1] != \"y\" && !links.include?(row[0])\r\n scrape_page(row[0]).each do |link| \r\n if !links.include?(link) # AVOID DUPLICATE LINKS IN THE INDEX \r\n links.add(link)\r\n CSV::open(filename, \"ab\") do |csv|\r\n csv << [link, \"n\"]\r\n end\r\n end\r\n end\r\n row[1] << \"y\" #doesn't work? can probably get rid of. \r\n end\r\n end\r\n i+=1\r\n end\r\n \r\n # index complete\r\n \r\nend", "def index()\n INDEXES.find { |i| (self + i).exist? }&.yield_self { |i| self + i }\n end", "def _lex_index_offsets=(_arg0); end", "def _lex_index_offsets=(_arg0); end", "def _lex_index_offsets=(_arg0); end", "def _lex_index_offsets=(_arg0); end", "def match parser, index\r\n raise \"multiple element child not set\" unless child\r\n raise \"multiple element range not set\" unless range\r\n count = 0\r\n while count < range.last\r\n found = child.match parser, index\r\n break unless found\r\n index = found\r\n count += 1\r\n end\r\n report range === count ? index : NO_MATCH\r\n end", "def build_index\n reset @store.all_files.sort, @store.all_classes_and_modules.sort\n\n index_classes\n index_methods\n index_pages\n\n { :index => @index }\n end", "def _lex_index_offsets; end", "def _lex_index_offsets; end", "def _lex_index_offsets; end", "def _lex_index_offsets; end", "def build_index!(&block)\n entries_added = do_build_index(&block) unless built?\n\n #make the hash from abbreviated parts of speech to full definitions\n @pos_hash ||= build_pos_hash\n\n entries_added\n end", "def freshen_parent_and_child_indexes\n freshen_parent_and_child_indexes(0)\n end", "def match parser, index\r\n raise \"Must override match\"\r\n end", "def build_index\n to_index = [@dir]\n index = {}\n while (dir = to_index.shift)\n Dir.new(dir).each { |entry| index_entry to_index, index, dir, entry }\n end\n\n index\n end", "def index\r\n build_index unless @index\r\n @index\r\n end", "def parse_indexes(marc)\n tag868 = marc['868']\n return [] unless tag868\n\n indexes = []\n\n marc.each_by_tag('868') do |t868|\n indexes.push( t868.subfields.collect {|s| s.value if s.code == 'a'}.join(' ').strip )\n end\n\n indexes\n\n\n # tag868 = marc.css(\"slim|datafield[@tag='868']\")\n # \n # return [] unless tag868\n # \n # indexes = []\n # tag868.each do |field|\n # subs = field.css(\"slim|subfield\").collect { |subfield| subfield.content if subfield.attr(\"code\").match(/[az]/)}\n # indexes << subs.join(\" \").strip unless subs.empty?\n # end\n # \n # indexes\n\n end", "def crawl_parser(results)\n\t\tputs \"[\".light_green + \"*\".white + \"] OK\".light_green + \", \".white + \"running parser on\".light_green + \": #{results}\".white\n\t\timportant = File.open(results, \"r\") #place our found links in variable to manipulate and search as needed\n\t\trezDir = \"#{$results}#{@zsite}/\" #Our results dir for this site which has been already created in first function cycles\n\n\t\t# placeholder arrays for sorting and finding unique testable links\n\t\tspreadsheetz=[]; executablez=[]; no_params=[]; test_keys=[]; noparamz=[]; archivez=[]; testlink=[]; opendocz=[]; outlookz=[]; paramz=[]; imagez=[];\n\t\taudioz=[]; videoz=[]; flashz=[]; multi=[]; vcardz=[]; bkupz=[]; jsz=[]; confz=[]; wordz=[]; xmlz=[]; pazz=[]; pdfz=[]; txtz=[]; pptz=[]; dbz=[];\n\n\t\tmcount=0 #Multi Parameter Links Count\n\t\tscount=0 #Single Parameter Links Count\n\t\tnocount=0 #No Parameter Links Count\n\n\t\t#loop through content of crawler.links file line by line...\n\t\timportant.each do |line|\n\t\t\tbegin\n\t\t\t\t#parse out parameters if they are present, if not will error NoMethodError and be handled there with rescue\n\t\t\t\tparam = URI.parse(line).query\n\n\t\t\t\t#break paramaters into hash [ \"@key\" => \"@value\" ] formatting held in storage for easier manipulation\n\t\t\t\tparamsHash = Hash[URI.parse(line).query.split('&').map{ |q| q.split('=') }] \n\n\t\t\t\t# Parse according to the number of parameters in link\t\t\n\t\t\t\t###### Handle Single Parameter links ######\n\t\t\t\tif paramsHash.length == 1\n\t\t\t\t\tscount += 1\n\t\t\t\t\tparamz << line\n\t\t\t\t\tparamsHash.each do |key, value|\n\t\t\t\t\t\tif value =~ /\\d+/ #if value is numerical replace with number and then we unique ;)\n\t\t\t\t\t\t\ttestlink << line.sub(/#{value}/, '1') \n\t\t\t\t\t\telse\n\t\t\t\t\t\t\ttestlink << line #keep strings since they can be funky sometimes\n\t\t\t\t\t\tend\n\t\t\t\t\tend #finish cycle\n\n\t\t\t\telsif \"#{paramsHash.length}\".to_i > 1\n\t\t\t\t\t###### Handle Multi Parameter links ######\n\t\t\t\t\tmcount += 1\n\t\t\t\t\tparamz << line\n\t\t\t\t\t#Test each link and see if the parameter key has been logged or not, this way we only get unique paramter links ;)\n\t\t\t\t\tparamsHash.keys.each do |key|\n\t\t\t\t\t\tif test_keys.include?(key)\n\t\t\t\t\t\t\t#Do Nothing, its already included in our test_keys array!\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t#Unique paramter, include key in test_key array and URL link in multi array for injector tests l8r\n\t\t\t\t\t\t\ttest_keys << key #so we dont catch anymore links with this parameter\n\t\t\t\t\t\t\tmulti << line.chomp #so we note the link for injection tests\n\t\t\t\t\t\tend\n\t\t\t\t\tend#end hash.key cycle\n\t\t\t\tend # parameter check looping\n\n\t\t\t###### Handle NO Parameter links ######\n\t\t\trescue NoMethodError\n\t\t\t\t# We really only need to check a few links without params to see if they throw errors (URL re-write type stuff hiding)\n\t\t\t\tnocount += 1\n\t\t\t\tif nocount < 10 # gives us up to 15 no parameter links to check, more than enough\n\t\t\t\t\tno_params << line\n\t\t\t\tend\n\n\t\t\t\t#Parse over links we're ditching & sort into appropriate results files (in case that info is needed for follow up l8r)\n\t\t\t\tif /\\/.+\\.pdf/i.match(line)\n\t\t\t\t\tpdfz << line.chomp\n\t\t\t\telsif /\\/.+\\.doc/i.match(line)\n\t\t\t\t\twordz << line.chomp\n\t\t\t\telsif /\\/.+\\.js|\\/.+\\.javascript/i.match(line)\n\t\t\t\t\tjsz << line.chomp\n\t\t\t\telsif /\\/.+\\.txt|\\/.+\\.rtf/i.match(line)\n\t\t\t\t\ttxtz << line.chomp\n\t\t\t\telsif /\\/.+\\.png|\\/.+\\.jpg|\\/.+\\.jpeg|\\/.+\\.gif|\\/.+\\.bmp|\\/.+\\.exif|\\/.+\\.tiff/i.match(line)\n\t\t\t\t\timagez << line.chomp\n\t\t\t\telsif /\\/.+\\.msg/i.match(line)\n\t\t\t\t\toutlookz << line.chomp\n\t\t\t\telsif /\\/.+\\.odt/i.match(line)\n\t\t\t\t\topendocz << line.chomp\n\t\t\t\telsif /\\/.+\\.csv|\\/.+\\.xlr|\\/.+\\.xls/i.match(line)\n\t\t\t\t\tspreadsheetz << line.chomp\n\t\t\t\telsif /\\/.+\\.pps|\\/.+\\.ppt/i.match(line)\n\t\t\t\t\tpptz << line.chomp\n\t\t\t\telsif /\\/.+\\.tar|\\/.+\\.zip|\\/.+\\.7z|\\/.+\\.cbr|\\/.+\\.deb|\\/.+\\.gz|\\/.+\\.bz|\\/.+\\.pkg|\\/.+\\.rar|\\/.+\\.rpm|\\/.+\\.sit/i.match(line)\n\t\t\t\t\tarchivez << line.chomp\n\t\t\t\telsif /\\/.+\\.vcf/i.match(line)\n\t\t\t\t\tvcardz << line.chomp\n\t\t\t\telsif /\\/.+\\.xml/i.match(line)\n\t\t\t\t\txmlz << line.chomp\n\t\t\t\telsif /\\/.+\\.m3u|\\/.+\\.m4a|\\/.+\\.mp3|\\/.+\\.mpa|\\/.+\\.wav|\\/.+\\.wma/i.match(line)\n\t\t\t\t\taudioz << line.chomp\n\t\t\t\telsif /\\/.+\\.avi|\\/.+\\.mov|\\/.+\\.mp4|\\/.+\\.mpg|\\/.+\\.srt|\\/.+\\.vob|\\/.+\\.wmv/i.match(line)\n\t\t\t\t\tvideoz << line.chomp\n\t\t\t\telsif /\\/.+\\.swf|\\/.+\\.flv/i.match(line)\n\t\t\t\t\tflashz << line.chomp\n\t\t\t\telsif /\\/.+\\.sql|\\/.+\\.accdb|\\/.+\\.db|\\/.+\\.mdb|\\/.+\\.pdb/i.match(line)\n\t\t\t\t\tdbz << line.chomp\n\t\t\t\telsif /\\/.+\\.apk|\\/.+\\.app|\\/.+\\.bat|\\/.+\\.cgi|\\/.+\\.exe|\\/.+\\.gadget|\\/.+\\.jar|\\/.+\\.pif|\\/.+\\.vbs|\\/.+\\.wsf/i.match(line)\n\t\t\t\t\texecutablez << line.chomp\n\t\t\t\telsif /\\/.+\\.bak|\\/.+\\.tmp|\\/.+\\.bk/i.match(line)\n\t\t\t\t\tbkupz << line.chomp\n\t\t\t\telsif /\\/.+\\.conf/i.match(line)\n\t\t\t\t\tconfz << line.chomp\n\t\t\t\telsif /\\/.+\\.passwd|\\/.+\\.htpasswd/i.match(line)\n\t\t\t\t\tpazz << line.chomp\n\t\t\t\telse\n\t\t\t\t\tnoparamz << line\n\t\t\t\tend\n\t\t\tend #End begin/rescue block\n\t\tend\n\n\t\t#make sure we dont have duplicates\n\t\tno_params = no_params.uniq\n\t\ttest_keys = test_keys.uniq\n\t\ttestlink = testlink.uniq\n\t\tmulti = multi.uniq\n\t\tinjtestlinks=[]\n\n\t\tputs \"[\".light_green + \"*\".white + \"] Crawler Results\".light_green + \": \".white\n\t\t#Write found NO parameter links to their own file just like everything else, just these dont fall into any group\n\t\tcount=0\n\t\tif not noparamz.empty?\n\t\t\tzfile=\"NO_paramaters\"\n\t\t\tnoparamz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\") #Open our file handle in write mode\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\") #Open our file handle in append mode\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\" #write the hits to file \n\t\t\t\tlostANDfound.close #close our file handle we opened a minute ago\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{noparamz.length} Links in total with NO paramaters in them\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not paramz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"paramater\"\n\t\t\tparamz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links in total with paramaters in them\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not jsz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"JS\"\n\t\t\tjsz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for JS Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not pdfz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"PDF\"\n\t\t\tpdfz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for PDF Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not wordz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"MS_WORD\"\n\t\t\twordz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for MS Word Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not txtz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"TEXT\"\n\t\t\ttxtz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for TEXT Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not outlookz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"OUTLOOK-MSG\"\n\t\t\toutlookz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for OUTLOOK-MSG Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not opendocz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"OpenDoc\"\n\t\t\topendocz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for OpenDoc Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not spreadsheetz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"SpreadSheet\"\n\t\t\tspreadsheetz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for SpreadSheet Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not pptz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"PowerPoint\"\n\t\t\tpptz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for PowerPoint Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not archivez.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"ARCHIVE\"\n\t\t\tarchivez.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for ARCHIVE Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not vcardz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"vCard\"\n\t\t\tvcardz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for vCard Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not xmlz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"XML\"\n\t\t\txmlz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for XML Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not audioz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"AUDIO\"\n\t\t\taudioz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for AUDIO Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not videoz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"VIDEO\"\n\t\t\tvideoz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for VIDEO Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not flashz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"FLASH\"\n\t\t\tflashz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for FLASH Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not dbz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"DATABASE\"\n\t\t\tdbz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for DATABASE Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not executablez.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"EXECUTABLES\"\n\t\t\texecutablez.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for EXECUTABLES Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not bkupz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"BackUp\"\n\t\t\tbkupz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for BackUp Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not confz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"CONFIG\"\n\t\t\tconfz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for CONFIG Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not pazz.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"PASSWORDS\"\n\t\t\tpazz.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for PASSWORDS Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tif not imagez.empty?\n\t\t\tcount=0\n\t\t\tzfile=\"IMAGE\"\n\t\t\timagez.each do |line|\n\t\t\t\tif count.to_i < 1\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"w+\")\n\t\t\t\t\tcount = count.to_i + 1\n\t\t\t\telse\n\t\t\t\t\tlostANDfound = File.new(\"#{rezDir}#{zfile}.links\", \"a+\")\n\t\t\t\tend\n\t\t\t\tlostANDfound.puts \"#{line.chomp}\"\n\t\t\t\tlostANDfound.close\n\t\t\tend\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{paramz.length} Links for IMAGE Files\".light_green + \": #{rezDir}#{zfile}.links\".white\n\t\tend\n\t\tputs \"[\".light_green + \"*\".white + \"] Other Info\".light_green + \".....\".white\n\t\tif not test_keys.empty?\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{test_keys.length} Testable Parameters\".light_green + \": \".white\n\t\t\tputs \"[\".light_green + \"*\".white + \"] \".light_green + \"#{test_keys.join(', ').to_s}\".white\n\t\tend\n\t\tif not testlink.empty?\n\t\t\t#print single parameter links we will test\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{testlink.length} Unique Single Parameter Links (out of #{scount} total)\".light_green + \": \".white\n\t\t\ttestlink.each do |line|\n\t\t\t\tputs \"\\t#{line.chomp}\".white\n\t\t\t\tinjtestlinks << line\n\t\t\tend\n\t\tend\n\t\tif not multi.empty?\n\t\t\t#print multi parameter links we will test\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{multi.length} Unique Multi Parameter Links (out of #{mcount} total)\".light_green + \":\".white\n\t\t\tmulti.each do |line|\n\t\t\t\tputs \"\\t#{line.chomp}\".white\n\t\t\t\tinjtestlinks << line\n\t\t\tend\n\t\tend\n\t\tif not no_params.empty?\n\t\t\tif no_params.length < 9\n\t\t\t\tputs \"[\".light_green + \"*\".white + \"] Found the following NO Parameter links\".light_green + \": \".white\n\t\t\t\tnopam = no_params\n\t\t\telse\n\t\t\t\tputs \"[\".light_green + \"*\".white + \"] 10 random No Parameter Links (out of #{nocount} total)\".light_green + \": \".white\n\t\t\t\tnopam = no_params.sort_by{rand}[0..9]\n\t\t\tend\n\t\t\t#print no parameter links we will test\n\t\t\tnopam.each do |line|\n\t\t\t\tputs \"\\t#{line.chomp}\".white\n\t\t\t\tinjtestlinks << line\n\t\t\tend\n\t\tend\n\t\tif not injtestlinks.empty?\n\t\t\t#Write the suggested testable links to their own file for use with other tools\n\t\t\tf = File.new(\"#{rezDir}testable.links\", \"w+\")\n\t\t\tinjtestlinks.each do |link|\n\t\t\t\tf.puts link\n\t\t\tend\n\t\t\tf.close\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Suggested Testable Links\".light_green + \": #{rezDir}testable.links\".white\n\t\tend\n\t\t#Display the emails found now....\n\t\tif not @emails_array.empty?\n\t\t\t@emails_array.uniq!\n\t\t\tf=File.open(\"#{rezDir}temp.emails\", 'w+')\n\t\t\t@emails_array.each do |email|\n\t\t\t\tf.puts email\n\t\t\tend\n\t\t\tf.close\n\t\t\t#Because Ruby built-in uniq function doesn't seem to be fully doing the job we use some OS magic to make sure it is unique emails only....\n\t\t\tsystem(\"cat #{rezDir}temp.emails | sort -u > #{rezDir}emails.txt\")\n\t\t\tcount=`wc -l #{rezDir}emails.txt | cut -d' ' -f1`\n\t\t\tFileUtils.rm(\"#{rezDir}temp.emails\")\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Found #{count} emails while crawling\".light_green + \"....\".white\n\t\t\tputs \"[\".light_green + \"*\".white + \"] Find them here\".light_green + \": #{rezDir}emails.txt\".white\n\t\tend\n\tend", "def index_extracted_attributes( extract_conf, doc, value_to_index )\n regexp = Regexp.new( extract_conf[\"regexp\"] )\n matches = false\n \n if value_to_index.is_a?(Array)\n value_to_index.each do |value|\n matches = regexp.match( value )\n if matches then doc[ extract_conf[\"idx\"].to_sym ].push( matches[0] ) end\n end\n else\n matches = regexp.match( value_to_index )\n if matches then doc[ extract_conf[\"idx\"].to_sym ].push( matches[0] ) end\n end\n end", "def build_index\r\n raise \"cannot build index without an identifier provider\" unless @identifier_provider\r\n @index = elements.collect { |e|\r\n ident = @identifier_provider.call(e, nil)\r\n ident && !ident.empty? ? [ident, e] : nil \r\n }.compact\r\n end", "def each_child_with_index\n end", "def parse\n self.class.rules.each do |target, (selector, delegate, plural)|\n if plural\n @doc.search(selector).each do |node|\n send(target) << parse_result(node, delegate)\n end\n else\n send(\"#{target}=\", parse_result(@doc.at(selector), delegate))\n end\n end\n self\n end", "def build_indices\n @files, @classes = RDoc::Generator::Context.build_indices(@toplevels,\n @options)\n end", "def build_indices\n @files, @classes = RDoc::Generator::Context.build_indices(@toplevels,\n @options)\n end" ]
[ "0.60973424", "0.56917083", "0.54896015", "0.54325575", "0.5408188", "0.5391383", "0.51944095", "0.51584613", "0.51584613", "0.51584613", "0.51584613", "0.5144807", "0.5136883", "0.5091499", "0.5091499", "0.5091499", "0.5091499", "0.50706524", "0.5065484", "0.50407165", "0.5007512", "0.49974078", "0.4984137", "0.49722886", "0.496786", "0.49186075", "0.49169797", "0.4916787", "0.4891017", "0.4891017" ]
0.67908156
0
combo_changed event handlers for composite foreign key: carton_pack_type_id combo_changed event handlers for composite foreign key: basic_pack_id search combo_changed event handlers for the unique index on this table(carton_pack_products)
def carton_pack_product_type_code_search_combo_changed type_code = get_selected_combo_value(params) session[:carton_pack_product_search_form][:type_code_combo_selection] = type_code @basic_pack_codes = CartonPackProduct.find_by_sql("Select distinct basic_pack_code from carton_pack_products where type_code = '#{type_code}'").map{|g|[g.basic_pack_code]} @basic_pack_codes.unshift("<empty>") # render (inline) the html to replace the contents of the td that contains the dropdown render :inline => %{ <%= select('carton_pack_product','basic_pack_code',@basic_pack_codes)%> <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_carton_pack_product_basic_pack_code'/> <%= observe_field('carton_pack_product_basic_pack_code',:update => 'carton_pack_style_code_cell',:url => {:action => session[:carton_pack_product_search_form][:basic_pack_code_observer][:remote_method]},:loading => "show_element('img_carton_pack_product_basic_pack_code');",:complete => session[:carton_pack_product_search_form][:basic_pack_code_observer][:on_completed_js])%> } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fg_product_item_pack_product_code_search_combo_changed\n\titem_pack_product_code = get_selected_combo_value(params)\n\tsession[:fg_product_search_form][:item_pack_product_code_combo_selection] = item_pack_product_code\n\t@unit_pack_product_codes = FgProduct.find_by_sql(\"Select distinct unit_pack_product_code from fg_products where item_pack_product_code = '#{item_pack_product_code}'\").map{|g|[g.unit_pack_product_code]}\n\t@unit_pack_product_codes.unshift(\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('fg_product','unit_pack_product_code',@unit_pack_product_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_fg_product_unit_pack_product_code'/>\n\t\t<%= observe_field('fg_product_unit_pack_product_code',:update => 'carton_pack_product_code_cell',:url => {:action => session[:fg_product_search_form][:unit_pack_product_code_observer][:remote_method]},:loading => \"show_element('img_fg_product_unit_pack_product_code');\",:complete => session[:fg_product_search_form][:unit_pack_product_code_observer][:on_completed_js])%>\n\t\t}\n\nend", "def build_basic_pack_form(basic_pack,action,caption,is_edit = nil,is_create_retry = nil)\n#\t--------------------------------------------------------------------------------------------------\n#\tDefine a set of observers for each composite foreign key- in effect an observer per combo involved\n#\tin a composite foreign key\n#\t--------------------------------------------------------------------------------------------------\n\tsession[:basic_pack_form]= Hash.new\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n\t field_configs = Array.new\n\tfield_configs[0] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'basic_pack_code'}\n\n\tfield_configs[1] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'short_code'}\n\n\tfield_configs[2] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'length'}\n\n\tfield_configs[3] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'width'}\n\n\tfield_configs[4] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'height'}\n \n field_configs[5] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'weight'}\n\n\tbuild_form(basic_pack,field_configs,action,'basic_pack',caption,is_edit)\n\nend", "def product_product_subtype_code_search_combo_changed\n\tproduct_subtype_code = get_selected_combo_value(params)\n\tsession[:product_search_form][:product_subtype_code_combo_selection] = product_subtype_code\n\t@tag1s = Product.find_by_sql(\"Select distinct tag1 from products where product_subtype_code = '#{product_subtype_code}' and product_type_code = 'PACK_MATERIAL' and is_composite = 'true'\").map{|g|[g.tag1]}\n\[email protected](\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('product','tag1',@tag1s)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_product_tag1'/>\n\t\t<%= observe_field('product_tag1',:update => 'tag2_cell',:url => {:action => session[:product_search_form][:tag1_observer][:remote_method]},:loading => \"show_element('img_product_tag1');\",:complete => session[:product_search_form][:tag1_observer][:on_completed_js])%>\n\t\t}\n\nend", "def build_set_fg_product_form(pack_station,action,caption)\n\n field_configs = Array.new\n\n\t#generate javascript for the on_complete ajax event for each combo for fk table: pack_material_products\n\tcombos_js = gen_combos_clear_js_for_combos([\"pack_station_fg_product_code\",\"pack_station_carton_setup_code\"])\n\n\t#Observers for combos representing the key fields of fkey table: carton_setup_id\n\tfg_code_observer = {:updated_field_id => \"carton_setup_code_cell\",\n\t\t\t\t\t :remote_method => 'pack_station_fg_product_code_changed', #re-using existing handler\n\t\t\t\t\t :on_completed_js => combos_js[\"pack_station_fg_product_code\"]}\n\n\n on_complete_js = \"\\n img = document.getElementById('img_pack_station_carton_setup_code');\"\n\ton_complete_js += \"\\n if(img != null)img.style.display = 'none';\"\n\n\tsession[:pack_station_form] = Hash.new\n\tsession[:pack_station_form][:carton_setup_js]= on_complete_js\n\n\t#Observers for search combos\n\tcarton_setup_observer = {:updated_field_id => \"ajax_distributor_cell\",\n\t\t\t\t\t :remote_method => 'carton_setup_combo_changed',\n\t\t\t\t\t :on_completed_js => on_complete_js}\n\n\n #-----------------------------------------------------------------------\n #Find fg_codes from fg_setups that match following criteria:\n #-> stand_size_count,marketing_variety,grade_code,production_schedule\n #-----------------------------------------------------------------------\n\n fg_codes = FgSetup.fg_codes_for_station_link_context(pack_station,session[:current_production_run]).map{|f|f.fg_product_code}\n fg_codes.unshift \"<empty>\"\n # pack_station.fg_product_code = \"<empty>\" if !pack_station.fg_product_code\n #----------------------------------------------------------------------------------------\n #See if a carton link record has been created, if so set this record's fg to the link fg\n #----------------------------------------------------------------------------------------\n\n link = CartonLink.find_by_production_run_id_and_station_code(session[:current_production_run].id,pack_station.station_code)\n pack_station.fg_product_code = link.fg_product_code if link\n pack_station.carton_setup_code = link.carton_setup_code if link\n\n if link\n carton_setup = CartonSetup.find(link.carton_setup_id)\n pack_station.inventory_code = carton_setup.fg_setup.inventory_code\n pack_station.target_market = carton_setup.fg_setup.target_market\n pack_station.extended_fg_code = carton_setup.fg_setup.extended_fg_code\n pack_station.marking = carton_setup.fg_setup.marking\n pack_station.retailer_sell_by_code = carton_setup.fg_setup.retailer_sell_by_code\n pack_station.order_no = carton_setup.order_number\n pack_station.diameter = carton_setup.fg_setup.diameter\n pack_station.palletizing = carton_setup.pallet_setup.pallet_format_product_code.to_s + \": \" + carton_setup.pallet_setup.no_of_cartons.to_s\n #pack_station.nett_mass = carton_setup.fg_setup.nett_mass\n packing_order = carton_setup.sequence_number.to_s\n packing_order = carton_setup.pack_order if carton_setup.pack_order\n pack_station.packing_order = packing_order\n\n end\n\n carton_setups = nil\n if pack_station.fg_product_code != \"\"\n carton_setups = CartonSetup.find_all_by_production_schedule_code_and_fg_product_code(pack_station.production_schedule_name, pack_station.fg_product_code).map {|c|[c.carton_setup_code]}\n carton_setups.unshift(\"<empty>\")\n else\n carton_setups = [\"select a value from fg product code\"]\n end\n\n\n\tfield_configs[0] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'production_schedule_name'}\n\n\tfield_configs[1] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'production_run_number'}\n\n\n\tfield_configs[2] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'marketing_variety'}\n\n\tfield_configs[3] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'color_percentage'}\n\n\n field_configs[4] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'grade'}\n\n\tfield_configs[5] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'more_groups'}\n\n\tfield_configs[6] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'size_count'}\n\n field_configs[7] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'station_code',:settings => {:css_class => \"heading_field\"}}\n\n\tfield_configs[8] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'fg_product_code',\n\t\t\t\t\t\t:settings => {:list => fg_codes},\n\t\t\t\t\t\t:observer => fg_code_observer}\n\n\tfield_configs[9] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'carton_setup_code',\n\t\t\t\t\t\t:settings => {:list => carton_setups},\n\t\t\t\t\t\t:observer => carton_setup_observer}\n\n\t#-----------------------------------------\n\t#Additional fields-related to carton setup\n\t#------------------------------------------\n\tfield_configs[10] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'packing_order',:settings => {:css_class => \"derived_field_nb\"}}\n\n\t field_configs[11] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'extended_fg_code',:settings => {:css_class => \"derived_field\"}}\n\n\t field_configs[12] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'inventory_code',:settings => {:css_class => \"derived_field\"}}\n\n\t field_configs[13] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'target_market',:settings => {:css_class => \"derived_field\"}}\n\n\n\t field_configs[14] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'marking',:settings => {:css_class => \"derived_field\"}}\n\n\tfield_configs[15] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'diameter',:settings => {:css_class => \"derived_field\"}}\n\n\tfield_configs[15] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'diameter',:settings => {:css_class => \"derived_field\"}}\n\n\tfield_configs[16] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'retailer_sell_by_code',:settings => {:css_class => \"derived_field\",:label_caption => \"sell_by_code\"}}\n\n#\tfield_configs[16] = {:field_type => 'LabelField',\n#\t\t\t\t\t\t:field_name => 'nett_mass'}\n\n\tfield_configs[17] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'palletizing',:settings => {:css_class => \"derived_field\"}}\n\n field_configs[18] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'order_no',:settings => {:css_class => \"derived_field\"}}\n\n\tfield_configs[19] = {:field_type => 'HiddenField',\n\t\t\t\t\t\t:field_name => 'ajax_distributor',\n\t\t\t\t\t\t:non_db_field => true}\n\n\tbuild_form(pack_station,field_configs,action,'pack_station',caption)\n\nend", "def pack_material_product_pack_material_type_code_search_combo_changed\n\tpack_material_type_code = get_selected_combo_value(params)\n\tsession[:pack_material_product_search_form][:pack_material_type_code_combo_selection] = pack_material_type_code\n\t@pack_material_product_codes = PackMaterialProduct.find_by_sql(\"Select distinct pack_material_product_code from pack_material_products where pack_material_type_code = '#{pack_material_type_code}'\").map{|g|[g.pack_material_product_code]}\n\t@pack_material_product_codes.unshift(\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('pack_material_product','pack_material_product_code',@pack_material_product_codes)%>\n\n\t\t}\n\nend", "def item_pack_product_commodity_group_code_changed\n \n\tcommodity_group_code = get_selected_combo_value(params)\n\tsession[:item_pack_product_form][:commodity_group_code_combo_selection] = commodity_group_code\n\t@commodity_codes = ItemPackProduct.commodity_codes_for_commodity_group_code(commodity_group_code)\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('item_pack_product','commodity_code',@commodity_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_item_pack_product_commodity_code'/>\n\t\t<%= observe_field('item_pack_product_commodity_code',:update => 'basic_pack_code_cell',:url => {:action => 'item_pack_product_commodity_code_changed'},:loading => \"show_element('img_item_pack_product_commodity_code');\",:complete => session[:item_pack_product_form][:commodity_code_observer][:on_completed_js])%>\n\t\t}\n\nend", "def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:pack_material_product_code => self.pack_material_product_code},{:id => self.id}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_pack_material_product\n\t end\nend", "def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:carton_pack_product_code => self.carton_pack_product_code}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_carton_pack_product\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:pallet_format_product_code => self.pallet_format_product_code}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_pallet_format_product\n\t end\n\t \n\t if is_valid\n\t self.cpp_code = self.pallet_format_product_code + \"_\" + self.carton_pack_product_code + \"_\" + self.cartons_per_pallet.to_s \n\t end\nend", "def pack_material_product_commodity_group_code_changed\n\tcommodity_group_code = get_selected_combo_value(params)\n\tsession[:pack_material_product_form][:commodity_group_code_combo_selection] = commodity_group_code\n\t@commodity_codes = PackMaterialProduct.commodity_codes_for_commodity_group_code(commodity_group_code)\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('pack_material_product','commodity_code',@commodity_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_pack_material_product_commodity_code'/>\n\t\t<%puts observe_field('pack_material_product_commodity_code',:update => 'marketing_variety_code_cell',:url => {:action => session[:pack_material_product_form][:commodity_code_observer][:remote_method]},:loading => \"show_element('img_pack_material_product_commodity_code');\",:complete => session[:pack_material_product_form][:commodity_code_observer][:on_completed_js])%>\n\t\t<%= observe_field('pack_material_product_commodity_code',:update => 'marketing_variety_code_cell',:url => {:action => session[:pack_material_product_form][:commodity_code_observer][:remote_method]},:loading => \"show_element('img_pack_material_product_commodity_code');\",:complete => session[:pack_material_product_form][:commodity_code_observer][:on_completed_js])%>\n\t\t}\n\nend", "def pack_station_fg_product_code_changed\n fg_code = get_selected_combo_value(params)\n @carton_setup_codes = CartonSetup.find_all_by_production_schedule_id_and_fg_product_code_and_active(session[:current_closed_schedule].id, fg_code, true).map { |c| [c.carton_setup_code] }\n @carton_setup_codes.unshift(\"<empty>\")\n#\trender (inline) the html to replace the contents of the td that contains the dropdown\n render :inline => %{\n\t\t<%= select('pack_station','carton_setup_code',@carton_setup_codes)%>\n <%= observe_field('pack_station_carton_setup_code',:update => 'ajax_distributor_cell',:url => {:action => 'carton_setup_combo_changed'},:loading => \"show_element('img_pack_station_carton_setup_code');\",:complete => session[:pack_station_form][:carton_setup_js])%>\n\n\t<script>\n\t\t <%= update_element_function(\n \"packing_order_cell\", :action => :update,\n :content => \"\") %>\n\n <%= update_element_function(\n \"extended_fg_code_cell\", :action => :update,\n :content => \"\") %>\n\n <%= update_element_function(\n \"inventory_code_cell\", :action => :update,\n :content => \"\") %>\n\n <%= update_element_function(\n \"target_market_cell\", :action => :update,\n :content => \"\")%>\n\n <%= update_element_function(\n \"marking_cell\", :action => :update,\n :content => \"\")%>\n\n <%= update_element_function(\n \"diameter_cell\", :action => :update,\n :content => \"\")%>\n\n <%= update_element_function(\n \"order_no_cell\", :action => :update,\n :content => \"\")%>\n\n <%= update_element_function(\n \"retailer_sell_by_code_cell\", :action => :update,\n :content => \"\")%>\n\n <%= update_element_function(\n \"palletizing_cell\", :action => :update,\n :content => \"\")%>\n\n </script>\n\n\t\t}\n end", "def item_pack_product_commodity_code_search_combo_changed\n\tcommodity_code = get_selected_combo_value(params)\n\tsession[:item_pack_product_search_form][:commodity_code_combo_selection] = commodity_code\n\t@marketing_variety_codes = ItemPackProduct.find_by_sql(\"Select distinct marketing_variety_code from item_pack_products where commodity_code = '#{commodity_code}'\").map{|g|[g.marketing_variety_code]}\n\t@marketing_variety_codes.unshift(\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('item_pack_product','marketing_variety_code',@marketing_variety_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_item_pack_product_marketing_variety_code'/>\n\t\t<%= observe_field('item_pack_product_marketing_variety_code',:update => 'actual_count_cell',:url => {:action => session[:item_pack_product_search_form][:marketing_variety_code_observer][:remote_method]},:loading => \"show_element('img_item_pack_product_marketing_variety_code');\",:complete => session[:item_pack_product_search_form][:marketing_variety_code_observer][:on_completed_js])%>\n\t\t}\n\nend", "def pallet_commodity_code_combo_changed()\n commodity_code = get_selected_combo_value(params)\n session[:filter_by_fruitspec_form][:commodity_code_selection] = commodity_code\n @marketing_variety_codes = Pallet.find_by_sql(\"SELECT DISTINCT marketing_variety_code FROM marketing_varieties WHERE commodity_code ='#{commodity_code}'\").map{|g|[g.marketing_variety_code]}\n @marketing_variety_codes.unshift(\"<empty>\")\n render :inline=>%{\n <%=select('pallet','marketing_variety_code',@marketing_variety_codes) %>\n }\n end", "def production_run_pack_material_fg_product_code_changed\n fg_code = get_selected_combo_value(params)\n @carton_setup_codes = CartonSetup.find_all_by_production_schedule_id_and_fg_product_code(session[:current_closed_schedule].id, fg_code).map { |c| [c.carton_setup_code, c.id] }\n#\trender (inline) the html to replace the contents of the td that contains the dropdown\n render :inline => %{\n\t\t<%= select('production_run_pack_material','carton_setup_code',@carton_setup_codes)%>\n\n\t\t}\n end", "def agregar_stock\n if combo.nil?\n producto.agregar_stock cantidad\n producto.save!\n else\n combo.agregar_stock cantidad\n combo.save\n end\n end", "def run_palletizing_criteria_setup_fg_product_code_changed\n fg_code = get_selected_combo_value(params)\n session[:run_palletizing_criteria_setup][:fg_code] = fg_code\n puts \"fg from fg combo: \" + fg_code.to_s\n\n @carton_setup_codes = CartonSetup.find_all_by_production_schedule_id_and_fg_product_code(session[:current_closed_schedule].id, fg_code).map { |c| [c.carton_setup_code] }\n @carton_setup_codes.unshift(\"<empty>\")\n#\trender (inline) the html to replace the contents of the td that contains the dropdown\n render :inline => %{\n\t\t<%= select('run_palletizing_criteria_setup','carton_setup_code',@carton_setup_codes)%>\n <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_run_palletizing_criteria_setup_carton_setup_code'/>\n\t\t<%= observe_field('run_palletizing_criteria_setup_carton_setup_code',:update => 'applet_container',:url => {:action => session[:run_palletizing_criteria_setup][:carton_setup_observer][:remote_method]},:loading => \"show_element('img_run_palletizing_criteria_setup_carton_setup_code');\")%>\n\t\t<script>\n\t\t<%= update_element_function(\n \"target_market_code_cell\", :action => :update,\n :content => \"\") %>\n\n <%= update_element_function(\n \"inventory_code_cell\", :action => :update,\n :content => \"\") %>\n\n\n <%= update_element_function(\n \"mark_code_cell\", :action => :update,\n :content => \"\") %>\n\n\n <%= update_element_function(\n \"sell_by_code_cell\", :action => :update,\n :content => \"\") %>\n\n <%= update_element_function(\n \"farm_code_cell\", :action => :update,\n :content => \"\") %>\n\n <%= update_element_function(\n \"units_per_carton_cell\", :action => :update,\n :content => \"\") %>\n </script>\n\t\t}\n\n\n end", "def build_season_order_quantity_form(season_order_quantity,action,caption,is_edit = nil,is_create_retry = nil,is_view = nil)#-----Luks\n#\t--------------------------------------------------------------------------------------------------\n#\tDefine a set of observers for each composite foreign key- in effect an observer per combo involved\n#\tin a composite foreign key\n#\t--------------------------------------------------------------------------------------------------\n\tsession[:season_order_quantity_form]= Hash.new\n\t\n\tseason_codes = Season.find_by_sql(\"select * from seasons\").map{|g|[g.season_code]}\n\tseason_codes.unshift(\"<empty>\")\n\t\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n\tfield_configs = Array.new\n if is_view\n\t field_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'season_code'}\n\t\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'customer_order_number'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'quantity_required'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'quantity_produced'}\nelse\n field_configs[field_configs.length] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'season_code',\n\t\t\t\t\t\t:settings => {:list => season_codes}}\n\t\n\tfield_configs[field_configs.length] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'customer_order_number'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'quantity_required'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'quantity_produced',\n\t\t\t\t\t\t:settings => {:static_value => 0,\n :show_label => true}}\n\nend\n\tbuild_form(season_order_quantity,field_configs,action,'season_order_quantity',caption,is_edit)\n\nend", "def set_unit_pack_product_type\n\n\tunit_pack_product_type = UnitPackProductType.find_by_type_code(self.type_code)\n\t if unit_pack_product_type != nil \n\t\t self.unit_pack_product_type = unit_pack_product_type\n\t\t return true\n\t else\n\t\terrors.add_to_base(\"combination of: 'type_code' is invalid- it must be unique\")\n\t\t return false\n\tend\nend", "def cb_charged\n if combo_main.active==0 then\n cb_newPark\n else\n #Vidage des frames\n framePan.each{|child| framePan.remove(child)}\n framePar.each{|child| framePar.remove(child)}\n\n #Recuperation des vues panneau et parking utile\n nomPark =self.combo_main.active_text\n builder.get_object(\"label_nomPark1\").text=nomPark\n vues=self.ctrl.get_park_views nomPark #Recup des \n\n #Ajout des vues\n framePar.add_child(builder,vues[0],nil)\n framePan.add_child(builder,vues[1],nil)\n\n #Mise a jour des info du parking affichés\n _change_park_property(self.ctrl.get_park_info nomPark)\n end\n #Show all\n @window.show_all\n end", "def supplier_product_description\n @product_combobox = ProductCombobox.db_active_both_operation\n arr_desc = ProductCombobox.put_description(@product_combobox)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: arr_desc }\n end\n end", "def variety_commodity_group_code_search_combo_changed\n\tcommodity_group_code = get_selected_combo_value(params)\n\tsession[:variety_search_form][:commodity_group_code_combo_selection] = commodity_group_code\n\t@commodity_codes = Variety.find_by_sql(\"Select distinct commodity_code from varieties where commodity_group_code = '#{commodity_group_code}'\").map{|g|[g.commodity_code]}\n\t@commodity_codes.unshift(\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('variety','commodity_code',@commodity_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_variety_commodity_code'/>\n\t\t<%= observe_field('variety_commodity_code',:update => 'rmt_variety_code_cell',:url => {:action => session[:variety_search_form][:commodity_code_observer][:remote_method]},:loading => \"show_element('img_variety_commodity_code');\",:complete => session[:variety_search_form][:commodity_code_observer][:on_completed_js])%>\n\t\t}\n\nend", "def build_cold_store_type_form(cold_store_type,action,caption,is_edit = nil,is_create_retry = nil)\n#\t--------------------------------------------------------------------------------------------------\n#\tDefine a set of observers for each composite foreign key- in effect an observer per combo involved\n#\tin a composite foreign key\n#\t--------------------------------------------------------------------------------------------------\n\tsession[:cold_store_type_form]= Hash.new\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n\t field_configs = Array.new\n\tfield_configs[0] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'cold_store_type_code'}\n\n\tfield_configs[1] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'cold_store_name'}\n\n\tbuild_form(cold_store_type,field_configs,action,'cold_store_type',caption,is_edit)\n\nend", "def orchard_id_changed\n orchard_id = get_selected_combo_value(params)\n session[:delivery_form][:orchard_id_combo_selection] = orchard_id\n @orchard_description = \"\"\n\n orchard = Orchard.find(orchard_id)\n if (orchard != nil)\n orchard_description = orchard.orchard_description\n @orchard_description = orchard_description\n session[:delivery_form][:orchard_description] = orchard_description\n else\n @orchard_description = \"\"\n end\n\n @rmt_product_codes = [\"select a value from rmt_product_type_code above\"]\n\n render :inline => %{\n <%= @orchard_description_content = @orchard_description %>\n <%= @rmt_product_codes_content = select('delivery','rmt_product_id',@rmt_product_codes,{:sorted=>true})%>\n <script>\n <%= update_element_function(\"orchard_description_cell\", :action => :update,:content => @orchard_description_content) %>\n <%= update_element_function(\"advised_rmt_product_code_cell\", :action => :update,:content => @rmt_product_codes_content) %>\n </script>\n }\n\n end", "def pu_track_family_has_changed\n family = params[:order]\n if family != '0'\n @family = ProductFamily.find(family)\n @products = @family.blank? ? products_dropdown : @family.products.order(:product_code)\n else\n @products = products_dropdown\n end\n # Products array\n @products_dropdown = products_array(@products)\n @json_data = { \"product\" => @products_dropdown }\n render json: @json_data\n end", "def build_standard_size_count_form(standard_size_count,action,caption,is_edit = nil,is_create_retry = nil)\n#\t--------------------------------------------------------------------------------------------------\n#\tDefine a set of observers for each composite foreign key- in effect an observer per combo involved\n#\tin a composite foreign key\n#\t--------------------------------------------------------------------------------------------------\n\tsession[:standard_size_count_form]= Hash.new\n\tstandard_count_values = StandardCount.find_by_sql('select distinct standard_count_value from standard_counts').map{|g|[g.standard_count_value]}\n\tstandard_count_values.unshift(\"<empty>\")\n\tcommodity_codes = Commodity.find_by_sql('select distinct commodity_code from commodities').map{|g|[g.commodity_code]}\n\tcommodity_codes.unshift(\"<empty>\")\n\tbasic_pack_codes = BasicPack.find_by_sql('select distinct basic_pack_code from basic_packs').map{|g|[g.basic_pack_code]}\n\tbasic_pack_codes.unshift(\"<empty>\")\n\told_pack_codes = OldPack.find_by_sql('select distinct old_pack_code from old_packs').map{|g|[g.old_pack_code]}\n\told_pack_codes.unshift(\"<empty>\")\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n\t field_configs = Array.new\n\tfield_configs[0] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'standard_size_count_description'}\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (commodity_id) on related table: commodities\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[1] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'commodity_code',\n\t\t\t\t\t\t:settings => {:list => commodity_codes}}\n \n\tfield_configs[2] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'diameter_mm'}\n\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (old_pack_id) on related table: old_packs\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[3] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'old_pack_code',\n\t\t\t\t\t\t:settings => {:list => old_pack_codes}}\n \n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (standard_count_id) on related table: standard_counts\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[4] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'standard_size_count_value',\n\t\t\t\t\t\t:settings => {:list => standard_count_values}}\n \n\n\tfield_configs[5] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'actual_count'}\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (basic_pack_id) on related table: basic_packs\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[6] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'basic_pack_code',\n\t\t\t\t\t\t:settings => {:list => basic_pack_codes}}\n\t#NAE 2015-04-17 add new field average_weight_gm\n\tfield_configs[7] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'average_weight_gm'}\n \n\tbuild_form(standard_size_count,field_configs,action,'standard_size_count',caption,is_edit)\n\nend", "def combo_params\n params.require(:combo).permit(:name, :description, :products, :price, :picture, :hidden)\n end", "def set_product_pack\n @product_pack = ProductPack.find(params[:id])\n end", "def build_palletizing_criterium_form(run_palletizing_criterium,action = nil,caption = nil,is_edit = nil,is_create_retry = nil,is_view = nil)\n\n\n #------------------------------------------------------------------------------------\n #Build a fg code observer to filter the list of available carton setups by selected\n #fg code\n #------------------------------------------------------------------------------------\n\t#generate javascript for the on_complete ajax event for each combo for fk table: pack_material_products\n\tcombos_js = gen_combos_clear_js_for_combos([\"run_palletizing_criteria_setup_fg_product_code\",\"run_palletizing_criteria_setup_carton_setup_code\"])\n\n\t#Observers for combos representing the key fields of fkey table: carton_setup_id\n\tfg_code_observer = {:updated_field_id => \"carton_setup_code_cell\",\n\t\t\t\t\t :remote_method => 'run_palletizing_criteria_setup_fg_product_code_changed',\n\t\t\t\t\t :on_completed_js => combos_js[\"run_palletizing_criteria_setup_fg_product_code\"]}\n\n\tcarton_setups = [\"select a value from fg product code\"]\n\n\tfg_product_codes = FgProduct.fg_codes_for_schedule(session[:current_closed_schedule].production_schedule_name)\n fg_product_codes.unshift \"<empty>\"\n\n\n if run_palletizing_criterium\n\n carton_setups = CartonSetup.find_all_by_production_schedule_id_and_fg_product_code(session[:current_closed_schedule].id,run_palletizing_criterium.fg_product_code).map {|c|[c.carton_setup_code]}\n # carton_setups.unshift(\"<empty>\")\n end\n\n carton_setup_code_observer = {:updated_field_id => \"applet_container\",\n\t\t\t\t\t :remote_method => 'run_palletizing_criteria_setup_carton_setup_code_changed'}\n\n\t#:on_completed_js => combos_js[\"run_palletizing_criteria_setup_carton_setup_code\"]\n\n\tsession[:run_palletizing_criteria_setup] = Hash.new if !session[:run_palletizing_criteria_setup]\n\tsession[:run_palletizing_criteria_setup][:carton_setup_observer]= carton_setup_code_observer\n\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n\tfield_configs = Array.new\n\n field_configs[0] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'fg_product_code',\n\t\t\t\t\t\t:settings => {:list => fg_product_codes},\n\t\t\t\t\t\t:observer => fg_code_observer}\n\n\t field_configs[1] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'carton_setup_code',\n\t\t\t\t\t\t:settings => {:list => carton_setups},\n\t\t\t\t\t\t:observer => carton_setup_code_observer}\n\n\tfield_configs[2] = {:field_type => 'CheckBox',\n\t\t\t\t\t\t:field_name => 'target_market_code'}\n\n\tfield_configs[3] = {:field_type => 'CheckBox',\n\t\t\t\t\t\t:field_name => 'inventory_code'}\n\n\tfield_configs[4] = {:field_type => 'CheckBox',\n\t\t\t\t\t\t:field_name => 'mark_code'}\n\n\tfield_configs[5] = {:field_type => 'CheckBox',\n\t\t\t\t\t\t:field_name => 'sell_by_code'}\n\n\tfield_configs[6] = {:field_type => 'CheckBox',\n\t\t\t\t\t\t:field_name => 'farm_code'}\n\n\tfield_configs[7] = {:field_type => 'CheckBox',\n\t\t\t\t\t\t:field_name => 'units_per_carton'}\n\n\tbuild_form(run_palletizing_criterium,field_configs,action,'run_palletizing_criteria_setup',caption,is_edit)\n\nend", "def create\n @product_combobox = ProductCombobox.new(params[:product_combobox])\n\n respond_to do |format|\n if @product_combobox.save\n format.html { redirect_to @product_combobox, notice: 'Product combobox was successfully created.' }\n format.json { render json: @product_combobox, status: :created, location: @product_combobox }\n else\n format.html { render action: \"new\" }\n format.json { render json: @product_combobox.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @product_combobox = ProductCombobox.find(params[:id])\n\n respond_to do |format|\n if @product_combobox.update_attributes(params[:product_combobox])\n format.html { redirect_to @product_combobox, notice: 'Product combobox was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @product_combobox.errors, status: :unprocessable_entity }\n end\n end\n end", "def delivery_farm_code_search_combo_changed\n farm_code = get_selected_combo_value(params)\n session[:delivery_search_form][:farm_code_combo_selection] = farm_code\n @puc_codes = Delivery.find_by_sql(\"select distinct puc_code from deliveries where farm_code = '#{farm_code}'\").map { |g| [g.puc_code] }\n @puc_codes.unshift(\"<empty>\")\n #render inline to replace the values of puc code dropdown\n render :inline => %{\n <%= select('delivery','puc_code', @puc_codes) %>\n <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_delivery_puc_code'/>\n <%= observe_field('delivery_puc_code', :update=>'commodity_code_cell', :url => {:action=>session[:delivery_search_form][:puc_code_observer][:remote_method]}, :loading=>\"show_element('img_delivery_puc_code');\", :complete=>session[:delivery_search_form][:puc_code_observer][:on_completed_js])%>\n }\n end" ]
[ "0.62615204", "0.61642337", "0.6071932", "0.6042467", "0.60266316", "0.60185677", "0.59009135", "0.58595985", "0.57825226", "0.5760937", "0.56612283", "0.56465", "0.55218667", "0.5261049", "0.5147732", "0.5133886", "0.5129493", "0.51280886", "0.51261866", "0.51144844", "0.50934494", "0.5086571", "0.5076479", "0.50688386", "0.5035728", "0.50165415", "0.4999315", "0.49932548", "0.49919686", "0.49834448" ]
0.6645778
0
Render multiple boxes. Takes as argument a single array of Hash For the Hash options, please see render_box. The boxes are wrapped in a div with class "textboxes". You can pass individual styling using :textboxes_style => textboxes_style. You can specify a template Hash ( :template => template ) which will be merged with each indivdual's box's options Hash. This way, you can create a list of boxes that look the same but some have their own characteristics. Also adds a div with style "clear: both" after the output so other objects won't start floating. If you don't want that, add :noclear => true as an option.
def render_boxes(array = [], options = {}) boxes = "" template = {} if options[:template].class.to_s.eql?("Hash") template = options[:template] end array.each do |individual_options| box_options = template box_options = template.merge(individual_options) unless individual_options.nil? r = render_box(box_options) unless individual_options[:link].blank? r = "<a href='#{individual_options[:link]}' target='#{individual_options[:link_target]}' class='no_underline render_boxes'>#{r}</a>" end boxes += r unless r.blank? end boxes_div = content_tag :div, boxes, :class => "textboxes", :style => options[:textboxes_style] clear_both_ = "" unless options[:noclear] === true clear_both_ = clear_both end boxes_div + clear_both_ end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def render_box(options = {})\n # list of classes for the outer div.\n outer_div_classes = [ \"textbox_container\" ]\n # inner div, same story\n inner_div_classes = [ \"textbox\" ]\n # heading\n heading_classes = [ \"heading\" ]\n\n content = yield if block_given?\n content ||= options[:content]\n \n return nil if content.blank? && options[:heading].blank? unless options[:empty]\n\n # Options:\n # float_left\n outer_div_classes.push(\"float_left\") if options[:float_left] === true\n # text_align_center\n inner_div_classes.push(\"text_align_center\") if options[:text_align_center] === true\n # highlight\n inner_div_classes.push(\"highlight\") if options[:highlight] === true\n # background_image\n background_image = options[:background_image]\n # header color\n heading_color = options[:heading_color]\n inner_div_classes.push(\"textbox_#{heading_color}\") unless heading_color.blank?\n # background color\n background_color = options[:background_color]\n\n ############################################################################\n # inner div\n ############################################################################\n\n inner_div_classes.push(\"#{background_color}_background\") unless background_color.blank?\n\n inner_div_options = { :class => c(inner_div_classes) }\n inner_div_styles = []\n unless background_image.blank?\n # opacity:0.4;filter:alpha(opacity=40);\n inner_div_styles.push \"background: url(#{background_image}) no-repeat center;\"\n end\n\n unless options[:height].blank?\n inner_div_styles.push \"height: #{options[:height]}\"\n end\n\n unless options[:width].blank?\n inner_div_styles.push \"width: #{options[:width]}\"\n end\n\n unless inner_div_styles.blank?\n inner_div_options[:style] = c(inner_div_styles)\n\n end\n inner_div_options[:style] ||= options[:inner_div_style] # can be overridden\n\n ############################################################################\n # outer div\n ############################################################################\n\n outer_div_options = { :class => c(outer_div_classes) }\n outer_div_options[:style] = options[:outer_div_style]\n\n ############################################################################\n # text div\n ############################################################################\n\n text_div_options = {}\n text_div_classes = []\n\n text_div_classes.push \"bigfont\" if options[:bigfont] === true\n text_div_classes.push \"solid_background\" if options[:solid_background] === true\n\n text_div_options[:class] = c(text_div_classes)\n\n ############################################################################\n # go render\n ############################################################################\n\n # let's go, outer div\n content_tag :div, outer_div_options do\n content_tag :div, inner_div_options do\n # heading\n heading = \"\"\n heading = content_tag :p, options[:heading], :class => c(heading_classes), :style => options[:heading_style] unless options[:heading].blank?\n # text div\n content_tag_ = content_tag :div, text_div_options do\n content_tag :p, content, :class => \"inner_p\"\n end\n # do it!\n heading + content_tag_\n end\n end\n end", "def box_it(array_of_lines, padding = 1, _box_colour = :bc_cyan)\n max_length = max_box_line_length(array_of_lines)\n pad_string = \"\\s\" * padding\n\n box_lines = [\n # Set the top box line\n \"#{BOX_TOP_LEFT}#{BOX_HORIZONTAL_LINE * (max_length + (padding + 1))}#{BOX_TOP_RIGHT}\"\n ]\n\n array_of_lines.each do |line|\n line_length = line.sanitize.length\n box_lines << \"#{BOX_SIDE}#{pad_string}\" + line.to_s + \"#{\"\\s\" * (max_length - line_length)}#{pad_string}#{BOX_SIDE}\"\n end\n\n # Set the bottom box line\n box_lines << \"#{BOX_BOTTOM_LEFT}#{BOX_HORIZONTAL_LINE * (max_length + (padding + 1))}#{BOX_BOTTOM_RIGHT}\"\n box_lines\n end", "def compile_all_boxes\n boxes={}\n row=0\n col=0\n i=1\n while row<8\n while col<8\n boxes[\"box_#{i}\"] = compile_box(row, col)\n i+=1\n col+=3\n end\n col=0\n # i+=1\n row+=3\n end\n boxes\n end", "def render_iform\n @multi_objs.each do |obj|\n render :partial => 'iform', :object => obj\n end\n end", "def create_pokemon_text_boxes\n @pkm_text_boxes = []\n $actors.each do |pkm|\n @pkm_text_boxes << Pokemon_Text_Box.new(@viewport, pkm)\n end\n end", "def box msgs, box_char=@box_char, box_size=@box_size\n self.liner box_char, box_size\n [msgs].flatten.each do |text|\n text.each_line do |line|\n self.<< '# ' + box_char + ' ' + line.chomp + \"\\n\"\n end\n end\n self.liner box_char, box_size\n end", "def add_boxes( name, number, properties = {} )\n number > 1 or raise \"Number of #{name} boxes #{number} is not positive\"\n ( 1 .. number ).each{ |j| VB_BOXES[ \"#{ name }#{ j }\" ] = properties }\nend", "def box(name, options={}, &block)\n options.merge!(:body=>capture(&block))\n concat(render(:partial => \"shared/ubiquo/boxes/#{name}\", :locals => options), block.binding)\n end", "def render_combos\n # build the cache of all combos\n (1..@box_size).each { |size| cache_all_boxes_sized(size) }\n\n puts \"\\nThere are #{@box_combinations[@box_size].size} combinations:\\n\\n\"\n\n # print the combos\n @box_combinations[@box_size].values.each_with_index do |box,index|\n box.render_cookies\n puts \"\"\n end\n end", "def prettybox(html_options, &proc)\n raise ArgumentError, \"Missing block\" unless block_given?\n concat(tag(\"div\", html_options, true), proc.binding)\n concat(\"<div class=\\\"prettybox_top\\\">\n <div>&nbsp;</div>\n </div><div class=\\\"prettybox_inside\\\">\", proc.binding)\n yield\n concat(\"</div><div class=\\\"prettybox_bot\\\">\n <div>&nbsp;</div>\n </div>\n </div>\", proc.binding)\n end", "def print_employee_data_box(box_x, box_y)\n\n # Draw box.\n x = box_x\n y = box_y - 0.375\n self.vms_text_box(@data[:employee][:ssn], x, y, 1.25, 0.25, 7, :bold, :center, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:wages][:gross]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:taxes][:federal]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(curr(@data[:wages][:social_security]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:taxes][:social_security]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.125\n self.vms_text_box(@data[:employer][:ein], x, y, 1.25, 0.25, 7, :bold, :center, :center, @data_font, @data_color)\n y -= 0.125\n self.vms_text_box(curr(@data[:wages][:medicare]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:taxes][:medicare]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"#{@data[:employer][:name]}\\n#{@data[:employer][:street]}\\n#{@data[:employer][:city]}, #{@data[:employer][:state]} #{@data[:employer][:zip]}\", x + 0.05, y, 3.65, 0.625, 7, :bold, :left, :center, @data_font, @data_color)\n y -= 1\n self.vms_text_box(\"#{@data[:employee][:name]}\\n#{@data[:employee][:street]}\\n#{@data[:employee][:city]}, #{@data[:employee][:state]} #{@data[:employee][:zip]}\", x + 0.05, y, 3.65, 0.625, 7, :bold, :left, :center, @data_font, @data_color)\n y -= 1\n self.vms_text_box(@data[:box_12][:a][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:a][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"X\", x + 0.05, y, 0.9, 0.125, 7, :bold, :center, :center, @data_font, @data_color) if @data[:box_13][:statutory]\n self.vms_text_box(@data[:box_12][:b][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:b][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"X\", x + 0.05, y, 0.9, 0.125, 7, :bold, :center, :center, @data_font, @data_color) if @data[:box_13][:retirement]\n self.vms_text_box(@data[:box_12][:c][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:c][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"X\", x + 0.05, y, 0.9, 0.125, 7, :bold, :center, :center, @data_font, @data_color) if @data[:box_13][:third_party_sick]\n self.vms_text_box(@data[:box_12][:d][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:d][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.125\n unless @data[:state][0].blank?\n self.vms_text_box(@data[:state][0][:code], x, y, 0.3, 0.125, 7, :bold, :center, :center, @data_font, @data_color)\n self.vms_text_box(@data[:state][0][:ein], x + 0.35, y, 1, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][0][:wages]), x + 1.45, y, 1.1, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][0][:tax]), x + 2.65, y, 1.05, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n end\n y -= 0.125\n unless @data[:state][1].blank?\n self.vms_text_box(@data[:state][1][:code], x, y, 0.3, 0.125, 7, :bold, :center, :center, @data_font, @data_color)\n self.vms_text_box(@data[:state][1][:ein], x + 0.35, y, 1, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][1][:wages]), x + 1.45, y, 1.1, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][1][:tax]), x + 2.65, y, 1.05, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n end\n y -= 0.375\n unless @data[:local][0].blank?\n self.vms_text_box(curr(@data[:local][0][:wages]), x + 0.05, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:local][0][:tax]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(@data[:local][0][:name], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n end\n y -= 0.125\n unless @data[:local][1].blank?\n self.vms_text_box(curr(@data[:local][1][:wages]), x + 0.05, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:local][1][:tax]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(@data[:local][1][:name], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n end\n\n end", "def create_congratulation_text_boxes\n @congrats_text_boxes = []\n $actors.each do |pkm|\n @congrats_text_boxes << Congratulation_Text_Box.new(@viewport, pkm)\n end\n end", "def create_boxes(num)\n box_vertices = polygon_vertices(NUM_SIDES, EDGE_SIZE)\n box_image = polygon_image(box_vertices)\n boxes = []\n num.times do\n body = CP::Body.new(1, CP::moment_for_poly(1.0, box_vertices, CP::Vec2.new(0, 0))) # mass, moment of inertia\n body.p = CP::Vec2.new(rand(SCREEN_WIDTH), rand(40) - 50)\n shape = CP::Shape::Poly.new(body, box_vertices, CP::Vec2.new(0, 0))\n shape.e = 0.0\n shape.u = 0.4\n boxes << AObject.new(box_image, body)\n @space.add_body(body)\n @space.add_shape(shape) \n end\n return boxes\n end", "def render_batch(languages,argsx={},callback_options={})\n clear\n result={}\n \n frame_binding= create_binding(argsx,callback_options)\n languages.each do |language|\n template=prep_template(language,frame_binding)\n apply_view_setup(frame_binding)\n result[language]= render_impl(template,language,frame_binding)\n end\n result\n end", "def generate_square_boxes(row, drawings)\n content_tag :div, :class => \"drawing_section\" do\n 1.upto(row){|item| concat(generate_row(item, row,drawings))}\n end\n end", "def create_boxes(num)\n box_vertices = polygon_vertices(NUM_SIDES, EDGE_SIZE)\n box_image = polygon_image(box_vertices)\n boxes = []\n num.times do\n body = CP::Body.new(1, CP::moment_for_poly(1.0, box_vertices, CP::Vec2.new(0, 0))) # mass, moment of inertia\n body.p = CP::Vec2.new(rand(WIDTH), rand(40) - 50)\n shape = CP::Shape::Poly.new(body, box_vertices, CP::Vec2.new(0, 0))\n shape.e = 0.0\n shape.u = 0.4\n boxes << Box.new(box_image, body)\n @space.add_body(body)\n @space.add_shape(shape) \n end\n return boxes\n end", "def check_for_boxes\n @boxes = []\n box_parser_hook = 'rpick_box_parser_hook'\n\n box_parser = Proc.new do |server_string|\n if server_string =~ /\\d+ items displayed/\n DownstreamHook.remove(box_parser_hook)\n elsif server_string =~ Dictionary.box_finder_regex\n box_id = $1\n box_noun = $2\n box_name = $3\n @boxes << { id: box_id, noun: box_noun, name: box_name }\n nil\n else\n nil\n end\n end\n\n DownstreamHook.add(box_parser_hook, box_parser)\n fput \"inv full\"\n end", "def prettybox_bottomonly(html_options, &proc)\n raise ArgumentError, \"Missing block\" unless block_given?\n concat(tag(\"div\", html_options, true), proc.binding)\n concat(\"<div class=\\\"prettybox_inside\\\">\", proc.binding)\n yield\n concat(\"</div><div class=\\\"prettybox_bot\\\">\n <div>&nbsp;</div>\n </div>\n </div>\", proc.binding)\n end", "def boxes\n @pz.group_by.each_with_index { |val, n| box_id(n) }\n end", "def build_box\n box = eval(type.sub('Template', '')).new\n box.box_template = self\n box.class.accessible_attributes.each do |attr|\n box.assign_attributes({attr => self.send(attr)}) unless ['type', ''].include? attr\n end\n box\n end", "def multiple_parameter_set_box\n view = Box.create_vertical_box\n top_row = Box.create_horizontal_box\n top_row.add(collapse_button)\n top_row.add(parameter_set_selection_combo)\n view.add(top_row)\n bottom_row = multi_buttons\n view.add(bottom_row)\n view.add(JSeparator.new)\n view.add(JSeparator.new)\n view\n end", "def box config={}, &block\n require 'canis/core/widgets/box'\n # take current stacks row and col\n # advance row by one and col by one\n # at end note row and advance by one\n # draw a box around using these coordinates. width should be\n # provided unless we have item width or something.\n @_ws_active ||= []\n last = @_ws_active.last\n if last\n r = last[:row]\n c = last[:col]\n config[:row] = r\n config[:col] = c\n last[:row] += config[:margin_top] || 1\n last[:col] += config[:margin_left] || 1\n _box = Box.new @form, config # needs to be created first or will overwrite area after others painted\n yield_or_eval &block if block_given?\n # FIXME last[height] needs to account for row\n h = config[:height] || last[:height] || (last[:row] - r)\n h = 2 if h < 2\n w = config[:width] || last[:width] || 15 # tmp\n case last\n when WsFlow\n w = last[:col]\n when WsStack\n #h += 1\n end\n config[:row] = r\n config[:col] = c\n config[:height] = h\n config[:width] = w\n _box.row r\n _box.col c\n _box.height h\n _box.width w\n last[:row] += 1\n last[:col] += 1 # ??? XXX if flow we need to increment properly or not ?\n end\n end", "def boxes\n box_lines.map {|l| parse_line l.match(PARSE_BOX) }.to_set\n end", "def box config={}, &block\n require 'canis/core/widgets/box'\n # take current stacks row and col\n # advance row by one and col by one\n # at end note row and advance by one\n # draw a box around using these coordinates. width should be\n # provided unless we have item width or something.\n last = @_ws_active.last\n if last\n r = last[:row]\n c = last[:col]\n config[:row] = r\n config[:col] = c\n last[:row] += config[:margin_top] || 1\n last[:col] += config[:margin_left] || 1\n _box = Box.new @form, config # needs to be created first or will overwrite area after others painted\n yield_or_eval &block if block_given?\n h = config[:height] || last[:height] || (last[:row] - r)\n h = 2 if h < 2\n w = config[:width] || last[:width] || 15 # tmp\n case last\n when WsFlow\n w = last[:col]\n when WsStack\n #h += 1\n end\n config[:row] = r\n config[:col] = c\n config[:height] = h\n config[:width] = w\n _box.row r\n _box.col c\n _box.height h\n _box.width w\n last[:row] += 1\n last[:col] += 1 # ??? XXX if flow we need to increment properly or not ?\n end\n end", "def to_boxes\n boxes = []\n @contents.each do |c|\n if @type == VERTICAL\n boxes << Box.new(c[0], 0, c[1], c[2])\n else\n boxes << Box.new(0, c[0], c[2], c[1])\n end\n end\n boxes\n end", "def merge(boxes)\n content = []\n tracker = nil\n boxes.each do |b|\n content << b.contents\n unless b.tracker.nil?\n if tracker.nil?\n tracker = b.tracker\n else\n tracker = tracker.merge(b.tracker)\n end\n end\n end\n Box.new(content, tracker)\n end", "def draw_multi(text, x, y, width, lines = -1, base_color = Color.new(255,255,255), shadow_color = nil,\n outline = false, y_line_diff = 24, allow_split_in_words = false)\n self.bmp.draw_multi(text, x, y, width, lines, base_color, shadow_color,\n outline, y_line_diff, allow_split_in_words)\n end", "def box(title=nil, options={}, &block)\n title = I18n.t(\"admin.boxs.#{title}\", :default => title.to_s.humanize) if title.is_a?(Symbol)\n subtitle = options.delete(:subtitle)\n options[:style] ||= \"width:100%;\"\n options[:start] ||= :open\n concat_content (<<-HTML).gsub(/ {10}/, '')\n <div class=\"#{options[:class]}\" style=\"options[:style]\">\n <div class=\"x-box\">\n <div class=\"x-box-tl\">\n <div class=\"x-box-tr\">\n <div class=\"x-box-tc\">&nbsp;</div>\n </div>\n </div>\n <div class=\"x-box-ml\">\n <div class=\"x-box-mr\">\n <div class=\"x-box-mc\">\n <div id=\"x-body-title\" style=\"#{\"cursor:pointer\" if options[:collapsible]}\" onclick=\"#{\"Admin.app.collapseBoxes(this);\" if options[:collapsible]}\">\n #{\"<h3 style=\\\"margin-bottom:0px;padding-bottom:0px;float:left;\\\">\"+title+\"</h3>\" if title.present?}\n #{\"<div style=\\\"float:right\\\"><em>\"+subtitle+\"</em></div>\" if subtitle.present?}\n #{\"<br class=\\\"clear\\\" />\" if title.present? || subtitle.present?}\n #{\"<div style=\\\"font-size:0px\\\">&nbsp;</div>\" if title.present? || subtitle.present?}\n </div>\n <div class=\"#{\"x-box-collapsible\" if options[:collapsible]}\" style=\"width:99%;#{\"display:none\" if options[:collapsible] && options[:start] == :close}\">\n #{\"<div style=\\\"font-size:10px\\\">&nbsp;</div>\" if title.present? || subtitle.present?}\n #{capture_html(&block)}\n </div>\n </div>\n </div>\n </div>\n <div class=\"x-box-bl\">\n <div class=\"x-box-br\">\n <div class=\"x-box-bc\">&nbsp;</div>\n </div>\n </div>\n </div>\n </div>\n HTML\n end", "def create_widgets\n top_box = Gtk::HBox.new(false, 0)\n @start_button = Gtk::Button.new(\"Start\")\n top_box.pack_start(@start_button, true, true, 5)\n @time_label = Gtk::Label.new\n @time_label.set_markup(\"<span size='xx-large'>00:00:00</span>\") \n top_box.pack_end(@time_label, false, false, 5)\n \n mid_vert_box = Gtk::VBox.new(false, 0)\n \n project_box = Gtk::HBox.new(false, 0)\n @project_combo = Gtk::ComboBox.new\n project_box.pack_start(@project_combo, true, true, 5)\n \n task_box = Gtk::HBox.new(false, 0)\n @task_combo = Gtk::ComboBox.new\n task_box.pack_start(@task_combo, true, true, 5)\n \n comment_box = Gtk::HBox.new(false, 0)\n @comment_entry = Gtk::Entry.new\n comment_box.pack_start(@comment_entry, true, true, 5)\n \n mid_vert_box.add(project_box)\n mid_vert_box.add(task_box)\n mid_vert_box.add(comment_box)\n mid_vert_box.spacing = 5\n \n bottom_box = Gtk::HBox.new\n bottom_box.spacing = 5\n @post_button = Gtk::Button.new(\"Post Timer\")\n bottom_box.pack_end(@post_button, false, 0)\n @reset_button = Gtk::Button.new(\"Clear Timer\")\n bottom_box.pack_end(@reset_button, false, 0)\n \n main_box = Gtk::VBox.new(false, 0)\n main_box.spacing = 20\n main_box.add(top_box)\n main_box.add(mid_vert_box)\n main_box.add(bottom_box)\n \n @window.add(main_box)\n end", "def roundedbox(html_options = {}, &block)\n html_options[:class] = ['box', html_options[:class]].compact.join(' ')\n concat <<-MARKUP\n <div #{tag_options(html_options)}>\n <div class=\"boxtop\"><div>&nbsp;</div></div>\n <div class=\"boxcontent\">#{capture(&block)}</div>\n <div class=\"boxbottom\"><div>&nbsp;</div></div>\n </div>\n MARKUP\n end" ]
[ "0.6464205", "0.5841228", "0.56698936", "0.5520285", "0.55042785", "0.5450058", "0.54241514", "0.52830034", "0.5258477", "0.5247274", "0.5208967", "0.5190762", "0.51529074", "0.514873", "0.5145886", "0.5129254", "0.50793684", "0.5023993", "0.50237775", "0.5003811", "0.49923488", "0.49608967", "0.49581966", "0.4916547", "0.49069664", "0.48998758", "0.48576194", "0.48338962", "0.48202148", "0.4808811" ]
0.81510353
0
Render a box. options: content (string) heading (string) float_left (true/false) text_align_center (true/false) highlight (true/false) background_image (url) bigfont (true/false) heading_color (color name, e.g. 'red') background_color (color name, e.g. 'blue') inner_div_style (css style, e.g. "width: 382px; height: 281px;") outer_div_style (same) heading_style (same) height (css style unit, e.g. "100px" or "6em") solid_background (true/false) You can wrap an tag around the box and it will have a:hover CSS enabled, e.g. link_to " do = render_box do "bar"
def render_box(options = {}) # list of classes for the outer div. outer_div_classes = [ "textbox_container" ] # inner div, same story inner_div_classes = [ "textbox" ] # heading heading_classes = [ "heading" ] content = yield if block_given? content ||= options[:content] return nil if content.blank? && options[:heading].blank? unless options[:empty] # Options: # float_left outer_div_classes.push("float_left") if options[:float_left] === true # text_align_center inner_div_classes.push("text_align_center") if options[:text_align_center] === true # highlight inner_div_classes.push("highlight") if options[:highlight] === true # background_image background_image = options[:background_image] # header color heading_color = options[:heading_color] inner_div_classes.push("textbox_#{heading_color}") unless heading_color.blank? # background color background_color = options[:background_color] ############################################################################ # inner div ############################################################################ inner_div_classes.push("#{background_color}_background") unless background_color.blank? inner_div_options = { :class => c(inner_div_classes) } inner_div_styles = [] unless background_image.blank? # opacity:0.4;filter:alpha(opacity=40); inner_div_styles.push "background: url(#{background_image}) no-repeat center;" end unless options[:height].blank? inner_div_styles.push "height: #{options[:height]}" end unless options[:width].blank? inner_div_styles.push "width: #{options[:width]}" end unless inner_div_styles.blank? inner_div_options[:style] = c(inner_div_styles) end inner_div_options[:style] ||= options[:inner_div_style] # can be overridden ############################################################################ # outer div ############################################################################ outer_div_options = { :class => c(outer_div_classes) } outer_div_options[:style] = options[:outer_div_style] ############################################################################ # text div ############################################################################ text_div_options = {} text_div_classes = [] text_div_classes.push "bigfont" if options[:bigfont] === true text_div_classes.push "solid_background" if options[:solid_background] === true text_div_options[:class] = c(text_div_classes) ############################################################################ # go render ############################################################################ # let's go, outer div content_tag :div, outer_div_options do content_tag :div, inner_div_options do # heading heading = "" heading = content_tag :p, options[:heading], :class => c(heading_classes), :style => options[:heading_style] unless options[:heading].blank? # text div content_tag_ = content_tag :div, text_div_options do content_tag :p, content, :class => "inner_p" end # do it! heading + content_tag_ end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def prettybox(html_options, &proc)\n raise ArgumentError, \"Missing block\" unless block_given?\n concat(tag(\"div\", html_options, true), proc.binding)\n concat(\"<div class=\\\"prettybox_top\\\">\n <div>&nbsp;</div>\n </div><div class=\\\"prettybox_inside\\\">\", proc.binding)\n yield\n concat(\"</div><div class=\\\"prettybox_bot\\\">\n <div>&nbsp;</div>\n </div>\n </div>\", proc.binding)\n end", "def box(name, options={}, &block)\n options.merge!(:body=>capture(&block))\n concat(render(:partial => \"shared/ubiquo/boxes/#{name}\", :locals => options), block.binding)\n end", "def box(title=nil, options={}, &block)\n title = I18n.t(\"admin.boxs.#{title}\", :default => title.to_s.humanize) if title.is_a?(Symbol)\n subtitle = options.delete(:subtitle)\n options[:style] ||= \"width:100%;\"\n options[:start] ||= :open\n concat_content (<<-HTML).gsub(/ {10}/, '')\n <div class=\"#{options[:class]}\" style=\"options[:style]\">\n <div class=\"x-box\">\n <div class=\"x-box-tl\">\n <div class=\"x-box-tr\">\n <div class=\"x-box-tc\">&nbsp;</div>\n </div>\n </div>\n <div class=\"x-box-ml\">\n <div class=\"x-box-mr\">\n <div class=\"x-box-mc\">\n <div id=\"x-body-title\" style=\"#{\"cursor:pointer\" if options[:collapsible]}\" onclick=\"#{\"Admin.app.collapseBoxes(this);\" if options[:collapsible]}\">\n #{\"<h3 style=\\\"margin-bottom:0px;padding-bottom:0px;float:left;\\\">\"+title+\"</h3>\" if title.present?}\n #{\"<div style=\\\"float:right\\\"><em>\"+subtitle+\"</em></div>\" if subtitle.present?}\n #{\"<br class=\\\"clear\\\" />\" if title.present? || subtitle.present?}\n #{\"<div style=\\\"font-size:0px\\\">&nbsp;</div>\" if title.present? || subtitle.present?}\n </div>\n <div class=\"#{\"x-box-collapsible\" if options[:collapsible]}\" style=\"width:99%;#{\"display:none\" if options[:collapsible] && options[:start] == :close}\">\n #{\"<div style=\\\"font-size:10px\\\">&nbsp;</div>\" if title.present? || subtitle.present?}\n #{capture_html(&block)}\n </div>\n </div>\n </div>\n </div>\n <div class=\"x-box-bl\">\n <div class=\"x-box-br\">\n <div class=\"x-box-bc\">&nbsp;</div>\n </div>\n </div>\n </div>\n </div>\n HTML\n end", "def prettybox_bottomonly(html_options, &proc)\n raise ArgumentError, \"Missing block\" unless block_given?\n concat(tag(\"div\", html_options, true), proc.binding)\n concat(\"<div class=\\\"prettybox_inside\\\">\", proc.binding)\n yield\n concat(\"</div><div class=\\\"prettybox_bot\\\">\n <div>&nbsp;</div>\n </div>\n </div>\", proc.binding)\n end", "def roundedbox(html_options = {}, &block)\n html_options[:class] = ['box', html_options[:class]].compact.join(' ')\n concat <<-MARKUP\n <div #{tag_options(html_options)}>\n <div class=\"boxtop\"><div>&nbsp;</div></div>\n <div class=\"boxcontent\">#{capture(&block)}</div>\n <div class=\"boxbottom\"><div>&nbsp;</div></div>\n </div>\n MARKUP\n end", "def box(title=nil, subtitle=nil, options={}, &block)\n options[:style] ||= \"width:100%;\"\n options[:start] ||= :open\n concat <<-HTML\n <div class=\"x-box\" style=\"#{options[:style]}\">\n <div class=\"x-box-tl\">\n <div class=\"x-box-tr\">\n <div class=\"x-box-tc\">&nbsp;</div>\n </div>\n </div>\n <div class=\"x-box-ml\">\n <div class=\"x-box-mr\">\n <div class=\"x-box-mc\">\n <div id=\"x-body-title\" style=\"#{\"cursor:pointer\" if options[:collapsible]}\" onclick=\"#{\"Backend.app.collapseBoxes(this);\" if options[:collapsible]}\">\n #{\"<h3 style=\\\"margin-bottom:0px;padding-bottom:0px;float:left;\\\">\"+title+\"</h3>\" unless title.blank?}\n #{\"<div style=\\\"float:right\\\"><em>\"+subtitle+\"</em></div>\" unless subtitle.blank?}\n #{\"<br class=\\\"clear\\\" />\" if !title.blank? || !subtitle.blank?}\n #{\"<div style=\\\"font-size:0px\\\">&nbsp;</div>\" if !title.blank? || !subtitle.blank?}\n </div>\n <div class=\"#{\"x-box-collapsible\" if options[:collapsible]}\" style=\"width:99%;#{\"display:none\" if options[:collapsible] && options[:start] == :close}\">\n #{\"<div style=\\\"font-size:10px\\\">&nbsp;</div>\" if !title.blank? || !subtitle.blank?}\n #{capture(&block)}\n #{\"<div style=\\\"text-align:right;margin-top:10px\\\">#{submit_tag(I18n.t(\"lipsiadmin.buttons.save\"), :onclick=>\"Backend.app.submitForm()\")}</div>\" if options[:submit]}\n </div>\n </div>\n </div>\n </div>\n <div class=\"x-box-bl\">\n <div class=\"x-box-br\">\n <div class=\"x-box-bc\">&nbsp;</div>\n </div>\n </div>\n </div>\n HTML\n end", "def render_boxes(array = [], options = {})\n boxes = \"\"\n\n template = {}\n\n if options[:template].class.to_s.eql?(\"Hash\")\n template = options[:template]\n end\n\n array.each do |individual_options|\n box_options = template\n box_options = template.merge(individual_options) unless individual_options.nil?\n r = render_box(box_options)\n\n unless individual_options[:link].blank?\n r = \"<a href='#{individual_options[:link]}' target='#{individual_options[:link_target]}' class='no_underline render_boxes'>#{r}</a>\"\n end\n\n boxes += r unless r.blank?\n end\n\n boxes_div = content_tag :div, boxes, :class => \"textboxes\", :style => options[:textboxes_style]\n\n clear_both_ = \"\"\n\n unless options[:noclear] === true\n clear_both_ = clear_both\n end\n\n boxes_div + clear_both_\n end", "def box_widget(title, options = {}, extra = [], &block)\n block_to_partial('shared/box_widget', options.merge(:title => title, :extra => extra), &block)\n end", "def div(options = {})\r\n attributes = \"id=\\\"#{@container}\\\" \"\r\n if options.has_key?(:height) && options.has_key?(:width)\r\n attributes += \"style=\\\"width:#{options.delete(:width)}px;height:#{options.delete(:height)}px\\\" \"\r\n end\r\n if options.has_key?(:class)\r\n attributes += options.keys.map {|opt| \"#{opt}=\\\"#{options[opt]}\\\"\" }.join(\" \")\r\n end\r\n \"<div #{attributes}></div>\"\r\n end", "def box(body)\n formatted_box(body, :blue, \"ℹ\", \"\")\nend", "def box config={}, &block\n require 'canis/core/widgets/box'\n # take current stacks row and col\n # advance row by one and col by one\n # at end note row and advance by one\n # draw a box around using these coordinates. width should be\n # provided unless we have item width or something.\n last = @_ws_active.last\n if last\n r = last[:row]\n c = last[:col]\n config[:row] = r\n config[:col] = c\n last[:row] += config[:margin_top] || 1\n last[:col] += config[:margin_left] || 1\n _box = Box.new @form, config # needs to be created first or will overwrite area after others painted\n yield_or_eval &block if block_given?\n h = config[:height] || last[:height] || (last[:row] - r)\n h = 2 if h < 2\n w = config[:width] || last[:width] || 15 # tmp\n case last\n when WsFlow\n w = last[:col]\n when WsStack\n #h += 1\n end\n config[:row] = r\n config[:col] = c\n config[:height] = h\n config[:width] = w\n _box.row r\n _box.col c\n _box.height h\n _box.width w\n last[:row] += 1\n last[:col] += 1 # ??? XXX if flow we need to increment properly or not ?\n end\n end", "def ebox(text:, x_pos:, y_pos:, width:, height:, title: '')\n puts %(\n <rect\n x=\"#{x_pos}\" y=\"#{y_pos}\" width=\"#{width}\" height=\"#{height}\"\n style=\"fill: #{color text}; stroke: black;\">\n <title>#{title}</title>\n </rect>\n )\nend", "def box config={}, &block\n require 'canis/core/widgets/box'\n # take current stacks row and col\n # advance row by one and col by one\n # at end note row and advance by one\n # draw a box around using these coordinates. width should be\n # provided unless we have item width or something.\n @_ws_active ||= []\n last = @_ws_active.last\n if last\n r = last[:row]\n c = last[:col]\n config[:row] = r\n config[:col] = c\n last[:row] += config[:margin_top] || 1\n last[:col] += config[:margin_left] || 1\n _box = Box.new @form, config # needs to be created first or will overwrite area after others painted\n yield_or_eval &block if block_given?\n # FIXME last[height] needs to account for row\n h = config[:height] || last[:height] || (last[:row] - r)\n h = 2 if h < 2\n w = config[:width] || last[:width] || 15 # tmp\n case last\n when WsFlow\n w = last[:col]\n when WsStack\n #h += 1\n end\n config[:row] = r\n config[:col] = c\n config[:height] = h\n config[:width] = w\n _box.row r\n _box.col c\n _box.height h\n _box.width w\n last[:row] += 1\n last[:col] += 1 # ??? XXX if flow we need to increment properly or not ?\n end\n end", "def render(_options = {})\n content_tag :div, class: css_name do\n content_text = data['text'] || ''\n CommonMarker::Rouge.render_html(\n content_text,\n %i[UNSAFE FOOTNOTES STRIKETHROUGH_DOUBLE_TILDE],\n %i[UNSAFE GITHUB_PRE_LANG HARDBREAKS TABLE_PREFER_STYLE_ATTRIBUTES FULL_INFO_STRING FOOTNOTES],\n %i[table strikethrough tasklist tagfilter],\n formatter: Rouge::Formatters::HTMLLegacy.new(inline_theme: 'github')\n ).html_safe\n end\n end", "def treatment_box\n box = TTY::Box.frame(width: 165, height: 5, align: :center) do\n \"Full List of Treatments\".green\n end\n puts box\nend", "def draw_box(x, y, w, h, options = {})\n options[:border] ||= 1\n options[:border_color] ||= RFPDF::COLOR_PALETTE[:black]\n options[:border_width] ||= 0.5\n options[:fill] ||= 1\n options[:fill_color] ||= RFPDF::COLOR_PALETTE[:white]\n options[:fill_colorspace] ||= :rgb\n SetLineWidth(options[:border_width])\n set_draw_color_a(options[:border_color])\n set_fill_color_a(options[:fill_color], options[:fill_colorspace])\n fd = \"\"\n fd = \"D\" if options[:border] == 1\n fd += \"F\" if options[:fill] == 1\n Rect(x, y, w, h, fd)\n end", "def content_box # :doc:\n \[email protected](:class => \"content-box\")\n end", "def rounded_titled_box(title, type, options = {}, &block)\n block_to_partial('shared/rounded_titled_box', options.merge(:title => title, :type => type), &block)\n end", "def draw(box)\n battr = 0\n bchar = 0\n fattr = @filler & Ncurses::A_ATTRIBUTES\n hist_x = @title_lines + 1\n hist_y = @bar_size\n\n @win.werase\n\n # Box the widget if asked.\n if box\n Draw.drawObjBox(@win, self)\n end\n\n # Do we have a shadow to draw?\n if !(@shadow.nil?)\n Draw.drawShadow(@shadow_win)\n end\n\n self.drawTitle(@win)\n\n # If the user asked for labels, draw them in.\n if @view_type != :NONE\n # Draw in the low label.\n if @low_string.size > 0\n Draw.writeCharAttrib(@win, @lowx, @lowy, @low_string,\n @stats_attr, @orient, 0, @low_string.size)\n end\n\n # Draw in the current value label.\n if @cur_string.size > 0\n Draw.writeCharAttrib(@win, @curx, @cury, @cur_string,\n @stats_attr, @orient, 0, @cur_string.size)\n end\n\n # Draw in the high label.\n if @high_string.size > 0\n Draw.writeCharAttrib(@win, @highx, @highy, @high_string,\n @stats_attr, @orient, 0, @high_string.size)\n end\n end\n\n if @orient == CDK::VERTICAL\n hist_x = @box_height - @bar_size - 1\n hist_y = @field_width\n end\n\n # Draw the histogram bar.\n (hist_x...@box_height - 1).to_a.each do |x|\n (1..hist_y).each do |y|\n battr = @win.mvwinch(x, y)\n \n if battr == ' '.ord\n @win.mvwaddch(x, y, @filler)\n else\n @win.mvwaddch(x, y, battr | fattr)\n end\n end\n end\n\n # Refresh the window\n @win.wrefresh\n end", "def colored_box(box_text, options={})\n options = { :fill_color => DARK_GRAY,\n :stroke_color => nil,\n :text_color => LIGHT_GRAY,\n :leading => LEADING\n }.merge(options)\n\n \n text_options = { :leading => options[:leading], \n :fallback_fonts => [\"Helvetica\", \"Kai\"]\n }\n\n box_height = height_of_formatted(box_text, text_options)\n\n bounding_box([INNER_MARGIN + RHYTHM, cursor],\n :width => bounds.width - (INNER_MARGIN+RHYTHM)*2) do\n\n fill_color options[:fill_color]\n stroke_color options[:stroke_color] || options[:fill_color]\n fill_and_stroke_rounded_rectangle(\n [bounds.left - RHYTHM, cursor],\n bounds.left + bounds.right + RHYTHM*2,\n box_height + RHYTHM*2,\n 5\n )\n fill_color BLACK\n stroke_color BLACK\n\n pad(RHYTHM) do\n formatted_text(box_text, text_options)\n end\n end\n\n move_down(RHYTHM*2)\n end", "def box_plot(x: nil, y: nil, color: nil, data: nil,\n order: nil, color_order: nil,\n orient: nil, key_color: nil, palette: nil, saturation: 1r,\n width: 0.8r, dodge: true, flier_size: 5, line_width: nil,\n whisker: 1.5, x_label: nil, y_label: nil, title: nil,\n **options, &block)\n Plotters::BoxPlotter.new(\n data: data,\n variables: { x: x, y: y, color: color },\n order: order,\n color_order: color_order,\n orient: orient,\n key_color: key_color,\n palette: palette,\n saturation: saturation,\n width: width,\n dodge: dodge,\n flier_size: flier_size,\n line_width: line_width,\n whisker: whisker,\n x_label: x_label,\n y_label: y_label,\n title: title,\n **options,\n &block\n )\n end", "def boxify(page, _site)\n return if page.content.nil?\n\n lang = page['lang'] || 'en'\n\n # Interim solution, fancier box titles\n # rubocop:disable Layout/LineLength\n page.content = page.content.gsub(%r{<(?<boxclass>#{Gtn::Boxify.box_classes})-title( ?(?<noprefix>noprefix))>(?<title>.*?)</\\s*\\k<boxclass>-title\\s*>}) do\n # rubocop:enable Layout/LineLength\n m = ::Regexp.last_match\n box_type = m[:boxclass]\n title = m[:title]\n noprefix = m[:noprefix]\n if page.data['citation_target'] == 'jupyter'\n title = Gtn::Boxify.safe_title(title)\n title = Gtn::Boxify.format_box_title(title, box_type, lang, noprefix: noprefix)\n icon = Gtn::Boxify.get_icon(box_type, emoji: true)\n box = \"<div class=\\\"box-title\\\" aria-description=\\\"#{box_type} box: \" \\\n \"#{title}\\\" style=\\\"font-size: 150%\\\">#{icon} #{title}</div>\"\n box.gsub!(/\\\\&quot/, '&quot')\n box.gsub!(/([^\\\\])\"/, '\\1\\\\\"')\n else\n _, box = Gtn::Boxify.generate_title(box_type, title, lang, page.path, noprefix: noprefix)\n end\n\n box\n end\n\n # Long term solution, proper new boxes\n # BUT: does not work with <details></details> that are actual HTML elements, so we'll need to rename those.\n # page.content = page.content.gsub(/<(#{Gtn::Boxify.box_classes})>/) {\n # box_type = $1\n # box = Gtn::Boxify.generate_box(box_type, nil, lang, page.path)\n # box\n # }\n\n # page.content = page.content.gsub(/<(#{Gtn::Boxify.box_classes}) title=\"([^\"]*)\">/) {\n # box_type = $1\n # title = $2\n # box = Gtn::Boxify.generate_box(box_type, title, lang, page.path)\n # box\n # }\n\n # page.content = page.content.gsub(/<\\/\\s*(#{Gtn::Boxify::box_classes})\\s*>/) {\n # box_type = $1\n # \"\\n</div></div><!--#{box_type}-->\"\n # }\n end", "def add_box(window, id, x, y, width, height, **args)\n window_exist?(window)\n box = Box.new(\n self,\n find_window(window),\n id,\n x,\n y,\n width,\n height,\n **args\n )\n @windows[window].add_widget(id, box)\n end", "def box(position, width, height, options = {})\n size = build_size_options(position, width, height)\n box = bounding_box(position, size) do\n padding(options[:padding] || [0, 0, 0, 0]) { yield if block_given? }\n end\n @last_created_box = box unless options[:dont_track]\n box\n end", "def body content = nil, options = nil, html_options = nil, &block\n @body = Component.new content, options, html_options, &block\n end", "def render_object(object, direction = nil)\n flow top: (object.y+1)*n, left: object.x*n, width: n, height: n do\n image = image_for_object object, direction\n style background: image if image\n end.tap do |element|\n @elements[object] = element\n end", "def draw_box(x, y, width, height, color, z = 0.0)\n draw_line(x, y, color, x + width, y, color, z)\n draw_line(x + width, y, color, x + width, y + height, color, z)\n draw_line(x, y, color, x, y + height, color, z)\n draw_line(x, y + height, color, x + width, y + height, color, z)\n end", "def rounded_box(css_class, options = {}, &block)\n block_to_partial('shared/rounded_box', options.merge(:css_class => css_class), &block)\n end", "def alert_box(heading, content, html_options = {})\n html_options = html_options.stringify_keys\n html_options['class'] = \"alert_box #{html_options['class']}\"\n content_tag(:div, html_options) do\n content_tag(:div) do\n content_tag(:p, heading, class: 'alert_box_heading') << content\n end\n end\n end", "def draw(box)\n # Draw the shadow.\n unless @shadow_win.nil?\n Draw.drawShadow(@shadow_win)\n end\n\n # Box the widget if asked.\n if box\n Draw.drawObjBox(@win, self)\n end\n\n self.drawTitle(@win)\n\n # Draw the label.\n unless @label_win.nil?\n Draw.writeChtype(@label_win, 0, 0, @label, CDK::HORIZONTAL,\n 0, @label_len)\n @label_win.wrefresh\n end\n @win.wrefresh\n\n # Draw the field window.\n self.drawField\n end" ]
[ "0.66518354", "0.64276874", "0.63438886", "0.62945646", "0.6275616", "0.62258786", "0.5826013", "0.57734585", "0.575188", "0.5711554", "0.5708607", "0.5708331", "0.56436723", "0.56094885", "0.5501951", "0.5469089", "0.54682136", "0.5411976", "0.54065824", "0.5400691", "0.535109", "0.52880824", "0.52856123", "0.52819836", "0.5260019", "0.5243506", "0.5242502", "0.52374095", "0.5215057", "0.5206725" ]
0.74547935
0
Set the value of the Selection input for this Choreo.
def set_Selection(value) set_input("Selection", value) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_selection\n @selection = Selection.find(params[:id])\n end", "def selected=(selected)\n @selected = selected\n update_cursor\n end", "def set_selection(*args)\n # Check for a cell reference in A1 notation and substitute row and column\n if args[0] =~ /^\\D/\n args = substitute_cellref(*args)\n end\n @selection = args\n end", "def selection\n eval_param(:selection)\n end", "def SetSelect(select)\n\t\t assert { select.instance_of? String }\n\t\t @select = select\n\t\tend", "def selected=(value)\n return if value == @selected\n if value\n move(*SELECT_POSITION_OFFSET)\n @icon.select(1, @real_index)\n @icon.angle = ANGLE_VARIATION\n else\n move(-SELECT_POSITION_OFFSET.first, -SELECT_POSITION_OFFSET.last)\n @icon.select(0, @real_index)\n @icon.angle = 0\n end\n @selected = value\n @counter = 0\n end", "def set option_value\n self.select option_value\n end", "def set_selection_criterium\n @selection_criterium = SelectionCriterium.find(params[:id])\n end", "def selections=(strings)\n @selections = strings\n if @selections.empty?\n self.text = nil\n else\n self.text = @selections[0]\n end\n end", "def select(val)\n raise \"select requires a String.\" unless val.is_a? String\n @select = val\n self\n end", "def selection\n\t\t\t$ruvim.editor.selection\n\t\tend", "def set_question_option_selection\n @question_option_selection = QuestionAnswer.question_option_selections.find(params[:id])\n end", "def toggle_selection\n buffer_current.toggle_selection\n update_status_line\n end", "def selected=(selected)\n @selected = selected\n @selector.visible = selected || @moving\n end", "def selected_federation_uris=(selection)\n\n only_use(selection)\n\n end", "def initialize\n @selection\n end", "def set_sel(first, last)\n send_message(:SETSEL, first, last)\n end", "def set_selected_values(port, selection_mask, value_mask)\n send_request(FUNCTION_SET_SELECTED_VALUES, [port, selection_mask, value_mask], 'k C C', 0, '')\n end", "def select(...)\n prompt.select(...)\n end", "def selection *params\n opt = parse_params_for_select params\n return @adapter.selection(opt)\n end", "def selection(cell)\n\t\t@last = cell\n\t\[email protected](cellsFromFirstToEnd())\n\t\[email protected]()\n\tend", "def selector=(sel)\n @selector = case sel\n when nil\n {}\n when Code\n {\"$where\" => sel}\n when String\n {\"$where\" => Code.new(sel)}\n when Hash\n sel\n end\n end", "def insel=(val)\n case val\n when Fixnum\n 4.times {|i| send(\"input_sel#{i}=\", val)}\n when Array\n val.each_with_index {|v,i| send(\"input_sel#{i}=\", v) if v}\n when Hash\n insel(val)\n end\n end", "def item_selected=(value)\n @item_selected = value\n end", "def select_option\n print_menu\n @choice = gets.chomp\n perform_selection\n end", "def select()\n return unless @@auth\n window.getSelection().removeAllRanges()\n @state = ( @state == :open ? :closed : :open )\n end", "def draw_selection\n return unless active_field? && sel_x != pos_x\n\n @window.draw_rectangle(\n @point.offset(sel_left, 0), Size(sel_width, height), 0, SELECTION_COLOR\n )\n end", "def set_Region(value)\n set_input(\"Region\", value)\n end", "def toggle_selection_mode\n if @mode == 'SEL'\n unselect_all\n @mode = nil\n message 'Selection mode is single. '\n else\n @mode = 'SEL'\n message 'Typing a hint selects the file. Typing again will clear . '\n end\nend", "def select\n @selected = true\n @image.rect(BORDER, BORDER, @image.width - BORDER, @image.height - BORDER, color: DeathAngel::SELECTED_COLOR, thickness: BORDER * 2)\n end" ]
[ "0.6730609", "0.60064816", "0.59250665", "0.55305684", "0.54792243", "0.5294307", "0.5193717", "0.5160014", "0.50771934", "0.49670652", "0.49642852", "0.49552462", "0.4897551", "0.48896053", "0.48892686", "0.48653993", "0.47962394", "0.47817543", "0.47708645", "0.4731124", "0.47135183", "0.46816796", "0.4585757", "0.45596343", "0.45131576", "0.4511567", "0.44893634", "0.44853956", "0.44837978", "0.44826823" ]
0.72626334
0
Set the value of the Title input for this Choreo.
def set_Title(value) set_input("Title", value) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_title(title)\n @title = title\n end", "def title=(title)\n if title.nil?\n fail ArgumentError, 'invalid value for \"title\", title cannot be nil.'\n end\n @title = title\n end", "def title=(title)\n if title.nil?\n fail ArgumentError, 'invalid value for \"title\", title cannot be nil.'\n end\n @title = title\n end", "def setTitle(title)\n @fields['title'] = title\n self\n end", "def setTitle(title)\n @fields['title'] = title\n self\n end", "def setTitle(title)\n @fields['title'] = title\n self\n end", "def setTitle(title)\n @fields['title'] = title\n self\n end", "def title=(value)\n\t\t\t@title = value\n\t\tend", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def set_Title(value)\n set_input(\"Title\", value)\n end", "def title_set(title)\n self.sirname.set title\n end", "def title=(value)\n if value\n @title = value if value.is_a? String\n end\n end", "def title(title)\n @title = title\n end", "def title=(title)\n if title.nil?\n fail ArgumentError, 'title cannot be nil'\n end\n\n if title.to_s.length < 1\n fail ArgumentError, 'invalid value for \"title\", the character length must be great than or equal to 1.'\n end\n\n @title = title\n end" ]
[ "0.7805282", "0.77696145", "0.77696145", "0.7668345", "0.7668345", "0.7668345", "0.7668345", "0.76442933", "0.7638002", "0.7638002", "0.7638002", "0.7638002", "0.7638002", "0.7638002", "0.7638002", "0.7618395", "0.7618395", "0.7618395", "0.7618395", "0.7618395", "0.7618395", "0.7618395", "0.7618395", "0.7618395", "0.759577", "0.759577", "0.75787", "0.7484066", "0.7474224", "0.74601024" ]
0.7820923
0
Set the value of the URL input for this Choreo.
def set_URL(value) set_input("URL", value) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def url=(value)\n @url = value\n Curl.set_option(:url, value_for(value, :string), handle)\n end", "def set_URL(value)\n set_input(\"URL\", value)\n end", "def set_URL(value)\n set_input(\"URL\", value)\n end", "def set_URL(value)\n set_input(\"URL\", value)\n end", "def set_URL(value)\n set_input(\"URL\", value)\n end", "def set_URL(value)\n set_input(\"URL\", value)\n end", "def set_URL(value)\n set_input(\"URL\", value)\n end", "def set_URL(value)\n set_input(\"URL\", value)\n end", "def setURL(url)\r\n\t\t\t\t\t@url = url\r\n\t\t\t\tend", "def setURL(url)\r\n\t\t\t\t\t@url = url\r\n\t\t\t\tend", "def setURL(url)\r\n\t\t\t\t\t@url = url\r\n\t\t\t\tend", "def setURL(url)\r\n\t\t\t\t\t@url = url\r\n\t\t\t\tend", "def setURL(url)\r\n\t\t\t\t\t@url = url\r\n\t\t\t\tend", "def url=(v)\n @url = v ? URI.parse(v) : nil\n end", "def url=(url)\n if url.nil?\n fail ArgumentError, 'url cannot be nil'\n end\n\n if url.to_s.length > 2083\n fail ArgumentError, 'invalid value for \"url\", the character length must be smaller than or equal to 2083.'\n end\n\n if url.to_s.length < 1\n fail ArgumentError, 'invalid value for \"url\", the character length must be great than or equal to 1.'\n end\n\n @url = url\n end", "def url=(url)\n @@url = url\n end", "def url=(new_url)\n @url = sanitize_url(new_url)\n end", "def url=(value)\n if value.nil?\n @url = nil\n else\n @url = Addressable::URI.parse(value)\n @url.path << '/' unless @url.path.end_with?('/')\n end\n end", "def url(value)\n @url = value\n end", "def url(url)\n @url = url\n end", "def url=(url)\n if url =~ /^http(s?)\\:\\/\\//i\n @url = url\n write_settings\n else\n $stderr.puts \"Please include a leading http://\"\n end\n end", "def url=(url)\n\n if !url.nil? && url.to_s.length > 500\n fail ArgumentError, \"invalid value for 'url', the character length must be smaller than or equal to 500.\"\n end\n\n @url = url\n end", "def url=(value)\n value = \"http://#{value}\" unless value.empty? || value =~ %r{^http://} || value =~ %r{^https://}\n write_local(:url, value)\n end", "def url=(url)\n @@url = url\n end", "def url=(url)\n active_window.url = url\n end", "def url=(url)\n @url = url\n @connection = nil\n end", "def url=(url)\n if not (self.type == :link || self.type == :image)\n raise NodeError, \"can't set URL for non-link or image\"\n end\n if !url.kind_of?(String)\n raise NodeError, \"url must be a String\"\n end\n # Make our own copy so ruby won't garbage-collect it:\n c_url = FFI::MemoryPointer.from_string(url)\n res = CMark.node_set_url(@pointer, c_url)\n if res == 0 then raise NodeError, \"could not set header level\" end\n end", "def set_url\n @url = DEFAULT_URL\n end", "def set_url(url_value)\n @path = url_value.delete_prefix \"/\"\n @dir = File.dirname(@path)\n @url = url_value\n end", "def url=(url)\n if url.nil?\n fail ArgumentError, 'url cannot be nil'\n end\n\n pattern = Regexp.new(/^https:\\/\\/(lob-assets|lob-assets-staging)\\.com\\/(letters|postcards|bank-accounts|checks|self-mailers|cards)\\/[a-z]{3,4}_[a-z0-9]{15,16}(\\.pdf|_thumb_[a-z]+_[0-9]+\\.png)\\?(version=[a-z0-9-]*&)?expires=[0-9]{10}&signature=[a-zA-Z0-9_-]+$/)\n if url !~ pattern\n fail ArgumentError, \"invalid value for \\\"url\\\", must conform to the pattern #{pattern}.\"\n end\n\n @url = url\n end" ]
[ "0.8073227", "0.76355296", "0.76355296", "0.76355296", "0.76355296", "0.76355296", "0.76355296", "0.76355296", "0.71796364", "0.71796364", "0.71796364", "0.71796364", "0.71796364", "0.70758444", "0.6956582", "0.68834627", "0.68829864", "0.68481743", "0.6793545", "0.6757589", "0.6662082", "0.6633582", "0.6589197", "0.65566564", "0.65509653", "0.6488953", "0.6464315", "0.6434313", "0.63489246", "0.62928766" ]
0.78341466
1
Show logout instead of link to adminpage on adminpanel
def show_logout @show_logout = true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def logout\n if @user != nil and @user.admin?(@routes)\n show :logout, views: File.join(Classiccms::ROOT, 'views/cms')\n end\n end", "def logout\n session.delete(:admin_password)\n redirect_to admin_login_path\n end", "def logout\n @logout_message = \"You have successfully logged out. Thanks for contributing!\"\n render \"/admin/login\", layout: \"public\"\n end", "def admin_log_out\n session.delete(:admin_user_id)\n @current_admin_user = nil\n end", "def logout_admin\n visit destroy_administrator_session_path\n end", "def destroy\n \t#call logout method in admin_helper but only if we r loggedin\n \tlog_out if logged_in?\n \t#redirect him to homepage\n \tredirect_to root_path\n end", "def admin_link\n # @subdomain = request.subdomain\n # @site = Site.where(subdomain: request.subdomain).first.user_id\n # @user = User.where(id: @site).first\n if user_signed_in? && @user.id == current_user.id\n html = '<li>' + (link_to '<i class=\"fa fa-cog\"></i> Admin'.html_safe, dashboard_path, target: \"_blank\") + '</li>'\n html.html_safe\n end\n end", "def signout\n #create a signout action at admin_helper\n logout\n redirect_to :controller=>:home, :action=>:index\n end", "def logout\n session[:user_id] = nil\n session[:admin_user_id] = nil\n flash[:notice] = \"Vous êtes déconnecté\"\n redirect_to root_url\n end", "def show_sign_out(user_id)\n if user_id\n content_tag :li do\n link_to 'Sign out', :session, method: :delete\n end\n end\n end", "def logged_in_admin\n unless admin?\n # show a flash message on the page\n flash[:danger] = \"Non sei autorizzato a visitare questa pagina\"\n # redirect user to home page\n redirect_to root_path\n end\n end", "def admin_user\n redirect_to(login_path) unless current_user.is_admin?\n end", "def show\n if !session[:is_admin]\n redirect_to root_url\n end\n end", "def log_out\n session.delete(:admin_id)\n end", "def auth_admin\n if !current_user.admin\n redirect_back\n end\n end", "def auth_admin\n if !current_user.admin\n redirect_back\n end\n end", "def auth_admin\n if !current_user.admin\n redirect_back\n end\n end", "def admin_user\n unless logged_in? && current_user.admin?\n redirect_to root_url\n end\n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_url) unless current_user.admin? # se current_user.admin for falso redireciona para pagina principal\n end", "def logging_out_as_admin?\n session[:logged_in_with_admin_token]\n end", "def admin_user\n redirect_to(root_url) unless current_user.admin? \n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end", "def admin_user\n redirect_to(root_path) unless is_admin?\n end" ]
[ "0.7869341", "0.7371892", "0.73304105", "0.71523815", "0.7088891", "0.7064473", "0.70633715", "0.7058166", "0.6968901", "0.69150984", "0.6904809", "0.68289655", "0.6823173", "0.68124586", "0.681163", "0.681163", "0.681163", "0.6787559", "0.6779616", "0.6779616", "0.6776586", "0.677625", "0.67553717", "0.67544585", "0.67544585", "0.6754225", "0.6754225", "0.6754225", "0.6754225", "0.6751742" ]
0.7381453
1
Receiving messages from client and sending to other clients
def client_handler(client, all_clients) client.puts 'Welcome to server, stranger!' loop do msg = client.gets if msg.nil? puts 'Client disconnected' break end all_clients.each { |dest| send_msg(msg, dest) if dest != client } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_messages\n\t\t\tloop do\n\t\t\t\tchan, message = @redis_listener.blpop(\"#{PREFIX}.network:#{@network}.messages\", 0)\n\t\t\t\[email protected](\"A client sent the message : #{message}\")\n\t\t\t\tmsgid, command, args = parse(message)\n\t\t\t\tunless command\n\t\t\t\t\[email protected](\"A client sent an invalid message.\")\n\t\t\t\t\tnext\n\t\t\t\tend\n\t\t\t\tif msgid && @failed_cmds.include?(msgid) # Every daemon tried to contact the multi (blpop act as first waiting, first served)\n\t\t\t\t\tanswer(msgid, false, \"No daemon could contact the multiplexer\")\n\t\t\t\t\tnext\n\t\t\t\tend\n\t\t\t\tans, info = case command\n\t\t\t\t\twhen \"add_sensor\"\n\t\t\t\t\t\tregister_device :sensor, args\n\t\t\t\t\twhen \"add_actuator\"\n\t\t\t\t\t\tregister_device :actuator, args\n\t\t\t\t\twhen \"delete_sensor\"\n\t\t\t\t\t\tunregister_device :sensor, args\n\t\t\t\t\twhen \"delete_actuator\"\n\t\t\t\t\t\tunregister_device :actuator, args\n\t\t\t\t\twhen \"take\"\n\t\t\t\t\t\ttake_callback args\n\t\t\t\t\twhen \"actuator_state\"\n\t\t\t\t\t\tactuator_state_callback args\n\t\t\t\t\telse\n\t\t\t\t\t\[email protected](\"A client sent an unknown command : \\\"#{command}\\\"\")\n\t\t\t\t\t\t[false, \"Unknown command \\\"#{command}\\\"\"]\n\t\t\t\tend\n\t\t\t\tcase ans\n\t\t\t\t\twhen true # Success\n\t\t\t\t\t\tanswer(msgid, true)\n\t\t\t\t\twhen false # Failure\n\t\t\t\t\t\tanswer(msgid, false, info)\n\t\t\t\t\telse # Timeout error, transmit to another daemon\n\t\t\t\t\t\tif not msgid\t\t\t # Generate an id only for daemons\n\t\t\t\t\t\t\tmsgid = rand.hash.abs\n\t\t\t\t\t\t\tmessage = \"#{msgid}:#{message}\"\n\t\t\t\t\t\tend\n\t\t\t\t\t\t@failed_cmds.push(msgid).unshift\n\t\t\t\t\t\t#answer(msgid, false, \"wait\") # TODO utile ?\n\t\t\t\t\t\t@redis_listener.lpush(\"#{PREFIX}.network:#@network.messages\", message) #TODO generate with path?\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def receive_data data\n # The first message from the user is its name\n @name ||= data.strip\n\n @@connections.each do |client|\n # Send the message from the client to all other clients\n client.send_data \"#{@name} says: #{data}\"\n end\n end", "def listen(client)\n loop do\n begin\n message = client.receive\n rescue Exception => e\n STDERR.puts \"Error: #{e.message}\"\n return\n end\n\n case message\n when :EOF\n return\n when :SKIP\n next\n when JoinRoom\n created, reason = create_or_join_room message[:name], client\n if created\n client.send Success.build(\"Joined #{message[:name]}.\")\n else\n client.send Error.build(reason)\n end\n when RequestRoomList\n room_list = @client_info_lock.synchronize { @rooms.keys.dup }\n client.send RoomList.build(room_list)\n when LeaveRoom\n left, reason = leave_room message[:name], client\n if left\n client.send Success.build(\"Left #{message[:name]}.\")\n else\n client.send Error.build(reason)\n end\n when RequestRoomMemberList\n client.send room_members(message[:name])\n when Say\n speak(message[:room], message[:message], client)\n room = message[:room]\n when Disconnect\n return\n when Whisper\n recipient, message = whisper(message[:to], client, message[:message])\n recipient.socket.send message\n else\n STDOUT.puts \"[Debug] unrecognized message received:\"\n p message\n end\n end\n end", "def send_to_clients(msg)\n EM.schedule do\n @clients.each do |socket|\n socket.send msg\n end\n end\n end", "def handle_client\n \t\t\t\tcase @state\n \t\t\t\twhen :new\n \t\t\t\t\tputs \"Session #{@id}: receiving hello\" if @@debug\n if @data_buf.length >= 2\n b = @data_buf.slice!(0,2)\n unless b.unpack(\"n\")[0] == 0x0002\n close_connection \n @data_suf = false\n end\n @state = :recv_key\n else\n @data_suf = false\n end\n \t\t\t\twhen :recv_key\n \t\t\t\t\tputs \"Session #{@id}: receiving key\" if @@debug\n if @data_buf.length >= 64\n \t\t\t\t\tb = @data_buf.slice!(0,64)\n \t\t\t\t\tb1 = @bot.rsakey.private_decrypt(b)\n \t\t\t\t\tiv = b1[0,16]\n \t\t\t\t\tkey = b1[16,32]\n \t\t\t\t\t@aes_send = AESStream.new(key,iv)\n \t\t\t\t\t@aes_recv = AESStream.new(key,iv)\n \t\t\t\t\tb1[0,16] = OpenSSL::Random.random_bytes 16\n \t\t\t\t\tb = @bot.rsakey.public_encrypt(b1)\n \t\t\t\t\tsend_data b\n \t\t\t\t\t@state = :recv_verify\n else\n @data_suf = false\n end\n \t\t\t\twhen :recv_verify\n \t\t\t\t\tputs \"Session #{@id}: receiving verification\" if @@debug\n if @data_buf.length >= 3\n \t\t\t\t\tb = @data_buf.slice!(0,3)\n \t\t\t\t\tout = @aes_recv.decrypt(b)\n \t\t\t\t\treturn false unless out == \"1\\r\\n\"\n \t\t\t\t\tputs \"Session #{@id}: repeating verification\" if @@debug\n \t\t\t\t\tputs \"Session #{@id}: ready\" if @@debug\n send_data b\n \t\t\t\t\t@state = :connected\n else\n @data_suf = false\n end\n \t\t\t\twhen :connected\n \t\t\t\t\tputs \"Session #{@id}: receiving block\" if @@debug\n \t\t\t\t\tb = @data_buf\n @data_buf = \"\"\n @data_suf = false\n if b.length > 0\n out = @aes_recv.decrypt(b)\n @bot.process(out, @peer)\n end\n \t\t\t\tend\n end", "def message( msg, sender )\n @clients.each do |client|\n client.sock.puts \"#{sender}: #{msg}\" unless sender.port == client.port\n end\n log( \"[message] #{sender}: #{msg}\" )\n end", "def listen_for_user_messages(username, client)\n loop {\n msg = client.gets.chomp\n # send a braodcast message, a message for all connected users, but not to self\n @connections[:clients].each do |other_name, other_client|\n unless other_name == username\n other_client.puts \"#{username}: #{msg}\"\n end\n end\n }\n end", "def write_incoming_messages_to_client(nickname, client_reader, socket)\n Thread.new do\n # 监视 client 输入, 然后将消息 push 到服务端.\n while incoming = client_reader.gets\n unless incoming.start_with?(nickname)\n puts incoming\n socket.puts incoming\n end\n end\n end\nend", "def receive_data data\n rdata = data.split(\"\\n\")\n rdata.each do |line|\n puts \"#{self} received <<< #{line}\"\n # the echo part\n send_data \">>>you sent: #{line}\\n\"\n # Close the connection when the client tells us to.\n close_connection if line =~ /quit/i\n end\n end", "def get_messages()\n @@log.debug \"#{self.class} get messages starts\"\n #\n eof_msg_not_received = true\n loop_count = 0\n #\n headers = {\"persistent\" => true, \"client-id\" => @client_id,\n \"ack\" => @runparms.ack}\n #\n # Do this until the EOF message is received.\n #\n while (eof_msg_not_received)\n loop_count += 1\n @@log.debug \"Client loop count: #{loop_count}\"\n #\n client = Stomp::Client.open(@runparms.userid, @runparms.password, \n @runparms.host, @runparms.port)\n @@log.debug \"next subscribe starts\"\n received = nil\n client.subscribe(@queue_name, headers ) do |message|\n #\n lmsg = \"Got Reply: ID=#{message.headers['message-id']} \"\n lmsg += \"BODY=#{message.body} \"\n lmsg += \"on QUEUE #{message.headers['destination']}\"\n @@log.debug \"#{lmsg}\"\n #\n proc_message(message)\n #\n if @runparms.ack == \"client\"\n @@log.debug \"subscribe loop, sending acknowledge\"\n client.acknowledge(message)\n end\n #\n if message.body == Runparms::EOF_MSG\n @@log.debug \"#{self.class} should be done\"\n eof_msg_not_received = false\n break\n end\n received = message\n end # end of subscribe\n @@log.debug \"#{self.class} Starting to sleep\"\n sleep 1.0 until received\n @@log.debug \"#{self.class} Ending sleep, closing client\"\n client.close()\n received = nil\n @@log.debug \"#{self.class} getter client loop ending\"\n end\n @@log.debug \"#{self.class} getter client ending\"\n end", "def listen_user(client)\n\t\tloop do\n\t\t\t# Revisamos si la conexion se cerro\n\t\t\tbreak if client.eof?\n\t\t\t# optenemos el mensaje del cliente\n\t\t\tmessage = client.gets.chomp\n\t\t\t# Revisamos si es un mensaje\n\t\t\tif message[0] == \"r\"\n\t\t\t\tbroadcast_message(message, client)\n\t\t\telse\n\t\t\t\t# lo retransmitimos a todos los demas clientes\n\t\t\t\tbroadcast(message)\n\t\t\tend\n\t\tend\n\tend", "def run\n listen\n broadcast\n loop do\n sleep(10)\n @all_clients.each {|client| client.puts \"Krazy Joe #{KJ_VERBS.sample} #{KJ_POS.sample} #{KJ_NOUNS.sample}!\"} \n end\nend", "def process_client(client, buffer); end", "def run\n loop do\n memcached = Memcached.new # each client has its oun cache storage\n new_client = @tcp_Server.accept # when a new client connects to the server\n client_handler_id = rand(999999).to_s\n client_handler = ClientHandler.new(id: client_handler_id, clientSocket: new_client, memcached: memcached)\n @@clients << client_handler\n\n Thread.start(client_handler) do |handler| # open a new thread for each accepted connection\n # Here we inform the client of the connections. It's human made, so can be removed if not needed\n puts \"New connection established! Now #{@@clients.length()} clients :>\"\n puts \"WAITING FOR REQUESTS\"\n handler.send(\"Server: Connection established with Client Handler ID: #{client_handler_id}\")\n handler.send(\"Server: You are the client ##{@@clients.length()}\")\n handler.send(\"Server: You may introduce commands now\")\n listen_requests(handler) # allow communication\n end\n end.join\n end", "def broadcast_message(message, rclient)\n\t\[email protected] do |client|\n\t\t\tclient.puts message unless client == rclient\n\t\tend\n\tend", "def on_message client, data\n controller(client).on_message(data)\n end", "def broadcast(message)\n\t\[email protected] do |client|\n\t\t\tclient.puts message\n\t\tend\n\tend", "def send_msg(conn,args)\n p = @app.get_client(conn) #pega objeto Player da lista de clientes\n unless p.nil?\n @app.broadcast(Message.new('chat','txt',\n {'author' => CGI::escapeHTML(p.to_s), 'msg' => CGI::escapeHTML(args['msg'])}\n )) #envia a mensagem para todos os clientes\n end\n end", "def get_messages()\n @@log.debug \"getter client starting, thread is: #{Thread.current}\"\n received = nil\n #\n # Note: in the subscribe loop there is actually a separate\n # thread, known as the 'callback listener'!.\n #\n count = 0\n @client.subscribe(@queue_name,\n {\"persistent\" => true, \"client-id\" => @client_id,\n \"ack\" => @ack} ) do |message|\n @@log.debug \"subscribe loop, thread is: #{Thread.current}\"\n lmsg = \"Got Reply: ID=#{message.headers['message-id']} \"\n lmsg += \"BODY=#{message.body} \"\n lmsg += \"on QUEUE #{message.headers['destination']}\"\n @@log.debug \"#{lmsg}\"\n received = message\n count += 1\n if @ack == \"client\"\n @@log.debug \"subscribe loop, sending acknowledge\"\n @client.acknowledge(received)\n end\n end\n #\n # Make sure this sleep time is sufficiently large, but only as large as\n # really required! There must be sufficient time for:\n # 1) The stomp server to dequeue all the messages in the queue\n # 2) The stomp server will then transmit these messages\n # 3) The consumer/getter (this code) then processes the messages received.\n #\n # If this is not done, this consumer/getter will appear to 'lose' messages,\n # because the main thread wakes up, sees 'received', and closes the client\n # connection prematurely.\n #\n # This anomaly is *much* more apparent with stompserver than with AMQ. It\n # appears to me that AMQ enqueues, and dequeues messages much more quickly,\n # which covers this up in many cases.\n #\n # Later note: The above paragraph may not be correct. Caution advised.\n #\n sleep 3 until received\n #\n @client.close\n @@log.debug \"getter client received count: #{count}\"\n @@log.debug \"getter client ending, thread is: #{Thread.current}\"\n end", "def event_incoming_chat(client, msg)\nend", "def broadcast message\n @clients.keys.each do |key|\n notify key, message\n end\n end", "def write_incoming_messages_to_client(nickname, client_reader, socket)\n Thread.new do\n while incoming = client_reader.gets\n unless incoming.start_with?(nickname)\n puts incoming\n socket.puts incoming\n end\n end\n end\nend", "def dispatch(messages)\n with_connection do |connection|\n connection.write(messages)\n connection.read if messages.last.replyable?\n end\n end", "def process_messages\n # Check status for all streams, reopen as necessary\n @streams.each { |_, stream| try { stream.keep_alive } }\n\n # Actual processing of incoming messages happens in event callbacks\n # Oбрабатываем пришедшее сообщение в интерфейсах обратного вызова\n @conn.ProcessMessage2(100)\n end", "def event_incoming_client_control(client, peer, cmd, *args)\nend", "def start\n @quit = nil\n @socket = self.connect()\n self.on_message(/^PING/) { |event|\n self.send_raw_line(\"PING \"+event[:matchdata].post_match)\n }\n self.on_server_message(353) { |event|\n }\n self.on_server_message(376) do |event|\n if @password and !@authenticated then\n self.message 'NickServ', \"IDENTIFY #{@password}\"\n @authenticated = true\n end\n @channels.each { |channel|\n if channel.kind_of? Hash then\n self.send_raw_line(\"JOIN \"+channel.keys.first+\" \"+channel.values.first)\n else\n self.send_raw_line(\"JOIN \"+channel)\n end\n }\n end\n \n self.send_raw_line(\"USER \"+@nickname+\" \"+@nickname+\" \"+@nickname+\" \"+@nickname)\n self.send_raw_line(\"NICK \"+@nickname)\n begin\n while line = @socket.gets\n handle_raw_line(line) \n end\n rescue IOError => ioe\n raise ioe unless @quit\n end\n end", "def start\n\t\tloop do\n\t\t\t@client = @server.accept # Wait for a client to connect\n\t\t\[email protected] \"220 ready\\r\\n\" # 220 - the server is ready\n\n\t\t\t# authentication (we assume that the client does this correctly)\n\t\t\t@user = @client.gets.gsub(\"\\r\\n\", \"\") # => USER\n\t\t\[email protected] \"331\\r\\n\" # => USER ok\n\n\t\t\t@pass = @client.gets.gsub(\"\\r\\n\", \"\") # => PASS\n\t\t\[email protected] \"230\\r\\n\" # => PASS ok\n\n\t\t\twhile req = @client.gets\n\t\t\t\treq.gsub!(\"\\r\\n\", \"\")\n\n\t\t\t\t# XXX not really needed since no QUIT signal is sent by FCP\n\t\t\t\tif req == \"QUIT\"\n\t\t\t\t\[email protected] \"221\\r\\n\" # => QUIT ok, bye!\n\t\t\t\t\[email protected]\n\t\t\t\t\t@client = nil\n\t\t\t\t\tbreak\n\t\t\t\tend\n\n\t\t\t\ttmp = req.split(\" \")\n\t\t\t\tcmd, args = tmp[0], tmp[1..tmp.length-1]\n\n\t\t\t\tif !SUPPORTED_CMD.include?(cmd)\n\t\t\t\t\[email protected] \"500\\r\\n\"\n\t\t\t\t\tnext\n\t\t\t\tend\n\n\t\t\t\tself.__send__(\"cmd_#{cmd.downcase}\", args)\n\t\t\tend\n\t\tend\n\tend", "def receiveMessage(client)\n while msg_str = client.gets\n # Ensures the message is valid\n if (msg_str.length >= Msg::LENGTH + 1 and Msg.new(msg_str.chop).validate)\n $mutex.synchronize {\n msg = Msg.new(msg_str.chop)\n fragment_seq = msg.getConfig(\"fragment_seq\")\n fragment_num = msg.getConfig(\"fragment_num\")\n\n # Checks to see if the message was fragmented\n if fragment_seq == 0\n runOperation(msg, client)\n else\n $receiver_buffer << msg\n if fragment_num == fragment_seq\n assembled_msg = assembleFragments($receiver_buffer)\n $receiver_buffer.clear()\n runOperation(assembled_msg, client)\n end\n end\n } \n end\n # We need this sleep because Ruby will have a difficult time with memory management\n sleep(0.01)\n end\nend", "def sendMsgCallBack(msg, client)\n message_arr = msg.getMessage().split(\" \")\n \n # Removes and stores the src and dst from the message\n src = message_arr.shift()\n dst = message_arr.shift()\n to_print = \"SNDMSG: %s --> %s\"\n\n # If the destination reached the right host, it will print out the correct message\n # If not, it will forward it to the next client\n if dst == $hostname\n message_arr = message_arr.join(\" \")\n STDOUT.puts(to_print % [src, message_arr])\n else\n k = $next[dst]\n forward_client = $clients[k]\n sendMessage(forward_client, msg)\n end\nend", "def receive_data data\n rdata = data.split(\"\\n\")\n rdata.each do |line|\n puts \"#{self} received <<< #{line}\"\n # the echo part\n send_data \">>>you sent: #{line}\\n\"\n close_connection if line =~ /quit/i\n end\n end" ]
[ "0.73470896", "0.7064501", "0.69389194", "0.69049066", "0.68902683", "0.68148494", "0.680604", "0.67075753", "0.66322184", "0.6594547", "0.65687734", "0.65055674", "0.649664", "0.64837456", "0.6478959", "0.646703", "0.64556307", "0.64452773", "0.6444162", "0.64072937", "0.63612777", "0.63527054", "0.63505477", "0.6345503", "0.63241374", "0.6303872", "0.62710834", "0.6263596", "0.6263269", "0.6254819" ]
0.714587
1
Helper for model classes. Allows for convenient instantiation of current athlete. This is completely agnostic to class type, it can be a DB model, a PORO, etc. Usage: class Account Strava::Athlete Can also perform lookup through another method: class User < ApplicationRecord has_one :account include Strava.model as: :athlete, via: 'account.token', id: 'account.strava_id' end
def model(as: :strava_athlete, via: :access_token, id: nil) Module.new.tap do |mod| str = <<~EOF def self.included(base) base.send(:define_method, :#{as}) { ::Strava::Athlete.new(#{id ? "{'id' => #{id}}" : '{}' }, token: #{via}, current: true) } end EOF mod.class_eval str end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def associate_one(person, account_class)\n return unless person\n\n account = account_class.find_by_secdn(person.dn)\n\n new(person, account)\n end", "def ar_resource\n return unless type && id\n return unless self.class.union_models.include?(type.to_sym)\n\n klass = type.classify.constantize rescue nil\n return unless klass\n klass.find_by_id(id)\n end", "def model_class_name\n options[:model] ? options[:model].classify : \"Account\"\n end", "def class_with_model_name # :nodoc:\n self.class_without_model_name.tap do |c|\n c.instance_variable_set('@_model_name', @model_name)\n (class << c; self; end).send(:define_method,:model_name) do\n model_namer = Struct.new(:name).new(self.instance_variable_get('@_model_name'))\n ActiveModel::Name.new(model_namer)\n end\n end\n end", "def find_athlete\n @athlete = Athlete.find(params[:athlete_id])\n end", "def access_token_model\n @access_token_model ||= access_token_class.constantize\n end", "def display_resource(athlete)\n \"#{athlete.first_name} #{athlete.last_name}\"\n end", "def associated_class\n self[:class] ||= self[:class_name].constantize\n end", "def acls\n @acls ||= SpaceAcls.new(self)\n end", "def tenant_class\n @tenant_class ||= if self.model.respond_to?(:call)\n self.model.call\n elsif self.model.respond_to?(:constantize)\n self.model.constantize\n else\n self.model\n end\n end", "def associated_class\n if options[:class_name]\n options[:class_name].constantize\n else\n klass.relative_const_get(attribute.to_s.camelize)\n end\n end", "def associated_class\n self[:class] ||= self[:class_name].constantize\n end", "def model(class_or_scope, options = nil)\n ActiveSupport.on_load(:active_record, yield: true) do\n class_or_scope = class_or_scope.constantize if class_or_scope.is_a?(String)\n options ||= {}\n conditions = options.delete(:conditions)\n\n @ar_scoped = conditions ? class_or_scope.where(conditions) : class_or_scope\n @ar_aggregate = AGGREGATES.find { |key| options.has_key?(key) }\n @ar_column = options.delete(@ar_aggregate)\n raise \"Cannot use multiple aggregates in a single metric\" if AGGREGATES.find { |key| options.has_key?(key) }\n\n @ar_timestamp = options.delete(:timestamp) || :created_at\n @ar_timestamp, @ar_timestamp_table = @ar_timestamp.to_s.split('.').reverse\n @ar_timestamp_table ||= @ar_scoped.table_name\n\n @ar_identity_block = options.delete(:identity)\n\n raise \"Unrecognized options: #{options.keys * ', '}\" unless options.empty?\n\n @ar_scoped.after_create(self)\n extend ActiveRecord\n end\n end", "def active_record_classes\n @active_record_classes ||= [\n AllCasaAdmin,\n CasaAdmin,\n CasaOrg,\n CasaCase,\n CaseContact,\n CaseCourtOrder,\n CaseAssignment,\n ChecklistItem,\n CourtDate,\n ContactType,\n ContactTypeGroup,\n HearingType,\n Judge,\n Language,\n LearningHourType,\n MileageRate,\n Supervisor,\n SupervisorVolunteer,\n User,\n Volunteer\n ]\n end", "def model_class=(_arg0); end", "def meta_def_ar_class\n klass = table_name.to_s.classify\n binder = self.class\n\n @table =\n if binder.const_defined? klass\n binder.const_get klass\n else\n binder.const_set(klass,\n Class.new(ActiveRecord::Base) do # class `TableName` < ActiveRecord::Base\n singleton_class.send(:define_method, :connect) do # def self.connect\n ActiveRecord::Base.establish_connection(binder.connection_data)\n end # end\n end) # end\n end #if\n end", "def set_athlete\n @athlete = Athlete.find(params[:id])\n end", "def set_athlete\n @athlete = Athlete.find(params[:id])\n end", "def set_athlete\n @athlete = Athlete.find(params[:id])\n end", "def set_athlete\n @athlete = Athlete.find(params[:id])\n end", "def create_oauth_strategy_class(keyword)\n class_name = Warden::OAuth::Utils.camelize(keyword.to_s) \n if self.const_defined?(class_name)\n self.const_get(class_name) \n else\n self.const_set(class_name, Class.new(self))\n end\n end", "def set_model_acronym\n @model_acronym = ModelAcronym.find(params[:id])\n end", "def setup_model(opts, current_account:, **)\n opts['model'] = current_account\n end", "def primary_account\n subclass_must_define\n end", "def model_class\n @class_name.constantize\n end", "def show\n @athlete = Athlete.find(params[:id])\n @commentable = @athlete\n @comment = @athlete.comments.new\n end", "def set_adventuring_class\n @adventuring_class = AdventuringClass.find(params[:id])\n end", "def get\n Ata.get self\n end", "def model name, **params\n # <<- CLOSURE_SCOPE\n current = @current # closure scope\n params = @environs.merge params if @environs\n filled_or_maybe = optionality(params)\n params[:class] ||= name.to_s.gsub(/(?:\\A|_)./) { |m| m[-1].upcase }\n # CLOSURE_SCOPE\n\n schema do\n __send__(current, name).__send__(filled_or_maybe, model?: params[:class])\n end\n\n define_helper_methods name\n end", "def user_account_instance\n Account.new\n end" ]
[ "0.52092934", "0.511394", "0.5069212", "0.50299656", "0.5023484", "0.4993129", "0.49767023", "0.49451876", "0.49443752", "0.49165156", "0.4914349", "0.49054357", "0.48659104", "0.4865236", "0.48552924", "0.4853309", "0.48528898", "0.48528898", "0.48528898", "0.48528898", "0.48435202", "0.4838889", "0.48357502", "0.48316702", "0.48286635", "0.482786", "0.48161423", "0.48147175", "0.48032513", "0.47953704" ]
0.723099
0
Reverse the word order of a given string =begin doctest: reverse word order of a string >> s = "This is test line one." >> reverse_word_order(s) => "one. line test is This" doctest: Lines are handled this way >> s = "This is test line one.\nThis is test line two." >> reverse_word_order(s) => "two. line test is This one. line test is This" =end
def reverse_word_order string string.split.reverse.join(' ') end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reverse_word_order(str)\n str.split.reverse.join(' ')\nend", "def word_reverse(str)\n p str.split(' ').reverse.join(' ')\nend", "def wordReverse(string)\n\tp string.split(\" \").reverse().join(\" \")\nend", "def reverse_words(string)\n words = string.split()\n words.each_with_index { |word, index| words[index] = word.reverse() }\n p words.join(\" \")\nend", "def wordReverse (string)\n puts string.split.reverse.join(' ')\nend", "def reverse_words(input_string)\n tokens = input_string.split(' ')\n swap_words(tokens)\nend", "def word_reverse str\n\tstr.split.reverse.join(' ')\nend", "def reverse_words(string)\n p string.split.map!{|word| word.reverse}.join(\" \")\nend", "def reverse_words(string)\n p string.split.map!{|word| word.reverse}.join(\" \")\nend", "def reverse_word_order( s )\n print arr = s.split(' ').reverse.join(' ')\nend", "def reverse_ordering_of_words(s)\n\tsplit_words = s.split('')\n\n\toutput = []\n\tj = split_words.length\n\n\t(0..split_words.length).each do |i|\n\t\toutput[i] = split_words[j]\n\t\tj = j - 1\n\tend\n\n\treturnval = output.join('')\n\treturn returnval\nend", "def wordReverse (str)\nstr.split(' ').reverse.join(' ')\nend", "def wordReverse (string_of_words)\n\n new_string = string_of_words.split(' ').reverse().join(' ')\n puts new_string\n\nend", "def word_reverse(string)\n reversed_word = string.split(' ').reverse().join(' ').reverse()\nend", "def word_reverse (str)\n str.split(' ').reverse.join(' ')\nend", "def reverse_words(s)\n s.split(' ').map(&:reverse!).join(' ')\nend", "def word_reverse(sentence)\n sentence.split(\" \").reverse.join(\" \")\nend", "def reverse_words(my_words)\n # raise NotImplementedError\n return my_words if my_words.nil? || my_words.empty?\n\n i = 0 # starting point of sentence\n j = my_words.length # ending point of sentence\n\n while i < j\n while my_words[i] == \" \" && i < j\n i += 1\n end\n\n word_start = i # starting point of next word in sentence\n\n while my_words[i] != \" \" && i < j\n i += 1\n end\n\n word_end = i - 1 # end point of word in sentence\n\n word_reverse(my_words, word_start, word_end)\n end\n return\nend", "def reverseWords(str) \n str.reverse!\n str.split.map{|word| word.reverse!}.join(\" \")\nend", "def reverse_words(string)\n # reversed_string = string.reverse!\n # reversed_array = reversed_string.split(\" \")\n # p reversed_array\n # reversed_array.sort! {|x, y| y<=>x}\n # p reversed_array\n\n split_string = string.split(\" \")\n split_string.each do |word|\n word.reverse!\n end\n reversed_string = split_string.join(\" \")\n puts reversed_string\nend", "def reverse_words (string)\n if string == \"\"\n p \"\"\n elsif\n words = string.split(\" \")\n words.each { |word|\n word.reverse!\n }\n p words.join(\" \")\nend\nend", "def reverseWords(s)\n s.split(\" \").reverse.join(\" \")\nend", "def reverseWordsLite(str)\n str.reverse!\n wordStart, wordEnd = 0, 0\n str.each_char do |char|\n if char == \" \"\n reverseSubString(str, wordStart, wordEnd-1)\n wordStart = wordEnd + 1\n end\n wordEnd += 1\n end\n reverseSubString(str, wordStart, wordEnd-1)\n str\nend", "def reverse_words(str)\n words = str.split(\" \")\n words.each { |word| word.reverse! }\n return words.join(\" \")\nend", "def reverse_words(word)\n p word.reverse.split.reverse.join(' ')\nend", "def reverse_each_word(string)\n array = string.split\n array.each do |word|\n word.reverse!\n end\n array.join(\" \")\nend", "def wordReverse(string)\n\treverseStr = string.reverse\n\tstringArr = reverseStr.split(' ')\n\tstringArr.map! do |word|\n\t\tword.reverse\n\tend\n\tp stringArr.join(' ')\nend", "def reverse_words(my_words)\n i = 0\n j = 0\n\n if my_words == nil\n return\n end\n\n loop do\n # binding.pry\n until my_words[i] != \" \"\n i += 1\n break if i >= my_words.length - 1\n end\n j = i\n until my_words[j + 1] == \" \" || j == (my_words.length - 1)\n j += 1\n end\n # binding.pry\n string_reverse(my_words, i, j)\n i = j + 2\n # binding.pry\n break if i >= my_words.length - 1\n end\n return my_words\nend", "def wordReverse(sentence) \n\tsentence = sentence.split (\" \")\n\tsentence.each do |words|\n\tend\n\tputs sentence.reverse\nend", "def word_reverse(string)\n reversed_word = string.split(' ').reverse().join(' ')\nend" ]
[ "0.7666444", "0.7598045", "0.7538827", "0.741925", "0.74179643", "0.74103767", "0.740417", "0.7379643", "0.7379643", "0.7373929", "0.73467344", "0.73209673", "0.7309497", "0.7302201", "0.7295405", "0.7286302", "0.72851825", "0.7282557", "0.7274572", "0.72719157", "0.72685456", "0.72554684", "0.7249964", "0.72282237", "0.71996504", "0.7197198", "0.7190241", "0.7179198", "0.71719056", "0.716551" ]
0.77907425
0
define equality between two entities by iterating over instance variables and comparing each field for equality
def ==(entity) rval = true self.instance_variables.each { |variable| rval &= self.instance_variable_get(variable) == entity.instance_variable_get(variable) } rval end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def object_equal(obj1, obj2)\n vars1 = obj1.instance_variables\n vars2 = obj2.instance_variables\n return false unless vars1.length == vars2.length\n # if they don't have exactly the same instance_variables names then return false\n return false unless vars1.map(&:to_s).sort.to_s == vars2.map(&:to_s).sort.to_s\n\n equal = true\n some(vars1, proc { |v|\n val1 = obj1.instance_variable_get(v)\n val2 = obj2.instance_variable_get(v)\n if val1 != val2\n equal = false\n true\n else\n false\n end\n })\n equal\nend", "def ==(other)\n attributes == other.attributes\n end", "def eql?(other)\n return true if equal?(other)\n\n # two instances for different models cannot be equivalent\n return false unless other.kind_of?(model)\n\n # two instances with different keys cannot be equivalent\n return false if key != other.key\n\n # neither object has changed since loaded, so they are equivalent\n return true if repository == other.repository && !dirty? && !other.dirty?\n\n # get all the loaded and non-loaded properties that are not keys,\n # since the key comparison was performed earlier\n loaded, not_loaded = properties.select { |p| !p.key? }.partition do |property|\n attribute_loaded?(property.name) && other.attribute_loaded?(property.name)\n end\n\n # check all loaded properties, and then all unloaded properties\n (loaded + not_loaded).all? { |p| p.get(self) == p.get(other) }\n end", "def ==(other)\n return false if self.class != other.class\n fields.all? do |field|\n name = field[:name]\n instance_variable_get(name) ==\n other.instance_variable_get(name)\n end\n end", "def equality_fields\n [:id, :dealership, :expires, :next]\n end", "def == (other)\n return true if self.equal?(other)\n return false if self.class != other.class\n self.class.fields.all? { |f| self.field_get(f) == other.field_get(f) }\n end", "def ==(other)\n self.class == other.class &&\n self.attributes == other.attributes\n end", "def eql?(other)\n return false if (other.nil? or self.class != other.class)\n ova = other.instance_variables\n iv = instance_variables\n return false if ova.size != iv.size\n iv.each do |vid|\n return false if instance_variable_get(vid) != other.instance_variable_get(vid)\n end\n true\n end", "def ==(other)\n self.class == other.class &&\n attributes == other.attributes\n end", "def == other\n return false unless other.kind_of? self.class\n attribute_of.all? do |key, val|\n val.get == other.__send__(key)\n end\n end", "def ===(other)\n required = self.class.required_attributes\n\n other.respond_to?(:keys) && (common = other.keys & required) &&\n common.size == other.keys.size && common.size == required.size\n end", "def ==(other)\n @klass == other.class && @attributes == strip_active_record(other)\n end", "def ==(other)\n Attribute === other && \n !(Expression === other) &&\n relation == other.relation && \n name == other.name && \n self.alias == other.alias && \n original_relation == other.original_relation\n end", "def eql?(other)\n return false unless self.class.eql?(other.class)\n instance_variables.map do |var|\n instance_variable_get(var).eql?(other.instance_variable_get(var))\n end.all?\n end", "def eql?(obj)\n return false unless obj.is_a?(self.class)\n fields.each do |tag, _|\n if value_for_tag?(tag)\n return false unless (obj.value_for_tag?(tag) && value_for_tag(tag).eql?(obj.value_for_tag(tag)))\n else\n return false if obj.value_for_tag?(tag)\n end\n end\n return true\n end", "def ==(other) # :nodoc:\n @attrs == other.attrs\n end", "def ==(other)\n return false unless other.instance_of? self.class\n attributes == other.attributes\n end", "def ==(other)\n valid = true\n self.instance_variables.each do |v|\n valid &&= instance_variable_get(v) == other.instance_variable_get(v)\n end\n valid\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.send(name) }\n end", "def eql?(other)\n return self.instance_variables.all?{ |v|\n self.instance_variable_get(v).hash == other.instance_variable_get(v).hash\n }\n end", "def ==(other)\n other.present? && self.attributes == other.attributes\n end", "def sync_duplicate_obj_attributes(obj1, obj2)\n duplicate_keys.each do |key|\n unless obj1[key].blank? && obj2[key].blank?\n if obj1[key].blank?\n obj1.send(\"#{key}=\", obj2[key])\n elsif obj2[key].blank?\n obj2.send(\"#{key}=\", obj1[key])\n else # Each obj has a value\n if obj1[key] != obj2[key]\n raise ArgumentError, \"#{key} attribute values on the two objects don't match: #{obj1[key]} vs #{obj2[key]}\"\n end\n end\n end\n end\n end", "def eql?(other)\n return true if equal?(other)\n return false unless self == other\n [:id, :fide_id, :rating, :fide_rating, :title, :gender].each do |m|\n return false if self.send(m) && other.send(m) && self.send(m) != other.send(m)\n end\n true\n end", "def ==(other)\n name == other.name &&\n color == other.color &&\n age == other.age\n end", "def vars_eql?(other,vars=nil)\n vars ||= instance_variables\n vars.each do |var|\n # puts instance_variable_get(var)\n if instance_variable_get(var).respond_to? 'is_eql'\n # puts 'responds to is_eql'\n return false if !(instance_variable_get(var).is_eql other.instance_variable_get(var))\n else\n # puts \"mine: #{instance_variable_get(var)} other: #{other.instance_variable_get(var)}\"\n return false if !(instance_variable_get(var) == other.instance_variable_get(var))\n end\n end\n true\nend", "def ==(other)\n return false if other.nil? || !other.respond_to?(:attributes)\n attributes == other.attributes\n end", "def ==(other)\n if self.class.identity_map_on?\n super\n else\n return false if other.nil?\n other.is_a?(Dynamoid::Document) && hash_key == other.hash_key && range_value == other.range_value\n end\n end", "def equivalentValues(other) # JS == operator\n other.is_a?(Object) && unwrap.eql?(other.unwrap)\n end", "def ==(other)\n self.class == other.class &&\n name == other.name &&\n age == other.age &&\n gender == other.gender &&\n species == other.species &&\n toys == other.toys\n end", "def matches(other)\n other.kind_of?(QueryField) && other.name == @name && other.operation == @operation && other.boost == @boost \n end" ]
[ "0.6365919", "0.6288923", "0.6226688", "0.62169", "0.6111295", "0.6087191", "0.598765", "0.5970042", "0.59560186", "0.59450203", "0.5894917", "0.5863724", "0.58579576", "0.5838317", "0.58370423", "0.58349097", "0.5823593", "0.58083266", "0.5806187", "0.5801017", "0.58009577", "0.5774571", "0.5770725", "0.5765255", "0.5741609", "0.5732007", "0.5704498", "0.5703978", "0.56992567", "0.56987536" ]
0.660682
1
undesignate_package params is passed from 'form_nested_params_for_undesignate'
def undesignate(undesignate_package = nil) packages = undesignate_package ? undesignate_package : @params OrdersPackage.undesignate_partially_designated_item(packages) @package.reload.undesignate_from_stockit_order end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unsolved_params\n \n end", "def drop_extra_params!(form, params)\n form_data = form['properties']['data']['properties']\n allowed_params = form_data['attributes']['properties'].keys rescue nil\n params['data'].fetch('attributes', {}).slice!(*allowed_params) if allowed_params.present?\n end", "def unnovel_params\n params.fetch(:unnovel, {})\n end", "def unparse_params\n @_unparse_params ? @_unparse_params.dup : nil\n end", "def disable_publication\n find_flat\n @flat.pap = false\n @flat.bienici = false\n @flat.leboncoin = false\n @flat.seloger = false\n @flat.facebook = false\n @flat.update!(flat_params)\n redirect_to flat_path(@flat)\n end", "def untouchable_params_attributes #:nodoc:\n { :outfile_id => true }\n end", "def data_package_params\n params.fetch(:data_package, {})\n end", "def purge_nested_form\n self.target_hostnames.find_all{|r| r.marked_for_destruction?}.each do |c|\n c.delete\n end\n end", "def unsubscription_params\n params.require(:unsubscription).permit(:kind, :reason_specific,\n choices_attributes: [:id, :completed, :user_id, :specific])\n end", "def no_group_params\n params.fetch(:no_group, {})\n end", "def unsolved_params\n params.require(:unsolved).permit(:department, :details, :priority, :status, :topic)\n end", "def packege_params\n params.require(:package).permit!\n end", "def unstructured_datum_params\n params.require(:unstructured_datum).permit(:name, :subcriterium_id)\n end", "def deprovision_groups\n @attributes[:deprovision_groups]\n end", "def nontrainer_package_params\n params.require(:nontrainer_package).permit(:freeze_time, package_attributes: [:id, :name, :price])\n end", "def sub_package_params\n params.require(:sub_package).permit(:name, :package_id)\n end", "def institute_package_params\n params.require(:institute_package).permit(:institute_id, :package_id)\n end", "def unuse_file_params\n params.require(:unuse_file).permit(:path)\n end", "def flat_stage_sub_stage_params\n params.fetch(:flat_stage_sub_stage, {})\n end", "def deprovision_behavior\n @attributes[:deprovision_behavior]\n end", "def package_params\n params.require(:package).permit!\n end", "def package_params\n params.require(:package).permit(:client_id, :origin, :destiantion, :arrival_date, :reciver, :status, :po, :ref, :coment, :pack_nr, :unit_ids, :components_ids)\n end", "def normal_params\n reject{|param, val| param_definitions[param][:internal] }\n end", "def filter_fields\n\t \n\t \tremove_attribute(:version)\n\t \tremove_attribute(:op_success)\n\t \tattributes\n\n\t \t\n\t end", "def filter_fields\n\t \n\t \tremove_attribute(:version)\n\t \tremove_attribute(:op_success)\n\t \tattributes\n\n\t \t\n\t end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def tour_package_params\n params.require(:tour_package).permit(:title, :days, :nights, :details, :uuid, :father_name_field, :birthdate_field, :place_of_birth_field,:passport_no_field, :en_name_field,:en_surename_field, :en_father_name_field, :attachment_field, :attachment_message)\n end", "def check_exclude_fields\n=begin\n [:for_index, :for_new, :for_edit, :for_show].each do |key|\n exc= exclude_fields.send(key)\n next if exc # Leave user options if given.\n \n # By default, the foreign key of the parents are assigned on nested resources,\n # so i remove the from the default columns of new\n exclude_fields.send(\"#{key}=\", parent_ids) if key == :for_new && !parent_ids.empty?\n end\n=end\n # Because a single resource can have multiple resource parents,\n # this check is going to be done on \"runtime\" (ie remove the field for the \n # current parent, not all parents' fields)\n end", "def unsubmit(_ = nil)\n # Skip the state validation in answers.\n @unsubmitting = true\n\n unsubmit_current_answers\n self.points_awarded = nil\n self.draft_points_awarded = nil\n self.awarded_at = nil\n self.awarder = nil\n self.submitted_at = nil\n self.publisher = nil\n self.published_at = nil\n end", "def group_product_params\n params.fetch(:group_product, {})\n end" ]
[ "0.5887348", "0.5579017", "0.550668", "0.5481046", "0.5415299", "0.5408723", "0.5318543", "0.5298929", "0.5264611", "0.523779", "0.5198984", "0.51949567", "0.51777846", "0.50805336", "0.5054774", "0.50440156", "0.5003783", "0.49490967", "0.49228296", "0.4879456", "0.48700336", "0.4869865", "0.48256123", "0.48128933", "0.48128933", "0.47905558", "0.47799262", "0.47639984", "0.4763426", "0.47562015" ]
0.7438915
0
Tell this track's channel to use the given instrument, and also set the track's instrument display name.
def instrument=(instrument) @events << MIDI::ProgramChange.new(@channel, instrument) super(GM_PATCH_NAMES[instrument]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def instrument=(instrument)\n @events << \nMIDI::ProgramChange.new(@channel, instrument)\n super(MIDI::GM_PATCH_NAMES[instrument])\n end", "def instrument=(instrument)\n @events << MIDI::ProgramChange.new(@channel, instrument)\n super(MIDI::GM_PATCH_NAMES[instrument])\n end", "def instrument=(instrument)\n\t @events << \nMIDI::ProgramChange.new(@channel, instrument)\n\t super(MIDI::GM_PATCH_NAMES[instrument])\n\t end", "def instrument=(instrument)\n\t @events << \nMIDI::ProgramChange.new(@channel, instrument)\n\t super(MIDI::GM_PATCH_NAMES[instrument])\n\t end", "def instrument=(instrument)\n\t @events << \nMIDI::ProgramChange.new(@channel, instrument)\n\t super(MIDI::GM_PATCH_NAMES[instrument])\n\t end", "def instrument=(instrument)\n\t @events << \n MIDI::ProgramChange.new(@channel, instrument)\n\t super(MIDI::GM_PATCH_NAMES[instrument])\n\t end", "def set_instrument\n @instrument = Instrument.find(params[:id])\n end", "def set_instrument\n @instrument = Instrument.find(params[:id])\n end", "def set_instrument\n @instrument = Instrument.find(params[:id])\n end", "def set_instrument\n @instrument = Instrument.find(params[:id])\n end", "def set_instrument\n @instrument = Instrument.find(params[:id])\n end", "def set_instrument\n self.instrument_id = self.code_list.instrument_id\n end", "def set_instrument\n self.instrument_id = self.code_list.instrument_id\n end", "def set_attr band, musician #, instrument\n @band = band\n @musician = musician\n # @instrument = instrument\n end", "def set_instrument\n @instrument = Instrument.find(params[:id])\n end", "def set_instrument\n @instrument = Instrument.find(params[:id])\n end", "def set_label(val, instrument)\n self.category = Category.find_by label: val, instrument_id: instrument.id\n if self.category.nil?\n self.category = Category.create label: val, instrument: instrument\n end\n end", "def set_instrument_preference\n @instrument_preference = InstrumentPreference.find(params[:id])\n end", "def instrument_name\n system_name\n end", "def label=(val)\n set_label(val, code_list.instrument)\n end", "def instr_desc\n instr_data = $instruments[values]\n\n if instr_data == nil\n return \"- Unknown instrument\"\n end\n\n result = \"\"\n\n for possible in instr_data\n result += \"- Instrument ##{possible[:instrument]} \" \\\n + \"(#{possible[:name]}) \" \\\n + \"v#{possible[:voice]}\\n\"\n end\n\n result\n end", "def display_name(display_name)\n @display_name = display_name\n self\n end", "def setNameSound _obj, _args\n \"_obj setNameSound _args;\" \n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end", "def display_name=(value)\n @display_name = value\n end" ]
[ "0.6368076", "0.62432176", "0.6185505", "0.6185505", "0.6185505", "0.61758345", "0.60637724", "0.60637724", "0.60637724", "0.60637724", "0.60637724", "0.58738804", "0.58738804", "0.5730139", "0.5724428", "0.5724428", "0.554737", "0.53196824", "0.5193287", "0.51252496", "0.5064646", "0.50138617", "0.50051427", "0.4973239", "0.4973239", "0.4973239", "0.4973239", "0.4973239", "0.4973239", "0.4973239" ]
0.63136387
1
Configure Vedeu using a simple configuration DSL.
def configure(&block) fail InvalidSyntax, '`configure` requires a block.' unless block_given? Vedeu::Configuration.configure(&block) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def configure(args = [], opts = {}, &block)\n @options.merge!(opts)\n\n @options.merge!(Config::API.configure(&block)) if block_given?\n @options.merge!(Config::CLI.configure(args)) if args.any?\n\n Vedeu::Renderers.renderer(*@options[:renderers])\n\n Vedeu::Configuration\n end", "def configure(&block); end", "def configure(&block); end", "def generate_vagrant_config\n template = Souffle::Template.new('Vagrantfile.erb')\n temp_binding = OpenStruct.new\n temp_binding.version = Souffle::VERSION\n \n template.render(temp_binding)\n end", "def configure; end", "def configure!(parser); end", "def configure(opts = {}, &block)\n @options.merge!(opts)\n\n @options.merge!(Config::API.configure(&block)) if block_given?\n\n Vedeu::Renderers.renderer(*@options[:renderers])\n\n Vedeu::Configuration\n end", "def configure(&block)\n Fastfood::Configuration.instance_eval( &block )\n end", "def new_config_content\n return <<-VHOST\n\n# vh configuration file\nInclude #{@target}\n# /vh configuration file\n VHOST\n end", "def configure(&block)\n config.run_callbacks(:configure) do\n config.instance_eval(&block)\n end\n end", "def configure\n puts 'Configuring Vault'\n vault = secure_vault\n vault.sys.mount('testing', 'kv', 'Mount used for testing purposes only')\n vault.logical.write('testing/test', value: @random_string)\n end", "def setup\n @configure = Hatemile::Util::Configure.new\n end", "def configure\n\n # config file default options\n configuration = {\n :options => {\n :verbose => false,\n :coloring => 'AUTO'\n },\n :mount => {\n :source => {\n :name => nil\n },\n :mountpoint => {\n :name => nil\n },\n :passphrasefile => {\n :name => 'passphrase'\n },\n :keyfile => {\n :name => 'encfs6.xml'\n },\n :cmd => nil,\n :executable => nil\n },\n :unmount => {\n :mountpoint => {\n :name => nil\n },\n :cmd => nil,\n :executable => nil\n },\n :copy => {\n :source => {\n :name => nil\n },\n :destination => {\n :name => nil\n },\n :cmd => nil,\n :executable => nil\n }\n }\n\n # set default config if not given on command line\n config = @options[:config]\n unless config\n config = [\n File.join(@working_dir, \"revenc.conf\"),\n File.join(@working_dir, \".revenc.conf\"),\n File.join(@working_dir, \"config\", \"revenc.conf\"),\n File.expand_path(File.join(\"~\", \".revenc.conf\"))\n ].detect { |filename| File.exists?(filename) }\n end\n\n if config && File.exists?(config)\n # rewrite options full path for config for later use\n @options[:config] = config\n\n # load options from the config file, overwriting hard-coded defaults\n config_contents = YAML::load(File.open(config))\n configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash)\n else\n # user specified a config file?, no error if user did not specify config file\n raise \"config file not found\" if @options[:config]\n end\n\n # the command line options override options read from the config file\n @options = configuration[:options].merge!(@options)\n @options.symbolize_keys!\n\n # mount, unmount and copy configuration hashes\n @options[:mount] = configuration[:mount].recursively_symbolize_keys! if configuration[:mount]\n @options[:unmount] = configuration[:unmount].recursively_symbolize_keys! if configuration[:unmount]\n @options[:copy] = configuration[:copy].recursively_symbolize_keys! if configuration[:copy]\n end", "def configure(&block)\n instance_eval(&block)\n end", "def configure(&block)\n instance_eval(&block)\n end", "def configure(&block)\n configurator.configure(&block)\n end", "def configure &block\n @config_helper = ConfigHelper.new(&block)\n end", "def configure(&block)\n self.instance_eval(&block)\n end", "def configure( &block )\n @configuration = block\n end", "def configure\n end", "def configure\n send_command \"--configure\"\n end", "def configure(&block)\n yield config\n end", "def configure &block\n\t\tinstance_eval &block\n\tend", "def setup(&block)\n Config.setup(&block)\n end", "def configure\n if @opts[:docker]\n Souschef::Print.info 'Creating Docker configuration .kitchen.local.yml'\n write(:docker, Souschef::Testkitchen::Docker.new(@cookbook).yaml)\n end\n if @opts[:solusvm]\n Souschef::Print.info 'Creating SolusVM configuraton .kitchen.local.yml'\n write(:solusvm, Souschef::Testkitchen::Solusvm.new(@cookbook).yaml)\n end\n\n Souschef::Print.info 'Creating Vagrant configuration in .kitchen.yml'\n write(:virtualbox, Souschef::Testkitchen::Virtualbox.new(@cookbook).yaml)\n end", "def default_config\n UvConfiguration.new\n end", "def configure(&blk)\n instance_eval &blk\n end", "def configure(root_config)\n end", "def configure(root_config)\n end", "def configure &blk\n instance_eval &blk\n end" ]
[ "0.650775", "0.6432643", "0.6432643", "0.64055663", "0.61986077", "0.6190462", "0.6190431", "0.6138053", "0.6106681", "0.6049971", "0.60169464", "0.5942714", "0.5928619", "0.59283185", "0.59283185", "0.59080756", "0.58889747", "0.58865875", "0.588558", "0.58774656", "0.58582926", "0.5848601", "0.584705", "0.5843621", "0.58405286", "0.5808483", "0.5807427", "0.5795062", "0.5795062", "0.57876635" ]
0.7594411
0
Register an interface by name which will display output from a event or command. This provides the means for you to define your application's views without their content.
def interface(name = '', &block) API::Interface.define({ name: name }, &block) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def register(interface)\n InvalidInterfaceError.check(interface)\n \n interfaces[interface.to_s.demodulize.underscore.to_sym] = interface\n end", "def register_ui thing\n @uis << thing\n end", "def name\n\t\t\"Interface Fingerprinter\"\n\tend", "def register_outputter(name, klass, method_name)\n outputters[name] = [klass, method_name]\n end", "def name\n\t\t\"Stdapi: User interface\"\n\tend", "def name\n\t\t\"Stdapi: User interface\"\n\tend", "def name\n\t\t\"Stdapi: User interface\"\n\tend", "def add_output(name, handler)\n @outputs[name] = handler\n end", "def interface(name, &block)\n raise Vedeu::Error::MissingRequired unless name\n raise Vedeu::Error::RequiresBlock unless block_given?\n\n attributes = { client: client(&block), name: name }\n\n interface = Vedeu::Interfaces::Interface\n .build(attributes, &block)\n .store\n\n add_buffers!(name)\n add_cursor!(name)\n add_editor!(name) if interface.editable?\n add_focusable!(name)\n add_keymap!(name)\n\n interface\n end", "def view(name, &block)\n @views[name] = block\n end", "def add_output(type, *args)\n class_name = type.to_s.capitalize\n klass = Drone::Interfaces.const_get(class_name)\n @output_modules << klass.new(*args)\n end", "def output(name, &block)\n raise \"Endpoint :#{@name} declares the output :#{name} twice.\" if @outputs.find { |o| o.name == name }\n output = Output.new name\n @outputs << output\n raise 'You must pass a block when calling `output`.' unless block_given?\n output.instance_eval(&block)\n output\n end", "def render_interface(stream)\n @render_interface = true\n render_function_declaration(stream) if live? && (public? || private?)\n end", "def use(name)\n Vedeu::Interface.new(Vedeu::Interfaces.find(name))\n end", "def add(interface_name)\n model.add(interface_name)\n end", "def views(name = nil)\n raise NotImplementedError, \"views is an abstract method\"\n end", "def output\n UI\n end", "def register(view_hash)\n self.class.register view_hash\n end", "def register(ui, event_filter)\n @event_filter = event_filter\n ui.register(self)\n end", "def set_interface(name)\n\tif !name\n\t\tputs 'please enter audio output interface name.'\n\t\treturn -1\n\tend\n\n\tdevs = CoreAudio.devices\n\n\ttgt = devs.find{|dev| dev.name.index(name)}\n\tif !tgt\n\t\tp \"no match interface #{name}\"\n\t\treturn -1\n\tend\n\n\tCoreAudio.set_default_output_device(tgt)\n\tp \"select default output audio interface #{tgt.name}\"\nend", "def output\n send(\"output_#{@type}\")\n end", "def init_ui(input, output)\n\t\tconsole.init_ui(input, output)\n\t\tconsole.set_log_source(log_source)\n\n\t\tsuper\n\tend", "def init_ui(input, output)\n\t\tself.user_input = input\n\t\tself.user_output = output\n\t\tconsole.init_ui(input, output)\n\t\tconsole.set_log_source(log_source)\n\n\t\tsuper\n\tend", "def register\n end", "def register\n self.class.definitions[name] = self\n self\n end", "def default_output\n name\n end", "def show\n @interface = Interface.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @interface }\n end\n end", "def new_interface(message)\n if @gui\n Commitsu::Interface::Gui.new(message)\n else\n Commitsu::Interface::Text.new(message)\n end\n end", "def print(*args)\n @interface.print(*args)\n end", "def print(*args)\n @interface.print(*args)\n end" ]
[ "0.5812963", "0.57885903", "0.57239634", "0.5534636", "0.54944015", "0.54944015", "0.54944015", "0.5466492", "0.5456569", "0.5287779", "0.52860355", "0.5271038", "0.526901", "0.5255215", "0.5211872", "0.51988626", "0.51811814", "0.51612604", "0.5107999", "0.5107547", "0.5058994", "0.5017478", "0.4958729", "0.49557424", "0.4908055", "0.49030155", "0.48959607", "0.48896584", "0.48888323", "0.48888323" ]
0.59082633
0
Trigger a registered or system event by name with arguments. If the event stored returns a value, that is returned. If multiple events are registered for a name, then the result of each event will be returned as part of a collection.
def trigger(name, *args) Events.use(name, *args) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def registered_events\n return repository.find(name) if repository.registered?(name)\n\n Vedeu::Events::Aliases.find(name).map do |event_name|\n Vedeu::Events::Trigger.trigger(event_name, *args)\n end\n\n []\n end", "def registered_events\n return repository.find(name) if repository.registered?(name)\n\n Vedeu::Events::Aliases.find(name).map do |event_name|\n Vedeu::Events::Trigger.trigger(event_name, *args)\n end\n\n []\n end", "def trigger_event(event_name, *args)\n event_callbacks[event_name].each do |cb|\n begin\n cb.call(*args)\n rescue Exception => ex\n warn \"[OnStomp/Event] triggering #{event_name} raised an error: #{ex}\"\n end\n end\n end", "def trigger\n Vedeu.log(type: :event,\n message: \"No action for: '#{name.inspect}'\") if results.empty?\n\n return results[0] if results.one?\n\n results\n end", "def trigger\n if Vedeu.config.debug? && results.empty?\n Vedeu.log(type: :nonevent,\n message: \"No action for: '#{name.inspect}'\")\n end\n\n return results[0] if results.one?\n\n results\n end", "def fire_events(event_name, step_result)\n events_to_fire = events.fetch(event_name, missing_events)\n if events_to_fire.empty?\n fail EventMissingError, \"No event registered for #{event_name}\"\n end\n events_to_fire.each_with_index do |event, i|\n execute_event(event_name, event, step_result)\n end\n @last_event_fired = event_name\n end", "def trigger(event, *params, &block)\n catch :return do\n return_value = nil\n __handlers[event.to_sym].each do |handler|\n return_value = handler.call(*params, &block)\n end\n return_value\n end\n end", "def trigger(event_name, payload = {})\n handlers.each do |handler|\n next unless handler.respond_to?(:trigger)\n\n handler.trigger(self, event_name, payload)\n end\n end", "def trigger(event_name, args, object, scope: nil)\n field = @schema.get_field(\"Subscription\", event_name)\n if !field\n raise \"No subscription matching trigger: #{event_name}\"\n end\n\n event = Subscriptions::Event.new(\n name: event_name,\n arguments: args,\n field: field,\n scope: scope,\n )\n execute_all(event, object)\n end", "def exec_hook(event_name, *args, &block)\n @hooks[event_name] ||= []\n\n # silence warnings to get rid of 1.8's \"warning: multiple values\n # for a block parameter\" warnings\n Pry::Helpers::BaseHelpers.silence_warnings do\n @hooks[event_name].map do |hook_name, callable|\n begin\n callable.call(*args, &block)\n rescue RescuableException => e\n errors << e\n e\n end\n end.last\n end\n end", "def fire(event_type, *arguments)\n @events[event_type].each do |event|\n event.call(*arguments)\n end if event_is_defined(event_type)\n end", "def dispatch(event, *args)\n result = nil\n @events[event]&.each { |hdl| result = hdl.call(*args) }\n result\n end", "def trigger_event(eventSymbol, *args)\n engine.send(eventSymbol, *args)\n end", "def event(*args)\n name, to = args.first.is_a?(Symbol) ? args.first : args.first.to_a.flatten\n @events[name.to_sym] = Event.new(name, to)\n end", "def fire(event_name, opts = {})\n adapter.fire name_with_suffix(event_name), opts do\n yield opts if block_given?\n end\n end", "def dispatch_event(event_name, args)\n @event_message_channels[event_name].each do |message_channel|\n message_channel.send [:event, event_name, args]\n end\n end", "def trigger(event_name, data)\n\t\[email protected] do |name, component|\n\t\t\t# Don't do this for flat tags, eg. :name\n\t\t\tcomponent.receive_event(event_name, data) if component.respond_to?(:receive_event)\n\t\tend\n\tend", "def execute_hook(event_name, args)\n @hook_manager.exec_hook(event_name, args)\n end", "def event_for(*args)\n Event.new(*args)\n end", "def trigger(side, event, *args)\n self.class.hooks[:\"#{ side }_#{ event }\"].each do |method_name|\n if method(method_name).arity.zero?\n __send__(method_name)\n else\n __send__(method_name, *args)\n end\n end\n\n nil\n end", "def emit name, *args\n # Trigger callbacks in scripts before triggering events in the client.\n notify_scripts name, *args\n\n matching_callbacks = callbacks[name]\n return false unless matching_callbacks&.any?\n\n matching_callbacks.each { |callback| callback.call *args }\n end", "def fire_event locator, event_name\r\n command 'fireEvent', locator, event_name\r\n end", "def fire_event locator, event_name\r\n command 'fireEvent', locator, event_name\r\n end", "def exec_hook(event_name, *args, &block)\n PuppetDebugServer.log_message(:debug, \"Starting to execute hook #{event_name}\") unless event_name == :hook_log_message\n @hooks[event_name.to_s].map do |_hook_name, callable|\n begin\n callable.call(*args, &block)\n rescue ::RuntimeError => e\n errors << e\n e\n end\n end.last\n PuppetDebugServer.log_message(:debug, \"Finished executing hook #{event_name}\") unless event_name == :hook_log_message\n end", "def execute_hook(hook_name, *args, &block)\n event = Event.new(self, hook_name, args, !!block)\n\n if block\n execute_hook_recursively(hook_name, event, block)\n else\n execute_hook_iteratively(hook_name, event)\n end\n end", "def execute_hook(hook_name, *args, &block)\n event = Event.new(self, hook_name, args, !!block)\n\n if block\n execute_hook_recursively(hook_name, event, block)\n else\n execute_hook_iteratively(hook_name, event)\n end\n end", "def fire(event_name)\n\t\t\tcallback = @events[event_name]\n\t\t\t\n\t\t\tif callback\n\t\t\t\tcallback.call(self)\n\t\t\tend\n\t\tend", "def event!(*args)\n @events&.call(*args)\n end", "def trigger_async(channels, event_name, data, params = {})\n post_async('/events', trigger_params(channels, event_name, data, params))\n end", "def run(event, params = nil)\n @events[event].call(params)\n end" ]
[ "0.63373756", "0.63373756", "0.63167703", "0.6304516", "0.6193974", "0.61852914", "0.6161528", "0.6115156", "0.6016299", "0.59253484", "0.5922085", "0.5793874", "0.5752463", "0.5727183", "0.5715739", "0.56951404", "0.56702304", "0.56689626", "0.56689507", "0.5660282", "0.5638943", "0.56167006", "0.56167006", "0.5604196", "0.5517099", "0.55169517", "0.5497344", "0.54882133", "0.5458609", "0.54396087" ]
0.662765
0
Unregisters the event by name, effectively deleting the associated events bound with it also.
def unevent(name) Events.remove(name) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def off(event_name)\n events.delete(event_name.to_sym)\n end", "def unregister name\n @tags.delete(name)\n end", "def unregister name\n @tags.delete(name)\n end", "def off(event_type = ANY_EVENT, name = ANY_STATE, &callback)\n sync_exclusive do\n hooks.unregister event_type, name, callback\n end\n end", "def off(event_type = ANY_EVENT, name = ANY_STATE, &callback)\n sync_exclusive do\n hooks.unregister event_type, name, callback\n end\n end", "def unsubscribe(name)\n EM.schedule { @subs.delete name }\n end", "def clear_event_hooks(event_name)\n @hooks[event_name.to_s] = []\n end", "def off(name)\n raise(ArgumentError, 'Argument `name` must be a String.') unless name.is_a?(String)\n @handlers.delete(name)\n return self\n end", "def delete_hooks(event_name)\n @hooks[event_name] = []\n end", "def remove_event(event)\n @events.delete(event)\n end", "def unsubscribe(key)\n @lock.synchronize do\n @handlers.clear\n @@name2inst.delete_if { |k, v| k == id.to_sym || k == address.to_sym}\n end\n end", "def unsubscribe(name)\n id = @subs[name]\n\n self.send(msg: 'unsub', id: id)\n end", "def deregister_extension(name)\n self.ext.aliases.delete(name)\n end", "def remove_event_subscription(event_name, mode, handler)\n ((events[mode] ||= {})[event_name_for(event_name)] ||=[]).delete(handler)\n end", "def unregister(name)\n resource = resources.delete(name)\n if resource\n resource.bulkhead&.unregister_worker\n consumers_for_resource = consumers.delete(name) || []\n consumers_for_resource.each do |consumer|\n if consumer.weakref_alive?\n consumer.clear_semian_resource\n end\n rescue WeakRef::RefError\n next\n end\n end\n end", "def unload name\n raise \"Cannot unload: No such script #{name}\" unless @scripts.has_key? name\n\n @scripts[name].die if @scripts[name].respond_to? \"die\"\n\n @scripts[name].unregister_script\n @scripts[name].unregister_commands\n @scripts[name].unregister_events\n\n @scripts.delete name\n end", "def unregister(event_type, body, opts = {})\n data, _status_code, _headers = unregister_with_http_info(event_type, body, opts)\n return data\n end", "def remove(name)\n if hook = by_name(name)\n hook.destroy!\n end\n end", "def unsubscribe(name, &block)\n @driver.unsubscribe(name, &block)\n end", "def unload name\n raise \"Cannot unload: No such script #{name}\" unless @scripts.key? name\n\n @scripts[name].die if @scripts[name].respond_to? \"die\"\n\n Events.dispatch_for @scripts[name], :unloading\n\n Events.delete_for @scripts[name]\n URL.delete_for @scripts[name] if defined? MODULE_LOADED_URL_HANDLER\n RegexHandlerManager.delete_for @scripts[name] if defined? MODULE_LOADED_REGEX_HANDLER\n\n @scripts[name].unregister_script\n @scripts[name].unregister_commands\n @scripts[name].unregister_events\n\n @scripts.delete name\n end", "def unsubscribeTo (event)\r\n @subscribedEvents.delete?(event)\r\n end", "def unregister_adapter(name)\n @@loaded_adapters.delete(name)\n end", "def first_event(name)\n cls = MAPPINGS[name]\n if cls.nil?\n raise ArgumentError, \"Bogus event name #{name}\"\n end\n matching = events.find do |event|\n cls === event\n end\n events.delete(matching)\n matching\n end", "def remove_listener(name)\n @listeners.delete name\n end", "def del(name)\n data.delete(name)\n end", "def unsubscribe(name)\n if subscriptions.has_key? name\n subscriptions[name].queue.unsubscribe(:nowait => false)\n subscriptions.delete(name)\n end\n end", "def remove_group(name)\n @handlers.delete_if { |o| o.group == name }\n end", "def dele(packet, params)\n\t\tif params[:name]\n\t\t\tif (event = Event.find_by_name(params[:name]))\n\t\t\t\tevent.destroy\n\t\t\t\tpacket.data = 'OK'\n\t\t\telse\n\t\t\t\tpacket.data = 'KO'\n\t\t\t\tlog_error(\"[dele] event #{params[:name]} doesn't existe\")\n\t\t\tend\n\t\telse\n\t\t\tpacket.data = 'KO'\n\t\t\tlog_error(\"[dele] name event is missing\")\n\t\tend\n\t\tpacket\n\tend", "def unsubscribe(event, *args, &block)\n raise HandlerError.new \"Unable to unsubscribe, there is no event #{event}\" unless events[event.to_sym]\n events[event.to_sym].unsubscribe(*args, &block)\n end", "def unregister_from_event_loop\n if @loop == :em\n @em_connection.unattach(false)\n else\n raise NotImplementedError.new(\"unregister_from_event_loop not implemented for #{@loop}\")\n end\n end" ]
[ "0.7441557", "0.6746965", "0.6746965", "0.67336833", "0.67336833", "0.6647178", "0.66150576", "0.6588004", "0.6495706", "0.6373919", "0.63577336", "0.6313051", "0.6273848", "0.6216565", "0.62098235", "0.619146", "0.6179944", "0.61641043", "0.6109086", "0.6096646", "0.60931474", "0.60758173", "0.6057973", "0.6032174", "0.6030996", "0.6028744", "0.5953994", "0.59240174", "0.5922059", "0.592028" ]
0.8343725
0
Removes all unnessesary data from the traces
def remove_useless_traces_data(params) convert_list_of_json_traces_to_objects(params[0]) create_new_traces @traces_json_string = '[' + @traces_json_string[0...-1] + ']' puts @traces_json_string end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clear\n trace.elegibility.transform_values { |_| 0 }\n trace.extended.each_value do |ext|\n ext.transform_values { |_| 0 }\n end\n\n error.responsibility = error.projected = error.gated = 0\n end", "def discardAllTreasures\n \n end", "def clear_transformed_data!\n @transformed_values = []\n end", "def remove_trace_func\n Kernel.clear_trace_func\n end", "def clean(backtrace, kind = :silent)\n filtered = filter_backtrace(backtrace)\n\n case kind\n when :silent\n silence(filtered)\n when :noise\n noise(filtered)\n else\n filtered\n end\n end", "def clean_up_arrays\n self.likes.reject! {|l| l.empty? } if self.likes\n self.outdoor_activities.reject! {|l| l.empty? } if self.outdoor_activities\n self.nightlife.reject! {|l| l.empty? } if self.nightlife\n end", "def drop_buffered_data\n @stats_engine.reset!\n @error_collector.drop_buffered_data\n @transaction_sampler.reset!\n @transaction_event_recorder.drop_buffered_data\n @custom_event_aggregator.reset!\n @span_event_aggregator.reset!\n @log_event_aggregator.reset!\n @sql_sampler.reset!\n\n if Agent.config[:clear_transaction_state_after_fork]\n Tracer.clear_state\n end\n end", "def clean(backtrace, kind = :silent)\n filtered = filter(backtrace)\n\n case kind\n when :silent\n silence(filtered)\n when :noise\n noise(filtered)\n else\n filtered\n end\n end", "def clear_deprecated\n @data.each do |k, _v|\n @data.delete(k) if @deprecated.include?(k)\n end\n end", "def cleanup_dfs\n # clean up vertices attributes set during dfs\n @vertices.values.each do |vertex|\n vertex.color = nil\n vertex.predecessor = nil\n vertex.discovery = nil\n vertex.finish = nil\n end\n @time = 0\n end", "def pop\n traces = @traces.pop(VERY_LARGE_INTEGER)\n\n measure_pop(traces)\n\n traces\n end", "def main_area_off\n\t\tif @main_array.length > 0 then\n\t\t\tfor i in 0..(@main_array.length - 1) do\n\t\t\t\t@layer_general.remove( @main_array[i] )\n\t\t\tend\n\t\t\t@main_array.clear\n\t\tend\n\t\tself.remove( @layer_general )\n\tend", "def unclear(object)\n toys = object[0]\n toys.each do |toy|\n add_toy(toy)\n end\n strokes = object[1]\n strokes.each do |stroke|\n add_stroke(stroke)\n end\n end", "def destroy\n @trace.destroy\n end", "def clear ; @data.clear ; end", "def unsafe_forget_past!\n slices.values.map(&:history).each{|h| h.recent(memory_size)}\n\n if multi_slices?\n to_delete = slices.values.reject{|s| keep_slice?(s)}\n to_delete.map(&:rack_id).map do |rack_id| \n slices.delete(rack_id)\n end\n end\n end", "def clear\n @extent.clear\n end", "def clear_changed_attributes\n\t\t\t \t\t$TRACE.debug 5, \"clear_changed_attributes\"\n\t\t\t \tself.changed_attributes_aado = []\n\t\t\t \tend", "def clear_data \n @data = []\n end", "def remove_all()\n @field_weights = Array.new\n end", "def clear_drawings\n execute_script(%(\n var elements = window.document.body.querySelectorAll('[id*=\"rudra_\"]');\n for (var i = 0; i < elements.length; i++) {\n elements[i].remove();\n }\n window.rudraTooltipSymbol = 9311;\n window.rudraTooltipLastPos = { x: 0, y: 0 };\n ))\n end", "def rm_cddts_outof_blk\n axes = [@ref_rows, @ref_cols]\n axes.each{|axis|\n axis.each{|ref|\n intrsct_cddts = []\n (self.to_a.flatten & ref).each{|elm|\n intrsct_cddts.push(elm.cddts).flatten!.uniq!\n }\n six_cells_cddts = []\n (self.to_a.flatten - ref).each{|elm|\n six_cells_cddts.push(elm.cddts).flatten!.uniq!\n }\n intrsct_cddts.each{|cddt|\n unless six_cells_cddts.include?(cddt)\n (ref - self.to_a.flatten).each{|elm|\n elm.cddts.delete(cddt)\n# if ProgramConfig[:debug]\n# if elm.fixed == false and elm.cddts.length == 1\n# print \"DEBUG: [#{elm.i}, #{elm.j}] = #{elm.cddts.first}\\n\"\n# end\n# end\n elm.fixed = true if(elm.cddts.length == 1)\n }\n end\n }\n }\n }\n end", "def clear_tracking\n ::ObjectSpace.trace_object_allocations_clear\n end", "def reset_log_data\n without_logging { update_all(log_data: nil) }\n end", "def clear_back_office_data\n @flbt_type = nil\n @version = nil\n @submitted_date = nil\n @effective_date = nil\n @filing_date = nil\n @ads_included = nil\n @ads_amount = nil\n @number_of_buyers = nil\n end", "def clear_data()\n\t\[email protected]\n\t\[email protected]\n\tend", "def remove_unused_curves(model)\n model.getCurves.each do |curve|\n if curve.directUseCount == 0\n model.removeObject(curve.handle)\n end\n end\n return model\n end", "def cleanup\n datas[:model_feature_values].each_pair { |model_key, feature_values| \n model = Model.find(model_key)\n feature_keys = []\n model.features_list { |feature| feature_keys << feature.key }\n values(model).delete_if { |feature_key, value| !feature_keys.include?(feature_key) }\n }\n end", "def pop\n @mutex.synchronize do\n traces = @traces\n @traces = []\n\n measure_pop(traces)\n\n return traces\n end\n end", "def clear_collect_data; @collect_data = Hash.new; @collect_module = Hash.new; end" ]
[ "0.67180717", "0.6350163", "0.61820173", "0.59679735", "0.5958402", "0.5931395", "0.58900374", "0.58790004", "0.5877097", "0.5816887", "0.5800543", "0.57929695", "0.57839453", "0.57833207", "0.5782553", "0.57753074", "0.575557", "0.57200986", "0.5714017", "0.57020986", "0.5660831", "0.561725", "0.56159425", "0.5576391", "0.55395347", "0.55385673", "0.5534324", "0.553316", "0.5531931", "0.55236965" ]
0.722608
0
Converts a trace string to JSON Object
def convert_json_trace_to_object(trace) JSON.parse(trace[1...-1].insert(0, '{'), object_class: OpenStruct) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def return_json_string\n @traces_json_string\n end", "def to_json(*_args)\n @trace.to_json\n end", "def load(string)\n ActiveSupport::JSON.decode string\n end", "def load(string)\n ActiveSupport::JSON.decode string\n end", "def meta_to_json(str)\n key_pairs = str.split(',')\n h_kp = {}\n key_pairs.each do | kp |\n a_kp = kp.split('=')\n key = a_kp[0]\n val = a_kp[1]\n h_kp[key] = val\n end\n return h_kp.to_json\n end", "def json_to_obj json_str\n hash_to_obj(parse_json(json_str))\n end", "def unserialize(string)\n data = JSON.parse(string)\n data\n end", "def json()\n @trace_arr.map{|trace| \n tile = trace.json \n @tiles[trace.id] = trace\n trace.id\n }\n end", "def parse_json str\n JSON.parse str rescue raise ConfigError, \"Invalid JSON\"\n end", "def string_to_hash(str)\n JSON.parse(str)\nend", "def parse_json(str)\n Yajl::Parser.parse(str)\n end", "def parse_string_to_json(response)\n JSON.parse(response)\n rescue JSON::ParserError\n response\n end", "def entry_as_json(entry)\n data = {}\n set_attribute(data, @time_key, entry.time) unless @time_key.nil?\n set_attribute(data, @severity_key, entry.severity_label) unless @severity_key.nil?\n set_attribute(data, @progname_key, entry.progname) unless @progname_key.nil?\n set_attribute(data, @pid_key, entry.pid) unless @pid_key.nil?\n set_attribute(data, @message_key, entry.message) unless @message_key.nil?\n\n tags = entry.tags\n if @custom_keys.size > 0\n tags = (tags.nil? ? {} : tags.dup)\n @custom_keys.each do |name, key|\n set_attribute(data, key, tags.delete(name.to_s))\n end\n end\n\n unless @tags_key.nil?\n tags ||= {}\n set_attribute(data, @tags_key, tags)\n end\n\n data = @formatter.format(data) if @formatter\n data\n end", "def convert_it_to_hash_format(object)\n JSON.parse(object)\n end", "def pjson(str)\n Oj.load(str)\nend", "def e(object)\n require 'json'\n object.respond_to?(:to_json) ? object.to_json : object.to_s.to_json\n end", "def json_from_text(name)\n JSON.parse(read_text(name))\nend", "def as_json(*args)\n eval(to_s).as_json(*args)\n end", "def responseToJson(responseString)\n # responseJson = JSON.parse(responseString)\n responseJson\n end", "def serialize_track(track)\n json = \"{\\\"id\\\": #{track.id},\n \\\"name\\\": \\\"#{track.name}\\\",\n \\\"artist\\\": {\\\"id\\\": #{track.artist.id},\\\"name\\\": \\\"#{track.artist.name}\\\"},\n \\\"release\\\": {\\\"id\\\": #{track.release.id},\\\"name\\\": \\\"#{track.release.name}\\\"},\n \\\"file\\\": \\\"#{track.file.url}\\\"}\"\n end", "def serialize_in(json_string, options = {})\n super(ActiveSupport::JSON.decode(json_string), options)\n end", "def convert_span obj\n TraceProtos::Span.new \\\n name: make_resource_name(@project_id, obj.trace_id, obj.span_id),\n span_id: obj.span_id,\n parent_span_id: obj.parent_span_id || \"\",\n display_name: convert_truncatable_string(obj.name),\n start_time: convert_time(obj.start_time),\n end_time: convert_time(obj.end_time),\n attributes:\n convert_attributes(obj.attributes,\n obj.dropped_attributes_count,\n include_agent_attribute: true),\n stack_trace:\n convert_stack_trace(obj.stack_trace, obj.dropped_frames_count,\n obj.stack_trace_hash_id),\n time_events:\n convert_time_events(obj.time_events,\n obj.dropped_annotations_count,\n obj.dropped_message_events_count),\n links: convert_links(obj.links, obj.dropped_links_count),\n status: convert_optional_status(obj.status),\n same_process_as_parent_span:\n convert_optional_bool(obj.same_process_as_parent_span),\n child_span_count: convert_optional_int32(obj.child_span_count)\n end", "def format(tag, time, record)\n [tag, time, record].to_json + \"\\n\"\n ## Alternatively, use msgpack to serialize the object.\n # [tag, time, record].to_msgpack\n end", "def to_json(*args)\n eval(to_s).to_json(*args)\n end", "def deserialize(string)\n string\n end", "def json(str)\n @headers[Rack::CONTENT_TYPE] = ContentType::JSON\n write(str)\n end", "def to_json(json)\n begin\n JSON.parse(json)\n rescue\n json\n end\n end", "def to_json\n obj = @options.clone\n # Remove non-JSON objects.\n obj.reject!{|k,v|\n !k.is_a?(String) && !k.is_a?(Symbol) || !@@valid_types.include?(v.class)\n }\n # Split at every even number of unescaped quotes. This gives either strings\n # or what is between strings.\n # If it's not a string then turn Symbols into String and replace => and nil.\n json_string = obj.inspect.split(/(\\\"(?:.*?[^\\\\])*?\\\")/).\n collect{|s|\n (s[0..0] != '\"') ? # If we are not inside a string\n s.gsub(/\\:(\\S+?(?=\\=>|\\s|,|\\}))/, \"\\\"\\\\1\\\"\"). # Symbols to String\n gsub(/\\=\\>/, \":\"). # Arrow to colon\n gsub(/\\bnil\\b/, \"null\") : # nil to null\n s # If it's a string don't touch it.\n }.join\n return json_string\nend", "def parseJsonString(jsonString) \n $jsonObjectMain = JSON.parse(jsonString);\n return $jsonObjectMain;\nend", "def to_hds_json json_string\n @document = to_hds(json_string)\n @document.to_json.to_json\n end" ]
[ "0.6320628", "0.6235496", "0.578373", "0.578373", "0.5767151", "0.56942123", "0.5670016", "0.56492263", "0.5531835", "0.55062896", "0.5493804", "0.546757", "0.5374033", "0.5363098", "0.53590876", "0.5348716", "0.52849364", "0.52409697", "0.5237889", "0.52342045", "0.52288604", "0.521112", "0.51828045", "0.5182706", "0.5177303", "0.51705474", "0.5153922", "0.51462644", "0.51460046", "0.5135658" ]
0.6937454
0
Generate the traces that will be used in the visualization process. This is done by 1 extract the variables names form the trace 2 extract the encoded locals from the trace 3 extract the heap values form the trace 4 extract the code from the trace
def create_new_traces @traces.each do |trace| trace_stack = trace.stack_to_render[0] unless(trace_stack.func_name.include? '<init>') trace_stack_ordered_variable_names = trace_stack.ordered_varnames trace_stack_encoded_locals = trace_stack.encoded_locals trace_heap = trace.heap trace_code = @code[trace.line] filtered_trace = filter_trace([ trace_stack_ordered_variable_names, trace_stack_encoded_locals, trace_heap, trace_code, trace.line ]) @new_traces << filtered_trace trace_string = Yajl::Encoder.encode(filtered_trace) @traces_json_array << trace_string @traces_json_string += trace_string + ',' end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def filter_trace(params)\n trace = {}\n trace['stack'] = {}\n trace['stack']['ordered_variable_names'] = params[0]\n trace['stack']['encoded_locals'] = {}\n params[1].each_pair do |key, value|\n trace['stack']['encoded_locals'][key] = value\n end\n trace['heap'] = {}\n params[2].each_pair do |key, value|\n trace['heap'][key] = value if value.is_a?(Array) && value.length > 2\n end\n trace['code'] = params[3]\n trace['lineNumber'] = params[4]\n trace\n end", "def visit_trace(code, ins, local_vars, ln, info)\r\n end", "def generate_tracing_configuration()\n result = \"\"\n\n if @tracing_vars\n @tracing_vars.each_with_index do |var_name, var_index|\n result += \"garbledwebpiratenlibraryname.add_traced_variable('#{var_name}', #{var_index})\\n\"\n end\n result += \"\\n\"\n end\n\n return result\n end", "def get_stages exec_trace\n ret_array = []\n lines = exec_trace.split /\\n/\n current_line = 0\n # Skip past preamble\n until lines[current_line] =~ /M@/\n current_line += 1\n end\n pattern = /M@(\\w+)/\n while current_line < lines.length\n if lines[current_line].match pattern\n command = lines[current_line].sub pattern, '\\1'\n case command\n when \"assign\"\n var = lines[current_line += 1]\n exp = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"#{var} := #{exp}\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"new\"\n var = lines[current_line += 1]\n exp = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"#{var} := new(#{exp})\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"dispose\"\n var = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"free(#{var})\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"lookup\"\n var1 = lines[current_line += 1]\n var2 = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"#{var1} := [#{var2}]\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"mutate\"\n var = lines[current_line += 1]\n exp = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"[#{var}] := #{exp}\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"conditional\"\n bool = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n prog = lines[current_line += 1]\n text = \"if #{bool} (taking branch: #{prog})\"\n ret_array.push Stage.new i_heap, i_store, i_heap, i_store, text\n current_line += 1\n else\n raise \"command did not match\"\n end\n else\n raise \"line #{lines[current_line]} didn't match\"\n end\n end\n ret_array\nend", "def texify exec_trace\n document_text = \"\"\n File.open \"preamble.tex\" do |file|\n while line = file.gets\n document_text += line\n end\n end\n document_text += \"\\\\begin{document}\\n\"\n stages = get_stages exec_trace\n stages.each do |stage|\n document_text += \"\\\\begin{frame}\\n\\n\"\n document_text += state_text stage.i_heap, stage.i_store\n document_text += \"\\n\"\n document_text += \"Current command: \"\n document_text += \"\\\\il{#{stage.text}}\"\n document_text += \"\\n\"\n document_text += \"\\\\vspace{1cm}\\n\\n\"\n document_text += state_text stage.f_heap, stage.f_store\n document_text += \"\\\\end{frame}\"\n document_text += \"\\n\"\n end\n document_text\nend", "def dump_caller_stack\n return unless $ITEST2_TRACE_EXECUTION\n begin\n caller.each_with_index do |position, idx|\n next unless position =~ /\\A(.*?):(\\d+)/\n file = $1\n # TODO: send multiple trace to be parse with pages.rb\n # next if file =~ /example\\/example_methods\\.rb$/ or file =~ /example\\/example_group_methods\\.rb$/ or file =~ /driver\\.rb$/ or file =~ /timeout\\.rb$/ # don't include rspec or ruby trace\n\n if file.include?(\"_spec.rb\") || file.include?(\"_test.rb\") || file.include?(\"_cmd.rb\")\n connect_to_itest(\" TRACE\", position)\n end\n\n break if idx > 4 or file =~ /\"_spec\\.rb$/\n end\n rescue => e\n puts \"failed to capture log: #{e}\"\n end\n end", "def traces\n trace_store.keys\n end", "def trace_raw\n $log.debug \"XSS trace raw\"\n # Output\n $abst_dataflows.each do |n1, d1|\n if d1.subtype == 'raw_out'\n if $enable_stdout\n print \"\\e[31m\" # red\n puts \" #{n1} has raw output.\"\n print \"\\e[0m\" # reset\n end\n $log.debug \"XSS #{n1} has raw output. check the state that input #{d1.src_id}, output #{d1.dst_id}\"\n\n d1.xss_trace = true\n $abst_states[d1.dst_id].xss_out << d1\n # Input\n in_states = []\n $abst_dataflows.each do |n2, d2|\n if d2.dst_id == d1.src_id\n $log.debug \"XSS #{d2.src_id} ==(#{d2.type})==> #{d1.src_id} ==(raw)==> #{d1.dst_id}\"\n d2.xss_trace = true\n $abst_states[d1.dst_id].xss_in << d2\n in_states << d2.src_id\n end\n end\n\n # add to Warnings\n w = Hash.new\n w['warning_type'] = 'Cross Site Scripting'\n w['message'] = \"Unescaped model attribute, path in:#{in_states}->var:#{d1.src_id}->out:#{d1.dst_id}\"\n w['file'] = d1.filename # TODO: condblk.filename is nil\n w['file2'] = nil\n w['line'] = nil\n w['code'] = nil\n w['location'] = nil\n w['user_input'] = nil\n # put explicit raw here => programmer should have some intentions => but test\n w['confidence'] = 'High' # Weak Medium High\n w['hit_state'] = d1.dst_id\n w['hit_variable'] = d1.src_id\n $warning.add(w)\n end\n end\n\n # Trace C-V(raw_out)\n $abst_transitions.each do |n1, t|\n if !$abst_states[t.dst_id].nil? && $abst_states[t.dst_id].type == 'view'\n v = $abst_states[t.dst_id]\n if $abst_states[t.src_id].type == 'controller'\n c = $abst_states[t.src_id]\n # C-V\n c.test_xss_path << t if v.xss_out.count > 0\n end\n end\n end # trans loop\n end", "def create_traces_markup_from_traces_array(traces_array) #{\n rally_host = $my_base_url.split(\"/\")[-2]\n story_detail_url_prefix = \"https://#{rally_host}/#/detail/userstory\"\n testcase_detail_url_prefix = \"https://#{rally_host}/#/detail/testcase\"\n traces_markup = '<p><b>Caliber TRACES</b></p><br/>'\n trace_counter = 1\n\n traces_array.each do | this_traceid |\n\n is_testcase = this_traceid.match(/^TC/)\n is_requirement = this_traceid.match(/^REQ/)\n\n if !is_testcase.nil? then\n testcase_tag, testcase_fid, testcase_oid, testcase_name = @testcase_TagFidOidName_by_reqid[this_traceid.sub(\"TC\", \"\")]\n\n if testcase_oid.nil? then\n @logger.warn \" *** No Rally TestCase found for Caliber TestCase: CID=#{this_traceid}; (link will be empty)\"\n this_trace = this_traceid\n else\n @logger.info \" Linking Trace JDtraceId=#{this_traceid}; to Rally TestCase: FmtID=#{testcase_fid}; OID=#{testcase_oid};\"\n #this_trace_name = @testcase_name_by_caliber_testcase_id[testcase_oid] || this_traceid\n this_trace_name = \"#{this_traceid}: #{testcase_name}\"\n\n detail_url = \"#{testcase_detail_url_prefix}/#{testcase_oid}\"\n this_trace = \"<a href=\\\"#{detail_url}\\\">#{this_trace_name}</a>\"\n end\n traces_markup += trace_counter.to_s + \". \"\n traces_markup += this_trace\n traces_markup += '<br/>'\n trace_counter += 1\n end\n\n if !is_requirement.nil? then\n story_tag, story_fid, story_oid, story_name = @story_TagFidOidName_by_reqid[this_traceid.sub(\"REQ\", \"\")]\n\n if story_oid.nil? then\n @logger.warn \" *** No Rally UserStory found for Caliber Requirement: CID=#{this_traceid}; (link will be empty)\"\n this_trace = @req_name_by_reqid[this_traceid] || this_traceid\n else\n @logger.info \" Linking Trace JDtraceId=#{this_traceid}; to Rally UserStory: FmtID=#{story_fid}; OID=#{story_oid};\"\n #this_trace_name = @req_name_by_reqid[this_traceid.sub(\"REQ\", \"\")] || this_traceid\n this_trace_name = \"#{this_traceid}: #{story_name}\"\n\n detail_url = \"#{story_detail_url_prefix}/#{story_oid}\"\n this_trace = \"<a href=\\\"#{detail_url}\\\">#{this_trace_name}</a>\"\n end\n traces_markup += trace_counter.to_s + \". \"\n traces_markup += this_trace\n traces_markup += '<br/>'\n trace_counter += 1\n end\n end\n return traces_markup\nend", "def debug!(tracing_vars, old_allocations, name_index, value)\n name = ''\n if tracing_vars.length > 0\n if name_index.kind_of? Integer\n if name_index >= 0 && name_index < tracing_vars.length\n name = tracing_vars[name_index].chomp\n end\n end\n end\n remove_prefix! name\n remove_prefix! value\n\n name = CGI::escapeHTML(name)\n value = CGI::escapeHTML(value)\n\n old_allocations[name] ||= {}\n if old_allocations[name] != value\n old_allocations[name] = value\n @packet.add_allocation(name, value)\n end\nend", "def trace\n set_trace_func proc { |event, _file, _line, id, binding, classname|\n if event == watched && id != :log && classes.include?(classname.to_s)\n vars = variables(binding)\n\n if vars.empty?\n log_this(sprintf(\"%s %-25s #%-20s\",\n class_count, classname, id))\n\n else\n log_this(sprintf(\"%s %-25s #%-20s\\n%s\\n\",\n class_count, classname, id, vars))\n\n end\n end\n } if trace?\n end", "def assemble\n # var a, b, c;\n \"var \" + @locals.join(\", \") + \";\\n\" +\n @code.join\n end", "def extract_functions\n output = ObjdumpReader.objdump_output(\n [\n \"-M\", \"intel\", \"-D\", \n \"--section=.text\", \"--section=.plt\", \"--section=.init\", \n \"--demangle\", @elf_path\n ]\n )\n lines = output.split(\"\\n\").map { |l| ObjdumpLine.new( l ) }\n\n @functions = Set.new\n last_label = nil\n last_instrs = nil\n\n lines.each do |l|\n if l.type == :label\n unless last_label.nil?\n f = Function.new(\n last_label.name,\n last_label.address,\n l.address,\n ObjdumpReader.lines_to_instrs( last_instrs )\n )\n @functions << f\n end\n last_label = l\n last_instrs = []\n elsif l.type == :instruction\n unless last_instrs.nil?\n last_instrs << l\n end\n end\n end\n end", "def create_traces_text_from_traces_array(traces_array) #{\n rally_host = $my_base_url.split(\"/\")[-2]\n detail_url_prefix = \"https://#{rally_host}/#/detail/userstory\"\n traces_markup = '<p><b>Caliber TRACES</b></p><br/>'\n trace_counter = 1\n\n traces_array.each do | this_trace |\n story_oid = @story_TagFidOidName_by_reqid[this_trace][1]\n if !story_oid.nil? then\n this_trace_name = this_trace\n story_url_detail = \"#{detail_url_prefix}/#{story_oid}\"\n this_trace = \"<a href=\\\"#{story_url_detail}\\\">#{this_trace_name}</a>\"\n end\n \n traces_markup += trace_counter.to_s + \". \"\n traces_markup += this_trace\n traces_markup += '<br/>'\n trace_counter += 1\n end \n return traces_markup\nend", "def code_analyzer(code, first_trace)\n code_to_viz = code_splitter(code)\n trace_analyzer = TraceAnalyzer.new\n trace_analyzer.handle_everything(code_to_viz, first_trace)\nend", "def build_trace\n if with_bt_set?\n Backtrace.to_s(@with_bt + [first_filtered_bt_line(backtrace)])\n else\n src_line\n end\n end", "def read_stack_cache_traces(analysis_task_elem)\n analysis_task_elem.each_element(\"value_analysis/messages/message/textline\") { |e|\n if e.text =~ /trace.*\\(context\\w*(.*)\\).*\\(\"user_(n_(?:fill|spill))\"\\).=.(\\d+)/\n yield $1,$2,$3\n end\n }\n end", "def assemble\n out = \"\"\n\n if @locals.size > 0\n out << \"var \" + @locals.join(', ') + \";\\n\"\n end\n\n out + @code.join\n end", "def stackFrameWalk()\n toKernel32Code = toKernel32()\n data = <<EOS\n push esi\n push ecx\n\n mov eax, ebp\n\n stack_walking:\n mov esi, eax\n lodsd\n mov ecx,[eax]\n test ecx, ecx\n jnz stack_walking\n\n ; esi now points to last stack frame (and since lodsd increments esi by 4 it points to function in ntdll.dll)\n mov eax,[esi]\n\n find_begin:\n dec eax\n xor ax,ax ; work through image until we find base address\n cmp word [eax],0x5A4D ; MZ start of PE header\n jnz find_begin\n\n pop ecx\n pop esi\n\n mov edx, eax\n ; edx now points to ntdll.dll or kernel32.dll base address (depending on windows version)\n\n #{toKernel32Code}\nEOS\n data\n end", "def seperate_and_filter_trace(junit_test_file,\n files_path,\n peruser_files_path,\n student_file_name)\n code_and_trace = generate_backend_trace(junit_test_file,\n files_path,\n peruser_files_path,\n student_file_name)\n splitter = '\"' + 'trace' + '\"' + ':'\n user_code, whole_trace = code_and_trace.split(splitter)\n\n whole_trace = whole_trace[1..whole_trace.length]\n\n entire_json_file = code_analyzer(user_code, whole_trace)\n\n entire_json_file\nend", "def exe_Point_Finder(trace)\n symbol_stack = []\n other_list = []\n top_symbol = ''\n exe = ''\n exe_point = ' '\n on = false\n off = false\n trace.split('').each do |i|\n current_symbol = i\n exe_point += current_symbol\n if i == '{' or i == '[' or i == '('\n symbol_stack << i\n elsif i == '}' or i == ')' or i == ']'\n if empty?(symbol_stack) == false\n top_symbol = symbol_stack.pop\n if i == '}' and top_symbol != '{'\n next\n end\n end\n elsif i == ','\n other_list << exe_point\n if symbol_stack.length.zero?\n other_list.each do |thing|\n exe += thing\n end\n if exe.include? 'startTraceNow'\n on = true\n exe = ''\n exe_point = ''\n other_list = []\n elsif exe.include? 'endTraceNow'\n off = true\n return\n else\n flag = verify_exe_point(on, off, exe)\n on = false if flag == false\n exe = ''\n exe_point = ''\n other_list = []\n end\n else\n exe_point = ''\n end\n\n else\n next\n end\n end\n end", "def tracing()\n #This is a stub, used for indexing\n end", "def compile_data\n res = Hash.new { |h, k| h[k] = [] }\n @result.to_two_level_hash.each do |klass, methods_and_locations|\n methods_and_locations.each_pair do |meth, locations|\n source, lineno = locations\n res[source] << [lineno, \"#{klass}#{meth}\"]\n end\n end\n res.sort # by source file path\n end", "def generate_stackframe_list\n stack_frames = []\n state = puppet_session_state.saved\n\n # Generate StackFrame for a Pops::Evaluator object with location information\n unless state.pops_target.nil?\n target = state.pops_target\n\n frame = DSP::StackFrame.new.from_h!(\n 'id' => stack_frames.count,\n 'name' => get_puppet_class_name(target),\n 'line' => 0,\n 'column' => 0\n )\n\n # TODO: Need to check on the client capabilities of zero or one based indexes\n if target.is_a?(Puppet::Pops::Model::Positioned)\n target_loc = get_location_from_pops_object(target)\n frame.name = target_loc.file\n frame.line = target_loc.line\n frame.column = pos_on_line(target, target_loc.offset)\n frame.source = DSP::Source.new.from_h!('path' => target_loc.file)\n\n if target_loc.length > 0 # rubocop:disable Style/ZeroLengthPredicate\n end_offset = target_loc.offset + target_loc.length\n frame.endLine = line_for_offset(target, end_offset)\n frame.endColumn = pos_on_line(target, end_offset)\n end\n end\n\n stack_frames << frame\n end\n\n # Generate StackFrame for an error\n unless state.exception.nil?\n err = state.exception\n frame = DSP::StackFrame.new.from_h!(\n 'id' => stack_frames.count,\n 'name' => err.class.to_s,\n 'line' => 0,\n 'column' => 0\n )\n\n # TODO: Need to check on the client capabilities of zero or one based indexes\n unless err.file.nil? || err.line.nil?\n frame.source = DSP::Source.new.from_h!('path' => err.file)\n frame.line = err.line\n frame.column = err.pos || 0\n end\n\n stack_frames << frame\n end\n\n # Generate StackFrame for each PuppetStack element\n unless state.puppet_stacktrace.nil?\n state.puppet_stacktrace.each do |pup_stack|\n source_file = pup_stack[0]\n # TODO: Need to check on the client capabilities of zero or one based indexes\n source_line = pup_stack[1]\n\n frame = DSP::StackFrame.new.from_h!(\n 'id' => stack_frames.count,\n 'name' => source_file.to_s,\n 'source' => { 'path' => source_file },\n 'line' => source_line,\n 'column' => 0\n )\n stack_frames << frame\n end\n end\n\n stack_frames\n end", "def trace( crashfile, template )\n end", "def render_debug args\n if !args.state.grid_rendered\n 65.map_with_index do |i|\n args.outputs.static_debug << {\n x: LOWREZ_X_OFFSET,\n y: LOWREZ_Y_OFFSET + (i * 10),\n x2: LOWREZ_X_OFFSET + LOWREZ_ZOOMED_SIZE,\n y2: LOWREZ_Y_OFFSET + (i * 10),\n r: 128,\n g: 128,\n b: 128,\n a: 80\n }.line\n\n args.outputs.static_debug << {\n x: LOWREZ_X_OFFSET + (i * 10),\n y: LOWREZ_Y_OFFSET,\n x2: LOWREZ_X_OFFSET + (i * 10),\n y2: LOWREZ_Y_OFFSET + LOWREZ_ZOOMED_SIZE,\n r: 128,\n g: 128,\n b: 128,\n a: 80\n }.line\n end\n end\n\n args.state.grid_rendered = true\n\n args.state.last_click ||= 0\n args.state.last_up ||= 0\n args.state.last_click = args.state.tick_count if args.lowrez.mouse_down # you can also use args.lowrez.click\n args.state.last_up = args.state.tick_count if args.lowrez.mouse_up\n args.state.label_style = { size_enum: -1.5 }\n\n args.state.watch_list = [\n \"args.state.tick_count is: #{args.state.tick_count}\",\n \"args.lowrez.mouse_position is: #{args.lowrez.mouse_position.x}, #{args.lowrez.mouse_position.y}\",\n \"args.lowrez.mouse_down tick: #{args.state.last_click || \"never\"}\",\n \"args.lowrez.mouse_up tick: #{args.state.last_up || \"false\"}\",\n \"Player.player_x: #{args.state.player.player_x.to_i}\",\n \"Player.player_y: #{args.state.player.player_y.to_i}\",\n \"Player.angle: #{args.state.player.angle.to_i}\",\n \"Active bullets: #{args.state.bullets.length}\",\n \"Active turrets: #{args.state.turrets.length}\",\n ]\n\n args.outputs.debug << args.state\n .watch_list\n .map_with_index do |text, i|\n {\n x: 5,\n y: 720 - (i * 20),\n text: text,\n size_enum: -1.5,\n\t r: 250,\n\t g: 250,\n\t b: 250,\n\t a: 250,\n }.label\n end\n\nend", "def sub_funcs\n # Find out function names, make map\n get_func_names.each do |var, _sub|\n code.gsub!(var, @rig.init_var(var))\n end\n\n code\n end", "def initialize\n @global = Hash.new\n @procedures = Hash.new\n @operands_stack = Stack.new\n @operations_stack = Stack.new\n @jumps_stack = Stack.new\n @lines_counter = 0\n @cuadruples_array = Array.new\n @scope_location = nil\n @sing_variable = nil\n @arguments = Array.new\n @data_type = nil\n @is_ref = false\n @has_return = false\n @exp_call = false\n @arg_stack = Stack.new\n @call_stack = Stack.new\n @addr_const_val = nil\n @filename = \"output.txt\"\n # Change to 'true' to see verbose in cuadruples\n @debug = false\n # Memory scheme:\n # Global address -> direction 1000, with 1000 directions for every data type\n # -> Total width: 4000\n # Local address -> direction 5000, with 1000 directions for every data type\n # in the normal and temporal addresses\n # -> Total width: 8000\n # Constant address -> direction 13000, with 1500 directions for integers and\n # floats, but 2 directions for boolean and the rest for strings\n # -> Total width: 6000\n # Pointers addresses -> direction 19000, with 1000 directions for every data type\n # -> Total width: 4000\n @global_memory = Memory.new(1000, 4000)\n @local_memory = LocalMemory.new(5000, 8000)\n @const_memory = ConstantMemory.new(13000, 6000, [0.25, 0.25, 0.0005, 0.4995])\n @pointer_memory = Memory.new(19000, 4000)\n\n @semanthic_cube = {\n 'int' => {\n 'int' => {\n\t'=' => 'int',\n\t'+' => 'int',\n\t'-' => 'int',\n\t'*' => 'int',\n\t'/' => 'int',\n\t'and' => 'boolean',\n\t'or' => 'boolean',\n\t'>' => 'boolean',\n\t'>=' => 'boolean',\n\t'<' => 'boolean',\n\t'<=' => 'boolean',\n\t'==' => 'boolean',\n\t'!=' => 'boolean'\n },\n 'float' => {\n\t'=' => 'int',\n\t'+' => 'float',\n\t'-' => 'float',\n\t'*' => 'float',\n\t'/' => 'float',\n\t'and' => 'boolean',\n\t'or' => 'boolean',\n\t'>' => 'boolean',\n\t'>=' => 'boolean',\n\t'<' => 'boolean',\n\t'<=' => 'boolean',\n\t'==' => 'boolean',\n\t'!=' => 'boolean'\n },\n 'boolean' => {\n\t'=' => 'int',\n\t'and' => 'boolean',\n\t'or' => 'boolean'\n },\n 'not' => 'boolean'\n },\n 'float' => {\n 'int' => {\n\t'=' => 'float',\n\t'+' => 'float',\n\t'-' => 'float',\n\t'*' => 'float',\n\t'/' => 'float',\n\t'and' => 'boolean',\n\t'or' => 'boolean',\n\t'>' => 'boolean',\n\t'>=' => 'boolean',\n\t'<' => 'boolean',\n\t'<=' => 'boolean',\n\t'==' => 'boolean',\n\t'!=' => 'boolean'\n },\n 'float' => {\n\t'=' => 'float',\n\t'+' => 'float',\n\t'-' => 'float',\n\t'*' => 'float',\n\t'/' => 'float',\n\t'and' => 'boolean',\n\t'or' => 'boolean',\n\t'>' => 'boolean',\n\t'>=' => 'boolean',\n\t'<' => 'boolean',\n\t'<=' => 'boolean',\n\t'==' => 'boolean',\n\t'!=' => 'boolean'\n },\n 'boolean' => {\n\t'=' => 'float',\n\t'and' => 'boolean',\n\t'or' => 'boolean'\n },\n 'not' => 'boolean'\n },\n 'string' => {\n 'string' => {\n\t'=' => 'string',\n\t'+' => 'string'\n }\n },\n 'boolean' => {\n 'int' => {\n\t'=' => 'boolean',\n },\n 'float' => {\n\t'=' => 'boolean',\n },\n 'boolean' => {\n\t'=' => 'boolean',\n\t'and' => 'boolean',\n\t'or' => 'boolean'\n },\n 'not' => 'boolean'\n }\n }\n end", "def dump_code( type_switch = 1 )\n wf_name = label.downcase.gsub(/ /,'_')\n puts\n puts \"Code Snippets for #{ label }:\"\n puts\n puts \"Number of tasks: #{ @task_list.count }\"\n puts \"Number of flows: #{ @flow_list.count }\"\n puts \"Number of states: #{ @status_list.count }\"\n puts\n puts \"List of Task Labels (I18n format):\"\n puts \n puts \" workflow:\"\n puts \" w00:\"\n puts \" label:\\t'#{ label }'\"\n puts \" tasks:\"\n @task_list.each_with_index do |t,i|\n next if t.nil?\n puts \" #{ sprintf('t%02d',i)}:\\t'#{ t.label }#{ ' <obsolete>' if t.obsolete }'\"\n end\n puts \" states:\"\n obsolete_marker = Array.new( status_list.count, false )\n @flow_list.each{ |f| obsolete_marker[ f.status_id ] |= f.obsolete }\n @status_list.each_with_index do |l,i|\n puts \" #{ sprintf('s%02d',i )}:\\t'#{ status_list[ i ]}#{ ' <obsolete>' if obsolete_marker[ i ] }'\"\n end\n puts\n puts \"Transition Structure:\"\n puts\n printf \"@#{ wf_name } = WorkFlowHelper.new([\"\n\n case type_switch\n when 0\n sep = \"\\n\"\n @task_list.each do |t|\n flows = t.outflows.collect{ |f| f.id }.join(',')\n tasks = t.outflows.collect{ |f| f.target_task_id }.join(',')\n printf \"%s [[%s],[%s]]\", sep, flows, tasks\n sep = \",\\n\"\n end\n when 1\n sep = \"\\n\"\n flow_tasks = ''\n @task_list[0...-1].each do |t|\n next if t.nil?\n flow_tasks = t.outflows.collect{ |f| \"[ %d, %d ]\" % [ f.status_id, f.target_task_id ]}.join(',')\n printf \"%s [%s]\", sep, flow_tasks\n sep = \",\\n\"\n end\n printf \"%s [[ -1, %d ]]\\n\", sep, @task_list.length - 1\n end\n\n puts \"])\"\n puts\n\n # list all roles with tasks for which they are responsible\n\n puts 'Responsibilities:'\n puts\n @role_list.each_with_index do |r,i|\n s = sprintf \"%-20s\", @role_list[ i ]\n sep = ''\n @task_list[0...-1].each_with_index do |t,j|\n next if t.nil?\n if t.role_id == i then\n s += sep + j.to_s\n sep = ','\n end\n end\n puts s\n end\n puts\n\n # better warn the user if there were any validation errors ...\n\n if @validation_errors > 0 then\n puts \">>> Errors detected during validation - check full report above. <<<\"\n puts\n end\n\n end", "def generate_backend_trace(junit_test_file,\n files_path,\n peruser_files_path,\n student_file_name)\n raw_code = junit_test_file\n raw_code.gsub! \"\\n\", \"\\\\n\" + \"\\n\"\n raw_code.gsub! \"\\t\", \"\\\\t\"\n lines = raw_code.split(\"\\n\")\n jUnit_test = ''\n lines.each { |line| jUnit_test += line}\n jUnit_test.gsub!('\\\"', \"\\\\\" + '\\\"')\n student_file = File.open(File.join(File.dirname(File.expand_path(__FILE__)),\n peruser_files_path,\n student_file_name), 'w+')\n full_string = '{' + \"\\n\" + '\"' + 'usercode' + '\"' + ':' + '\"' + jUnit_test +\n '\"' + ',' + \"\\n\" + '\"' + 'options' + '\"' + ':' + '{' + '}' \\\n ',' + \"\\n\" + '\"' + 'args' + '\"' + ':' + '[' + ']' + ',' \\\n \"\\n\" + '\"' + 'stdin' + '\"' + ':' + '\"' + '\"' + \"\\n\" + '}'\n student_file.puts(full_string)\n student_file.close\n output = `java -cp .:cp:cp/javax.json-1.0.4.jar:java/tools.jar traceprinter.InMemory < cp/traceprinter/output.txt` # the shell command\n output\nend" ]
[ "0.644559", "0.6297783", "0.58538085", "0.56983066", "0.5570515", "0.5535104", "0.5380226", "0.5338043", "0.5216844", "0.52124184", "0.5202664", "0.5117278", "0.5096113", "0.5090454", "0.50670594", "0.5060551", "0.50140655", "0.50054634", "0.49925035", "0.4990763", "0.4983535", "0.4968569", "0.49527052", "0.49405572", "0.49281982", "0.49266708", "0.49066997", "0.49015585", "0.48782665", "0.4867607" ]
0.694777
0
getter method to return the new trace as JSON string
def return_json_string @traces_json_string end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_json(*_args)\n @trace.to_json\n end", "def to_s\n @trace.to_s\n end", "def to_hash\n @trace\n end", "def json()\n @trace_arr.map{|trace| \n tile = trace.json \n @tiles[trace.id] = trace\n trace.id\n }\n end", "def trace\n attributes.fetch(:trace)\n end", "def to_s\n to_json\n end", "def to_s\n self.to_json\n end", "def to_json\n @front_end.get_json_string\n end", "def to_s\n \"#{self.class.name} #{@json_dict}\"\n end", "def to_string\n str = trace_id\n str += \"/#{span_id}\" if span_id\n unless sampled?.nil?\n options = 0\n options |= 1 if sampled?\n options |= 2 if capture_stack?\n str += \";o=#{options}\"\n end\n str\n end", "def json\n\n JSON.fast_generate(@gltf)\n\n end", "def to_json_raw_object()\n #This is a stub, used for indexing\n end", "def to_s\n to_json.to_s\n end", "def to_json_string\n MARC::JSONLWriter.encode(self)\n end", "def build_trace\n Backtrace.to_s(backtrace)\n end", "def to_s\n JSON.dump(to_h)\n end", "def to_s\n to_json_element\n end", "def json_serialize\n end", "def inspect\n JSON.pretty_generate to_h\n end", "def to_s\n JSON.pretty_generate(raw)\n end", "def to_s\n return @data.to_json\n end", "def to_s\n JSON.pretty_generate(@json)\n end", "def debug_out()\n return JSON.pretty_generate(self).gsub(\"\\\": \", \"\\\" => \").gsub(\" => null\", \" => nil\")\n end", "def show\n render json: @trace\n end", "def inspect\n \"#<#{self.class}:0x#{object_id.to_s(16)}> JSON: \" +\n JSON.pretty_generate(@data)\n end", "def inspect\n\t\t\told_to_s\n\t\tend", "def pretty_generate\n JSON.pretty_generate( self.to_h )\n end", "def to_s # :nocov:\n s = []\n s << \"#{self.class}:#{self.object_id}\"\n s << \" id: #{self.id}\"\n s << \" type: #{self.type}\"\n s << \" headers: \" + Debug.pretty_hash(self.headers)\n s << \" body: \" + Debug.pretty_hash(MultiJson.load(self.body))\n s.join(\"\\n\")\n end", "def to_json\n to_s.to_json\n end", "def toJsonString(prettyP = false)\n case(prettyP)\n when(true) ;\n return JSON.pretty_generate(toJson()) ;\n when(:line) ;\n _strList = @entryList.map{|entry| JSON.generate(entry.toJson())} ;\n return \"[\\n #{_strList.join(\",\\n \")}\\n]\" ;\n else\n return JSON.generate(toJson()) ;\n end\n end" ]
[ "0.77254003", "0.7145027", "0.6813827", "0.6757803", "0.66630393", "0.6413217", "0.63729984", "0.6330249", "0.6316424", "0.63129944", "0.6271973", "0.62525904", "0.6241202", "0.6188315", "0.61733526", "0.6162095", "0.6154478", "0.6142723", "0.61175704", "0.6100477", "0.6090325", "0.6086501", "0.6052527", "0.60497975", "0.603859", "0.6029947", "0.60042566", "0.6001796", "0.59893763", "0.5976264" ]
0.82976204
0
Generates the full execution trace for the complete source code by executing the command related to Java_Jail
def generate_backend_trace(junit_test_file, files_path, peruser_files_path, student_file_name) raw_code = junit_test_file raw_code.gsub! "\n", "\\n" + "\n" raw_code.gsub! "\t", "\\t" lines = raw_code.split("\n") jUnit_test = '' lines.each { |line| jUnit_test += line} jUnit_test.gsub!('\"', "\\" + '\"') student_file = File.open(File.join(File.dirname(File.expand_path(__FILE__)), peruser_files_path, student_file_name), 'w+') full_string = '{' + "\n" + '"' + 'usercode' + '"' + ':' + '"' + jUnit_test + '"' + ',' + "\n" + '"' + 'options' + '"' + ':' + '{' + '}' \ ',' + "\n" + '"' + 'args' + '"' + ':' + '[' + ']' + ',' \ "\n" + '"' + 'stdin' + '"' + ':' + '"' + '"' + "\n" + '}' student_file.puts(full_string) student_file.close output = `java -cp .:cp:cp/javax.json-1.0.4.jar:java/tools.jar traceprinter.InMemory < cp/traceprinter/output.txt` # the shell command output end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dump_caller_stack\n return unless $ITEST2_TRACE_EXECUTION\n begin\n caller.each_with_index do |position, idx|\n next unless position =~ /\\A(.*?):(\\d+)/\n file = $1\n # TODO: send multiple trace to be parse with pages.rb\n # next if file =~ /example\\/example_methods\\.rb$/ or file =~ /example\\/example_group_methods\\.rb$/ or file =~ /driver\\.rb$/ or file =~ /timeout\\.rb$/ # don't include rspec or ruby trace\n\n if file.include?(\"_spec.rb\") || file.include?(\"_test.rb\") || file.include?(\"_cmd.rb\")\n connect_to_itest(\" TRACE\", position)\n end\n\n break if idx > 4 or file =~ /\"_spec\\.rb$/\n end\n rescue => e\n puts \"failed to capture log: #{e}\"\n end\n end", "def inspect_jobs(index = nil)\n return empty_msg if empty?\n desc = []\n puts \"\\n\"\n @jobs.each_with_index do |j, i|\n unless index.nil?\n next unless i == index\n end\n desc << '| Job: ' + \"#{i + 1} \".rjust(8) + '|' + 'Pattern:'.rjust(18) + \" #{j.pattern.basename}\".ljust(120) + '|'\n desc << '| |' + 'Compiler ID:'.rjust(18) + \" #{j.id} \".ljust(120) + '|'\n desc << '| |' + 'Pinmap:'.rjust(18) + \" #{j.pinmap_workbook} \".ljust(120) + '|'\n desc << '| |' + '.atp directory:'.rjust(18) + \" #{j.pattern.dirname} \".ljust(120) + '|'\n desc << '| |' + '.pat directory:'.rjust(18) + \" #{j.output_directory} \".ljust(120) + '|'\n desc << '| |' + 'LSF:'.rjust(18) + \" #{j.location == :lsf ? true : false} \".ljust(120) + '|'\n desc << '| |' + 'Delete log files:'.rjust(18) + \" #{j.clean} \".ljust(120) + '|'\n desc << '| |' + 'Verbose:'.rjust(18) + \" #{j.verbose} \".ljust(120) + '|'\n fragment = '| |' + 'Compiler args:'.rjust(18)\n overflow_fragment = '| |' + ' '.rjust(18)\n compiler_args = []\n compiler_fragment = ''\n j.compiler_options.each_key do |k|\n if compiler_fragment.size + \" -#{k}\".size >= 120\n compiler_args << compiler_fragment\n compiler_fragment = nil\n end\n compiler_fragment += \" -#{k}\"\n end\n compiler_args << compiler_fragment unless compiler_fragment.nil?\n compiler_fragment = ''\n j.compiler_options_with_args.each_pair do |k, v|\n if compiler_fragment.size + \" -#{k}:#{v}\".size >= 120\n compiler_args << compiler_fragment\n compiler_fragment = nil\n end\n compiler_fragment += \" -#{k}:#{v}\"\n end\n compiler_args << compiler_fragment unless compiler_fragment.nil?\n if compiler_args.join.length <= 120\n desc << fragment + \"#{compiler_args.join}\".ljust(120) + '|'\n else\n # Need to cycle through compiler args and build a fragment <= 100 characters\n # and print it. Keep going until the remaining args is <= 100 and print again\n char_cnt = 0\n line_cnt = 0\n args = []\n compiler_args = compiler_args.join.strip.split(/\\s+/)\n until compiler_args.empty?\n args = compiler_args.select { |e| (char_cnt += e.length + 1) < 120 }\n # remove the args that fit on the first line\n compiler_args -= args\n if line_cnt == 0\n desc << fragment + \" #{args.join(' ')}\".ljust(120) + '|'\n else\n desc << overflow_fragment + \" #{args.join(' ')}\".ljust(120) + '|'\n end\n args = []\n line_cnt += 1\n char_cnt = 0\n end\n end\n desc << '-' * desc.first.size\n end\n puts desc.flatten.join(\"\\n\")\n end", "def build_trace\n if with_bt_set?\n Backtrace.to_s(@with_bt + [first_filtered_bt_line(backtrace)])\n else\n src_line\n end\n end", "def caller\n %x{\n function getErrorObject(){\n try { throw Error('') } catch(err) { return err; }\n }\n\n\n var err = getErrorObject();\n }\n stack = `err.stack`\n caller_lines = stack.split(\"\\n\")[4..-1]\n caller_lines.reject! { |l| l.strip.empty? }\n\n result_formatter = lambda do |filename, line, method=nil|\n \"#{filename}:#{line} in `(#{method ? method : 'unknown method'})'\"\n end\n\n caller_lines.map do |raw_line|\n if match = /\\s*at (.*) \\((\\S+):(\\d+):\\d+/.match(raw_line)\n method, filename, line = match.captures\n result_formatter[filename, line, method]\n elsif match = /\\s*at (\\S+):(\\d+):\\d+/.match(raw_line)\n filename, line = match.captures\n result_formatter[filename, line]\n # catch phantom/no 2nd line/col #\n elsif match = /\\s*at (.*) \\((\\S+):(\\d+)/.match(raw_line)\n method, filename, line = match.captures\n result_formatter[filename, line, method]\n elsif match = /\\s*at (.*):(\\d+)/.match(raw_line)\n filename, line = match.captures\n result_formatter[filename, line]\n # Firefox - Opal.modules[\"rspec/core/metadata\"]/</</</</def.$populate@http://192.168.59.103:9292/assets/rspec/core/metadata.self.js?body=1:102:13\n elsif match = /(.*?)@(\\S+):(\\d+):\\d+/.match(raw_line)\n method, filename, line = match.captures\n result_formatter[filename, line, method]\n # webkit - http://192.168.59.103:9292/assets/opal/rspec/sprockets_runner.js:45117:314\n elsif match = /(\\S+):(\\d+):\\d+/.match(raw_line)\n filename, line = match.captures\n result_formatter[filename, line]\n else\n \"#{filename}:-1 in `(can't parse this stack trace)`\"\n end\n end\n end", "def dump_compiled code\n\t\t\tbuf = do_compile code,false\n\t\t\tprint buf,\"\\n\"\n\t\tend", "def stack_trace; end", "def execute\n\n logger = Logger.new(\"/dev/null\")\n logger.level = Logger::WARN\n log_adapter = JerichoLoggerAdapter.new(logger)\n\n perl_pages = File.join(top_git_directory, 'java/code/**/*.{jsp,jspf}')\n java_pages = File.join(top_git_directory, 'web//**/*.{pxt, pxi}')\n [perl_pages, java_pages].each do |pages|\n Dir.glob(pages).each do |path|\n content = File.read(path)\n on_file_start(content, path)\n source = Source.new(content)\n source.setLogger(log_adapter)\n out = OutputDocument.new(source)\n\n tags = source.getAllStartTags\n tags.each do |tag|\n if applicable?(tag)\n process_tag(source, out, tag, path)\n end\n end\n\n on_file_changed(content, out.toString, path)\n on_file_done(path)\n end\n end\n\n Dir.glob(File.join(top_git_directory, 'java/code/**/*.{java}')).each do |path|\n content = File.read(path)\n on_file_start(content, path)\n on_file_done(path)\n end\n\n Dir.glob(File.join(top_git_directory, 'web/**/*.{pm}')).each do |path|\n content = File.read(path)\n on_file_start(content, path)\n on_file_done(path)\n end\n\n on_done\n end", "def trace(args)\n if solve(args)\n path_stack, current_cell = [], @seen_stack.last\n path_stack.push(current_cell)\n until @seen_stack.empty?\n current_cell = find_steps(current_cell, path_stack)\n end\n path_stack.reverse.each { |cell| print \"-->#{cell} \" }\n puts \"\"\n path_stack\n else nil\n end\n end", "def main_method(file_path, student_full_code)\n my_test = seperate_and_filter_trace(student_full_code, file_path,\n 'cp/traceprinter/', 'output.txt')\n Dir.chdir('/home')\n #puts my_test\n my_test\nend", "def run_ktrace(jobid)\n\n initialize_db = lambda {|dbconn, required_tables|\n init = false\n db_init_script = File.join($script_path, 'ktrace_schema.sql')\n required_tables.each do |t|\n res = dbconn.exec(\"SELECT to_regclass('public.#{t}');\")\n if res.values[0][0].nil?\n init = true\n break\n end\n end\n if init\n stage \"[7] Initializing KTrace DB\"\n dbconn.exec(File.read(db_init_script))\n end\n }\n\n ingest_file = lambda {|dbconn, table_name, file_path|\n dbconn.copy_data \"COPY #{table_name} FROM STDIN delimiter '|' quote '`' csv\" do\n str = File.read(file_path)\n str.each_line do |line|\n dbconn.put_copy_data jobid + \"|\" + line\n end\n end\n }\n\n stage \"[7] Populating KTrace DB\"\n job_sandbox_path = File.join($workdir, \"job_#{jobid}\")\n\n if Dir.exists?(job_sandbox_path)\n globals_path = File.join(job_sandbox_path, \"globals.dsv\")\n messages_path = File.join(job_sandbox_path, \"messages.dsv\")\n peer_role_path = File.join(job_sandbox_path, \"peers.dsv\")\n\n if [globals_path, messages_path, peer_role_path].all? {|f| File.file?(f) }\n stage \"[7] Found trace data, now copying.\"\n conn = PG.connect()\n initialize_db.call(conn, ['Globals', 'Messages', 'Peers'])\n\n ingest_file.call(conn, \"Globals\", globals_path)\n stage \"[7] Copied globals trace data.\"\n\n ingest_file.call(conn, \"Messages\", messages_path)\n stage \"[7] Copied messages trace data.\"\n\n ingest_file.call(conn, \"Peers\", peer_role_path)\n stage \"[7] Copied peer role data.\"\n\n # TODO: automatic querying and verification of job logs.\n else\n stage \"[7] ERROR: No ktrace data found for job #{jobid}\"\n end\n end\n\nend", "def trace\n `#{@native}.trace()`\n end", "def evaluate\n\t\t# :mem, :cpu, :hang, :sig, :ok, :exit, :compile, :fail\n\t\tcodes = {}\n\t\tStatusCode.all.each { |c| codes[c.name.downcase.to_sym] = c.id }\n\t\tlanguage = @program.programming_language\n\t\tcompiler = language.compiler\n\t\texecution = language.execution\n\t\ttcmd = \"#{Rails.root.join('script/timeout/timeout')} -t %s -m %s\"\n\t\tTempfile.open('src', Rails.root.join('tmp')) do |file|\n\t\t\tfile.write(@program.source_code)\n\t\t\tfile.flush\n\t\t\toutfile = File.dirname(file.path) + '/test'\n\t\t\tOpen3.popen2e(compiler % {out: outfile, in: file.path}) do |_, _, thread|\n\t\t\t\texit_code = thread.value\n\t\t\t\tunless exit_code.success?\n\t\t\t\t\[email protected]_code_id = codes[:compile]\n\t\t\t\t\tnext\n\t\t\t\tend\n\t\t\t\ttask = @program.programming_task\n\t\t\t\ttimelimit = task.time_limit\n\t\t\t\tmemlimit = task.memory_limit.megabytes / 1.kilobyte\n\t\t\t\ttimeout = tcmd % [timelimit, memlimit]\n\t\t\t\ttestcases = task.programming_test_cases\n\t\t\t\ttestcases.each do |testcase|\n\t\t\t\t\texecution = execution % {file: outfile}\n\t\t\t\t\tOpen3.popen3(\"#{timeout} #{execution}\") do |stdin, stdout, stderr, thread|\n\t\t\t\t\t\tstdin.write testcase.stdin\n\t\t\t\t\t\tstdin.flush\n\t\t\t\t\t\tstdin.close_write\n\t\t\t\t\t\texit_code = thread.value\n\t\t\t\t\t\toutput = stdout.read.gsub(/\\r\\n?/, \"\\n\").strip\n\t\t\t\t\t\texpected = testcase.stdout\n\t\t\t\t\t\terr = stderr.read\n\t\t\t\t\t\tstatus = nil\n\t\t\t\t\t\terr.split(\"\\n\").reverse.each do |line|\n\t\t\t\t\t\t\tnext if line[0] == \"<\"\n\t\t\t\t\t\t\tcase line.split.first\n\t\t\t\t\t\t\twhen \"TIMEOUT\"\n\t\t\t\t\t\t\t\tstatus = codes[:cpu]\n\t\t\t\t\t\t\twhen \"HANGUP\"\n\t\t\t\t\t\t\t\tstatus = codes[:hang]\n\t\t\t\t\t\t\twhen \"MEM\"\n\t\t\t\t\t\t\t\tstatus = codes[:mem]\n\t\t\t\t\t\t\twhen \"SIGNAL\"\n\t\t\t\t\t\t\t\tstatus = codes[:sig]\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tend\n\t\t\t\t\t\tif status.nil?\n\t\t\t\t\t\t\tstatus = codes[:ok] if output == expected\n\t\t\t\t\t\t\tstatus = codes[:fail] if output != expected\n\t\t\t\t\t\t\tstatus = codes[:exit] unless exit_code.success?\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\toutput = \"\"\n\t\t\t\t\t\tend\n\t\t\t\t\t\[email protected]_results.new(\n\t\t\t\t\t\t\tprogramming_test_case_id: testcase.id,\n\t\t\t\t\t\t\tstatus_code_id: status,\n\t\t\t\t\t\t\tlog: output\n\t\t\t\t\t\t)\n\t\t\t\t\t\[email protected]_code_id = status unless status == codes[:ok]\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\[email protected]_code_id = codes[:ok] if @program.status_code_id.nil?\n\t\t\tend\n\t\t\tFile.delete(outfile) if File.exist?(outfile)\n\t\tend\n\tend", "def stacktrace; end", "def compile_to_ruby\n statements.collect { |s| s.compile_to_ruby }.join(\"\\n\")\n end", "def texify exec_trace\n document_text = \"\"\n File.open \"preamble.tex\" do |file|\n while line = file.gets\n document_text += line\n end\n end\n document_text += \"\\\\begin{document}\\n\"\n stages = get_stages exec_trace\n stages.each do |stage|\n document_text += \"\\\\begin{frame}\\n\\n\"\n document_text += state_text stage.i_heap, stage.i_store\n document_text += \"\\n\"\n document_text += \"Current command: \"\n document_text += \"\\\\il{#{stage.text}}\"\n document_text += \"\\n\"\n document_text += \"\\\\vspace{1cm}\\n\\n\"\n document_text += state_text stage.f_heap, stage.f_store\n document_text += \"\\\\end{frame}\"\n document_text += \"\\n\"\n end\n document_text\nend", "def exec; end", "def exec; end", "def send_to_testrail()\n options = ArgParser.parse_opts\n # Get pass/fail/skips from junit file\n results = load_junit_results(options[:junit_file])\n\n puts \"Run results:\"\n puts \"#{results[:passes].length} Passing\"\n puts \"#{results[:failures].length} Failing or Erroring\"\n puts \"#{results[:skips].length} Skipped\"\n\n # Set results in testrail\n bad_results = set_testrail_results(results, options[:junit_file], options[:testrun_id], options[:dry_run])\n\n # Print error messages\n if not bad_results.empty?\n puts \"Error: There were problems processing these test scripts:\"\n bad_results.each do |test_script, error|\n puts \"#{test_script}:\\n\\t#{error}\"\n end\n end\n end", "def stack_trace=(_arg0); end", "def trace\n DSL.new(@source.append(Trace.new))\n end", "def execute_code source\n source.execute(@scope)\n rescue Exception => e\n message, name = @exception_service.get_exception_message(e)\n puts \"#{name}: #{message}\"\n end", "def commence\n @vm, = API.compile( @db.handle, @sql )\n\n @current_row = API.step( @vm )\n\n @columns = @current_row[ :columns ]\n @types = @current_row[ :types ]\n\n check_eof( @current_row )\n end", "def augment_fail(send, line)\n @phase = :execute\n @code = make_runnable(@code)\n\n begin\n open(\"log/simplemode.log\", 'a') do |file|\n file.puts '--------------------------------'\n file.puts Time.now\n file.puts '--------------------------------'\n file.puts @augmented_code\n file.puts \"\\n\\n\\n\"\n\n @augmented_code = nil\n end\n ensure\n send.call([\n {:write_file => {:filename => @filename, :content => @code}},\n {:execute => {:command => \"env PYTHONPATH=$LIB$/python #{VM_PYTHON} -B #{@filename}\",\n :stdout => 'executeoutput',\n :stderr => 'executeerror'}}])\n return {:type => :warning, :message => 'Start im vereinfachten Modus.'}\n end\n end", "def run(args)\n\n ## FIXME: DRY this code, tbreak and break.\n unless args.size == 1\n describe, klass_name, which, name, line, ip = \n @proc.breakpoint_position(args[1..-1])\n unless describe\n errmsg \"Can't parse temporary breakpoint location\"\n return \n end\n if name.kind_of?(Rubinius::CompiledMethod)\n bp = @proc.set_breakpoint_method(describe, name, line, ip,\n {:temp=>true, :event =>'tbrkpt'})\n unless bp\n errmsg \"Trouble setting temporary breakpoint\"\n return \n end\n else\n return unless klass_name\n begin\n klass = @proc.debug_eval(klass_name, settings[:maxstring])\n rescue NameError\n errmsg \"Unable to find class/module: #{klass_name}\"\n return\n end\n \n begin\n if which == \"#\"\n method = klass.instance_method(name)\n else\n method = klass.method(name)\n end\n rescue NameError\n errmsg \"Unable to find method '#{name}' in #{klass}\"\n return\n end\n arg_str = args[1..-1].join(' ')\n bp = @proc.set_breakpoint_method(arg_str.strip, method, line, nil,\n {:temp=>true, :event =>'tbrkpt'})\n unless bp\n errmsg \"Trouble setting temporary breakpoint\"\n return \n end\n end\n end\n @proc.continue('continue')\n end", "def source\n source = source_compiler['jison.js'].to_s\n source_compiler.each_logical_path do |logical_path|\n next if logical_path == 'jison.js'\n src = source_compiler[logical_path].to_s\n logical_path.sub! /\\.js$/, ''\n source.concat \"require.def('#{logical_path}',{factory:function(require,exports,module){#{src}}});\"\n end\n source + \"var Dock = require('dock').Dock;\"\n end", "def jumble\n command = \"\"\n\n @js_file_paths.each {|item|\n command += '--js \"' + item + '\" '\n }\n\n command += ' --js_output_file \"' + @output_file + '\"'\n \n self.exjar command\n end", "def trace( crashfile, template )\n end", "def source_location\n if @file.nil?\n args =[*(1..(arity<-1 ? -arity-1 : arity ))]\n\n set_trace_func method(:trace_func).to_proc\n call(*args) rescue nil\n set_trace_func nil\n @file = File.expand_path(@file) if @file && File.exist?(File.expand_path(@file))\n end\n [@file, @line] if @file\n end", "def trace!\n request! :trace\n end", "def jump_sql\n \n FileUtils.cd(@app_path+\"/lib/tasks\",:verbose => true)\n if File.directory? @d\n puts \"Directory #{@d} exists\"\n else\n FileUtils.mkdir @d, :mode => 0700, :verbose => true\n end\n \n FileUtils.cd(@d,:verbose => true)\n @n = Time.now.strftime(\"%H%M%S\")\n @h = File.open(@n,\"a+\")\n @h.write(\"\\n#{@sql}\\n\")\n \n end" ]
[ "0.5608189", "0.5282671", "0.52793324", "0.5163975", "0.5157312", "0.5133898", "0.51140076", "0.5084825", "0.508095", "0.50801665", "0.50302386", "0.5028595", "0.50142825", "0.49818859", "0.4976015", "0.49694765", "0.49694765", "0.4936821", "0.493411", "0.49049076", "0.49045375", "0.4896432", "0.48952708", "0.4887948", "0.48760834", "0.48705205", "0.486164", "0.4861416", "0.48612723", "0.4859598" ]
0.57624656
0
Sets the line number
def set_line(line_number) @line_number = line_number end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def lineno=(num)\n num = Maglev::Type.coerce_to(num, Fixnum, :to_int)\n @_st_lineno = num\n $. = num\n num\n end", "def line_number\n @line_number_overwrite || default_line_number\n end", "def line_numbering(value)\n @document_builder.line_numbering = value\n end", "def lineno= integer\n #This is a stub, used for indexing\n end", "def update_line_numbers!\n each_with_index do |lo, new_line_number|\n lo.line_number = new_line_number\n end\n end", "def line_number\n\t\t\t@line_index + 1\n\t\tend", "def line_number\n raise \"This loader doesn't support line_number\"\n end", "def start_line_number=(_); end", "def track_line_number(line_number)\n @min_line_number = line_number if line_number < min_line_number\n @max_line_number = line_number if line_number > max_line_number\n self\n end", "def line(number)\n end", "def lineno=(p0) end", "def lineno=(p0) end", "def lineno=(p0) end", "def line_number=(_arg0); end", "def line_number=(_arg0); end", "def line_number=(_arg0); end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line(number); end", "def lineno=(arg0)\n end", "def line_num; end", "def line_numbering=(on_or_not)\n s9_document_builder.setLineNumbering(on_or_not)\n end", "def start_line_number; end", "def start_line_number; end", "def current_line_number; end" ]
[ "0.80674815", "0.7915055", "0.7709483", "0.7512962", "0.7491955", "0.7491835", "0.73757076", "0.7301996", "0.7254114", "0.7139814", "0.7121126", "0.7121126", "0.7120693", "0.7105037", "0.7105037", "0.7105037", "0.7085615", "0.7085615", "0.7085615", "0.7085615", "0.7085615", "0.7085615", "0.7085615", "0.70800704", "0.7052069", "0.6981969", "0.69236416", "0.6901769", "0.6901769", "0.6891991" ]
0.8918514
0
gets the line number if the trace at the specified index
def get_line_number(index) if @list_of_events.length.zero? puts 'list is empty' else temp_event = @list_of_events[index] temp_event.line_number end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def line_number\n return unless backtrace and backtrace[0]\n\n backtrace[0].split(\":\")[1].to_i\n end", "def line_number\n\t\t\t@line_index + 1\n\t\tend", "def line_number(pos=pos)\n line_index(pos) + 1\n end", "def line_number(pos=pos())\n line_index(pos) + 1\n end", "def line_index()\n end", "def line_number\n env(:line_number).to_i - 1\n end", "def get_lineno\n RubyVM::Frame.get(1).source_location[0]\n end", "def extract_line_number(backtrace)\n return unless backtrace\n backtrace = backtrace.to_a\n return unless backtrace.length > 1\n m = backtrace.first.match(/^.+:(\\d+):/)\n return unless m and m.length > 1\n m[1]\n end", "def lineNum()\n caller_infos = caller.first.split(\":\")\n # Note caller_infos[0] is file name\n # caller_infos[1]\n return \"Line no. #{caller_infos[1]}\"\nend", "def line\n backtrace[0].match(Pattern)[1].to_i + 1\n end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number; end", "def line_number\n @value.line_number if @value.respond_to?(:line_number)\n end", "def line_number=(_arg0); end", "def line_number=(_arg0); end", "def line_number=(_arg0); end", "def lineNum()\n caller_infos = caller.first.split(\":\")\n # Note caller_infos[0] is file name\n caller_infos[1]\nend", "def line_index(num)\n\t\tif num == 0\n\t\t\treturn -1\n\t\telsif num <= @line_indices.length\n\t\t\treturn @line_indices[num - 1]\n\t\telsif num == @line_indices.length + 1\n\t\t\treturn @text.length\n\t\telse\n\t\t\treturn -999 # todo\n\t\tend \n\tend", "def from_line_index\n from_line - 1\n end", "def line_number\n number[6..-1]\n end", "def __caller_line_number__(caller_depth=0)\n return if RUBY_ENGINE == 'opal'\n caller[caller_depth] && caller[caller_depth][PutsDebuggerer::STACK_TRACE_CALL_LINE_NUMBER_REGEX, 1].to_i\n end", "def current_line_number; end", "def line_offset(line_index)\n return unless line_exists?(line_index)\n line_index == 0 ? 0 : @line_lengths[0..(line_index - 1)].sum\n end", "def line(number)\n lines[number - 1]\n end", "def lineno()\n #This is a stub, used for indexing\n end" ]
[ "0.77366424", "0.7610707", "0.7297889", "0.72958374", "0.7276237", "0.72306144", "0.7224381", "0.72243", "0.7223026", "0.7218484", "0.7212791", "0.7212791", "0.7212791", "0.7212791", "0.7212791", "0.7212791", "0.7212791", "0.7108751", "0.7079458", "0.7079458", "0.7079458", "0.7063498", "0.7052656", "0.7032161", "0.69649374", "0.6964637", "0.69511145", "0.69299626", "0.6905508", "0.6901239" ]
0.7773393
0
Adds the event to the list of events
def add_event(event) @list_of_events << event end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_events(new_events); end", "def <<(add)\n @_events << add \n end", "def push(event)\n @events.push(event)\n end", "def record_event(event)\n @events_mutex.synchronize do\n @events << event\n end\n end", "def add_event(event_id)\n\t\treturn ERR_UNSUCCESSFUL if not Event.exists?(event_id)\n\t\tself.event_list |= [event_id]\n\t\tself.update_attribute(:event_list, self.event_list)\n\t\tSUCCESS\n\tend", "def add_event(args)\n this_event = get_event_object(args)\n save_event(this_event)\n events\n end", "def add(name, obj)\n if @events[name] && !@events[name].include?(obj)\n @events[name] << obj\n else\n @events[name] = [obj]\n end\n end", "def save_event(event)\n @events.push(event)\n end", "def push_event event\n @event_queue << event\n end", "def add_event(e, task_id)\n @events[task_id] ||= []\n @events[task_id] << e\n end", "def add_event(event)\n @queue[event.key] = EventData.new(event)\n end", "def add message\n @events[message.sequence] = message\n end", "def fAddEvent(name,event)\n @sports.addEvent(name,event)\n end", "def subscribeTo (event)\r\n @subscribedEvents.add(event)\r\n end", "def addEvent(name, event)\n @sports[name].addEvent(event)\n @eventCount +=1\n end", "def add_event(&block) #:yield:event\n push Vevent::Maker.make( &block )\n end", "def event(event) # TODO args for events like keypress\n @events << event\n self\n end", "def add_event(from,to,kind,msg=nil)\n @bra.synchronize do\n @tits.push(Event.new(from,to,kind,msg))\n end\n end", "def add(event_klass, options)\n # TODO raise if events reach batch size?\n events << event_klass.new(self, options)\n end", "def add_event(options)\n self.events ||= []\n event = EventAssertion.new\n event.add_value(options)\n self.events << event\n end", "def push(event:)\n super\n\n @queue << event\n end", "def fired_event(event)\n history << event\n update_task_status(event)\n end", "def add_to_user_event_lists(user_list)\n\t\tuser_list.each do |users_id| \n\t\t\tuser = User.find(users_id)\n\t\t\tuser.add_event(self.id)\n\t\tend\n\tend", "def started(event)\n @started_events.push(event)\n end", "def add_event(options={})\n post('event/add', options)\n end", "def append(event_name, **data)\n id = SecureRandom.uuid\n event = Akasha::Event.new(event_name, id, { aggregate_id: aggregate_id }, **data)\n @aggregate.apply_events([event])\n @events << event\n end", "def fired_event(event)\n history << event\n\t update_task_status(event)\n end", "def add_result(new_result)\n @events=@events+new_result.events\n end", "def started(event)\n @mutex.synchronize do\n started_events << event\n all_events << event\n end\n end", "def started(event)\n started_events.push(event)\n end" ]
[ "0.77535295", "0.7713343", "0.7484306", "0.7373104", "0.73165375", "0.71663284", "0.7020312", "0.7010055", "0.69903207", "0.69689035", "0.6899304", "0.6890351", "0.68839157", "0.68167365", "0.67840266", "0.67667526", "0.67644536", "0.67023915", "0.6662739", "0.66297203", "0.65970767", "0.6584637", "0.65055925", "0.6463357", "0.6462003", "0.6456053", "0.6442099", "0.64359367", "0.6402369", "0.6400059" ]
0.90519327
0
Prints the events one by one
def print_events if @filtered_events.length.zero? puts 'List of events is empty' else (0..@filtered_events.length).each do |x| temp_event = @filtered_events[x] puts temp_event.trace end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_events(events)\n events.each do |name, description|\n puts \"Event: #{name}\"\n puts \"Description: #{description} \\n\\n\"\n end\n end", "def print_event\n clear\n @talks.sort_by {|task| task.start_time }.each do |t|\n puts \"#{t.start_time.strftime(\"%I:%M%p\").delete_prefix(\"0\").downcase} - #{t.end_time.strftime(\"%I:%M%p\").delete_prefix(\"0\").downcase}\"\n puts \" #{t.name} presented by #{t.speaker.name}\"\n end\n puts\n end", "def show_events\n @event_list.each do |restaurant, diners|\n print restaurant, diners\n end\n @event_list\n end", "def print_events(status)\n return unless events = status.events.presence\n @output.puts \"\\n#{resource_identifier(status)} events:\"\n\n groups = events.group_by { |e| [e[:type], e[:reason], (e[:message] || \"\").split(\"\\n\").sort] }\n groups.each do |_, event_group|\n count = sum_event_group(event_group)\n counter = \" x#{count}\" if count != 1\n e = event_group.first\n @output.puts \" #{e[:type]} #{e[:reason]}: #{e[:message]}#{counter}\"\n end\n end", "def print_all_events\n return NO_EVENTS_IN_CALENDAR unless events?\n\n @calendar_events.each do |date, events|\n puts \"On date #{date}:\"\n print_events(events)\n end\n end", "def listOfEvents\r\n puts (@BetESS.fDisplayEvents)\r\n end", "def displayEvents\n events = self.getAllEvents\n s = \"List of events\\n\\n\"\n events.each do |sportname, sport|\n s << \"\\t\\t\" << sportname << \"\\n\"\n sport.each do |eventID, event|\n s << event.toString << \"---\\n\"\n end\n end\n s\n end", "def run events\n events.each do |event| \n interprete event\n end\n# return\n puts \"Statistics:\"\n @counts.each do |k,v|\n puts \"#{k.inspect} =>\"\n i = 0\n step = 6\n while i < v.size\n puts \"\\t#{v[i,step]}\"\n i += step\n end\n end\n end", "def show_events(final=false)\n if @last_shown_event_id.nil?\n i = find_index(:start)\n print_events(i)\n else\n i = find_index(:last_shown)\n # puts \"last_shown index #{i}\"\n print_events(i-1) unless i == 0\n end\n\n return if final\n sleep 5 unless ENV['TEST']\n refresh_events\n end", "def list_events\n puts \"Here are the most recent events at the Cuyahoga County Public Library:\"\n all_events = Trendster::Event.all\n all_events.each do |event|\n puts \"#{all_events.index(event) + 1}. #{event.name}\"\n end\n end", "def print_pod_events(pod)\n @output.puts \"POD EVENTS:\"\n print_events(pod.events)\n end", "def stdout(event) ; $stdout.puts event ; $stdout.flush ; end", "def print(io)\n tree.each_with_index do |(command, event_called_handlerss), index|\n io.puts '+++++++++++++++++++++++++++++++++++' if index == 0\n io.puts \"Command: #{command.class} resulted in #{event_called_handlerss.length} events\"\n event_called_handlerss.each_with_index do |event_called_handlers, i|\n io.puts '' if i > 0\n io.puts \"-- Event #{event_called_handlers.event.class} was handled by:\"\n io.puts \"-- Projectors: [#{event_called_handlers.projectors.join(', ')}]\"\n io.puts \"-- Workflows: [#{event_called_handlers.workflows.join(', ')}]\"\n end\n\n io.puts '+++++++++++++++++++++++++++++++++++'\n end\n end", "def activity_output(obs)\n Thread.start do\n obs.each do |event, tuple|\n puts \"#{event} #{tuple[1]} #{tuple[3]} URI: #{tuple[2].__drburi} ref: #{tuple[2].__drbref}\"\n end\n end\n end", "def display_events(array)\n array.each do |entry|\n #binding.pry\n puts \"Event: \" + entry.title #hashies let you call keys with a .\n paragraph(entry.description) #hashies let you call keys with a .\n puts \"\"\n puts \"(press Enter to continue or 1 to finish)\"\n gets.to_i == 1 ? break : entry #entry is meaningless here, it just continues the loop.\n end\n h_line\nend", "def list\n puts \"Events for Tech:\"\n puts \"\"\n TechCliApp::Tech.all.each.with_index(1) do |tech, i|\n puts \"#{i}. #{tech.title}\"\n end\n end", "def show_events_on_date(date)\n return nil unless events_at?(date)\n\n events = @calendar_events[date]\n puts 'You have following events on this date:'\n print_events(events)\n events\n end", "def print_events_on_date(date)\n return NO_EVENTS_IN_CALENDAR unless events?\n return NO_EVENTS_AT_DATE unless events_at?(date)\n\n events = @calendar_events[date]\n puts \"Your events on #{date}\"\n print_events(events)\n end", "def print_event(printer, event)\n $stdout.puts printer.call(event)\nend", "def printall\n $page.css('.oneRes').each do |play|\n puts \"#{play.css('.eventTitle').text}---#{play.css('.detail li a')[0].text}\"\n end\nend", "def showAll()\n\t\tlogs = @log.sort\n\t\tputs \"******************LOG****************OLD\\n\"\n\t\tlogs.each { |date,item| printDate(date)\t} \n\t\tputs \"******************LOG END************NEW\\n\"\n\n\tend", "def showAll\n @logHash.each do |date, items|\n puts \"#{date}\"\n items.each do |item|\n puts \" #{item.name}\"\n end\n end\n end", "def list_events(events, question)\n\n clear_screen\n\n events_hash = events.map.with_index(1) do |event|\n {name: event.name, value: event}\n end\n\n @prompt.select(question, events_hash, per_page: 20)\n\n end", "def print_event_yml()\n # Parse the event container <aside><div><p>...</p></div></aside>\n # to get the orga dates and names\n allevents = fetch_html()\n allevents.xpath('//aside//div//p').each do |events_chunk|\n\n # # Split array in cohensive elements at once\n # elements = events_chunk.content.split(/\\,\\ |\\.\\ |\\n/)\n\n # # Puts warning\n # elements_yml = \"# Do not edit this list manually, it will be overwritten\\n\"\n # elements_yml = elements_yml + \"# in a couple of hours anyway!\\n\\n\"\n\n # elements_yml = elements_yml + \"events:\\n\"\n # i = 0\n\n # until i >= elements.length do\n # if i != nil and elements[i +3] != nil then\n # # Puts all event names out of elements\n # elements_yml = elements_yml + \" - name: \\\"\" + elements[i + 3] + \"\\\"\\n\"\n # end\n # if i != nil then\n # # Puts all event dates out of elements\n # puts elements[i + 2] + \":\" + elements[i + 1]\n # begin\n # elements_yml = elements_yml + Date.new(2018,elements[i + 2].to_i,elements[i + 1].to_i).strftime(\" date: \\\"%b %d, %Y\\\"\\n\")\n # rescue ArgumentError\n # end\n # end\n # if i != nil then\n # # Puts all event background colors\n # elements_yml = elements_yml + \" background: \\\"\" + gen_color() + \"\\\"\\n\"\n # end\n # i += 4;\n # end\n # return elements_yml\n end\nend", "def display_info(event)\n\n event.print_event_information\n\n open_in_browser(event)\n\n end", "def to_txt(events = self.events)\n # Create empty string\n txt = +''\n\n events.each do |event|\n # Add event to string\n txt << \"#{event.name} - #{event.location}\\n\"\\\n \"#{event.start_date.strftime('%d.%m.%Y %H:%M')} Uhr\"\\\n \" - #{event.end_date.strftime('%d.%m.%Y %H:%M')} Uhr\"\n\n # Adding two empty lines when current event is not the last one\n txt << \"\\n\\n\" unless events.last.name == event.name\n end\n\n txt\n end", "def show\n @tasks.each do |project_name, project_tasks|\n @output.puts project_name\n project_tasks.each do |task|\n @output.printf(\" [%c] %d: %s : %s \\n\", (task.done? ? 'x' : ' '), task.id, task.description, task.deadline)\n end\n @output.puts\n end\n end", "def each(&block)\n events.each(&block)\n end", "def print\n added .sort.each { |pod| UI.message('A'.green + \" #{pod}\", '', 2) }\n deleted .sort.each { |pod| UI.message('R'.red + \" #{pod}\", '', 2) }\n changed .sort.each { |pod| UI.message('M'.yellow + \" #{pod}\", '', 2) }\n unchanged.sort.each { |pod| UI.message('-' + \" #{pod}\", '', 2) }\n end", "def list_of_events\n @events = Event.find(:all)\n @report_name = \"List of Events\"\n end" ]
[ "0.8099862", "0.74389297", "0.7233531", "0.72172785", "0.7173616", "0.71060103", "0.69325256", "0.69086456", "0.6794468", "0.6791981", "0.66129893", "0.6533328", "0.6512295", "0.64493334", "0.64128244", "0.6406028", "0.63991565", "0.63930964", "0.6180031", "0.61016333", "0.6082304", "0.5998829", "0.59704244", "0.5964971", "0.5854875", "0.5852888", "0.5838214", "0.5837732", "0.5822928", "0.5813537" ]
0.7645054
1
Extract the execution trace for the student solution only. THis is done by finding the execution trace for the code that is surrounded by startTraceNow and endTraceNow function calls.
def exe_Point_Finder(trace) symbol_stack = [] other_list = [] top_symbol = '' exe = '' exe_point = ' ' on = false off = false trace.split('').each do |i| current_symbol = i exe_point += current_symbol if i == '{' or i == '[' or i == '(' symbol_stack << i elsif i == '}' or i == ')' or i == ']' if empty?(symbol_stack) == false top_symbol = symbol_stack.pop if i == '}' and top_symbol != '{' next end end elsif i == ',' other_list << exe_point if symbol_stack.length.zero? other_list.each do |thing| exe += thing end if exe.include? 'startTraceNow' on = true exe = '' exe_point = '' other_list = [] elsif exe.include? 'endTraceNow' off = true return else flag = verify_exe_point(on, off, exe) on = false if flag == false exe = '' exe_point = '' other_list = [] end else exe_point = '' end else next end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def trace(begX, begY, endX, endY)\n if solve(begX, begY, endX, endY)\n node = @tnode\n trace = Array.new\n while node != nil do\n trace.unshift(node.to_S)\n node = node.prev\n end\n\n trace.each do |elem|\n print elem, \" \"\n end\n print \"\\n\"\n else\n puts \"Error! No solution exists.\"\n end\n\n end", "def dump_caller_stack\n return unless $ITEST2_TRACE_EXECUTION\n begin\n caller.each_with_index do |position, idx|\n next unless position =~ /\\A(.*?):(\\d+)/\n file = $1\n # TODO: send multiple trace to be parse with pages.rb\n # next if file =~ /example\\/example_methods\\.rb$/ or file =~ /example\\/example_group_methods\\.rb$/ or file =~ /driver\\.rb$/ or file =~ /timeout\\.rb$/ # don't include rspec or ruby trace\n\n if file.include?(\"_spec.rb\") || file.include?(\"_test.rb\") || file.include?(\"_cmd.rb\")\n connect_to_itest(\" TRACE\", position)\n end\n\n break if idx > 4 or file =~ /\"_spec\\.rb$/\n end\n rescue => e\n puts \"failed to capture log: #{e}\"\n end\n end", "def trace (begX, begY, endX, endY)\n solve(begX, begY, endX, endY)\n if @result[0] == false\n puts \"No valid Path\"\n else\n result_trace(@result[1])\n end\n end", "def trace_step(&block)\n if @trace_execution_steps_counter > 0\n puts \"Trace: \" + yield.to_s\n end\n end", "def trace(s_x, s_y, e_x, e_y)\r\n\t\tstart = Place.new( s_x, s_y, nil)\r\n\t\tend_p = Place.new(e_x, e_y, nil)\r\n\t\tif check_place(start)&&check_place(end_p)\r\n\t\t\tt = MazeSolver.new(@n, @m, @maze, start, end_p).trace\r\n\t\t\tdisplay(t)\r\n\t\telse puts \"invalid start or end\" end\r\n\tend", "def trace(begX, begY, endX, endY)\n solve(begX, begY, endX, endY)\n if @maze_trace.empty?\n return\n else\n @maze_trace.each do |i|\n print \"#{i} -> \"\n end\n print \"exit\"\n end\n end", "def trace(args)\n if solve(args)\n path_stack, current_cell = [], @seen_stack.last\n path_stack.push(current_cell)\n until @seen_stack.empty?\n current_cell = find_steps(current_cell, path_stack)\n end\n path_stack.reverse.each { |cell| print \"-->#{cell} \" }\n puts \"\"\n path_stack\n else nil\n end\n end", "def seperate_and_filter_trace(junit_test_file,\n files_path,\n peruser_files_path,\n student_file_name)\n code_and_trace = generate_backend_trace(junit_test_file,\n files_path,\n peruser_files_path,\n student_file_name)\n splitter = '\"' + 'trace' + '\"' + ':'\n user_code, whole_trace = code_and_trace.split(splitter)\n\n whole_trace = whole_trace[1..whole_trace.length]\n\n entire_json_file = code_analyzer(user_code, whole_trace)\n\n entire_json_file\nend", "def main_method(file_path, student_full_code)\n my_test = seperate_and_filter_trace(student_full_code, file_path,\n 'cp/traceprinter/', 'output.txt')\n Dir.chdir('/home')\n #puts my_test\n my_test\nend", "def trace_execution_steps(&block)\n begin\n @trace_execution_steps_counter += 1\n yield\n ensure\n @trace_execution_steps_counter -= 1\n end\n end", "def visit_trace(code, ins, local_vars, ln, info)\r\n end", "def trace(begX, begY, endX, endY); MazeSolver.new(plane,graph).trace(begX, begY, endX, endY) end", "def __trace(*args, **opt, &block)\n __trace_impl(*args, **opt, &block)\nend", "def trace_execution_scoped_header(options, t0=Time.now.to_f)\n scope = log_errors(\"trace_execution_scoped header\") do\n push_flag!(options[:force])\n scope = stat_engine.push_scope(:method_tracer, t0, options[:deduct_call_time_from_parent])\n end\n # needed in case we have an error, above, to always return\n # the start time.\n [t0, scope]\n end", "def trace (begX, begY, endX, endY)\n beg_x = 2 * begY + 1\n beg_y = 2 * begX + 1\n end_x = 2 * endY + 1\n end_y = 2 * endX + 1\n @visit = Array.new(@maze_table.size){Array.new(@maze_table[0].size, false)}\n @track = []\n if scout(beg_x, beg_y, end_x, end_y)\n printf \"it is a path between %s and %s \\n\", [begX, begY], [endX, endY]\n @track.each do |i|\n printf \"Position: (%s, %s)\\n\", (i[1]-1)/2, (i[0]-1)/2 if i[0] % 2 ==1 && i[1] % 2 == 1\n end\n end\n end", "def get_execution_info; end", "def trace(begX, begY, endX, endY)\n path,solution = solve(begX, begY, endX, endY)\n if(solution.length != 0)\n solution.each{|x| self.graph[x[0]][x[1]] = '@'}\n puts graph.map { |x| x.join(' ') }\n else\n puts \"There are no way from #{[begX,begY]} to #{[endX,endY]}\"\n end\n end", "def trace\n set_trace_func proc { |event, _file, _line, id, binding, classname|\n if event == watched && id != :log && classes.include?(classname.to_s)\n vars = variables(binding)\n\n if vars.empty?\n log_this(sprintf(\"%s %-25s #%-20s\",\n class_count, classname, id))\n\n else\n log_this(sprintf(\"%s %-25s #%-20s\\n%s\\n\",\n class_count, classname, id, vars))\n\n end\n end\n } if trace?\n end", "def tracing()\n #This is a stub, used for indexing\n end", "def trace *args, &block\n\n\t\treturn nil unless tracing?\n\n\t\ttrace_with_block_ 1, args, &block\n\tend", "def possibly_add_trace_info_calls(line)\n # If the current line does not start a logical line, don't bother\n if not @state[:ll_start]\n return line\n end\n\n # We will be making decisions based on the first word on the line\n line_words = line.split\n if line_words.empty?\n # The line is empty, so we disregard it\n return line\n end\n first_word = line_words[0]\n\n # Extract first word and check if it makes us want to refrain from adding a line number call\n if KEYWORDS_WITHOUT_LINE_NUMBERS.include?(first_word)\n # It's one of the statements we don't want\n return line\n\n elsif [\"'\", '\"', \"#\"].include?(first_word[0])\n # The line starts with a string or with a comment\n return line\n end\n\n # Do include a line number call\n return \"#{@state[:indent_string]}garbledwebpiratenlibraryname.debug(locals(), globals())\\n\" +\n \"#{@state[:indent_string]}garbledwebpiratenlibraryname.line(#{@state[:line_number]})\\n\" +\n \"#{line}\"\n end", "def current_trace\n if @@spans.empty?\n nil\n else\n @@spans.slice(-1)\n end\n end", "def texify exec_trace\n document_text = \"\"\n File.open \"preamble.tex\" do |file|\n while line = file.gets\n document_text += line\n end\n end\n document_text += \"\\\\begin{document}\\n\"\n stages = get_stages exec_trace\n stages.each do |stage|\n document_text += \"\\\\begin{frame}\\n\\n\"\n document_text += state_text stage.i_heap, stage.i_store\n document_text += \"\\n\"\n document_text += \"Current command: \"\n document_text += \"\\\\il{#{stage.text}}\"\n document_text += \"\\n\"\n document_text += \"\\\\vspace{1cm}\\n\\n\"\n document_text += state_text stage.f_heap, stage.f_store\n document_text += \"\\\\end{frame}\"\n document_text += \"\\n\"\n end\n document_text\nend", "def trace_execution_scoped_footer(t0, first_name, metric_names, expected_scope, options, t1=Time.now.to_f)\n log_errors(\"trace_method_execution footer\") do\n pop_flag!(options[:force])\n if expected_scope\n scope = stat_engine.pop_scope(expected_scope, first_name, t1)\n duration = t1 - t0\n exclusive = duration - scope.children_time\n record_metrics(first_name, metric_names, duration, exclusive, options)\n end\n end\n end", "def thread_stack_trace(tid)\r\n with_suspended_thread(tid) do\r\n ctx = thread_context(tid)\r\n if((start = read32(ctx.Ebp)) != 0) \r\n a = start\r\n stack = [[start, read32(start+4)]]\r\n while((a = read32(a)) and a != 0 and not stack.member?(a))\r\n begin\r\n stack << [a, read32(a+4)]\r\n rescue; break; end\r\n end\r\n return stack\r\n end\r\n end\r\n []\r\n end", "def trace( *args )\n\t\tRake.application.trace( *args ) if Rake.application.options.trace\n\tend", "def stacktrace\n result = caller().reduce([]) do |memo, loc|\n if loc =~ /\\A(.*\\.pp)?:([0-9]+):in\\s(.*)/\n # if the file is not found we set to code\n # and read from Puppet[:code]\n # $3 is reserved for the stacktrace type\n memo << [$1.nil? ? :code : $1, $2.to_i]\n end\n memo\n end.reverse\n end", "def find_calling_line(trace, method_name)\n trace.each_cons(2) do |line, next_line|\n if /(.*):(\\d+):in .(.*)'/ =~ line && \n $3 == method_name &&\n /(.*):(\\d+):in .(.*)'/ =~ next_line\n return [$1,$2]\n end\n end\n nil\n end", "def trace!(*methods)\n@_traced = @_traced || []\n# Remember the set of traced methods\n# If no methods were specified, use all public methods defined\n# directly (not inherited) by the class of this object\nmethods = public_methods(false) if methods.size == 0\nmethods.map! {|m| m.to_sym } # Convert any strings to symbols\nmethods -= @_traced\n# Remove methods that are already traced\nreturn if methods.empty?\n# Return early if there is nothing to do\n@_traced |= methods\n# Add methods to set of traced methods\n# Trace the fact that we're starting to trace these methods\nSTDERR << \"Tracing #{methods.join(', ')} on #{object_id}\\n\"\n# Singleton methods are defined in the eigenclass\neigenclass = class << self; self; end\nmethods.each do |m|\n# For each method m\n# Define a traced singleton version of the method m.\n# Output tracing information and use super to invoke the\n# instance method that it is tracing.\n# We want the defined methods to be able to accept blocks, so we\n# can't use define_method, and must instead evaluate a string.\n# Note that everything between %Q{ and the matching } is a\n# double-quoted string, not a block. Also note that there are\n# two levels of string interpolations here. #{} is interpolated\n# when the singleton method is defined. And \\#{} is interpolated\n# when the singleton method is invoked.\neigenclass.class_eval %Q{\ndef #{m}(*args, &block)\nbegin\nSTDERR << \"Entering: #{m}(\\#{args.join(', ')})\\n\"\nresult = super\nSTDERR << \"Exiting: #{m} with \\#{result}\\n\"\nresult\nrescue\nSTDERR << \"Aborting: #{m}: \\#{$!.class}: \\#{$!.message}\"\nraise\nend\nend\n}\nend\nend", "def code_splitter(code)\n student_code = []\n code = code.split('startTraceNow();')\n new_code = code[1].split('endTraceNow();')\n executed_code = new_code[0]\n executed_code_list = executed_code.split('\\\\n')\n flag = false\n counter = 0\n until flag\n if executed_code_list[counter] == '' || executed_code_list[counter] == ' '\n flag = false\n counter += 1\n elsif executed_code_list[counter] != ''\n flag = true\n end\n end\n x = counter\n while x < executed_code_list.length\n temp = executed_code_list[x]\n temp = temp.strip\n student_code << executed_code_list[x] unless temp.empty?\n\n x += 1\n end\n student_code\nend" ]
[ "0.61676794", "0.61020243", "0.5964391", "0.5948465", "0.59072137", "0.58359414", "0.57576954", "0.5685536", "0.5553746", "0.55075586", "0.5504756", "0.54980147", "0.54239726", "0.54068494", "0.5302817", "0.53017026", "0.52682984", "0.52546424", "0.52263254", "0.5190801", "0.5188089", "0.51726574", "0.51440316", "0.51427925", "0.513538", "0.51321787", "0.51223373", "0.51214576", "0.5115813", "0.5101122" ]
0.63415736
0
GET /podvals GET /podvals.xml
def index @podvals = Podval.find(:all) @podval = Podval.find_by_main(1) if @podval == nil @podvals = Podval.find_all_by_vis(1) @podval = @podvals.choice end respond_to do |format| format.html # index.html.erb format.xml { render :xml => @podvals } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def values(params = {})\n @client.get(\"#{path}/values\", params)\n end", "def new\n @podval = Podval.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @podval }\n end\n end", "def get_prop(values)\n cmd = \"{\\\"id\\\":1,\\\"method\\\":\\\"get_prop\\\",\\\"params\\\":[#{values}]}\\r\\n\"\n request(cmd)\n end", "def destroy\n @podval = Podval.find(params[:id])\n @podval.destroy\n\n respond_to do |format|\n format.html { redirect_to(podvals_url) }\n format.xml { head :ok }\n end\n end", "def index\n @known_values = KnownValue.find(:all, :order => 'name')\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @known_values }\n end\n end", "def vulnerability_value\n query_root_node(\"gdacs:vulnerability/@value\", @@NAMESPACES)\n end", "def propfind\n unless(resource.exist?)\n NotFound\n else\n unless(request_document.xpath(\"//#{ns}propfind/#{ns}allprop\").empty?)\n properties = resource.properties\n else\n check = request_document.xpath(\"//#{ns}propfind\")\n if(check && !check.empty?)\n properties = request_document.xpath(\n \"//#{ns}propfind/#{ns}prop\"\n ).children.find_all{ |item|\n item.element?\n }.map{ |item|\n # We should do this, but Nokogiri transforms prefix w/ null href into\n # something valid. Oops.\n # TODO: Hacky grep fix that's horrible\n hsh = to_element_hash(item)\n if(hsh.namespace.nil? && !ns.empty?)\n raise BadRequest if request_document.to_s.scan(%r{<#{item.name}[^>]+xmlns=\"\"}).empty?\n end\n hsh\n }.compact\n else\n properties = []\n end\n end\n multistatus do |xml|\n find_resources.each do |resource|\n xml.response do\n unless(resource.propstat_relative_path)\n xml.href \"#{scheme}://#{host}:#{port}#{url_format(resource)}\"\n else\n xml.href url_format(resource)\n end\n propstats(xml, get_properties(resource, properties.empty? ? resource.properties : properties))\n end\n end\n end\n end\n end", "def index\n @config_values = ConfigValue\n .page(params[:page])\n .per(10)\n end", "def vips\n request :get, '/vips'\n end", "def vitals\n raise UserNotAuthenticated unless access_token\n\n get('records/vitals')\n end", "def values_search(params)\n @client.get(\"#{path}/values/search\", nil, params, \"Content-Type\" => \"application/json\")\n end", "def index\n @policy_valuations = PolicyValuation.all\n end", "def index\n @ipadmissions = Ipadmission.all\n\t@v= Verify.new\n\t@[email protected](\"IP Admission\")\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ipadmissions }\n end\n end", "def index\n @pod_reports = PodReport.all\n end", "def ps(app_name)\n deprecate # 07/31/2012\n json_decode get(\"/apps/#{app_name}/ps\", :accept => 'application/json').to_s\n end", "def getNodeList\n broker_url = APP_CONFIG['broker_ip'] + ':' + APP_CONFIG['broker_port'].to_s\n result = HTTParty.get(broker_url + \"/resources/nodes\", :verify => false)\n temp2 = JSON.parse(result.body)\n\n node_data = temp2[\"resource_response\"][\"resources\"]\n return node_data\n \n end", "def list_uptime_check_configs project_id\n require \"google/cloud/monitoring\"\n\n client = Google::Cloud::Monitoring.uptime_check_service\n project_name = client.project_path project: project_id\n configs = client.list_uptime_check_configs parent: project_name\n\n configs.each { |config| puts config.name }\nend", "def list_tasks(api_object)\n puts \"Current Tasks:\"\n doc = Nokogiri::XML.parse api_object.read\n puts doc\n descriptions = doc.xpath('tasks/task/description').collect {|e| e.text }\n puts descriptions.join(\", \")\n puts \"\"\nend", "def votd\n require 'rss'\n\n votd = RSS::Parser.parse('https://www.biblegateway.com/usage/votd/rss/votd.rdf?31', false)\n\n render json: votd\n end", "def value\n @value ||= XmlRpc::API::Message.parse_value(@document.root.elements[\"params/param/value\"])\n end", "def values\n root.values\n end", "def index\n @chef_values = ChefValue.all\n end", "def healthinfo_doc\n begin\n timeout(3) do\n return XML::Parser.string(open(\"#{@@rn_url}#{params[:id]}\").read).parse() \n end\n rescue Exception\n return nil\n rescue Timeout::Error\n return nil\n end\n end", "def show\n @prop_value = PropValue.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @prop_value }\n end\n end", "def get_listings_xml(url)\n @client.get_content(url)\n end", "def get_xml\n response = @api.request(:get, @location, type: 'xml')\n response.body if response.status == 200\n end", "def get; end", "def read_pods\n kubeclient = build_kube_client!\n\n kubeclient.get_pods(namespace: actual_namespace).as_json\n rescue Kubeclient::ResourceNotFoundError\n []\n end", "def index\n @peeps = Peep.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @peeps }\n end\n end", "def list\n get()\n end" ]
[ "0.60993767", "0.57483554", "0.56734437", "0.5239529", "0.5156862", "0.5083917", "0.50354815", "0.5031465", "0.49419847", "0.492067", "0.49194166", "0.49026126", "0.4887002", "0.48712024", "0.48311663", "0.481108", "0.48047805", "0.4791674", "0.47803277", "0.47778094", "0.47694853", "0.47592637", "0.47510523", "0.47422883", "0.47387832", "0.47378471", "0.47279283", "0.47221", "0.4706451", "0.4685849" ]
0.66280293
0
GET /podvals/new GET /podvals/new.xml
def new @podval = Podval.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @podval } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def new\n @prop_value = PropValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prop_value }\n end\n end", "def new\n @versioned_jnlp_url = MavenJnlp::VersionedJnlpUrl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @versioned_jnlp_url }\n end\n end", "def new\n @known_value = KnownValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @known_value }\n end\n end", "def new\n @pdig = Pdig.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pdig }\n end\n end", "def new\n @p_stat = PStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @p_stat }\n end\n end", "def new\n @versioned_jnlp = MavenJnlp::VersionedJnlp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @versioned_jnlp }\n end\n end", "def new\n @pulve = Pulve.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pulve }\n end\n end", "def get_all_new\n uri = [@@base_uri, 'all', 'getAllNew'].join('/')\n return get(uri)\n end", "def new\n @prd_threshold = PrdThreshold.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prd_threshold }\n end\n end", "def new\n @periode = Periode.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @periode }\n end\n end", "def new\n @newtype = params[:newtype]\n @ptbudget = Ptbudget.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ptbudget }\n end\n end", "def new\n @config_value = ConfigValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @config_value }\n end\n end", "def new\n @app_version = @app.app_versions.build\n # @app_version = AppVersion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @app_version }\n end\n end", "def new\n @prop = Prop.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prop }\n end\n end", "def new\n @param_value = ParamValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @param_value }\n end\n end", "def new_rest\n @instrument_version = InstrumentVersion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @instrument_version }\n end\n end", "def new\n @probe = Probe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @probe }\n end\n end", "def new\n @precio = Precio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @precio }\n end\n end", "def new\n @retain_node = RetainNode.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @retain_node }\n format.json { render :json => @retain_node }\n end\n end", "def new_releases\n api_call(\"https://api.spotify.com/\",\"/v1/browse/new-releases\")\n end", "def new\n @promos = Promos.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @promos }\n end\n end", "def new\n @occurence = Occurence.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @occurence }\n end\n end", "def new\n @novel = Novel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @novel }\n end\n end", "def new\n @erratum = Erratum.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @erratum }\n end\n end", "def new\n @st_pi = StPi.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @st_pi }\n end\n end", "def new\n @peep = Peep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @peep }\n end\n end", "def new\n @period = Period.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @period }\n end\n end", "def new\n @resp = Response.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @resp }\n end\n end", "def new\n @ref = Ref.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ref }\n end\n end" ]
[ "0.62041026", "0.5975784", "0.59499407", "0.58696115", "0.5821277", "0.58180106", "0.5790565", "0.5777775", "0.5769915", "0.5724539", "0.56767046", "0.5672125", "0.56688523", "0.5617821", "0.5609206", "0.5586452", "0.55854684", "0.558404", "0.55838054", "0.5582039", "0.5566621", "0.55627483", "0.5544045", "0.55416536", "0.55385816", "0.55326873", "0.5519811", "0.55188435", "0.5516727", "0.5514215" ]
0.7312344
0
DELETE /podvals/1 DELETE /podvals/1.xml
def destroy @podval = Podval.find(params[:id]) @podval.destroy respond_to do |format| format.html { redirect_to(podvals_url) } format.xml { head :ok } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def netdev_resxml_delete( xml )\n top = netdev_resxml_top( xml )\n par = top.instance_variable_get(:@parent)\n par['delete'] = 'delete'\n end", "def delete_data(index_name)\n uri = @client.make_uri(\"/#{index_name}/update/\")\n req = HTTP::Post.new(uri)\n req.content_type = 'text/xml'\n req.body = '<delete><query>*:*</query></delete>'\n response = @client.send_http(req, true, ['200'])\n end", "def delete()\n response = send_post_request(@xml_api_delete_path)\n response.is_a?(Net::HTTPSuccess) or response.is_a?(Net::HTTPRedirection)\n end", "def destroy\n RestClient.delete \"#{REST_API_URI}/contents/#{id}.xml\" \n self\n end", "def delete()\n response = send_post_request(@xml_api_delete_path)\n response.is_a?(Net::HTTPSuccess) or response.is_a?(Net::HTTPRedirection)\n end", "def delete(path, params)\n parse_response @client[path].delete(:params => params)\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def delete path\n make_request(path, \"delete\", {})\n end", "def delete(*uris); end", "def delete\n response = WebPay.client.delete(path)\n response['deleted']\n end", "def delete_data\n response = WebPay.client.delete([path, 'data'].join('/'))\n response['deleted']\n end", "def delete(path, params = {})\n debug_log \"DELETE #{@host}#{path} params:#{params}\"\n res = connection.delete path, params\n debug_log \"Response status:#{res.status}, body:#{res.body}\"\n res\n end", "def delete(value)\n end", "def delete(value)\n end", "def delete(value)\n find_node(value)&.delete\n end", "def delete(path, params)\n request(:delete, path, {})\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @prop_value = PropValue.find(params[:id])\n @prop_value.destroy\n\n respond_to do |format|\n format.html { redirect_to(prop_values_url) }\n format.xml { head :ok }\n end\n end", "def deleteResource(doc, msg_from)\n \n \n begin\n\n puts \"Deleting\"\n\n path = \"\"\n params = {}\n headers = {}\n \n context, path = findContext(doc, path) \n \n # Deleting member from group\n if context == :user_group_member\n params = {}\n else\n raise Exception.new(\"No context given!\")\n end\n \n httpAndNotify(path, params, msg_from, :delete)\n \n rescue Exception => e\n puts \"Problem in parsing data (CREATE) from xml or sending http request to the VR server: \" + e\n puts \" -- line: #{e.backtrace[0].to_s}\"\n end\n \n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def delete(value)\n delete_node(find(value))\n end", "def delete\n Iterable.request(conf, base_path).delete\n end", "def delete(path, params={})\n request(:delete, path, params)\n end" ]
[ "0.64152956", "0.6399643", "0.6387767", "0.6370322", "0.6267758", "0.6196657", "0.6159628", "0.613705", "0.61281145", "0.61144996", "0.60902584", "0.6066382", "0.6052238", "0.6052238", "0.60420334", "0.6035436", "0.6028942", "0.60017455", "0.59953773", "0.5993745", "0.5993745", "0.5993745", "0.5993745", "0.5993745", "0.5993745", "0.5993745", "0.5982569", "0.59658897", "0.5965781", "0.5940262" ]
0.7289542
0
GET /properties/new GET /properties/new.json
def new @property = Property.new respond_to do |format| format.html # new.html.erb format.json { render json: @property } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n @property = Property.new\n\n\t\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end", "def new\n @prop = Prop.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @prop }\n end\n end", "def new\n @property = @user.properties.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @property }\n end\n end", "def new\n @property_field = PropertyField.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property_field }\n end\n end", "def new\r\n property = Property.new\r\n property.save\r\n puts \"\\nStarting with new property #{property.id}\\n\\n\"\r\n create_or_continue_property(property)\r\n end", "def new\n @sample_property = SampleProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sample_property }\n end\n end", "def new\n @rent = Rent.new\n @properties = AddProperty.find(:all, :conditions =>\" is_rented = 0 \");\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @rent }\n end\n end", "def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @property }\n end\n end", "def new\n @location_property = LocationProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @location_property }\n end\n end", "def new\n @quick_property = QuickProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @quick_property }\n end\n end", "def new\n @propose = Propose.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @propose }\n end\n end", "def new\n @property_user = PropertyUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property_user }\n end\n end", "def new\n @prop = Prop.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prop }\n end\n end", "def create\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @property_picture = PropertyPicture.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property_picture }\n end\n end", "def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @property = Property.new(property_params)\n\n if @property.save\n render json: @property, status: :created, location: @property\n else\n render json: @property.errors, status: :unprocessable_entity\n end\n end", "def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render action: 'show', status: :created, location: @property }\n else\n format.html { render action: 'new' }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render action: 'show', status: :created, location: @property }\n else\n format.html { render action: 'new' }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @tenant = Tenant.new\n @property = Property.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tenant }\n end\n end", "def new\n @prop_value = PropValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prop_value }\n end\n end" ]
[ "0.7802905", "0.7802905", "0.7802905", "0.7802905", "0.7802905", "0.7799518", "0.77899367", "0.77023524", "0.7676439", "0.7641626", "0.7340625", "0.7294141", "0.72753036", "0.72743183", "0.7229975", "0.7199456", "0.71836406", "0.70413727", "0.6951421", "0.6927972", "0.6655688", "0.662418", "0.6621279", "0.6621279", "0.66195035", "0.66193503", "0.6585007", "0.6585007", "0.6576393", "0.6551314" ]
0.780913
0
Reset all associated sheets total_response_count to nil to trigger refresh of sheet answer coverage
def reset_sheet_total_response_count sheets.where(missing: false).update_all(response_count: nil, total_response_count: nil, percent: nil) sheets.where(missing: true).update_all(response_count: 0, total_response_count: 0, percent: 100) SubjectEvent.where(id: sheets.select(:subject_event_id)).update_all( unblinded_responses_count: nil, unblinded_questions_count: nil, unblinded_percent: nil, blinded_responses_count: nil, blinded_questions_count: nil, blinded_percent: nil ) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset\n @results = @hits = @verified_hits = @total = @solr_response = @doc_ids = nil\n end", "def reset\n @results = @hits = @verified_hits = @total = @solr_response = @doc_ids = nil\n end", "def reset\n total_calls.clear\n total_success_calls.clear\n total_failed_calls.clear\n end", "def clear_all\n @sheets = []; self\n end", "def reset_stats\n self.actual_rounds = 0\n self.points = 0\n self.average = 0.0\n self.total_correct = 0\n self.total_errors = 0\n self.rank = 0\n \n # total quizzes\n total_quizzes = 0\n self.quiz_team.round_teams.each do |round_team|\n total_quizzes += 1 if round_team.round.complete? and round_team.round.from_prelims?\n end\n self.total_rounds = total_quizzes\n end", "def reset\n @count = 0\n end", "def reset_hit_count\n \"0\"\n end", "def reset\n @previous_valid_total_score = 0\n @previous_valid_scores = Hash.new(0)\n end", "def reset_stats; reset!; end", "def reset!\n @last_response = nil\n @last_exit_code = nil\n end", "def reset\n @results = {}\n @success = false\n end", "def clear_stats\n reset!\n NewRelic::Agent::BusyCalculator.reset\n end", "def reset_results\n @loaded = false\n @results = ResultSet.new\n @solr_response = nil\n end", "def reset\n @results = []\n @number = 0\n @score = 0\n @average = 0\n @min = 0\n @max = 0\n end", "def reset_statistics!; end", "def reset_statistics!; end", "def reset_discounts\n @discounts = []\n end", "def stats_reset\n @stats = nil\n end", "def reset_contents\n self.quizzes.destroy_all\n end", "def reset_response\n self.instance_variable_set(:@_response_body, nil)\n end", "def reset_stats\n self.rounds = 0\n self.wins = 0\n self.losses = 0\n self.total_points = 0\n self.rank = 0\n end", "def reset_response\n self.instance_variable_set(:@_response_body, nil)\n end", "def clear\n @total = 0\n end", "def reset_all_statistics\n super\n end", "def reset\n @errors = []\n @journal_rows = []\n @journaled_facility_ids = Set.new\n @product_recharges = {}\n end", "def reset()\n #This is a stub, used for indexing\n end", "def reset()\n #This is a stub, used for indexing\n end", "def reset!\n executions.reset\n end", "def reset\n @dice_cup.clear\n @number_of_dice = 6\n @farkle_count= 0\n end", "def reset_abs_data\n # reset killed battlers arrays and the counters\n @killed, @battlers_number = {}, {}\n end" ]
[ "0.6726427", "0.6726427", "0.66224194", "0.6501848", "0.6456136", "0.6179454", "0.61737", "0.6166184", "0.6092449", "0.6084171", "0.6077026", "0.6005463", "0.5977864", "0.5970744", "0.59525883", "0.59525883", "0.5930283", "0.5920953", "0.5910665", "0.5909001", "0.59019107", "0.58992356", "0.58723444", "0.5848999", "0.5819857", "0.57671905", "0.57671905", "0.5738055", "0.5732397", "0.5730844" ]
0.8666964
0
POST /api/favourites?key= curl X POST v u admin:admin
def create favourite=current_user.add_favourite(params[:key]) if favourite respond_to do |format| format.json { render :json => jsonp(favourites_to_json([favourite])) } format.xml { render :xml => favourites_to_xml([favourite]) } format.text { render :text => text_not_supported } end else render_error('Favourite not found', 404) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_favorite(id)\n post \"favorites/create/#{id}\", {}\n end", "def favorite(action, value)\n raise ArgumentError, \"Invalid favorite action provided: #{action}\" unless @@FAVORITES_URIS.keys.member?(action)\n value = value.to_i.to_s unless value.is_a?(String)\n uri = \"#{@@FAVORITES_URIS[action]}/#{value}.json\"\n case action\n when :add\n response = http_connect {|conn| create_http_post_request(uri) }\n when :remove\n response = http_connect {|conn| create_http_delete_request(uri) }\n end\n bless_model(Twitter::Status.unmarshal(response.body))\n end", "def favorite(id)\n post(\"/favorites/create/#{id}.json\")\n end", "def add_favorite username, password, slideshow_id\n do_request 'add_favorite', username: username, password: password, slideshow_id: slideshow_id\n end", "def getFavorites(userID, ofWhat)\n request('getFavorites', {'userID' => userID, 'ofWhat' => ofWhat})\nend", "def create\n @favorite = current_user.favoritables.build(favorite_params)\n\n if @favorite.save\n render json: @favorite, status: :created\n else\n render json: @favorite.errors, status: :unprocessable_entity\n end\n end", "def favorite_foods\n get(\"/user/#{@user_id}/foods/log/favorite.json\")\n end", "def index\n authorize! :index, Spree::Favorite\n @favorites = spree_current_user.favorites\n respond_to do |format|\n format.html\n format.json { render json: @favorites }\n end\n end", "def add_to_favourites\n \n #pull out whichever recipe you are clicking on\n yummly_id = params[:yummly_id]\n recipe = Yummly.find(yummly_id)\n\n # make new instance of that recipe\n r = Recipe.find_or_create_by(name: recipe.name, thumbnail: recipe.thumbnail)\n\n UserFavouriteRecipe.create(recipe_id: r.id, user_id: current_user.id, yummly_id: yummly_id)\n\n redirect_to recipes_url, notice: \"Added recipe from your list of favourite recipes\"\n\n end", "def favourite\n if session[:user_id] == nil\n render json: {code: 401}\n else\n url_id = params[:id]\n url = Url.find_by(id: url_id)\n current_user = User.find_by(id: session[:user_id])\n if current_user.urls.exists?(url_id)\n current_user.urls.delete(url)\n favourite = false\n else\n current_user.urls << url\n favourite = true\n end\n users = url.users\n render json: {code: 200, favourite: favourite, users: users}\n end\n end", "def index\n @favorites = current_user.favorites\n render json: Api::V1::WatchableSerializer.new(@favorites.map(&:favoritable)).serialized_json\n end", "def create\n @favourite = Favourite.new(favourite_params)\n\n respond_to do |format|\n if @favourite.save\n sync_update @favourite.fav_post\n format.html { redirect_to :my_favourites, notice: 'Favourite was successfully created.' }\n format.json { render json: @favourite }\n else\n format.json { render json: @favourite.errors, status: :unprocessable_entity }\n end\n end\n end", "def mark_favourite\n @favourite_artist = FavouriteArtist.where(spotify_id: params[:spotify_id]).first_or_create(_params)\n render :json => @favourite_artist.to_json\n end", "def favorites(action=nil)\n my.favorites(action)\n end", "def index\n respond_with @favorites\n end", "def set_api_favorite\n @api_favorite = Api::Favorite.find(params[:id])\n end", "def create\n @favourites = Favourite.new()\n @favourites.user_id = current_user.id;\n @favourites.army_list_id = params[:favourite][:army_list_id]\n \n respond_to do |format|\n if @favourites.save\n flash[:notice] = 'Favourites was successfully created.'\n format.html { redirect_back_or_default(user_favourites_url(current_user)) }\n format.xml { render :xml => @favourites, :status => :created, :location => @favourites }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @favourites.errors, :status => :unprocessable_entity }\n end\n end\n end", "def get_user_favorites username_for\n do_request 'get_user_favorites', username_for: username_for\n end", "def add_word_to_favorites(word, *args)\n http_method = :post\n path = '/word/{word}/favorite'\n path.sub!('{word}', word.to_s)\n\n # Ruby turns all key-value arguments at the end into a single hash\n # e.g. Wordnik.word.get_examples('dingo', :limit => 10, :part_of_speech => 'verb')\n # becomes {:limit => 10, :part_of_speech => 'verb'}\n last_arg = args.pop if args.last.is_a?(Hash)\n last_arg = args.pop if args.last.is_a?(Array)\n last_arg ||= {}\n\n # Look for a kwarg called :request_only, whose presence indicates\n # that we want the request itself back, not the response body\n if last_arg.is_a?(Hash) && last_arg[:request_only].present?\n request_only = true\n last_arg.delete(:request_only)\n end\n\n params = last_arg\n body ||= {}\n request = Wordnik::Request.new(http_method, path, :params => params, :body => body)\n request_only ? request : request.response.body\n end", "def get_favorites\n authenticate_rem\n follower = @current_user || User.find_by_id(params[:user_id])\n render json: Product.order(created_at: :desc).limit(20).map(&:simple_info.with(follower)),\n status: :ok\n end", "def add_favorite_food(food_id)\n post(\"/user/#{@user_id}/foods/log/favorite/#{food_id}.json\")\n end", "def test_new_favourite_and_remove_favourite\n \n user = User.getByUsername(\"Adam\")\n bookmark = Bookmark.getAll[0]\n \n result = Favourite.newFavourite(bookmark.bookmarkId, user.userId)\n \n assert_equal true, result\n \n favourites = Favourite.getByUserId(user.userId)\n \n favourite = favourites[0]\n \n assert_equal \"amazon\", favourite.title\n assert_equal bookmark.bookmarkId, favourite.bookmarkId\n \n resultTwo = Favourite.removeFavourite(bookmark.bookmarkId, user.userId)\n \n assert_equal true, resultTwo\n \n end", "def favourite_params\n params.require(:favourite).permit(:user_id, :fav_post_id)\n end", "def show_favorites\n authenticate_rem\n follower = @current_user || User.find_by_id(params[:user_id])\n render json: follower.favorite_products.map(&:simple_info.with(follower)), status: :ok\n end", "def create\n @favorite = current_user.favorites.build(params[:favorite])\n if @favorite.save\n flash[:notice] = \"Favorite saved!\"\n end\n # redirect_to root_path\n respond_with(@favorite)\n end", "def create\n @favorite = user.favorites.new(favorite_params)\n\n if @favorite.save\n render :show, status: :ok\n else\n render json: @favorite.errors, status: :unprocessable_entity\n end\n end", "def add_to_favorites(new_fav)\n @fav_list << new_fav \n end", "def index #devolver todos os filmes e series que a gente escolheu\n # (@favorites.map(&:favoritable)) - esta serializando todos os favoritos.\n # map -faz um mapeamento\n #tabela favorite campo favoritable, e mapeia todas as series e videos, com watchableserializer.\n @favorites = current_user.favorites.all \n render json: Api::V1::WatchableSerializer.new(@favorites.map(&:favoritable)).serialized_json\n end", "def set_favorite\n @json = Punk::API.one_beer!(params[:id])\n @json = @json&.first\n if FavoriteBeer.where(punk_id: @json[:punk_id], user_id: @current_user.id).empty?\n @fav_beer = FavoriteBeer.new(@json)\n @fav_beer.user_id = @current_user.id.to_i\n @fav_beer.save!\n end\n\n @json[:favorite] = true\n render json: {\n favorite_beer_set: @json\n }\n end", "def my_favorites\n\tend" ]
[ "0.6387259", "0.6329252", "0.6308692", "0.6107945", "0.60683686", "0.60001296", "0.5972972", "0.5876344", "0.5863978", "0.58421916", "0.5823987", "0.58015203", "0.5791557", "0.5779967", "0.57413447", "0.57254255", "0.56926626", "0.5689076", "0.56798154", "0.56775385", "0.56735367", "0.56696975", "0.56607985", "0.5636885", "0.5631434", "0.5603446", "0.5597447", "0.55931413", "0.5587963", "0.55848813" ]
0.6386259
1
Description Sets that the notification has been seen by the user (see Notificationhas_been_seen) Mode Ajax Specific filters NotificationsControllerinitialize_notification_with_owner
def seen if @ok @ok = @notification.has_been_seen end @new_notifications = current_user.number_notifications_not_seen end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def saw_notification\n current_user.notice_seen = true\n current_user.save\n end", "def notifications_count\n notifications_count ||= self.notifications_to_show_user.where(:seen_by_user => false).count\n end", "def show\n @notification.seen = true\n @notification.save\n end", "def notifications_to_show_user\n notifications ||= UserEvent.where('user_id = ? AND error_during_render = ? AND event_type != ?', self.id, false, UserEvent.event_type_value(:video_play))\n end", "def check\n\n\t\t@unseenNotifications = {notifications: current_user.notifications.unseen.count}\n\t\trespond_to do |format|\n\n\t\t\tformat.json { render json: @unseenNotifications }\n\n\t\tend\n\n\tend", "def validate_seen\n errors.add(:seen, :must_be_false_if_new_record) if !@notification && self.seen\n end", "def load_notifications\n \t\tif current_user\n \t\t\t@notifications = current_user.notifications.limit 5\n \t\t\t@unseen_notifications_count = current_user.notifications.unseen.count\n \t\tend\n \tend", "def put_seenNotification\n user = User.where(id: params[:idUser]).first\n token = params[:auth_token]\n if(user.auth_token == token)\n req = Notification.where(id: params[:idNotification]).first\n req.update(:seen=>true)\n\n\n render json: { status: 'SUCCESS', message: 'Notificacion actualizada' }, status: :ok\n else\n render json: { status: 'INVALID', message: 'Token invalido'}, status: :unauthorized\n end\n end", "def notification\n notifications = Notification.where(\"user_id = ? AND viewed = ?\", current_user, false)\n flash[:notice] = \"Vous avez vendu #{notifications.size} bon(s)\" if notifications.size > 0\n notifications.each do |notification|\n notification.viewed = \"true\"\n notification.save\n end\n end", "def initialize_notification_with_owner\n @notification_id = correct_integer?(params[:notification_id]) ? params[:notification_id].to_i : 0\n @notification = Notification.find_by_id @notification_id\n update_ok([email protected]? && current_user.id == @notification.user_id)\n end", "def notified_users_with_custom_users\n notified = notified_users_without_custom_users\n\n custom_users_current = custom_users\n custom_users_changed = custom_users_added_or_removed\n\n notified_custom_users = (custom_users_current + custom_users_changed).select do |u|\n u.active? && u.notify_custom_user?(self, custom_users_current, custom_users_changed) && visible?(u)\n end\n notified += notified_custom_users\n notified.uniq\n end", "def set_notifications\n\t\t@notifications = Notification.where(reciever_id: current_user).order(\"created_at DESC\")\n\tend", "def show_notifications # :norobots:\n pass_query_params\n data = []\n @observation = find_or_goto_index(Observation, params[:id].to_s)\n return unless @observation\n name_tracking_emails(@user.id).each do |q|\n fields = [:naming, :notification, :shown]\n naming_id, notification_id, shown = q.get_integers(fields)\n next unless shown.nil?\n notification = Notification.find(notification_id)\n if notification.note_template\n data.push([notification, Naming.find(naming_id)])\n end\n q.add_integer(:shown, 1)\n end\n @data = data.sort_by { rand }\n end", "def get_notifications\n \t\n \t@notifs = []\n\n \tif current_user\n @notifs = Notification.where(:user_id => current_user.id, :seen => false)\n \tend\n end", "def online_notification_seen_state(user_id_check = nil)\n state = Ticket::State.find_by(id: state_id)\n state_type = Ticket::StateType.find_by(id: state.state_type_id)\n\n # always to set unseen for ticket owner and users which did not the update\n if state_type.name != 'merged'\n if user_id_check\n end\n end\n\n # set all to seen if pending action state is a closed or merged state\n if state_type.name == 'pending action' && state.next_state_id\n state = Ticket::State.find_by(id: state.next_state_id)\n state_type = Ticket::StateType.find_by(id: state.state_type_id)\n end\n\n # set all to seen if new state is pending reminder state\n if state_type.name == 'pending reminder'\n if user_id_check\n return false if owner_id == 1\n\n return true\n end\n return true\n end\n\n # set all to seen if new state is a closed or merged state\n return true if state_type.name == 'closed'\n return true if state_type.name == 'merged'\n\n false\n end", "def mark_shown_invite_friends\n current_user.shown_invite_friends!\n render nothing: true\n end", "def notifications\n @other_user = @login_user\n @notifications = DiscussionGroupUser.where(['user_id =? AND is_member=?', @login_user.id, false])\n @disc_notifications = NonSiteUser.where([\"email=? AND invitable_type=? and invitation_type=?\",@login_user.email,\"Discussion\",\"Invited\"])\n respond_to do |format|\n format.html\n end\n end", "def set_notifications\n @notifications = current_user.my_notifications\n end", "def mark_all_user_notifications_notified(user)\n user.notifications.each do |n|\n n.notified = true\n n.save\n end\n end", "def update\r\n\t\tif @notification.update(notification_params)\r\n\t\t\tAction.create(info: current_user.username + ' has seen this notification: (' + @notification.info + ').', user_email: current_user.email)\r\n\t\tend\r\n\tend", "def personal_pnsqs_in_holder\n if ((@user = User.find_by_id(params[:id])) and (its_me?(@user)))\n\n @pnsqs = @user.privates_all\n\n # Notificaciones leidas\n @user.update_attributes(:notifications_count => 0)\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.js { render }\n end\n\n else\n error404\n end\n end", "def noCookieNotifications=(value)\n\t\t\t@noCookieNotifications = value\n\t\tend", "def noCookieNotifications=(value)\n\t\t\t@noCookieNotifications = value\n\t\tend", "def acknowledge\n if current_user\n if current_user.notifications_seen.nil?\n current_user.notifications_seen = [params[:notif_id]]\n else\n current_user.notifications_seen << params[:notif_id]\n end\n current_user.save\n end\n head 200, content_type: \"text/html\"\n end", "def notified_watchers\n notified = (watcher_users.active + watcher_users_through_groups.active).uniq\n notified.reject! {|user| user.mail.blank? || user.mail_notification == 'none'}\n if respond_to?(:visible?)\n notified.reject! {|user| !visible?(user)}\n end\n notified\n end", "def notify_user_actions\n @attributes[:notify_user_actions]\n end", "def display_notif_unseen(usr_id)\n num = PublicActivity::Activity.where(is_seen: false, owner_id: usr_id, owner_type: \"User\").count\n return num if num > 0\n return \"\" # Else return blank string\n end", "def apple_news_blocked=(value)\n @apple_news_blocked = value\n end", "def set_user_notification\n @user_notification = @user.user_notifications.find(params[:id])\n end", "def request_viewed(other_user)\n\t\trequest = received_relationships.find_by(friend_active_id: other_user.id)\n\t\tif request.new_request?\n\t\t\trequest.update_attributes(new_request: false)\n\t\tend\n\tend" ]
[ "0.6892667", "0.66317225", "0.65939784", "0.63638735", "0.61339563", "0.59575915", "0.59058136", "0.58849347", "0.5855978", "0.5805134", "0.5784054", "0.5756029", "0.5728686", "0.5715061", "0.5695581", "0.56925845", "0.5641947", "0.56171817", "0.5608322", "0.5569345", "0.5559753", "0.55138975", "0.55138975", "0.5483", "0.54665107", "0.545881", "0.544883", "0.54412764", "0.540461", "0.53925437" ]
0.70680195
0
Initializes the notifications offset
def initialize_notification_offset @offset_notifications = (correct_integer?(params[:offset]) ? params[:offset].to_i : NOTIFICATIONS_LOADED_TOGETHER) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_notifications\n @notifications = Notification.all\n end", "def init_position\n @init_position\n end", "def set_notifications\n\t\t@notifications = Notification.where(reciever_id: current_user).order(\"created_at DESC\")\n\tend", "def offset!(offset)\n @offset = offset || 0\n self\n end", "def offset(count=nil)\n if count\n @offset = count\n self\n else\n @offset\n end\n end", "def set_default_position\n if self.position.nil?\n self.position = newsletter.blocs.count + 1\n end\n end", "def set_offset(offset)\n @offset = offset\n self\n end", "def initialize(offset, previous_offset, timestamp)\n super(offset, previous_offset)\n @timestamp = timestamp\n @at = nil\n end", "def reload\n @notifications = current_user.notifications_visible_block 0, SETTINGS['notifications_loaded_together']\n @new_notifications = current_user.number_notifications_not_seen\n @offset_notifications = @notifications.length\n @tot_notifications = current_user.tot_notifications_number\n end", "def default_offset_amount\n 50\n end", "def offset; end", "def offset; end", "def offset; end", "def offset()\n @offset__\n end", "def _start_offset= offset\n fail(\"who dares set offset as such? #{offset}\") unless\n offset.kind_of?(Fixnum)\n @start_offset = offset\n end", "def init\n if super\n @offset = 0\n @sg = ITALY\n self\n end\n end", "def init\n\t\tself.extra_person = 0 if self.extra_person.nil?\n\t\tself.from_date = Date.today if self.from_date.nil?\n\t\tself.to_date = Date.today + 1.day if self.to_date.nil?\n\tend", "def offset\n @offset ||= (position.unitless? || position.unit_str == \"px\") ? position.value : 0\n end", "def offset= offset\n @value = nil\n @offset = offset\n end", "def current_offset; end", "def reset\n @offset = 0\n end", "def initialize initial\n @markers = [initial]\n end", "def initialize(api_client, received_options)\n @start_at_offset = 0\n @end_at_offset = nil\n\n unless received_options[OFFSET_KEYS[0]].nil?\n @start_at_offset = received_options[OFFSET_KEYS[0]].to_i\n end\n unless received_options[OFFSET_KEYS[1]].nil?\n @end_at_offset = received_options[OFFSET_KEYS[1]].to_i\n end\n\n @options = received_options.reject { |key| OFFSET_KEYS.include? key.to_sym }\n super(api_client)\n\n # Cache pagesize, MUST NOT change between requests\n @page_size = client.page_size\n end", "def initialize_points\n self.current_points = 0\n self.expiring_points = 0\n end", "def default_values\n self.unread_entries = 0 if self.unread_entries.blank? || self.unread_entries < 0\n end", "def default_values\n self.unread_entries = 0 if self.unread_entries.blank? || self.unread_entries < 0\n end", "def get_offset\n @offset\n end", "def generate_notifications\n\t\t@notifications = Notification.find(:all, :order => \"created_at DESC\")\n\tend", "def set_initial_values\n self.hints_used = 0\n end", "def offset(*) end" ]
[ "0.5799061", "0.57546103", "0.5683678", "0.5666489", "0.5606115", "0.55998945", "0.5530408", "0.55098337", "0.55013764", "0.54930305", "0.54706126", "0.54706126", "0.54706126", "0.5445654", "0.5392907", "0.53885037", "0.53631544", "0.53539306", "0.5348342", "0.5306498", "0.5300385", "0.5298791", "0.52941567", "0.5268243", "0.5255322", "0.5255322", "0.5244668", "0.52389336", "0.5236014", "0.52269804" ]
0.84568256
0
Updates the last visited
def last_visited Deck.find(params[:id]).update_attribute(:last_visited, DateTime.now) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def visited\n self.visited_at = Time.now\n self.save!\n end", "def visited!\n self.count = self.count.to_i + 1\n self.last_used = Time.now\n save!\n end", "def visit\n self.update(last_visit: DateTime.now);\n self.update(visit_count: (self.visit_count + 1));\n end", "def update_visited_moves\n visited_coordinates << [x , y]\n end", "def update_lastlyUsed(chall)\n $game_temp.lbchll_lastly_used = chall.id\n #for ch in @challenges\n # ch.lastly_used = false\n #end\n #chall.lastly_used = true\n end", "def visited\n clone.visit!\n end", "def update_visits_count\n if self.visited && self.visited.visits_count_column? || self.visited.views_count_column?\n \n self.visited.sweep_count_cache\n \n self.visited.class.transaction do \n self.visited.lock!\n \n attributes = {}\n \n # visits count\n if self.visited.visits_count_column? && self.unique?\n attributes[:visits_count] = self.visited[:visits_count] = self.visited.visits_count_cache = self.visited.calculate_visits_count\n end\n\n # views count\n if self.visited.views_count_column?\n attributes[:views_count] = self.visited[:views_count] = self.visited.views_count_cache = self.visited.calculate_views_count\n end\n \n self.visited.update_attributes(attributes) unless attributes.empty?\n end\n end\n end", "def update!(**args)\n @visited_type = args[:visited_type] if args.key?(:visited_type)\n end", "def update_last_user_activity\n now = session[:last_activity] = Time.now\n return if session_is_cloned?\n if ( current_user && (session[:last_activity_saved].nil? || (now - session[:last_activity_saved] > APP_CONFIG[:save_last_activity_granularity_in_seconds].to_i ) ) ) \n logger.info(\"Saved last activity date to #{now} for #{current_user.log_info}\")\n current_user.update_last_activity_date\n session[:last_activity_saved] = now\n end\n end", "def update_activity\n self.last_activity = Time.now\n end", "def store_path_visited(path)\n redis.sadd paths_visited_key, path\n end", "def set_visited_url\n @visited_url = VisitedUrl.find(params[:id])\n end", "def remember_last_visited_record(record)\n session[:last_admin_edited] = record.id if record.respond_to?(:id)\n end", "def add_visit\n self.visits += 1\n self.date_last_visit = DateTime.now\n end", "def visited(page)\n @visited[:forward] = [] unless @visited[:clicked]\n @visited[:back] << page unless @visited[:back].last.eql?(page)\n end", "def seen!\n @last_seen = Time.now\n end", "def last\n @history.last\n end", "def seen\n assign_attributes(last_seen_at: Time.current)\n increment(:seen_count)\n save(validate: false)\n end", "def show\n @bookmark = Bookmark.find(params[:id])\n# Update visited date\n @bookmark.visited_date=Time.now\n @bookmark.update_attributes(params[:bookmark])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @bookmark }\n end\n end", "def doctors_visit(patient_id)\n patient = Patient.find(patient_id)\n patient.update(last_visited_on: DateTime.now)\nend", "def refresh!\n self.update_attributes(:last_logged => Time.now)\n end", "def just_saw\n\t\t\t@last_seen = Time.now\n\t\tend", "def update_steps_history # rubocop:disable Metrics/AbcSize\n if history.nil?\n log_action('Creating first step into the back link history')\n session[:back_link_history] = { '1' => page }\n elsif last_step_page != page\n return clear_unused_steps if back_button && history\n\n log_action('Adding step to the back link history')\n session[:back_link_history][next_step] = page\n end\n end", "def update_visits(short_url)\n\n url = Url.find_by_short_url(short_url)\n url.visit_count = url.visit_count + 1\n url.save\n \n end", "def update\n\t\t\t@last_run = Time.new\n\t\tend", "def seen!()\n self.redirects_count += 1\n self.last_redirect_at = Time.now\n end", "def increment\n self.visits = self.visits.to_i.next\n self.save\n end", "def bump_access\n @access_lock.synchronize do\n @last_acc = Time.new\n end\n end", "def show\n @link = Link.find_by(token: params[:token])\n @link.times_visited = @link.times_visited + 1\n @link.save\n Click.create(link: @link) # for reporting on most popular\n redirect_to @link.original_url\n end", "def access!\n \n if self[:last_access].nil? || last_access < Time.now\n self[:prev_access] = self[:last_access] \n self[:last_access] = Time.now\n save\n end\n end" ]
[ "0.73839927", "0.721183", "0.66453266", "0.6333308", "0.5924842", "0.5876325", "0.58687824", "0.58549196", "0.58478695", "0.5814965", "0.57685786", "0.56967264", "0.56853765", "0.5658096", "0.565176", "0.55385536", "0.5486038", "0.5485777", "0.54771256", "0.54714674", "0.54658395", "0.54175544", "0.5390482", "0.53833205", "0.535917", "0.53524756", "0.53389084", "0.5334937", "0.53228205", "0.53220445" ]
0.7327326
1
Checks if the current user is the creator of the deck
def creator? unless current_user.id == Deck.find(params[:id]).user_id flash[:error] = "You do not have permission to modify this deck" redirect_to root_path end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def owned?(user_to_check = current_user)\n user_to_check ? self.creator == user_to_check : false\n end", "def creator?(object)\n current_user == object.user ? true : false\n \n end", "def created_by?(user)\n unless user.nil?\n userid = user.send(BigbluebuttonRails.configuration.user_attr_id)\n self.creator_id == userid\n else\n false\n end\n end", "def owned?\n user.present?\n end", "def owner? usr\n user_id == usr.id\n end", "def owner? (user)\n user == owner\n end", "def owner?(current_user)\n user == current_user\n end", "def is_owner?(this_user)\n user == this_user\n end", "def creator?\n if session[:user_id] == @event.id\n @creator = true\n else\n @creator = false\n end\n end", "def owned_by?(user_id)\n user_id = user_id.id if user_id.is_a?(User)\n has_role(user_id, :creator)\n end", "def creatable_by?(user)\n true\n end", "def creatable_by?(creator)\n creator.administrator? || !administrator\n end", "def destroyable_by?(user)\n return !!(user.is_admin? or self.creator == nil or self.creator == user or (self.roll and self.roll.creator == user))\n end", "def is_creator?\n\t\tself.is_creator == 1\n\tend", "def owned_by?(current_user)\n current_user && user_id == current_user.id\n end", "def is_owned_by_user?(user)\n self.user == user\n end", "def is_owner?(user)\n !user.nil? && (self.user_id == user.id)\n end", "def is_owner?(user)\n user.id == self.user_id\n end", "def hasOwner? \n\t\tunless self.author_id.nil? || self.author_id == 0\n\t\t\tUser.find(self.author_id)\n\t\tend\n\n\tend", "def owned_by?(u)\n self.user == u\n end", "def owned_by? a_user\n a_user == user\n end", "def owner?(user)\n\t\tuser.id == self.user.id\n\tend", "def created_by?(check_user)\n return false unless check_user.present?\n return true if check_user.cornerstone_admin?\n self.user && self.user == check_user\n end", "def is_owner\n object == current_user\n end", "def creatable_by?(actor)\n actor.is_a?(User)\n end", "def owner?\n resource.user_id == current_user.id\n end", "def isCommentCreator(current_user, comment_id)\n Comment.where(:user_id => current_user, :id => comment_id).exists? \n end", "def isCommentCreator(current_user, comment_id)\n Comment.where(:user_id => current_user, :id => comment_id).exists? \n end", "def owner?(user)\n user == owner || owners.include?(user)\n end", "def owner?(id)\n if current_user.id == id\n return true\n else\n return false\n end\n end" ]
[ "0.77848387", "0.77739817", "0.7398696", "0.73590356", "0.7240787", "0.7201834", "0.7200356", "0.71779436", "0.7176693", "0.7141878", "0.7140763", "0.7075012", "0.70477724", "0.70252395", "0.7017225", "0.69944763", "0.6974815", "0.6963963", "0.6956399", "0.6948928", "0.6917776", "0.6910884", "0.6910806", "0.6884121", "0.68412817", "0.6833268", "0.6829136", "0.6829136", "0.6825573", "0.67682415" ]
0.82552415
0
Rails 5.2 moved from a unary Migrator class to MigrationContext, that can be scoped to a given path. Rails 6.0 requires the schema migration object as an argument.
def migration_context klass = ActiveRecord::MigrationContext case klass.instance_method(:initialize).arity when 1 klass.new(migration_path) else klass.new(migration_path, schema_migration) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def migration(&block)\n if caller[0].rindex(/\\/(?:[0-9]+)_([_a-z0-9]*).rb:\\d+(?::in `.*')?$/)\n m = Object.const_set $1.camelize, Class.new(ActiveRecord::Migration)\n m.class_eval(&block) # 3.1\n else\n raise ArgumentError, \"Could not create migration at: #{caller[0]}\"\n end\n end", "def migrate(schema, to_version = nil)\n conn = ActiveRecord::Base.connection\n return false unless conn.schema_exists? schema\n current_search_path = conn.schema_search_path\n conn.schema_search_path = schema\n ActiveRecord::Migrator.migrate('db/migrate', to_version)\n conn.schema_search_path = current_search_path\n end", "def migrate(path, version = nil)\n # Establish a connection for migration.\n ActiveRecord::Base.establish_connection(@connection_config)\n ActiveRecord::Migration.verbose = false\n # Namespace definition for the current database.\n # This will ensure that each database is migrated independently.\n ActiveRecord::Base.table_name_prefix = base_model.table_name_prefix\n ActiveRecord::Migrator.migrate(path, version)\n # Clean-up once done.\n ActiveRecord.send(:remove_const, :SchemaMigration)\n load 'active_record/schema_migration.rb'\n ActiveRecord::Base.table_name_prefix = ''\n ActiveRecord::Base.connection.close\n end", "def migration\n end", "def schema?(model_class)\n model_class.name == 'ActiveRecord::SchemaMigration'\n end", "def migrate_plugin(migration_path)\n # Execute Migrations on engine load.\n ActiveRecord::Migrator.migrations_paths += [migration_path]\n begin\n ActiveRecord::Tasks::DatabaseTasks.migrate\n rescue ActiveRecord::NoDatabaseError\n end\n end", "def migration_folder name\n migrations_path = File.dirname(__FILE__)\n name ? File.join(\"#{migrations_path}\" \"#{name}\") : \"#{migrations_path}/migrations\" # adding /migrations here is safer\nend", "def with_migration(&block)\n migration_class = ActiveRecord::Migration[\n ActiveRecord::Migration.current_version\n ]\n\n Class.new(migration_class, &block).new\nend", "def set_migration\n @migration = Migration.find(params[:id])\n end", "def schema_version\n migration_context.current_version\n end", "def migrate\n raise NotImplementedError\n end", "def migrate\n migrations_path = File.join(File.dirname(__FILE__), \"#{backend_name}/migrations\")\n Sequel.extension :migration\n unless Sequel::Migrator.is_current?(@db, migrations_path)\n store = self; log = @log; @db.instance_eval { @log = log; @store = store }\n Sequel::Migrator.run(@db, migrations_path)\n unless (v = @db[:schema_info].first) && v[:magic] && v[:backend]\n @db[:schema_info].update(\n magic: Bitcoin.network[:magic_head].hth, backend: backend_name)\n end\n end\n end", "def migrate\n migrations_path = File.join(File.dirname(__FILE__), \"#{backend_name}/migrations\")\n Sequel.extension :migration\n unless Sequel::Migrator.is_current?(@db, migrations_path)\n store = self; log = @log; @db.instance_eval { @log = log; @store = store }\n Sequel::Migrator.run(@db, migrations_path)\n unless (v = @db[:schema_info].first) && v[:magic] && v[:backend]\n @db[:schema_info].update(\n magic: Bitcoin.network[:magic_head].hth, backend: backend_name)\n end\n end\n end", "def alter_table_generator_class\n Schema::AlterTableGenerator\n end", "def activate(schema,verify_migration = false)\n base_path = self.initial_search_path\n self.create(schema) if verify_migration\n conn = ActiveRecord::Base.connection\n return false unless conn.schema_exists?(schema)\n conn.schema_search_path = [schema, base_path].compact.join(',')\n end", "def to_class\n @migration_class ||= migration_class_name.constantize\n rescue NameError => e\n @name_error = true\n\n raise e unless e.missing_name.eql?(migration_class_name)\n\n puts \"WARNING: Migration-Class not found '#{migration_class_name}'\"\n end", "def pre_migrate_database\n old_schema_version = get_schema_version\n new_schema_version = File.read(File.join(source_directory,'db','schema_version')).to_i\n \n return unless old_schema_version > 0\n \n # Are we downgrading?\n if old_schema_version > new_schema_version\n message \"Downgrading schema from #{old_schema_version} to #{new_schema_version}\"\n \n in_directory install_directory do\n unless system(\"rake -s migrate VERSION=#{new_schema_version}\")\n raise InstallFailed, \"Downgrade migrating from #{old_schema_version} to #{new_schema_version} failed.\"\n end\n end\n end\n end", "def migration_class_name\n migration_name.camelize\n end", "def migrate!\n Migrator.migrate(name)\n end", "def migrate!\n Migrator.migrate(name)\n end", "def in_migration?(node)\n dirname(node).end_with?('db/migrate', 'db/geo/migrate') || in_post_deployment_migration?(node)\n end", "def migration?(migration)\n @migrations.include?(migration)\n end", "def prefix_for_tables\n migration_version = ActiveRecord::Migrator.current_version\n end", "def migration_dir\n return Roomer.shared_migrations_directory if shared?\n return Roomer.tenanted_migrations_directory\n end", "def migrate!\n connect! unless connected?\n Sequel.extension :migration\n Sequel::Migrator.run(db, File.join(__dir__, \"../../db/migrations\"), table: schema_table)\n end", "def migrations\n raise(ArgumentError, \"Can't set migrations while using :version option\") if @using_deprecated_version_setting\n yield\n end", "def create_migration\n if invoked_attributes.present?\n args = [\"create_#{plural_name}\"] + (invokable(invoked_attributes) | timestamps)\n args += [\"--database\", options['database']] if options['database']\n Rails::Generators.invoke('migration', args)\n return\n end\n\n return if with_resource_tenant do\n table_name = resource.klass.table_name\n\n if ActiveRecord::Base.connection.table_exists?(table_name)\n say_status(:error, \"#{table_name} table already exist. We can't migrate (yet). Exiting.\", :red)\n true\n end\n end\n\n if resource.model_attributes.blank?\n say_status(:error, \"No model attributes present. Please add the effective_resource do ... end block and try again\", :red)\n return\n end\n\n args = [\"create_#{plural_name}\"] + invokable(resource.model_attributes) - timestamps\n args += [\"--database\", options['database']] if options['database']\n\n if options['database'].blank? && defined?(Tenant)\n args += [\"--database\", resource.klass.name.split('::').first.downcase]\n end\n\n Rails::Generators.invoke('migration', args)\n end", "def check_schema_migrations\n return if column_family_exists?('schema_migrations')\n say 'Creating schema_migrations column family'\n DatastaxRails::Cql::CreateColumnFamily.new('schema_migrations').primary_key('cf')\n .columns(cf: :text, digest: :text, solrconfig: :text, stopwords: :text).execute\n end", "def run(&block)\n original_path = @connection.schema_search_path\n set_path_if_required(@schema)\n yield\n ensure\n set_path_if_required(original_path)\n end", "def upgrade(migrations, context, meta_node)\n migrations.each do |m|\n Neo4j.logger.info \"Running upgrade: #{m}\"\n m.execute_up(context, meta_node)\n end\n end" ]
[ "0.60223454", "0.5730504", "0.5651764", "0.55012083", "0.54448247", "0.5438543", "0.53481907", "0.52664554", "0.52230257", "0.5205954", "0.5120648", "0.50873554", "0.50873554", "0.5083134", "0.50599277", "0.5045491", "0.50440073", "0.5040061", "0.5036226", "0.50357646", "0.49932998", "0.49757648", "0.49683827", "0.4884429", "0.48791656", "0.48749372", "0.48520845", "0.48287317", "0.48177072", "0.48085237" ]
0.6889356
0
Write a value array to multiple pwm ports (or a single port if the param is a hash)
def write(values) if values.is_a? Hash # TODO: hacky - refactor fail "wrong hash format, expected the keys 'port' and 'value'" unless values.key?(:port) && values.key?(:value) write_to_port(values[:port], values[:value]) elsif values.is_a? Array log.error('more values than configured lamps') && return if values.size > @ports.size values.map! { |x| x.to_i > 255 ? 255 : x.to_i } client.pwm_write_registers(start_index: @ports.sort.first, values: values) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write_to_port(port, value)\n value = value.to_i\n @values[port.to_i] = value\n # log.debug \"write bar #{port} value #{value}\"\n client.pwm_write(@ports[port.to_i], value)\n end", "def pwm(value)\n GPIO.write \"gpio#{@number}/value\", value\n end", "def ports *ports\n @ports = *ports unless ports.length == 0\n @ports\n end", "def write_multi(pairs)\n pairs.each do |name,value|\n write(name, value)\n end\n end", "def write(*args)\n args.each do |a|\n @serial.write a.chr\n end\n end", "def write_parameter_to_device(id, value)\n @ramps_arduino.execute_command(\"F22 P#{id} V#{value}\", false, false)\n end", "def runner_output(*keys)\n # Registers each signal as run port\n keys.each do |key|\n # Ensure the key is a symbol.\n key = key.to_sym\n # Register it with the corresponding signal.\n name = HDLRuby.uniq_name # The name of the signal is uniq.\n @runner_outputs[name] = send(key)\n end\n end", "def ports\n # prevent original array from being changed\n @ports.dup\n end", "def output_port_list\n output_ports.values\n end", "def write_array(array)\n\t\twrite_byte(10)\n\t\twrite_word32_network(array.length)\n\t\tarray.each do |el| \n\t\t\twrite(el)\n\t\tend\n\tend", "def write(value, options = {})\n # If an array is written it means a data value and an overlay have been supplied\n # in one go...\n if value.is_a?(Array) && !value.is_a?(BitCollection)\n overlay(value[1])\n value = value[0]\n end\n value = value.data if value.respond_to?('data')\n\n with_lsb0 do\n size.times do |i|\n self[i].write(value[i], options)\n end\n end\n self\n end", "def add_output_ports(*names)\n create_port(:output, *names)\n end", "def write(*commands)\n serial_port.write_nonblock(commands.map(&:chr).join)\n end", "def each_output_port\n return output_ports.enum_for(:each_value) unless block_given?\n output_ports.each_value { |port| yield(port) }\n end", "def setup\n RPi::GPIO.set_numbering(:board)\n\n if @motor_controller.motors.count == 2\n RPi::GPIO.setup(@pins[:enable_a], as: :output)\n @port_a_pwm = RPi::GPIO::PWM.new(@pins[:enable_a], @pwm_freq)\n @port_a_pwm.start(0)\n RPi::GPIO.setup(@pins[:in1], as: :output)\n RPi::GPIO.setup(@pins[:in2], as: :output)\n RPi::GPIO.setup(@pins[:enable_b], as: :output)\n @port_b_pwm = RPi::GPIO::PWM.new(@pins[:enable_b], @pwm_freq)\n @port_b_pwm.start(0)\n RPi::GPIO.setup(@pins[:in3], as: :output)\n RPi::GPIO.setup(@pins[:in4], as: :output)\n else\n if @pins[:enable_a]\n RPi::GPIO.setup(@pins[:enable_a], as: :output)\n @port_a_pwm = RPi::GPIO::PWM.new(@pins[:enable_a], @pwm_freq)\n @port_a_pwm.start(0)\n RPi::GPIO.setup(@pins[:in1], as: :output)\n RPi::GPIO.setup(@pins[:in2], as: :output)\n elsif @pins[:enable_b]\n RPi::GPIO.setup(@pins[:enable_b], as: :output)\n @port_b_pwm = RPi::GPIO::PWM.new(@pins[:enable_b], @pwm_freq)\n @port_b_pwm.start(0)\n RPi::GPIO.setup(@pins[:in3], as: :output)\n RPi::GPIO.setup(@pins[:in4], as: :output)\n else\n raise \"'#{@motor_controller.name}' has no PWM pin set for #{@motor_controller.type.to_s.upcase}\"\n end\n end\n end", "def forwardSensorValues\n logger.debug \"This is my params: \"+params[\"data\"][\"temperature\"].to_s\n logger.debug \"This is my params: \"+params[\"data\"][\"temperature\"].to_s\n rp = params[\"data\"][\"temperature\"].to_i + 1\n respond_to do |format|\n format.json {render :json => { :value => rp }.to_json}\n end\n if !@@sockets[params[\"serialPort\"]]\n create_socket(params[\"serialPort\"])\n end\n @@sockets[params[\"serialPort\"]].write(params[\"data\"].to_json)\n end", "def write(method, data)\n self.send(method.to_sym, convert_to_hash_array(data))\n end", "def output_pins(nums)\n ar = Array(nums)\n ar.each {|n| output_pin(n)} \n end", "def pwm(v)\n regdata = @@i2c.read(0x08, 1)\n @@i2c.write([0x08, regdata[0] | (1 << @id)])\n @@i2c.write([@ion, v])\n @@i2c.write([0x08, regdata[0]])\n end", "def update(value)\n @serial_port.puts value\n end", "def emit_values(values)\n values.each do |value|\n emit_self(value)\n end\n end", "def input_port_list\n input_ports.values\n end", "def []= name, value\n pin = GenericPinMap[name.to_sym]\n raise \"Unknown Pin '#{name}'\" unless pin\n self.send \"#{pin[0]}_write\", pin[1], value\n end", "def write(*args)\n case args.count\n when 0\n raise ArgumentError, \"missing arguments\"\n when 1\n data = args.first\n else\n data = args\n end\n\n enable do\n case data\n when Numeric\n Rpio.driver.spi_transfer(data)\n when Enumerable\n Rpio.driver.spi_transfer_bytes(data)\n else\n raise ArgumentError, \"#{data.class} is not valid data. Use Numeric or an Enumerable of numbers\"\n end\n end\n end", "def set_pins(motor, mode = :stop)\n pwm, forward, backward = nil, nil, nil\n if motor.port == :a\n pwm = @port_a_pwm\n forward = @pins[:in1]\n backward = @pins[:in2]\n elsif motor.port == :b\n pwm = @port_b_pwm\n forward = @pins[:in3]\n backward = @pins[:in4]\n end\n\n case mode\n when :stop\n pwm.duty_cycle = 0\n RPi::GPIO.set_low(forward)\n RPi::GPIO.set_low(backward)\n when :forward\n pwm.duty_cycle = motor.pwm_speed\n RPi::GPIO.set_high(forward)\n RPi::GPIO.set_low(backward)\n when :backward\n pwm.duty_cycle = motor.pwm_speed\n RPi::GPIO.set_low(forward)\n RPi::GPIO.set_high(backward)\n end\n # log(\"Motor #{motor.port}: POWER: #{motor.power}, PWM: #{pwm.duty_cycle}, forward: #{RPi::GPIO.high?(forward)}, backward: #{RPi::GPIO.high?(backward)}\")\n end", "def write_parameter_to_device(id, value)\n execute_command(\"F22 P#{id} V#{value}\", false, false)\n end", "def emit(token_name, data, target_array, ts, te)\n target_array << {:name => token_name.to_sym, :value => data[ts...te].pack(\"c*\") }\nend", "def write(io)\n @values.each {|el|\n el.write io\n }\n end", "def outputs\n ports_with_capabilities(:output)\n end", "def write(file)\n value.each do |item|\n # always write int4 in network order (as per GDSII spec)\n file.write [item].pack('N')\n end\n end" ]
[ "0.7004192", "0.5874171", "0.5744025", "0.5642534", "0.5557398", "0.5477633", "0.5468817", "0.54197204", "0.5395847", "0.53791815", "0.53435653", "0.5329575", "0.53013176", "0.5265486", "0.52597994", "0.5255402", "0.51564205", "0.51431113", "0.5107263", "0.5103409", "0.5084731", "0.5072124", "0.50604075", "0.5056559", "0.5051372", "0.5049195", "0.5025058", "0.50172955", "0.49476478", "0.49341267" ]
0.7972539
0
Write a value to a pwm port
def write_to_port(port, value) value = value.to_i @values[port.to_i] = value # log.debug "write bar #{port} value #{value}" client.pwm_write(@ports[port.to_i], value) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pwm(value)\n GPIO.write \"gpio#{@number}/value\", value\n end", "def pwm(v)\n regdata = @@i2c.read(0x08, 1)\n @@i2c.write([0x08, regdata[0] | (1 << @id)])\n @@i2c.write([@ion, v])\n @@i2c.write([0x08, regdata[0]])\n end", "def update(value)\n @serial_port.puts value\n end", "def write(new_value)\n raise \"#{to_s} cannot be used through Firmata\" if mode == Rufirmata::UNAVAILABLE\n raise \"#{to_s} is set up as an INPUT and therefore cannot be written to\" if mode == Rufirmata::INPUT\n if (new_value != value)\n self.value = new_value\n if mode == Rufirmata::OUTPUT\n port ? port.write() :\n board.write_command(Rufirmata::DIGITAL_MESSAGE, pin_number, value)\n elsif mode == Rufirmata::PWM\n val = (@value * 255).to_i\n board.write_command(Rufirmata::ANALOG_MESSAGE + pin_number, val % 128, val >> 7)\n end\n end\n end", "def write_parameter_to_device(id, value)\n @ramps_arduino.execute_command(\"F22 P#{id} V#{value}\", false, false)\n end", "def write(values)\n if values.is_a? Hash # TODO: hacky - refactor\n fail \"wrong hash format, expected the keys 'port' and 'value'\" unless values.key?(:port) && values.key?(:value)\n write_to_port(values[:port], values[:value])\n elsif values.is_a? Array\n log.error('more values than configured lamps') && return if values.size > @ports.size\n values.map! { |x| x.to_i > 255 ? 255 : x.to_i }\n client.pwm_write_registers(start_index: @ports.sort.first, values: values)\n end\n end", "def write pin, value\n if value == 0\n set_int_at(GPCLR0 + PI_BANK(pin), PI_BIT(pin))\n else\n set_int_at(GPSET0 + PI_BANK(pin), PI_BIT(pin))\n end\n end", "def on\n pwm(0xff)\n end", "def pwm_set(frequency,on_ratio)\n r=on_ratio.to_i \n \n puts \"pwm #{@gpio} => set to f=#{frequency} pulse=#{r}%\" if @verbose\n async_spawn( \"fast-gpio\",\"pwm\",@gpio.to_s,frequency.to_s,(r < 0 ? 0 : (r > 100 ? 100 : r)).to_s) \n end", "def on\n GPIO.write \"gpio#{@number}/value\", \"1\"\n end", "def digital_write(value)\n set_mode('w') unless @mode == 'w'\n\n if value.is_a? Symbol\n value = (value == :high) ? 1 : 0\n end\n\n value = value.to_i\n\n raise StandardError unless ([HIGH, LOW].include? value)\n\n @status = (value == 1) ? 'high' : 'low'\n\n @pin_file.write(value)\n @pin_file.flush\n end", "def set(value)\n if (value == 0) || (value == 1)\n IO.write(VALUE % @pin, \"%d\" % value)\n else\n raise \"invalid value #{value.inspect}\"\n end\n end", "def analog_write(pin, value)\n @pins[pin].value = value\n write(ANALOG_MESSAGE | pin, value & 0x7F, (value >> 7) & 0x7F)\n end", "def write_parameter_to_device(id, value)\n execute_command(\"F22 P#{id} V#{value}\", false, false)\n end", "def set_pin(val)\n\n @pwm.duty_cycle = val ? @duty_cycle : 0 \n super(val)\n \n end", "def write(pin, value)\n value ? set(pin) : clear(pin)\n end", "def digital_write(pin, value)\n port = (pin / 8).floor\n port_value = 0\n\n @pins[pin].value = value\n\n 8.times do |i|\n port_value |= (1 << i) unless @pins[8 * port + i].value.zero?\n end\n\n write(DIGITAL_MESSAGE | port, port_value & 0x7F, (port_value >> 7) & 0x7F)\n end", "def send_dmx(channel, value)\n\n # Write the channel and value in the format for Arduino\n write(\"#{channel}c\")\n write(\"#{value}w\")\n end", "def pin_write(command_line)\n HardwareInterface.current.pin_std_set_value(command_line.pin_nr, command_line.pin_value_1, command_line.pin_mode)\n end", "def write(value)\n # pass\n end", "def signal(port, val)\n # The derived class needs to implement the value method.\n self.activate\n @inputs[port] = val\n newval = self.value\n if newval != @outval then\n @outval = newval\n @outputs.each { | c | c.signal(newval) }\n end\n self.deactivate\n end", "def send_param(value)\n begin\n self.device.set_to(value)\n rescue Encoding::CompatibilityError => e\n puts \"Error: #{e}\"\n end\n # Update widget status\n @widget = self.class.find_by_id(self.id)\n @widget.status = value.to_i\n # Send the update to all running sessions\n unless ActionCable.server.logger.nil?\n ActionCable.server.broadcast 'widgets', {type: \"slider\", id: self.id, status: @widget.status}\n end\n end", "def speed_set _value\n send_cmd(\"speed_set #{_value}\")\n end", "def servo_std_move(pin, value)\n @ramps_arduino.execute_command(\"F61 P#{pin} V#{value}\", false, @status_debug_msg)\n end", "def pin_std_set_value(pin, value, mode)\n @ramps_arduino.execute_command(\"F41 P#{pin} V#{value} M#{mode}\", false, @status_debug_msg)\n end", "def switch_on port=-1\n run(:func => \"relayWrite\", :port => port, :value => 1)\n end", "def servo_std_move(pin, value)\n execute_command(\"F61 P#{pin} V#{value}\", false, @status_debug_msg)\n end", "def servo_std_move(pin, value)\n start_command(\"F61 P#{pin} V#{value}\", false, @status_debug_msg)\n end", "def []= name, value\n pin = GenericPinMap[name.to_sym]\n raise \"Unknown Pin '#{name}'\" unless pin\n self.send \"#{pin[0]}_write\", pin[1], value\n end", "def set_power(port, state)\n\t\tstate = state ? 1 : 0\n\t\t\n\t\tdo_send(\"\\eP#{port}*#{state}DCPP\")\n\t\t# Response: DcppP_port*portstatus 0 == off, 1== on\n\tend" ]
[ "0.87874556", "0.76924926", "0.70983934", "0.7093962", "0.69010884", "0.67103577", "0.6678591", "0.6648178", "0.6571475", "0.6500164", "0.6472061", "0.64682066", "0.64077723", "0.6370701", "0.62217563", "0.61374813", "0.6110579", "0.6110504", "0.60622525", "0.60194933", "0.5957346", "0.5947679", "0.5920723", "0.5880493", "0.5819987", "0.5754146", "0.5738371", "0.57067543", "0.5706593", "0.56843084" ]
0.8472275
1
GET /days/new GET /days/new.xml
def new @trip = Trip.find(params[:trip_id]) @prev_day = @trip.days[-1] @day = Day.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @day } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @the_day = TheDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @the_day }\n end\n end", "def new\n @user_day = UserDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_day }\n end\n end", "def new\n @work_day = WorkDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @work_day }\n end\n end", "def new\n @bday = Bday.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @bday }\n end\n end", "def new\n @commission_day = CommissionDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @commission_day }\n end\n end", "def new\n @availability_day = AvailabilityDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @availability_day }\n end\n end", "def new\n @daily_grr = DailyGrr.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @daily_grr }\n end\n end", "def new\n \t@conference = Conference.find(params[:conference_id])\n @day = Day.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @day }\n end\n end", "def new\n @vehicle_daily = VehicleDaily.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vehicle_daily }\n end\n end", "def new\n @today_activity = TodayActivity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @today_activity }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def new\n respond_to do |format|\n format.xml { render :xml => @schedule }\n end\n end", "def new\n @potd = Potd.new\n @action = \"Create\"\n @active_school_day = SchoolDay.find(params[:day]) unless params[:day].nil? || params[:day].empty?\n load_prev_and_next_day\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @potd }\n end\n end", "def new\n @calendar = Calendar.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @calendar }\n end\n end", "def new\n @calendar = Calendar.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @calendar }\n end\n end", "def new\n @calendar = Calendar.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @calendar }\n end\n end", "def new\n @calendar = Calendar.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @calendar }\n end\n end", "def new\n @calendar = Calendar.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @calendar }\n end\n end", "def new\n @countdown = Countdown.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @countdown }\n end\n end", "def set_new_day\n @new_day = NewDay.find(params[:id])\n end", "def new\n @day_list = DayList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @day_list }\n end\n end", "def new\n @dailyreport = Dailyreport.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @dailyreport }\n end\n end", "def new\n #@day = current_user.days.build\n @day = Day.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @day }\n end\n end", "def new\n @calendario = Calendario.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @calendario }\n end\n end", "def new\n @dining = Dining.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @dining }\n end\n end", "def new\n @ep = Ep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ep }\n end\n end", "def new\n @day_week = DayWeek.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @day_week }\n end\n end", "def new\n @viewdate = Viewdate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @viewdate }\n end\n end", "def new\n @todo = Todo.new\n @active_school_day = SchoolDay.find(params[:day]) unless params[:day].nil? || params[:day].empty?\n load_prev_and_next_day\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end", "def new\n @weekday = Weekday.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weekday }\n end\n end" ]
[ "0.7310398", "0.69277835", "0.6785754", "0.67822", "0.6775603", "0.6694091", "0.65848374", "0.65452087", "0.64741373", "0.64677095", "0.6448222", "0.64481646", "0.64406395", "0.63979113", "0.63979113", "0.63979113", "0.63979113", "0.63979113", "0.6370935", "0.63697785", "0.6355807", "0.63483286", "0.63240254", "0.6304117", "0.62972516", "0.62935627", "0.6289732", "0.62841815", "0.62744015", "0.6273603" ]
0.70595556
1
Query the API server for the root device
def root_device begin @root_device = open('http://instance-data/latest/meta-data/block-device-mapping/root').read rescue message.fatal 'Could not get the root device!' end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def root_device_name\n data[:root_device_name]\n end", "def root_device_type\n data[:root_device_type]\n end", "def query_device_management\n @devices = query(\"select * from device_management \")\n end", "def get_root\n http = Net::HTTP.start(@server_ip, @server_port)\n request = Net::HTTP::Get.new(\"/\")\n request.basic_auth @username, @password\n http.request(request)\n end", "def debug_if_root_device(bdms)\n return if bdms.nil? || bdms.empty?\n image_id = config[:image_id]\n image = ec2.resource.image(image_id)\n begin\n root_device_name = image.root_device_name\n rescue ::Aws::EC2::Errors::InvalidAMIIDNotFound\n # Not raising here because AWS will give a more meaningful message\n # when we try to create the instance\n return\n end\n bdms.find { |bdm|\n if bdm[:device_name] == root_device_name\n logger.info(\"Overriding root device [#{root_device_name}] from image [#{image_id}]\")\n end\n }\n end", "def device\n xpath '.', 'device'\n end", "def get_all_device_info\n # @device = Device.where(\"user_id = ?\",current_user[:id])\n # render json: @device\n @devices = User.get_all_user_devices(current_user[:id])\n render json: @devices\n end", "def device\n @client.get('VBD', :device, @uuid)\n end", "def show\n json_response(@device)\n end", "def server_devices_list\n if !ccl_active? or (session[:usertype] != \"admin\" and ccl_active?)\n dont_be_so_smart\n redirect_to :controller => \"callc\", :action => \"main\" and return false\n end\n @page_title = _('Server_devices')\n @page_icon = 'server.png'\n @help_link = \"http://wiki.kolmisoft.com/index.php/Multi_Server_support\"\n # ip_auth + server_devices.server_id is null + server_devices.server_id is not that server + not server device(which were created with server creation)\n @devices = Device.select(\"devices.*,server_devices.server_id AS serv_id\").joins(\"LEFT JOIN server_devices ON (server_devices.device_id = devices.id AND server_devices.server_id = #{params[:id].to_i}) LEFT JOIN users ON (users.id = devices.user_id)\").where(\"(host != 'dynamic' OR device_type != 'SIP') AND users.owner_id = #{current_user.id} AND server_devices.server_id is null AND user_id != -1 AND name not like 'mor_server_%'\").order(\"extension ASC\").all\n end", "def devices; end", "def get_synthetics_devices\n request(Net::HTTP::Get, \"/api/#{API_VERSION}/synthetics/browser/devices\", nil, nil, false)\n end", "def devices\n\texecute(\"devices\").split(\"\\n\")[1..-1]\nend", "def query_moon_api\n result = connection.query\n end", "def devices(params={})\n res = @client.get(\"#{path}/devices\", params)\n\n res.json[\"devices\"].map{ |atts| ::M2X::Client::Device.new(@client, atts) } if res.success?\n end", "def find\n raise Zype::Client::NoAppKey if Zype.configuration.app_key.to_s.empty?\n\n client.execute(method: :get, path: '/app')\n end", "def get_root(options = {})\n object_from_response(GogoKit::Root,\n GogoKit::RootRepresenter,\n :get,\n api_root_endpoint,\n options)\n end", "def index\n @api_v1_user_device_infos = Api::V1::UserDeviceInfo.all\n end", "def check_devices\n\n\n end", "def get_root_modules(org_unit_id) # GET\n query_string = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/root/\"\n _get(query_string)\nend", "def get_device_data(param = false)\n\n # get the user-agent\n if param == false\n user_agent = ''\n if [email protected]?\n user_agent = @headers['HTTP_USER_AGENT']\n end\n elsif param == true\n\t\t\tuser_agent = @settings.test_useragent\n else\n if @request.nil?\n @request = {}\n end\n @headers = get_normalised_headers param # normalize the given header hash\n user_agent = (@headers.has_key?'user-agent')?@headers['user-agent']:''\n\t\tend\n\n # get the DeviceAtlas Client Side Component cookie if usage=on and exists\n cookie = nil\n\t\tif @settings.use_client_cookie && [email protected]? &&\n !@cookies[@settings.client_cookie_name].nil?\n\t\t\tcookie = @cookies[@settings.client_cookie_name]\n elsif @settings.use_client_cookie && \n [email protected]? &&\n @headers.has_key?('cookie')\n @headers['cookie'].gsub!(\" \", \"\")\n cookie_items = @headers['cookie'].split ';'\n cookie_items.each do |cookie_item|\n cookie_name_value = cookie_item.split '='\n if @settings.client_cookie_name == cookie_name_value[0]\n cookie = cookie_name_value[1].gsub(\" \", \"\")\n end\n end\n\t\tend\n\n # get device data from cache or cloud\n @last_used_cloud_url = nil\n @self_auto_ranking = 'n' # 'y' = the API called the ranking\n @ranking_status = nil # for debugging\n @called_servers = [] # for debugging\n\n\t\tbegin\n\t\t\t# check cache for cached data\n\t\t\tif @settings.use_cache\n source = SOURCE_CACHE\n results = get_cache user_agent, cookie\n\t\t\tend\n\t\t\t# use cloud service to get data\n\t\t\tif results.nil?\n source = SOURCE_CLOUD\n\t\t\t\tresults = get_cloud_service user_agent, cookie\n # set the caches for future queries\n if @settings.use_cache && source === SOURCE_CLOUD\n set_cache user_agent, cookie, results[KEY_PROPERTIES]\n end\n\t\t\tend\t\n\t\t# handle errors\n\t\trescue Exception => e\n if results.nil?\n results = {}\n end\n results[KEY_ERROR] = e.message\n if @settings.debug_mode\n raise Exception, e.message\n end\n\t\tend\n\n # In Ruby, we return properties as symbols\n if results.has_key?KEY_PROPERTIES\n results[KEY_PROPERTIES] = results[KEY_PROPERTIES].inject({}){\n |memo,(k,v)| memo[k.to_sym] = v; memo\n }\n end\n\n results[KEY_SOURCE] = source\n results[KEY_USERAGENT] = user_agent\n return results\n\n end", "def show\n @device = Device.find(params[:id], :include => [:button, :picture])\n unless @device.application\n get_device_data(@device)\n end\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @device }\n end\n end", "def list\n all.each { |device| puts(device.pretty_name) }\n end", "def is_root_device?(volume_id)\n vols = @ec2_api.describe_volumes(:volume_id => volume_id)\n if vols['volumeSet']['item'][0]['attachmentSet'] == nil || vols['volumeSet']['item'][0]['attachmentSet']['item'].size == 0\n #not linked to any instance, cannot be a root-device\n return false\n end\n instance_id = vols['volumeSet']['item'][0]['attachmentSet']['item'][0]['instanceId']\n res = @ec2_api.describe_instance_attribute(:instance_id => instance_id, :attributes => {:rootDeviceName => true})\n if res[\"rootDeviceName\"] == nil\n return false\n end\n rdn = res['rootDeviceName']['value']\n res = @ec2_api.describe_instances(:instance_id => instance_id)\n if res['reservationSet']['item'][0]['instancesSet']['item'][0]['blockDeviceMapping']['item'].size == 0\n # volume unattached in the meantime\n return false\n end\n attached = res['reservationSet']['item'][0]['instancesSet']['item'][0]['blockDeviceMapping']['item']\n attached.each() {|ebs|\n volume = ebs['ebs']['volumeId']\n device_name = ebs['deviceName']\n if volume == volume_id && rdn == device_name\n return true\n end\n }\n return false\n end", "def get_api_node(path_array)\n return JSON.parse(lxc(['query', '--wait', '-X', 'GET', return_api_path(path_array)]))\n end", "def command_get_device(command)\n\t\tif @device then message(\"device: #{@device.name}\")\n\t\telse error(\"no device loaded\")\n\t\tend\n\tend", "def index\n @devices = current_user.devices\n end", "def root\n JenkinsApi::Client::Root.new(self)\n end", "def ring_server\n return @ring_server ||= @ring_finger.lookup_ring_any\n end", "def root; get(\"\"); end" ]
[ "0.6693326", "0.6457548", "0.61086637", "0.59151244", "0.5870444", "0.5663838", "0.5659754", "0.56459373", "0.56307954", "0.5594551", "0.55858386", "0.5581615", "0.55655944", "0.55509573", "0.55283517", "0.5521352", "0.5515588", "0.5510941", "0.5438437", "0.5416547", "0.54066736", "0.5400792", "0.53947663", "0.5383187", "0.5374459", "0.53470546", "0.5319292", "0.53149086", "0.53034407", "0.5302441" ]
0.7180721
0
Autodetect Devise scope using +Devise.default_scope+. Used to make the linkhelpers smart if like in most cases only one devise scope will be used, e.g. "user" or "account".
def auto_detect_scope(*args) options = args.extract_options! if options.key?(:for) options[:scope] = options[:for] ::ActiveSupport::Deprecation.warn("DEPRECATION: " << "Devise scope :for option is deprecated. " << "Use: facebook_*_link(:some_scope), or facebook_*_link(:scope => :some_scope)") end scope = args.detect { |arg| arg.is_a?(Symbol) } || options[:scope] || ::Devise.default_scope mapping = ::Devise.mappings[scope] if mapping.for.include?(:facebook) scope else error_message = "%s" << " Did you forget to devise facebook_connect in your model? Like this: devise :facebook_connectable." << " You can also specify scope explicitly, e.g.: facebook_*link :for => :customer." error_message %= if scope.present? "#{scope.inspect} is not a valid facebook devise scope. " << "Loaded modules for this scope: #{mapping.for.inspect}." else "Could not auto-detect any facebook_connectable devise scope." end raise error_message end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def default_scope\n @default_scope ||= 'entitlements'\n end", "def devise_scope(scope); end", "def selected_scope\n (params[:scope] || :default).to_sym\n end", "def default_search_scope\n @default_search_scope ||= default_search_scopes[controller_name.to_sym][:actions][action_name.to_sym] ||\n default_search_scopes[controller_name.to_sym][:default]\n end", "def default_search_scope\n @default_search_scope ||= default_search_scopes[controller_name.to_sym][:actions][action_name.to_sym] ||\n default_search_scopes[controller_name.to_sym][:default]\n end", "def available_scopes\n (default_scopes << Doorkeeper.config.optional_scopes.to_a).flatten.uniq\n end", "def default_scope; end", "def current_scope\n params[:scope].try(:to_sym) || railgun_resource.default_scope.try(:key)\n end", "def default_scopes\n Doorkeeper.config.default_scopes.to_a\n end", "def default_scope\n Configuration::Scope.new(Configuration.new)\n end", "def devise_scope(scope)\n constraint = lambda do |request|\n request.env[\"devise.mapping\"] = Devise.mappings[scope]\n true\n end\n\n constraints(constraint) do\n yield\n end\n end", "def with_default_scope\n queryable.with_default_scope\n end", "def downgrade_scopes!\n return unless Feature.enabled?(:omniauth_login_minimal_scopes, current_user,\n default_enabled: :yaml)\n\n auth_type = params.delete('gl_auth_type')\n return unless auth_type == 'login'\n\n ensure_read_user_scope!\n\n params['scope'] = Gitlab::Auth::READ_USER_SCOPE.to_s if application_has_read_user_scope?\n end", "def default_search_scope(id, options = {})\n if actions = options[:only]\n actions = [] << actions unless actions.is_a?(Array)\n actions.each {|a| default_search_scopes[controller_name.to_sym][:actions][a.to_sym] = id.to_s}\n else\n default_search_scopes[controller_name.to_sym][:default] = id.to_s\n end\n end", "def default_search_scope(id, options = {})\n if actions = options[:only]\n actions = [] << actions unless actions.is_a?(Array)\n actions.each {|a| default_search_scopes[controller_name.to_sym][:actions][a.to_sym] = id.to_s}\n else\n default_search_scopes[controller_name.to_sym][:default] = id.to_s\n end\n end", "def default_param_group_scope\n @scope\n end", "def default_discount_scope=(default_discount_scope)\n validator = EnumAttributeValidator.new('String', [\"sessionTotal\", \"cartItems\", \"additionalCosts\"])\n unless validator.valid?(default_discount_scope)\n fail ArgumentError, \"invalid value for \\\"default_discount_scope\\\", must be one of #{validator.allowable_values}.\"\n end\n @default_discount_scope = default_discount_scope\n end", "def define_default_scope(klass, conditions)\n if Rails.version.to_i < 4 # Rails 2/3\n klass.send :default_scope, conditions\n else\n klass.send :default_scope do\n klass.scoped(conditions)\n end\n end\n end", "def define_default_scope(klass, conditions)\n if Rails.version.to_i < 4 # Rails 2/3\n klass.send :default_scope, conditions\n else\n klass.send :default_scope do\n klass.scoped(conditions)\n end\n end\n end", "def process_application_default_auth(options)\n ::Google::Auth.get_application_default(options[:google_api_scope_url])\n end", "def default_scopes(*scopes)\n @config.instance_variable_set(:@default_scopes, OAuth::Scopes.from_array(scopes))\n end", "def _default_param_group_scope\n @param_group && @param_group[:scope]\n end", "def apply_default_scope\n if klass.default_scoping && default_scopable?\n self.default_scopable = false\n fuse(klass.default_scoping)\n else\n self\n end\n end", "def current_user_scope\n current_user\n end", "def use_default\n Gist.scoped.includes(:profile)\n end", "def default_object\n @_scope.respond_to?(:controller) ?\n instance_variable_get(\"@#{@_scope.controller.controller_name}\") :\n nil\n end", "def select_scope(scope)\n if [Scopes::SCOPE_PRIVATE, Scopes::SCOPE_PUBLIC, nil].include?(scope)\n Scopes::SCOPE_PRIVATE\n else\n scope\n end\n end", "def scope_from_params(params)\n return default_scope if params[:scope].blank?\n scope = params[:scope].is_a?(Array) ? params[:scope] : params[:scope].split(',')\n scope = scope.map(&:downcase).map(&:strip)\n return scope & default_scope\n end", "def define_default_scope(klass, conditions)\n if default_scopes_accept_a_block?\n if conditions\n klass.instance_eval %{\n default_scope { where(#{conditions.inspect}) }\n}\n end\n else\n if conditions\n klass.instance_eval %{\n default_scope where(#{conditions.inspect})\n}\n end\n end\n end", "def find_scope(filter_name)\n @model_decorator.filters[filter_name].try(:[], :scope) || filter_name\n end" ]
[ "0.66070735", "0.6594775", "0.6593576", "0.63586944", "0.63586944", "0.63369197", "0.62723523", "0.62362134", "0.59804624", "0.59734815", "0.59291697", "0.5908682", "0.58899844", "0.5889887", "0.5889887", "0.5771757", "0.57378805", "0.57091737", "0.57091737", "0.5700931", "0.5663392", "0.56409794", "0.5572558", "0.55382377", "0.5534423", "0.54838514", "0.5455937", "0.5424222", "0.5372902", "0.5348958" ]
0.73611414
0
Generate agnostic hidden sign in/out (connect) form for Facebook Connect.
def facebook_connect_form(scope, options = {}) sign_out_form = options.delete(:sign_out) options.reverse_merge!( :id => (sign_out_form ? 'fb_connect_sign_out_form' : 'fb_connect_sign_in_form'), :style => 'display:none;' ) scope = ::Devise::Mapping.find_by_path(request.path).name rescue scope url = sign_out_form ? destroy_session_path(scope) : session_path(scope) form_for(scope, :url => url, :html => options) { |f| } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fb_sign_out_tab\n %{\n <form action=\"/users/sign_out\" id=\"fb_connect_sign_out_form\" method=\"get\" style=\"display:none;\"></form>\n <li><a href=\"#\" onclick=\"FB.Connect.logoutAndRedirect('/users/sign_out')\"><span>Sign out</span></a></li>\n }\n end", "def html_logout_form(cgi_dir)\n <<~HTML\n <form NAME=\"login\" ACTION=\"#{cgi_dir}/login.rbx\" METHOD=\"post\">\n <input TYPE=\"submit\" NAME=\"logout\" VALUE=\"logout\" >\n </form>\n HTML\n end", "def fb_init(options = {})\n perms = (options[:perms] || %w{email publish_stream}).join(\",\")\n locale = options[:locale] || \"es_ES\"\n\n js = <<-DATA\n <div id=\"fb-root\"></div>\n <script type=\"text/javascript\">\n window.fbAsyncInit = function() {\n FB.init({\n appId: '#{Facebook::APP_ID.to_s}',\n status: true,\n cookie: true,\n xfbml: true\n });\n\n FB.Canvas.setAutoResize(100);\n\n #{options[:append_to_init]}\n };\n\n (function() {\n var e = document.createElement('script'); e.async = true;\n e.src = document.location.protocol +\n '//connect.facebook.net/#{locale}/all.js';\n document.getElementById('fb-root').appendChild(e);\n }());\n\n var login = function(targetUrl, perms) {\n if (perms == null) {\n perms = \"#{perms}\"\n }\n FB.login(function(response) {\n if (response.session) {\n fixSession(JSON.stringify(response.session), targetUrl);\n } else {\n //pending to do when not logged in\n }\n }, {perms: perms});\n }\n\n var fixSession = function(fbSession, targetUrl) {\n $(\"body\").prepend('<form id=\"fixSession\"></form>');\n\n var f = $('form')[0];\n f.method = 'POST';\n f.action = \"/cookie_fix\";\n var m = document.createElement('input');\n m.setAttribute('type', 'hidden');\n m.setAttribute('name', '_session_id');\n m.setAttribute('value', fbSession);\n f.appendChild(m);\n\n m = document.createElement('input');\n m.setAttribute('type', 'hidden');\n m.setAttribute('name', 'redirect_to');\n m.setAttribute('value', targetUrl);\n f.appendChild(m);\n\n f.submit();\n }\n </script>\n DATA\n \n js.html_safe\n end", "def authButtonAction(sender)\n if FBSession.activeSession.open?\n appDelegate.closeSession\n else\n appDelegate.openSessionWithAllowLoginUI(true)\n end\n end", "def show\n auth = Authentication.auth.from_cookie(cookies)\n authenticate Authentication.identify(auth.user)\n redirect_to Facebook.config[:app_url]\n end", "def fb_auth\n session[:sign_up_reason] = nil\n\n if params[:return_to]\n set_after_sign_in_location(params[:return_to])\n elsif params[:spree_user_return_to]\n set_after_sign_in_location(params[:spree_user_return_to])\n elsif is_user_came_from_current_app\n set_after_sign_in_location(request.referrer)\n end\n\n if params[:redeem_via_fb_state]\n session[:redeem_via_fb_state] = params[:redeem_via_fb_state]\n end\n\n if params[:new_modal_fb_state]\n session[:new_modal_fb_state] = params[:new_modal_fb_state]\n end\n\n if params[:show_promocode_modal]\n session[:show_promocode_modal] = params[:show_promocode_modal]\n # reset current modal popup\n set_after_sign_in_location(root_path)\n end\n\n session[:auto_apply] = params[:auto_apply] if params.key?(:auto_apply)\n session[:auto_apply_promo] = params[:auto_apply_promo] if params.key?(:auto_apply_promo)\n\n # Capture PLEASE REMIND ME ABOUT MY SALE events to push onto customer.io later.\n session[:email_reminder_promo] = params[:email_reminder_promo] if params.key?(:email_reminder_promo)\n\n\n redirect_to spree.spree_user_omniauth_authorize_url(provider: :facebook, scope: 'email,public_profile,user_friends')\n end", "def signin_get\n @mode = :signin\n \n if params[:req].present? && !ApplicationController::RequiredIdentity.payload(session)\n @mode = :signup\n kind = params[:req].to_sym\n back = request.env[\"HTTP_REFERER\"]\n \n ApplicationController::RequiredIdentity.set_payload(session, \n :on_success => back,\n :on_cancel => back,\n :kind => kind)\n end\n \n render! :action => \"new\", :layout => \"dialog\"\n end", "def sign_in\n render inline: \"<html><head><script>window.close();</script></head><body></body></html>\".html_safe\n end", "def new\n session[:user_return_to] ||= params[:user_return_to]\n @already_hoc_registered = params[:already_hoc_registered]\n @hide_sign_in_option = true\n if params[:providerNotLinked]\n if params[:useClever]\n # The provider was not linked, and we need to tell the user to sign in specifically through Clever\n flash.now[:alert] = I18n.t 'auth.use_clever', provider: I18n.t(\"auth.#{params[:providerNotLinked]}\")\n else\n # This code is only reached through the oauth flow when the user already has an email account.\n # Usually email would not be available for students, this is a special case where oauth fills it in.\n flash.now[:alert] = I18n.t 'auth.not_linked', provider: I18n.t(\"auth.#{params[:providerNotLinked]}\")\n @email = params[:email]\n end\n end\n super\n end", "def show\n auth = Facebook.auth.from_cookie(cookies)\n authenticate Facebook.identify(auth.user)\n redirect_to dashboard_url\n end", "def login_popup\n session[:redirect_to_after_auth] = request.env['HTTP_REFERER']\n @login_form = LoginForm.new\n render :layout => \"blank\"\n end", "def displayLoginPage()\n\t# User Name: \n\t# Password:\n\t# Forgot Password?\tNew User?\n\treturn\nend", "def show\n auth = Facebook.auth.from_cookie(cookies)\n authenticate Facebook.identify(auth.user)\n redirect_to dashboard_url\n end", "def new\n @partner_sign_in = true\n render layout: 'sign_pages'\n end", "def hide_passwords\n if params[:hide_passwords]\n session[:hide_passwords] = true\n else\n session[:hide_passwords] = false\n end\n redirect_to request.referrer\n end", "def form_logout\n post '/goldberg/auth/logout'\n end", "def before_connect(facebook_session)\n self.login = 'facebook_' + facebook_session.user.name\n self.facebook_name = facebook_session.user.name\n self.password = \"5uttr33_#{self.login}\"\n self.signup_source = 'facebook'\n end", "def logout\r\n reset_session \r\n refreshLogout ##This will hide the logout button and display the login box\r\n \r\n end", "def show_logout\n @show_logout = true\n end", "def koala_logout_button(button_text = \"Logout\", logout_url = \"/\", options = {})\n options = { :unobtrusive => true, :onclick => \"FB.getLoginStatus(function(status){if(status.session){FB.logout(function(response){document.location.href='#{logout_url}'});}else{document.location.href='#{logout_url}'}})\" }.merge(options)\n link_to button_text, \"#\", options\n end", "def before_connect(facebook_session)\n self.login = facebook_session.user.name\n self.facebook_name = facebook_session.user.name\n self.password = \"5uttr33_#{self.login}\"\n self.signup_source = 'facebook'\n end", "def disconnect_facebook\n current_user.fb_uid = nil\n current_user.fb_access_token = nil\n current_user.save!\n redirect_to request.referer, notice: 'Disconnected from Facebook'\n end", "def disconnect_facebook\n current_user.fb_uid = nil\n current_user.fb_access_token = nil\n current_user.save!\n redirect_to request.referer, notice: 'Disconnected from Facebook'\n end", "def fill_out_form(email, password, password_confirmation)\n fill_in \"Email\", with: email\n fill_in \"Password\", with: password\n fill_in \"Password confirmation\", with: password_confirmation\n click_button \"Sign up\"\n end", "def fill_out_form(email, password, password_confirmation)\n fill_in \"Email\", with: email\n fill_in \"Password\", with: password\n fill_in \"Password confirmation\", with: password_confirmation\n click_button \"Sign up\"\n end", "def create_fb_url_with_creds(indv_u_id, ac_token, decoded_state: nil)\n url = FACEBOOK_URL + \"?individual_user_id=#{indv_u_id}&secret=#{ac_token}\"\n if decoded_state\n url += \"pathway=#{decoded_state['pathway']}\" +\n \"&gift_template_id=#{decoded_state['gift_template_id']}\" \n end\n \n #Creates facebook oauth dialog url\n #--PE 10/30/14\n def create_oauth_url(cb_url, encoded_auth_state)\n oauth_url = \"https://www.facebook.com/dialog/oauth/?client_id=\" +\n \"#{APP_ID}&redirect_uri=#{cb_url}&state=#{encoded_auth_state}\"\n end\n\n #########\n protected\n ######### \n\n #Renew the access_token after API failure --PE July 17, 2012\n def rescue_api_error\n session.delete(:access_token)\n\t session.delete(:individual_user_id)\n\t oauth = Koala::Facebook::OAuth.new(APP_ID, APP_SECRET, AUTH_CALLBACK)\n\t redirect_to(:action => \"exit_portal\", :url => oauth.url_for_oauth_code)\n end\n\n #Redirect to app index page after connection is reset --PE July 23, 2012\n def rescue_connection_reset\n redirect_to(:action => \"index\")\n flash[:notice] = \"Sorry, something went wrong (connection reset). \" +\n \"Please try again.\"\n end\n\n #Redirect to app index page after undefined method errors --PE July 23, 2012\n def rescue_undefined_method\n redirect_to(:action => \"index\")\n flash[:notice] = \"Sorry, something went wrong (undefined method). \" +\n \"Please try again.\"\n end\nend", "def connect\n raise ArgumentError unless (params[:fname] == '_opener')\n raise ArgumentError unless connect = ActiveSupport::JSON.decode(params[:session])\n\n @user = User.find_by_facebook_uid(connect['uid'])\n\n if @user.nil?\n # create a new user for the Facebook User if not present\n @user = User.new\n @user.facebook_uid = connect['uid']\n\n # XXX this is crap: login, country and email should be fetched from the facebook. Why?\n # because: login clashes could occur (if an user names itself fb_123456), the \"unknown\"\n # country is BAD design, because it's a corner case to cope with in views, and the fake\n # email is USELESS to send mewsic e-mail notifications to the user.\n #\n @user.login = \"fb_#{@user.facebook_uid}\" # XXX\n @user.country = \"unknown\" # XXX\n @user.email = \"#{@user.facebook_uid}@users.facebook.com\" # XXX\n\n @user.password = @user.password_confirmation = rand(2**32).to_s\n @user.save!\n end\n\n session[:fb_connect] = true\n self.current_user = @user\n\n # render the cross-domain communication channel\n render :layout => false\n\n rescue ActiveRecord::ActiveRecordError\n debugger\n head :forbidden\n\n rescue ArgumentError\n head :bad_request\n end", "def show_connect_form\n if params[:award].present?\n @connect_for_award = true\n end\n @user = User.find(params[:uid])\n render :partial => \"profile_connect_with\", :layout => false\n end", "def signout\n #Made changes to show feedback form at certain intervals as per discussion & also signout auditors gracefully\n #Author: Ashish Wadekar\n #Date: 16th February 2017\n if @current_user.auditor?\n logout_user\n elsif @current_user.login_count < 6 || @current_user.login_count % 50 == 0\n redirect_to login_logout_feedback_path\n else\n logout_user\n end\n end", "def feature_plain_sign_in(login, password, options = {})\n visit '/'\n fill_in 'educator_login_text', with: login\n fill_in 'educator_password', with: password\n if options[:login_code]\n fill_in 'educator_login_code', with: options[:login_code]\n end\n click_button 'Sign in'\n end" ]
[ "0.6992346", "0.5685852", "0.5656324", "0.5525541", "0.53849596", "0.5353388", "0.5326352", "0.53056586", "0.5285196", "0.5282517", "0.5274615", "0.5268719", "0.5264819", "0.52586305", "0.52490914", "0.5213328", "0.52072877", "0.5185584", "0.5177293", "0.5154246", "0.51484555", "0.5140725", "0.5140725", "0.5123044", "0.5123044", "0.51203245", "0.510129", "0.50986624", "0.5090323", "0.50788164" ]
0.75580984
0
Test data: (;PB[Honinbo Shusaku]BR[6d]PW[Honinbo Shuwa]WR[8d])
def test_data_hash [{ 'PB' => 'Honinbo Shusaku', 'BR' => '6d', 'PW' => 'Honinbo Shuwa', 'WR' => '8d', 'GC' => 'game from Hikaru no Go chapter 2, this version only in the anime', 'RE' => 'W+4' }] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_DR_PDB\n data = \"DR PDB; 1NB3; X-ray; A/B/C/D=116-335, P/R/S/T=98-105.\"\n sp = SPTR.new(data)\n assert_equal([[\"1NB3\", \"X-ray\", \"A/B/C/D=116-335, P/R/S/T=98-105\"]],\n sp.dr['PDB'])\n end", "def strand; @data[8]; end", "def process_data(data)\n print_headline\n tmp = data.dup\n\n # TELNETコマンドを抽出しダンプする.\n tmp.gsub!(/#{IAC}(\n [#{DONT}#{DO}#{WONT}#{WILL}].|\n #{SB}.(#{IAC}#{IAC}|[^#{IAC}])*#{IAC}#{SE}|\n [#{NOP}-#{GA}#{0.chr}-#{239.chr}]\n )/xon){\n case $1[0].chr\n when DONT; print \"> IAC DONT #{$1[1]}\\n\"\n when DO ; print \"> IAC DO #{$1[1]}\\n\"\n when WONT; print \"> IAC WONT #{$1[1]}\\n\"\n when WILL; print \"> IAC WILL #{$1[1]}\\n\"\n when SB ; print \"> IAC SB #{$1[1]} #{$1[2..-3].dump} IAC SE\\n\"\n else ; print \"> IAC #{$1[1]}\\n\"\n end\n }\n\n # 残りの部分を出力.\n tmp.each { |line| print line.dump, \"\\n\" } if tmp.size > 0\n end", "def test_nested_loops\n want = <<~EDI.gsub(/\\n/, \"\")\n ST*810*0001~\n BIG*19700101*test*19700101*00000007397108*004010~\n REF*IO*define-this-value~\n N1*ST*Sweeney Todd~\n N3*2705 Fleet St~\n N4*Birmingham*AL*35226*US~\n DTM*011*19700101~\n IT1*1*1*EA*59.95**UP*860001662184*VP*860001662184*A3*860001662184*ZZ*860001662184*EN*860001662184~\n CTP**DPR*0*0**DIS*0*59.95~\n PID*F****CBD Topical Cream 400mg THC Free~\n SAC*C*ZZZZ***0~\n IT1*2*2*EA*49.95**UP*860001662184*VP*860001662184*A3*860001662184*ZZ*860001662184*EN*860001662184~\n CTP**DPR*0*0**DIS*0*49.95~\n PID*F****500mg Full Spectrum Garden Mint Oil Tincture~\n SAC*C*ZZZZ***0~\n TDS*17985~\n CAD*****define-this-value~\n SAC*C*ZZZZ***5995~\n SAC*C*ZZZZ***9990~\n CTT*2~\n SE*21*0001\n EDI\n store = Eddy::Data::Store.new(time: @epoch)\n ts = Eddy::TransactionSets::TS810::TS.new(store)\n ts.BIG do |big|\n big.BIG01 = @epoch\n big.BIG02 = \"test\"\n big.BIG03 = @epoch\n big.BIG04 = \"00000007397108\"\n big.BIG05 = \"004010\"\n end\n ts.REF.REF01 = \"IO\"\n ts.REF.REF02 = \"define-this-value\"\n ts.L_N1 do |n1|\n n1.N1.N101 = \"ST\"\n n1.N1.Name = \"Sweeney Todd\"\n n1.N3.AddressInformation1 = \"2705 Fleet St\"\n n1.N4.CityName = \"Birmingham\"\n n1.N4.StateOrProvinceCode = \"AL\"\n n1.N4.PostalCode = \"35226\"\n n1.N4.CountryCode = \"US\"\n end\n ts.DTM.DTM01 = \"011\"\n ts.DTM.DTM02 = @epoch\n ts.L_IT1 do |rep|\n rep.IT1 do |it1|\n it1.AssignedIdentification = \"1\"\n it1.QuantityInvoiced = 1\n it1.IT103 = \"EA\"\n it1.UnitPrice = 59.95\n it1.IT106 = \"UP\"\n it1.IT107 = \"860001662184\"\n it1.IT108 = \"VP\"\n it1.IT109 = \"860001662184\"\n it1.IT110 = \"A3\"\n it1.IT111 = \"860001662184\"\n it1.IT112 = \"ZZ\"\n it1.IT113 = \"860001662184\"\n it1.IT114 = \"EN\"\n it1.IT115 = \"860001662184\"\n end\n # CTP\n rep.CTP do |ctp|\n ctp.CTP02 = \"DPR\"\n ctp.CTP03 = 0\n ctp.CTP04 = 0\n ctp.CTP06 = \"DIS\"\n ctp.CTP07 = 0\n ctp.CTP08 = 59.95\n end\n # PID\n rep.L_PID do |pid|\n pid.PID.PID01 = \"F\"\n pid.PID.PID05 = \"CBD Topical Cream 400mg THC Free\"\n end\n # SAC\n rep.L_SAC do |sac|\n sac.SAC.SAC01 = \"C\"\n sac.SAC.SAC02 = \"ZZZZ\"\n sac.SAC.SAC05 = 0\n end\n end\n ts.L_IT1 do |rep|\n # IT1\n rep.IT1.AssignedIdentification = \"2\"\n rep.IT1.QuantityInvoiced = 2\n rep.IT1.IT103 = \"EA\"\n rep.IT1.UnitPrice = 49.95\n rep.IT1.IT106 = \"UP\"\n rep.IT1.IT107 = \"860001662184\"\n rep.IT1.IT108 = \"VP\"\n rep.IT1.IT109 = \"860001662184\"\n rep.IT1.IT110 = \"A3\"\n rep.IT1.IT111 = \"860001662184\"\n rep.IT1.IT112 = \"ZZ\"\n rep.IT1.IT113 = \"860001662184\"\n rep.IT1.IT114 = \"EN\"\n rep.IT1.IT115 = \"860001662184\"\n # CTP\n rep.CTP.CTP02 = \"DPR\"\n rep.CTP.CTP03 = 0\n rep.CTP.CTP04 = 0\n rep.CTP.CTP06 = \"DIS\"\n rep.CTP.CTP07 = 0\n rep.CTP.CTP08 = 49.95\n # PID\n rep.L_PID do |rep|\n rep.PID.PID01 = \"F\"\n rep.PID.PID05 = \"500mg Full Spectrum Garden Mint Oil Tincture\"\n end\n # SAC\n rep.L_SAC do |rep|\n rep.SAC.SAC01 = \"C\"\n rep.SAC.SAC02 = \"ZZZZ\"\n rep.SAC.SAC05 = 0\n end\n end\n ts.TDS.TDS01 = 179.85\n ts.CAD.CAD05 = \"define-this-value\"\n ts.L_SAC do |rep|\n rep.SAC.SAC01 = \"C\"\n rep.SAC.SAC02 = \"ZZZZ\"\n rep.SAC.SAC05 = 59.95\n end\n ts.L_SAC do |rep|\n rep.SAC.SAC01 = \"C\"\n rep.SAC.SAC02 = \"ZZZZ\"\n rep.SAC.SAC05 = 49.95 * 2\n end\n ts.CTT.NumberOfLineItems = 2\n result = ts.render()\n assert_equal(want, result)\n end", "def test_OH_lines\n data = 'OS Tomato black ring virus (strain E) (TBRV).\nOC Viruses; ssRNA positive-strand viruses, no DNA stage; Comoviridae;\nOC Nepovirus; Subgroup B.\nOX NCBI_TaxID=12277;\nOH NCBI_TaxID=4681; Allium porrum (Leek).\nOH NCBI_TaxID=4045; Apium graveolens (Celery).\nOH NCBI_TaxID=161934; Beta vulgaris (Sugar beet).\nOH NCBI_TaxID=38871; Fraxinus (ash trees).\nOH NCBI_TaxID=4236; Lactuca sativa (Garden lettuce).\nOH NCBI_TaxID=4081; Lycopersicon esculentum (Tomato).\nOH NCBI_TaxID=39639; Narcissus pseudonarcissus (Daffodil).\nOH NCBI_TaxID=3885; Phaseolus vulgaris (Kidney bean) (French bean).\nOH NCBI_TaxID=35938; Robinia pseudoacacia (Black locust).\nOH NCBI_TaxID=23216; Rubus (bramble).\nOH NCBI_TaxID=4113; Solanum tuberosum (Potato).\nOH NCBI_TaxID=13305; Tulipa.\nOH NCBI_TaxID=3603; Vitis.'\n\n res = [{'NCBI_TaxID' => '4681', 'HostName' => 'Allium porrum (Leek)'},\n {'NCBI_TaxID' => '4045', 'HostName' => 'Apium graveolens (Celery)'},\n {'NCBI_TaxID' => '161934', 'HostName' => 'Beta vulgaris (Sugar beet)'},\n {'NCBI_TaxID' => '38871', 'HostName' => 'Fraxinus (ash trees)'},\n {'NCBI_TaxID' => '4236', 'HostName' => 'Lactuca sativa (Garden lettuce)'},\n {'NCBI_TaxID' => '4081', 'HostName' => 'Lycopersicon esculentum (Tomato)'},\n {'NCBI_TaxID' => '39639', 'HostName' => 'Narcissus pseudonarcissus (Daffodil)'},\n {'NCBI_TaxID' => '3885', \n 'HostName' => 'Phaseolus vulgaris (Kidney bean) (French bean)'},\n {'NCBI_TaxID' => '35938', 'HostName' => 'Robinia pseudoacacia (Black locust)'},\n {'NCBI_TaxID' => '23216', 'HostName' => 'Rubus (bramble)'},\n {'NCBI_TaxID' => '4113', 'HostName' => 'Solanum tuberosum (Potato)'},\n {'NCBI_TaxID' => '13305', 'HostName' => 'Tulipa'},\n {'NCBI_TaxID' => '3603', 'HostName' => 'Vitis'}]\n sp = SPTR.new(data)\n assert_equal(res, sp.oh)\n end", "def sample_data\n %w(A,B,1 A,C,2 B,C,3 B,D,3 C,D,1 B,E,2 D,F,3 D,E,3 E,G,3 F,G,1)\n end", "def test_855\n want = <<~EDI.gsub(/\\n/, \"\")\n ST*855*0001~\n BAK*00*AC*00000007397108*19700101~\n N1*ST*Sweeney Todd~\n N3*2705 Fleet St~\n N4*Birmingham*AL*35226*US~\n PO1*1*1*EA*59.95**UP*860001662184*VP*860001662184~\n PID*F****CBD Topical Cream 400mg THC Free~\n ACK*IA*1*EA****UP*860001662184*VP*860001662184~\n PO1*2*2*EA*49.95**UP*860001662108*VP*860001662108~\n PID*F****500mg Full Spectrum Garden Mint Oil Tincture~\n ACK*IA*2*EA****UP*860001662108*VP*860001662108~\n CTT*2~\n SE*13*0001\n EDI\n store = Eddy::Data::Store.new(time: @epoch)\n ts = Eddy::TransactionSets::TS855::TS.new(store)\n ts.BAK do |bak|\n bak.TransactionSetPurposeCode = \"00\"\n bak.AcknowledgmentType = \"AC\"\n bak.PurchaseOrderNumber = \"00000007397108\"\n bak.Date = @epoch\n end\n ts.L_N1 do |rep|\n # N1\n rep.N1.EntityIdentifierCode = \"ST\"\n rep.N1.Name = \"Sweeney Todd\"\n # N3\n rep.N3.AddressInformation1 = \"2705 Fleet St\"\n # N4\n rep.N4.CityName = \"Birmingham\"\n rep.N4.StateOrProvinceCode = \"AL\"\n rep.N4.PostalCode = \"35226\"\n rep.N4.CountryCode = \"US\"\n end\n ts.L_PO1 do |rep|\n rep.PO1.AssignedIdentification = \"1\"\n rep.PO1.QuantityOrdered = 1\n rep.PO1.UnitOrBasisForMeasurementCode = \"EA\"\n rep.PO1.UnitPrice = 59.95\n rep.PO1.ProductServiceIdQualifier1 = \"UP\"\n rep.PO1.ProductServiceId1 = \"860001662184\"\n rep.PO1.ProductServiceIdQualifier2 = \"VP\"\n rep.PO1.ProductServiceId2 = \"860001662184\"\n rep.L_PID do |rep|\n rep.PID.ItemDescriptionType = \"F\"\n rep.PID.Description = \"CBD Topical Cream 400mg THC Free\"\n end\n rep.L_ACK do |rep|\n rep.ACK.LineItemStatusCode = \"IA\"\n rep.ACK.Quantity = 1\n rep.ACK.UnitOrBasisForMeasurementCode = \"EA\"\n rep.ACK.ACK07 = \"UP\"\n rep.ACK.ACK08 = \"860001662184\"\n rep.ACK.ACK09 = \"VP\"\n rep.ACK.ACK10 = \"860001662184\"\n end\n end\n ts.L_PO1 do |rep|\n rep.PO1.AssignedIdentification = \"2\"\n rep.PO1.QuantityOrdered = 2\n rep.PO1.UnitOrBasisForMeasurementCode = \"EA\"\n rep.PO1.UnitPrice = 49.95\n rep.PO1.ProductServiceIdQualifier1 = \"UP\"\n rep.PO1.ProductServiceId1 = \"860001662108\"\n rep.PO1.ProductServiceIdQualifier2 = \"VP\"\n rep.PO1.ProductServiceId2 = \"860001662108\"\n rep.L_PID do |rep|\n rep.PID.ItemDescriptionType = \"F\"\n rep.PID.Description = \"500mg Full Spectrum Garden Mint Oil Tincture\"\n end\n rep.L_ACK do |rep|\n rep.ACK.LineItemStatusCode = \"IA\"\n rep.ACK.Quantity = 2\n rep.ACK.UnitOrBasisForMeasurementCode = \"EA\"\n rep.ACK.ACK07 = \"UP\"\n rep.ACK.ACK08 = \"860001662108\"\n rep.ACK.ACK09 = \"VP\"\n rep.ACK.ACK10 = \"860001662108\"\n end\n end\n ts.CTT.NumberOfLineItems = 2\n result = ts.render()\n assert_equal(want, result)\n end", "def test_parsing_from_syntheyes_2dp\n fixture = File.open(File.dirname(__FILE__) + '/sy_subpix_2dpaths.txt')\n trackers = Tracksperanto::Import::Syntheyes.new(:io => fixture, :width => 720, :height => 576).to_a\n \n bl_kf = trackers[2][0]\n assert_in_delta 0.0, bl_kf.abs_x, DELTA\n assert_in_delta 0.0, bl_kf.abs_y, DELTA\n\n tr_kf = trackers[3][0]\n assert_in_delta 720.0, tr_kf.abs_x, DELTA\n assert_in_delta 576.0, tr_kf.abs_y, DELTA\n end", "def test_RG_line\n data = \"\nRN [1]\nRG The C. elegans sequencing consortium;\nRG The Brazilian network for HIV isolation and characterization;\"\n sp = SPTR.new(data)\n assert_equal(['The C. elegans sequencing consortium', \n 'The Brazilian network for HIV isolation and characterization'],\n sp.ref.first['RG'])\n end", "def test_parse_hapmap_snp_data\n column_headings = []\n snp_data = []\n File.open(\"#{RAILS_ROOT}/test/mocks/#{@hapmap_filename}\",\"r\") do |file|\n while (f = file.gets)\n\n next if f =~ /^#/ # ignore lines that start with a hash - comments\n f.strip! # remove any whitespace, linefeeds, etc.\n\n # if this line has the column headings, extract and do the next line\n if f =~ /^rs#/\n column_headings = f.split(/\\s/)\n next\n end\n\n # Split the hapmap file based on spaces\n snp_data = f.split(/\\s/)\n\n # load_hapmap_snp_data(column_headings,snp_data)\n break\n end # end of file_array.each loop\n\n # test that we're parsing the headings and the SNP data correctly\n assert_equal \"SNPalleles\",column_headings[1]\n assert_equal \"rs7754266\",snp_data[0]\n assert_equal \"ncbi_b35\",snp_data[5]\n end\n end", "def extrst(data)\n io = StringIO.new(data)\n\n _, cb = io.read(4).unpack('vv')\n # reserved (2 bytes): MUST be 1, and MUST be ignored.\n result = { cb: cb } # cb (2 bytes): An unsigned integer that specifies the size, in bytes, of the phonetic string data.\n\n result[:phs] = phs(io.read(4)) # phs (4 bytes): A Phs that specifies the formatting information for the phonetic string.\n result[:rphssub] = rphssub(io) # rphssub (variable): An RPHSSub that specifies the phonetic string.\n\n result[:rphssub][:crun].times do # See 2.5.219 RPHSSub\n result[:rgphruns] ||= []\n result[:rgphruns] << rgphruns(io)\n end\n\n result\n end", "def process_data(data)\n puts '=' * 100\n puts data.class\n hash = {}\n data.split('&').each do |kv|\n key, value = kv.split('=')\n hash[key] = value\n end\n puts hash\n puts hash['glass'].chars.each_slice(10).to_a.reverse.map(&:join).join(\"\\n\")\n puts '-' * 100\n puts empty = hash['glass'].index(' ')\n puts hash['glass'][hash['x'].to_i+1]\n if hash['y'].to_i == 17\n @result = 'drop'\n return\n end\n if hash['figure'] = 'I'\n if hash['x'].to_i == empty\n @result = 'drop'\n else\n @result = \"left=#{hash['x'].to_i-empty}\"\n end\n else\n if (hash['x'].to_i == empty) && (hash['glass'][hash['x'].to_i + 1] == ' ')\n @result = 'drop'\n else\n @result = \"left=#{hash['x'].to_i-empty}\"\n end\n end\n\n # @result = 'drop'\n end", "def test_dolla_squiggle\n m = match_data_example\n assert_equal m[0], $~[0]\n\n mismatch_data_example\n assert_nil $~\n end", "def test_parsing_from_pftrack\n fixture = File.open(File.dirname(__FILE__) + '/julik_pftrack.txt')\n trackers = Tracksperanto::Import::PFTrack.new(:io => fixture, :width => 720, :height => 576).to_a\n \n bl_kf = trackers[0][0]\n assert_in_delta 0.5, bl_kf.abs_x, DELTA\n assert_in_delta 0.5, bl_kf.abs_y, DELTA\n \n tr_kf = trackers[1][0]\n assert_in_delta 715.5, tr_kf.abs_x, DELTA\n assert_in_delta 571.514, tr_kf.abs_y, DELTA\n end", "def test_parse_mdc_snp_data\n column_headings = []\n snp_data = []\n File.open(\"#{RAILS_ROOT}/test/mocks/#{@mdc_filename}\",\"r\") do |file|\n while (f = file.gets)\n\n next if f =~ /^#/ # ignore lines that start with a hash - comments\n f.strip! # remove any whitespace, linefeeds, etc.\n\n # if this line has the column headings, extract and do the next line\n if f =~ /^a1_External_ID/\n column_headings = f.split(/\\t/)\n next\n end\n\n # Split the mdc file based on tabs\n snp_data = f.split(/\\t/)\n\n # load_hapmap_snp_data(column_headings,snp_data)\n break # jump out after first line as we're just testing the parsing\n end # end of file_array.each loop\n\n # test that we're parsing the headings and the SNP data correctly\n assert_equal 235, snp_data.size\n assert_equal \"a2_RGSCv3.4_chr\",column_headings[1]\n assert_equal \"rat105_009_k11.p1ca_226\",snp_data[0]\n assert_equal \"2283252\",snp_data[2]\n assert_equal '6',snp_data[233] # penultimate entry\n assert_equal '6',snp_data[234] # last entry\n assert_equal nil,snp_data[235] # shouldnt exist\n end\n end", "def parse_parameters(raw)\n ret = Array.new\n i = 0\n while raw.size > 0\n case raw[0]\n when 'Z', 'B', 'C', 'S', 'F', 'I', 'D', 'J'\n ret[i] = ['P']\n i += 1\n raw = raw[1..-1]\n when 'L'\n t = raw.index(';')\n ret[i] = ['L', raw[1..t-1]]\n i += 1\n raw = raw[t+1..-1]\n if raw.size == 0\n return ret\n end\n when '['\n if raw[1] == 'L'\n t = raw.index(';')\n ret[i] = ['L', raw[2..t-1]]\n i += 1\n raw = raw[t+1..-1]\n else\n ret[i] = ['P']\n i += 1\n raw = raw[2..-1]\n end\n end\n end\n return ret\nend", "def test_parse_headword\n entry = BigramEntry.new\n entry.parse_line(\"8\t工作\t18904\t6.89133239246\t213454\")\n assert_equal(\"\",entry.headword_trad)\n assert_equal(\"工作\",entry.headword_simp)\n end", "def question_split\n arr_of_strings = []\n single_question = []\n @data.each do |str|\n if str.length == 3 || str.length == 2\n if str[0].numeric? && str[-1] == '.'\n arr_of_strings << single_question\n single_question = []\n single_question << str\n else\n single_question << str\n end\n else\n single_question << str\n end\n end\n arr_of_strings << single_question\n @data = arr_of_strings\n end", "def testParseLine\n ep = EiBiScheduleParser.new\n\n line = \"7490;2300-0455;;;WBCQ;E;NA;;;;\"\n bc = ep.parseEiBiTextLine(line)\n assert_equal 7490, bc[:frequency]\n assert_equal \"WBCQ\", bc[:broadcaster]\n assert_equal 23, bc[:startHour]\n assert_equal 0, bc[:startMinute]\n assert_equal 4, bc[:endHour]\n assert_equal 55, bc[:endMinute]\n assert_equal \"NA\", bc[:targetRegion]\n end", "def pre_operation\n reportICE_tmp = Array.new\n printf(\"@I:Pre-Operation\\n\")\n # line operation\n line_s = Array.new\n @Report_Data.each do |line|\n if /^\\|/ =~ line # for \"1\" \n line = line.sub(\"\\n\",\"\") # erase \"\\n\"\n line_s = line.split(/\\|/) # sub \"|\" charactor\n line_s.delete_at(0)\n reportICE_tmp << line_s\n end\n end\n\n # word operation for each line\n # - modify structrure for multi line description\n size = reportICE_tmp.size-1 \n while( size >= 0 )\n reportICE_tmp[size][@PinNo] = reportICE_tmp[size][@PinNo].gsub(\" \",\"\") # delete space char for 1-st column\n reportICE_tmp[size][@PinName] = reportICE_tmp[size][@PinName].gsub(\" \",\"\") # delete space char for 2-nd column\n reportICE_tmp[size][@ConnectionList] = reportICE_tmp[size][@ConnectionList].gsub(\" \",\"\") # delete space char for 3-rd column\n reportICE_tmp[size][@Attribute] = \"\" # for attribute\n if ( reportICE_tmp[size][@PinNo] == \"\" )\n reportICE_tmp[size-1][@ConnectionList] = reportICE_tmp[size-1][@ConnectionList] + reportICE_tmp[size][@ConnectionList] # combile multi lines\n reportICE_tmp.delete_at(size) \n end\n size -= 1\n end\n\n #\n # modify each data\n #\n if $VERBOSE == true; printf(\"@I:Print Attribute\\n\"); end;\n reportICE_tmp.each do |word|\n pininfo = ReportPinInfo.new\n word[@ConnectionList] = word[@ConnectionList].sub(\"\\[out\\/ioshort\\]\",\"\") # delete unsuported comment\n #\n # PULLDOWN\n #\n if /\\[pulldown\\]/ =~ word[@ConnectionList]\n# if $VERBOSE == true; puts word[@PinNo] + \":\" + word[@PinName] + \" is Pull Down signal\"; end;\n word[@Attribute] = \"pulldown\"\n word[@ConnectionList] = word[@ConnectionList].sub(\"\\[pulldown\\]\",\"\")\n\n # make data\n pininfo.No,pininfo.NetName,pininfo.Attribute,pininfo.PIN = make_pininfo(word)\n \n # connection list\n pininfo.ConnectInfo, @PullDown, pininfo.Type = make_connection_data(word[@ConnectionList],pininfo)\n @List[\"#{pininfo.No}\"] = pininfo\n \n @ConnectList[\"#{pininfo.No}\"] = pininfo\n @NetNameList[\"#{pininfo.NetName}\"] = pininfo\n\n #\n # PULLUP\n #\n elsif /\\[pullup\\]/ =~ word[@ConnectionList]\n# if $VERBOSE == true; puts word[@PinNo] + \":\" + word[@PinName] + \" is Pull Up signal\"; end;\n word[@Attribute] = \"pullup\"\n word[@ConnectionList] = word[@ConnectionList].sub(\"\\[pullup\\]\",\"\")\n \n # make data\n pininfo.No,pininfo.NetName,pininfo.Attribute,pininfo.PIN = make_pininfo(word)\n\n # connection list\n pininfo.ConnectInfo, @PullUp, pininfo.Type = make_connection_data(word[@ConnectionList],pininfo)\n @List[\"#{pininfo.No}\"] = pininfo\n\n @ConnectList[\"#{pininfo.No}\"] = pininfo\n @NetNameList[\"#{pininfo.NetName}\"] = pininfo\n\n elsif /\\[opennet\\]/ =~ word[@ConnectionList]\n# if $VERBOSE == true; puts word[@PinNo] + \":\" + word[@PinName] + \" is Open Net signal\"; end;\n word[@Attribute] = \"opennet\"\n word[@ConnectionList] = word[@ConnectionList].sub(\"\\[opennet\\]\",\"\")\n # make data\n pininfo.No,pininfo.NetName,pininfo.Attribute,pininfo.PIN = make_pininfo(word)\n\n # connection list\n pininfo.ConnectInfo, @OpenNet, pininfo.Type = make_connection_data(word[@ConnectionList],pininfo)\n @OpenNetList[\"#{pininfo.NetName}\"] = pininfo\n @List[\"#{pininfo.No}\"] = pininfo\n\n @ConnectList[\"#{pininfo.No}\"] = pininfo\n @NetNameList[\"#{pininfo.NetName}\"] = pininfo\n \n\n elsif /\\[nofanin\\]/ =~ word[@ConnectionList]\n# if $VERBOSE == true; puts word[@PinNo] + \":\" + word[@PinName] + \" is No Fanin signal\"; end;\n word[@Attribute] = \"nofanin\"\n word[@ConnectionList] = word[@ConnectionList].sub(\"\\[nofanin\\]\",\"\")\n # make data\n pininfo.No,pininfo.NetName,pininfo.Attribute,pininfo.PIN = make_pininfo(word)\n\n # connection list\n pininfo.ConnectInfo, @NoFanin, pininfo.Type = make_connection_data(word[@ConnectionList],pininfo)\n @NoFaninList[\"#{pininfo.NetName}\"] = pininfo\n @List[\"#{pininfo.No}\"] = pininfo\n\n @ConnectList[\"#{pininfo.No}\"] = pininfo\n @NetNameList[\"#{pininfo.NetName}\"] = pininfo\n elsif /\\[out\\/ioshort\\]/ =~ word[@ConnectionList]\n word[@Attribute] = \"ioshort\"\n word[@ConnectionList] = word[@ConnectionList].sub(\"\\[out\\/ioshort\\]\",\"\")\n # make data\n pininfo.No,pininfo.NetName,pininfo.Attribute,pininfo.PIN = make_pininfo(word)\n\n # connection list\n pininfo.ConnectInfo, @NoFanin, pininfo.Type = make_connection_data(word[@ConnectionList],pininfo)\n @IOShortList[\"#{pininfo.NetName}\"] = pininfo\n @List[\"#{pininfo.No}\"] = pininfo\n\n @ConnectList[\"#{pininfo.No}\"] = pininfo\n @NetNameList[\"#{pininfo.NetName}\"] = pininfo\n else\n # make data\n pininfo.No,pininfo.NetName,pininfo.Attribute,pininfo.PIN = make_pininfo(word)\n\n # connection list\n pininfo.ConnectInfo, @Other, pininfo.Type = make_connection_data(word[@ConnectionList],pininfo)\n\n @ConnectList[\"#{pininfo.No}\"] = pininfo\n @List[\"#{pininfo.No}\"] = pininfo\n @NetNameList[\"#{pininfo.NetName}\"] = pininfo\n \n end\n end\n # Update Original-Data Structure\n @Report_Data = reportICE_tmp\n \n printf(\"@I:Pre-Operation Done\\n\")\n end", "def call_input_data\n if creates && input\n input[/a165627a7a72305820\\w{64}0029(\\w*)/,1]\n elsif input && input.length>10\n input[10..input.length]\n else\n []\n end\n end", "def call_input_data\n if creates && input\n input[/a165627a7a72305820\\w{64}0029(\\w*)/,1]\n elsif input && input.length>10\n input[10..input.length]\n else\n []\n end\n end", "def test_hash_end_and_start\n\t\ttest_array1 = '2|abb2|George>Amina(16):Henry>James(4):Henry>Cyrus(17):Henry>Kublai(4):George>Rana(1):SYSTEM>Wu(100)|1518892051.753197000|c72d'.split('|').map(&:chomp)\n\t\ttest_array2 = '3|c72d|SYSTEM>Henry(100)|1518892051.764563000|7419'.split('|').map(&:chomp)\n\t\tassert_equal test_array2[1], test_array1[4]\n\tend", "def test_a_vertical_pipe_means_or\n grays = /(James|Dana|Summer) Gray/\n assert_equal 'James Gray', \"James Gray\"[grays]\n assert_equal 'Summer', \"Summer Gray\"[grays, 1]\n assert_equal nil, \"Jim Gray\"[grays, 1]\n end", "def table_data(data)\n left, middle, right = [@chars[:ldb], @chars[:idb], @chars[:rdb]]\n a = []\n data.each_with_index do |item, x|\n a << (' ' + item.to_s.send(@align[x] || :ljust, @widths[x]) + ' ')\n end\n s = @chars.wrap(left) + a.join(@chars.wrap(middle)) + @chars.wrap(right) + \"\\n\"\n s\n end", "def populate(data)\n @content.gsub(/\\[\\[ (\\S*) \\]\\]/) { |x| data[$1] }\n end", "def separate_tubes(outname, ops, test_str, stamp_columns)\n stop_cycles_tab = display_stop_cycles(outname, ops, stamp_columns)\n wells_tab = display_plate(outname, ops, stamp_columns)\n coll = ops.first.output(outname).collection # get collection item\n\n show do\n title \"Separate #{test_str} stripwell tubes\"\n note \"During the <b>#{REAL}</b> qPCR run, you will need to remove single wells when different cycles are reached, according to the following:\"\n table stop_cycles_tab\n check \"Get a scissors and carefully separate the wells of <b>#{coll}-#{test_str}</b>\"\n check \"Verify that the separated wells are in the correct order:\"\n table wells_tab\n end\n end", "def phs(data)\n ifnt, attrs = data.unpack('vv')\n attrs = Unxls::BitOps.new(attrs)\n\n ph_type = attrs.value_at(0..1)\n ph_type_d = {\n 0x0 => :narrow_katakana,\n 0x1 => :wide_katakana,\n 0x2 => :hiragana,\n 0x3 => :any # Use any type of characters as phonetic string\n }[ph_type]\n\n alc_h = attrs.value_at(2..3)\n alc_h_d = {\n 0x0 => :general, # General alignment\n 0x1 => :left, # Left aligned\n 0x2 => :center, # Center aligned\n 0x3 => :distributed # Distributed alignment\n }[alc_h]\n\n {\n ifnt: ifnt, # ifnt (2 bytes): A FontIndex structure that specifies the font.\n phType: ph_type, # A - phType (2 bits): An unsigned integer that specifies the type of the phonetic information.\n phType_d: ph_type_d,\n alcH: alc_h, # B - alcH (2 bits): An unsigned integer that specifies the alignment of the phonetic string.\n alcH_d: alc_h_d\n # unused (12 bits): Undefined and MUST be ignored.\n }\n end", "def create_run_code\n @index = self.short_description.index(\"ip\")\n @end_index = self.short_description.index(\"and bin_id\")\n @result = self.short_description[@index + 1, @end_index - @index]\n @string = @result.gsub(/[ipa:,]/,' ')\n @array = @string.split(/\\s*/)\n @prod_run_code =\"\"\n @array.each do |char|\n if(char==\":\")\n @prod_run_code.concat(\"\")\n elsif(char==\"\")\n @prod_run_code.concat(\"\")\n elsif(char==\",\")\n @prod_run_code.concat(\"\")\n else\n @prod_run_code.concat(char)\n end\n end\n self.run_code = @prod_run_code.strip()\nend", "def initLog(data)\n n = data[:names].join(\"; \")\n l = data[:data].length\n p = (l === 1) ? \"y\" : \"ies\"\n return %Q_- NAME: #{n}\\n #{l} matching entr#{p}\\n_\nend" ]
[ "0.55512685", "0.53138405", "0.52826405", "0.5220785", "0.5218726", "0.5201712", "0.5189527", "0.5176986", "0.51764995", "0.5163787", "0.5154532", "0.5125206", "0.506041", "0.5060026", "0.5042854", "0.50314355", "0.50238216", "0.49907583", "0.49907136", "0.4989221", "0.49692002", "0.49692002", "0.49521437", "0.4940619", "0.49358022", "0.493186", "0.49291098", "0.4927614", "0.49264306", "0.49246097" ]
0.60254514
0
Append 'phrase' and 'translation'. If this 'phrase' already exists as key, then simply append 'translation' to the value array.
def append(phrase, translation) phrase.strip! translation.strip! if @value_hash[phrase].nil? @value_hash[phrase] = [translation] else @value_hash[phrase] << translation end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_translation(first, second)\r\n @dictionary[second] = first\r\n @dictionary[first] = second\r\n end", "def add_translation(from, to)\n @dictionary[to] = from\n @dictionary[from] = to\n end", "def add_word word #Function shovels individual strings into the dictionary array\n @dictionary << word\n end", "def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength\n I18n.with_locale(locale) do\n # when an array has to be inserted with a default value, it needs to\n # be done like:\n # I18n.t('foo', default: [['bar', 'baz']])\n # because without the double array, array items are treated as fallback keys\n # - then, the last array element is the final fallback; so in this case we\n # don't specify fallback keys and only specify the final fallback, which\n # is the array\n val = value.is_a?(Array) ? [value] : value\n I18n.t(key, default: val)\n\n # this indicates that this translation already exists\n existing_translation =\n Lit::Localization.joins(:locale, :localization_key)\n .find_by('localization_key = ? and locale = ?', key, locale)\n\n return unless existing_translation\n\n if @raw\n existing_translation.update(default_value: value)\n else\n existing_translation.update(translated_value: value, is_changed: true)\n lkey = existing_translation.localization_key\n lkey.update(is_deleted: false) if lkey.is_deleted\n end\n end\n end", "def translate\n @new_phrase = []\n words\n @phrase.each do |word|\n @new_phrase << changer(word)\n end\n end", "def add_translation(translation)\n translations.add(translation)\n end", "def append(key, value); end", "def append(key, value); end", "def add(word)\n\t\tif word.class == String\n\t\t\tword = {word => nil}\n\t\tend\n\n\t\tword.each do |key, value|\n\t\t\t@entries[key] = value\n\t\tend\n\tend", "def add entry\n existing_entry = @entries[entry.msgid]\n if existing_entry\n entry = existing_entry.merge(entry)\n end\n @entries[entry.msgid] = entry\n end", "def append2_to_hash (key, intermediatekey, value )\n if not self.has_key?(key)\n self[key] = Hash.new(Array.new)\n end\n self[key].append(intermediatekey,value)\n end", "def merge_texts!(hash, element)\n unless element.has_text?\n hash\n else\n # must use value to prevent double-escaping\n texts = +\"\"\n element.texts.each { |t| texts << t.value }\n merge!(hash, CONTENT_KEY, texts)\n end\n end", "def append(row,text)\n\t\t@text[row] = @text[row].dup\n\t\t@text[row] += text\n\tend", "def create_phrases\n pinwheel = %w{ | / - \\\\ }\n puts \"Creating keys for locale : #{@locale}\"\n _keys_and_values = yml_to_keys_and_values\n _keys_and_values.each_with_index do |(key, value), index|\n percentage = ((index + 1).to_f / _keys_and_values.length * 100).to_i\n print \"\\b\" * 50, \"Progress: #{percentage}% - #{index + 1}/#{_keys_and_values.length} \", pinwheel.rotate!.first\n\n _key = key.to_s.split('.')[1..-1] * '.'\n next if whitelisted?(_key)\n phrasing_phrases.find_or_initialize_by(key: _key).tap do |pp|\n pp.value = value\n pp.save\n end\n end\n puts 'Done.'\n end", "def add_v1_translations dictionary\n\n ['eligibility', 'accommodation', 'purpose'].each do |trans_type|\n\n trans = dictionary.keys.select { |key| key.to_s.match(/^#{trans_type}_/) }\n trans.each do |tran|\n new_key = tran.sub(\"#{trans_type}_\", \"\")\n dictionary[new_key] = dictionary[tran]\n end\n end\n\n dictionary\n\n end", "def add(key, value)\n update_array(key, value, :add)\n end", "def append(value, hash, array)\n key = array[1]\n hash[value[:key]] = { flags: value[:flags], exptime: value[:exptime], value: hash[key][:value] + value[:value], cas_unique: value[:cas_unique] }\n value[:reply] != 'false' ? (self.result = \"\\r\\nSTORED\") : (self.result = '')\n end", "def append_metadata\n terms = self.characterization_terms\n Sufia.config.fits_to_desc_mapping.each_pair do |k, v|\n if terms.has_key?(k)\n # coerce to array to remove a conditional\n terms[k] = [terms[k]] unless terms[k].is_a? Array\n terms[k].each do |term_value|\n proxy_term = self.send(v)\n if proxy_term.kind_of?(Array)\n proxy_term << term_value unless proxy_term.include?(term_value)\n else\n # these are single-valued terms which cannot be appended to\n self.send(\"#{v}=\", term_value)\n end\n end\n end\n end\n end", "def append_metadata\n terms = self.characterization_terms\n Sufia.config.fits_to_desc_mapping.each_pair do |k, v|\n if terms.has_key?(k)\n # coerce to array to remove a conditional\n terms[k] = [terms[k]] unless terms[k].is_a? Array\n terms[k].each do |term_value|\n proxy_term = self.send(v)\n if proxy_term.kind_of?(Array)\n proxy_term << term_value unless proxy_term.include?(term_value)\n else\n # these are single-valued terms which cannot be appended to\n self.send(\"#{v}=\", term_value)\n end\n end\n end\n end\n end", "def add locale, key, value\n entry = self[key] ||= Entry.new\n entry[locale] = value\n end", "def append(key, value)\n perform(:append, key, value.to_s)\n end", "def test_add_two_xlates\n @dict.add_translation(\"book\", \"boek\")\n @dict.add_translation(\"house\", \"huis\")\n assert [email protected]?\n assert_equal \"book\", @dict.translate(\"boek\")\n assert_equal \"house\", @dict.translate(\"huis\")\n end", "def build_variant_replacements(variant_words)\n # first check if the number of words in a given set is not 7\n # (meaning doesn't include all source/target for each locale + source)\n invalid_variant_words = variant_words.select { |words| words.count != 7 }\n unless invalid_variant_words.empty?\n pp \"Found Invalid Variants: #{invalid_variant_words}\"\n raise Exception.new(\"Found Invalid Variants: #{invalid_variant_words.count}\")\n end\n locale_words = { 'en-GB' => [], 'en-CA' => [], 'en-AU' => [], }\n variant_words.each do |source, gb_source, gb_target, ca_source, ca_target, au_source, au_target|\n puts \"A single row below:\"\n puts \"#{source}, #{gb_source}, #{gb_target}, #{ca_source}, #{ca_target}, #{au_source}, #{au_target}\"\n locale_words['en-GB'] << { origin: source, source: gb_source, target: gb_target }\n # puts locale_words['en-GB']\n locale_words['en-CA'] << { origin: source, source: ca_source, target: ca_target }\n pp locale_words\n # puts locale_words['en-CA']\n locale_words['en-AU'] << { origin: source, source: au_source, target: au_target }\n # puts locale_words['en-AU']\n end\n locale_words\nend", "def append!(key, value); end", "def append!(key, value); end", "def test_add_two_xlates\r\n @dict.add_translation(\"book\", \"boek\")\r\n @dict.add_translation(\"house\", \"huis\")\r\n assert [email protected]?\r\n assert_equal \"book\", @dict.translate(\"boek\")\r\n assert_equal \"house\", @dict.translate(\"huis\")\r\n end", "def to_h\n phrase.to_h.tap do |hash|\n hash[:old_key] = old_phrase.key if old_phrase\n end\n end", "def record_longer_phrase\n compiled_phrase = compile_phrase\n compiled_phrase_length = compiled_phrase.word_count\n @phrases[compiled_phrase_length] ||= Hash.new(0)\n\n # The first duplicate we find needs to record both occurrances\n # TODO: Clean this up. Absolute mother to read.\n new_occurrances = @phrases[compiled_phrase_length][compiled_phrase] > 0 ? 1 : 2\n @phrases[compiled_phrase_length][compiled_phrase] += new_occurrances\n end", "def append(name, val)\n name = name.to_sym\n val = val.to_s\n if @values.key?(name)\n @values[name] << val\n else\n self[name]= val\n end\n val\n end", "def [] aPhrase, *aArgs\n s = aPhrase.to_s\n if key? s\n super(s)\n else\n s\n end.to_s % aArgs\n end" ]
[ "0.6549509", "0.58722985", "0.58677083", "0.5681713", "0.5624002", "0.5559441", "0.55037403", "0.55037403", "0.55036044", "0.54069334", "0.5338864", "0.5314179", "0.5296966", "0.526507", "0.5226372", "0.5176444", "0.5171205", "0.5166237", "0.5166237", "0.5161603", "0.51430196", "0.51397514", "0.5123802", "0.51122147", "0.51122147", "0.5070646", "0.50695294", "0.5055909", "0.50366306", "0.5028229" ]
0.83789486
0
Imports the dict.cc file given in the constructor and builds/writes the database files.
def import read_dict_file(:langA) write_database(:langA) read_dict_file(:langB) write_database(:langB) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 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 load_db\n input_data = File.read($fn)\n $cd_arr = YAML.load(input_data)\nend", "def initialize(path)\n @dictionary_path = path\n @index_path = File.dirname(@dictionary_path)\n @pos_hash = {}\n\n raise \"No dictionary found at path #{@dictionary_path}\" unless File.exists? @dictionary_path\n\n @db_file = File.join(@index_path, \"jdict.db\")\n initialize_db(@db_file)\n end", "def dbs_init\n @dbs_hash = Dir[\"#{dbs_store}/*.db\"]\n .map do |dbfile|\n File.open(dbfile){|f| JSON.parse(f.read, symbolize_names: true)}\n end\n .inject({}) do |h, db|\n h.update({\n db[:name].to_sym => LaPack::const_get(db[:clazz]).new(self, db[:params])\n })\n end\n end", "def initialize(file = File.expand_path(File.join(File.dirname(__FILE__), '../../../db/ush.sqlite.db')))\n FileUtils.touch(file) unless File.exist?(file) # create the db if it doesnt already exist\n puts \"Database is being stored at #{file}\"\n @db = SQLite3::Database.new(file)\n @db.execute 'CREATE TABLE IF NOT EXISTS pairings(url TEXT, code TEXT)'\n end", "def initialize(*dictfiles)\n @searchmode = 0\n Dir.mkdir(dictDir) unless File.exist?(dictDir)\n\n # 固定辞書初期化\n @dc = DictCache.new\n if !@dc[\"kanji\"] then\n DictCache.createCache(dictfiles)\n end\n\n # 個人辞書を読出し\n @localdict = loadDict(localDictFile) \n\n # 学習辞書を読出し\n @studydict = loadDict(studyDictFile)\n end", "def initialize(file_name='persistance.db')\n require 'gdbm'\n # Creates database file if it doesn't exist\n @file_name = file_name\n unless File.directory?('db')\n Dir.mkdir('db/')\n end\n @db = GDBM.new('db/' + file_name)\n @wallet_db = GDBM.new('db/wallets_' + file_name)\n end", "def load_from_file(path = nil)\n path ||= \"db/#{table_name}.yml\"\n\n self.destroy_all\n\n if connection.respond_to?(:reset_pk_sequence!)\n connection.reset_pk_sequence!(table_name)\n end\n\n records = YAML.load(File.open(File.expand_path(path, Rails.root)))\n records.each do |record|\n record_copy = self.new(record.attributes)\n record_copy.id = record.id\n\n # For Single Table Inheritance\n klass_col = record.class.inheritance_column.to_sym\n if record[klass_col]\n record_copy.type = record[klass_col]\n end\n\n record_copy.save\n end\n\n if connection.respond_to?(:reset_pk_sequence!)\n connection.reset_pk_sequence!(table_name)\n end\n end", "def initialize\n self.db = YAML::Store.new(DB_FILE)\n end", "def initialize(database, file_path)\n @file_path = file_path\n @entries = database.entries\n validate_csv_header\n end", "def initialize(db, name, filename)\r\n @db = db\r\n @name = name\r\n @filename = filename\r\n @encrypted = false\r\n @lookup_key = :recno\r\n @idx_timestamps = {}\r\n @idx_arrs = {}\r\n\r\n # Alias delete_all to clear method.\r\n alias delete_all clear\r\n\r\n update_header_vars\r\n create_indexes\r\n create_table_class unless @db.server?\r\n end", "def import_dict_from_file_hnd(dict_name, dict_folder)\n puts \"start importing dictionary\"\n\n base_path = @file_dir+\"/\"+dict_folder\n dict_idx_path = base_path + \"/\" + \"#{dict_folder}.index\"\n dict_data_path = base_path + \"/\" +\"#{dict_folder}.dict\"\n\n dict_table = @DB[@dict_table_name];\n dict_id = -1\n begin\n dict_id = dict_table.insert(:name=>dict_name.force_encoding(\"UTF-8\"),\n :string_id=>dict_folder.force_encoding(\"UTF-8\"))\n rescue\n #dict_id = @DB['SELECT * FROM ? WHERE string_id = ?',@dict_table_name, dict_folder].first\n dict_id = dict_table[:string_id=>dict_folder][:id]\n #puts \"count not insert dict #{dict_id}\"\n end\n\n if (dict_id<0)\n puts \"unknown error, could not find dict_id\"\n return\n end\n\n word_table = @DB[@word_table_name];\n meaning_table = @DB[@meaning_table_name];\n\n\n count = 0\n File.open(dict_data_path, \"r\") do |data_file|\n File.open(dict_idx_path, \"r\") do |idx_file|\n while (line = idx_file.gets)\n count+=1\n pos1 = line.index(\"\\t\")\n pos2=line.index(\"\\t\",pos1+1)\n\n keyword = line[0..pos1-1]\n str_entry_offset = line[pos1+1..pos2-1]\n str_entry_len = line[pos2+1..line.length-2]\n\n entry_offset = dec_val(str_entry_offset)\n entry_len = dec_val(str_entry_len)\n data_file.seek(entry_offset, IO::SEEK_SET)\n meaning = data_file.read(entry_len)\n\n word_id = -1\n existed_meaning = nil\n begin\n ch = keyword[0].upcase\n kind = 0\n if (ch<='Z' and ch >= 'A')\n kind = ch.getbyte(0) - 64\n end\n word_id = word_table.insert(:word=>keyword.force_encoding(\"UTF-8\"), :kind=>kind)\n rescue Exception => e\n word_id = word_table[:word=>keyword][:id]\n existed_meaning = meaning_table[:word=>word_id, :dict=>dict_id]\n if !existed_meaning.nil?\n existed_meaning = existed_meaning[:meaning]\n end\n end\n\n if (word_id<0)\n puts \"unknown error, could not get word id\"\n return\n end\n\n begin\n if (!existed_meaning.nil?)\n meaning = existed_meaning + \"\\n\\n\" + meaning.force_encoding(\"UTF-8\");\n meaning_table[:dict=>dict_id, :word=>word_id] = {:meaning=>meaning}\n else\n meaning_table.insert(:dict=>dict_id,:word=>word_id, :meaning=>meaning)\n end\n rescue Exception => e\n puts \"could not insert meaning #{keyword} e: #{e}\"\n end\n\n if count%1000==0\n puts \"count: #{count}\"\n #return\n end\n\n end\n end\n end\n\n puts \"importing done\"\n\nend", "def init(dir)\n dir = File.expand_path(dir)\n db_file = db(dir)\n raise \"Database #{db_file} already exists\" if File.exist?(db_file)\n FileUtils.mkdir_p(File.dirname(db_file))\n # create database\n monotone(\"db init\", db_file)\n # TODO: do a genkey\n monotone(\"read\", db_file) do |io|\n io.write(File.open(@keys_file).read)\n io.close_write\n end\n end", "def load_db\n basic_foods = {} # store BasicFood objects\n recipes = {} # store Recipe objects\n File.readlines('FoodDB.txt').each do |line|\n line = line.chomp.split(\",\")\n if line[1] == \"b\"\n basic_food = BasicFood.new(line[0], line[2])\n basic_foods[basic_food.name] = basic_food\n elsif line[1] == \"r\"\n recipe = Recipe.new(line[0], line[2..line.size])\n recipes[recipe.name] = recipe\n end\n end\n [basic_foods, recipes]\n end", "def initialize(database_file)\n @database_file = database_file\n @data = get_all()\n end", "def initialize filename = 'db.yaml'\n FileUtils.touch(filename)\n @db = YAML::Store.new(filename)\n end", "def import\n\n output = ''\n\n country_src = 'tmp/Countries.txt'\n \n rs = File.open(country_src)\n rs.gets # <-- remove first line (columns header) \"CountryID:Title\"\n countries = {}\n City.delete_all\n Region.delete_all\n Country.delete_all\n\n while (row = rs.gets) \n row = row.split(':')\n row[0].gsub!(/\\n/, '')\n row[1].gsub!(/\\n/, '')\n countries[row[0]] = {:name => row[1], :regions => {}, :model => nil}\n c = Country.new\n c.iso = row[0]\n c.name = row[1]\n c.save\n countries[row[0]][:model] = c\n end\n\n regions_src = 'tmp/Regions.txt'\n \n rs = File.open(regions_src)\n rs.gets # <-- remove the 1st line (header row) #CountryID:RegionID:Title\n while (row = rs.gets) \n row = row.split(':')\n row[0].gsub!(/\\n/, '')\n row[1].gsub!(/\\n/, '')\n row[2].gsub!(/\\n/, '')\n c = countries[row[0]][:model]\n r = Region.new\n r.iso = row[1]\n r.country_id = c.id\n\n # magic trick to ignore UTF-8 chars for now.\n ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')\n r.name = ic.iconv(row[2] + ' ')[0..-2]\n r.save\n countries[row[0]][:regions][row[1]] = r\n\n end\n\n cities_src = 'tmp/Cities.txt'\n \n rs = File.open(cities_src)\n rs.gets # <-- remove 1st row (header) #CountryID:RegionID:Title:Latitude:Longitude\n while(row = rs.gets)\n row = row.split(':')\n row[1].gsub!(/\\n/, '')\n row[2].gsub!(/\\n/, '')\n row[3].gsub!(/\\n/, '')\n row[4].gsub!(/\\n/, '')\n \n r = countries[row[0]][:regions][row[1]]\n if (!r.nil?) \n c = City.new\n ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')\n c.name = ic.iconv(row[2] + ' ')[0..-2] \n c.region_id = r.id\n c.lat = row[3]\n c.lng = row[4]\n c.save\n end\n end\n\n output += '<h1>Import complete</h1>'\n render(:text => output, :layout => false)\n end", "def import_cities\n City.destroy_all\n print_title('importing cities')\n File.open 'db/2_sql_insert_city.sql', 'r' do |file|\n while row = file.gets\n row.strip!\n columns = /.+\\(\\d+,'(\\d+)','(.+)','(\\d+)'\\)/.match(row)\n code = columns[1]\n name = columns[2]\n province_code = columns[3]\n city = City.create(code: code, name: name, province_code: province_code)\n print_content \"imported city: #{city.id}, #{city.code}, #{city.name}, #{city.province_code}\"\n end\n end\n print_summary \"total imported cities count: #{City.count}\"\nend", "def init # should eventually take configuration options (hash || block)\n if ActiveRecord::Base.connection.tables.include? 'aux_codes'\n aux_codes_yml = File.join 'config', 'aux_codes.yml'\n if File.file? aux_codes_yml\n load_file aux_codes_yml\n create_classes!\n end\n end\n end", "def import_file! file\n # if given a file name, try opening it\n if file.instance_of? String\n _file = File.open file\n elsif file.instance_of? File\n _file = file\n else\n raise \"type not recognized: #{file.class.name}\"\n end\n\n puts \"- Iterating over keys in #{_file.inspect}\" if @verbose\n \n # iterate over keys\n YAML::load(_file).each do |env, env_hash|\n env_hash.each do |app, app_hash|\n app_hash.each do |namespace, namespace_hash|\n namespace_hash.each do |identifier, value|\n k = \"#{namespace}:#{identifier}\"\n set! k, value, app, env\n end\n end\n end\n end\n end", "def import\n Map.import(params[:file])\n end", "def main\n # Does the SQLite File already exist? Exit or delete based on option\n if RECREATE_SQLITE_DB && File.exist?(SQLITE_FILE)\n File.delete(SQLITE_FILE)\n end\n return \"Error - File [#{SQLITE_FILE}] already exists\" if File.exist?(SQLITE_FILE)\n\n # Connect to Db and Create Tables.\n # Several PRAGMA statements are used for optimization, however\n # the primary optimization for SQLite is Transactions otherwise\n # this script could take hours. Using prepared statements on\n # insert increases script performance by about 100%.\n db = SQLite3::Database.new(SQLITE_FILE)\n db.execute 'PRAGMA synchronous = OFF'\n db.execute 'PRAGMA journal_mode = MEMORY'\n db.transaction\n db.execute %{\n CREATE TABLE countries (\n iso TEXT,\n iso3 TEXT,\n iso_numeric INT,\n fips TEXT,\n country TEXT,\n capital TEXT,\n area_km INT,\n population INT,\n continent TEXT,\n tld TEXT,\n currency_code TEXT,\n currency_name TEXT,\n phone TEXT,\n postal_code_format TEXT,\n postal_code_regex TEXT,\n languages TEXT,\n geoname_id TEXT,\n neighbours TEXT,\n equivalent_fips_code TEXT\n )\n }\n db.execute %{\n CREATE TABLE geonames (\n geonames_id INT PRIMARY KEY,\n name TEXT,\n ascii_name TEXT,\n alternate_names TEXT,\n latitude DOUBLE,\n longitude DOUBLE,\n feature_class TEXT,\n feature_code TEXT,\n country_code TEXT,\n cc2 TEXT,\n admin1_code TEXT,\n admin2_code TEXT,\n admin3_code TEXT,\n admin4_code TEXT,\n population LONG,\n elevation INT,\n dem INT,\n timezone TEXT,\n modification_date TEXT\n )\n }\n\n # Insert Records for [countries] Table\n record_count = 0\n path = File.join(CUR_DIR, COUNTRIES_FILE)\n sql = 'INSERT INTO countries (iso, iso3, iso_numeric, fips, country, capital, area_km, population, continent, tld, currency_code, currency_name, phone, postal_code_format, postal_code_regex, languages, geoname_id, neighbours, equivalent_fips_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'\n stmt = db.prepare(sql)\n File.open(path, 'r') do |f|\n f.each_line do |line|\n if line.strip != '' && line.index('#') != 0\n values = line.split(\"\\t\")\n stmt.execute values\n record_count += 1\n end\n end\n end\n stmt.close\n puts \"Added #{record_count} Records to [countries] Table\"\n\n # Insert Records for [geonames] Table\n record_count = 0\n path = File.join(CUR_DIR, PLACES_FILE)\n sql = 'INSERT INTO geonames (geonames_id, name, ascii_name, alternate_names, latitude, longitude, feature_class, feature_code, country_code, cc2, admin1_code, admin2_code, admin3_code, admin4_code, population, elevation, dem, timezone, modification_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'\n stmt = db.prepare(sql)\n File.open(path, 'r:utf-8') do |f|\n f.each_line do |line|\n if line.strip != ''\n values = line.split(\"\\t\")\n stmt.execute values\n record_count += 1\n end\n end\n end\n stmt.close\n puts \"Added #{record_count} Records to [geonames] Table\"\n\n # Add Indexes\n db.execute 'CREATE INDEX country_feature ON geonames (country_code, feature_class, feature_code)'\n db.execute 'CREATE INDEX country_admin1_feature ON geonames (country_code, admin1_code, feature_class, feature_code)'\n db.execute 'CREATE INDEX place_names ON geonames (name , country_code, feature_class, feature_code, population)'\n\n # Commit Transactions and return\n db.commit\n db.close\n 'Success Database Created'\nend", "def createDB(filename)\n db = Hash.new()\t\n csvfile = File.open(filename, \"r\")\n csvfile.each_line do |line|\n arr = line.split(\",\")\n if arr[1] == \"b\"\n\tdb[arr[0]] = BasicFood.new(arr[0], arr[2].to_i)\n end\n\n # if object is a recipe it adds up the calories of all\n #items in the foods list\n if arr[1] == \"r\"\n\tr = Recipe.new (arr[0])\n\ttotal =0\n\tarr.shift\n\tarr.shift\n\tarr.each do |elt|\n\t if (db.has_key?(elt))\n\t r.foods << db[elt]\n\t total += db[elt].calories\n\t end\t\t\n\tend\n\tr.setcalories(total)\n\tdb[r.name] = r\n end\n end\n db\n end", "def initialize \n @Attributes = Hash.new \n @ConfigurationFilename = \"configuration.txt\" \n load_attributes \n end", "def dictionary\n begin\n YAML.load_file(@@abbrevs_file) || initialize_dictionary\n rescue Errno::ENOENT\n initialize_dictionary\n end\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!(input_dir = MODEL_DIR)\n if Rails.env.production?\n raise RuntimeError.new(\"You can't run this in production!\") unless self.i_am_absolutely_positive\n end\n\n Dir.glob( File.join(input_dir.split(\"/\"), \"*.#{ FILE_EXT }\") ).each do |filename|\n model_class = File.basename( filename, \".#{ FILE_EXT }\").gsub(\"-\", \"/\").classify.constantize\n print \"Importing table data for #{ model_class.name.pluralize }... \"\n\n File.open( filename, \"r\" ) do |file|\n next unless File.size?(file)\n\n JSON.parse(file.read).each do |attributes|\n record = model_class.new\n\n # This approach unfortunately appears not to increment any sequences. That\n # means that the next INSERT will try to use a pkey that's been used already.\n record.assign_attributes(attributes)\n record.save\n end\n end\n\n # Here's the problem: STI models share a common table name, so even though\n # there are separate data dumps for each model, they really all go in\n # one table. The sequence number needs to be restarted for each *table*,\n # not each *model*.\n table_name = model_class.table_name\n\n if table_name == model_class.name.tableize.gsub(\"/\", \"_\") && model_class.any?\n\n # This model has its own table, so fix its sequence.\n sequence_name = \"#{ table_name }_id_seq\"\n next_seq_num = model_class.last.id + 1\n ActiveRecord::Base.connection.execute(\"ALTER SEQUENCE #{ sequence_name } RESTART WITH #{ next_seq_num };\")\n end\n\n puts \"done!\"\n end\n\n true\n end", "def initialize\n Dir.chdir(File.dirname(__FILE__))\n super('questions.db')\n self.type_translation = true\n self.results_as_hash = true\n end", "def initialize(config, *args)\n file_type = config[:file_type]\n @symmetric_key = config[:symmetric_key]\n @schemas = ::NmDatafile::SCHEMA[:schemas]\n set_file_type(file_type)\n \n load_data(args)\n \n setup_object_for_schema\n end" ]
[ "0.6305885", "0.6237008", "0.6169982", "0.6139616", "0.60817873", "0.60049087", "0.5991264", "0.5945808", "0.5920002", "0.5895195", "0.5876167", "0.5869841", "0.5865554", "0.5822463", "0.58046085", "0.5761357", "0.5747154", "0.5736692", "0.56692624", "0.564758", "0.5620761", "0.5616436", "0.55853766", "0.55660486", "0.5554637", "0.5548828", "0.55203426", "0.5491589", "0.54848206", "0.54589474" ]
0.66139275
0
Cause the CSVfile contains phrases we cannot be sure what is the most important word. This method strikes out everything between parenthesis, and if multiple words stay over, simply takes the longes one.
def extract_word( phrase ) w = phrase.gsub(/(\([^(]*\)|\{[^{]*\}|\[[^\[]*\])/, '').strip.downcase return nil if w.empty? # No empty strings # Now return the longest word, hoping that it's the most important, too ary = w.gsub(/[.,\-<>]/, ' ').strip.split do |i| i.strip! end ary.sort!{ |x,y| y.length <=> x.length } ary[0] # The longest element is the first end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_ambigious_words(file_name)\n File.open(file_name, 'w') do |f|\n sentences.each do |s|\n s.words.each do |w|\n tag_strings = w.get_correct_tags().collect { |t| t.clean_out_tag }\n f.puts w.string + \"\\t\" + tag_strings.sort.join(\"\\t\") if tag_strings.count > 1\n end\n end\n end\n\n nil\n end", "def wash_row(s)\n i = s.index(')')\n raise \"line in file phrases.ini does not contain )\" if i == nil\n return s.slice(i+1..-1).strip.upcase\n # slice vraci oznaceny substring\n # slice! vraci zbytek stringu\nend", "def _search_text\n [_concatenated_brand,\n _concatenated_description,\n _concatenated_sell_unit,\n classic_mbid\n ].compact.map { |w| w.hanize.split(' ') }.flatten.uniq.reject { |w| w.size < 3 || self.class.stop_words.include?(w) }.join(' ')\nend", "def catch_phrase\n [\n [\"ninja\",\"master\",\"student\"].rand, \n [\"\", \"\", \"\", \"\", \"\", \"\", \"weapons\", \"s' 3rd annual\",\"s' 5th annual\",\"s' 10th annual\", \"s' secret\"].rand,\n [\"gathering\",\"celebration\",\"meeting\",\"tournament\",\"competition\",\"party\",\"training camp\",\"sparring event\"].rand,\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"with Leonardo\", \"with Raphael\", \"with Michaelangelo\", \"with Donatello\"].rand\n ].join(' ').gsub(/ s\\'/,'s\\'').gsub(/\\s\\s/,' ').strip\n end", "def top_scoring_words\n @dictionary.each_with_object([]) do |cur_word, words_found|\n return words_found if words_found.length >= WORDS_TO_FIND\n\n words_found << cur_word if letters_present_for cur_word\n end\n end", "def save_ambigious_file(file_name)\n File.open(file_name, 'w') do |f|\n sentences.each do |s|\n s.words.each do |w|\n tag_strings = w.get_correct_tags().collect { |t| t.clean_out_tag }\n tag_strings = ['unkjent_ord'] if tag_strings.count == 0\n f.puts w.norm_string + \"\\t\" + tag_strings.sort.join(\"\\t\")\n end\n\n f.puts\n end\n end\n\n nil\n end", "def save_cleaned_cor_file(file_name)\n File.open(file_name, 'w') do |f|\n sentences.each do |s|\n s.words.each do |w|\n if w.ambigious? and w.clean_tag_ambiguity?\n w.remove_clean_tag_ambiguity\n elsif w.ambigious? and w.noun_gender_ambiguity?\n w.remove_noun_gender_ambiguity\n end\n f.puts '\"<' + w.string + '>\"'\n\n w.tags.each do |t|\n f.puts \"\\t\\\"#{t.lemma}\\\" #{t.string} \" + (t.correct ? \"\\t<Correct!>\" : \"\")\n end\n end\n end\n end\n\n nil\n end", "def preserve_best_sentences(data)\n puts \"For each word with multiple examples below, choose the best selection:\"\n\n total_words = data.count { |d| d[:sentences].size > 1 }\n curr_word = 0\n data.select { |d| d[:sentences].size > 1 }.map! do |d|\n curr_word += 1\n puts \"#{curr_word} of #{total_words}: #{d[:word]} (#{d[:pronounciation]})\"\n d[:sentences].each_with_index do |s, i|\n puts \"#{i + 1}.\\t#{s[0]}\"\n puts \"\\t#{s[1]}\"\n end\n n = get_selection_number(\"Best sentence: \", 1, d[:sentences].size)\n selection = d[:sentences][n - 1]\n d[:sentences] = [ [ selection[0], selection[1] ] ]\n d\n end\n\n puts \"\\nDone.\"\nend", "def most_com_word(text, min: 3)\n freq = word_freq(text).delete_if { |x, y| x.length} <= min}\nend", "def save_unmatched_words # :nodoc:\n tokens = phrase_without_matches.split(' ')\n unmatched_db = Corpus.new(\"unmatched-#{program_name}.db\")\n tokens.each do |token|\n if !complex_token_matches?(token) # token was not transformed earlier\n @to_match << token\n unmatched_db[token] = @processor.original_text\n end\n end\n unmatched_db.close\n end", "def remove_bad_words(report_model = nil)\n all_words = Word.all_words\n contain_bad_words = false\n res = self.gsub(/\\b\\w+\\b/) do |word|\n if all_words.include?(word.downcase)\n contain_bad_words = true\n '***'\n else\n word\n end\n end.squeeze(' ')\n Report.where(description: 'Contain bad words', target: report_model).first_or_create if contain_bad_words\n res\n end", "def cleanup_title(line)\n\t#deletes everything but the song title\n\tline.gsub!(/.+>/, '')\n\t#deletes superfluous text\n\tline.gsub!(/(\\(|\\[|\\{|\\\\|\\/|\\_|\\-|\\:|\\\"|\\`|\\+|\\=|\\*|feat\\.).+$/,'')\n\t\t#deletes punctuation\n\t\tline.gsub!(/(\\?|\\¿|\\!|\\¡|\\.|\\;|\\&|\\@|\\%|\\#|\\|)*/,'')\n\t\t#determines if a word uses english characters or not\n\t\tif line =~ /^[\\w\\s']+$/\n\t\t\tline = line.downcase\n\t\t\t#if not english, sets line to nil\n\t\telse\n\t\t\tline = nil\n\t\tend\n\t\treturn line\n\tend", "def supervising_checker(keywords, tline)\r\n lowestindex = tline.length\r\n counter = 0\r\n keywords.each do |word|\r\n counter += tline.scan(/(?=#{word})/).count\r\n if counter > 2\r\n lowestindex = 1\r\n end\r\n end\r\n return lowestindex\r\nend", "def remove_all_straits!\n patch_file!(\"map/adjacencies.csv\") do |file|\n # Haida-Tlingit\n file.b.lines.select{|x|\n t = x.split(\";\")[2]\n x =~ /Haida/ or (t != \"sea\" and t != \"lake\")\n }.join\n end\n end", "def most_significant\n most_sig = []\n # if !description.nil?\n # if tags.any?\n # most_sig = tags.select {|tag| self.description.downcase.include?(tag)}.collect {|tag| tag.singularize }\n # else\n # most_sig = word_frequency.keys.select {|tag| self.description.downcase.include?(tag)}.collect {|tag| tag.singularize }\n # end\n # end\n\n description.to_s.split.each do |word|\n self.word_frequency[word] ||= 0\n self.word_frequency[word] += 1\n end\n\n if most_sig.empty?\n most_sig = self.word_frequency.reject {|k,v| v < 3}.keys\n most_sig.flatten!\n end\n\n if description && tags.any?\n tags.each do |tag|\n if description.include?(tag)\n most_sig << tag.singularize\n end\n end\n end\n \n most_sig.uniq!\n\n self.validate_lang\n\n if SiteClassifier.translate_tags?\n begin\n if self.lang == \"auto\"\n @lang = EasyTranslate.detect(most_sig.first, key: SiteClassifier.configuration.google_translate_api_key)\n end\n EasyTranslate.translate(most_sig, from: self.lang, to: :en, key: SiteClassifier.configuration.google_translate_api_key)\n rescue\n return most_sig\n end\n else\n return most_sig\n end\n end", "def LongestWord(sen)\n str = sen.split(\" \")\n longest_word = str[0]\n str.each do |word|\n word.sub(/[\\w\\s]/, '')\n if longest_word.length < word.length\n longest_word = word\n end\n end\n longest_word\nend", "def top_3_words(text)\n text.gsub(\"\\n\", \" \")\n .split(\" \")\n .map(&:downcase)\n .map(&sanitize)\n .reject(&empty)\n .reject(&no_letters)\n .reduce({}, &top_word)\n .sort_by(&word_count)\n .reverse\n .take(3)\n .map(&:first)\nend", "def trim_post content\n line = ''\n counter = 1\n words = content.split(/ /)\n \n # we break before 272 leaving space for cw and break in case it's needed\n while not words.empty? and not too_long?(line)\n line += \" #{words.shift}\"\n end\n \n return line.strip, words.join(' ')\n end", "def top_3_words(text)\n count = Hash.new { 0 }\n text.scan(/\\w+'*\\w*/) { |word| count[word.downcase] += 1 }\n count.map{|k,v| [-v,k]}.sort.first(3).map(&:last)\nend", "def neutralize(sentence)\n words = sentence.split(' ')\n words.each_with_index do |word, index|\n p index\n p word\n p words\n words.delete(word) if negative?(word)\n p words\n end\n\n words.join(' ')\nend", "def clean_keywords(input)\n keywords = input.split(',').map! { |i| i.chomp.strip.downcase }.compact.uniq.keep_if { |i| i != '' }\n if keywords.empty?\n nil\n else\n keywords.join(', ')\n end\n end", "def parse\n parse_results = []\n @words.each_index do |i|\n i.upto(@words.size - 1) do |j|\n phrase = Phrase.new(@words[i..j])\n unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles)\n break unless @repository.try_this_phrase_or_longer?(phrase)\n matching_articles = @repository.find_matching_articles(phrase)\n matching_articles.each do |matching_article|\n parse_results << [phrase.to_s, matching_article]\n end\n end\n end\n end\n parse_results = clean_results(parse_results, @existing_article_titles)\n end", "def record_longer_phrase\n compiled_phrase = compile_phrase\n compiled_phrase_length = compiled_phrase.word_count\n @phrases[compiled_phrase_length] ||= Hash.new(0)\n\n # The first duplicate we find needs to record both occurrances\n # TODO: Clean this up. Absolute mother to read.\n new_occurrances = @phrases[compiled_phrase_length][compiled_phrase] > 0 ? 1 : 2\n @phrases[compiled_phrase_length][compiled_phrase] += new_occurrances\n end", "def most_common(text, too_short: 3)\n long_enough = each_word_count(text).delete_if{ |word, count| word.length <= too_short }\n\n long_enough.select do |word, count|\n count == long_enough.values.max\n end\nend", "def mcw(search)\n\t\tif !$bigrams.has_key?(search) # if the search word doesn't exist in the bigram...\n\t\t\tmost_common = nil # we're going to return nil.\n\n\t\telse most_common = $bigrams[search].max_by{|word, number| number}[0] # search for max by # of maxes\n\t\tend\n\n\t\treturn most_common\nend", "def wp_trim_words(text, num_words = 55, more = nil)\n if more.nil?\n more = '&hellip;'\n end\n\n original_text = text\n text = wp_strip_all_tags(text)\n\n if false # no asian...\n else\n words_array = text.split(/[\\n\\r\\t ]+/, num_words + 1)\n sep = ' '\n end\n\n if words_array.length > num_words\n words_array.pop\n text = words_array.join(sep)\n text = text + more\n else\n text = words_array.join(sep)\n end\n\n # Filters the text content after words have been trimmed.\n apply_filters('wp_trim_words', text, num_words, more, original_text)\n end", "def find_most_similar(term)\n\n match_scores = @words.map { |word|\n\n index = 0\n possibilities = [term.dup]\n\n while index < word.length\n new_possibilities = []\n possibilities.each { |poss|\n\n if word[index] == poss[index]\n new_possibilities.push(poss.dup)\n else\n # '!' stands for inserted character'\n # '?' stands for replaced character'\n char_inserted = poss.dup.insert(index, '!')\n char_replaced = poss.dup\n char_replaced[index] = '?'\n new_possibilities.push(char_inserted)\n new_possibilities.push(char_replaced)\n end\n\n }\n\n possibilities = new_possibilities\n index += 1\n\n end\n\n possibilities.map { |poss|\n\n poss.scan(/\\?/).count + poss.scan(/!/).count\n }.min\n }\n\n return @words[match_scores.index(match_scores.min)]\n\n end", "def process_phrase_for_word_count\n # remove punctuation\n @phrase.gsub!(/[^0-9a-z ,]/i, '')\n \n # remove list\n @phrase.gsub!(/[,]/, ' ')\n \n # lowercase everything\n @phrase.downcase!\n \n end", "def corrections\n #For each word to be looked at\n $words.each do |word_array|\n #If the word is misspelled attempt corrections\n possible_matches = Array.new\n if word_array[1] == false\n #Sets word to the actual word, instead of array pair\n word = word_array[0]\n # Get lexicon searching vars\n first_char = word[0]\n len = word.length\n\n ##Find words with similar letters\n #Saves the length of the word for eaiser access\n size = word.length\n #Iterates over words with matching starting letter and length +- 1\n $lexicon[first_char][len].each do |word_compare|\n possible_matches << word_compare[0]\n end\n\n # only check shorter words if length is greater than 1\n if len > 1\n $lexicon[first_char][len-1].each do |word_compare|\n possible_matches << word_compare[0]\n end\n end\n\n $lexicon[first_char][len+1].each do |word_compare|\n possible_matches << word_compare[0]\n end\n\n #Iterate over the possible matches, taking the match with the highest percentage\n #Hash to hold similarity\n similarity = Hash.new(0.0)\n possible_matches.each do |word_to_compare|\n similarity[word_to_compare] = match_percentage word, word_to_compare\n end\n\n best_match = ''\n similarity.each do |match|\n if match[1] > similarity[best_match]\n best_match = match[0]\n end\n end\n $correction[word] = best_match\n end\n end\nend", "def selective_tweet_shortener(tweet)\n tweet.length > 140 ? word_substituter(tweet) : tweet\nend" ]
[ "0.56514716", "0.5527386", "0.5458064", "0.54185283", "0.5280017", "0.5211028", "0.51405776", "0.5105221", "0.5092543", "0.5079871", "0.5069431", "0.5043012", "0.5033231", "0.5020461", "0.5016071", "0.49755785", "0.49654907", "0.49645582", "0.49581897", "0.49507964", "0.4931415", "0.49270886", "0.49270236", "0.48979014", "0.48937714", "0.4892473", "0.48896757", "0.48857364", "0.48561", "0.48530328" ]
0.5826419
0
Fulltext regexp lookup. Complexity: O(n)
def query_fulltext_regexp( query ) read_db do |dbm| dbm.each_value do |raw_val| val = RDictCcEntry.format_str(raw_val) match_line_found = false val.each_line do |line| if line =~ /^\s+/ if match_line_found puts line else # Skip lines starting with blanks, because these are already # translations and they don't belong to the matching line. next end else match_line_found = false end if line.downcase =~ /#{query}/ puts line match_line_found = true end end end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def match(regexp); end", "def match(keyword); end", "def make_regexp\n @intent = self.intent\n regexp = self.pattern.dup.downcase\n words = regexp.split(\" \")\n words.each do |word|\n if word.include? '/'\n regexp = regexp.gsub(word,\"(#{word})\")\n\n end\n\n end\n regexp = regexp.gsub('/',\"|\")\n regexp = regexp.gsub('^ ','.{0,60}').gsub(' ^','.{0,60}').gsub(' *','.{1,60}').gsub('* ','.{1,60}').gsub('^','.{1,60}').gsub(' [','.{0,60}[')\n regexp = regexp.gsub(' .{0,60}','.{0,60}')\n regexp = regexp.gsub(' .{1,60}','.{1,60}')\n regexp = '.{0,60}' + regexp + '.{0,60}'\n self.regexp = regexp\n chunks = self.pattern.split(' ')\n chunks.each do |ch|\n result= Regexp.new(/\\[.{0,12}\\]/) =~ ch\n if(result==0)\n set = WordSet.find_by_keyword(ch[1..-2])\n str = '(' + set.words.join('|') + ')'\n regexp = self.regexp.gsub(ch,str)\n self.regexp = regexp\n end\n end\n self.save\n end", "def word_pattern(pattern, input)\n \nend", "def matching_lines(regex); end", "def match_text text\n @lookups.each do |rx_curr|\n return true if text =~ rx_curr\n end\n false\n end", "def search_words\n begin\n regex = Regexp.new(@pattern)\n rescue RegexpError => msg\n error_msg(msg)\n rescue NameError => msg\n error_msg(msg)\n end\n @results = DICT.select do |word|\n regex =~ word\n end\n @num_results = @results.length\n format_results\n display_results\n end", "def pre_match() end", "def regexp; end", "def regexp; end", "def match(pattern); end", "def textmatch(text, terms)\n terms.all? { |term| text =~ /#{term}/i }\nend", "def match_query(query); end", "def find_reg_ex_matches( reg_ex )\n match_set = Set.new\n @words_set.to_a.each do |word|\n match_set.add word if word.downcase.match(reg_ex)\n end\n match_set\n end", "def re; end", "def match(tokens, definitions); end", "def regexps; end", "def submatcher; end", "def submatcher; end", "def find_terms(doc)\n terms_match = @terms.select { |term| doc.join('').match(term.to_s) }\n\n terms_match.map do |term, definition|\n \"*[#{term}]: #{definition}\".delete(\"\\t\\r\\n\").squeeze(' ').strip\n end\nend", "def fulltextsearch(query, text, words=2)\n result = \"\"\n if text =~ /.*#{query}.*/i\n text_words = text.scan(/\\w*/)\n indexes = []\n text_words.each_with_index do |word,index|\n if word =~ /.*#{query}.*/i\n i = []\n i << index - words unless words == 0 || index - words < 0\n i << index\n i << index + words unless words == 0 || index + words > text_words.length\n indexes << i\n end\n end\n indexes.each do |i|\n result += \"... \" unless i.length == 1\n i.each {|j| result += \"#{text_words[j]} \"}\n result += \" ...\" unless i.length == 1\n end\n end\n result\n end", "def test_a_regexp_can_search_a_string_for_matching_content\n assert_equal 'match', \"some matching content\"[/match/]\n end", "def article_match? (query, article_title)\n found = false\n return true if query.empty?\n temp_article = article_title.downcase\n query.each do |kw|\n pattern = Regexp.new /.*#{kw.downcase}.*/\n found = true if temp_article =~ pattern\n end\n found\nend", "def match(p0) end", "def match(p0) end", "def match(text)\n if match = @regexp.match(text)\n @matched_text = match.to_s\n [match.to_s, @name]\n else\n nil\n end\n end", "def regex_search\n if use_regex?\n ::Arel::Nodes::Regexp.new((custom_field? ? field : table[field]), ::Arel::Nodes.build_quoted(formated_value))\n else\n non_regex_search\n end\n end", "def on_match_pattern(node); end", "def on_match_pattern_p(node); end", "def regexp\n @regexp ||= Regexp.compile(source.to_s, Regexp::IGNORECASE)\n end" ]
[ "0.68299747", "0.6342473", "0.62648624", "0.61767787", "0.617327", "0.61730075", "0.61099666", "0.60797215", "0.6057485", "0.6057485", "0.60552454", "0.60254884", "0.600918", "0.5985297", "0.5951371", "0.59369147", "0.59265125", "0.59112245", "0.59112245", "0.58205426", "0.57938796", "0.57896733", "0.57679397", "0.5747721", "0.5747721", "0.5746925", "0.5738865", "0.5727701", "0.57168674", "0.57045126" ]
0.68641853
0
Public: Setup callback on headers parsing complete block Block the block of code Examples headers = HttpProxy::HeadersParser.new headers.process do |parsing_result| p parsing_result["UserAgent"] end Returns nothing
def process(&block) @parser.on_headers_complete = block end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parser_init\n @http = Http::Parser.new\n @http.on_headers_complete = proc do\n p @http.headers\n end\n @http.on_body = proc do |chunk|\n # One chunk of the body\n p chunk\n end\n\n @http.on_message_complete = proc do |env|\n # Headers and body is all parsed\n puts \"Done!\"\n end\n\n\n end", "def parse(headers, &block)\n @headers = headers\n parse_headers!(block)\n end", "def parse_headers!(block)\n headers.each { |header| block.call(header.key, parse_value(header.value)) }\n end", "def processed_headers; end", "def parse_header_contents; end", "def handle_headers_complete(headers)\n @code = @parser.status_code.to_i\n if @code != 200\n receive_error(\"invalid status code: #{@code}.\")\n end\n self.headers = headers\n @state = :stream\n end", "def cgi_parse_header(line); end", "def headers=(_arg0); end", "def headers=(_arg0); end", "def headers=(_arg0); end", "def headers=(_arg0); end", "def on_headers_complete(headers)\n @headers = headers\n end", "def fill_header(response); end", "def headers(headers); end", "def on_header_init()\n end", "def read_headers!; end", "def parseHeaders(request) \n headers = {};\n\n # Loop through headers\n request.lines[1..-1].each do |line|\n # If we are moving to the next line, return what we currently have\n return headers if line == \"\\r\\n\"\n\n # Structure data\n header, value = line.split\n header = header.gsub(\":\", \"\").downcase.to_sym\n headers[header] = value\n end\nend", "def on_headers(headers)\n log.info { \">> headers (#{headers.size})\" }\n headers.each {|h| @node.queue.push([:block, h])}\n end", "def header_write_callback\n @header_write_callback ||= proc {|stream, size, num, object|\n @response_headers << stream.read_string(size * num)\n size * num\n }\n end", "def parse_headers\n headers = {}\n @request.lines[1..-1].each do |line|\n # puts line.inspect\n # puts line.split.inspect\n return headers if line == \"\\r\\n\" # Because HTTP header's last line will be /r/n we return bc we're done\n header, value = line.split\n header = normalize(header)\n headers[header] = value\n end\n \n return headers\n end", "def install_header_callback( request, wrapped_response )\n original_callback = request.on_header\n request._ty_original_on_header = original_callback\n request._ty_header_str = ''\n request.on_header do |header_data|\n wrapped_response.append_header_data( header_data )\n\n if original_callback\n original_callback.call( header_data )\n else\n header_data.length\n end\n end\n end", "def request_headers=(_arg0); end", "def parse_headers(raw_headers)\n # raw headers from net_http have an array for each result. Flatten them out.\n raw_headers.inject({}) do |remainder, (k, v)|\n remainder[k] = [v].flatten.first\n remainder\n end\n end", "def read_headers!\n until @parser.headers?\n result = read_more(BUFFER_SIZE)\n raise ConnectionError, \"couldn't read response headers\" if result == :eof\n end\n\n set_keep_alive\n end", "def make_headers(user_headers); end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def headers; end" ]
[ "0.7018227", "0.69397557", "0.692272", "0.66465926", "0.65960246", "0.6448536", "0.61827725", "0.61497754", "0.61497754", "0.61497754", "0.61497754", "0.60907024", "0.59932834", "0.596692", "0.59114987", "0.5881159", "0.58745456", "0.58024544", "0.5777607", "0.5706517", "0.56920505", "0.5690344", "0.5689659", "0.566579", "0.56650954", "0.5608585", "0.5608585", "0.5608585", "0.5608585", "0.5608585" ]
0.83165455
0
Move the cursor to specified row. The main window and the headers will be updated reflecting the displayed files and directories. The row number can be out of range of the current page.
def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 end item = items[current_row] main.draw_item item, current: true main.display current_page header_l.draw_current_file_info item @current_row end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def goto_row(row)\n \n set RGhost::Cursor.goto_row(row) \n end", "def jump_rows(row)\n @rows+=row\n set RGhost::Cursor.jump_rows(row)\n end", "def select_row(row_number = 0)\n set_cursor(Gtk::TreePath.new(row_number), nil, false)\n end", "def update_head_vertical_location(row)\n locate_head[0] = row\n end", "def next_row\n @rows+=1\n set RGhost::Cursor.next_row\n end", "def move_to position\n orig = @cursor\n place_cursor(CLEAR) if @highlight_row_flag\n @cursor = position\n @cursor = [@cursor, @view.size - 1].min\n @cursor = [@cursor, 0].max\n\n # try to stop it from landing on separator\n if current_file == SEPARATOR\n @cursor += 1 if @cursor_movement == :down\n @cursor -= 1 if @cursor_movement == :up\n # 2019-06-01 - remove return in case scrolling happens here\n # return\n end\n\n # 2019-03-18 - adding sta\n # @sta = position - only when page flips and file not visible\n # FIXME not correct, it must stop at end or correctly cycle\n # sta goes to 0 but cursor remains at 70\n # viewport.size may be wrong here, maybe should be pagesize only\n oldsta = @sta\n if @cursor - @sta >= @pagesize\n @sta += @pagesize\n # elsif @sta - @cursor >= @vps\n end\n if @sta > @cursor\n @sta -= @pagesize\n # @sta = @cursor\n end\n\n @cursor_movement = nil if oldsta != @sta # we need to redraw\n\n # -------- return here --- only visual mode continues ---------------------#\n return unless @visual_mode\n\n star = [orig, @cursor].min\n fin = [orig, @cursor].max\n @cursor_movement = nil # visual mode needs to redraw page\n\n # PWD has to be there in selction\n # FIXME with visited_files\n if selected? File.join(@current_dir, current_file)\n # this depends on the direction\n # @selected_files = @selected_files - @view[star..fin]\n remove_from_selection @view[star..fin]\n ## current row remains in selection always.\n add_to_selection current_file\n else\n # @selected_files.concat @view[star..fin]\n add_to_selection @view[star..fin]\n end\n message \"#{@selected_files.count} files selected. \"\nend", "def move_to(row = nil, column = nil)\n return CSI + 'H' if row.nil? && column.nil?\n CSI + \"#{column + 1};#{row + 1}H\"\n end", "def set_cursor_position(row, col)\n\t\tinvalid_rows = [@cursor_row, row]\n\t\t@cursor_row, @cursor_col = row, col\n\t\tif @cursor_row < first_line_in_view\n\t\t\tset_contents_pos(0, line_num_to_coord(@cursor_row))\n\t\t\temit_changed(nil)\n\t\telsif @cursor_row > last_line_in_view\n\t\t\tset_contents_pos(0, line_num_to_coord(@cursor_row - num_lines_in_view))\n\t\t\temit_changed(nil)\n\t\tend\n\tend", "def goto_next_selection\n return if selected_rows().length == 0 \n row = selected_rows().sort.find { |i| i > @obj.current_index }\n row ||= @obj.current_index\n #@obj.current_index = row\n @obj.goto_line row\n end", "def customize_row_index(row_index)\n row_index += 1\n end", "def go_to_next_row()\n turn_left()\n move()\n turn_left()\n end", "def next_row\n @current_row += 1\n end", "def current_row\n @row_offset\n end", "def update_head_horizontal_location(column)\n locate_head[1] = column\n end", "def row_seek(n)\n @result.row_seek(n)\n end", "def move_to(row, col)\n @row, @col = wrap(row, col)\n end", "def row_seek(n)\n ret = @index\n @index = n\n ret\n end", "def cursor_to( row, col, do_display = DONT_DISPLAY, stopped_typing = STOPPED_TYPING, adjust_row = ADJUST_ROW )\n old_last_row = @last_row\n old_last_col = @last_col\n\n row = row.fit( 0, @lines.length - 1 )\n\n if col < 0\n if adjust_row\n if row > 0\n row = row - 1\n col = @lines[ row ].length\n else\n col = 0\n end\n else\n col = 0\n end\n elsif col > @lines[ row ].length\n if adjust_row\n if row < @lines.length - 1\n row = row + 1\n col = 0\n else\n col = @lines[ row ].length\n end\n else\n col = @lines[ row ].length\n end\n end\n\n if adjust_row\n @desired_column = col\n else\n goto_col = [ @desired_column, @lines[ row ].length ].min\n if col < goto_col\n col = goto_col\n end\n end\n\n new_col = tab_expanded_column( col, row )\n view_changed = show_character( row, new_col )\n @last_screen_y = row - @top_line\n @last_screen_x = new_col - @left_column\n\n @typing = false if stopped_typing\n @last_row = row\n @last_col = col\n @last_screen_col = new_col\n changed = ( @last_row != old_last_row or @last_col != old_last_col )\n if changed\n record_mark_start_and_end\n\n removed = false\n if not @changing_selection and selecting?\n remove_selection( DONT_DISPLAY )\n removed = true\n end\n if removed or ( do_display and ( selecting? or view_changed ) )\n display\n else\n @diakonos.display_mutex.synchronize do\n @win_main.setpos( @last_screen_y, @last_screen_x )\n end\n end\n @diakonos.update_status_line\n @diakonos.update_context_line\n\n @diakonos.remember_buffer self\n end\n\n changed\n end", "def move row, col\n @row = row\n @col = col\n end", "def goto_prev_selection\n return if selected_rows().length == 0 \n row = selected_rows().sort{|a,b| b <=> a}.find { |i| i < @obj.current_index }\n row ||= @obj.current_index\n #@obj.current_index = row\n @obj.goto_line row\n end", "def ensure_visible row = @current_index\n unless is_visible? row\n @prow = row\n end\n end", "def ensure_visible row = @current_index\n unless is_visible? row\n @prow = @current_index\n end\n end", "def current_row\n @current_row ||= 1\n end", "def row=(row)\n @row = Utility.clamp(row, 0, GRID_ROWS - 1)\n end", "def scroll_forward\n #@oldindex = @current_index\n @current_index += @scrollatrows\n @prow = @current_index - @scrollatrows\n end", "def select_next!\n pane.next_row!\n end", "def row_position=(position)\n @row_position = position \n end", "def restore_cursor_position() set_cursor_position(@event[\"line\"], @event[\"column\"]) end", "def show_focus_on_row row0, _prow, tf=true\n # color = tf ? $reversecolor : $datacolor\n # if cursor on row, reverse else normal\n attr = tf ? Ncurses::A_REVERSE : Ncurses::A_NORMAL\n color = @color_pair\n r = row0+1 \n #check if row is selected or not\n row_att = @list_attribs[_prow] unless @list_attribs.nil?\n if !row_att.nil?\n status = row_att.fetch(:status, \" \")\n attr1 = row_att[:bgcolor] \n color = attr1 unless attr1.nil?\n end\n @datawidth ||= @width-2\n return if r > get_content().length\n @form.window.mvchgat(y=r+@row, x=1+@col, max=@datawidth, attr, color, nil)\n end", "def scroll_forward\n @oldindex = @current_index\n @current_index += @scrollatrows\n @prow = @current_index - @scrollatrows\n end" ]
[ "0.72010726", "0.68817645", "0.6806795", "0.64135754", "0.64131194", "0.6307145", "0.6255472", "0.6245421", "0.62252295", "0.61407685", "0.60533386", "0.6020533", "0.59794873", "0.5968704", "0.5912319", "0.5890729", "0.5836306", "0.583052", "0.5828907", "0.58208406", "0.58069265", "0.58032185", "0.57952654", "0.5723768", "0.5699866", "0.56943804", "0.56731546", "0.5649522", "0.5644759", "0.5612328" ]
0.84249705
0
Sort the whole files and directories in the current directory, then refresh the screen. ==== Parameters +direction+ Sort order in a String. nil : order by name r : reverse order by name s, S : order by file size sr, Sr: reverse order by file size t : order by mtime tr : reverse order by mtime c : order by ctime cr : reverse order by ctime u : order by atime ur : reverse order by atime e : order by extname er : reverse order by extname
def sort(direction = nil) @direction, @current_page = direction, 0 sort_items_according_to_current_direction switch_page 0 move_cursor 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sort_items_according_to_current_direction\n case @direction\n when nil\n @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort)\n when 'r'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse}\n when 'S', 's'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}}\n when 'Sr', 'sr'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)}\n when 't'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}}\n when 'tr'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)}\n when 'c'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}}\n when 'cr'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)}\n when 'u'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}}\n when 'ur'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)}\n when 'e'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}}\n when 'er'\n @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)}\n end\n items.each.with_index {|item, index| item.index = index}\n end", "def sort_files!; end", "def order\n \"#{sort} #{dir}\"\n end", "def swap_sort_direction(direction = @paginable_params[:sort_direction])\n direction_upcased = upcasing_sort_direction(direction)\n return 'DESC' if direction_upcased == 'ASC'\n return 'ASC' if direction_upcased == 'DESC'\n end", "def sort_direction\n params[:dir] == \"asc\" ? \"asc\" : \"desc\"\n end", "def sort_direction(direction)\n %w[asc desc].include?(direction) ? direction : 'asc'\n end", "def sort!\n #N Without this, the immediate sub-directories won't get sorted\n dirs.sort_by! {|dir| dir.name}\n #N Without this, files contained immediately in this directory won't get sorted\n files.sort_by! {|file| file.name}\n #N Without this, files and directories contained within sub-directories of this directory won't get sorted\n for dir in dirs\n #N Without this, this sub-directory won't have its contents sorted\n dir.sort!\n end\n end", "def sort_direction\n %w[asc, desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def list_files dir='*', sorto=@sorto, hidden=@hidden, _filter=@filterstr\n dir += '/*' if File.directory?(dir)\n dir = dir.gsub('//', '/')\n\n # decide sort method based on second character\n # first char is o or O (reverse)\n # second char is macLn etc (as in zsh glob)\n so = sorto ? sorto[1] : nil\n func = case so\n when 'm'\n :mtime\n when 'a'\n :atime\n when 'c'\n :ctime\n when 'L'\n :size\n when 'n'\n :path\n when 'x'\n :extname\n end\n\n # sort by time and then reverse so latest first.\n sorted_files = if hidden == 'D'\n Dir.glob(dir, File::FNM_DOTMATCH) - %w[. ..]\n else\n Dir.glob(dir)\n end\n\n # WARN: crashes on a deadlink since no mtime\n if func\n sorted_files = sorted_files.sort_by do |f|\n if File.exist? f\n File.send(func, f)\n else\n sys_stat(func, f)\n end\n end\n end\n\n sorted_files.sort! { |w1, w2| w1.casecmp(w2) } if func == :path && @ignore_case\n\n # zsh gives mtime sort with latest first, ruby gives latest last\n sorted_files.reverse! if sorto && sorto[0] == 'O'\n\n # add slash to directories\n sorted_files = add_slash sorted_files\n # return sorted_files\n @files = sorted_files\n calculate_bookmarks_for_dir # we don't want to override those set by others\nend", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : 'asc'\n end", "def files_search_results(search_result, direction)\n files, files_in_folders = search_result.compact.partition { |v| v[:file_path] == \"/\" }\n\n folders_result = files_map(files_in_folders)\n sorted_folders = []\n folders_result.\n group_by { |k| [k[:path]] }.\n sort_by { |k, _| k[0].downcase }.\n each { |_, v| sorted_folders << v }\n sorted_folders.flatten!\n\n files_result = files_map(files)\n sorted_files = files_result.sort_by { |k| k[:title].downcase }\n\n if direction == \"desc\"\n sorted_folders = sorted_folders.reverse\n sorted_files = sorted_files.reverse\n end\n sorted_folders + sorted_files\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end" ]
[ "0.6753547", "0.62339425", "0.6180216", "0.605791", "0.5885136", "0.57776505", "0.5731589", "0.57272637", "0.5712036", "0.5698475", "0.5698475", "0.5698475", "0.5698475", "0.5698475", "0.56878465", "0.56710196", "0.56634325", "0.56546617", "0.56546617", "0.5644094", "0.5644094", "0.5644094", "0.5644094", "0.5644094", "0.5644094", "0.5644094", "0.5643172", "0.5604612", "0.5604612", "0.5604612" ]
0.7013775
0
Change the file permission of the selected files and directories. ==== Parameters +mode+ Unix chmod string (e.g. +w, gr, 755, 0644)
def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def chmod(mode) File.chmod(mode, path) end", "def chmod(mode, options={})\n #list = list.to_a\n fileutils.chmod(mode, list, options)\n end", "def chmod(file, mode)\n if File.stat(file).mode != mode\n FileUtils.chmod(mode, file, :verbose => verbose?) \n end\n end", "def chmod(mode, path)\n exec! \"chmod #{mode.to_s(8)} #{escape(expand_path(path))}\"\n end", "def set_mode\n if (mode = target_mode) && (mode != (stat.mode & 007777))\n File.chmod(target_mode, file)\n Chef::Log.info(\"#{log_string} mode changed to #{mode.to_s(8)}\")\n modified\n end\n end", "def chmod(path, mode, *args, **opts)\n TTY::File.chmod(path, mode, *args, **opts)\n end", "def chmod(mode, list, noop: nil, verbose: nil)\n list = fu_list(list)\n fu_output_message sprintf('chmod %s %s', mode_to_s(mode), list.join(' ')) if verbose\n return if noop\n list.each do |path|\n Entry_.new(path).chmod(fu_mode(mode, path))\n end\n end", "def chmod(path, mode = 0700)\n if session.platform == 'windows'\n raise \"`chmod' method does not support Windows systems\"\n end\n\n if session.type == 'meterpreter' && session.commands.include?(Rex::Post::Meterpreter::Extensions::Stdapi::COMMAND_ID_STDAPI_FS_CHMOD)\n session.fs.file.chmod(path, mode)\n else\n cmd_exec(\"chmod #{mode.to_s(8)} '#{path}'\")\n end\n end", "def chmod(mode, list, options = {})\r\n fu_check_options options, :noop, :verbose\r\n list = fu_list(list)\r\n fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose]\r\n return if options[:noop]\r\n File.chmod mode, *list\r\n end", "def chmod( mode ) File.chmod( mode, expand_tilde ) end", "def chmod ctx, path, mode\n\n end", "def set_mode\n chmod = command? 'chmod'\n find = command? 'find'\n\n return unless chmod && find\n\n {fmode: 'f', dmode: 'd'}.each do |k, v|\n next if send(k).nil?\n cmd = [find, destination_path, '-type', v, '-exec']\n cmd.concat [chmod, send(k).to_s(8), '{}', '+']\n logger.debug { \"Running command: #{cmd.join ' '}\" }\n system(*cmd)\n end\n end", "def change_mode!\n chmod_params = [Integer(\"0\" + self.target_mode), self.target]\n\n if(File.symlink?(self.target) && (self.no_follow == 'both' || self.no_follow == 'chmod'))\n File.lchmod *chmod_params\n elsif(self.stat(:ftype) == 'directory' && (self.recursive == 'both' || self.recursive == 'chmod'))\n FileUtils.chmod_R *chmod_params\n else\n File.chmod *chmod_params\n end\n rescue NotImplementedError => ex\n WarningShot::PermissionResolver.logger.error(\"lchmod is not implemented on this machine, (disable nofollow).\")\n return false\n rescue Exception => ex\n WarningShot::PermissionResolver.logger.error(\"Unable to change mode for file: #{self.target}; Exception: #{ex.message}\")\n return false\n end", "def chmod(path, mode, config = {})\n return unless behavior == :invoke\n path = File.expand_path(path, destination_root)\n say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true)\n FileUtils.chmod_R(mode, path) unless options[:pretend]\n end", "def chmod(mode, args, options)\n FileUtils.chmod_R(mode, args, **options)\n end", "def chmod_r(mode)\n util.chmod_r(mode, path)\n end", "def chmod_r(mode, options={})\n #list = list.to_a\n fileutils.chmod_r(mode, list, options)\n end", "def action_chmod\n if @omode == nil\n Chef::Log::fatal \"target mode need to be provided to perform chmod\"\n elsif (!dir_exists?(@path))\n Chef::Log::Error(\"Directory #{ @path } doesn't exist; chmod action not taken\")\n else\n converge_by(\"chmod #{ @new_resource }\") do\n @client.chmod(@path, @mode)\n end\n new_resource.updated_by_last_action(true)\n end\n end", "def mode=(value)\n File.chmod(Integer(\"0\" + value), @resource[:name])\n end", "def chmod_r(mode, path)\n exec! \"chmod -R #{mode.to_s(8)} #{escape(expand_path(path))}\"\n end", "def chmod(path, mode, options = {})\n paths = glob(path, options).reject{|f| f.include?(\".git\")} # We can probably generalize this later\n changed = false\n\n paths.each do |f|\n old_mode = File.stat(f).mode & 07777\n unless old_mode == mode\n puts \"Changing mode of #{f} from #{old_mode.to_s(8)} to #{mode.to_s(8)}\"\n FileUtils.chmod(mode, f)\n changed = true\n end\n end\n\n @changed ||= changed\n changed\n end", "def mode=(value)\n File.chmod(Integer(\"0#{value}\"), @resource[:name])\n end", "def chmod(path, mode = nil, &block)\n add Config::Patterns::Chmod do |p|\n p.path = path\n p.mode = mode if mode\n yield p if block_given?\n end\n end", "def chmod(file)\n mode = options[:mode]\n return unless mode\n\n FileUtils.chmod(mode, file)\n end", "def set_modes(dir)\n Dir.glob(\"#{dir}/**/*\", File::FNM_DOTMATCH).each do |path|\n next if File.basename(path) == '.'\n\n if File.directory? path\n File.chmod(0755, path)\n else\n File.chmod(0644, path)\n end\n end\nend", "def chmod(mode, target)\n eval(CHMOD, binding, __FILE__, CHMOD_LINE)\n nil\nend", "def set_access_mode(mode = :r)\n modes = [:r, :w, :rw, :x]\n raise ArgumentError, \"Mode must be one of #{modes}\" unless modes.include? mode\n case mode\n when :r\n self.access_mode = 0\n when :w\n self.access_mode = 1\n when :rw\n self.access_mode = 2\n when :x\n self.access_mode = 3\n end\n end", "def chmod(acl)\n if(acl == 777)\n mode = \"777\"\n end\n end", "def chmod mod, path\n add \"chmod #{mod} #{path}\", check_perms(mod, path)\n end", "def set_perms_on_remote(host, path, mode, opts = {})\n opts[:owner] ||= on(host, puppet('config print user')).stdout.rstrip\n opts[:group] ||= on(host, puppet('config print group')).stdout.rstrip\n\n on(host, \"chmod -R #{mode} #{path}\")\n on(host, \"chown -R #{opts[:owner]}:#{opts[:group]} #{path}\")\n end" ]
[ "0.7961633", "0.79208547", "0.79111606", "0.7789717", "0.7640511", "0.76338196", "0.7572123", "0.75515854", "0.7550537", "0.7530089", "0.751246", "0.7440374", "0.7425923", "0.7330557", "0.72711575", "0.724482", "0.7224371", "0.72054064", "0.72024363", "0.7167651", "0.7126878", "0.7115463", "0.6974075", "0.6969252", "0.69196725", "0.69186026", "0.6897974", "0.6880145", "0.66826284", "0.6607638" ]
0.7932743
1
Change the file owner of the selected files and directories. ==== Parameters +user_and_group+ user name and group name separated by : (e.g. alice, nobody:nobody, :admin)
def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def change_owner(username, group, path)\n %x(sudo chown -R #{Shellwords.escape(username)}:#{Shellwords.escape(group)} #{path})\n\n $?.success?\n end", "def set_owner\n user = @conf['user'] || Process.uid\n group = @conf['group'] || Process.gid\n\n begin\n FileUtils.chown_R(user, group, @location)\n rescue StandardError => err\n Pemlogger.logit(err, :fatal)\n raise(err)\n end\n end", "def set_owner\n return unless owner || group\n chown = command? 'chown'\n\n return unless chown\n\n cmd = [chown, '-R', \"#{owner}:#{group}\", destination_path]\n logger.debug { \"Running command: #{cmd.join ' '}\" }\n system(*cmd)\n end", "def chown( owner, group ) File.chown( owner, group, expand_tilde ) end", "def chown(owner, group) File.chown(owner, group, path) end", "def chown(user, group, options={})\n #list = list.to_a\n fileutils.chown(user, group, list, options)\n end", "def change_user!\n tgt_uid = self.target_user.is_a?(Fixnum) ? self.target_user : Etc.getpwnam(self.target_user).uid\n chown_params = [tgt_uid, nil, self.target]\n\n if(File.symlink?(self.target) && (self.no_follow == 'both' || self.no_follow == 'chown'))\n File.lchown *chown_params\n elsif(self.stat(:ftype) == 'directory' && (self.recursive == 'both' || self.recursive == 'chown'))\n #DOcumenation for FileUtils.chown_R is wrong (at least for Ubuntu 8.1, takes ID as String.)\n chown_params[1] = chown_params[1].to_s\n FileUtils.chown_R *chown_params\n else\n File.chown *chown_params\n end\n rescue NotImplementedError => ex\n WarningShot::PermissionResolver.logger.error(\"lchown is not implemented on this machine, (disable nofollow).\")\n return false\n rescue Exception => ex\n WarningShot::PermissionResolver.logger.error(\"Unable to change user for file: #{self.target}; Exception: #{ex.message}\")\n return false\n end", "def chown(file, user)\n user = user.to_s\n # who is the current owner?\n @uids ||= {}\n @uids[user] ||= Etc.getpwnam(user).uid\n uid = @uids[user]\n if File.stat(file).uid != uid\n run \"chown #{user}:#{user} '#{file}'\" \n end\n end", "def chown(path, owner, options = {})\n paths = glob(path, options)\n owner = Etc.getpwnam(owner)\n changed = false\n\n paths.each do |f|\n stat = File.stat(f)\n unless stat.uid == owner.uid && stat.gid == owner.gid\n old_owner = \"#{Etc.getpwuid(stat.uid).name}:#{Etc.getgrgid(stat.gid).name}\"\n puts \"Changing owner of #{f} from #{old_owner} to #{owner.name}:#{owner.name}\"\n File.chown(owner.uid, owner.gid, f)\n changed = true\n end\n end\n\n @changed ||= changed\n changed\n end", "def chown(owner, group, *files)\n token = FFI::MemoryPointer.new(:ulong)\n\n begin\n bool = OpenProcessToken(\n GetCurrentProcess(),\n TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,\n token\n )\n\n raise SystemCallError.new(\"OpenProcessToken\", FFI.errno) unless bool\n\n token_handle = token.read_ulong\n\n privs = [\n SE_SECURITY_NAME,\n SE_TAKE_OWNERSHIP_NAME,\n SE_BACKUP_NAME,\n SE_RESTORE_NAME,\n SE_CHANGE_NOTIFY_NAME\n ]\n\n privs.each{ |name|\n luid = LUID.new\n\n unless LookupPrivilegeValueA(nil, name, luid)\n raise SystemCallError.new(\"LookupPrivilegeValue\", FFI.errno)\n end\n\n tp = TOKEN_PRIVILEGES.new\n tp[:PrivilegeCount] = 1\n tp[:Privileges][0][:Luid] = luid\n tp[:Privileges][0][:Attributes] = SE_PRIVILEGE_ENABLED\n\n unless AdjustTokenPrivileges(token_handle, 0, tp, 0, nil, nil)\n raise SystemCallError.new(\"AdjustTokenPrivileges\", FFI.errno)\n end\n }\n\n sid = FFI::MemoryPointer.new(:uchar)\n sid_size = FFI::MemoryPointer.new(:ulong)\n dom = FFI::MemoryPointer.new(:uchar)\n dom_size = FFI::MemoryPointer.new(:ulong)\n use = FFI::MemoryPointer.new(:ulong)\n\n wowner = owner.wincode\n\n # First run, get needed sizes\n LookupAccountNameW(nil, wowner, sid, sid_size, dom, dom_size, use)\n\n sid = FFI::MemoryPointer.new(:uchar, sid_size.read_ulong * 2)\n dom = FFI::MemoryPointer.new(:uchar, dom_size.read_ulong * 2)\n\n # Second run with required sizes\n unless LookupAccountNameW(nil, wowner, sid, sid_size, dom, dom_size, use)\n raise SystemCallError.new(\"LookupAccountName\", FFI.errno)\n end\n\n files.each{ |file|\n wfile = string_check(file).wincode\n\n size = FFI::MemoryPointer.new(:ulong)\n sec = FFI::MemoryPointer.new(:ulong)\n\n # First pass, get the size needed\n GetFileSecurityW(wfile, OWNER_SECURITY_INFORMATION, sec, sec.size, size)\n\n security = FFI::MemoryPointer.new(size.read_ulong)\n\n # Second pass, this time with the appropriately sized security pointer\n bool = GetFileSecurityW(\n wfile,\n OWNER_SECURITY_INFORMATION,\n security,\n security.size,\n size\n )\n\n raise SystemCallError.new(\"GetFileSecurity\", FFI.errno) unless bool\n\n unless InitializeSecurityDescriptor(security, SECURITY_DESCRIPTOR_REVISION)\n raise SystemCallError.new(\"InitializeSecurityDescriptor\", FFI.errno)\n end\n\n unless SetSecurityDescriptorOwner(security, sid, 0)\n raise SystemCallError.new(\"SetSecurityDescriptorOwner\", FFI.errno)\n end\n\n unless SetFileSecurityW(wfile, OWNER_SECURITY_INFORMATION, security)\n raise SystemCallError.new(\"SetFileSecurity\", FFI.errno)\n end\n }\n ensure\n CloseHandle(token.read_ulong)\n end\n\n files.size\n end", "def chown(user, group, list, noop: nil, verbose: nil)\n list = fu_list(list)\n fu_output_message sprintf('chown %s %s',\n (group ? \"#{user}:#{group}\" : user || ':'),\n list.join(' ')) if verbose\n return if noop\n uid = fu_get_uid(user)\n gid = fu_get_gid(group)\n list.each do |path|\n Entry_.new(path).chown uid, gid\n end\n end", "def action_chown\n if @tuser == nil\n Chef::Log::fatal \"target user need to be provided to perform chown\"\n elsif (!dir_exists?(@path))\n Chef::Log::Error(\"Directory #{ @path } doesn't exist; chown action not taken\")\n else\n if @tgroup == nil\n @tgroup = @meta_data[\"group\"]\n end\n converge_by(\"chown #{ @new_resource }\") do\n @client.chown(@path, 'owner' => @tuser, 'group' => @tgroup)\n end\n new_resource.updated_by_last_action(true)\n end\n end", "def owner=(new_owner)\n if @owner != new_owner\n @dacl.reassign!(@owner, new_owner)\n @owner = new_owner\n end\n end", "def chown_r(user, group, options={})\n #list = list.to_a\n fileutils.chown_r(user, group, list, options)\n end", "def chown(path, owner = nil, group = nil, &block)\n add Config::Patterns::Chown do |p|\n p.path = path\n p.owner = owner if owner\n p.group = group if group\n yield p if block_given?\n end\n end", "def chown(file)\n user = options[:user]\n group = options[:group]\n return unless user || group\n\n FileUtils.chown(user, group, file)\n end", "def chown(path, owner); raise NotImplementedError; end", "def chown user, path, options = {}\n recursive = '-R ' if options[:recursive]\n add \"chown #{recursive}#{user}:#{user} #{path}\", check_owner(user, path)\n end", "def chown_run_user( *args )\n flags, paths = args.partition { |a| a =~ /^-/ }\n sudo( [ 'chown', flags,\n [ run_user, run_group || run_user ].join(':'),\n paths ].flatten.compact.join( ' ' ) )\n end", "def owner=(owner)\n debug \"#{self.artifactid}: Changing owner to '#{self.artifactOwner}'.\"\n begin\n File.chown(Etc.getpwnam(self.owner).uid,nil,self.artifact)\n rescue => detail\n raise Puppet::Error, \"Failed to set owner to '#{self.owner}': #{detail}\"\n end\n end", "def user= user\n unless user.class == Modeles::User\n username = user.to_s\n user = Modeles::User.find_by_name username\n unless user\n @errors << \"User #{username} doesn't exists\"\n return false\n end\n end\n @fileInTable.user = user\n @fileInTable.path = user.name + '/'\n @fileInTable.path += @group + '/' + @path\n @user = user.name\n @path = @user + '/' + @group + '/' + @path\n save\n end", "def setUserFileAccess(adminSettingPerms, userName, filePath, grantAccess)\n\n #filePath = GlobalSettings.changeFilePathToMatchSystem(filePath)\n fAccess = filePath.concat \".access\"\n access = Hash.new {}\n if !File.exist?(fAccess)\n if grantAccess\n access[\"users\"] = \";#{userName};\"\n else\n access[\"users\"] = \"\"\n end\n access[\"groups\"] = \"\"\n if(adminSettingPerms == \"root\")\n access[\"adminUsers\"] = \";root(rwp);\"\n else\n access[\"adminUsers\"] = \";root(rwp);\"+adminSettingPerms+\"(rw);\"\n end\n access[\"adminGroups\"] = \"\"\n else\n access = YAML.load_file(fAccess)\n users = access[\"users\"]\n if users.index(userName) == nil && grantAccess\n users.concat( userName+\";\")\n elsif users.index(userName) != nil && !grantAccess\n\n beginning = users[0..users.index(userName)]\n gend = users[users.index(\";\", users.index(userName)+userName.size)]\n users = beginning.concat gend\n end\n access[\"users\"] = users\n end\n File.write(fAccess, access.to_yaml)\n\n end", "def chown_files(tmpdir)\n notifying_block do\n Dir[\"#{tmpdir}/**/*\"].each do |path|\n declare_resource(::File.directory?(path) ? :directory : :file, path) do\n owner new_resource.user if new_resource.user\n group new_resource.group if new_resource.group\n end\n end\n end\n end", "def change_group!\n tgt_gid = self.target_group.is_a?(Fixnum) ? self.target_group : Etc.getgrnam(self.target_group).gid\n chown_params = [nil, tgt_gid, self.target]\n\n if(File.symlink?(self.target) && (self.no_follow == 'both' || self.no_follow == 'chown'))\n File.lchown *chown_params\n elsif(self.stat(:ftype) == 'directory' && (self.recursive == 'both' || self.recursive == 'chown'))\n #DOcumenation for FileUtils.chown_R is wrong (at least for Ubuntu 8.1, takes ID as String.)\n chown_params[1] = chown_params[1].to_s\n FileUtils.chown_R *chown_params\n else\n File.chown *chown_params\n end\n rescue NotImplementedError => ex\n WarningShot::PermissionResolver.logger.error(\"lchown is not implemented on this machine, (disable nofollow).\")\n return false\n rescue Exception => ex\n WarningShot::PermissionResolver.logger.error(\"Unable to change group for file: #{self.target}; Exception: #{ex.message}\")\n return false\n end", "def stash_user_file(file,path)\n users = get_all_over500_users\n users.each_key do |u|\n puts \"copying files to #{u}\\'s home at #{path}.\"\n system \"ditto -V #{file} #{get_homedir(u)}/#{path}/#{File.basename(file)}\"\n FileUtils.chown_R(\"#{u}\", nil, \"#{get_homedir(u)}/#{path}/#{File.basename(file)}\")\n end\n end", "def setPermissionEdit( other_user )\n return setPermission( other_user, Dfile::PP_MAYEDIT )\n end", "def owner=(newuser) #:nodoc:\n saved? ? raise(NotImplementedError, \"Cannot change a document's owner once the document has been saved\") : super\n end", "def change_privilege(user, group=user)\n Merb.logger.info \"Changing privileges to #{user}:#{group}\"\n \n uid, gid = Process.euid, Process.egid\n target_uid = Etc.getpwnam(user).uid\n target_gid = Etc.getgrnam(group).gid\n \n if uid != target_uid || gid != target_gid\n # Change process ownership\n Process.initgroups(user, target_gid)\n Process::GID.change_privilege(target_gid)\n Process::UID.change_privilege(target_uid)\n end\n rescue Errno::EPERM => e\n Merb.logger.error \"Couldn't change user and group to #{user}:#{group}: #{e}\"\n end", "def owner=(user)\n de = document_editor_owner\n if de\n return user if de == user\n de.set_owner(false)\n end\n\n de = document_editors.find_by(user_id: user.id)\n if de.nil?\n self.editors << user\n de = document_editors.find_by(user_id: user.id)\n end\n de.set_owner(true)\n end", "def set_publication_owner(name, owner)\n typed_exec(\"ALTER PUBLICATION #{connection.quote_ident(name)} OWNER TO #{connection.quote_ident(owner)}\")\n end" ]
[ "0.7031798", "0.6613002", "0.64483887", "0.6332136", "0.63318396", "0.63233644", "0.62693286", "0.62464225", "0.6110811", "0.61022156", "0.5947538", "0.5878171", "0.58744186", "0.5788736", "0.5786735", "0.57764375", "0.5693316", "0.5679787", "0.5665396", "0.5661425", "0.56358135", "0.5619848", "0.5581551", "0.5566809", "0.55650526", "0.55612695", "0.5546541", "0.5517812", "0.5512831", "0.54583025" ]
0.7470499
0
Fetch files from current directory or current .zip file.
def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main_files\n retrieve_files_in_main_dir\n end", "def retrieve_files_in_main_dir\n ensure_file_open!\n @file.glob('*').map do |entry|\n next if entry.directory?\n\n entry_file_name = Pathname.new(entry.name)\n [entry_file_name, entry.get_input_stream(&:read)]\n end.compact.to_h\n end", "def get_current_files\n get_files(OcflTools::Utils.version_string_to_int(@head))\n end", "def files\n return get_result('files')\n end", "def files\n return @files if @files and not @files.empty?\n\n @files = []\n\n each_zip_entry do |entry|\n @files << entry.name\n end\n\n @files\n end", "def get_remote_files\n manager = @current_source.file_manager\n manager.start do \n @current_source.folders.each do |folder|\n @files[folder] = manager.find_files folder\n @files[folder] = @files[folder].take(@take) if @take\n Logger.<<(__FILE__,\"INFO\",\"Found #{@files[folder].size} files for #{@current_source.base_dir}/#{folder} at #{@current_source.host.address}\")\n SignalHandler.check\n end\n end\n end", "def get_file_listing\n execute!(drive.files.list).data\n end", "def retrieve_files\r\n if RUBY_PLATFORM =~ /win32|win64/i then\r\n $help_file = File.read('C:\\files\\BJHelp.txt')\r\n $welcome_file = File.read('C:\\files\\BJWelcome.txt')\r\n $credits_file = File.read('C:\\files\\BJCredits.txt')\r\n else\r\n $help_file = File.read('files/BJHelp.txt')\r\n $welcome_file = File.read('files/BJWelcome.txt')\r\n $credits_file = File.read('files/BJCredits.txt')\r\n end\r\n end", "def files(*args)\r\n LocalDirectory.current.files(*args)\r\n end", "def base\n\t\t@base ||= begin\n\t\t\tzip_file = Dir[File.join(self.location,\"*.zip\")].sort.first\n\t\t\tif zip_file\n\t\t\t\tZip::File.open(zip_file){ |z| z.get_entry(\"contents.xml\").get_input_stream.read }\n\t\t\telse\n\t\t\t\traise RuntimeError, \"Rubyfocus::LocalFetcher looking for zip files at #{self.location}: none found.\"\n\t\t\tend\n\t\tend\n\tend", "def monolithic_files\n get_files_in_dir(@monolithic_dir)\n end", "def download_response_files!\n files_downloaded = []\n File.makedirs(cache_location + '/returns')\n with_ftp do |ftp|\n files = ftp.list('*.csv')\n files.each do |filels|\n size, file = filels.split(/ +/)[4], filels.split(/ +/)[8..-1].join(' ')\n ftp.get(file, cache_location + '/returns/' + user_suffix + '_' + file)\n files_downloaded << file\n end\n end\n files_downloaded\n end", "def list_files\n [].tap do |files|\n remote_files do |file|\n files << file\n end\n end\n end", "def get_files\n return @files if @files.present?\n raise \"No user token present\" unless access[:user_token].present?\n @files ||= get(proviso_url + \"files\")\n @files.presence || raise(\"No files available\")\n end", "def retrieve_github_files(url)\n\n #create a virtual browser with a Chrome Windows Agent\n agent = Mechanize.new\n agent.user_agent = CHROME_USER_AGENT\n\n #retrieve the page and report if page not found (404)\n begin\n page = agent.get(url)\n rescue Exception => e\n #REPORT THE ERROR\n end\n\n #recursively download all content\n get_files_from_github_page(page)\n\n end", "def files\n results\n rescue ApiStruct::EntityError\n result\n end", "def fetch_files(program)\n program = init_fields(program)\n files = []\n\n SouvlakiRS.logger.info \" Trying to fetch: '#{program[:pub_title]}', use html? #{program[:use_html]}\"\n\n begin\n agent = init_agent\n files += if program[:use_html]\n from_html(agent, program)\n else\n rss, date, error = rss_shows_available(agent, program[:show_name_uri], program[:show_date])\n if rss.nil?\n program[:err_msg] = error if error\n return []\n end\n\n SouvlakiRS.logger.info \" date match (#{date})\"\n from_rss(agent, rss)\n end\n rescue StandardError => e\n SouvlakiRS.logger.error \" Fetch error: #{e}\"\n end\n\n # logout\n # logout(agent)\n # uri = \"#{@creds[:base_uri]}?op=logout&amp;\"\n # agent.get(uri)\n\n files\n end", "def fetch_files(name)\n @files = Dir.glob(\"./workspace/*#{name}*.txt\")\n .select { |v| /\\d+-\\d+-\\d+_[[:alpha:]]+\\.txt$/.match v }\n\n throw RuntimeError if @files.empty?\n @files\n end", "def get_remote_files\n raise BucketNotFound.new(\"#{self.config.fog_provider} Bucket: #{self.config.fog_directory} not found.\") unless directory\n files = []\n directory.files.each { |f| files << f if File.extname(f.key).present? }\n return files\n end", "def get_files(site, folder)\n files = []\n Dir.chdir(File.join(site.source, folder)) { files = filter_entries(Dir.glob('**/*.*')) }\n files\n end", "def retrieve_cloud_files(files); end", "def get_files(query_obj=nil,with_nested_resources=false)\n uri = URI.parse(@uri + \"/Files\")\n results = get(uri,query_obj,with_nested_resources)\n end", "def remote_files\n @remote_files ||= local_files\n end", "def files() = files_path.glob('**/*')", "def processFiles\n readRemoteXML\n parsePhotoRequestReponseXMl2\n handle_files\n zip_files\n end", "def fetch!\n old_path = path\n if old_path && path.length > 0\n path = \"\"\n @results = get(old_path, @options)\n end\n end", "def getPullRequestFiles(id)\n getFilesFromDiff(getPullRequestDiff(id))\n end", "def files\n get_back_here = Dir.pwd\n Dir.chdir(@path)\n @files = Dir.glob(\"*.mp3\")\n Dir.chdir(get_back_here)\n @files\n end", "def files_get(opts = {})\n files_get_with_http_info(opts)\n end", "def pull_files(remote_path,local_path)\n debug_p(\"pull_files from #{remote_path} to #{local_path}\")\n @sftp_session.dir.foreach(remote_path){ |path|\n #unless path.name == \".\" || path.name == \"..\"\n #not directory\n unless /^d/ =~ path.longname\n @sftp_session.download!(remote_path + \"/\" + path.name,local_path + \"/\" + path.name)\n end\n #end\n }\n end" ]
[ "0.6927383", "0.6580163", "0.65114397", "0.6503587", "0.64773613", "0.6402373", "0.62845725", "0.62720746", "0.6225117", "0.6222155", "0.62179345", "0.6168878", "0.6163954", "0.61059165", "0.60978436", "0.6096858", "0.6085929", "0.6067498", "0.606264", "0.6007258", "0.600525", "0.59768665", "0.59710777", "0.59322447", "0.59307367", "0.59164155", "0.5913249", "0.58748007", "0.58352476", "0.58330727" ]
0.7121194
0
Rename selected files and directories. ==== Parameters +pattern+ new filename, or a shash separated Regexp like string
def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def rename_all(pattern, replace)\n Dir.new('.').each do |f|\n File.rename(f, f.gsub(pattern, replace)) if f.match(pattern)\n end\nend", "def rename(root, pattern, replacement, force: false, excluding: nil)\n options = {force: force, excluding: excluding}\n\n ::Find.find(root) do |path|\n # The first emitted path will be the root directory\n next if path == root\n\n # Don't look any further into this directory\n ::Find.prune if excluding && path.match?(excluding)\n\n # The path doesn't match, keep searching\n next unless path.match?(pattern)\n\n # The path matches, so rename it\n dest = path.sub(pattern, replacement)\n FileUtils.mv(path, dest, force: force)\n\n # Find and rename the children of the path\n rename(dest, pattern, replacement, **options) if File.directory?(dest)\n\n # We already searched the directory's children, so we should stop\n ::Find.prune\n end\n end", "def update!(**args)\n @name_pattern = args[:name_pattern] if args.key?(:name_pattern)\n end", "def file_sub(path, pattern, replacement = nil, &b)\n tmp_path = \"#{path}.tmp\"\n File.open(path) do |infile|\n File.open(tmp_path, 'w') do |outfile|\n infile.each do |line|\n outfile.write(line.sub(pattern, replacement, &b))\n end\n end\n end\n File.rename(tmp_path, path)\nend", "def pattern=(pattern)\n @pattern = pattern\n substitute_variables! # TODO: Remove this call\n end", "def fnmatch( pattern, *args ) File.fnmatch( pattern, self, *args ) end", "def fnmatch(pattern, *args) File.fnmatch(pattern, path, *args) end", "def glob_match(filenames, pattern)\n\t\n\tnewPattern = pattern.gsub( '*', '.*').gsub( '?', '.')\n\n\treturn filenames.select{|i| i.match(/#{newPattern}/)}\n\t\nend", "def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end", "def file_pattern( pattern )\n self.class_eval { @file_pattern = pattern }\n end", "def add_file_pattern(name, pattern_string)\n if name.to_s !~ FILE_PATTERN_NAME_REGEX\n raise ArgumentError.new(\"A file pattern name must match this regex: #{ FILE_PATTERN_NAME_REGEX.inspect }\")\n end\n @file_patterns[name.to_sym] = pattern_string.to_s\n end", "def edit_matched_files(*match, &block)\n match.each do |m|\n if Pathname.new(m).absolute?\n path = m\n else\n path = File.join(File.expand_path(TARGET_PATH), m)\n end\n puts \"path: #{path}\"\n\n Dir.glob(path).each do |file|\n block.call(Content.create(file))\n end\n end\nend", "def glob(pattern)\n Dir.chdir(@output_dir) do\n Dir[pattern]\n end\n end", "def gsub(pat, rep)\n inject(FileList.new) { |res, fn| res << fn.gsub(pat,rep) }\n end", "def glob=(pattern)\n @glob = pattern\n if pattern.kind_of?(Regexp)\n @pattern = pattern\n else\n @pattern = scan_string\n end\n end", "def glob_match (filenames, pattern)\n\t# Escape the '*', '?', and '.' characters\n\tpattern.gsub!(/[\\*\\?\\.]/, '*' => '.*', '?' => '.', '.' => '\\.') \t\n\tregex = Regexp.new(pattern)\n\t#select returns a new array\n\tfilenames.select do |filename|\n\t\tfilename =~ regex\n\tend\nend", "def naming_pattern=(v)\n segment_naming.pattern = v\n end", "def fdelete_pattern(dir, pattern)\n\t# input params are ok?\n\tif dir != \"\" and dir != nil and pattern != \"\" and pattern != nil\n\t\t# list all files in temporary dir\n\t\tDir.foreach(dir).to_a.each do |d|\n\t\t\t# file name contains temp name?\n\t\t\tif d.match(/#{pattern}/) != nil\n\t\t\t\t# delete file\n\t\t\t\tfdelete(\"#{dir}/#{d}\")\n\t\t\tend\n\t\tend\n\tend\nend", "def update!(**args)\n @parent_pattern = args[:parent_pattern] if args.key?(:parent_pattern)\n @pattern = args[:pattern] if args.key?(:pattern)\n end", "def rename_files(format:)\n require 'pp'\n child_items.each_with_index do |child, index|\n new_name = sprintf(format, index+1)\n extname = child.path.extname\n dirname = child.path.dirname.to_s\n new_filename = dirname + \"/\" + new_name + extname\n FileManager.rename(from_file: child.path.to_s, to_file: new_filename)\n end\n end", "def file_edit(filename, regexp, replacement)\n Tempfile.open(\".#{File.basename(filename)}\", File.dirname(filename)) do |tempfile|\n File.open(filename).each do |line|\n tempfile.puts line.gsub(regexp, replacement)\n end\n tempfile.fdatasync\n tempfile.close\n stat = File.stat(filename)\n FileUtils.chown stat.uid, stat.gid, tempfile.path\n FileUtils.chmod stat.mode, tempfile.path\n FileUtils.mv tempfile.path, filename\n end\n end", "def gsub_file(relative_destination, regexp, *args, &block)\r\n path = destination_path(relative_destination)\r\n content = File.read(path).gsub(regexp, *args, &block)\r\n File.open(path, 'wb') { |file| file.write(content) }\r\n end", "def apply_to(pattern)\n @pattern = pattern\n end", "def gsub_file(relative_destination, regexp, *args, &block)\n path = destination_path(relative_destination)\n content = File.read(path).gsub(regexp, *args, &block)\n File.open(path, 'wb') { |file| file.write(content) }\n end", "def glob pattern\n Dir[File.join(@originals,pattern)].collect do |f|\n File.basename(f)\n end\n end", "def test_files_pattern=(pattern)\n warn 'test_files_pattern= is deprecated in QUnited rake task config, use test_files= with a pattern'\n @test_files = pattern\n end", "def rsub(pattern, replacement)\n if i = rindex(pattern) # rubocop:disable Lint/AssignmentInCondition\n s = @string.dup\n s[i] = replacement\n self.class.new s\n else\n self\n end\n end", "def find_files(pattern)\n Dir[File.join(folder, pattern, \"*.#{pattern}\")].sort{|f1, f2|\n File.basename(f1) <=> File.basename(f2)\n }.collect{|f|\n File.join(pattern, File.basename(f))\n }\n end", "def remove_files(pattern,skip=nil)\n Dir.glob(pattern).each do |file_name|\n remove_file(file_name) unless file_name == skip\n end\n end", "def input_files_pattern\n @args.options[:input_files_pattern]\n end" ]
[ "0.6490024", "0.6006657", "0.5734607", "0.57127804", "0.5549183", "0.5548546", "0.55439925", "0.55129874", "0.5512433", "0.5495125", "0.54512054", "0.5416406", "0.5378884", "0.53518045", "0.53289044", "0.52556765", "0.5229619", "0.5212441", "0.51935375", "0.51900387", "0.5175399", "0.5169746", "0.51688385", "0.5165535", "0.5153248", "0.51438135", "0.5123096", "0.512181", "0.50631505", "0.50558436" ]
0.736625
0
Change the timestamp of the selected files and directories. ==== Parameters +timestamp+ A string that can be parsed with `Time.parse`. Note that this parameter is not compatible with UNIX `touch t`.
def touch_t(timestamp) FileUtils.touch selected_items, mtime: Time.parse(timestamp) ls end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def modified_at(file, timestamp = nil)\n require 'date'\n time = timestamp ? DateTime.parse(\"#{timestamp}\") : DateTime.now\n timestamp = time.strftime('%Y%m%d%H%M')\n execute(\"/bin/touch -mt #{timestamp} #{file}\")\n end", "def timestamp=(timestamp)\n @timestamp = _check_timestamp(timestamp)\n end", "def timestamp=(timestamp)\n @timestamp = _check_timestamp(timestamp)\n end", "def record_modification_timestamp(path, timestamp)\n File.utime(timestamp, timestamp, path)\n record_access_timestamp(path, timestamp)\n record_changed_timestamp(path, timestamp)\n end", "def record_access_timestamp(path, timestamp)\n # Hook method: Already stored with File.utime\n end", "def update!(timestamp = Time.now)\n ts = timestamp.respond_to?(:xmlschema) ? timestamp.xmlschema : timestamp.to_s\n\n if has_updated?\n updated.text = ts\n else\n add_child Updated.new { |u| u.text = ts }\n end\n\n self\n end", "def record_creation_timestamp(path, timestamp)\n # Hook method: Linux filesystems doesn't store creation datetime\n end", "def bundleTimestampNone(dest_folder,new_timestamp)\n @files = Dir.glob(dest_folder+\"**/**\")\n for file in @files\n File.utime(new_timestamp, new_timestamp, file)\n if !(File::directory?(file))\n # Add to zip bundle \n archive=zipBundle(file,new_timestamp)\n end \n end\n generateZipBundle() \n @latest_ts=new_timestamp+60\nend", "def update_optime(timestamp)\n # track what's been written with this - write optime to the fs, perhaps periodically.\n @log.debug(\"Optime: #{timestamp}\")\n begin\n @_mongoClient.db(\"local\").collection(\"oplog.tracker\").update({}, {'timestamp' => timestamp}, {:upsert => true})\n rescue\n @log.error(\"Unable to update optime: #{timestamp}\")\n raise\n end\n end", "def timestamp=(time)\n @timestamp = time.is_a?(Time) ? time.to_f : time\n end", "def []=(timestamp, value)\n if value.nil?\n @data.delete(timestamp)\n else\n @data[timestamp] = value\n end\n end", "def format_timestamp(timestamp)\n Time.parse(timestamp).strftime(\"%T (%z)\")\n end", "def get_revision_number_by_timestamp(wanted_timestamp, path = nil)\n if @timestamps_revisions.empty?\n raise 'No revisions, so no timestamps.'\n end\n\n all_timestamps_list = []\n remaining_timestamps_list = []\n @timestamps_revisions.each_key do |time_dump|\n all_timestamps_list.push(Marshal.load(time_dump)) # rubocop:disable Security/MarshalLoad\n remaining_timestamps_list.push(Marshal.load(time_dump)) # rubocop:disable Security/MarshalLoad\n end\n\n # find closest matching timestamp\n mapping = {}\n first_timestamp_found = false\n old_diff = 0\n # find first valid revision\n all_timestamps_list.each do |best_match|\n remaining_timestamps_list.shift\n old_diff = wanted_timestamp - best_match\n mapping[old_diff.to_s] = best_match\n if path.nil? || (!path.nil? && @timestamps_revisions[Marshal.dump(best_match)].revision_at_path(path))\n first_timestamp_found = true\n break\n end\n end\n\n # find all other valid revision\n remaining_timestamps_list.each do |curr_timestamp|\n new_diff = wanted_timestamp - curr_timestamp\n mapping[new_diff.to_s] = curr_timestamp\n if path.nil? || (!path.nil? && @timestamps_revisions[Marshal.dump(curr_timestamp)].revision_at_path(path))\n if (old_diff <= 0 && new_diff <= 0) ||\n (old_diff <= 0 && new_diff > 0) ||\n (new_diff <= 0 && old_diff > 0)\n old_diff = [old_diff, new_diff].max\n else\n old_diff = [old_diff, new_diff].min\n end\n end\n end\n\n if first_timestamp_found\n wanted_timestamp = mapping[old_diff.to_s]\n @timestamps_revisions[Marshal.dump(wanted_timestamp)]\n else\n @current_revision\n end\n end", "def raw_timestamp_to_cache_version(timestamp)\n key = timestamp.delete(\"- :.\")\n if key.length < 20\n key.ljust(20, \"0\")\n else\n key\n end\n end", "def set_for_time timestamp\n return nil unless @date\n case timestamp[0,2]\n when \"00\"\n @datetime.hour == 23 ? @date_add_1_hr : @date\n when \"23\"\n @datetime.hour == 00 ? @date_1_hr_ago : @date\n else\n @date\n end\n end", "def call(timestamp:, signature:)\n validate_parameters(timestamp, signature)\n\n \"t=#{timestamp.to_i},#{scheme}=#{signature}\"\n end", "def update_timestamp(namespace, new_timestamp)\n @coll.update({ SolrConfigConst::SOLR_URL_KEY => @solr_loc,\n SolrConfigConst::NS_KEY => namespace\n },\n { \"$set\" => {\n SolrConfigConst::UPDATE_TIMESTAMP_KEY => new_timestamp\n }})\n end", "def save_timestamp_changes(root)\n iterator = Iterators::PreOrderEntriesIterator.new(root)\n while iterator.has_next?\n next_entry = iterator.next_item\n record_creation_timestamp(next_entry.path, next_entry.new_created_datetime)\n record_modification_timestamp(next_entry.path, next_entry.new_modified_datetime)\n end\n end", "def timestamp=(timestamp)\n @wsu_timestamp = timestamp\n end", "def update_timestamp(*_args)\n current_time = current_time_from_proper_timezone\n\n write_attribute('updated_at', current_time) if respond_to?(:updated_at)\n write_attribute('updated_on', current_time) if respond_to?(:updated_on)\n end", "def bundleTimestampFileCount(dest_folder,new_timestamp,max_count)\n ts=new_timestamp\n fileCount=0\n deletedFileList=\"\"\n @files = Dir.glob(dest_folder+\"**/**\")\n for file in @files\n if(fileCount>max_count)\n ts=ts+60\n fileCount=0\n end\n if file.to_s().end_with?(\"searchDB.sql\") \n File.utime(new_timestamp, new_timestamp, file)\n elsif file.to_s().end_with?(\"Deleted_List.list\")\n deletedFileList=file \n else\n File.utime(ts, ts, file)\n fileCount=fileCount+1\n end\n end \n File.utime(ts, ts, deletedFileList)\nend", "def timestamp(time)\n date = @file[/(\\w+ \\d+, \\d+)/]\n ASF::Board::TIMEZONE.parse(\"#{date} #{time}\").to_i * 1000\n end", "def convert_timestamp(timestamp)\n timestamp = db.to_application_timestamp(timestamp) if timestamp.is_a?(String)\n timestamp\n end", "def newer_than_timestamp(timestamp)\n non_future_partitions.select do |p|\n timestamp <= p.timestamp\n end\n end", "def set_deleted_timestamp(time=nil)\n field = model.deleted_timestamp_field\n meth = :\"#{field}=\"\n if respond_to?(field) && respond_to?(meth) && (model.deleted_timestamp_overwrite? || send(field).nil?)\n self.send(meth, time||=Sequel.datetime_class.now)\n self.save\n end\n end", "def set_signature_timestamp\n time = Time.now\n @signed_at = time\n @signed_at_timestamp = TimeFormatting.printable_time time\n @signed_at_timestamp_ms = TimeFormatting.ms_timestamp(time)\n set_document_tag :esigntimestamp, @signed_at_timestamp\n end", "def update_system_time_stamp\n out = Jhead.call(\"-ft\", \"-q\", @match, @pattern)\n raise(JheadError.new, out) unless out.empty?\n end", "def check_timestamp!(timestamp)\n fail ArgumentError, 'Timestamp must be a Time' unless timestamp.is_a? Time\n end", "def touch( fname, time = Time.now )\n stamp = time.strftime('%Y%m%d%H%M.%S')\n %x[ touch -m -t #{stamp} #{fname} ]\n end", "def touch( fname, time = Time.now )\n stamp = time.strftime(\"%Y%m%d%H%M.%S\")\n %x[ touch -m -t #{stamp} #{fname} ]\n end" ]
[ "0.6365125", "0.6343466", "0.6308022", "0.6152845", "0.5780877", "0.5666242", "0.5505432", "0.53912926", "0.5374339", "0.52755016", "0.5058137", "0.50204706", "0.5016717", "0.5002579", "0.49970952", "0.49921483", "0.49688482", "0.49676868", "0.49618778", "0.4936849", "0.49342787", "0.4917471", "0.48907673", "0.48904294", "0.48587582", "0.48413485", "0.48357627", "0.47926298", "0.4783953", "0.4779943" ]
0.7202312
0
Paste yanked files / directories here.
def paste if @yanked_items if current_item.directory? FileUtils.cp_r @yanked_items.map(&:path), current_item else @yanked_items.each do |item| if items.include? item i = 1 while i += 1 new_item = load_item dir: current_dir, name: "#{item.basename}_#{i}#{item.extname}", stat: item.stat break unless File.exist? new_item.path end FileUtils.cp_r item, new_item else FileUtils.cp_r item, current_dir end end end ls end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def blacklisted_dir_entries\n %w[. ..]\n end", "def replicate_dir(f)\n out_original = f.sub($queue,$original)\n out_watermarked = f.sub($queue,$watermarked)\n if !File.exist?(out_original) && !File.exist?(out_watermarked)\n FileUtils.mkdir(out_original)\n FileUtils.mkdir(out_watermarked) \n end\nend", "def copy_skel_files(exclude = [])\n full_path = File.join(File.dirname(__FILE__), @skel)\n excluded = exclude.map {|x| \"#{full_path}/#{x}\" }\n Dir.glob(\"#{full_path}/**/*\").select {|x| File.directory?(x)}.each do |f|\n relative_path = f.gsub(/#{full_path}\\//, '')\n FileUtils.mkdir_p relative_path\n end\n (\n Dir.glob(\"#{full_path}/**/*\") + Dir.glob(\"#{full_path}/**/.*\") - excluded\n )\n .select {|x| File.file?(x)}.each do |f|\n next if f =~ /\\.gitkeep/\n relative_path = f.gsub(/#{full_path}\\//, '')\n FileUtils.cp f, relative_path\n end\n end", "def copy_base_files\n\tbase_files = Dir[\"templates/Base/**/*\"].reject { |fn| \n\t\tFile.directory?(fn) \n\t}\n\n\tprint \"copying base base files .\"\n\n\tbase_files.each do |base_file|\n\t\tdestination = base_file.gsub(\"templates\", \"output\")\n\n\t\tcreate_folders_for_path destination\n\n\t\tFileUtils.cp(base_file, destination)\n\t\tprint \".\"\n\tend\n\tprint \"\\n\"\nend", "def copy_files\r\n %w{_config.dev.yml about.md feed.xml gulpfile.js index.html}.each do |file|\r\n copy_file file\r\n end\r\n end", "def copy_files\n copy_file 'downr.rb', 'config/initializers/downr.rb'\n end", "def copy_content\n @tocopy.each do |pair|\n src = pair[0]\n dst = File.expand_path(File.join(@temp_path, pair[1] || ''))\n dstdir = File.dirname(dst)\n FileUtils.mkpath(dstdir) unless File.exist?(dstdir)\n FileUtils.cp_r(src, dst)\n end\n\n # clear out the list of things to copy so that snippets can\n # re-load it and call copy_content again if needed\n @tocopy = []\n end", "def concat(dir_dest)\n\tDir.chdir(dir_dest)\n\tdvs_all = File.open(\"DVS_ALL.txt\", \"a\")\n\tDir.glob(\"*.{pre,PRE}*\").each do |f|\n\t\tdvs_files = File.open(f,'r')\n\t\tdvs_files.each_line{|line| dvs_all.puts line}\n\tend\n\tDir.glob(\"*.{tab,TAB}*\").each do |f|\n\t\tdvs_files = File.open(f,'r')\n\t\tdvs_files.each_line{|line| dvs_all.puts line}\n\tend\n\tdvs_all.close\nend", "def copy_folders\r\n %w{_includes _layouts _posts _sass assets}.each do |dir|\r\n directory dir\r\n end\r\n end", "def copy_files_to_current_path()\n require 'fileutils'\n @files.each do |f|\n FileUtils::cp(f,'./')\n end\n end", "def rearrange\n rootpath = \"#{$paths.restore_path}/Student_Records_D20130520/Student_Records\"\n Dir.entries(rootpath).each{|entry|\n if !entry.gsub(/\\.|rb/,\"\").empty?\n Dir.chdir(\"#{rootpath}/#{entry}/SY_2012-2013\")\n if !File.directory?(\"#{rootpath}/#{entry}/SY_2012-2013/Withdrawal\")\n Dir.mkdir(\"#{rootpath}/#{entry}/SY_2012-2013/Withdrawal\")\n end\n Dir.glob('WD_**') do |file|\n #puts File.expand_path(file)\n oldpath = File.expand_path(file)\n FileUtils.mv(\"#{oldpath}\",\"#{rootpath}/#{entry}/SY_2012-2013/Withdrawal\")\n end\n end\n }\n end", "def copy_data_dir_here\n copy_all from: content, to: current_dir\nend", "def pop_dir\n return # 2014-07-25 - 22:43 \n # the first time we pop, we need to put the current on stack\n if !$visited_dirs.index(Dir.pwd)\n $visited_dirs.push Dir.pwd\n end\n ## XXX make sure thre is something to pop\n d = $visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n $visited_dirs.push d\n Dir.chdir d\n $filterstr ||= \"M\"\n $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}#{$filterstr})'`.split(\"\\n\")\n post_cd\nend", "def enhance_file_list\n return unless $enhanced_mode\n # if only one entry and its a dir\n # get its children and maybe the recent mod files a few\n \n # zsh gives errors which stick on stdscr and don't get off!\n # Rather than using N I'll try to convert to ruby, but then we lose\n # similarity to cetus and its tough to redo all the sorting stuff.\n if $files.size == 1\n # its a dir, let give the next level at least\n if $files.first[-1] == \"/\"\n d = $files.first\n #f = `zsh -c 'print -rl -- #{d}*(omM)'`.split(\"\\n\")\n f = get_file_list d\n if f && f.size > 0\n $files.concat f\n $files.concat get_important_files(d)\n return\n end\n else\n # just a file, not dirs here\n return\n end\n end\n # \n # check if a ruby project dir, although it could be a backup file too,\n # if so , expand lib and maby bin, put a couple recent files\n #\n if $files.index(\"Gemfile\") || $files.grep(/\\.gemspec/).size > 0\n # usually the lib dir has only one file and one dir\n flg = false\n $files.concat get_important_files(Dir.pwd)\n if $files.index(\"lib/\")\n f = `zsh -c 'print -rl -- lib/*(om[1,5]MN)'`.split(\"\\n\")\n if f && f.size() > 0\n insert_into_list(\"lib/\", f)\n flg = true\n end\n dd = File.basename(Dir.pwd)\n if f.index(\"lib/#{dd}/\")\n f = `zsh -c 'print -rl -- lib/#{dd}/*(om[1,5]MN)'`.split(\"\\n\")\n if f && f.size() > 0\n insert_into_list(\"lib/#{dd}/\", f)\n flg = true\n end\n end\n end\n if $files.index(\"bin/\")\n f = `zsh -c 'print -rl -- bin/*(om[1,5]MN)'`.split(\"\\n\")\n insert_into_list(\"bin/\", f) if f && f.size() > 0\n flg = true\n end\n return if flg\n\n # lib has a dir in it with the gem name\n\n end\n return if $files.size > 15\n\n ## first check accessed else modified will change accessed\n moda = `zsh -c 'print -rn -- *(/oa[1]MN)'`\n if moda && moda != \"\"\n modf = `zsh -c 'print -rn -- #{moda}*(oa[1]MN)'`\n if modf && modf != \"\"\n insert_into_list moda, modf\n end\n modm = `zsh -c 'print -rn -- #{moda}*(om[1]MN)'`\n if modm && modm != \"\" && modm != modf\n insert_into_list moda, modm\n end\n end\n ## get last modified dir\n modm = `zsh -c 'print -rn -- *(/om[1]MN)'`\n if modm != moda\n modmf = `zsh -c 'print -rn -- #{modm}*(oa[1]MN)'`\n insert_into_list modm, modmf\n modmf1 = `zsh -c 'print -rn -- #{modm}*(om[1]MN)'`\n insert_into_list(modm, modmf1) if modmf1 != modmf\n else\n # if both are same then our options get reduced so we need to get something more\n # If you access the latest mod dir, then come back you get only one, since mod and accessed\n # are the same dir, so we need to find the second modified dir\n end\nend", "def copyUsedEmojiFiles(outputDir)\r\n @usedEmojis.each { |emoji|\r\n emojiBaseName = \"emoji_u#{emoji}#{@emojiExt}\"\r\n inputFileName = @emojiDir.join(emojiBaseName)\r\n outputFileName = outputDir.join(emojiBaseName)\r\n IO.copy_stream(inputFileName, outputFileName)\r\n }\r\n end", "def copy_sample_files\n system 'for filename in config/*.sample; do cp -n \"$filename\" \"${filename%.sample}\"; done'\nend", "def pop_dir\n # the first time we pop, we need to put the current on stack\n if !$visited_dirs.index(Dir.pwd)\n $visited_dirs.push Dir.pwd\n end\n ## XXX make sure thre is something to pop\n d = $visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n $visited_dirs.push d\n Dir.chdir d\n display_dir\n\n return\n # old stuff with zsh\n $filterstr ||= \"M\"\n $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}#{$filterstr})'`.split(\"\\n\")\n post_cd\nend", "def copy_markdown_files\n %w[AUTHORS.md CODE_OF_CONDUCT.md TODO.md].map { |f| copy_file(f, f) }\n end", "def pop_dir\n # the first time we pop, we need to put the current on stack\n if !$visited_dirs.index(Dir.pwd)\n $visited_dirs.push Dir.pwd\n end\n ## XXX make sure thre is something to pop\n d = $visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n $visited_dirs.push d\n Dir.chdir d\n $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split(\"\\n\")\n $patt=nil\nend", "def copy_config_files\n copy_file 'config/arkivo.yml', 'config/arkivo.yml'\n copy_file 'config/zotero.yml', 'config/zotero.yml'\n end", "def get_video_destination(dir, prompt = 'directory > ')\n dir_prefix = \"#{ dir }\".length\n Readline.completion_case_fold = true\n Readline.completion_proc = lambda do |prefix|\n path = \"#{ dir }#{ prefix }*\"\n list = Dir.glob(path)\n list = list.map { |f| File.directory?(f) ? \"#{ f }/\" : f }\n list = list.map { |f| f[dir_prefix, f.length] }\n list = list.sort { |f1, f2| f1.downcase <=> f2.downcase }\n list\n end \n dest = dir + Readline.readline(prompt)\n puts dest\n return dest\nend", "def copy_or_fetch\n filename_pattern = File.join self.class.source_root, \"*\" #/*.html.#{template_engine}\"\n Dir.glob(filename_pattern).map {|f| File.basename f}.each do |f|\n directory f.to_s, \"app/views/#{f}\"\n end\n end", "def copy_assets\r\n FileUtils.cd('view') do\r\n %w[style.css napoli.png ferraro.svg].each do |name|\r\n FileUtils.cp(name, File.join('..', 'output', name))\r\n end\r\n end\r\nend", "def backup2Drive(src,conf)\n dest = conf[:backupDrive]\n dest = dest + \"/\" unless dest [-1] =~ /[\\/\\\\]/\n dest = dest + src\n puts src\n puts dest\n FileUtils.mkdir_p(File.dirname(dest))\n FileUtils.cp(src, dest)\n puts aktTime()+\" archive copied\"\n cleanUp(conf) if conf[:generations]\n \nend", "def register_self!(dir)\n Find.find(dir).each do |f|\n next if f == dir\n basename = f.sub(/^#{dir}\\//, '')\n next if basename.match(/^.git$/)\n next if basename.match(/^.git\\W/)\n next if gitignore_list(dir).include?(basename)\n\n if @files[basename]\n carp \"From #{'self'.blue.bold} #{basename.bold} \",\n 'keep'.white, 2 if @files[basename] == '__self'\n else\n carp \"From #{'self'.blue.bold} #{basename.bold}\",\n 'registed'.green.bold, 1\n @files[basename] = '__self'\n end\n\n @self_files << f unless @self_files.include?(f)\n end\n end", "def from_sublime_to_repo\n copy_files(packages_files, \"#{SAVED_PREFS}/packages\")\n copy_files(settings_files, \"#{SAVED_PREFS}/settings\")\n copy_files(snippets_files, \"#{SAVED_PREFS}/snippets\")\nend", "def mirror_file(source, dest, copied = [], duplicated = [], postfix = '_override')\n base, rest = split_name(source)\n dst_dir = File.dirname(dest)\n dup_path = dst_dir / \"#{base}#{postfix}.#{rest}\" \n if File.file?(source)\n mkdir_p(dst_dir) unless File.directory?(dst_dir)\n if File.exists?(dest) && !File.exists?(dup_path) && !FileUtils.identical?(source, dest)\n # copy app-level override to *_override.ext\n copy_entry(dest, dup_path, false, false, true)\n duplicated << dup_path.relative_path_from(Merb.root)\n end\n # copy gem-level original to location\n if !File.exists?(dest) || (File.exists?(dest) && !FileUtils.identical?(source, dest))\n copy_entry(source, dest, false, false, true) \n copied << dest.relative_path_from(Merb.root)\n end\n end\n end", "def mirror_dirs (source_dir, target_dir)\n # Skip hidden root source dir files by default.\n source_files = Dir.glob File.join(source_dir, '*')\n case RUBY_PLATFORM\n when /linux|darwin/ then\n source_files.each { | source_file | sh 'cp', '-a', source_file, target_dir }\n else\n cp_r source_files, target_dir, :preserve => true\n end\nend", "def add_default_files_to_definition\n mkdir_p('files')\n default_files = File.join(File.dirname(__FILE__), '../../files')\n files = []\n chdir(default_files) do\n files += Dir.glob(\"**/*\")\n end\n files.each do |filespec|\n dest = File.join('files', filespec)\n unless File.exist?(dest)\n src = File.join(default_files, filespec)\n if File.file?(src)\n destdir = File.dirname(dest)\n mkdir_p(destdir) unless File.exist?(destdir)\n # puts \"cp(#{src}, #{dest}), destdir => #{destdir}\"\n cp(src, dest)\n end\n end\n end\n end", "def move_files_if(src_files, dst_dir = nil)\n Dir[src_files].each do |srcfile|\n cp_action = 0\n dst_dir = File.dirname(src_files).gsub(TMPDIR, '').gsub(/^\\//, '') if dst_dir == nil\n dst_dir << \"/\" unless dst_dir =~ /\\/$/\n dstfile = \"#{dst_dir}#{File.basename(srcfile)}\"\n\n # check if exists similar one in hdl/ directory\n if !File.file? dstfile\n cp_action = 1\n # if exists but differs\n elsif !FileUtils.identical?(dstfile, srcfile) then\n \n puts \"-\" * 43 << \"existing one\" << \"-\" * 44 << '|' << \"-\" * 44 << \"generated\" << \"-\" * 43 << \"\\n\" \n puts %x{diff -y -W200 #{dstfile} #{srcfile} | less }\n puts \"-\" * 200\n print \"Use generated file #{File.basename(srcfile)}? [Y/N] \"\n if $stdin.gets =~ /y/i\n cp_action = 2\n end\n end\n if cp_action > 0\n FileUtils.mkdir_p(dst_dir) unless File.directory? dst_dir\n FileUtils.cp srcfile, dstfile\n if cp_action == 1\n printf(\"%5s %20s %s\\n\",\"\", \" new file added:\", dstfile)\n else\n printf(\"%20s %s\\n\",\" overwrited:\", dstfile)\n end\n end\n end\nend" ]
[ "0.563246", "0.5365304", "0.53574353", "0.53080815", "0.5290943", "0.5287722", "0.5275275", "0.52750075", "0.52619284", "0.52032536", "0.5198403", "0.51540506", "0.513296", "0.5128863", "0.5099883", "0.50897795", "0.50862366", "0.50715935", "0.5070146", "0.5068272", "0.5066366", "0.50657594", "0.5038755", "0.50235236", "0.50186175", "0.5003172", "0.49885264", "0.4980246", "0.49710813", "0.49473417" ]
0.7160363
0
Copy selected files and directories' path into clipboard on OSX.
def clipboard IO.popen('pbcopy', 'w') {|f| f << selected_items.map(&:path).join(' ')} if osx? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_clipboard_copy\n return nil unless sel=@selection and dat=@data[sel]\n # XXX i feel dirty\n if Wx::PLATFORM == \"WXMAC\"\n IO.popen(\"pbcopy\", \"w\") {|io| io.write dat}\n stat = $?.success?\n else\n dobj = RawDataObject.new(dat)\n stat = Wx::Clipboard.open {|clip| clip.place dobj}\n end\n return stat\n end", "def filecopy(input)\n\tosascript <<-END\n\t\tdelay #{@moreimage}\n\t\tset the clipboard to POSIX file (\"#{input}\")\n\t\ttell application \"Copied\"\n\t\t\tsave clipboard\n\t\tend tell\n\tEND\nend", "def do_clipboard_paste\n dat = if Wx::PLATFORM == \"WXMAC\" \n # XXX i feel dirty\n `pbpaste`\n else\n dobj=RawDataObject.new\n Wx::Clipboard.open {|clip| clip.fetch dobj}\n dobj.raw_data\n end\n\n self.gui_set_value(self.cur_pos, dat) if dat and dat.size > 0\n end", "def copy_to_clipboard\n end", "def copyFromClipboard \n \"copyFromClipboard\" \n end", "def copy(item)\n copy_command = darwin? ? \"pbcopy\" : \"xclip -selection clipboard\"\n\n Kernel.system(\"echo '#{item.value.gsub(\"\\'\",\"\\\\'\")}' | tr -d \\\"\\n\\\" | #{copy_command}\")\n\n \"Boom! We just copied #{item.value} to your clipboard.\"\n end", "def copy\n\n # FIXME: #copy, #cut and #paste really shouldn't use platform-\n # dependent keypresses like this. But until DSK-327491 is fixed,\n # this will have to do.\n if OperaWatir::Platform.os == :macosx\n keys.send [:command, 'c']\n else\n keys.send [:control, 'c']\n end\n end", "def copyToClipboard _args\n \"copyToClipboard _args;\" \n end", "def pbcopy(text)\n # work around, ' wrecks havoc on command line, but also caused some weird regexp substitution\n rtf = text.index('{\\rtf1')\n File.open(\"/tmp/script.scpt\", 'w') do |f|\n if rtf\n f << text\n else\n f << \"set the clipboard to \\\"#{text}\\\"\"\n end\n end\n if rtf\n `cat /tmp/script.scpt | pbcopy -Prefer rtf`\n else\n `osascript /tmp/script.scpt`\n end\nend", "def paste link\n clipboard = %w{\n /usr/bin/pbcopy\n /usr/bin/xclip\n }.find { |path| File.exist? path }\n\n if clipboard\n IO.popen clipboard, 'w' do |io| io.write link end\n end\n end", "def cop\n last_value = IRB.CurrentContext.last_value\n %x[echo '#{last_value}' | pbcopy]\n \"copied \\`#{last_value}' to your clipboard\"\nend", "def cop\n last_value = IRB.CurrentContext.last_value\n %x[echo '#{last_value}' | pbcopy]\n \"copied \\`#{last_value}' to your clipboard\"\nend", "def textcopy(input)\n\tosascript <<-END\n\t\ttell application \"Copied\"\n\t\t\tsave \"#{input}\"\n\t\tend tell\n\tEND\nend", "def pbpaste\n a = IO.popen(\"osascript -e 'the clipboard as unicode text' | tr '\\r' '\\n'\", 'r+').read\n a.strip.force_encoding(\"UTF-8\")\nend", "def copy(*args) IO.popen('pbcopy', 'r+') { |clipboard| clipboard.puts args.map(&:inspect) }; end", "def cp(string)\n `echo \"#{string} | pbcopy`\n puts 'copied to clipboard'\nend", "def copy(content)\n case RUBY_PLATFORM\n when /darwin/\n return content if `which pbcopy`.strip == ''\n IO.popen('pbcopy', 'r+') { |clip| clip.print content }\n when /linux/\n return content if `which xclip 2> /dev/null`.strip == ''\n IO.popen('xclip', 'r+') { |clip| clip.print content }\n when /i386-cygwin/\n return content if `which putclip`.strip == ''\n IO.popen('putclip', 'r+') { |clip| clip.print content }\n end\n\n content\n end", "def paste; clipboard_paste; end", "def do_clipboard_cut\n if do_clipboard_copy()\n pos = @selection.first\n self.gui_set_value(nil, '')\n self.cur_pos = pos\n end\n end", "def do_copy\n @editor.value = @current_copycode\n @editor.focus\n end", "def get_clipboard_contents\n out = \"\"\n\n Open3.popen3(\"xclip -o -selection clipboard\") do |_, o, _, _|\n out = o.read.strip\n end\n\n out\n end", "def copy(content)\n cmd = case true\n when system(\"type pbcopy > /dev/null 2>&1\")\n :pbcopy\n when system(\"type xclip > /dev/null 2>&1\")\n :xclip\n when system(\"type putclip > /dev/null 2>&1\")\n :putclip\n end\n\n if cmd\n IO.popen(cmd.to_s, 'r+') { |clip| clip.print content }\n end\n\n content\n end", "def copy(content)\n cmd = case true\n when system(\"type pbcopy > /dev/null 2>&1\")\n :pbcopy\n when system(\"type xclip > /dev/null 2>&1\")\n :xclip\n when system(\"type putclip > /dev/null 2>&1\")\n :putclip\n end\n\n if cmd\n IO.popen(cmd.to_s, 'r+') { |clip| clip.print content }\n end\n\n content\n end", "def get_selection\n return `xclip -o` if RUBY_PLATFORM =~ /linux/\n return `pbpaste` if RUBY_PLATFORM =~ /darwin/\nend", "def pbcopy(str)\n IO.popen('pbcopy', 'r+') {|io| io.puts str }\n output.puts \"-- Copy to clipboard --\\n#{str}\"\nend", "def pbpaste\n Clipboard.paste\nend", "def copy\n out = ''\n\n Selection.each do |dd|\n docu = dd.cite_key.get\n docu.strip!\n out << \"[@#{docu}] \"\n end\n\n pbcopy(out.strip)\n growl(\"#{Selection.size} citation references copied to the clipboard\")\nend", "def pbcopy(str)\n IO.popen('pbcopy', 'r+') {|io| io.puts str }\n puts \"-- Copy to clipboard --\\n#{str}\"\nend", "def paste\n\n # FIXME\n if OperaWatir::Platform.os == :macosx\n keys.send [:command, 'v']\n else\n keys.send [:control, 'v']\n end\n end", "def copy(str = nil)\n clipboard_copy(:string => (!$stdin.tty? ? $stdin.read : str))\n end" ]
[ "0.7115079", "0.7002764", "0.69583875", "0.6808353", "0.6765171", "0.6653057", "0.663103", "0.6491936", "0.64842623", "0.64713055", "0.6452405", "0.6452405", "0.64059824", "0.6365171", "0.6360526", "0.63305914", "0.63264066", "0.6302481", "0.62640446", "0.61834943", "0.6111439", "0.6110237", "0.6110237", "0.6071464", "0.6067827", "0.6012887", "0.60027915", "0.59836066", "0.5961133", "0.59368163" ]
0.8589144
0
Unarchive .zip and .tar.gz files within selected files and directories into current_directory.
def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, mode: entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unpack( archive, into = Dir.pwd )\n Dir.chdir( into ) do \n if archive.match( /\\.tar\\.gz\\Z/ ) or archive.match(/\\.tgz\\Z/) then\n tgz = ::Zlib::GzipReader.new( File.open( local_source, 'rb') )\n ::Archive::Tar::Minitar.unpack( tgz, into )\n elsif archive.match( /\\.gem\\Z/ ) then\n subdir = File.basename( archive, \".gem\" )\n Gem::Installer.new( archive ).unpack( subdir )\n else\n raise \"Unable to extract files from #{File.basename( local_source)} -- unknown format\"\n end\n end\n end", "def unpack\n self.dir = Rails.root + 'tmp' + SecureRandom.hex(20)\n FileUtils.mkdir(dir)\n\n dirs = []\n files = []\n\n Zip::Archive.open(file_path) do |archive|\n archive.each do |file|\n next if file.name =~ /__MACOSX/ or file.name =~ /\\.DS_Store/\n destination = dir + file.name\n name = Pathname.new(file.name).cleanpath.to_s\n\n if file.directory?\n FileUtils.mkdir_p(destination)\n dirs << name\n else\n dirname = File.dirname(file.name)\n FileUtils.mkdir_p(dirname) unless File.exist?(dirname)\n open(destination, 'wb') {|f| f << file.read}\n files << name\n end\n end\n end\n\n [dirs, files]\n end", "def extract\n for file_path in @files\n if !File.directory?(file_path)\n if file_path.downcase.index('.7zip') || file_path.downcase.index('.7z') || file_path.downcase.index('.zip')\n extension = '7zip' if file_path.downcase.index('.7zip')\n extension = '7z' if file_path.downcase.index('.7z')\n extension = 'zip' if file_path.downcase.index('.zip')\n cmd = \"7za e -o#{@dir} #{file_path}\"\n #puts \"Extracting #{file_path}: #{cmd}\"\n system(cmd)\n if cmd\n if file_path.downcase.index('att')\n file_name = File.join(@dir, \"attendance_ads_#{Time.now.year}_#{Time.now.month}_#{Time.now.day}.#{extension}\")\n elsif file_path.downcase.index('enroll')\n file_name = File.join(@dir, \"enrollment_ads_#{Time.now.year}_#{Time.now.month}_#{Time.now.day}.#{extension}\")\n elsif file_path.downcase.index('ili') || file_path.downcase.index('h1n1')\n file_name = File.join(@dir, \"ili_ads_#{Time.now.year}_#{Time.now.month}_#{Time.now.day}.#{extension}\")\n else\n file_name = File.join(@dir, \"ads_#{Time.now.year}_#{Time.now.month}_#{Time.now.day}.#{extension}\")\n end\n File.rename(file_path, file_name)\n FileUtils.mv(file_name, File.join(@dir, \"archive\"))\n end\n end\n end\n end\n\n end", "def unzip\n file = self\n #destination = \"/\" + self.split(\"/\")[1..-2].join(\"/\") + \"/\"\n destination = self + \"_extracted_files/\"\n Zip::File.open(file) { |zip_file|\n zip_file.each { |f|\n f_path=File.join(destination, f.name)\n #puts f_path\n FileUtils.mkdir_p(File.dirname(f_path))\n FileUtils.rm f_path if File.exist?(f_path)\n zip_file.extract(f, f_path) #unless File.exist?(f_path)\n }\n }\n end", "def unzip\n file = self\n #destination = \"/\" + self.split(\"/\")[1..-2].join(\"/\") + \"/\"\n destination = self + \"_extracted_files/\"\n Zip::ZipFile.open(file) { |zip_file|\n zip_file.each { |f|\n f_path=File.join(destination, f.name)\n #puts f_path\n FileUtils.mkdir_p(File.dirname(f_path))\n FileUtils.rm f_path if File.exist?(f_path)\n zip_file.extract(f, f_path) #unless File.exist?(f_path)\n }\n }\n end", "def stage_unzipped(zipfile, stage_dir)\n # Unzip file to a specified directory\n Dir.mkdir stage_dir unless Dir.exist?(stage_dir)\n Zip::File.open(zipfile) do |z|\n z.each do |f|\n extract_path = File.join(stage_dir, f.name)\n z.extract(f, extract_path) unless File.exist?(extract_path)\n end\n end\nend", "def perform\n @extracted_files = Array.new\n @files_to_extract.each do |f|\n @extracted_files.push File.basename(@filename, '.tbz') + '/' + f\n end\n\n extract = extract_command(@basename, @extracted_files.join(' '))\n\n result = system \"cd #{@dirname} && #{extract}\"\n\n if result\n _extracted_files = @extracted_files.map{|f| File.join(@dirname, f)}\n @file_entry = FileEntry.new(@filename, Hash[@files_to_extract.zip(_extracted_files)])\n FileUtils.remove_file(@filename, true) unless keep_tbz_after_extract?\n else\n raise \"Unable to extract files '#{@files_to_extract.join(' ')}' from #{@filename}\"\n end\n\n @file_entry\n end", "def zip_files\n time = Time.now.strftime('%Y-%d-%m_%H-%M-%S')\n Archive::Zip.archive(File.join(ARCHIVE[0], ARCHIVE[1], time, ARCHIVE[2]), File.join(LOCAL_DIR, '.'))\n Dir.glob(File.join(LOCAL_DIR, FILE_EXTN)).each { |file| File.delete(file) }\n end", "def extract_files\n while file = @package_file.next_header\n if file.pathname == \"control.tar.gz\"\n control_tar_gz = Archive.read_open_memory(@package_file.read_data)\n while control_entry = control_tar_gz.next_header\n case control_entry.pathname\n when \"./control\"\n @control_file_contents = control_tar_gz.read_data\n when \"./preinst\"\n @preinst_contents = control_tar_gz.read_data\n when \"./prerm\"\n @prerm_contents = control_tar_gz.read_data\n when \"./postinst\"\n @postinst_contents = control_tar_gz.read_data\n when \"./postrm\"\n @postrm_contents = control_tar_gz.read_data\n end\n end\n end\n if file.pathname == \"data.tar.gz\"\n data_tar_gz = Archive.read_open_memory(@package_file.read_data)\n while data_entry = data_tar_gz.next_header\n # Skip dirs; they're listed with a / as the last character\n @filelist << data_entry.pathname.sub(/^\\./, \"\") unless data_entry.pathname =~ /\\/$/\n end\n end\n end\n end", "def extract\n Dir.mktmpdir do |dir|\n open_zip do |zip_file|\n zip_file.each do |entry|\n unless entry.name_is_directory?\n entry.extract(File.join(dir, File.basename(entry.name)))\n end\n end\n\n yield dir\n end\n end\n end", "def unzip\n files = {}\n unzip_dir = @fullpath[0..-5]\n FileUtils.mkpath(unzip_dir)\n Zip::File.open(@fullpath) do |zipfile|\n zipfile.each do |entry|\n next unless entry.file?\n full_source_path = \"#{unzip_dir}/#{entry.name}\"\n entry.extract(full_source_path) { true } # true for overwrite\n files[full_source_path] = entry.name\n end\n end\n files\n end", "def archive\n files.each do |path|\n path_obj = Pathname.new(path)\n path_name = path_obj.dirname.to_s\n compress = Kellerkind::Compress.new(:target_path => out,\n :source_path => path,\n :tarball_prefix => path_obj.basename.to_s)\n compress.find_at_source_path = true\n if File.exists?(path)\n Kellerkind::Process.verbose(:start_compressing)\n compress.gzip\n if File.exists?(\"#{path_name}/#{compress.tarball_name}\")\n Kellerkind::Process.verbose(:finished_compressing)\n FileUtils.mv(\"#{path_name}/#{compress.tarball_name}\",\n \"#{out}/#{compress.tarball_name}\")\n FileUtils.rm_rf(path)\n FileUtils.touch(path) if self.recreate\n end\n end\n end\n end", "def unzip_archive(archive, dest)\n # Adapted from examples at...\n # https://github.com/rubyzip/rubyzip\n # http://seenuvasan.wordpress.com/2010/09/21/unzip-files-using-ruby/\n Zip::File.open(archive) do |zf|\n zf.each do |f|\n f_path = File.join(dest, f.name)\n FileUtils.mkdir_p(File.dirname(f_path))\n zf.extract(f, f_path) unless File.exist?(f_path) # No overwrite\n end\n end\nend", "def extract\n Dir.mktmpdir do |dir|\n open_zip do |zip_file|\n zip_file.each do |entry|\n entry.extract(File.join(dir, File.basename(entry.name))) unless entry.name_is_directory?\n end\n\n yield dir\n end\n end\n end", "def extract\n base.say_status 'extract', @file\n if @zip_file\n base.exec(\"cd #{@temp_dir} ; unzip #{@file}\")\n else\n base.exec(\"cd #{@temp_dir} ; tar xvfpz #{@file}\")\n end\n \n # Remove the file\n base.destination_files.rm_rf(@file_path)\n end", "def extract src_path, dst_path = File.dirname(src_path)\n src_path = File.expand_path(src_path)\n src_name = File.basename(src_path)\n src_suffix = File.extname(src_name)\n src_prefix = File.basename(src_name, src_suffix)\n\n Dir.mktmpdir(nil, dst_path) do |tmp_dir|\n # decompress the archive\n cd tmp_dir do\n case src_name.sub(/\\.part$/, '')\n when /\\.(tar\\.gz|tar\\.Z|tgz|taz)$/i\n system 'tar', '-zxf', src_path\n\n when /\\.(tar\\.bz|tar\\.bz2|tbz|tbz2)$/i\n system 'tar', '-jxf', src_path\n\n when /\\.(tar\\.xz|txz)$/i\n system 'tar', '-Jxf', src_path\n\n when /\\.(tar|cpio|gem)$/i\n system 'tar', '-xf', src_path\n\n when /\\.(tar.lzo|tzo)$/i\n system \"lzop -xc #{src_path.inspect} | tar -xf -\"\n\n when /\\.(lzo)$/i\n system 'lzop', '-x', src_path\n\n when /\\.(gz)$/i\n system \"gunzip -c #{src_path.inspect} > #{src_prefix.inspect}\"\n\n when /\\.(bz|bz2)$/i\n system \"bunzip2 -c #{src_path.inspect} > #{src_prefix.inspect}\"\n\n when /\\.(shar)$/i\n system 'sh', src_path\n\n when /\\.(7z)$/i\n system '7zr', 'x', src_path\n\n when /\\.(zip)$/i\n system 'unzip', src_path\n\n when /\\.(jar)$/i\n system 'jar', 'xf', src_path\n\n when /\\.(rz)$/i\n ln src_path, src_name # rzip removes the archive after extraction\n system 'rzip', '-d', src_name\n\n when /\\.(rar)$/i\n system 'unrar', 'x', src_path\n\n when /\\.(ace)$/i\n system 'unace', 'x', src_path\n\n when /\\.(arj)$/i\n system 'arj', 'x', src_path\n\n when /\\.(arc)$/i\n system 'arc', 'x', src_path\n\n when /\\.(lhz|lha)$/i\n system 'lha', 'x', src_path\n\n when /\\.(a|ar)$/i\n system 'ar', '-x', src_path\n\n when /\\.(Z)$/\n system \"uncompress -c #{src_path.inspect} > #{src_prefix.inspect}\"\n\n when /\\.(z)$/\n system \"pcat #{src_path.inspect} > #{src_prefix.inspect}\"\n\n when /\\.(zoo)$/i\n system 'zoo', 'x//', src_path\n\n when /\\.(cab)$/i\n system 'cabextract', src_path\n\n when /\\.(deb)$/i\n system 'ar', 'x', src_path\n\n when /\\.(rpm)$/i\n system \"rpm2cpio #{src_path.inspect} | cpio -i --make-directories\"\n\n else\n warn \"I do not know how to extract #{src_path.inspect}\"\n end\n end\n\n # clean any mess made by decompression\n manifest = Dir.new(tmp_dir).entries - %w[ . .. ]\n\n if manifest.length == 1 # there was no mess!\n adj_dst = File.join(dst_path, manifest.first)\n adj_src = File.join(tmp_dir, manifest.first)\n else\n adj_src = tmp_dir\n adj_dst = File.join(dst_path, src_name[/.*(?=\\..*?)/])\n end\n\n adj_dst << \"+#{Time.now.to_i}\" until\n not File.exist? adj_dst and\n mv(adj_src, adj_dst, :force => true)\n\n touch tmp_dir # give Dir.mktmpdir() something to remove\n\n adj_dst\n end\nend", "def decompress_files(compressed_files=[], dir = decompressed_spool_dir )\n\n files = []\n\n compressed_files.each do |file|\n Zip::Archive.open(file) do |ar|\n ar.each do |zf|\n if zf.directory?\n FileUtils.mkdir_p(zf.name)\n else\n dirname = File.dirname(zf.name)\n FileUtils.mkdir_p(dirname) unless File.exist?(dirname)\n output_file = File.join(dir, zf.name)\n open(output_file, 'wb') do |f|\n f << zf.read\n end\n files << output_file\n end\n end\n end\n # TODO: Delete processed file\n end\n\n files\n end", "def extract_zip\n # FileUtils.rmtree(@extract_folder)\n zip_files = Dir[\"#{@download_folder}/*.zip\"]\n\n zip_files.each do |zip|\n Zip::File.open(zip) do |zip_file|\n zip_file.each do |f|\n file_name = f.name\n FileUtils.mkdir_p(\"#{@extract_folder}/#{File.dirname(file_name)}\")\n\n # doesn't extract empty files or files with fake locale\n if f.size && f.size != 0\n # if true overwrite existing files with same name\n zip_file.extract(f, \"#{@extract_folder}/#{f.name}\") { true }\n end\n end\n end\n delete_zip(zip)\n end\n end", "def unpack_zip_on_darwin archive, destination, clobber\n # Unzipping on OS X\n FileUtils.makedirs destination\n zip_dir = File.expand_path File.dirname(archive)\n zip_name = File.basename archive\n output = File.expand_path destination\n # puts \">> zip_dir: #{zip_dir} zip_name: #{zip_name} output: #{output}\"\n %x(cd #{zip_dir};unzip #{zip_name} -d #{output})\n end", "def extract (file = nil)\n export_path = archive.path.gsub('.zip', '_content')\n\n Zip::ZipFile.open(file.path) { |zip_file|\n zip_file.each { |image|\n image_path = File.join(export_path, image.name)\n FileUtils.mkdir_p(File.dirname(image_path))\n unless File.exist?(image_path)\n zip_file.extract(image, image_path)\n photo = photos.build\n photo.image = File.open(image_path)\n photo.save\n File.delete(image_path)\n end\n }\n }\n # clean up source files, but leave the zip\n FileUtils.remove_dir(export_path)\n end", "def compressFiles\n Dir.chdir(\"#{@outputDir}/RDPsummary\")\n #system(\"tar -zcf #{@sampleSetName1}.tar.gz * --exclude=*.log --exclude=*.sra --exclude=*.sff --exclude=*.local.metadata\")\n system(\"tar czf class.result.tar.gz class\")\n system(\"tar czf domain.result.tar.gz domain\")\n system(\"tar czf family.result.tar.gz family\")\n system(\"tar czf genus.result.tar.gz genus\")\n system(\"tar czf order.result.tar.gz order\")\n system(\"tar czf phyla.result.tar.gz phyla\")\n system(\"tar czf species.result.tar.gz species\")\n system(\"tar czf pdf.result.tar.gz 'find . -name `*.pdf`'\")\n Dir.chdir(@scratch)\n end", "def extract\n # Only used by tar\n compression_switch = \"\"\n compression_switch = \"z\" if downloaded_file.end_with?(\"gz\")\n compression_switch = \"--lzma -\" if downloaded_file.end_with?(\"lzma\")\n compression_switch = \"j\" if downloaded_file.end_with?(\"bz2\")\n compression_switch = \"J\" if downloaded_file.end_with?(\"xz\")\n\n if Ohai[\"platform\"] == \"windows\"\n if downloaded_file.end_with?(*TAR_EXTENSIONS) && source[:extract] != :seven_zip\n returns = [0]\n returns << 1 if source[:extract] == :lax_tar\n\n shellout!(\"tar #{compression_switch}xf #{downloaded_file} --force-local -C#{project_dir}\", returns: returns)\n elsif downloaded_file.end_with?(*COMPRESSED_TAR_EXTENSIONS)\n Dir.mktmpdir do |temp_dir|\n log.debug(log_key) { \"Temporarily extracting `#{safe_downloaded_file}' to `#{temp_dir}'\" }\n\n shellout!(\"7z.exe x #{safe_downloaded_file} -o#{windows_safe_path(temp_dir)} -r -y\")\n\n fname = File.basename(downloaded_file, File.extname(downloaded_file))\n fname << \".tar\" if downloaded_file.end_with?(\"tgz\", \"txz\")\n next_file = windows_safe_path(File.join(temp_dir, fname))\n\n log.debug(log_key) { \"Temporarily extracting `#{next_file}' to `#{safe_project_dir}'\" }\n shellout!(\"7z.exe x #{next_file} -o#{safe_project_dir} -r -y\")\n end\n else\n shellout!(\"7z.exe x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\")\n end\n elsif downloaded_file.end_with?(\".7z\")\n shellout!(\"7z x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\")\n elsif downloaded_file.end_with?(\".zip\")\n shellout!(\"unzip #{safe_downloaded_file} -d #{safe_project_dir}\")\n else\n shellout!(\"#{tar} #{compression_switch}xf #{safe_downloaded_file} -C#{safe_project_dir}\")\n end\n end", "def unzip_file\n info(\"Extracting file #{@filename} started.\")\n\n Zip::File.open(local_file) do |zip_file|\n zip_file.each do |f|\n info(\"Processing zipped file #{f}\")\n f_path = File.join(DATA_DIR, f.name)\n FileUtils.mkdir_p(File.dirname(f_path))\n zip_file.extract(f, f_path) unless File.exist?(f_path)\n end\n end\n\n info(\"Extracting file #{@filename} completed successfully.\")\n rescue StandardError => e\n error(\"Unable to unzip file #{@filename} due to following error occurred #{e}\")\n end", "def extract_all\n files.each do |file|\n extract file\n end\n end", "def zip_xml_files\n logger.debug('ZIPPING ALL FILES.')\n # time = Time.now.strftime('%Y-%d-%m_%H-%M-%S')\n Dir.glob(File.join(LOCAL_DIR, FILE_EXTN)).each do |file|\n list_files.push(file)\n end\n puts list_files.length\n list_files.each do |file|\n Archive::Zip.archive((file + ARCHIVE_EXTN), file) if File.extname(file).eql?('.xml')\n end\n list_files.each do |file|\n File.delete(file)\n end\n logger.debug('ALL FILES ZIPPED.')\n end", "def unpack(args)\n full_path, file = args[:full_path], args[:file]\n \n # Is unpack activated?\n if self.config[:unpack][:active]\n self.files = File.directory?(full_path) ? Unpack.runner!(full_path, self.config[:unpack]) : []\n else\n self.files = []\n end\n \n if files.any?\n self.growl(self.messages[:unpack][:title], file, :unpack); return 5\n else\n return 6\n end\n end", "def extract_data\n cmd = \"unzip -d #{DATA_DIR} -o #{DATA_PATH}\"\n system cmd\n end", "def unzip_file_with_translations(zipfile_name, dest_path, files_list, ignore_match)\n # overwrite files if they already exist inside of the extracted path\n Zip.on_exists_proc = true\n\n # files that exists in archive and doesn't match current project configuration\n unmatched_files = []\n\n Zip::File.open(zipfile_name) do |zipfile|\n zipfile.select { |zip_entry| zip_entry.file? }.each do |f|\n filename = f.name\n if @branch_name and @base_path_contains_branch_subfolders\n # strip branch from filename\n filename = f.name.sub(File.join(@branch_name, '/'), '')\n end\n\n # `f' - relative path in archive\n file = files_list[filename]\n if file\n fpath = File.join(dest_path, file)\n FileUtils.mkdir_p(File.dirname(fpath))\n puts \"Extracting: `#{file}'\"\n zipfile.extract(f, fpath)\n else\n unmatched_files << f\n end\n end\n end\n\n unless unmatched_files.empty? or ignore_match\n puts \"Warning: Downloaded translations do not match current project configuration. The following files will be omitted:\"\n unmatched_files.each { |file| puts \" - `#{file}'\" }\n end\nend", "def untar!(tarball)\n system(\"tar -C #{@tmp} -xzf #{tarball}\")\n end", "def extract_to!(directory, flags: DEFAULT_FLAGS)\n each_entry.map do |entry|\n raise Danbooru::Archive::Error, \"Can't extract archive containing absolute path (path: '#{entry.pathname_utf8}')\" if entry.pathname_utf8.starts_with?(\"/\")\n raise Danbooru::Archive::Error, \"'#{entry.pathname_utf8}' is not a regular file\" if !entry.file?\n\n path = \"#{directory}/#{entry.pathname_utf8}\"\n entry.extract!(path, flags: flags)\n end\n end" ]
[ "0.62768906", "0.61366785", "0.598008", "0.5943704", "0.59319764", "0.59226274", "0.58503044", "0.5823995", "0.5799449", "0.57321995", "0.5729694", "0.5718601", "0.5682455", "0.567469", "0.5632223", "0.56250256", "0.557718", "0.5564379", "0.5561875", "0.55276746", "0.5514639", "0.54860157", "0.5480269", "0.547596", "0.5452019", "0.54390144", "0.54367244", "0.5427602", "0.5426026", "0.5406762" ]
0.70867246
0