query
stringlengths 7
9.55k
| document
stringlengths 10
363k
| metadata
dict | negatives
sequencelengths 0
101
| negative_scores
sequencelengths 0
101
| document_score
stringlengths 3
10
| document_rank
stringclasses 102
values |
---|---|---|---|---|---|---|
GET /list_invites/1 GET /list_invites/1.json | def show
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index_invites\n puts \"user: #{@current_user.json_hash[:id]}\"\n dinners = []\n @dinners = @current_user.invited_dinners\n @dinners.each do |dinner|\n dinners << dinner.all_info\n end\n render json: dinners\n end",
"def index\n @invites = current_user.invites\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n session[:new_invite_error] = nil\n session[:new_invite_error_url] = nil\n end",
"def index\n @list_invites = ListInvite.all\n end",
"def show\n @invites = Invite.all\n end",
"def index\n\t\t@guild_invites = @guild.invites.order(\"id DESC\")\n\tend",
"def index\n @inviteds = Invited.all\n end",
"def invites\n raise 'Tried to request invites from a non-server channel' unless server\n\n invites = JSON.parse(API::Channel.invites(@bot.token, @id))\n invites.map { |invite_data| Invite.new(invite_data, @bot) }\n end",
"def invitations\n\t\t@invits = current_user.receive_invites.order(\"id DESC\")\n\tend",
"def show\n @invite_list = InviteList.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite_list }\n end\n end",
"def received_invitations\n user = User.find(params[:user_id])\n @invitations = user.invitations\n\n render json: @invitations\n end",
"def index\n if params[:story_id].present?\n @invitations = Story.find(params[:story_id]).invitations\n else\n @invitations = Invitation.find_by_email(@current_user.email)\n end\n render json: @invitations\n end",
"def dogwalker_invited\n #@invitations = Invitation.invited_clients_email(params[:email]).select(:email)\n @invitations = Invitation.invitees(params[:email]).select(:email)\n logger.debug(\"@invitations.to_json = \" + @invitations.to_json)\n render json: {:invitations => @invitations }, :layout => false\n end",
"def index\n @invitations = Invitation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invitations }\n end\n end",
"def view_invitations\n @invitations = Invitation.all(:conditions => ['status = ?', 'pending'])\n end",
"def invitestatuslist\n @inviteStatus = InviteStatus.find :all\n render :layout => 'plain'\n end",
"def index\n @invites = Invite.find(:all, :conditions => \"to_user_id = #{current_user.id} or to_email = '#{current_user.email}'\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invites }\n end\n end",
"def index\n @invitations = Invitation.all\n\n render json: @invitations, except: [:created_at, :updated_at], \n include: [:event => {include: [:host => {except: [:password_digest, :created_at, :updated_at]}]}]\n end",
"def index\n @invitations = Invitation.all\n respond_with(@invitations)\n end",
"def invited_users\n render json: @moot.list_users_can_vote\n end",
"def index\n @invitations = Invitation.all\n end",
"def index\n @invitations = Invitation.all\n end",
"def index\n @invitations = Invitation.all\n end",
"def invitestatuslist\n @inviteStatus = InviteStatus.all\n render :layout => 'plain'\n end",
"def index\n @team_invites = TeamInvite.where(team: current_team)\n end",
"def index\n @title = 'Invitations'\n @invitations = Invitation.all\n\n respond_to do |format|\n format.html # index.html.haml\n format.json { render json: @invitations }\n end\n end",
"def index\n # @invitations = Invitation.all\n end",
"def invitations\n @invitations = Invitation.pending_by_user(current_user.id)\n\n respond_to do |format|\n format.html\n end\n end",
"def index\n @invites = current_user.invites.where(is_declined: nil).all\n end",
"def invitations\n res = []\n\n tmp = GoodData.get @json['project']['links']['invitations']\n tmp['invitations'].each do |invitation|\n res << GoodData::Invitation.new(invitation)\n end\n\n res\n end",
"def new_invites\n self.invites.all(:hide => false)\n end",
"def index\n @invitees = Invitee.all\n end",
"def index\n @invitees = Invitee.all\n end",
"def group_invites\n @invites = GroupsController.group_invites current_user\n end",
"def invites(auth, server_id)\n MijDiscord::Core::API.request(\n :guilds_sid_invites,\n server_id,\n :get,\n \"#{MijDiscord::Core::API::APIBASE_URL}/guilds/#{server_id}/invites\",\n Authorization: auth\n )\n end",
"def index\n @invitations = Invitation.where(organization_id: current_user.organization_id).all\n end",
"def index\n @invitations = Invitation.where(receiver_id: current_user.id)\n end",
"def index\n @invite_requests = InviteRequest.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invite_requests }\n end\n end",
"def invite_detail\n service_response = AdminManagement::AdminUser::GetInviteDetail.new(params).perform\n render_api_response(service_response)\n end",
"def index\n @invitations = Invitation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitations }\n end\n end",
"def index\n @team = Team.find_by_id(params[:team_id])\n @invite_requests = @team.invite_requests\n end",
"def pending_invites\n list = []\n pending_contacts.links(:class=>\"s3d-bold s3d-regular-light-links\", :title=>/View/).each { |link| list << link.text }\n return list\n end",
"def sent_invitations\n user = User.find(params[:user_id])\n @invitations = Invitation.created_by_user(user)\n\n render json: @invitations\n end",
"def index\n @invstatuses = Invstatus.all\n end",
"def index\n @invitations = @event.invitations.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitations }\n end\n end",
"def show\n @invite_status = InviteStatus.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite_status }\n end\n end",
"def index\n @invitations = Invitation.find(:all)\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @invitations.to_xml }\n end\n end",
"def show\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite }\n end\n end",
"def show\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite }\n end\n end",
"def show\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite }\n end\n end",
"def show\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite }\n end\n end",
"def get_mission_invites\n\t#get all missions of user with invitaion_status = pending\n user = User.exists? (params[:user_id])\n\tif user\n\t\tmissions = user.missions.references( :user_missions).select('missions.id, missions.title, user_missions.invitation_time').where( user_missions:{ invitation_status: PENDING_MESA_INVITATION})\n\t\trespond_to do |format|\n\t\t format.json {render :json=> {:mesa_invites=> missions, :status => true} }\n\t\tend\n else\n\t respond_to do |format|\n\t\t format.json {render :json=> {:error=>'No user exists with id' , :status => false} }\n\t end\n\tend\n end",
"def index\n @invts = Invt.all\n end",
"def index\n @user_invitations = UserInvitation.all\n end",
"def index\n @invites = current_user.recieved_team_requests\n @sent = current_user.sent_team_requests\n end",
"def index\n @invitecodes = Invitecode.all\n end",
"def index\n @user = User.find(params[:user_id]) \n @invitations = @user.invitations\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @invitations.to_xml }\n end\nend",
"def show\n user = User.find_by(id: params[:id]) #should use session id\n if user\n invitations = user.invitations\n if invitations\n render json: invitations, status: :ok\n else\n head :no_content\n end\n else\n render json: {error: \"User not found\"}, status: :not_found\n end\n end",
"def index\n # LE TEMPS DE ...\n if self.admin?\n @invites = Invite.all\n elsif self.check_user && self.check_no_guild\n @invites = Invite.where(:user_id => session[:user_id])\n elsif self.check_user && self.check_is_guild_owner\n @invites = Invite.where(:guild_id => @guild[:id])\n end\n end",
"def new\n @invite_list = InviteList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invite_list }\n end\n end",
"def index\n @invited_fiends = InvitedFiend.all\n end",
"def index\n @invs = Inv.all\n end",
"def index\n @os_groups_invites = OsGroupsInvite.all\n end",
"def index\n @friend_invites = FriendInvite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @friend_invites }\n end\n end",
"def index\n @teams = current_user.teams\n\n @team_invitations = current_user.team_invitations_as_receiver\n end",
"def index\n\n @emails = Email.all\n #redirect_to invites_path\n\n end",
"def index\n\t\t@users = Invitation.pending_users(params[:page])\n\tend",
"def index\n invitations = Invitation.where('email = ? AND status = ?', @current_user.email, 'pending')\n invitations_array = []\n\n invitations.each do |inv|\n user = User.find(inv.from_user)\n user_hash = { :id => @current_user.id, :email => user.email, :first_name => user.user_info.first_name, :last_name => user.user_info.last_name }\n\n project = Project.find(inv.project_id)\n project_hash = { :id => project.id , :project_title => project.title, :project_profile => inv.project_profile_id }\n\n invitations_array << { :id => inv.id, :user => user_hash, :project => project_hash, :date => \"#{l inv.created_at, format: :long}\" }\n end\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { render json: invitations_array }\n end\n end",
"def index\n if params[:admin] == \"1\"\n @invites = Invite.all\n else\n render file: \"#{Rails.root}/public/403.html\", status: 403, layout: false\n end\n end",
"def get_unissued_invites()\n User.find(session[:user_id]).unissued_invites\n end",
"def invites\n user = current_user\n\n # Query to get only not yet accepted trips associated wiht the current user\n @trips = Trip.joins(:user_trips).where(user_trips: { accepted: false }).where(user_trips: { user_id: user.id })\n render json: @trips\n end",
"def show\n @invite = @event.invites.find(params[:id])\n end",
"def index\n @members = Member.members\n @participants = Member.participants\n @invited_count = Member.count\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @members }\n end\n end",
"def index\n @invoices = @user.invoices.all\n render json: @invoices, status: :ok\n end",
"def index\n @mammon_invite_records = Mammon::InviteRecord.all\n end",
"def get_user_invitations(filter: {}, includes: nil, limit: nil, sort: nil)\n params = users_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)\n users_request_client.get(\"userInvitations\", params)\n end",
"def invitations_list_with_http_info(account_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: InvitationsApi.invitations_list ...'\n end\n # verify the required parameter 'account_id' is set\n if @api_client.config.client_side_validation && account_id.nil?\n fail ArgumentError, \"Missing the required parameter 'account_id' when calling InvitationsApi.invitations_list\"\n end\n # resource path\n local_var_path = '/accounts/{account_id}/invitations'.sub('{' + 'account_id' + '}', CGI.escape(account_id.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'per_page'] = opts[:'per_page'] if !opts[:'per_page'].nil?\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n header_params[:'X-PhraseApp-OTP'] = opts[:'x_phrase_app_otp'] if !opts[:'x_phrase_app_otp'].nil?\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<Invitation>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['Basic', 'Token']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: InvitationsApi#invitations_list\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n response = ::Phrase::Response.new(data, headers)\n return response, status_code, headers\n end",
"def index\n @invitaciones = Invitacione.all\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def index\n @invitados = Invitado.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitados }\n end\n end",
"def index\n @events = Event.where({ user_id: current_user.id }).order(created_at: :desc)\n @invitations = EventUser.where({ number: current_user.phone }).map { |invite| invite.event }\n \n end",
"def all_inviters(page = nil, per_page = nil)\n pipeline = [\n { '$project' =>\n { _id: 0,\n f_id: 1,\n invitable_id: 1,\n invitable_type: 1\n }\n },\n {\n '$match' => {\n 'invitable_id' => self.id,\n 'invitable_type' => self.class.name.split('::').last\n }\n }\n ]\n\n if page && per_page\n pipeline << { '$skip' => (page * per_page) }\n pipeline << { '$limit' => per_page }\n end\n\n pipeline << { '$project' => { f_id: 1 } }\n\n command = {\n aggregate: 'invits',\n pipeline: pipeline\n }\n\n if defined?(Mongoid)\n db = Mongoid.default_session\n elsif defined?(MongoMapper)\n db = MongoMapper.database\n end\n\n users_hash = db.command(command)['result']\n\n ids = users_hash.map {|e| e['f_id']}\n\n User.where(id: { '$in' => ids }).all.entries\n end",
"def index\n @emails = current_user.emails\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @emails }\n end\n end",
"def index\n # session[:user_id] = nil\n # binding.pry\n @user = User.new\n @invitations = Invitation.where(email: session[:user_email])\n @num_of_invites = @invitations.length\n end",
"def index\n @emails = @user.emails\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @emails }\n end\n end",
"def index\n @emails = @user.emails\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @emails }\n end\n end",
"def accepted_invites\n since = Time.zone.now - params[:days].to_i.days\n count = GroupInvitation.accepted\n .where('created_at > ?', since)\n .count\n respond_with json_response('accepted_invites', count)\n end",
"def show\n #@trips = Trip.find params[:user_id]\n @user = User.find(params[:id])\n @invitations = Invitation.where(email: session[:user_email])\n @num_of_invites = @invitations.length\n end",
"def index\n\t\t@events = Event.where(\"creator_id = ?\", current_user.id)\n\t\tInvitation.where(\"email = ? and accepted = ?\", current_user.email, true).each do |invitation|\n\t\t\t@events << invitation.event\n\t\tend\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @events }\n end\n end",
"def getInvited\n rsvpInvited = []\n Invitation.where(\"study_session_id = '#{self.id}' AND status = 'invited'\").each do |invitation|\n rsvpInvited.push(User.where(\"id = '#{invitation.user_id}'\").first)\n end\n return rsvpInvited\n end",
"def index\n @invitations = @event.invitations.to_a\n if @invitations.empty?\n redirect_to new_page_event_invitation_path(@page, @event)\n return\n end\n @summary = Invitation.summarize(@invitations)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitations }\n end\n end",
"def invite\n @data['invite']\n end",
"def invite\n @obj['invite']\n end",
"def get_public_dashboard_invitations(token, opts = {})\n data, _status_code, _headers = get_public_dashboard_invitations_with_http_info(token, opts)\n data\n end",
"def show\n @users = User.where(:invite_code => @invitecode.name)\n\n end"
] | [
"0.783392",
"0.783392",
"0.783392",
"0.7665716",
"0.7665716",
"0.7665716",
"0.7665716",
"0.7665716",
"0.7593002",
"0.7571785",
"0.748109",
"0.7428276",
"0.7377974",
"0.7314764",
"0.72087216",
"0.7208569",
"0.71678585",
"0.71645445",
"0.71438724",
"0.70629054",
"0.7059363",
"0.70209545",
"0.6991008",
"0.6937346",
"0.69228876",
"0.6850015",
"0.6831501",
"0.6821902",
"0.6821902",
"0.6821902",
"0.68074477",
"0.68044454",
"0.6797346",
"0.6787369",
"0.67827946",
"0.6776688",
"0.67708683",
"0.67454064",
"0.6692249",
"0.6692249",
"0.66886485",
"0.6687975",
"0.6616087",
"0.6591916",
"0.65897906",
"0.65660024",
"0.65417206",
"0.651825",
"0.6490246",
"0.6483779",
"0.6477711",
"0.64728075",
"0.64712876",
"0.64514613",
"0.6426008",
"0.6426008",
"0.6426008",
"0.6426008",
"0.6416794",
"0.64132863",
"0.64103746",
"0.63767874",
"0.63701046",
"0.6357386",
"0.6273845",
"0.6270045",
"0.6248812",
"0.6239597",
"0.62328935",
"0.62273514",
"0.6224696",
"0.62018746",
"0.6200019",
"0.6191847",
"0.6191262",
"0.6158877",
"0.6152909",
"0.61191916",
"0.6111112",
"0.6102814",
"0.6093886",
"0.6080275",
"0.607757",
"0.6042732",
"0.6031666",
"0.6018681",
"0.60173196",
"0.60079664",
"0.6004743",
"0.59881157",
"0.59836644",
"0.59836644",
"0.5970049",
"0.5964283",
"0.59633106",
"0.59350854",
"0.59050715",
"0.5903621",
"0.58827704",
"0.5871265",
"0.5869728"
] | 0.0 | -1 |
POST /list_invites POST /list_invites.json | def create
@list_invite = ListInvite.new(list_invite_params.merge(user_id: current_user.id))
respond_to do |format|
if @list_invite.save
format.html { redirect_to lists_path, notice: 'List invite was successfully created.' }
format.json { render action: 'show', status: :created, location: @list_invite }
else
format.html { render action: 'new' }
format.json { render json: @list_invite.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @list_invites = ListInvite.all\n end",
"def index\n @invites = current_user.invites\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n session[:new_invite_error] = nil\n session[:new_invite_error_url] = nil\n end",
"def invites\n raise 'Tried to request invites from a non-server channel' unless server\n\n invites = JSON.parse(API::Channel.invites(@bot.token, @id))\n invites.map { |invite_data| Invite.new(invite_data, @bot) }\n end",
"def index_invites\n puts \"user: #{@current_user.json_hash[:id]}\"\n dinners = []\n @dinners = @current_user.invited_dinners\n @dinners.each do |dinner|\n dinners << dinner.all_info\n end\n render json: dinners\n end",
"def index\n @inviteds = Invited.all\n end",
"def index\n\t\t@guild_invites = @guild.invites.order(\"id DESC\")\n\tend",
"def invitations\n\t\t@invits = current_user.receive_invites.order(\"id DESC\")\n\tend",
"def dogwalker_invited\n #@invitations = Invitation.invited_clients_email(params[:email]).select(:email)\n @invitations = Invitation.invitees(params[:email]).select(:email)\n logger.debug(\"@invitations.to_json = \" + @invitations.to_json)\n render json: {:invitations => @invitations }, :layout => false\n end",
"def show\n @invites = Invite.all\n end",
"def received_invitations\n user = User.find(params[:user_id])\n @invitations = user.invitations\n\n render json: @invitations\n end",
"def group_invites\n @invites = GroupsController.group_invites current_user\n end",
"def new_invites\n self.invites.all(:hide => false)\n end",
"def invites(auth, server_id)\n MijDiscord::Core::API.request(\n :guilds_sid_invites,\n server_id,\n :get,\n \"#{MijDiscord::Core::API::APIBASE_URL}/guilds/#{server_id}/invites\",\n Authorization: auth\n )\n end",
"def invited_users\n render json: @moot.list_users_can_vote\n end",
"def index\n @invitations = Invitation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invitations }\n end\n end",
"def index\n if params[:story_id].present?\n @invitations = Story.find(params[:story_id]).invitations\n else\n @invitations = Invitation.find_by_email(@current_user.email)\n end\n render json: @invitations\n end",
"def invitations\n res = []\n\n tmp = GoodData.get @json['project']['links']['invitations']\n tmp['invitations'].each do |invitation|\n res << GoodData::Invitation.new(invitation)\n end\n\n res\n end",
"def invitestatuslist\n @inviteStatus = InviteStatus.find :all\n render :layout => 'plain'\n end",
"def index\n @invitations = Invitation.all\n respond_with(@invitations)\n end",
"def index\n @invitees = Invitee.all\n end",
"def index\n @invitees = Invitee.all\n end",
"def index\n @invitations = Invitation.all\n\n render json: @invitations, except: [:created_at, :updated_at], \n include: [:event => {include: [:host => {except: [:password_digest, :created_at, :updated_at]}]}]\n end",
"def index\n @invites = current_user.invites.where(is_declined: nil).all\n end",
"def index\n @invitations = Invitation.all\n end",
"def index\n @invitations = Invitation.all\n end",
"def index\n @invitations = Invitation.all\n end",
"def sent_invitations\n user = User.find(params[:user_id])\n @invitations = Invitation.created_by_user(user)\n\n render json: @invitations\n end",
"def invitestatuslist\n @inviteStatus = InviteStatus.all\n render :layout => 'plain'\n end",
"def index\n @team_invites = TeamInvite.where(team: current_team)\n end",
"def index\n # @invitations = Invitation.all\n end",
"def index\n @os_groups_invites = OsGroupsInvite.all\n end",
"def invitations\n @invitations = Invitation.pending_by_user(current_user.id)\n\n respond_to do |format|\n format.html\n end\n end",
"def index\n @title = 'Invitations'\n @invitations = Invitation.all\n\n respond_to do |format|\n format.html # index.html.haml\n format.json { render json: @invitations }\n end\n end",
"def index\n @user_invitations = UserInvitation.all\n end",
"def index\n @invite_requests = InviteRequest.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invite_requests }\n end\n end",
"def index\n @invited_fiends = InvitedFiend.all\n end",
"def accepted_invites\n since = Time.zone.now - params[:days].to_i.days\n count = GroupInvitation.accepted\n .where('created_at > ?', since)\n .count\n respond_with json_response('accepted_invites', count)\n end",
"def index\n @invts = Invt.all\n end",
"def index\n @invstatuses = Invstatus.all\n end",
"def view_invitations\n @invitations = Invitation.all(:conditions => ['status = ?', 'pending'])\n end",
"def index\n @invites = Invite.find(:all, :conditions => \"to_user_id = #{current_user.id} or to_email = '#{current_user.email}'\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invites }\n end\n end",
"def index\n @invites = current_user.recieved_team_requests\n @sent = current_user.sent_team_requests\n end",
"def index\n @invitecodes = Invitecode.all\n end",
"def index\n @team = Team.find_by_id(params[:team_id])\n @invite_requests = @team.invite_requests\n end",
"def index\n @invitations = @event.invitations.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitations }\n end\n end",
"def index\n @invitations = Invitation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitations }\n end\n end",
"def pending_invites\n list = []\n pending_contacts.links(:class=>\"s3d-bold s3d-regular-light-links\", :title=>/View/).each { |link| list << link.text }\n return list\n end",
"def index\n @invitations = Invitation.where(organization_id: current_user.organization_id).all\n end",
"def index\n @invitations = Invitation.where(receiver_id: current_user.id)\n end",
"def index\n\n @emails = Email.all\n #redirect_to invites_path\n\n end",
"def index\n @invs = Inv.all\n end",
"def show\n @invite_list = InviteList.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite_list }\n end\n end",
"def index\n @invitations = Invitation.find(:all)\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @invitations.to_xml }\n end\n end",
"def total_invites\n since = Time.zone.now - params[:days].to_i.days\n count = GroupInvitation\n .where('created_at > ?', since)\n .count\n respond_with json_response('total_invites', count)\n end",
"def invite_by_email\n\n @errors = ''\n emails = params[:emails].split(',')\n servicelisting = Servicelisting.find(params[:servicelisting_id])\n no_of_guests = servicelisting.no_of_guests.to_i\n invites = GuestList.where(:user_id => current_user.id, :product => params[:order_id])\n\n if(invites.size + emails.size <= no_of_guests)\n emails.each do |email|\n guest_list = GuestList.new({\n :email => email.strip,\n :user_id => current_user.id,\n :product => params[:order_id]\n })\n\n if guest_list.save\n Notifier.invite_friend_party(guest_list.email, params[:subject], params[:message], current_user.email).deliver\n end\n end\n else\n @errors = \"You can only invite #{no_of_guests} friends.\"\n end\n\n respond_to do |format|\n format.js\n end\n end",
"def index\n # session[:user_id] = nil\n # binding.pry\n @user = User.new\n @invitations = Invitation.where(email: session[:user_email])\n @num_of_invites = @invitations.length\n end",
"def invitations_list(account_id, opts = {})\n data, _status_code, _headers = invitations_list_with_http_info(account_id, opts)\n data\n end",
"def all_inviters(page = nil, per_page = nil)\n pipeline = [\n { '$project' =>\n { _id: 0,\n f_id: 1,\n invitable_id: 1,\n invitable_type: 1\n }\n },\n {\n '$match' => {\n 'invitable_id' => self.id,\n 'invitable_type' => self.class.name.split('::').last\n }\n }\n ]\n\n if page && per_page\n pipeline << { '$skip' => (page * per_page) }\n pipeline << { '$limit' => per_page }\n end\n\n pipeline << { '$project' => { f_id: 1 } }\n\n command = {\n aggregate: 'invits',\n pipeline: pipeline\n }\n\n if defined?(Mongoid)\n db = Mongoid.default_session\n elsif defined?(MongoMapper)\n db = MongoMapper.database\n end\n\n users_hash = db.command(command)['result']\n\n ids = users_hash.map {|e| e['f_id']}\n\n User.where(id: { '$in' => ids }).all.entries\n end",
"def index\n # LE TEMPS DE ...\n if self.admin?\n @invites = Invite.all\n elsif self.check_user && self.check_no_guild\n @invites = Invite.where(:user_id => session[:user_id])\n elsif self.check_user && self.check_is_guild_owner\n @invites = Invite.where(:guild_id => @guild[:id])\n end\n end",
"def index\n invitations = Invitation.where('email = ? AND status = ?', @current_user.email, 'pending')\n invitations_array = []\n\n invitations.each do |inv|\n user = User.find(inv.from_user)\n user_hash = { :id => @current_user.id, :email => user.email, :first_name => user.user_info.first_name, :last_name => user.user_info.last_name }\n\n project = Project.find(inv.project_id)\n project_hash = { :id => project.id , :project_title => project.title, :project_profile => inv.project_profile_id }\n\n invitations_array << { :id => inv.id, :user => user_hash, :project => project_hash, :date => \"#{l inv.created_at, format: :long}\" }\n end\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { render json: invitations_array }\n end\n end",
"def index\n @teams = current_user.teams\n\n @team_invitations = current_user.team_invitations_as_receiver\n end",
"def index\n @mammon_invite_records = Mammon::InviteRecord.all\n end",
"def new\n @invite_list = InviteList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invite_list }\n end\n end",
"def invites\n user = current_user\n\n # Query to get only not yet accepted trips associated wiht the current user\n @trips = Trip.joins(:user_trips).where(user_trips: { accepted: false }).where(user_trips: { user_id: user.id })\n render json: @trips\n end",
"def index\n @friend_invites = FriendInvite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @friend_invites }\n end\n end",
"def invite_detail\n service_response = AdminManagement::AdminUser::GetInviteDetail.new(params).perform\n render_api_response(service_response)\n end",
"def invitable_users\n @title = \"Invitar usuario\"\n @invitable_users = GetInvitableUsers.call(@previa_group)\n end",
"def index\n @user = User.find(params[:user_id]) \n @invitations = @user.invitations\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @invitations.to_xml }\n end\nend",
"def index\n @invoices = @user.invoices.all\n render json: @invoices, status: :ok\n end",
"def index\n\t\t@users = Invitation.pending_users(params[:page])\n\tend",
"def index\n @invitations = @event.invitations.to_a\n if @invitations.empty?\n redirect_to new_page_event_invitation_path(@page, @event)\n return\n end\n @summary = Invitation.summarize(@invitations)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitations }\n end\n end",
"def index\n @invitados = Invitado.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @invitados }\n end\n end",
"def index\n\t\t@events = Event.where(\"creator_id = ?\", current_user.id)\n\t\tInvitation.where(\"email = ? and accepted = ?\", current_user.email, true).each do |invitation|\n\t\t\t@events << invitation.event\n\t\tend\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @events }\n end\n end",
"def index\n @members = Member.members\n @participants = Member.participants\n @invited_count = Member.count\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @members }\n end\n end",
"def index\n @invitaciones = Invitacione.all\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def create\n\t\tif params[:remove_invites]\n\t\t\tUser.remove_all_invitations\n flash[:notice] = \"Invitation limit updated.\"\n redirect_to admin_users_path\n else\n\t\t\tflash.now[:error] = \"There was a problem updating the invitation limit.\"\n render :action => 'index'\n\t\tend\n\tend",
"def get_unissued_invites()\n User.find(session[:user_id]).unissued_invites\n end",
"def index\n if params[:admin] == \"1\"\n @invites = Invite.all\n else\n render file: \"#{Rails.root}/public/403.html\", status: 403, layout: false\n end\n end",
"def get_user_invitations(filter: {}, includes: nil, limit: nil, sort: nil)\n params = users_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)\n users_request_client.get(\"userInvitations\", params)\n end",
"def index\n @pending_invitations = @organization.invitations.pending\n @declined_invitations = @organization.invitations.declined\n @contributors = @organization.contributors\n @invitation = Invitation.new(organization: @organization)\n\n authorize! @invitation\n end",
"def update_invitations\n # user: nil is here to make sure invitations are linked only once\n invitations << Invitation.where(token: invitation_token, user: nil)\n end",
"def index\n @invitations = Invitation.where(email: session[:user_email])\n @num_of_invites = @invitations.length\n @invitation = Invitation.new\n @trips = Trip.joins(:trip_user_lists).where('trip_user_lists.user_id' => session[:user_id])\n end",
"def index\n # @tweets = @zombie.tweets\n @invites = @event.invites\n end",
"def list_invite_params\n params.require(:list_invite).permit(:list_id, :user_id, :email, :complete)\n end",
"def invitations_list_with_http_info(account_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: InvitationsApi.invitations_list ...'\n end\n # verify the required parameter 'account_id' is set\n if @api_client.config.client_side_validation && account_id.nil?\n fail ArgumentError, \"Missing the required parameter 'account_id' when calling InvitationsApi.invitations_list\"\n end\n # resource path\n local_var_path = '/accounts/{account_id}/invitations'.sub('{' + 'account_id' + '}', CGI.escape(account_id.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'per_page'] = opts[:'per_page'] if !opts[:'per_page'].nil?\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n header_params[:'X-PhraseApp-OTP'] = opts[:'x_phrase_app_otp'] if !opts[:'x_phrase_app_otp'].nil?\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<Invitation>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['Basic', 'Token']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: InvitationsApi#invitations_list\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n response = ::Phrase::Response.new(data, headers)\n return response, status_code, headers\n end",
"def get_public_dashboard_invitations(token, opts = {})\n data, _status_code, _headers = get_public_dashboard_invitations_with_http_info(token, opts)\n data\n end",
"def index\n @investables = Investable.all\n end",
"def create\n @invite_list = InviteList.new(params[:invite_list])\n\n respond_to do |format|\n if @invite_list.save\n format.html { redirect_to @invite_list, notice: 'Invite list was successfully created.' }\n format.json { render json: @invite_list, status: :created, location: @invite_list }\n else\n format.html { render action: \"new\" }\n format.json { render json: @invite_list.errors, status: :unprocessable_entity }\n end\n end\n end",
"def load_invitations\n @invitations ||= begin\n ids = resend_invitation_params\n ids ||= current_course.invitations.unconfirmed.select(:id)\n if ids.blank?\n []\n else\n current_course.invitations.unconfirmed.where('course_user_invitations.id IN (?)', ids)\n end\n end\n end",
"def load_invitations\n @invitations ||= begin\n ids = resend_invitation_params\n ids ||= current_course.invitations.unconfirmed.select(:id)\n if ids.blank?\n []\n else\n current_course.invitations.unconfirmed.where('course_user_invitations.id IN (?)', ids)\n end\n end\n end",
"def invite\n @invite = Invite.new\n @invite.invited_id = params[:invited_id]\n @invite.dinner_id = params[:id]\n if @invite.valid?\n @invite.save\n render json: @invite\n else\n puts @invite.errors.messages.inspect\n render status: :bad_request, json: {\n errors: @invite.errors.messages\n }\n end\n end",
"def list\n perform_request(Entities::MarketingEmail, 'newsletter/list.json')\n end",
"def set_list_invite\n @list_invite = ListInvite.find(params[:id])\n end"
] | [
"0.7562937",
"0.7562937",
"0.7562937",
"0.7562937",
"0.7562937",
"0.74954313",
"0.74954313",
"0.74954313",
"0.7424402",
"0.73826724",
"0.7326685",
"0.73035353",
"0.72660786",
"0.6934265",
"0.69220006",
"0.69176203",
"0.686093",
"0.6793714",
"0.6766695",
"0.67482245",
"0.6738669",
"0.67006236",
"0.66462547",
"0.66392463",
"0.65730155",
"0.6553398",
"0.65423816",
"0.6529913",
"0.6529913",
"0.6520614",
"0.6520376",
"0.6516813",
"0.6516813",
"0.6516813",
"0.6499959",
"0.6499261",
"0.64626354",
"0.6426566",
"0.6398312",
"0.6385609",
"0.63165927",
"0.63142073",
"0.6306354",
"0.6293341",
"0.6291688",
"0.6286162",
"0.6257651",
"0.62574834",
"0.6239839",
"0.6229219",
"0.6213445",
"0.6187588",
"0.61504596",
"0.6129352",
"0.61125654",
"0.6107211",
"0.6069142",
"0.60615724",
"0.60467446",
"0.602356",
"0.60066754",
"0.5949695",
"0.5938214",
"0.59313595",
"0.59088933",
"0.59014714",
"0.5898725",
"0.58956486",
"0.5892918",
"0.58835554",
"0.58697146",
"0.5829297",
"0.5823284",
"0.58207726",
"0.5813023",
"0.5811547",
"0.5792345",
"0.5791572",
"0.5765172",
"0.57598495",
"0.57514185",
"0.57467663",
"0.57413536",
"0.5735771",
"0.57339144",
"0.57007486",
"0.569611",
"0.5691467",
"0.5667689",
"0.56665593",
"0.5664691",
"0.5662035",
"0.56466967",
"0.5642164",
"0.56338376",
"0.56184566",
"0.5610212",
"0.5610212",
"0.56056887",
"0.55974877",
"0.5596374"
] | 0.0 | -1 |
PATCH/PUT /list_invites/1 PATCH/PUT /list_invites/1.json | def update
ListUser.create!(user: User.where(email: @list_invite.email).last, list: @list_invite.list)
respond_to do |format|
if @list_invite.update(list_invite_params)
format.html { redirect_to lists_path, notice: 'List invite was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @list_invite.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update\n @invite_list = InviteList.find(params[:id])\n\n respond_to do |format|\n if @invite_list.update_attributes(params[:invite_list])\n format.html { redirect_to @invite_list, notice: 'Invite list was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invite_list.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_invitations\n # user: nil is here to make sure invitations are linked only once\n invitations << Invitation.where(token: invitation_token, user: nil)\n end",
"def update\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n if @invite.update_attributes(params[:invite])\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n if @invite.update_attributes(params[:invite])\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n if @invite.update_attributes(params[:invite])\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_list_invite\n @list_invite = ListInvite.find(params[:id])\n end",
"def update\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n if @invite.update_attributes(params[:invite])\n format.html { redirect_to @invite, notice: (t 'invite.update') }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n if @invite.update_attributes(invite_params)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @users = User.all\n respond_to do |format|\n if @event.update(event_params.except(:invites))\n\n event_params.slice(:invites).values.each do |x|\n x.each do |y|\n if y.empty?\n else\n user = @users.find(y.to_i)\n @event.attendees << user\n end\n end\n end\n format.html { redirect_to @event, notice: 'Event was successfully updated.' }\n format.json { render :show, status: :ok, location: @event }\n else\n format.html { render :edit }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n begin\n @collection = Collection.find(params[:id])\n if params[:collection][:invite_only] && params[:invitations]\n @collection.invited_user_ids = params[:invitations][:user_ids] \n end\n @collection.assign_attributes(params[:collection])\n\n @collection.transaction do\n @collection.save!\n end\n\n render \"show\", handlers: [:rabl]\n \n rescue ActiveRecord::RecordInvalid => invalid\n render :json => @collection.errors.full_messages, status: 422\n end\n end",
"def update!(**args)\n @invitations = args[:invitations] if args.key?(:invitations)\n end",
"def update\n respond_to do |format|\n if @invited.update(invited_params)\n format.html { redirect_to @invited, notice: 'Invited was successfully updated.' }\n format.json { render :show, status: :ok, location: @invited }\n else\n format.html { render :edit }\n format.json { render json: @invited.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite.update(invite_params)\n format.html { redirect_to event_invites_url, notice: 'Invite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @invite_status = InviteStatus.find(params[:id])\n\n respond_to do |format|\n if @invite_status.update_attributes(params[:invite_status])\n format.html { redirect_to @invite_status, notice: 'Invite status was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invite_status.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite.update(invite_params)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite.update(invite_params)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite.update(invite_params)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { render :show, status: :ok, location: @invite }\n else\n format.html { render :edit }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite.update(invite_params)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { render :show, status: :ok, location: @invite }\n else\n format.html { render :edit }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite.update(invite_params)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { render :show, status: :ok, location: @invite }\n else\n format.html { render :edit }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite.update(invite_params)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { render :show, status: :ok, location: @invite }\n else\n format.html { render :edit }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @invite = Invite.find(params[:id])\n\n respond_to do |format|\n if @invite.update_attributes(params[:invite])\n flash[:notice] = 'Invite was successfully updated.'\n format.html { redirect_to(@invite) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @invite.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\n @invites = current_user.invites\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n session[:new_invite_error] = nil\n session[:new_invite_error_url] = nil\n end",
"def update\n @invitee = Invitee.find(params[:id])\n\n respond_to do |format|\n if @invitee.update_attributes(params[:invitee])\n format.html { redirect_to invitees_url, notice: 'Invitee was successfully updated.' }\n format.json { head :ok }\n\t\t\t\tformat.js\n else\n @age = Age.all\n @gender = Gender.all\n @status = Status.all\n @couple = Couple.all\n\t\t\t\t@hosts = InviteeHost.all\n @inviteegroup = InviteeGroup.where(:user_account_id => current_user.user_account.id)\n \n \n format.html { render action: \"edit\"}\n format.json { render json: @invitee.errors, status: :unprocessable_entity }\n\t\t\t\tformat.js\n end\n end\n end",
"def update!(**args)\n @invitations = args[:invitations] if args.key?(:invitations)\n @next_page_token = args[:next_page_token] if args.key?(:next_page_token)\n end",
"def update\n @instrulife_list = InstrulifeList.find(params[:id])\n\n respond_to do |format|\n if @instrulife_list.update_attributes(params[:instrulife_list])\n format.html { redirect_to @instrulife_list, notice: 'Instrulife list was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @instrulife_list.errors, status: :unprocessable_entity }\n end\n end\n end",
"def edit\n @invite = Invite.find(params[:id])\n end",
"def test_should_update_invite_via_API_XML\r\n get \"/logout\"\r\n put \"/invites/1.xml\", :invite => {:message => 'API Invite 1',\r\n :accepted => false,\r\n :email => 'test@email.com',\r\n :user_id => 1 }\r\n assert_response 401\r\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @invites = Invite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @invites }\n end\n end",
"def index\n @list_invites = ListInvite.all\n end",
"def update\n respond_to do |format|\n if @inv.update(inv_params)\n format.html { redirect_to @inv, notice: 'Inv was successfully updated.' }\n format.json { render :show, status: :ok, location: @inv }\n else\n format.html { render :edit }\n format.json { render json: @inv.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @email_list.update(email_list_params)\n format.html { redirect_to @email_list, notice: 'Email list was successfully updated.' }\n format.json { render :show, status: :ok, location: @email_list }\n else\n format.html { render :edit }\n format.json { render json: @email_list.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @gift = Gift.find(params[:id])\n\t@invitations = current_host.invitations\n\t@invite_hash = {}\n @invitations.each do |i| \n\t\t@invite_hash[\"#{i.party.name} | #{i.guest.name}\"] = i.id\n\tend\n\n respond_to do |format|\n if @gift.update_attributes(params[:gift])\n format.html { redirect_to(@gift, :notice => 'Gift was successfully updated.') }\n else\n format.html { render :action => \"edit\" }\n end\n end\n end",
"def update\n @invitations = Invitation.where(:specification_id => session[:specification_sel_id]).all\n \n @act.update(act_params)\n @act.docencia = params[\"doc\"]\n @act.investigacion = params[\"inv\"]\n @act.extension = params[\"ext\"]\n @act.apoyo = params[\"apoyoA\"]\n @act.responsable = @act.responsable.upcase\n @act.justificacion = @act.justificacion.upcase\n @act.providencia = @act.providencia.upcase\n respond_to do |format|\n if @act.save\n format.html { redirect_to @act, notice: 'Act was successfully updated.' }\n format.json { render :show, status: :ok, location: @act }\n else\n format.html { render :edit }\n format.json { render json: @act.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_invited\n @invited = Invited.find(params[:id])\n end",
"def list_invite_params\n params.require(:list_invite).permit(:list_id, :user_id, :email, :complete)\n end",
"def update_list\n current_path = '/api/v1/update'\n @conn.get(current_path)\n end",
"def update_list(id, list)\n record \"/todos/update_list/#{id}\", :list => list\n end",
"def update\n respond_to do |format|\n @group = @guest_list.group_id\n @assign = '0'\n if(!params[:assigned].blank?)\n @assign = params[:assigned]\n end\n if @guest_list.update(guest_list_params)\n @guest_list.update_attribute(:assigned, @assign)\n format.html { redirect_to '/invite' }\n format.json { render :show, status: :ok, location: @guest_list }\n else\n format.html { render :edit }\n format.json { render json: @guest_list.errors, status: :unprocessable_entity }\n end\n GuestList.all.each do |guest|\n if(guest.group_id == @group)\n if guest.update_attribute(:status, @guest_list.status)\n guest.update_attribute(:assigned, @assign)\n format.html { redirect_to '/invite' }\n format.json { render :show, status: :ok, location: @guest_list }\n else\n format.html { render :edit }\n format.json { render json: @guest_list.errors, status: :unprocessable_entity }\n end\n end\n end\n end\n end",
"def update\n @invite_request = InviteRequest.find(params[:id])\n\n respond_to do |format|\n if @invite_request.update_attributes(params[:invite_request])\n flash[:notice] = 'InviteRequest was successfully updated.'\n format.html { redirect_to(@invite_request) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @invite_request.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @invite_request.update(invite_request_params)\n format.html { redirect_to @invite_request, notice: 'Invite request was successfully updated.' }\n format.json { render :show, status: :ok, location: @invite_request }\n else\n format.html { render :edit }\n format.json { render json: @invite_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @email_list = EmailList.find(params[:id])\n\n respond_to do |format|\n if @email_list.update_attributes(params[:email_list])\n format.html { redirect_to(@email_list, :notice => 'Email list was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @email_list.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @activities_list.update(activities_list_params)\n format.html { redirect_to @activities_list, notice: 'Activities list was successfully updated.' }\n format.json { render :show, status: :ok, location: @activities_list }\n else\n format.html { render :edit }\n format.json { render json: @activities_list.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @maintain_invite_user = Maintain::InviteUser.find(params[:id])\n\n respond_to do |format|\n if @maintain_invite_user.update_attributes(params[:maintain_invite_user])\n format.html { redirect_to @maintain_invite_user, notice: 'Invite user was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @maintain_invite_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n inviter_mail = resource_params.delete \"invitermail\"\n \n accepted_inviter = resource_class.to_adapter.find_first(email: inviter_mail)\n \n # before inviting person gets credit for the new user: check if he is\n # really allowed to claim. Only certain vip users are allowed...\n if accepted_inviter && accepted_inviter.ability.can?(:invite, resource_class)\n self.resource = resource_class.accept_invitation!(resource_params) \n resource.invited_by = accepted_inviter\n else\n ## No discussion. User didn't have the right to invite, so show...\n flash[:error] = I18n.t(\"devise.invitations.no_authorized_inviter\")\n raise CanCan::AccessDenied\n end\n\n if resource.errors.empty?\n flash_message = resource.active_for_authentication? ? :updated : :updated_not_active \n set_flash_message :notice, flash_message\n sign_in(resource_name, resource)\n respond_with resource, :location => after_accept_path_for(resource)\n else\n respond_with_navigational(resource){ render :edit }\n end\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def index\n @invites = Invite.all\n end",
"def invited_users\n render json: @moot.list_users_can_vote\n end",
"def update\n ActiveRecord::Base.transaction do\n @invitee = @invitation.invitee\n accepted_invitees = @meeting.invitations.count { |invitation| invitation.response == \"Accepted\"}\n if @invitee==current_user && @meeting.max_size>= accepted_invitees\n if @invitation.update_attributes(invitation_update_params)\n return json_response(@invitation, :updated)\n end\n end\n end\n head :no_content\n end",
"def show\n @invite_list = InviteList.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invite_list }\n end\n end",
"def invites\n raise 'Tried to request invites from a non-server channel' unless server\n\n invites = JSON.parse(API::Channel.invites(@bot.token, @id))\n invites.map { |invite_data| Invite.new(invite_data, @bot) }\n end",
"def update_list(list_id, name)\n data = {\n list: {\n name: name\n }\n }\n rest(\"patch\", \"lists/#{list_id}\", data)\n end",
"def update\n @email_price_list = EmailPriceList.find(params[:id])\n\n if @email_price_list.update(email_price_list_params)\n head :no_content\n else\n render json: @email_price_list.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @event.update(event_params)\n format.html { redirect_to @event, notice: 'Event was successfully updated.' }\n format.json { render :show, status: :ok, location: @event }\n\n @event.invitees_email.split(',').each do | user_email |\n user = User.find_by(email: user_email)\n \n unless @event.invitees.include?(user) || @event.attendees.include?(user)\n @event.invitees << user\n end\n end\n else\n format.html { render :edit }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @invitee = Invitee.find(params[:id])\n\n respond_to do |format|\n if @invitee.update_attributes(params[:invitee])\n flash[:notice] = 'Invitee was successfully updated.'\n format.html { redirect_to(@invitee) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @invitee.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @list = current_user.lists.find(params[:id])\n @list.update_attributes(params[:list])\n respond_with(@list, :location => my_list_url(@list))\n end",
"def update\n respond_to do |format|\n if @invitee.update(invitee_params)\n format.html { redirect_to @invitee, notice: 'Invitee was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @invitee.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @invitation = Invitation.find(params[:id])\n @invitation.update_attributes(params[:invitation])\n respond_with(@invitation)\n end",
"def update\n respond_to do |format|\n if @invite.proces(confirmed_params, current_user)\n format.html { redirect_to @invite, notice: 'Invite was successfully updated.' }\n format.json { render :show, status: :ok, location: @invite }\n else\n format.html { render :edit }\n format.json { render json: @invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def dogwalker_invited\n #@invitations = Invitation.invited_clients_email(params[:email]).select(:email)\n @invitations = Invitation.invitees(params[:email]).select(:email)\n logger.debug(\"@invitations.to_json = \" + @invitations.to_json)\n render json: {:invitations => @invitations }, :layout => false\n end",
"def update\n respond_to do |format|\n if @invstatus.update(invstatus_params)\n format.html { redirect_to @invstatus, notice: 'Invstatus was successfully updated.' }\n format.json { render :show, status: :ok, location: @invstatus }\n else\n format.html { render :edit }\n format.json { render json: @invstatus.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(id, params = {})\n @client.call(method: :put, path: \"recipient-lists/#{id}\", body_values: params.slice(:name, :description, :attributes, :recipients))\n end",
"def update_list(access_token, list)\n url = Util::Config.get('endpoints.base_url') + sprintf(Util::Config.get('endpoints.list'), list.id)\n url = build_url(url)\n payload = list.to_json\n response = RestClient.put(url, payload, get_headers(access_token))\n Components::ContactList.create(JSON.parse(response.body))\n end",
"def update\n authorize @list\n\n if @list.update(list_params)\n json_response(@list.decorate, :ok)\n else\n json_response(@list.errors, :unprocessable_entity)\n end\n end",
"def invitations\n\t\t@invits = current_user.receive_invites.order(\"id DESC\")\n\tend",
"def update\n @invitado = Invitado.find(params[:id])\n\n respond_to do |format|\n if @invitado.update_attributes(params[:invitado])\n format.html { redirect_to(@invitado, :notice => 'Invitado was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @invitado.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @listed.update(listed_params)\n format.html { redirect_to session[:previous_url], notice: 'List item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @listed.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n \n @list_item = ListItem.find(params[:id])\n\n if @list_item.update(list_item_params)\n head :no_content\n else\n render json: @list_item.errors, status: :unprocessable_entity\n end\n end",
"def update\n @invitation = Invitation.with_token!(params[:id])\n\n authorize! @invitation\n\n @invitation.update_attributes(invitation_params)\n\n head 204\n end",
"def update_multiple\r\n i = InvitationEngine.new(current_user, @resource, params)\r\n i.update_multiple\r\n flash.now[:notice] = \"#{view_helpers.pluralize(i.records_count, 'invitation')} was updated.\"\r\n \r\n load_objects\r\n respond_to do |format|\r\n format.js do\r\n render :update do |page|\r\n page.reload_flashes!\r\n page.replace_html 'users_and_guests', :partial => 'users_and_guests'\r\n page.replace_html 'invitations_buttons', :partial => 'invitations/buttons'\r\n end\r\n end\r\n end\r\n end",
"def update\n params[:interview][:participant_ids].each do |participant_id|\n unless participant_id.empty?\n participant = Participant.find(participant_id)\n @interview.participants << participant\n end\n end\n respond_to do |format|\n\n if @interview.update(interview_params)\n participants = @interview.participants\n emails = []\n participants.each do |p|\n emails += [p.email]\n ReminderMailer.update_email(p.email).deliver_now\n end\n format.html { redirect_to @interview, notice: 'Interview was successfully updated.' }\n format.json { render :show, status: :ok, location: @interview }\n else\n format.html { render :edit }\n format.json { render json: @interview.errors, status: :unprocessable_entity }\n end\n end\n end",
"def received_invitations\n user = User.find(params[:user_id])\n @invitations = user.invitations\n\n render json: @invitations\n end",
"def set_invupdate\n @invupdate = Invupdate.find(params[:id])\n end",
"def update\n @call_list_membership = CallListMembership.find(params[:id])\n params[:call_list_membership][:oncall_candidate] = false if params[:call_list_membership][:oncall_candidate] == 0\n\n respond_to do |format|\n if @call_list_membership.update_attributes(params[:call_list_membership])\n format.html { redirect_to @call_list_membership, :notice => 'Call list membership was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @call_list_membership.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @linked_in_invitation = LinkedInInvitation.find(params[:id])\n\n respond_to do |format|\n if @linked_in_invitation.update_attributes(params[:linked_in_invitation])\n format.html { redirect_to @linked_in_invitation, notice: 'Linked in invitation was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @linked_in_invitation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def invite_resource\n resource_class.invite!(invite_params, current_inviter) do |invitable|\n invitable.company_id = current_user.company_id\n invitable.is_admin = true\n invitable.require_email = true\n invitable.save\n end\n end",
"def batch_update_invitees\n # 1. create\n current_invitees = Array(params[:user_ids]).map do |user_id|\n invitee = end_of_association_chain.new(user_id: user_id)\n if invitee.save\n invitee\n else\n existing_invitee = @event.invitees.where(user_id: user_id).first\n if existing_invitee\n existing_invitee\n end\n end\n end.compact\n # 2. remove non present\n @event.invitees.find_each do |invitee|\n if !current_invitees.include?(invitee)\n invitee.destroy\n end\n end\n @event.invitees.reload\n end",
"def index_invites\n puts \"user: #{@current_user.json_hash[:id]}\"\n dinners = []\n @dinners = @current_user.invited_dinners\n @dinners.each do |dinner|\n dinners << dinner.all_info\n end\n render json: dinners\n end",
"def update!(**args)\n @client = args[:client] if args.key?(:client)\n @list_update_requests = args[:list_update_requests] if args.key?(:list_update_requests)\n end",
"def associate_invites\n Invitation.where_email_matches(email)\n .where(invitee: nil)\n .update_all(invitee_id: id)\n end",
"def update\n respond_to do |format|\n if @activity_list.update(activity_list_params) & current_user.admin?\n format.html { redirect_to @activity_list, notice: 'Activity list was successfully updated.' }\n format.json { render :show, status: :ok, location: @activity_list }\n else\n format.html { render :edit }\n format.json { render json: @activity_list.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @waiting_list = WaitingList.find(params[:id])\n\n respond_to do |format|\n if @waiting_list.update_attributes(params[:waiting_list])\n format.html { redirect_to @waiting_list, notice: 'Waiting list was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @waiting_list.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_many\n if @admin_notifications.update_all(admin_notification_params)\n render json: @admin_notifications, status: :ok, location: admin_notifications_url\n else\n render json: @admin_notifications.errors, status: :unprocessable_entity\n end\n end",
"def update_many\n if @users.update_all(user_params)\n render json: @users, status: :ok, location: users_url\n else\n render json: @users.errors, status: :unprocessable_entity\n end\n end",
"def update\n @clientsOffers = ClientsOffers.find(params[:id])\n\n respond_to do |format|\n if @clientsOffers.update_attributes(params[:clientsOffers])\n format.html { redirect_to @clientsOffers, notice: 'ClientsOffers was succesfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @clientsOffers.errors, status: :unprocesable_entity }\n end\n end\n end",
"def update\n @reminder_task_list = ReminderTaskList.find(params[:id])\n\n respond_to do |format|\n if @reminder_task_list.update_attributes(params[:reminder_task_list])\n format.html { redirect_to(@reminder_task_list, :notice => 'Reminder task list was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @reminder_task_list.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @list_of_value = Irm::ListOfValue.find(params[:id])\n\n respond_to do |format|\n if @list_of_value.update_attributes(params[:irm_list_of_value])\n format.html { redirect_to({:action => \"index\"}, :notice => t(:successfully_updated)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @list_of_value.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\n @inviteds = Invited.all\n end",
"def update\n @invitacione = Invitacione.find(params[:id])\n\n respond_to do |format|\n if @invitacione.update_attributes(params[:invitacione])\n format.html { redirect_to @invitacione, :notice => 'Invitacione was successfully updated.' }\n\n else\n format.html { render :action => \"edit\" }\n\n end\n end\n end",
"def update_list(user, list, options={})\n post(\"/#{user}/lists/#{list}.json\", options)\n end",
"def update\n \n @invoice_item.update(@invoice_item)\n respond_with(@invoice)\n \n end",
"def update\n respond_to do |format|\n if @os_groups_invite.update(os_groups_invite_params)\n format.html { redirect_to @os_groups_invite, notice: 'Os groups invite was successfully updated.' }\n format.json { render :show, status: :ok, location: @os_groups_invite }\n else\n format.html { render :edit }\n format.json { render json: @os_groups_invite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def invitations\n @invitations = Invitation.pending_by_user(current_user.id)\n\n respond_to do |format|\n format.html\n end\n end",
"def new\n @invite_list = InviteList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invite_list }\n end\n end",
"def update\n @invoice = Invoice.find(params[:id])\n title=params['q_param']['title']\n total=params['q_param']['total']\n tax_rate=params['q_param']['tax_rate']\n l=params['q_param']['list']\n comment=params['q_param']['comment']\n list=Array.new\n l.keys.each do |j|\n list << [l[j][0],l[j][1],l[j][2],l[j][3]]\n end\n invoice={:title=>title,:total=>total,:list=>list,:tax_rate=>tax_rate,:comment=>comment}\n @invoice.update(invoice)\n format.json { head :no_content }\n end",
"def update\n item = @list.list_items.find(params[:id])\n\n if item.update_attributes(params[:list_item])\n render json: item\n else\n error(t('messages.list_item.errors.update'))\n end\n end"
] | [
"0.71500707",
"0.6453307",
"0.6387229",
"0.6387229",
"0.6387229",
"0.6381915",
"0.6373369",
"0.6336115",
"0.629756",
"0.62940776",
"0.6284023",
"0.62697524",
"0.62616867",
"0.6201426",
"0.61371064",
"0.61371064",
"0.6110206",
"0.6110206",
"0.6110206",
"0.6110206",
"0.6056468",
"0.605327",
"0.602383",
"0.6015202",
"0.6001725",
"0.5995778",
"0.5978191",
"0.5955302",
"0.5955302",
"0.5955302",
"0.5950314",
"0.59439766",
"0.5907507",
"0.59033686",
"0.589074",
"0.58664507",
"0.5815724",
"0.58074296",
"0.58068675",
"0.5805696",
"0.57990736",
"0.5791775",
"0.5790687",
"0.57858425",
"0.57838625",
"0.57813174",
"0.5736178",
"0.5736178",
"0.5736178",
"0.5736178",
"0.5736178",
"0.57292485",
"0.57289016",
"0.5724736",
"0.57180333",
"0.57094985",
"0.570456",
"0.5696329",
"0.5691999",
"0.5690055",
"0.56821895",
"0.5681764",
"0.5677637",
"0.5671582",
"0.5666112",
"0.5663801",
"0.5663203",
"0.5624368",
"0.5622264",
"0.5620688",
"0.5614577",
"0.55890405",
"0.558564",
"0.55804795",
"0.5573682",
"0.5571108",
"0.5565663",
"0.5565063",
"0.5563234",
"0.5558264",
"0.55514663",
"0.55512273",
"0.5547108",
"0.5545521",
"0.5534809",
"0.5534693",
"0.5534501",
"0.5531697",
"0.55292875",
"0.55259514",
"0.5521778",
"0.5507657",
"0.55053896",
"0.5504031",
"0.55009615",
"0.55004317",
"0.5496619",
"0.54836434",
"0.5483378",
"0.5482084"
] | 0.637834 | 6 |
DELETE /list_invites/1 DELETE /list_invites/1.json | def destroy
@list_invite.destroy
respond_to do |format|
format.html { redirect_to list_invites_url }
format.json { head :no_content }
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def destroy\n @invite_list = InviteList.find(params[:id])\n @invite_list.destroy\n\n respond_to do |format|\n format.html { redirect_to invite_lists_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite = Invite.find(params[:id])\n @invite.destroy\n\n respond_to do |format|\n format.html { redirect_to invites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite = Invite.find(params[:id])\n @invite.destroy\n\n respond_to do |format|\n format.html { redirect_to invites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite = Invite.find(params[:id])\n @invite.destroy\n\n respond_to do |format|\n format.html { redirect_to invites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite = Invite.find(params[:id])\n @invite.destroy\n\n respond_to do |format|\n format.html { redirect_to invites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite.destroy\n respond_to do |format|\n format.html { redirect_to invites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite.destroy\n respond_to do |format|\n format.html { redirect_to invites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite_status = InviteStatus.find(params[:id])\n @invite_status.destroy\n\n respond_to do |format|\n format.html { redirect_to invite_statuses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite = Invite.find(params[:id])\n @invite.destroy\n\n respond_to do |format|\n format.html { redirect_to(invites_url) }\n format.xml { head :ok }\n end\n end",
"def remove_invite\n @invited = Dinner.find(params[:id]).invites.find_by(invited_id: params[:user_id])\n @invited.delete\n render json: { message: 'user uninvited' }\n end",
"def destroy\n\t\tredirect_to guild_invites_url, :alert => \"Already used\" and return unless @guild.invites.find(params[:id]).state == \"waiting\"\n\t\t@guild.invites.destroy(params[:id])\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to guild_invites_url, notice: 'Invite was successfully destroyed.' }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n @invite.destroy\n respond_to do |format|\n format.html { redirect_to event_invites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite.destroy\n respond_to do |format|\n format.html { redirect_to invites_url, notice: 'Invite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite.destroy\n respond_to do |format|\n format.html { redirect_to invites_url, notice: 'Invite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite.destroy\n respond_to do |format|\n format.html { redirect_to invites_url, notice: 'Invite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite.destroy\n respond_to do |format|\n format.html { redirect_to invites_url, notice: 'Invite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invited.destroy\n respond_to do |format|\n format.html { redirect_to inviteds_url, notice: 'Invited was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite_request = InviteRequest.find(params[:id])\n @invite_request.destroy\n\n respond_to do |format|\n format.html { redirect_to(invite_requests_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @invite_request.destroy\n render :index\n\n end",
"def delete_invite(token, code)\n request(\n __method__,\n :delete,\n \"#{api_base}/invites/#{code}\",\n Authorization: token\n )\n end",
"def destroy\n @invitee.destroy\n respond_to do |format|\n format.html { redirect_to invitees_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @maintain_invite_user = Maintain::InviteUser.find(params[:id])\n @maintain_invite_user.destroy\n\n respond_to do |format|\n format.html { redirect_to maintain_invite_users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @inv.destroy\n respond_to do |format|\n format.html { redirect_to invs_url, notice: 'Inv was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitee = Invitee.find(params[:id])\n @invitee.destroy\n\n respond_to do |format|\n format.html { redirect_to(invitees_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :ok }\n end\n end",
"def delete\n\t\trender json: Investor.delete_by_id(params[:id])\n\tend",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @instrulife_list = InstrulifeList.find(params[:id])\n @instrulife_list.destroy\n\n respond_to do |format|\n format.html { redirect_to instrulife_lists_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invstatus.destroy\n respond_to do |format|\n format.html { redirect_to invstatuses_url, notice: 'Invstatus was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation.destroy\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n if self.admin? || (self.check_user && self.check_own_invite)\n @invite.destroy\n head :no_content\n else\n render json: { }, status: :unprocessable_entity\n end\n end",
"def destroy\n @inven.destroy\n respond_to do |format|\n format.html { redirect_to invens_url, notice: 'Inven was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @team_invite.destroy\n respond_to do |format|\n format.html { redirect_to team_team_invites_url, notice: 'Invite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitado = Invitado.find(params[:id])\n @invitado.destroy\n\n respond_to do |format|\n format.html { redirect_to(invitados_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @os_groups_invite.destroy\n respond_to do |format|\n format.html { redirect_to os_groups_invites_url, notice: 'Os groups invite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @linked_in_invitation = LinkedInInvitation.find(params[:id])\n @linked_in_invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to linked_in_invitations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to invitations_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @inv_x_ref = InvXRef.find(params[:id])\n @inv_x_ref.destroy\n\n respond_to do |format|\n format.html { redirect_to inv_x_refs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitee = Invitee.find(params[:id])\n\t\t@address = @invitee.address\n\t\t@address.destroy\n @invitee.destroy\n\n respond_to do |format|\n format.html { redirect_to invitees_url }\n format.json { head :ok }\n\t\t\tformat.js\n end\n end",
"def delete_list(params={})\n @obj.delete('delete', @auth.merge(params))\n end",
"def destroy\n @activities_list.destroy\n respond_to do |format|\n format.html { redirect_to activities_lists_url, notice: 'Activities list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @inv_type = InvType.find(params[:id])\n @inv_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(inv_types_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @login = Login.find(params[:id])\n #first destory invitees and responses\n r = Response.find_by_login_id(@login.id)\n r.destroy if !r.nil?\n Invitee.find(:all, :conditions => { :login_id => @login.id }).each { |i| i.destroy }\n @login.destroy\n\n respond_to do |format|\n format.html { redirect_to(logins_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to(invitations_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to(invitations_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n record = InvoiceLineItem.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 @email_list.destroy\n respond_to do |format|\n format.html { redirect_to email_lists_url, notice: 'Email list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mammon_invite_record.destroy\n respond_to do |format|\n format.html { redirect_to mammon_invite_records_url, notice: 'Invite record was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation.destroy\n respond_to do |format|\n format.html { redirect_to invitations_url, notice: 'Invitation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation.destroy\n respond_to do |format|\n format.html { redirect_to invitations_url, notice: 'Invitation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation.destroy\n respond_to do |format|\n format.html { redirect_to invitations_url, notice: 'Invitation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation.destroy\n respond_to do |format|\n format.html { redirect_to invitations_url, notice: 'Invitation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation.destroy\n respond_to do |format|\n format.html { redirect_to invitations_url, notice: 'Invitation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n authorize! :manage, @invitee\n @invitee.destroy\n respond_to do |format|\n format.html { redirect_to \"/data_curation_network/accounts\", notice: \"Account was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n result = access_token.delete(\"/api/v1/emails/#{params[:id]}\")\n display_api_response( result )\n respond_with(\"\",:location => :back)\n end",
"def destroy\n @activite = Activite.find(params[:id])\n @activite.destroy\n\n respond_to do |format|\n format.html { redirect_to activites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invoice_status = InvoiceStatus.find(params[:id])\n @invoice_status.destroy\n\n respond_to do |format|\n format.html { redirect_to invoice_statuses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n return if auth(\"website_administrator\")\n @incident = Incident.find(params[:id])\n @incident.destroy\n\n respond_to do |format|\n format.html { redirect_to incidents_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @email_list = EmailList.find(params[:id])\n @email_list.destroy\n\n respond_to do |format|\n format.html { redirect_to(email_lists_url) }\n format.xml { head :ok }\n end\n end",
"def delete(email, list_id = nil)\n query = \"email=#{CGI.escape(email)}\"\n query += \"&list_id=#{list_id}\" if list_id\n\n del \"#{@endpoint}?#{query}\", nil\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def destroy\n @invited_fiend.destroy\n respond_to do |format|\n format.html { redirect_to invited_fiends_url, notice: 'Invited fiend was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @inbox = Inbox.find(params[:id])\n @inbox.destroy\n\n respond_to do |format|\n format.html { redirect_to inboxes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @clientsOffers = ClientsOffers.find(params[:id])\n @clientsOffers.destroy\n\n respond_to do |format|\n format.html { redirect_to clientsOffers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invier_acceso = InvierAcceso.find(params[:id])\n @invier_acceso.destroy\n\n respond_to do |format|\n format.html { redirect_to(invier_accesos_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @invitation = @event.invitations.find(params[:id])\n @invitation.destroy\n @summary = Invitation.summarize(@event.invitations)\n\n respond_to do |format|\n format.html { redirect_to(page_event_invitations_path(@page, @event)) }\n format.xml { head :ok }\n format.js\n end\n end",
"def incident_delete(statuspage_id, incident_id)\n data = {}\n data['statuspage_id'] = statuspage_id\n data['incident_id'] = incident_id\n\n request :method => :post,\n :url => @url + 'incident/delete',\n :payload => data\n end",
"def destroy\n @activite = Activite.find(params[:id])\n @activite.destroy\n\n respond_to do |format|\n format.html { redirect_to(activites_url) }\n format.xml { head :ok }\n format.json {render :json => {\"success\"=>true,\"data\"=>[]}}\n \n end\n end",
"def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end",
"def delete_list(id)\n record \"/todos/delete_list/#{id}\"\n end",
"def destroy\n @invite_code = InviteCode.find(params[:id])\n @invite_code.destroy\n\n respond_to do |format|\n format.html { redirect_to(backend_privacy_path, :alert => \"Url was deleted\") }\n end\n end",
"def destroy\n @friend_invite = FriendInvite.find(params[:id])\n @friend_invite.destroy\n\n respond_to do |format|\n format.html { redirect_to(friend_invites_url) }\n format.xml { head :ok }\n end\n end",
"def delete!(id:)\n client.delete_list(id: id)\n end",
"def destroy\n @invoiceline = Invoiceline.find(params[:id])\n @invoiceline.destroy\n\n respond_to do |format|\n format.html { redirect_to(invoicelines_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @ip_list.destroy\n respond_to do |format|\n format.html { redirect_to ip_lists_url, notice: 'Ip list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ignite.destroy\n respond_to do |format|\n format.html { redirect_to ignites_url, notice: 'Ignite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = @event.invitations.find(params[:id])\n @invitation.destroy\n\n respond_to do |format|\n format.html { redirect_to(page_event_invitations_path(@page, @event)) }\n format.xml { head :ok }\n format.js\n end\n end",
"def destroy\n @activity_list.destroy\n respond_to do |format|\n format.html { redirect_to activity_lists_url, notice: 'Activity list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @guestlist.destroy\n respond_to do |format|\n format.html { redirect_to guestlists_url, notice: 'Guestlist was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @guestlist.destroy\n respond_to do |format|\n format.html { redirect_to guestlists_url, notice: 'Guestlist was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @activite.destroy\n respond_to do |format|\n format.html { redirect_to activites_url, notice: 'Activite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @guestlist.destroy\n respond_to do |format|\n format.html { redirect_to event_guestlists_path(@event), notice: 'Guest was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @inbound_email_log = InboundEmailLog.find(params[:id])\n @inbound_email_log.destroy\n\n respond_to do |format|\n format.html { redirect_to(inbound_email_logs_url) }\n format.xml { head :ok }\n end\n end",
"def deleteEntityList( gen_id, entity_id)\n params = Hash.new\n params['gen_id'] = gen_id\n params['entity_id'] = entity_id\n return doCurl(\"delete\",\"/entity/list\",params)\n end",
"def destroy\n @agent_list.destroy\n respond_to do |format|\n format.html { redirect_to agent_lists_url, notice: 'Agent list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invitation = Invitation.find(params[:id])\n @invitation.destroy\n respond_with(@invitation)\n end",
"def destroy\n @sent_list.destroy\n respond_to do |format|\n format.html { redirect_to sent_lists_url, notice: 'Sent list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n # @invoice = Invoice.find(params[:id])\n @invoice.destroy\n\n respond_to do |format|\n format.html { redirect_to invoices_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invite = Invite.find(params[:id])\n @invite.destroy\n\n respond_to do |format|\n format.html { redirect_to dwelling_path @invite.dwelling_id}\n end\n end",
"def destroy\n @invoice = Invoice.find(params[:id])\n @invoice.destroy\n\n respond_to do |format|\n format.html { redirect_to invoices_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invoice = Invoice.find(params[:id])\n @invoice.destroy\n\n respond_to do |format|\n format.html { redirect_to invoices_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invoice = Invoice.find(params[:id])\n @invoice.destroy\n\n respond_to do |format|\n format.html { redirect_to invoices_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invoice = Invoice.find(params[:id])\n @invoice.destroy\n\n respond_to do |format|\n format.html { redirect_to invoices_url }\n format.json { head :no_content }\n end\n end",
"def delete_list_member(f)\n File.open f, 'r' do |file|\n file.each do |email|\n begin\n print email\n email.chomp!\n RestClient.delete(\"https://api:key-#{API_KEY}\" \\\n \"@api.mailgun.net/v3/lists/#{LIST}@#{DOMAIN_NAME}/members/#{email}\")\n rescue\n puts \"--------\\n#{email} Not found..NEXT\\n\"\n next\n end\n end\n end\nend",
"def destroy\n render status: 200, json: @request_item.destroy\n end"
] | [
"0.7614332",
"0.7483555",
"0.7483555",
"0.7483555",
"0.7483555",
"0.7312825",
"0.7312825",
"0.72277004",
"0.72108185",
"0.71746373",
"0.7099659",
"0.7077111",
"0.7051402",
"0.7051402",
"0.7051402",
"0.7051402",
"0.6994812",
"0.6852885",
"0.68522215",
"0.6768387",
"0.6764497",
"0.6729345",
"0.67075574",
"0.6670407",
"0.6652794",
"0.66412055",
"0.66271925",
"0.66271925",
"0.66271925",
"0.66271925",
"0.66271925",
"0.6585788",
"0.658181",
"0.6549716",
"0.65492874",
"0.65111613",
"0.65046036",
"0.64596474",
"0.64373064",
"0.6408063",
"0.6384546",
"0.63704765",
"0.6363851",
"0.6334265",
"0.6322735",
"0.631141",
"0.62983626",
"0.6294178",
"0.6281727",
"0.6281727",
"0.62782645",
"0.6275478",
"0.62674564",
"0.6264162",
"0.6264162",
"0.6264162",
"0.6264162",
"0.6264162",
"0.6263515",
"0.62602484",
"0.62524086",
"0.62438524",
"0.6237015",
"0.62296784",
"0.6224172",
"0.6218372",
"0.62147963",
"0.62070537",
"0.61895066",
"0.61845434",
"0.61822504",
"0.6179141",
"0.6175968",
"0.61539406",
"0.6152775",
"0.6149158",
"0.6146263",
"0.61421746",
"0.6141092",
"0.6136255",
"0.6127628",
"0.612756",
"0.61229837",
"0.6122919",
"0.6122919",
"0.61157066",
"0.6112036",
"0.611061",
"0.610948",
"0.61081797",
"0.6101098",
"0.60938907",
"0.6090795",
"0.6078202",
"0.6072663",
"0.6072663",
"0.6072663",
"0.6072663",
"0.6061249",
"0.6060539"
] | 0.7661324 | 0 |
Use callbacks to share common setup or constraints between actions. | def set_list_invite
@list_invite = ListInvite.find(params[:id])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def setup_handler\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def workflow\n end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup\n # override and do something appropriate\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def after_set_callback; end",
"def setup\n #implement in subclass;\n end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def save_action; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def default_action; end",
"def setup(&blk)\n @setup_block = blk\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def duas1(action)\n action.call\n action.call\nend",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend"
] | [
"0.6163163",
"0.6045976",
"0.5946146",
"0.591683",
"0.5890051",
"0.58349305",
"0.5776858",
"0.5703237",
"0.5703237",
"0.5652805",
"0.5621621",
"0.54210985",
"0.5411113",
"0.5411113",
"0.5411113",
"0.5391541",
"0.53794575",
"0.5357573",
"0.53402257",
"0.53394014",
"0.53321576",
"0.53124547",
"0.529654",
"0.5296262",
"0.52952296",
"0.52600986",
"0.52442724",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.5232394",
"0.523231",
"0.5227454",
"0.52226824",
"0.52201617",
"0.5212327",
"0.52079266",
"0.52050185",
"0.51754695",
"0.51726824",
"0.51710224",
"0.5166172",
"0.5159343",
"0.51578903",
"0.51522785",
"0.5152022",
"0.51518047",
"0.51456624",
"0.51398855",
"0.5133759",
"0.5112076",
"0.5111866",
"0.5111866",
"0.5110294",
"0.5106169",
"0.509231",
"0.50873137",
"0.5081088",
"0.508059",
"0.50677156",
"0.50562143",
"0.5050554",
"0.50474834",
"0.50474834",
"0.5036181",
"0.5026331",
"0.5022976",
"0.5015441",
"0.50121695",
"0.5000944",
"0.5000019",
"0.4996878",
"0.4989888",
"0.4989888",
"0.49864885",
"0.49797225",
"0.49785787",
"0.4976161",
"0.49683493",
"0.4965126",
"0.4958034",
"0.49559742",
"0.4954353",
"0.49535993",
"0.4952725",
"0.49467874",
"0.49423352",
"0.49325448",
"0.49282882",
"0.49269363",
"0.49269104",
"0.49252945",
"0.4923091",
"0.49194667",
"0.49174926",
"0.49173003",
"0.49171105",
"0.4915879",
"0.49155936"
] | 0.0 | -1 |
Never trust parameters from the scary internet, only allow the white list through. | def list_invite_params
params.require(:list_invite).permit(:list_id, :user_id, :email, :complete)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def allow_params_authentication!; end",
"def allowed_params\n ALLOWED_PARAMS\n end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def param_whitelist\n [:role, :title]\n end",
"def expected_permitted_parameter_names; end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def valid_params_request?; end",
"def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end",
"def allowed_params\n params.require(:allowed).permit(:email)\n end",
"def permitted_params\n []\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend",
"def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end",
"def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end",
"def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end",
"def safe_params\n params.require(:user).permit(:name)\n end",
"def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def check_params; true; end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def quote_params\n params.permit!\n end",
"def valid_params?; end",
"def paramunold_params\n params.require(:paramunold).permit!\n end",
"def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend",
"def filtered_parameters; end",
"def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end",
"def filtering_params\n params.permit(:email, :name)\n end",
"def check_params\n true\n end",
"def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend",
"def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end",
"def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend",
"def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end",
"def active_code_params\n params[:active_code].permit\n end",
"def filtering_params\n params.permit(:email)\n end",
"def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end",
"def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end",
"def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end",
"def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end",
"def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end",
"def list_params\n params.permit(:name)\n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end",
"def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end",
"def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end",
"def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end",
"def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end",
"def url_whitelist; end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def admin_social_network_params\n params.require(:social_network).permit!\n end",
"def filter_params\n params.require(:filters).permit(:letters)\n end",
"def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end",
"def sensitive_params=(params)\n @sensitive_params = params\n end",
"def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end",
"def permit_request_params\n params.permit(:address)\n end",
"def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end",
"def secure_params\n params.require(:location).permit(:name)\n end",
"def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end",
"def question_params\n params.require(:survey_question).permit(question_whitelist)\n end",
"def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end",
"def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end",
"def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end",
"def backend_user_params\n params.permit!\n end",
"def url_params\n params[:url].permit(:full)\n end",
"def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end",
"def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend",
"def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end",
"def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end",
"def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end",
"def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end",
"def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end",
"def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end",
"def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end",
"def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end"
] | [
"0.6981537",
"0.67835593",
"0.6748275",
"0.67436063",
"0.6736311",
"0.65937173",
"0.6503359",
"0.6498499",
"0.6482832",
"0.6478776",
"0.645703",
"0.6439998",
"0.63802195",
"0.6377008",
"0.6366287",
"0.632018",
"0.63016284",
"0.63011277",
"0.62932974",
"0.62919617",
"0.62905645",
"0.6289235",
"0.6283876",
"0.62425834",
"0.62410337",
"0.6218672",
"0.62151134",
"0.62096137",
"0.6192354",
"0.6178057",
"0.6177618",
"0.61727077",
"0.6162073",
"0.6152049",
"0.61515594",
"0.61458135",
"0.6122875",
"0.61165285",
"0.6107696",
"0.6104097",
"0.6091097",
"0.6080201",
"0.60699946",
"0.6063739",
"0.60206395",
"0.60169303",
"0.60134894",
"0.601003",
"0.6007347",
"0.6007347",
"0.6001054",
"0.59997267",
"0.5997844",
"0.5991826",
"0.5991213",
"0.59911627",
"0.5980111",
"0.5967009",
"0.59597385",
"0.5958542",
"0.595787",
"0.5957425",
"0.59522784",
"0.5951228",
"0.59423685",
"0.5939385",
"0.5939122",
"0.5939122",
"0.59325653",
"0.5930178",
"0.59248054",
"0.59243476",
"0.59164625",
"0.59106",
"0.59101933",
"0.59084356",
"0.5905666",
"0.58975077",
"0.58974737",
"0.5895128",
"0.58946574",
"0.589308",
"0.58916",
"0.5885987",
"0.58838505",
"0.58792",
"0.58723736",
"0.58684355",
"0.58677715",
"0.5865701",
"0.5865538",
"0.5865288",
"0.586385",
"0.5862139",
"0.58614355",
"0.58593005",
"0.5857459",
"0.58541363",
"0.58536613",
"0.58520085",
"0.585011"
] | 0.0 | -1 |
Use callbacks to share common setup or constraints between actions. | def set_user
@user = User.find(params[:id])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def setup_handler\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def workflow\n end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup\n # override and do something appropriate\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def after_set_callback; end",
"def setup\n #implement in subclass;\n end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def save_action; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def default_action; end",
"def setup(&blk)\n @setup_block = blk\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def duas1(action)\n action.call\n action.call\nend",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend"
] | [
"0.6163163",
"0.6045976",
"0.5946146",
"0.591683",
"0.5890051",
"0.58349305",
"0.5776858",
"0.5703237",
"0.5703237",
"0.5652805",
"0.5621621",
"0.54210985",
"0.5411113",
"0.5411113",
"0.5411113",
"0.5391541",
"0.53794575",
"0.5357573",
"0.53402257",
"0.53394014",
"0.53321576",
"0.53124547",
"0.529654",
"0.5296262",
"0.52952296",
"0.52600986",
"0.52442724",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.5232394",
"0.523231",
"0.5227454",
"0.52226824",
"0.52201617",
"0.5212327",
"0.52079266",
"0.52050185",
"0.51754695",
"0.51726824",
"0.51710224",
"0.5166172",
"0.5159343",
"0.51578903",
"0.51522785",
"0.5152022",
"0.51518047",
"0.51456624",
"0.51398855",
"0.5133759",
"0.5112076",
"0.5111866",
"0.5111866",
"0.5110294",
"0.5106169",
"0.509231",
"0.50873137",
"0.5081088",
"0.508059",
"0.50677156",
"0.50562143",
"0.5050554",
"0.50474834",
"0.50474834",
"0.5036181",
"0.5026331",
"0.5022976",
"0.5015441",
"0.50121695",
"0.5000944",
"0.5000019",
"0.4996878",
"0.4989888",
"0.4989888",
"0.49864885",
"0.49797225",
"0.49785787",
"0.4976161",
"0.49683493",
"0.4965126",
"0.4958034",
"0.49559742",
"0.4954353",
"0.49535993",
"0.4952725",
"0.49467874",
"0.49423352",
"0.49325448",
"0.49282882",
"0.49269363",
"0.49269104",
"0.49252945",
"0.4923091",
"0.49194667",
"0.49174926",
"0.49173003",
"0.49171105",
"0.4915879",
"0.49155936"
] | 0.0 | -1 |
Only allow a trusted parameter "white list" through. | def user_params
params.permit(:first_name, :last_name, :email, :phone, :base_currency, :token_id, :balance)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def allowed_params\n ALLOWED_PARAMS\n end",
"def expected_permitted_parameter_names; end",
"def param_whitelist\n [:role, :title]\n end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def permitted_params\n []\n end",
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def filtered_parameters; end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def parameters_list_params\n params.require(:parameters_list).permit(:name, :description, :is_user_specific)\n end",
"def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def valid_params?; end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend",
"def filter_parameters; end",
"def filter_parameters; end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def check_params; true; end",
"def valid_params_request?; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end",
"def list_params\n params.permit(:name)\n end",
"def check_params\n true\n end",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def additional_permitted_params\n []\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def resource_params\n params[resource_singular_name].try(:permit, self.class.param_whitelist)\n end",
"def allow_params_authentication!; end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end",
"def paramunold_params\n params.require(:paramunold).permit!\n end",
"def param_params\n params.require(:param).permit(:param_category_id, :param_table_id, :name, :english_name, :weighting, :description)\n end",
"def quote_params\n params.permit!\n end",
"def list_params\n params.permit(:list_name)\n end",
"def allowed_params(parameters)\n parameters.select do |name, values|\n values.location != \"path\"\n end\n end",
"def all_params; end",
"def permitted_resource_params\n params[resource.object_name].present? ? params.require(resource.object_name).permit! : ActionController::Parameters.new\n end",
"def source_params\n params.require(:source).permit(all_allowed_params)\n end",
"def user_params\n end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def get_allowed_parameters\n return _get_specific_action_config(:allowed_action_parameters, :allowed_parameters)&.map(&:to_s)\n end",
"def permitted_params\n @wfd_edit_parameters\n end",
"def user_params\r\n end",
"def param_whitelist\n whitelist = [\n :comment,\n :old_progress, :new_progress,\n :metric_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:metric_id)\n end\n \n whitelist\n end",
"def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend",
"def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end",
"def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend",
"def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end",
"def get_params\n\t\t\n\t\treturn ActionController::Parameters.new(self.attributes).permit(:first_name, :last_name, :email, :provider)\n\n\tend",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end",
"def valid_parameters\n sort_symbols(@interface.allowed_parameters)\n end",
"def params_permit\n params.permit(:id)\n end",
"def allowed_params\n params.require(:allowed).permit(:email)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def filter_params\n params.permit(*resource_filter_permitted_params)\n end",
"def community_params\n params.permit(:profile_image, :name, :description, :privacy_type, :viewed_by, {tags: []}, {features: []}, {admins: []}, :members, :location, :beacon, :creator, :ambassadors, :current_events, :past_events, :feed, :category, :address, :allow_member_post_to_feed, :allow_member_post_to_events)\n end",
"def specialty_params\n\t\tparams.require(:specialty).permit(*Specialty::DEFAULT_ACCESSIBLE_ATTRIBUTES)\n\tend",
"def authorize_params\n super.tap do |params|\n %w[display scope auth_type].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n end\n end\n end\n end",
"def feature_params_filter\n params.require(:feature).permit(:name, :cat, :lower, :upper, :opts, :category, :description, :company, :active, :unit, :icon)\n end",
"def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end",
"def argument_params\n params.require(:argument).permit(:name)\n end",
"def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end",
"def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end",
"def property_params\n params.permit(:name, :is_available, :is_approved, :owner_id)\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def sponsor_params\n params.require(:sponsor).permit(WHITE_LIST)\n end",
"def whitelist_person_params\n params.require(:person).permit(:family, :pre_title, :given_name, :dates, :post_title, :epithet, :dates_of_office, same_as: [], related_authority: [], altlabel: [], note: []) # Note - arrays need to go at the end or an error occurs!\n end",
"def parameters\n nil\n end",
"def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end",
"def sequence_param_whitelist\n default_param_whitelist << \"show_index\"\n end",
"def resource_filter_permitted_params\n raise(NotImplementedError, 'resource_filter_permitted_params method not implemented')\n end",
"def normal_params\n reject{|param, val| param_definitions[param][:internal] }\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def special_device_list_params\n params.require(:special_device_list).permit(:name)\n end",
"def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end"
] | [
"0.7121987",
"0.70541996",
"0.69483954",
"0.6902367",
"0.6733912",
"0.6717838",
"0.6687021",
"0.6676254",
"0.66612333",
"0.6555296",
"0.6527056",
"0.6456324",
"0.6450841",
"0.6450127",
"0.6447226",
"0.6434961",
"0.64121825",
"0.64121825",
"0.63913447",
"0.63804525",
"0.63804525",
"0.6373396",
"0.6360051",
"0.6355191",
"0.62856233",
"0.627813",
"0.62451434",
"0.6228103",
"0.6224965",
"0.6222941",
"0.6210244",
"0.62077755",
"0.61762565",
"0.61711127",
"0.6168448",
"0.6160164",
"0.61446255",
"0.6134175",
"0.6120522",
"0.6106709",
"0.60981655",
"0.6076113",
"0.60534036",
"0.60410434",
"0.6034582",
"0.6029977",
"0.6019861",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.6019158",
"0.60184896",
"0.60157263",
"0.6005857",
"0.6003803",
"0.60012573",
"0.59955895",
"0.5994598",
"0.5993604",
"0.5983824",
"0.5983166",
"0.5977431",
"0.597591",
"0.5968824",
"0.5965953",
"0.59647584",
"0.59647584",
"0.59566855",
"0.59506303",
"0.5950375",
"0.59485626",
"0.59440875",
"0.5930872",
"0.5930206",
"0.5925668",
"0.59235454",
"0.5917905",
"0.59164816",
"0.5913821",
"0.59128743",
"0.5906617",
"0.59053683",
"0.59052664",
"0.5901591",
"0.58987755",
"0.5897456",
"0.58970183",
"0.58942604"
] | 0.0 | -1 |
require 'admin_template' include AdminTemplate protected ssl_required :admin_authorize if SSL_ENABLE | def set_locale
# session[:locale] = params[:locale] if params[:locale]
# session[:locale] = "zh" if session[:locale].blank?
# session[:locale] = "zh"
# I18n.locale = session[:locale] || I18n.default_locale
I18n.locale = 'zh'
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def require_admin\n end",
"def require_admin\n if Rails.env.production? && is_market? && Rails.configuration.admin_hostname != request.host\n render plain: \"ADMIN_HOSTNAME setting does not match your host header.\"\n else\n unless is_admin?\n flash[:alert] = \"Access not authorized. Need to be logged in first.\"\n redirect_to admin_new_session_path\n end\n end\n end",
"def superadminify\n without_access_control do\n User.module_eval do\n def role_symbols\n @role_symbols = [ :superadmin ]\n end\n end\n\n request.session[:auth_via] = 'cas'\n request.session[:user_id] = users(:one)\n end\n end",
"def ssl_allowed?\n admin_subdomain? #|| (logged_in? && current_account.ssl_allowed?)\n end",
"def require_admin\n unless view_context.admin?\n redirect_to root_url\n end\n end",
"def force_ssl_admin(force = nil)\n # TS_INFO: true always\n #\tstatic forced = false\n #\n #\tunless force.nil?\n #\t\told_forced = forced\n #\t\tforced = force\n #\t\treturn old_forced\n #\tend\n #\n #\tforced\n true\n end",
"def require_ssl\n @require_ssl = true\n end",
"def verify_admin\n render_401 unless current_user.is_admin?\n end",
"def require_admin\n not_authorized(\"Invalid credentials.\") unless is_admin?\n end",
"def secure_subresource_integrity_context?; end",
"def secure_subresource_integrity_context?; end",
"def ssl_required?\n return false if disable_ssl?\n return true if logged_in?\n super\n end",
"def require_admin\n deny_wrong_user if !admin?\n end",
"def ssl_required?\n true\n end",
"def secure_admin?\n File.exist?(\"#{context.domain_directory}/config/secure.marker\")\n end",
"def require_admin\n redirect_to root_path unless admin_logged_in?\n end",
"def require_admin_login\n unless admin_signed_in?\n redirect_to login_url\n end\n end",
"def ensure_admin!\n authorize! :read, :admin_dashboard\n end",
"def ensure_admin!\n authorize! :read, :admin_dashboard\n end",
"def use_ssl?; end",
"def require_admin\n unless !current_user.nil? && current_user.admin?\n render file: 'public/401.html', status: :unauthorized\n end\n end",
"def ssl; end",
"def ssl_required?\r\n true\r\n end",
"def configure_ssl(http); end",
"def require_admin\n redirect_to(root_path) unless current_user.admin?\n end",
"def use_bundled_cert!; end",
"def secure?\n true\n end",
"def w000thenticate_admin!\n check_token\n authenticate_user!\n raise AbstractController::ActionNotFound unless current_user.admin?\n end",
"def verify_admin\n :authenticate_user!\n have_no_rights('restricted area') unless current_user.isAdmin?\nend",
"def directoryadminify\n without_access_control do\n User.module_eval do\n def role_symbols\n @role_symbols = [ :directoryadmin ]\n end\n end\n\n request.session[:auth_via] = 'cas'\n request.session[:user_id] = users(:one)\n end\n end",
"def allow_production; end",
"def devise_modules_hook!; end",
"def check_if_should_be_admin\n end",
"def security_server_client\n end",
"def require_admin\n logger.debug \"ApplicationController::require_user\"\n if current_user.admin?\n return true\n else\n flash[:error] = \"You do not have permissions to view this page\"\n redirect_to surveys_path\n end\n end",
"def force_ssl; end",
"def force_ssl; end",
"def authorizeAdmin\n redirect_to '/adminlogin' unless admin_user\n end",
"def require_admin\n unless current_admin\n store_location\n flash[:error] = \"你还没有登录,请先登录!\"\n redirect_to admin_login_url\n return false\n end\n end",
"def ssl\n conf['dashboard']['ssl']\n end",
"def check_admin\n if not ensure_admin\n redirect_to root_url, alert: \"you are not authorized\"\n end # end if\n end",
"def require_ssl\n log \"NAV: Checking for SSL\"\n # check for enviroment variable\n return unless ENV['REQUIRE_HTTPS']\n\n unless request.ssl?\n log \"NAV OVERRIDE: Redirecting to https://#{request.host_with_port}#{request.fullpath}\"\n redirect_to({:protocol => 'https://'}.merge(params), :flash => flash)\n end\n end",
"def secure?\n false\n end",
"def require_ssl!\n throw(:halt, 403) unless request.secure?\n end",
"def rollcall_admin_required\n if current_user.is_rollcall_admin?\n return true\n else\n redirect_to :action => \"unauthorized\", :controller => 'rollcall/rollcall_app'\n return false\n end\n end",
"def authenticate_admin!\n render_404 unless current_user.try(:admin?) && current_user\n end",
"def serverssl\n super\n end",
"def conscientious_require; end",
"def authenticate_admin_user!\n raise SecurityError unless current_user.is_admin \n end",
"def require_admin\n render file: '/public/404' unless current_admin?\n end",
"def require_ssl!\n request.halt(403) unless request.ssl?\n end",
"def require_admin!\n authenticate_user!\n\n if current_user && !current_user.admin?\n redirect_to root_path\n end\n end",
"def require_admin!\n authenticate_user!\n\n if current_user && !current_user.admin?\n redirect_to root_path\n end\n end",
"def require_admin!\n authenticate_user!\n\n if current_user && !current_user.admin?\n redirect_to root_path\n end\n end",
"def require_admin!\n authenticate_user!\n\n if current_user && !current_user.admin?\n redirect_to root_path\n end\n end",
"def admin_required\n if not admin?\n redirect \"/login?#{env[\"REQUEST_PATH\"]}\"\n end\n end",
"def generate\n\n verify_cert_hash = get_ssl_cert_hash(datastore['StagerVerifySSLCert'],\n datastore['HandlerSSLCert'])\n\n super(\n ssl: true,\n verify_cert_hash: verify_cert_hash\n )\n end",
"def ssl_required?\n HTTPS_ON\n end",
"def require_admin\n unless admin?\n flash[:notice] = \"Sorry, only administrators can do that.\"\n redirect_to :controller => 'typus', :action => 'dashboard'\n end\n end",
"def authenticate_admin_user!\n redirect_to(root_url, :alert => I18n.t('unauthorized.default')) unless current_user.try(:access_admin_section?)\n end",
"def host_authorization; end",
"def host_authorization; end",
"def access_control\n \n end",
"def require_admin\n unless admin?\n flash[:warning] = \"Sorry, only administrators can do that.\"\n redirect_to Warnings_url\n end\n end",
"def verify_super_admin\n redirect_to admin_path unless current_user.user_level == \"super_admin_access\"\n\n end",
"def require_admin\n logger.debug \"ApplicationController::require_admin\"\n if require_user\n unless current_user.admin?\n #store_location\n flash[:notice] = \"You are not authorized to access this page\"\n redirect_to userhome_url\n return false\n end\n true\n end\n false\n end",
"def authorize_only_for_admin\n unless authorized?(Admin)\n render :file => \"#{RAILS_ROOT}/public/404.html\", \n :status => 404\n end\n end",
"def authenticate_admin?\n render text: '请和管理员联系!' unless current_user.admin?\n end",
"def ensure_admin_user!\n redirect_to(region_templates_path, :alert => \"You may not perform this action on regions!\") and return unless current_user.admin?\n end",
"def authenticate_admin\n unless current_user.admin?\n redirect_to site_path, alert: 'You do not have permission to access that page.' and return\n end\n end",
"def require_admin\n unless current_user.admin\n flash[:notice] = \"Need admin account.\"\n redirect_to(\"/login\")\n end\n end",
"def admin_check\n render_401 && return unless current_user\n render_403 && return unless current_user.admin?\n end",
"def admin?; false end",
"def verify_admin\n unless current_cas_user.admin?\n render(file: File.join(Rails.root, 'public/403.html'), status: :forbidden, layout: false)\n end\n end",
"def enable_ssl_verification\n true\n end",
"def authorize_admin!\n unless admin?\n flash[:alert] = 'Unauthorized access'\n redirect_to home_path\n false\n end\n end",
"def admin_required\n redirect_to(\"/\") unless admin?\n end",
"def needs_authorization?\n true\n end",
"def ssl_required?\n !disable_ssl?\n end",
"def authorize_admin\n redirect_to(:controller => 'main', :action => 'index') and return false unless @logged_in_user.is_admin?\n end",
"def require_admin\n redirect_to root_path unless @current_user.admin?\n end",
"def require_admin!\n # return if current token found and active\n return if current_admin\n\n # render error\n respond_with_error :unauthorized, I18n.t('not_authorized')\n end",
"def secure?\n false\n end",
"def verify_super_admin\r\n redirect_to admin_path unless current_user.user_level == \"super_admin_access\"\r\n end",
"def ssl_option\n super\n end",
"def check_admin\n redirect_to new_admin_session_path unless is_admin?\n end",
"def require_admin_privileges\n\t\tredirect_to root_path unless is_global_admin?\n\tend",
"def authenticated_admin\n\t authenticated\n\t error!('401 Unauthorized', 401) unless is_admin?\n\t end",
"def require_admin\n unless admin?\n flash[:warning] = \"Sorry, only administrators can do that.\"\n redirect_to messages_url\n end\n end",
"def authenticate_admin\n unless current_user.admin?\n redirect_to merge_default_redirect_params(site_path, scpbr: params[:scpbr]), alert: 'You do not have permission to access that page.' and return\n end\n end",
"def authenticate_admin\n unless current_user.admin?\n redirect_to merge_default_redirect_params(site_path, scpbr: params[:scpbr]), alert: 'You do not have permission to access that page.' and return\n end\n end",
"def authenticate_admin!\n current_user.is_admin? \n end",
"def disable_ssl; end",
"def authenticate_spraycan\n authorize! :admin, Spraycan::ViewOverride\n end",
"def cert; end",
"def cert; end",
"def cert; end",
"def authorize_admin!\n\t\tredirect_to new_admin_session_path unless current_admin\n\tend",
"def authenticate_admin!\n render \"errors/not_found\", :status => 404 unless signed_in? && current_teacher.admin\n end",
"def require_admin\n #byebug\n redirect_to user_path(current_user) unless current_user.role === \"Admin\"\n end",
"def enable_ssl(opts); end"
] | [
"0.6793391",
"0.6157994",
"0.611231",
"0.6007195",
"0.5996177",
"0.59879786",
"0.5939336",
"0.59091264",
"0.5906301",
"0.58824813",
"0.58821917",
"0.58766514",
"0.582218",
"0.58077264",
"0.57807684",
"0.5780454",
"0.5776235",
"0.5772891",
"0.5772891",
"0.57704055",
"0.5764316",
"0.5760325",
"0.57572293",
"0.5731996",
"0.5718667",
"0.57051325",
"0.5684495",
"0.56745654",
"0.5658854",
"0.56535643",
"0.5630692",
"0.56229216",
"0.5608921",
"0.560013",
"0.5591175",
"0.5577692",
"0.5577692",
"0.55755115",
"0.5568015",
"0.5567475",
"0.5562915",
"0.5558753",
"0.55575323",
"0.5557502",
"0.5543072",
"0.5541272",
"0.5533985",
"0.5530912",
"0.5523139",
"0.55133414",
"0.5510395",
"0.5508541",
"0.55083823",
"0.55083823",
"0.5508059",
"0.5500723",
"0.55000377",
"0.5488354",
"0.54868245",
"0.5485744",
"0.548033",
"0.548033",
"0.5471469",
"0.546881",
"0.54670155",
"0.545898",
"0.54496855",
"0.54482627",
"0.5437969",
"0.54296666",
"0.54261065",
"0.5423795",
"0.54231054",
"0.54185486",
"0.54149806",
"0.5409059",
"0.54088104",
"0.54086876",
"0.54038775",
"0.5395824",
"0.5394657",
"0.5393864",
"0.5393619",
"0.53925157",
"0.5391123",
"0.53859854",
"0.5385544",
"0.53839505",
"0.5376165",
"0.5373113",
"0.5373113",
"0.53715783",
"0.5367542",
"0.5366619",
"0.53629345",
"0.53629345",
"0.53629345",
"0.5360395",
"0.5360015",
"0.5357855",
"0.5356573"
] | 0.0 | -1 |
Returns the permissions associated with the role | def permissions
Roles.type_map[role_type].permissions
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def role_permissions\n return @role_permissions\n end",
"def permissions\n if @permissions.nil?\n perm_array = []\n roles.each { |r| perm_array << r.permission_ids }\n @permissions = perm_array.flatten.uniq\n else\n @permissions\n end\n end",
"def permissions\n Rails.cache.fetch(\"permissions_#{self.id}\", expire_in: 1.month) do\n self.roles.map(&:permissions).flatten\n end\n end",
"def all_permissions\n return permissions unless role\n (permissions + role.permissions).uniq\n end",
"def all_permissions\n permissions = Array.new\n \n all_roles.each do |role|\n permissions.concat(role.permissions)\n end\n \n return permissions\n end",
"def show\n @permissions = @role.permissions\n end",
"def permissions( force_reload = false )\n\n # Two levels of joins here, so can't use has_many :through\n if force_reload\n @permissions = nil \n @permissions_by_class_and_op = {}\n end\n\n cond_str = 'role_id in ' + self.class.role_assigned_cond( '?' )\n if !instance_variable_defined?(\"@permissions\") || @permissions.nil?\n @permissions ||= Permission.where([cond_str, self]).to_a\n end\n\n return @permissions\n end",
"def index\n @role_permissions = RolePermission.all\n end",
"def permissions\n return @permissions\n end",
"def existing_permissions(role)\n role.permissions.where.not(action: CardPermissions::STATELESS_ACTIONS).where.not(filter_by_card_id: nil)\n end",
"def load_permissions \n @current_permissions = current_user.role.permissions.collect{|i| [i.subject_class, i.action]} \n end",
"def load_permissions\n @current_permissions = current_user.role.permissions.collect{|i| [i.subject_class, i.action]}\n end",
"def get_role_permissions(role_id, options = {})\n raise Auth0::MissingParameter, 'Must supply a valid role_id' if role_id.to_s.empty?\n\n request_params = {\n per_page: options.fetch(:per_page, nil),\n page: options.fetch(:page, nil),\n include_totals: options.fetch(:include_totals, nil)\n }\n get \"#{roles_path}/#{role_id}/permissions\", request_params\n end",
"def role\n permission_type\n end",
"def permissions\n read_attribute(:permissions) || {}\n end",
"def index\n @rolepermissions = Rolepermission.all\n end",
"def get_permissions\n permissions.keys\n end",
"def get_permissions\n permissions.keys\n end",
"def permissions\n @attributes[:permissions]\n end",
"def permissions\n @attributes[:permissions]\n end",
"def role_permissions=(value)\n @role_permissions = value\n end",
"def permissions\n @resource_permissions\n end",
"def my_permissions\n @my_permissions ||= self.roles.map {|r| r.permissions.map {|p| p.name}}.flatten.freeze\n end",
"def load_permissions\n \n @current_permissions = current_user.role.permissions.collect{|i| [i.subject_class, i.action]}\n end",
"def resource_role_scopes\n return @resource_role_scopes\n end",
"def permissions\n objects_from_response(Code42::Permission, :get, 'permission')\n end",
"def permission_resources\n %w{roles sites employees classrooms students gapps_org_units}\n end",
"def permitted_roles privilege\n result = JSON.parse url_for(:resources_permitted_roles, credentials, id, privilege).get\n if result.is_a?(Hash) && ( count = result['count'] )\n count\n else\n result\n end\n end",
"def permission_keys\n return @permission_keys if @permission_keys\n\n role_keys = if role(true)\n role_key = \"#{role.cache_key}/permissions\"\n\n keys = Rails.cache.fetch(role_key) do\n role.permission_keys.clone\n end\n\n Rails.cache.write(role_key, keys)\n keys\n else\n []\n end\n\n user_keys = Rails.cache.fetch(permissions_cache_key) do\n user_permission_keys.clone\n end\n\n user_keys = [] unless user_keys\n\n Rails.cache.write(permissions_cache_key, keys) unless new_record?\n\n @permission_keys = (role_keys + user_keys).uniq\n end",
"def roles\n roles_from_users\n end",
"def roles\n Jak.role_klass.where(id: grants.pluck(:role_ids).compact.flatten)\n end",
"def permissions\n [\"read_permissions\", \"update_permissions\", \"delete_permissions\"].each do |p|\n perms = self.send(p)\n perm_string = []\n AssetPermission::GROUP.each do |g, v|\n if perms & AssetPermission::GROUP[g] > 0\n perm_string << g\n end\n end\n puts \"#{self.name}: #{p}: #{perm_string.join(',')}\"\n end\n end",
"def permissions\n\t\tauthorize @user\n\t\t@permissions = []\n\t\tonly_theirs = \"Only theirs\"\n\t\tyes = \"Yes\"\n\t\tno = \"No\"\n\t\tnames = [\"View positions\", \"Create positions\", \"Edit positions\", \"Delete positions\",\n\t\t \"Apply\", \"View applications\", \"Edit applications\", \"Delete applications\",\n\t\t \"Change application submission status\"]\n\t\tadmin_permissions = [yes, yes, yes, yes, yes, \"All\", yes, yes, yes]\n\t\tmod_permissions = [yes, no, yes, no, yes, \"All but incomplete\", only_theirs, only_theirs, yes]\n\t\tuser_permissions = [yes, no, no, no, yes, only_theirs, only_theirs, only_theirs, no]\n\t\tnames.each_with_index do |permission, index|\n\t\t\t@permissions << { name: names[index], admin: admin_permissions[index], mod: mod_permissions[index], user: user_permissions[index]}\n\t\tend\n\n @title = 'Permissions'\n\tend",
"def show\r\n \r\n @role = Role.find(params[:id])\r\n @permissions = @role.permissions.group_by &:subject_class\r\n end",
"def permissions\n attribute_prop(5)\n end",
"def calendar_permissions\n return @calendar_permissions\n end",
"def permissions_for(game)\n self.permissions.where(\"user_roles.game_id = ?\", game.id)\n end",
"def roles\n # we can't use abilities as those are not defined when creating a new operator that is not yet saved\n #result = abilities.collect(&:name)\n authorizations.collect{|auth| auth.ability.try(:name)}\n end",
"def roles\n # we can't use abilities as those are not defined when creating a new operator that is not yet saved\n #result = abilities.collect(&:name)\n authorizations.collect{|auth| auth.ability.try(:name)}\n end",
"def list_permissions\n BrickFTP::API::Permission.all\n end",
"def list_permissions\n BrickFTP::API::Permission.all\n end",
"def permission_grants\n return @permission_grants\n end",
"def roles\n @resource_roles\n end",
"def roles_with_permission\n shift.location.loc_group.roles\n end",
"def authorizations_for(role)\n auth_roles = roles.find(:all, :joins => :role, :include => :authorizations, :conditions => { \"roles.name\" => role.to_s })\n return nil if auth_roles.empty?\n auth_roles.collect(&:authorizations).flatten.compact\n end",
"def permissions\n User.do_find_permissions session_id: kb_session_id\n end",
"def get_permissions\n permissions = Hash.new\n permissions[:CanEditAllTeams] = 1\n permissions[:CanEditAllPlayers] = 2\n permissions[:CanEditAllSeasons] = 3\n permissions[:CanEditAllDivisions] = 4\n permissions[:CanEditAllRatings] = 5\n permissions[:CanEditAllRoles] = 6\n permissions[:CanEditAllPermissions] = 7\n permissions[:CanImport] = 8\n permissions[:CanApproveRatings] = 10\n @permissions = permissions\n end",
"def roles\n self.dig_for_array(\"roles\")\n end",
"def the_roles\n roles.each.map{|_r| User::ROLES[_r.to_sym] }\n end",
"def accessible_roles\n index = ROLES.index(self.role)\n roles = User::ROLES[0..index].map{|x| [x.humanize, x]} if index\n return roles\n end",
"def roles\n roles_as_editor + roles_as_reviewer + role_as_admin\n end",
"def permission\n Ricer::Irc::Permission.by_permission(self.permissions, authenticated?)\n end",
"def all_permissions\n array = []\n @permissions.each { |_, permission| array << permission }\n @groups.each do |_, group|\n group.all_permissions.each do |permission|\n array << permission\n end\n end\n array\n end",
"def find_permissions\n\n return nil if @user.admin?\n\n groupnames = Group.find_groups(@user)\n\n StorePermission.find_all_by_groupname(groupnames).inject({}) do \n |result, permission|\n\n result[permission.storename] = permission\n result\n end\n end",
"def index\n index_helper\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @role_permissions }\n end\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability,:read)\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability,:read)\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability,:read)\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability,:read)\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability,:read)\n end",
"def role_assignments\n return @role_assignments\n end",
"def get_permissions who, resource_tree\n who = get_group(who) unless who.is_a?(Group)\n \n last_resource = resource_tree.last\n \n # go down the resource tree to determine the permissions\n resource_tree.each do |resource|\n raise \"unknown resource\" unless resource\n \n # get permissions to resource\n r = w = x = false\n\n ownership = belongs_to_group?(who, resource.owner_uuid)\n\n get_permissions_by_resource(resource).each do |permission|\n next unless belongs_to_group?(who, permission.group_uuid, ownership)\n\n # group has effect on permissions\n r = true if permission.is_readable\n w = true if permission.is_writable\n x = true if permission.is_executable\n end\n \n # return permissions of resource if last\n return [r,w,x] if last_resource == resource\n \n # no read permission => no permission to browse further\n return [false, false, false] unless r\n end\n \n raise \"internal error\"\n end",
"def add_permissions\r\n @role = Role.find(params[:id])\r\n end",
"def custom_permissions\n discover_permissions\n export_sets_permissions\n batches_permissions\n preservation_events_permissions\n end",
"def resource_roles\n return @resource_roles\n end",
"def roles\n self.class.roles.map do |name|\n __send__(name)\n end\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability, :read)\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability, :read)\n end",
"def roles\n groups.find(:all, :conditions => {:context => Group::GroupType::ROLE})\n end",
"def get_permissions_by_resource resource_uuid\n resource_uuid = resource_uuid.uuid if resource_uuid.is_a?(Resource)\n \n @permissions.find_all{|per|per.resource_uuid == resource_uuid}\n end",
"def roles\n ::Syncano::QueryBuilder.new(self, ::Syncano::Resources::Role)\n end",
"def get_current_permissions\n sd = get_security_descriptor(DO_NOT_REFRESH_SD)\n permissions = []\n unless sd.nil?\n permissions if sd.dacl.nil?\n sd.dacl.each do |ace|\n permissions << Puppet::Type::Acl::Ace.new(convert_to_permissions_hash(ace), self)\n end\n end\n permissions\n end",
"def custom_permissions\n alias_action :show, :manifest, to: :read\n alias_action :color_pdf, :pdf, :edit, :browse_everything_files, :structure, :file_manager, to: :modify\n roles.each do |role|\n send \"#{role}_permissions\" if current_user.send \"#{role}?\"\n end\n end",
"def custom_permissions\n alias_action :show, :manifest, to: :read\n alias_action :color_pdf, :pdf, :edit, :browse_everything_files, :structure, :file_manager, to: :modify\n roles.each do |role|\n send \"#{role}_permissions\" if current_user.send \"#{role}?\"\n end\n end",
"def getPermissions\n perms = []\n perms.push :disseminate if params[:disseminate_perm] == \"on\"\n perms.push :withdraw if params[:withdraw_perm] == \"on\"\n perms.push :peek if params[:peek_perm] == \"on\"\n perms.push :submit if params[:submit_perm] == \"on\"\n perms.push :report if params[:report_perm] == \"on\" \n perms \n end",
"def roles\n User.valid_roles\n end",
"def effective_permissions(project_or_component)\n return nil if project_or_component.nil?\n\n return 'admin' if admin\n\n case project_or_component\n when Project\n Membership.where(\n membership_type: 'Project',\n membership_id: project_or_component.id,\n user_id: id\n ).pick(:role)\n when Component\n memberships = Membership.where(\n membership_type: 'Project',\n membership_id: project_or_component.project_id,\n user_id: id\n ).or(\n Membership.where(\n membership_type: 'Component',\n membership_id: project_or_component.id,\n user_id: id\n )\n ).pluck(:role)\n # Pick the greater of the two possible permissions\n memberships.max do |role_a, role_b|\n PROJECT_MEMBER_ROLES.index(role_a) <=> PROJECT_MEMBER_ROLES.index(role_b)\n end\n end\n end",
"def role_contexts\n auth_scope do\n send(permission_role_plural_key).group(:context_type, :context_id).map(&:context)\n end\n end",
"def index\n return unless check_permission\n\n @roles = Role.left_joins(:user)\n end",
"def admin_permissions\n {\n id: 1,\n appendable_permissions: [\n { permission_type: 'basic' },\n { permission_type: 'admin' }\n ]\n }\n end",
"def perms\n if @perms.nil?\n @perms = {}\n permissions = ['comment', 'edit', 'reassign', 'prioritize', 'close', 'milestone']\n permissions.each do |p|\n if @task.project_id.to_i == 0 || current_user.can?(@task.project, p)\n @perms[p] = {}\n else\n @perms[p] = { :disabled => 'disabled' }\n end\n end\n\n end\n\n @perms\n end",
"def permissions_for(context=nil, force_context=nil)\n auth_scope do\n force_context ||= config.force_context\n context = Zuul::Context.parse(context)\n roles = roles_for(context)\n if force_context\n return role_and_subject_permissions_for(context, roles)\n else\n return role_and_subject_permissions_within(context, roles)\n end\n end\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability, :read)\n end",
"def project_permissions\n user.project_permissions(rule.project)\n end",
"def accessible_roles\n @accessible_roles = Role.accessible_by(current_ability)\n end",
"def core_getUsersPermissions\n # definisco permessi iniziali\n initial_permissions = (1...11).to_a\n\n unpermitted = core_getHideUsersPermissionsSettings\n permitted_permissions = initial_permissions\n permitted_permissions = initial_permissions - unpermitted if unpermitted\n\n permissions = []\n names = core_getUsersPermissionsNamesSettings\n return permitted_permissions if !names\n\n permitted_permissions.each do |permission|\n names.each do |name|\n permissions.push([permission, name.last]) if permission === name.first.to_i\n end\n end\n\n return permissions\n end",
"def permissions\n if @prm\n @prm\n else\n @maximum_prms\n end\n end",
"def get_permissions permissions_ds\n # default to rightsMetadata (like standard Hydra) if permissions_ds isn't set\n permissions_ds = \"rightsMetadata\" if permissions_ds.to_s == \"\"\n (datastreams[permissions_ds].groups.map {|x| {:type=>'group', :access=>x[1], :name=>x[0] }} + \n datastreams[permissions_ds].individuals.map {|x| {:type=>'user', :access=>x[1], :name=>x[0]}})\n\n (datastreams[permissions_ds].groups.map {|x| {:type=>'group', :access=>x[1], :name=>x[0] }} + \n datastreams[permissions_ds].individuals.map {|x| {:type=>'user', :access=>x[1], :name=>x[0]}})\n end",
"def roles_list(role = nil)\n self.role_symbols\n end",
"def groups\n roles\n end",
"def permissions(*constraints)\n _permissions = {\n super_admin: self.super_admin?,\n digital_store_admin: self.digital_store_admin?,\n group_admin: self.group_admin?,\n event_admin: self.event_admin?,\n photo_approval_admin: self.photo_approval_admin?,\n club_admin: self.club_admin?,\n india_admin: self.india_admin?,\n }\n\n independent_roles = self.user_roles.joins(:role).where(roles: {role_type: Role.role_types.independent})\n\n independent_roles.each do |independent_role|\n _permissions[independent_role.role.name] ||= true\n end\n\n if constraints.present?\n constraints.each do |constraint|\n next unless constraint.class.ancestors.include?(ActiveRecord::Base)\n\n role_dependencies = self.role_dependencies.includes({user_role: [:role]}).where(role_dependencies: {role_dependable_type: constraint.class.to_s, role_dependable_id: constraint.id})\n\n selected_role_dependencies = role_dependencies.select do |role_dependency|\n !role_dependency.is_restriction || (role_dependency.start_date..role_dependency.end_date).include?(Date.today)\n end\n\n selected_role_dependencies.each do |role_dependency|\n _permissions[role_dependency.user_role.role.name] ||= true\n end\n end\n end\n\n ActiveSupport::HashWithIndifferentAccess.new(_permissions)\n end",
"def accessible_roles\n @accessible_roles = Level.accessible_by(current_ability, :read)\n end",
"def role\n @role\n end",
"def permissions(options: {})\n Permissions.new(fetch(\n path: Permissions::PATH.call(id),\n options: options\n )).permissions\n end",
"def get_current_permissions()\n\t\t\tkparams = {}\n\t\t\tclient.queue_service_action_call('permission', 'getCurrentPermissions', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend",
"def all_permissions( privilege, klass )\n\n class_perms = self.perms_for_class( klass.name ) || {}\n all_perms = class_perms[ privilege ] || []\n\n if !class_perms[ :any ].nil?\n all_perms = all_perms + class_perms[ :any ]\n end\n\n return all_perms\n\n end",
"def role_select\n @@Roles.list\n end",
"def meta_abilities\n User.roles.each do |(k, v)|\n if user.has_role? k\n can \"do_#{k}\".to_sym, :all\n end\n end\n end",
"def roles\n client.user_roles(id)\n end",
"def roles\n client.user_roles(id)\n end"
] | [
"0.83612496",
"0.7967314",
"0.7944717",
"0.7577825",
"0.7563391",
"0.74145716",
"0.74088514",
"0.72138083",
"0.71344703",
"0.7127846",
"0.7009284",
"0.69980043",
"0.6966114",
"0.69469106",
"0.6939263",
"0.6932439",
"0.68984014",
"0.68984014",
"0.689288",
"0.689288",
"0.68855464",
"0.688029",
"0.68800646",
"0.6867392",
"0.6852364",
"0.68193436",
"0.6737279",
"0.6666258",
"0.66492355",
"0.6635681",
"0.6559366",
"0.6545512",
"0.6541745",
"0.6536541",
"0.65291756",
"0.65270096",
"0.65229625",
"0.6515844",
"0.6515844",
"0.6514451",
"0.6514451",
"0.65069973",
"0.65052277",
"0.6489055",
"0.6488717",
"0.6485247",
"0.6327344",
"0.6320994",
"0.6318821",
"0.6313947",
"0.6313791",
"0.6305193",
"0.6300331",
"0.6290132",
"0.62885225",
"0.6272583",
"0.6272583",
"0.6272583",
"0.6272583",
"0.6270846",
"0.6245983",
"0.6243473",
"0.62362987",
"0.62321204",
"0.6219481",
"0.6198151",
"0.61943305",
"0.61943305",
"0.6185925",
"0.6170679",
"0.61681575",
"0.6135048",
"0.61216086",
"0.61216086",
"0.6107311",
"0.6093479",
"0.6089745",
"0.60879797",
"0.60833305",
"0.60814065",
"0.6077887",
"0.6061376",
"0.6057035",
"0.60545343",
"0.6048343",
"0.60371345",
"0.6032971",
"0.60184187",
"0.6006361",
"0.6006263",
"0.6004598",
"0.6000887",
"0.5994454",
"0.5985669",
"0.59828347",
"0.5974706",
"0.5970973",
"0.596598",
"0.59619206",
"0.59619206"
] | 0.81939876 | 1 |
Sets the nearest timeframe | def set_time_frame time, time_slot = 30.minutes
Time.at(((time.to_i / time_slot).round * time_slot) + time_slot).to_i
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def adjust_timeframe(timeframe)\n timeframe\n end",
"def timeframe=(val)\n raise(ArgumentError, 'timeframe value must be in the days_ago_list') unless days_ago_list.include? val\n\n @timeframe = val\n refresh_data\n\n end",
"def set_timeframe\n @timeframe = Timeframe.find(params[:id])\n end",
"def timeframe\n Sleek::Timeframe.to_range(@timeframe, @timezone) if @timeframe\n end",
"def set_default_times\n if !self.start\n return\n end\n\n if self.start.hour == 0 # hour set to 0 if not otherwise defined...\n self.start = self.start + 9.hours\n end\n\n if !self.end\n if self.online?\n self.end = self.start + 1.hour\n else\n diff = 17 - self.start.hour\n self.end = self.start + diff.hours\n end\n end\n # TODO: Set timezone for online events. Where to get it from, though?\n # TODO: Check events form to add timezone autocomplete.\n # Get timezones from: https://timezonedb.com/download\n\n end",
"def set_current_time_as_adjusted\n self.adjusted_at = Time.current\n end",
"def set_next_run\n self.next_run_at = Time.zone.now unless self.next_run_at\n end",
"def set(time)\n reset\n @offset = now - time\n end",
"def target_framerate=( framerate )\n\t\t\t\tif framerate\n\t\t\t\t\t@target_frametime = 1000.0 / framerate\n\t\t\t\telse\n\t\t\t\t\t@target_frametime = nil\n\t\t\t\tend\n\t\t\trescue ZeroDivisionError\n\t\t\t\t@target_frametime = nil\n\t\t\tend",
"def post_initialize\n\t\tunless time_frame.active?\n\t\t\t@time_frame = TimeFrame.new( start_date: Changeset_Query.earliest_changeset_date, end_date: Changeset_Query.latest_changeset_date )\n\t\tend\n\tend",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def set_Timeframe(value)\n set_input(\"Timeframe\", value)\n end",
"def with_floating_timezone\n dup.set_tzid(:floating)\n end",
"def set_timezone(timezone); end",
"def set_timezone(timezone); end",
"def set_timezone(timezone); end",
"def set_timezone(timezone); end",
"def set_timezone(timezone); end",
"def set_timespan(doc, object)\n\n # For this import, assume everything is current, even if it isn't marked that way\n\n object.create_timespan if object.timespan.nil?\n object.timespan.update_attribute(:is_current, true)\n\n #puts 'updating timespan:::::' + object.class.to_s\n #if object.respond_to? :feature\n # puts \"Feature PID == #{object.feature.pid}\"\n #end\n #puts \"ERRORS == #{object.errors.inspect}\"\n #result = object.timespan.nil? ? object.create_timespan(:is_current => true) : object.timespan.update_attribute(:is_current, true)\n #puts result.inspect\n\n #if(doc.attributes['isCurrent'])\n # if(doc.attributes['isCurrent']=='yes')\n # object.timespan = Timespan.new(:is_current => true)\n # elsif(doc.attributes['isCurrent']=='no')\n # object.timespan = Timespan.new(:is_current => false)\n # end\n #end\n end",
"def set_timezone\n loc = Location.find(self.location_id)\n self.time_zone, self.localGMToffset = loc.time_zone, loc.localGMToffset\n end",
"def setpoint_to_target\n @setpoint = @freq_target\n end",
"def set_next_run\n self.next_run_at = calc_next_run_at_date\n end",
"def set_start_time\n @start_time = Time.now.to_f\n end",
"def set_start_time\n @start_time = Time.now.to_f\n end",
"def set_initial_next_run\n self.next_run_at = Time.zone.now if self.next_run_at.nil?\n end",
"def set_initial_next_run\n self.next_run_at = Time.zone.now if self.next_run_at.nil?\n end",
"def start=(time); end",
"def set_new_time\n @dt_in = time_in.to_datetime\n update_column(:time_in, @dt_in.change(hour: hour_in.to_i, min: min_in.to_i))\n \n @dt_out = time_out.to_datetime\n update_column(:time_out, @dt_out.change(hour: hour_out.to_i, min: min_out.to_i))\n end",
"def within(value)\n @time = value\n self\n end",
"def from_now(t = Time.now); t + self; end",
"def from_now(t = Time.now); t + self; end",
"def set_current_time\n current_time = Time.zone.now.strftime(\"%B %e at %I:%M %p\")\n self.start_time = current_time\n end",
"def nearest_time_event\n now = (Time.now.to_f * 1000).truncate\n nearest = nil\n @time_events.each do |time_event|\n if nearest.nil?\n nearest = time_event\n elsif time_event.process_at < nearest.process_at\n nearest = time_event\n else\n next\n end\n end\n \n nearest\n end",
"def set_sighted_at\n\t\tif @sighted_date.present?\n\t\t\tself[:sighted_at] = Time.zone.parse(\"#{@sighted_date} #{@sighted_time}\")\n\t\tend\n\t\tif self[:sighted_at].blank?\n\t\t\tself[:sighted_at] = Time.zone.now\n\t\tend\n\tend",
"def frame_time=(a); motion.frame_time = a; end",
"def extendbyfourteendays\n updated_at = Time.now\n end",
"def mock_current_time(new_time)\n time_travel_offsets.push(Time.now - new_time)\n end",
"def set_max_min_times(movie_time)\n\n if self.min_time.nil? || (self.min_time > movie_time[0].time)\n self.min_time = movie_time[0].time\n end\n\n if self.max_time.nil? || (self.max_time < movie_time[-1].time)\n self.max_time = movie_time[-1].time + \n movie_time[-1].duration.minutes + TIME_BUF.minutes\n end\n\n\n end",
"def setup_start_at\n return unless start_at.blank?\n \n self.start_at = Time.now\n end",
"def setup_start_at\n return unless start_at.blank?\n \n self.start_at = Time.now\n end",
"def start_datetime(timeframe = nil)\n case timeframe\n when \"1month\" then 1.month.ago.to_datetime\n when \"3months\" then 3.months.ago.to_datetime\n when \"2years\" then 2.years.ago.to_datetime\n else 5.years.ago.to_datetime\n end\n end",
"def setup_time_zone(&block)\n Time.use_zone(Time.find_zone!(@mentor.time_zone.to_i.hours), &block)\n end",
"def start_time(time)\n if time < time.set_time_to( @opening_time )\n time.set_time_to( @opening_time )\n else\n time\n end\n end",
"def update_time_date\n start_year = self.start_at.change(:year => self.lesson_date.year)\n start_month = start_year.change(:month => self.lesson_date.month)\n start_day = start_month.change(:day => self.lesson_date.day)\n self.start_at = start_day\n\n end_year = self.end_at.change(:year => self.lesson_date.year)\n end_month = end_year.change(:month => self.lesson_date.month)\n end_day = end_month.change(:day => self.lesson_date.day)\n self.end_at = end_day\n end",
"def set_ends_at\n return unless self.duration && self.starts_at\n self.ends_at = starts_at + duration.hours\n end",
"def set(options)\n opts={}\n options.each_pair do |k,v|\n k = :min if k.to_s =~ /^min/\n k = :sec if k.to_s =~ /^sec/\n opts[k] = v.to_i\n end\n self.class.send(\n self.utc? ? :utc : :local,\n opts[:year] || self.year,\n opts[:month] || self.month,\n opts[:day] || self.day,\n opts[:hour] || self.hour,\n opts[:min] || self.min,\n opts[:sec] || self.sec,\n opts[:usec] || self.usec\n )\n end",
"def set_date\n gon.time_period = @verdict.time_period.strftime('%m/%d/%Y %H:%M') if !@verdict.time_period.nil?\n end",
"def update_target_duration\n self.target_duration = self.endDate - self.startDate\n end",
"def with_past\n without_temporal_condition\n end",
"def shift_time(options={:distance => :days, :direction => :either, :base => nil, :min => nil, :max => nil})\n random_time_shift options\n end",
"def setWaypointTimeout _obj, _args\n \"_obj setWaypointTimeout _args;\" \n end",
"def schedule_break start_time, end_time, rate = 0.0\n check_break start_time, end_time\n\n roadall.insert(-2, [start_time.to_i, nil, roadall.last.last])\n roadall.insert(-2, [end_time.to_i, nil, rate])\n end",
"def reset\n @time_travel_offsets = []\n end",
"def set_time_zone\n Time.zone = 'Warsaw'\n end",
"def set_values(times)\n @values[:start_time] = times[:actual]\n @values[:end_time] = times[:next]\n end",
"def reset_period_point\n\t\t\t\t@post_data[\"PeriodPoint\"] = get_period_time_of_today\n\t\t\tend",
"def restore_times; end",
"def restore_times; end",
"def adjust_time(timediff)\n Jhead.call(\"-ta\" << timediff, @match, @pattern)\n end",
"def before_connected_to_strava_at(tt = 8.hours)\n dt = connected_to_strava_at\n dt -= tt if dt\n dt\n end",
"def schedule\n schedule = start_time > Time.current ? UPCOMING_MATCH : PLAYED_MATCH\n\n schedule\n end",
"def propagate_start_and_end_times\n if @start_time && @start_time != shift.start_time\n self.starts_at = twenty_four_hour_time(@start_time)\n else\n self.starts_at = nil\n end\n if @end_time && @end_time != shift.end_time\n self.ends_at = twenty_four_hour_time(@end_time)\n else\n self.ends_at = nil\n end\n end",
"def push_next_try_at\r\n self.next_try_at = 15.minutes.from_now\r\n end",
"def shift_to absolute_time\n start = times.first\n if start\n shift absolute_time - start\n else\n clone\n end\n end",
"def set_timezone\n Time.zone = Time.zone_default\n end",
"def initialize(options = {})\n super\n @nearest = options[:nearest] || 0.1\n end",
"def shift_to! absolute_time\n start = times.first\n if start\n shift! absolute_time - start\n end\n self\n end",
"def update_time_range(time_in_ms)\n cv = find('#myChartView')\n cv.change_time time_in_ms\n end",
"def set_timezone\n offset = [ Time.now.beginning_of_year.utc_offset, Time.now.beginning_of_year.change(:month => 7).utc_offset ].min\n offset *= 3600 if offset.abs < 13\n Time.zone = ActiveSupport::TimeZone.all.select { |zone| zone.utc_offset == offset }.first\n end",
"def adjust(start,finish)\n @start=DateTime.new(start.year,start.month,start.day)\n @finish=DateTime.new(finish.year,finish.month,finish.day)\n refresh\n end",
"def set_clocks\n now = DateTime.now\n $current_time.value = now.strftime(DateTimeFormat)\n $universal_time.value = now.new_offset.strftime(DateTimeFormat)\n $lunar_date.value = '%4d\\'%02d\\'%02d' % LunarYear.lunar_date(now.to_date)\n now\nend",
"def at other, scale=true\n if other.is_a?(self)\n new(other)\n else\n if not other.is_a?(Time)\n other = Time.at(other)\n end\n\n if scale\n new(scale(other))\n else\n new(other)\n end\n end\n end",
"def schedule_to_close_timeout; Float::INFINITY; end",
"def update!(**args)\n @end_time_offset = args[:end_time_offset] if args.key?(:end_time_offset)\n @start_time_offset = args[:start_time_offset] if args.key?(:start_time_offset)\n end",
"def set_time_treinador\n @time_treinador = TimeTreinador.find(params[:id])\n end",
"def set(event, time)\n key[:schedule].zadd time.to_f, event\n end",
"def set_duration\n if self.end_time\n # self.duration = (end_time - start_time).to_i\n self.duration = (end_time - start_time).to_i\n else\n self.duration = DEFAULT_DURATION\n self.end_time = self.start_time + self.duration\n end\n end",
"def change_time_to_beginning_of_hour\n self.starts_at = self.starts_at.beginning_of_hour()\n self.ends_at = self.starts_at.end_of_hour()\n end",
"def set_best_of_day\n @best_of_day = BestOfDay.find(params[:id])\n end",
"def update_times\n\t\t@today = Time.now\n\t\t@current_start_day = @today - MONTH\n\t\t@previous_start_day = @current_start_day - MONTH\n\tend",
"def move(start)\n self.start_time = start\n new_min = start.min + self.duration.min\n new_hour = start.hour + self.duration.hour\n add_day = 0\n if new_min >= 60\n new_hour += new_min/60\n new_min -= (new_min/60) * 60\n end\n if new_hour >= 24\n add_day = 1\n new_hour -= (new_hour/24) * 24\n end\n self.end_time = start.change(day: self.start_time.day + add_day, hour: new_hour, min: new_min)\n return self\n end",
"def set_timezone\n \tTime.zone = \"Pacific Time (US & Canada)\"\n \tend",
"def change(options)\n if options[:zone] && options[:offset]\n raise ArgumentError, \"Can't change both :offset and :zone at the same time: #{options.inspect}\"\n end\n\n new_time = time.change(options)\n\n if options[:zone]\n new_zone = ::Time.find_zone(options[:zone])\n elsif options[:offset]\n new_zone = ::Time.find_zone(new_time.utc_offset)\n end\n\n new_zone ||= time_zone\n periods = new_zone.periods_for_local(new_time)\n\n self.class.new(nil, new_zone, new_time, periods.include?(period) ? period : nil)\n end",
"def change(options)\n ::Time.send(\n self.utc? ? :utc_time : :local_time,\n options[:year] || self.year,\n options[:month] || self.month,\n options[:day] || options[:mday] || self.day, # mday is deprecated\n options[:hour] || self.hour,\n options[:min] || (options[:hour] ? 0 : self.min),\n options[:sec] || ((options[:hour] || options[:min]) ? 0 : self.sec),\n options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : self.usec)\n )\n end",
"def set_scheduled_times_option\n @scheduled_times = ScheduledTime.all\n end",
"def set_deadline\n self.deadline ||= self.created_at.advance(years: 1)\n end",
"def time_to_live=(new_time_to_live)\n @time_to_live = new_time_to_live.round\n @time_to_live = 30.minutes if @time_to_live < 30.minutes\n end",
"def set_moon_clocks\n now = set_clocks\n \n # Has new or full moon expired?\n if now > $tnew1 || now > $tfull1\n $tnew0, $tnew1, $tfull0, $tfull1 = LunarYear.date_of_moons(now)\n end\n \n $last_new_moon.value = format_days(now - $tnew0)\n $next_new_moon.value = format_days($tnew1 - now)\n $last_full_moon.value = format_days(now - $tfull0)\n $next_full_moon.value = format_days($tfull1 - now)\nend",
"def update!(**args)\n @end_time = args[:end_time] if args.key?(:end_time)\n @start_time = args[:start_time] if args.key?(:start_time)\n end",
"def reset\n @time_zone = 'Europe/London'\n @email_address = 'test.test@test.com'\n @start_time = Date.today.to_time + 1\n @end_time = (Date.today + 1).to_time - 1\n end",
"def set_located_at\n @located_at = LocatedAt.find(params[:id])\n end",
"def added_closest_temporal_range(temporal_range, indexes, days, count)\n index = temporal_range.index { |t| days >= t }\n if index\n range = temporal_range[index]\n indexes[range.to_s] = { 'days' => days, 'count' => count }\n end\nend",
"def update!(**args)\n @end_time = args[:end_time] if args.key?(:end_time)\n @start_time = args[:start_time] if args.key?(:start_time)\n end",
"def update!(**args)\n @end_time = args[:end_time] if args.key?(:end_time)\n @start_time = args[:start_time] if args.key?(:start_time)\n end"
] | [
"0.67763716",
"0.5833987",
"0.5665923",
"0.5644117",
"0.5591518",
"0.5580752",
"0.5405682",
"0.53374815",
"0.53036475",
"0.52960515",
"0.5290458",
"0.5290458",
"0.5290458",
"0.5290458",
"0.5290458",
"0.5290458",
"0.5290458",
"0.5290458",
"0.5276369",
"0.5274024",
"0.5274024",
"0.5274024",
"0.5274024",
"0.5274024",
"0.52513635",
"0.52122074",
"0.52117354",
"0.5156183",
"0.5119606",
"0.5119606",
"0.5109789",
"0.5109789",
"0.5107199",
"0.5084964",
"0.50839746",
"0.5063284",
"0.5063284",
"0.5062836",
"0.5059836",
"0.50566834",
"0.50277007",
"0.5018008",
"0.5001975",
"0.49964562",
"0.49850687",
"0.49850687",
"0.49842504",
"0.4969217",
"0.49516797",
"0.49510208",
"0.4948591",
"0.49258468",
"0.4911549",
"0.48978713",
"0.48750585",
"0.48699605",
"0.48685473",
"0.48515213",
"0.4847682",
"0.4835362",
"0.48351625",
"0.48327252",
"0.4821411",
"0.4821411",
"0.47991264",
"0.4791919",
"0.47896108",
"0.47870502",
"0.4785464",
"0.478443",
"0.47841713",
"0.47673392",
"0.47583428",
"0.47531247",
"0.47527677",
"0.47521505",
"0.4749769",
"0.4746315",
"0.47417405",
"0.47320905",
"0.4726321",
"0.47245067",
"0.47244322",
"0.4721282",
"0.4720804",
"0.47190392",
"0.47130328",
"0.47106817",
"0.4703042",
"0.46891373",
"0.4682774",
"0.46815816",
"0.4679848",
"0.46775857",
"0.46705544",
"0.46656144",
"0.4664324",
"0.46599957",
"0.46546498",
"0.465438"
] | 0.59649295 | 1 |
TODO: Needs to take into account the amount that one is owed :( | def total_owed_amount(ower)
return data[ower] ? data[ower].values.reduce(:+) : 0
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def amount_owed\n total_price - amount_paid\n end",
"def owes_amount\n loans=@loans\n net_worth=@net_worth\n @balance = net_worth-loans\n print \"the balance is : \",balance,\"\\n\"\n is_developer_solvent?\n end",
"def net_payments(current_user_id)\n payments = {\"you_are_owed\" => {}, \"you_owe\" => {}}\n # {\"Matt\"=>15.0, \"Sam\"=>10.0, \"Drew\"=>10.0, \"Tristan\"=>22.22} you_are_owed\n # {\"Matt\"=>11.11, \"Kyle\"=>25.22, \"Dega\"=>30.22, \"Drew\"=>30.22} you_owe\n\n you_owe_hash = you_owe(current_user_id)\n you_are_owed_hash = you_are_owed(current_user_id)\n\n\n # Find all the uniq keys of the two hashes, then sum the you_are_owed - you_owe, if value is positive, you are owed that amount, if value is negative you owe that amount\n user_payments = you_owe_hash.keys + you_are_owed_hash.keys\n user_payments = user_payments.uniq\n\n user_payments.each do |user|\n # user is in you_owe_hash and NOT you_are_owed_hash\n if you_owe_hash.has_key?(user) && !you_are_owed_hash.has_key?(user)\n payments[\"you_owe\"][user] = you_owe_hash[user]\n # user is NOT in you_owe_hash and in you_are_owed_hash\n elsif !you_owe_hash.has_key?(user) && you_are_owed_hash.has_key?(user)\n payments[\"you_are_owed\"][user] = you_are_owed_hash[user]\n # user is in both you_owe hash and you_are_owed hash\n else\n amount = (you_are_owed_hash[user] - you_owe_hash[user]).round(2)\n if amount > 0\n # Goes to you are owed\n payments[\"you_are_owed\"][user] = amount\n\n elsif amount < 0\n payments[\"you_owe\"][user] = -amount\n # Goes to you owe\n end\n end\n end\n\n payments\n\n end",
"def make_payment_now_amount\n if payment_owed.positive?\n payment_owed\n elsif workshop_price.payment_price < balance_owed\n workshop_price.payment_price\n else\n balance_owed\n end\n end",
"def withdraw(name, amount)\n a = find_account(name)\n a[:balance] < amount ? a[:balance] -= 30 : a[:balance] -= amount\n end",
"def amount_owed\n invoice_total - total_amount_paid\n end",
"def pay_owner(rental)\n # make credit operation on balanced\n balanced.credit(rental)\n\n # account it on subledger\n subledger.credit(rental)\n end",
"def tax_money_owed\n if update_taxable <= 43953 && update_taxable >= 0\n update_taxable * 0.15\n elsif update_taxable >= 43954 && update_taxable <=87907\n (43953*0.15) + ((update_taxable-43953) * 0.22)\n elsif update_taxable >= 87908 && update_taxable <=136270\n (43953*0.15)+ (48363*0.22) + (update_taxable * 0.26)\n elsif update_taxable >= 136270\n (43953*0.15)+ (48363*0.22)+ (43954*0.26) + (update_taxable * 0.29)\n else\n update_taxable \n end\n end",
"def pay_interest!(entity)\n owed = interest_owed(entity)\n # This is here so that the log message does not get duplicated.\n if corp_has_new_zealand?(entity) && entity.loans.size.positive?\n @log << \"#{entity.name}'s token in Nieuw Zeeland covers one loan's worth of interest\"\n end\n return super unless owed.negative?\n\n # Negative interest -> corporation has New Zealand\n @log << \"#{entity.name} gets $20 for having a token in Nieuw Zeeland and no loans\"\n entity.spend(owed, bank, check_cash: false, check_positive: false)\n nil\n end",
"def you_owe(current_user_id)\n\n you_owe_list = {}\n billsplits = Billsplit.joins(:bill).includes(:bill_author).where('recipient_id = ?', current_user_id).where('recipient_paid = false').where('paid = false')\n\n billsplits.each do |bill|\n if you_owe_list.has_key? bill.bill_author.username\n temp_amount = you_owe_list[bill.bill_author.username]\n you_owe_list[bill.bill_author.username] = temp_amount + bill.split_amount\n else\n you_owe_list[bill.bill_author.username] = bill.split_amount\n end\n end\n\n\n you_owe_list\n\n\n\n end",
"def still_needed\r\n\t@target_fund - @fund\r\nend",
"def reward\n business.add_to_balance(amount)\n end",
"def buy(amount)\n @bought_amount += amount if amount_remaining >= amount\n end",
"def distribute_money_internal_2(dealer_total, player , hand_index)\n i = hand_index\n dt = dealer_total\n hv = player.get_value(i)\n bet = player.get_bet(i)\n pn = player.player_number\n\n # instead of modifiying amount directly, should use a function call to increment player amount by payoff factor\n if (hv == 21 and (dt > 21 or dt < 21) )\n #player.amount += (bet * 2.5)\n player.modify_account(bet,2.5)\n puts \"Player #{pn} H#{i} #{hv} Blackjack - Dealer #{dt} , Amount= #{player.amount}\"\n elsif (hv < 21 and dt > 21) or (dt <= 21 and hv <= 21 and hv > dt)\n #player.amount += (bet * 2)\n player.modify_account(bet,2)\n puts \"Player #{pn} H#{i} #{hv} - Dealer #{dt} , Amount= #{player.amount}\"\n elsif (dt > 21 and hv > 21) or ((hv == 21) and dt == 21 ) or (hv == dealer_total and dt <= 21 and hv <= 21)\n #player.amount += (bet * 1)\n player.modify_account(bet,1)\n puts \"Player #{pn} H#{i} #{hv} - Dealer #{dt} , Amount= #{player.amount}\"\n else\n puts \"Player #{pn} H#{i} #{hv} - Dealer #{dt} , Amount= #{player.amount}\"\n end\n\n end",
"def deposit\n if admin_use\n 0\n elsif estimated_numbers < 20\n 150\n elsif estimated_numbers < 40\n 300\n else\n 600\n end\n end",
"def balance_owed\n discounted_price - amount_paid\n end",
"def attemp_buying\n\n end",
"def receive_winnings(amount)\n @bankroll += amount\n end",
"def total_owned\n self.shares.map{ |share| share.value }.inject(:+)\n end",
"def payment_owed\n if workshop_price&.recurring_payments?\n to_pay = recurring_what_should_be_paid_by_now - amount_paid\n to_pay.negative? ? Money.new(0, workshop_price.price.currency) : to_pay\n else\n balance_owed\n end\n end",
"def _spent_on\n return payment\n end",
"def withdraw(name_of_account, amount)\n\t\taccount = find_account(name_of_account)\n\t\tbalance_check = account[:balance] \n\t\tif balance_check < amount\n\t\t\taccount[:balance] -= 30\n\t\telse\n\t\t\taccount[:balance] -= amount\n\t\tend\n\tend",
"def overdraft_fee\n @balance -= 30 \n end",
"def withdraw(monies)\n @amount -= monies\n end",
"def investment\n if buy_price\n num_of_shares * buy_price\n end\n end",
"def net_worth\n result = self.cash_on_hand\n self.holdings.each do |holding|\n share_price = holding.company.share_price\n result += share_price * holding.amount\n end\n @net_worth = result\n end",
"def this_iz_payday(driver, hash)\n # TODO :\n # hash is a hash list, key : person, value : amount of dollz\n\n # for each couple, Access.has_paid(driver, person, amount)\n\n # need a timestamp TODO\n end",
"def present_value\n # Payoff amount = 0, we’re assuming a fully amortizing loan\n payoff_amount = 0\n end",
"def mark_up_amt\n rounder5(self.vehicle.price * 0.082)\n end",
"def you_are_owed\n detailed_expenses = self.expenses.includes(:expense_details)\n amount = 0\n more_details = Hash.new {|h,k| h[k] = k }\n detailed_expenses.each do |ex|\n id = Friend.includes(:profile).find(ex.payable_id)\n friend_id = self.id != id.profile_id ? id.profile_id : id.friend_id\n ex.expense_details.each do |ed|\n if ed.paid_by == self.id\n amount += (ed.amount_paid / 2.0)\n more_details[friend_id] ||= {}\n more_details[friend_id] += ed.amount_paid / 2.0\n end\n end\n end\n [amount, more_details]\n end",
"def withdraw(amount)\n @balance -= amount\n end",
"def withdraw ( person, amount )\r\n\t\tif @bank_listing[person.id_number][:balance] >= amount\r\n\t\t\t@bank_listing[person.id_number][:balance]-=amount\r\n\t\t\tputs \"#{@bank_name}: Thanks #{person.name}, here's your $#{amount}. Your current balance is $#{@bank_listing[person.id_number][:balance]}.\"\r\n\t\telse\r\n\t\t\tputs \"#{@bank_name}: Sorry #{person.name}, insufficient funds.\"\r\n\t\tend\r\n\tend",
"def withdraw(amount, atm, pin, acc_no)\n if @balance >= amount && atm.balance >= amount && @pin == pin && acc_no == @account_no\n atm.dispense(amount)\n @balance = @balance - amount\n puts \"your new balance is #{@balance}\"\n else\n puts \"you are too pov\"\n end\n end",
"def disbursed_amount\n amount = 0\n loans.each do |project|\n amount += project.disbursed_amount.to_i\n end\n amount\n end",
"def award; end",
"def you_are_owed(current_user_id)\n\n you_are_owed_list = {}\n\n bills = Bill.joins(:bill_splits).joins(:bill_author).where('author_id = ?', current_user_id).where('recipient_paid = false').where('paid = false').includes(:bill_recipients)\n bills.uniq.each do |bill|\n bill.bill_splits.each do |split|\n user = split.recipient.username\n if you_are_owed_list.has_key? user\n temp_amount = you_are_owed_list[user]\n you_are_owed_list[user] = temp_amount + split.split_amount\n else\n you_are_owed_list[user] = split.split_amount\n end\n end\n end\n\n you_are_owed_list\n\n end",
"def donate\r\n @fund += 25\r\n puts \"Project #{@name} received a generous donation!\"\r\n end",
"def win!(payoff)\n\t\t@balance.balance += Integer((1.0 + payoff)*@bet)\n\t\t@bet = 0\n\tend",
"def allowance(amt.to_f)\r\n save.deposit(amt.to_f * 0.6)\r\n puts \"Save balance = $#{@balance}.\"\r\n spend.deposit(amt.to_f * 0.3)\r\n puts \"Spend balance = $#{@balance}.\"\r\n spare.deposit(amt.to_f * 0.1)\r\n puts \"Spare balance = $#{@balance}.\"\r\nend",
"def loan_money(lender, lendee, amount)\nlender[:monies] -= amount\nlendee[:monies] += amount\nend",
"def sell_bonus\n bonus = 0.0\n battle_members.each { |member| bonus += member.sell_bonus }\n bonus\n end",
"def withd amount\n unless amount > @savings_account_balance\n @savings_account_balance -= amount\n \n else\n end\n end",
"def withdrawal_rate\n (youngest_person_retirement_age - 15.0) / 1000.0\n end",
"def unpaid_amount\n gross_amount - paid_amount\n end",
"def withdraw(amount)\n @balance = @balance - amount\n end",
"def pay_targeted_invoices_first!\n payments.each do |pm|\n if pm.invoice\n @remaining_amounts[pm.invoice.fy_year] ||= Hash.new(0)\n if pm.invoice.canceled?\n @remaining_amounts[pm.invoice.fy_year][pm.invoice.object_type] += pm.amount\n else\n paid_amount = [[pm.amount, pm.invoice.missing_amount].min, 0].max\n pm.invoice.increment!(:paid_amount, paid_amount)\n @remaining_amounts[pm.invoice.fy_year][pm.invoice.object_type] += pm.amount - paid_amount\n end\n else\n @remaining_amount += pm.amount\n end\n end\n end",
"def withdraw(amount)\n @balance -= amount\n end",
"def fully_paid?\n amount_owed <= 0\n end",
"def pays_transfers\n self.offers_as_buyer.accepted.inject(0){|sum,offer| sum += offer.pay}\n end",
"def deposit ( person, amount )\r\n\t\tif person.worth >= amount\r\n\t\t@bank_listing[person.id_number][:balance]+=amount\r\n\t\tputs \"#{@bank_name}: Thanks #{person.name}, you deposited #{amount}. Your current balance is $#{@bank_listing[person.id_number][:balance]}.\"\r\n\t\telse\r\n\t\t\tputs \"#{@bank_name}: Sorry, you don't have enough on hand.\"\r\n\t\tend\r\n\tend",
"def createDebts\n owedUsers = {}\n debtedUsers = {}\n\n # Separate users into those who owe and those who\n # are owed. O(n)\n self.contributions.each do |contribution|\n owedAmount = contribution.amount - contribution.paid\n if owedAmount > 0\n debtedUsers[contribution.user.id] = [owedAmount, contribution.user]\n elsif owedAmount < 0\n owedUsers[contribution.user.id] = [owedAmount * -1, contribution.user]\n end \n end\n\n # First, create debts for perfect matches. O(n squared)\n debtedUsers.each do |debtedKey, debtedUser|\n owedUsers.each do |owedKey, owedUser|\n if (debtedUser[0] == owedUser[0])\n Debt.settleDebt(owedUser[1], debtedUser[1], owedUser[0])\n owedUsers.delete(owedKey) #removes this contribution from Owed\n debtedUsers.delete(debtedKey) #TODO check this. removes this contribution from Owers\n end\n end\n end\n\n # IMPLEMENT OPTIMIZATION:\n # Now, if debts stll remain, use a greedy approach to \n # settle the remainder of debts. Match the users who \n # owe the most with those who are owed the least. O(n log n)\n\n # debtedUsers.sort{|x,y| x[0] <=> y[0]}.reverse!\n # owedUsers.sort{|x,y| x[0] <=> y[0]}\n\n\n # Pay off debts.\n debtedUsers.each do |debtedKey, debtedUser|\n amountToPay = debtedUser[0]\n\n owedUsers.each do |owedKey, owedUser|\n amountToReceive = owedUser[0]\n\n # If debtedUser can pay off owedUser and more,\n # settle the debt and update amount to pay.\n if (amountToPay > amountToReceive)\n amountToPay = amountToPay - amountToReceive\n Debt.settleDebt(owedUser[1], debtedUser[1], amountToReceive)\n owedUsers.delete(owedKey)\n\n # If debtedUser can only pay off part of owedUser,\n # settle debt, and leave debted user alone.\n elsif (amountToPay < amountToReceive)\n owedUser[0] = amountToReceive - amountToPay\n Debt.settleDebt(owedUser[1], debtedUser[1], amountToPay)\n debtedUsers.delete(debtedKey)\n break\n\n # It is possible that after paying off debts,\n # there is now a perfect match. In case, settle debt.\n else\n Debt.settleDebt(owedUser[1], debtedUser[1], owedUser[0])\n owedUsers.delete(owedKey)\n debtedUsers.delete(debtedKey)\n break\n end\n end\n end\n end",
"def loan_money_to_other(lender, lendee, amount)\n lender[:monies] -= amount\n lendee[:monies] += amount\nend",
"def current_commission\n if timesheets.current_week.any?\n pay = timesheets.current_week.distinct.sum(:gross_pay)\n bill = timesheets.current_week.distinct.sum(:total_bill)\n (bill - pay) /2 * 0.05 #FAKE COMMISSION RATE\n else\n 0.00\n end\n end",
"def pay_amount(user, amount)\r\n if(self.credits>= amount)\r\n self.credits= self.credits-amount\r\n user.receive_credits(amount)\r\n else\r\n return 'suddenly you dont have enough money'\r\n end\r\n end",
"def redeem\n #TO BE IMPLEMENTED\n end",
"def deposit(name, amount)\n find_account(name)[:balance] += amount\n end",
"def pay_in(balance)\n @balance += balance\nend",
"def loan_money(person_lending, person_receiving, loan)\n person_lending[:monies] -= loan\n person_receiving[:monies] += loan\nend",
"def extra_cash(db, user_name)\r\n\t# determine extra monies (conditional on + amount)\r\n\tdifference = (current_income(db, user_name) - current_expenses(db, user_name))\r\n\tcache_bonus = difference if difference > 0 || 0\r\nend",
"def profit\n \tself.bid - self.payout\n end",
"def bought_by(new_owner)\r\n self.owner = new_owner\r\n self.to_inactive\r\n end",
"def party_worth\n get_worth_of( shared_inventory + actors_inventory )\n end",
"def withdraw(amount_of_money)\n return @balance - amount_of_money\n end",
"def has_paid (driver, person, amount)\n # debt - amount\n end",
"def owner_only_offers_reward?\n self.rewards_count == 1 && self.rewards.visible[0].sender == self.person\n end",
"def pay_interest_on(account)\n # first interest is calculated and stored to local variable\n interest = calculate_interest(account)\n # if statement used to check if account is overdrawn\n if account.overdrawn?\n # if it is the interest is subtracted\n account.withdraw interest\n @master.deposit interest\n else\n # else the interest is added\n @master.withdraw interest\n account.deposit interest\n end\n end",
"def deposit(money) #Creating a method called deposit for the 1st user story\n @balance = @balance + money #The instance of 'balance' get recreated everytime the deposit method is called\n end",
"def award\n\tend",
"def money_for_us(auction)\n total_sale = auction.current_bid * auction.quantity\n if auction.premium_service\n total_sale * 0.1 # ten percent commission\n else\n total_sale * 0.05 # five percent commission\n end\n end",
"def amount_remaining\n @desired_amount - @bought_amount\n end",
"def credits; end",
"def check_for_buyout\n if self.is_bought_out\n if self.bought_out_by_team_id\n self.subcontracts.future_years.each do |sub|\n sub.salary_amount *= 0.6\n sub.this_is_a_buyout = true\n sub.save!\n\n # update GM's annual actions to not allow more buyouts\n actions = AnnualGmAction.find_by_team_id_and_year(self.bought_out_by_team_id, current_year)\n actions.has_bought_out = true\n actions.bought_out_player_id = self.player.id\n actions.save!\n end\n end\n end\n end",
"def deposit\n end",
"def deposit\n end",
"def loan_amt\n (self.buying_price*1000) * (1 - (self.deposit/100))\n end",
"def buy(amount)\n ether = amount.to_f\n\n @ether_reserve += ether\n new_token_reserve = @konst / @ether_reserve\n\n tokens_bought = @token_reserve - new_token_reserve\n price = sprintf(\"%0.4f\", ether / tokens_bought)\n log \"You get #{tokens_bought} tokens for #{ether} ether, price #{price}\" # this is where we would transfer tokens to the buyer\n\n @token_reserve = new_token_reserve\n output\n\n return tokens_bought\n end",
"def gain_interest\n @balance *= (1 + @interest_rate)\n end",
"def donated_amount\n self.fees.purchased.sum(:amount).to_f\n end",
"def benefits_transfers\n self.offers_as_seller.accepted.inject(0) {|sum, offer| sum += offer.pay}\n end",
"def pay_workers\r\n\t\t@cash -= (@sellers + @thieves)*10\r\n\tend",
"def deposit(money)\n @balance += money\nend",
"def withdraw(amount)\n if amount <= @balance && (@balance - amount >= self.class::MINIMUM_BALANCE)\n @balance -= amount\n else\n puts \"Your account does not contain enough to withdraw the amount requested.\"\n end\n return @balance\n end",
"def amount; end",
"def pay(amount)\n @bankroll -= amount\n @@bankroll -= amount\n end",
"def weighIntrade()\n\n end",
"def add_to_bank\n @user.balance -= 10\n @croupier.balance -= 10\n @bank = 20\n end",
"def offenses_to_check; end",
"def buy()\n #films the customer has tickets to\n all_films = films()\n #sum the films (as there can be more than one) and from each film add the price up and assign it to price\n price = all_films.sum{|film| film.price}\n remaining_funds = @funds - price\n @funds = remaining_funds\n update() #update the customer's funds!\n end",
"def pay_blinds\n @dealer.pay(@game.small_blind)\n @under_the_gun.pay(@game.big_blind)\n end",
"def amount_charged\n\t\t@amount = 6000\n\tend",
"def checkout\n self.balance = 0\n self.orders.each do |order|\n self.balance += order.food.price\n end\n self.balance\n end",
"def get_paid(salary)\n self.bank_account += salary\n self.happiness += 1\n \"all about the benjamins\"\n end",
"def buy?(buyer)\r\n if buyer.credits < self.price or not self.active or buyer == self.owner\r\n false\r\n return\r\n end\r\n owner.credits += self.price\r\n buyer.credits -= self.price\r\n self.owner.remove_owned(self)\r\n self.owner = buyer \r\n buyer.add_owned(self)\r\n self.active = false\r\n true \r\n end",
"def process_won_bets\n return unless @bet.won?\n # calculate_amount is profit in case of win and in case of refund or loss it will be stake\n # TODO : Need Transaction here\n amount = calculate_amount\n amount = Wallets::Base.new(wallet).credit(amount + @bet.stake)\n wallet.ledgers.create(arguments_of_bets) unless amount.zero?\n end",
"def offenses; end",
"def offenses; end",
"def offenses; end",
"def sell_to_current_winner\r\n if self.rank_one != nil\r\n winner = self.get_current_winner\r\n item.price = self.get_current_price\r\n item.take_ownership(winner)\r\n item.state = :pending\r\n winner.credits_in_auction -= self.get_current_bid\r\n winner.credits += (self.get_current_bid - self.get_current_price)\r\n EmailSender.win_auction(winner, item)\r\n else\r\n item.state = :inactive\r\n end\r\n end",
"def bought?\n # paym\n end",
"def borrower_paid_outside_closing\n purchase_credits.where(:name => 'BorrowerPaidOutsideClosing').first.value rescue nil\n end",
"def withdrawal(t)\n if (@balance - t.amount) < 0\n #print error message\n puts \"#{t.date} Overdraft: Unable to complete transaction to #{t.payee} for #{t.amount}\"\n\n else\n @balance = @balance - t.amount\n t.currBalance = @balance\n @ledger << t\n\n end\n end"
] | [
"0.6368402",
"0.63607574",
"0.62984735",
"0.62647045",
"0.6234975",
"0.6222604",
"0.62193406",
"0.6215096",
"0.61938524",
"0.61914426",
"0.61813277",
"0.6152021",
"0.60807174",
"0.60623497",
"0.6049904",
"0.6031863",
"0.59963197",
"0.59942365",
"0.5992578",
"0.59881175",
"0.5981014",
"0.5977933",
"0.59616804",
"0.59435946",
"0.5922834",
"0.59217393",
"0.591989",
"0.5918056",
"0.59078723",
"0.58943516",
"0.58896816",
"0.5887457",
"0.5879258",
"0.5872696",
"0.5871331",
"0.5865582",
"0.5854649",
"0.5851919",
"0.58395004",
"0.58390903",
"0.58382696",
"0.5837677",
"0.58319694",
"0.58085257",
"0.580616",
"0.58046764",
"0.5801872",
"0.5801296",
"0.57970357",
"0.57905865",
"0.57890534",
"0.578468",
"0.57807213",
"0.5779873",
"0.577616",
"0.5767461",
"0.57672405",
"0.57660896",
"0.57633346",
"0.5760885",
"0.57596594",
"0.5752083",
"0.57515967",
"0.5740458",
"0.5734371",
"0.57317793",
"0.5720255",
"0.57146305",
"0.5712973",
"0.57029146",
"0.56994176",
"0.5697037",
"0.5696312",
"0.5696312",
"0.5693216",
"0.56872135",
"0.56862783",
"0.5686241",
"0.5684054",
"0.5680525",
"0.56763464",
"0.5665756",
"0.56644946",
"0.56610554",
"0.565166",
"0.5648418",
"0.56400627",
"0.56369466",
"0.56357634",
"0.563457",
"0.5634294",
"0.5633159",
"0.56314826",
"0.56308234",
"0.5628334",
"0.5628334",
"0.5628334",
"0.5616715",
"0.5612865",
"0.5607693",
"0.560358"
] | 0.0 | -1 |
as_is transformation of input Copy values from input hash to output hash for keys specified by keys attribute. | def run(input)
{}.tap do |result|
keys.each do |key|
result[key] = input[key]
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def transform_keys!(hash)\n return enum_for(:transform_keys!, hash) unless block_given?\n hash.keys.each do |key|\n hash[yield(key)] = hash.delete(key)\n end\n hash\n end",
"def hash_to_hash(hash_from, hash_to)\n hash_from.each do |key, value|\n hash_to[key] = value\n end\n end",
"def conversicate\n hash = self.attributes.dup\n\n # Apparently for conversica:\n # 1) they do not like to receive nil values so we need to remove the nils\n # 2) we also need to convert integers into strings\n hash.reject! { |_k, v| v.nil? }\n hash.transform_values! { |v| v = v.is_a?(Integer) ? v.to_s : v }\n hash.transform_keys! { |k| k.camelize(:lower) }\n hash\n end",
"def transform_keys_to_symbols(hash)\n return hash if not hash.is_a?(Hash)\n hash.inject({}) { |result, (key, value)|\n new_key = case key\n when String then\n key.to_sym\n else\n key\n end\n new_value = case value\n when Hash\n if key.eql? 'attributes'\n value\n else\n transform_keys_to_symbols(value)\n end\n else\n value\n end\n result[new_key] = new_value\n result\n }\n end",
"def transform_keys_to_symbols(hash)\n return hash if not hash.is_a?(Hash)\n hash.inject({}) { |result, (key, value)|\n new_key = case key\n when String then key.to_sym\n else key\n end\n new_value = case value\n when Hash\n if key.eql? 'attributes'\n value\n else\n transform_keys_to_symbols(value)\n end\n else value\n end\n result[new_key] = new_value\n result\n }\n end",
"def deep_transform_hashes_of(hash, hash_cache = {})\n new_hash = FlexHash.new(mapping)\n hash.each_pair do |key, val|\n if val.class == Hash\n # only transform a given instance once\n hash_cache[val.object_id] ||= deep_transform_hashes_of(val, hash_cache)\n val = hash_cache[val.object_id]\n end\n new_hash[key] = val\n end\n new_hash\n end",
"def transform_keys!(&block); end",
"def pass(hash, allowed_keys)\n ret = {}\n hash.each do |k,v|\n ret[k] = v if allowed_keys.include? k\n end\n ret\n end",
"def deep_transform_keys!(hash, &block)\n _deep_transform_keys_in_object!(hash, &block)\n end",
"def symbolize_hash_keys(hash); end",
"def map_keys(hash)\n hash.map { |k, v| { yield(k) => v } }.reduce(:merge)\n end",
"def deep_transform_keys!(&block); end",
"def deconstruct_keys(keys)\n if @value.respond_to?(:deconstruct_keys)\n @value.deconstruct_keys(keys)\n else\n EMPTY_HASH\n end\n end",
"def deconstruct_keys(keys)\n if @value.respond_to?(:deconstruct_keys)\n @value.deconstruct_keys(keys)\n else\n EMPTY_HASH\n end\n end",
"def copyhash(inputhash)\n h = Hash.new\n inputhash.each do |pair|\n h.store(pair[0], pair[1])\n end\n return h\nend",
"def transform_keys(&block); end",
"def deconstruct_keys(keys)\n if @base_object.respond_to?(:deconstruct_keys)\n @base_object\n .deconstruct_keys(keys)\n .transform_values!(&NEW_DIVE)\n else\n keys.to_h { |k| @base_object.public_send(k).then { |v| [k, NEW_DIVE[v]] } }\n end\n end",
"def symbolize_keys(hash)\r\n target = hash.dup\r\n\r\n target.keys.each do |key|\r\n value = target.delete(key)\r\n if value.is_a? Hash\r\n value = symbolize_keys(value)\r\n end\r\n target[(key.to_sym rescue key) || key] = value\r\n end\r\n\r\n target\r\n end",
"def deep_transform_keys(&block); end",
"def to_hash(keys = :camelcase)\n\t\t\thash = super(keys)\n\t\t\treturn hash\n end",
"def hashishify_values\n @hash.each do |key, value|\n if @hash[key].kind_of? Hash\n @hash[key] = Hashish.new(value)\n elsif @hash[key].kind_of? Array\n @hash[key].each_index do |index|\n element = @hash[key][index]\n if element.kind_of? Hash\n @hash[key][index] = Hashish.new(element)\n end\n end\n end\n end\n end",
"def symbolize_keys!(hash)\n new_hash = hash.inject({}){ |memo, (k, v)|\n memo[k.to_sym] = v\n if v.class.eql? ::Hash\n memo[k.to_sym] = symbolize_keys! v\n elsif v.class.eql? ::Array\n memo[k.to_sym] = symbolize_keys_of_hashs! v\n end\n memo\n }\n hash.replace new_hash\n end",
"def symbolize_hash(old_hash)\n old_hash.each_with_object({}) { |(k, v), new_hash|\n new_hash[k.to_sym] = if v.is_a?(Hash)\n symbolize_hash(v)\n elsif v.is_a?(Array)\n v.map{ |h| h.is_a?(Hash) ? symbolize_hash(h) : h }\n else\n v\n end\n }\n end",
"def normalize_keys(hash)\n hash.inject(HashWithIndifferentAccess.new) do |new_hash, (key, value)|\n new_hash[key.parameterize(separator: \"_\")] = value\n new_hash\n end\n end",
"def _keys_to_hash(keys)\n keys.reduce({}) do |hsh, k|\n hsh.merge k.is_a?(Hash) ? k.symbolize_keys : { k.to_sym => k.to_sym }\n end\n end",
"def normalize(hash)\n hash.symbolize_keys if hash\n end",
"def to_input_hash\n Types::Coercible::Hash.schema(\n map { |attr| [attr.name, attr] }.to_h\n )\n end",
"def hash\n self.class.hash ^ key_attributes.hash\n end",
"def to_hash *args\n hsh = super(*args)\n hsh.each do |attr, val|\n hsh[attr] = val.to_hash if val.respond_to?(:to_hash)\n end\n hsh\n end",
"def hash_invert(hash, new_key)\n hash.each_with_object({}) { |(key, value), out| (out[value[new_key]] ||= []) << value.merge(prefix: key) }\n end",
"def clean_up(attr_values_hash_of_hash)\n\t\tattr_values = Hash.new\n\t\tattr_values_hash_of_hash.each do |bad_key,good_hash|\n\t\t\tattr_values.merge!(good_hash)\n\t\tend\n\t\treturn attr_values\n\tend",
"def normalize_keys(hash, method = :to_s)\n hash = hash.dup\n hash.keys.each do |k|\n normalized_key = k.respond_to?(method) ? k.send(method) : k\n hash[normalized_key] = hash.delete(k)\n end\n hash\n end",
"def to_h(keys: attribute_definitions.keys, enforce_read_only: false)\n casted_data = {}\n keys.each do |key|\n value = attribute_to_hash(key, enforce_read_only)\n # If the value is an empty hash but we specify that it is valid (via default value), serialize it\n casted_data[key] = value unless value.nil? || (value.respond_to?(:empty?) && value.empty? &&\n !(attribute_definitions[key].default == value && value.is_a?(Hash)))\n end\n casted_data\n end",
"def transform_values\n map_to_hash { |key, value| [key, yield(value)] }\n end",
"def slice_hash(hash, keys)\n keys.inject({}) do |memo, key|\n memo[key] = hash[key] if hash.has_key?(key)\n memo\n end\n end",
"def slice_hash(hash, keys)\n keys.inject({}) do |memo, key|\n memo[key] = hash[key] if hash.has_key?(key)\n memo\n end\n end",
"def coerce_keys(*attrs); end",
"def deep_transform_keys(hash, &block)\n result = {}\n hash.each do |key, value|\n result[yield(key)] = value.is_a?(Hash) ? deep_transform_keys(value, &block) : value\n end if hash\n result\n end",
"def underscorize_keys(hash)\n return unless hash.is_a?(Hash)\n hash.keys.each do |k|\n key = k.to_s.underscore.to_sym\n hash[key] = hash[k]\n hash.delete(k) if key != k\n end\n hash\n end",
"def clean(source,target)\n source.stringify_keys!\n target.stringify_keys!\n output = Hash.new\n target.each do |key,value|\n if not value.is_a? Hash and source[key]\n output[key] = value\n elsif value.is_a? Hash and source[key]\n output[key] = clean(source[key],value)\n else\n puts \" Cleaning #{key} from target\"\n end\n end\n return output\nend",
"def filter(*keys)\n if self.respond_to?(:to_hash_proxy) then\n to_hash_proxy.filter(*keys)\n else\n raise NotImplementedError.new('not implemented for plain hash')\n end\n end",
"def to_normal_hash(hash)\n hash.to_h.transform_keys(&:to_sym)\n end",
"def flatten_keys(hash)\n hash.transform_keys(&:downcase).transform_keys(&:to_sym)\n end",
"def from_candy(hash)\n unwrapped = {}\n hash.each do |key, value|\n field = Wrapper.unwrap_key(key)\n unwrapped[field] = Wrapper.unwrap(value, self, field)\n end\n unwrapped\n end",
"def remainder_hash!(hash, *keys)\n keys = gather_keys(*keys)\n hash = normalize_hash(hash) unless hash.class == ::Hash\n hash.slice!(*keys)\n end",
"def convert(lines, keys)\n array = Array.new\n \n lines.each do |line|\n zipped = keys.zip(line)\n \n # Filter value (Integer, Boolean, \"\" for nil, or String#strip)\n for pair in zipped\n value = pair.pop \n pair << filter(value)\n end\n \n array << Hash[zipped]\n end\n\n return array\n end",
"def ordered_clean_hash source\n ordered_keys.each_with_object({}) do |key, target|\n if source.key? key\n target[key] = source[key] unless value_is_an_empty_hash(source[key])\n end\n end\n end",
"def shallow_update(other_hash)\n other_hash.each_pair do |k,v|\n regular_writer(convert_key(k), convert_value(v, true))\n end\n self\n end",
"def untaint_values( hash )\n\t\tnewhash = {}\n\n\t\thash.each do |key,val|\n\t\t\tcase val\n\t\t\twhen Hash\n\t\t\t\tnewhash[ key ] = untaint_values( hash[key] )\n\n\t\t\twhen NilClass, TrueClass, FalseClass, Numeric, Symbol\n\t\t\t\tnewhash[ key ] = val\n\n\t\t\twhen Arrow::Path\n\t\t\t\t# Arrow::Logger[ self ].debug \"Untainting %p\" % val\n\t\t\t\tval.untaint\n\t\t\t\tnewhash[ key ] = val\n\n\t\t\twhen Array\n\t\t\t\t# Arrow::Logger[ self ].debug \"Untainting array %p\" % val\n\t\t\t\tnewval = val.collect do |v|\n\t\t\t\t\tcase v\n\t\t\t\t\twhen NilClass, TrueClass, FalseClass, Numeric, Symbol\n\t\t\t\t\t\tv\n\t\t\t\t\telse\n\t\t\t\t\t\tv.dup.untaint\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tnewhash[ key ] = newval\n\n\t\t\telse\n\t\t\t\t# Arrow::Logger[ self ].debug \"Untainting %p\" % val\n\t\t\t\tnewval = val.dup\n\t\t\t\tnewval.untaint\n\t\t\t\tnewhash[ key ] = newval\n\t\t\tend\n\t\tend\n\n\t\treturn newhash\n\tend",
"def convert_hash(hash)\n raise ArgumentError, \"#{hash.inspect} is not a Hash\" unless Hash === hash\n\n hash.keys.each do |key|\n hash[(key.to_sym rescue key) || key] = convert hash.delete(key)\n end\n\n hash.keys.all? do |k|\n Symbol === k or raise ArgumentError, \"keys must be Symbols, #{k.inspect} is not\"\n end\n hash\n end",
"def desymbolize(hash)\n new_hash = Hash.new\n hash.each do |k, v|\n new_hash[k.to_s] = v\n end\n new_hash\n end",
"def hashie_stringify_keys\n dup.stringify_keys!\n end",
"def deep_update(other_hash)\n other_hash = other_hash.to_hash if other_hash.is_a?(DocumentMapper::Base)\n other_hash = other_hash.stringify_keys\n other_hash.each_pair do |k,v|\n k = convert_key(k)\n self[k] = self[k].to_mash if self[k].is_a?(Hash) unless self[k].is_a?(DocumentMapper::Base)\n if self[k].is_a?(Hash) && other_hash[k].is_a?(Hash)\n self[k] = self[k].deep_merge(other_hash[k]).dup\n else\n self.send(k + \"=\", convert_value(other_hash[k],true))\n end\n end\n end",
"def values_at(*keys)\n super(*keys.map(&method(:convert_key)))\n end",
"def deep_stringify_keys(hash)\n hash.each_with_object({}) do |(key, value), new_hash|\n new_hash[key.to_s] = (value.respond_to?(:to_hash) ? deep_stringify_keys(value) : value)\n end\n end",
"def with_keys\n keys.each_with_object self.class.new do |hash_key, hsh|\n hsh[ yield hash_key ] = self[ hash_key ]\n end\n end",
"def filter_hash!(hsh)\n [[:timestamp, ->(t) { t.to_f }]].each do |k, f|\n hsh[k] = f.call(hsh[k])\n end\n hsh\n end",
"def transform_hash(original, &block)\n original.inject({}) do |result, (key, value)|\n value = if value.is_a?(Hash)\n transform_hash(value, &block)\n else\n value\n end\n yield(result, key, value)\n result\n end\n end",
"def copy_attributes(hsh_copy_to, hsh_copy_from, attr_to_copy_list)\n\t\t\t\tattr_to_copy_list.each do |a_attr_to_copy|\n\t\t\t\t\thsh_copy_to[a_attr_to_copy] = hsh_copy_from[a_attr_to_copy]\n\t\t\t\tend\n\t\t\t\treturn hsh_copy_to\n\t\t\tend",
"def copy_hash(hash, wrapper: {})\n hash.each_with_object(wrapper) do |(key, value), new|\n new[key] = value.is_a?(Hash) ? copy_hash(value) : value\n end\n end",
"def modify_keys\n each_with_object self.class.new do |hash_pair, hsh|\n hsh[ yield( hash_pair ) ] = self[ hash_pair[0] ]\n end\n end",
"def to_hash\n\t\tpure_hash = {}\n\t\t@hash.each do |info|\n\t\t\tpure_hash[info.key] = info.value\n\t\tend\n\t\tpure_hash\n\tend",
"def deep_copy_label_hash(hash)\n tmp = Hash.new{|h,k| h[k] = PolicyHelper.new }\n hash.each do |k,v|\n tmp[k] = v.dup\n end\n tmp\n end",
"def symbolize_keys(hash)\n hash.inject({}){|result, (key, value)|\n new_key = case key\n when String then key.to_sym\n else key\n end\n new_value = case value\n when Hash then symbolize_keys(value)\n else value\n end\n result[new_key] = new_value\n result\n }\n end",
"def transform_keys\n { a: 1, b: 2 }.transform_keys { |key| key_map[key] || key }\n end",
"def symbolize_keys(hash)\n hash.inject({}){|result, (key, value)|\n new_key = case key\n when String then key.to_sym\n else key\n end\n new_value = case value\n when Hash then symbolize_keys(value)\n else value\n end\n result[new_key] = new_value\n result\n }\nend",
"def normalize_keys(hash)\n hash.each{|k, v|\n hash.delete(k) unless @@valid_types.include?(v.class)\n if k.is_a?(String)\n hash.delete(k)\n hash[k.gsub(/\\-/, \"_\").to_sym] = v\n elsif !k.is_a?(Symbol) # elsunless\n hash.delete(k)\n end\n }\n return hash\nend",
"def sanitize_keys(hash)\n new_hash = Hash.new\n hash.each do |key,value|\n sanitized_key = key.downcase.tr(\" \", \"_\")\n\n if value.is_a? Hash\n new_hash[sanitized_key] = sanitize_keys(value)\n else\n new_hash[sanitized_key] = value\n end\n end\n return new_hash\n end",
"def project_attribute_hash\n to_a.inject({}) { |hash,(k,v)| hash[k] = v }\n end",
"def accept_keys!(hash, keys)\n reject_keys!(hash, hash.keys - keys)\n end",
"def deep_stringify_keys!(hash)\n deep_transform_keys!(hash){ |key| key.to_s }\n end",
"def invert_hash_of_arrays(hash)\n hash.reduce({}) do |memo, (key, values)|\n values.each do |v|\n memo[v] ||= []\n memo[v] << key\n end\n\n memo\n end\n end",
"def transform_hash(hash, path = \"\")\n hash.each_with_object({}) do |(k, v), ret|\n key = path + k.to_s\n\n if v.is_a?(Hash)\n ret.merge! transform_hash(v, \"#{key}:\")\n else\n ret[key] = v\n end\n end\n end",
"def deep_transform_keys!(&block)\n keys.each do |key|\n value = delete(key)\n self[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys!(&block) : value\n end\n self\n end",
"def deep_transform_keys!(&block)\n keys.each do |key|\n value = delete(key)\n self[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys!(&block) : value\n end\n self\n end",
"def copy_options_to_attributes(keys)\n keys.each do |k|\n if @opts.has_key?(k) && !@attr.has_key?(k)\n @attr[k] = @opts[k]\n end\n end\n end",
"def reverse_assign_attributes(attributes_hash)\n attributes_to_assign = attributes_hash.keys.reject{|_attribute_name| attribute_present?(_attribute_name) }\n\n assign_attributes(attributes_hash.slice(attributes_to_assign))\n end",
"def keys_to_symbols(hash)\n\t\thash.keys.inject({}) do |hsh, key|\n\t\t\thsh[key.to_sym] = hash[key]\n\t\t\thsh\n\t\tend\n\tend",
"def map_keys!(hash, fn)\n hash.keys.each { |key| hash[fn[key]] = hash.delete(key) }\n hash\n end",
"def deep_copy_hash hash\n require_that(hash.is_a?(Hash), \"deep_copy_hash requires a hash be specified, got #{hash.class}\")\n Marshal.load Marshal.dump(hash)\n end",
"def attributes_to_copy_to_neo4j(*keys)\n @attribute_keys_to_copy_to_neo4j = [] unless defined?(@attribute_keys_to_copy_to_neo4j)\n @attribute_keys_to_copy_to_neo4j += keys\n end",
"def deep_transform_keys(&block)\n _deep_transform_keys_in_object(self, &block)\n end",
"def deep_transform_keys(&block)\n _deep_transform_keys_in_object(self, &block)\n end",
"def from_h(a_hash)\n a_hash.each_pair do |k, v|\n add k\n send(\"#{k}=\", v)\n end\n end",
"def sanitize_keys(hash, keys_to_sanitize)\n hash.each_with_object({}) do |(k, v), h|\n k = k.to_s.downcase\n if keys_to_sanitize.include?(k)\n h[k] = SANITIZED_VALUE\n else\n h[k] = v\n end\n end\n end",
"def replace_values(hash, filtered_keys = [], new_value = nil)\n\t\t\thash.map do |key, value|\n\t\t\t\t(filtered_keys.include?(key) && new_value) ? [key, new_value] : [key, value]\n\t\t\tend.to_h\n\t\tend",
"def symbolize_hash hash\n hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}\n end",
"def extract_hash!(hash, *keys)\n keys = gather_keys(*keys)\n hash = normalize_hash(hash) unless hash.class == ::Hash\n hash.slice(*keys).tap { |matches| hash.except!(*matches.keys) }\n end",
"def rewrite_attributes(h={})\n row, original_primary_key, record_class \\\n = CkuruTools.validate_hash_arguments(h,\n [:row,{:instance_that_inherits_from => ActiveRecord::Base,:required => true}],\n [:original_primary_key,{:instance_that_inherits_from => String,:required => true}],\n [:record_class,{:klass_that_inherits_from => ActiveRecord::Base,:required => true}]\n )\n\n\n new = Hash.new\n row.attributes.keys.each do |k|\n new_key = k.downcase\n if new_key == record_class.primary_key\n if new_key == original_primary_key\n ckebug 0, \"mapping #{new_key} from #{record_class.primary_key}\"\n new_key = \"original_#{new_key}\"\n else\n ckebug 1, \"skipping attribute #{new_key}; assuming this is the system generated key\"\n next\n end\n end\n new[new_key] = row.attributes[k]\n end\n return new\n end",
"def to_output_hash\n Types::Coercible::Hash.schema(\n map { |attr| [attr.key, attr.to_read_type] }.to_h\n )\n end",
"def symbolize_keys(hash)\n hash.inject({}) { |memo, (k, v)| memo[k.to_sym] = v; memo }\n end",
"def __convert hash #:nodoc:\n instance = self.class.new\n hash.each do |k, v|\n k = k.to_s if !k.respond_to?(:to_sym) && k.respond_to?(:to_s)\n instance.new_ostruct_member k\n if v.is_a?(Hash)\n v = v[\"type\"] == \"hash\" ? v[\"contents\"] : __convert(v)\n elsif v.is_a?(Array)\n v = v.map{|e| e.instance_of?(Hash) ? __convert(e) : e}\n end\n instance.send \"#{k}=\".to_sym, v\n end\n instance\n end",
"def values_at(*keys)\n keys.map! { |key| convert_key(key) }\n super\n end",
"def deep_copy_hash g\n h = {}\n g.each_pair do |k,v|\n v = Marshal.load(Marshal.dump(v))\n h[k] = v\n end\n h\nend",
"def serializable_hash(options)\n original_hash = super(options)\n Hash[original_hash.map {|k, v| [self.aliased_fields.invert[k] || k , v] }]\n end",
"def symbolify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tkeysym = key.to_s.dup.untaint.to_sym\n\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ keysym ] = symbolify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ keysym ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def symbolify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tkeysym = key.to_s.dup.untaint.to_sym\n\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ keysym ] = symbolify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ keysym ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def symbolify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tkeysym = key.to_s.dup.untaint.to_sym\n\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ keysym ] = symbolify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ keysym ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def symbolify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tkeysym = key.to_s.dup.untaint.to_sym\n\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ keysym ] = symbolify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ keysym ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def __deep_copy__\n self.class.new(aliases, serializers, associations, aliased_associations) do |copy|\n each_pair do |key, value|\n copy.merge!(key => value.__deep_copy__)\n end\n end\n end",
"def deep_stringify_keys(hash)\n transform_hash(hash, :deep => true) {|hash, key, value|\n hash[key.to_s] = value\n }\n end"
] | [
"0.6288772",
"0.6115494",
"0.60285205",
"0.5999685",
"0.5984444",
"0.5965115",
"0.5906839",
"0.58621645",
"0.5849198",
"0.58331937",
"0.58055055",
"0.57818747",
"0.5772143",
"0.5772143",
"0.57685286",
"0.5765048",
"0.57573473",
"0.5752304",
"0.5740258",
"0.5737534",
"0.5733638",
"0.5672069",
"0.5663139",
"0.5659746",
"0.5636302",
"0.5625327",
"0.5607077",
"0.5565613",
"0.5557335",
"0.555304",
"0.55514634",
"0.55324894",
"0.5528614",
"0.552183",
"0.55184746",
"0.55184746",
"0.55073935",
"0.55041426",
"0.54993856",
"0.5495638",
"0.54857326",
"0.5484413",
"0.54843074",
"0.5474814",
"0.5464187",
"0.5460193",
"0.5457481",
"0.5443095",
"0.54412335",
"0.5428994",
"0.5423646",
"0.5413053",
"0.5409682",
"0.5393553",
"0.5389683",
"0.5387534",
"0.53799546",
"0.53757834",
"0.5375431",
"0.5370502",
"0.53663015",
"0.5362911",
"0.5359828",
"0.5354124",
"0.53511083",
"0.53481764",
"0.53442055",
"0.5341893",
"0.53392243",
"0.5328792",
"0.5323309",
"0.5322502",
"0.5320464",
"0.5317801",
"0.5317801",
"0.531455",
"0.53131026",
"0.5311976",
"0.53097916",
"0.530912",
"0.53046393",
"0.5304497",
"0.5304497",
"0.53011537",
"0.53000104",
"0.529394",
"0.52937806",
"0.52925456",
"0.5290094",
"0.52880895",
"0.52856845",
"0.5274862",
"0.5273297",
"0.5268563",
"0.526817",
"0.526348",
"0.526348",
"0.526348",
"0.526348",
"0.5255422",
"0.52525026"
] | 0.0 | -1 |
Returns the recipe classes in order based on the Gemfile order | def ordered_recipes
return @ordered_recipes if @ordered_recipes
names = Bundler.load.dependencies.map(&:name)
# Setup a hash with the recipe name and the recipe class
recipe_pool = recipes.dup.inject({}) {|memo,recipe| memo[recipe.gem_name] = recipe ; memo }
# Go through the gems in the order they are in the Gemfile, then
# add them to the ordered list
@ordered_recipes = []
names.each do |name|
if recipe_pool[name]
@ordered_recipes << recipe_pool[name]
recipe_pool.delete(name)
end
end
# Add the remaining recipes (load them after everything else)
@ordered_recipes += recipe_pool.values
return @ordered_recipes
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def depends_all\n pkg_depends = self.class.depends_all\n if self.class.omnibus_package\n self.class.omnibus_recipes.each { |omni_recipe|\n recipe_file = File.expand_path(omni_recipe + '.rb', File.dirname(filename))\n\n Book.instance.load_recipe(recipe_file, config) do |recipe|\n pkg_depends << recipe.depends_all\n end\n }\n end\n\n pkg_depends.flatten.uniq\n end",
"def depends_all\n pkg_depends = self.class.depends_all\n if self.class.omnibus_package\n self.class.omnibus_recipes.each { |omni_recipe|\n recipe_file = File.expand_path(omni_recipe + '.rb', File.dirname(filename))\n\n Book.instance.load_recipe(recipe_file, config) do |recipe|\n pkg_depends << recipe.depends_all\n end\n }\n end\n\n pkg_depends.flatten.uniq\n end",
"def cookbook_order\n @cookbook_order ||= begin\n ordered_cookbooks = []\n seen_cookbooks = {}\n run_list_expansion.recipes.each do |recipe|\n cookbook = Chef::Recipe.parse_recipe_name(recipe).first\n add_cookbook_with_deps(ordered_cookbooks, seen_cookbooks, cookbook)\n end\n logger.debug(\"Cookbooks to compile: #{ordered_cookbooks.inspect}\")\n ordered_cookbooks\n end\n end",
"def gems\n Recommendable.config.ratable_classes.map { |klass| gemd_for(klass) }.flatten\n end",
"def find_classes\n puppetClasses = []\n Dir.glob( SpkDashboard::MANIFEST_ROOT + \"/modules/**/*.pp\" ).each do |manifest|\n File.read( manifest ).each do |line|\n foundClass = line.match(/^class (\\S+).*\\{/)\n if foundClass and puppetClasses.include?( foundClass[1] ) == false\n puppetClasses << foundClass[1]\n end\n end\n end\n \n return puppetClasses\n end",
"def requires\n require_items.collect(&:package)\n end",
"def runtime_specific_gems\n []\n end",
"def depends_upon(match_name) #, constraint)\n list = []\n $LEDGER.each do |name, libs|\n case libs\n when Library\n list << libs if libs.requirements.any?{ |r| match_name == r['name'] } \n else\n libs.each do |lib|\n list << lib if lib.requirements.any?{ |r| match_name == r['name'] } \n end\n end\n end\n list\n end",
"def dependencies\n return @dependencies unless @dependencies.nil?\n @dependencies = [ ]\n lockfile.each_line do |line|\n if line =~ /^\\s{4}([-\\w_.0-9]+)\\s*\\((.*)\\)/\n @dependencies << [$1, $2]\n end\n end\n @dependencies\n end",
"def r(*gems)\n gems.map {|g| require g.to_s}\nend",
"def libraries_order\n order = [:Ruby_]\n order.unshift(:Statistics2_) if has_statistics2?\n order.unshift(:GSL_) if has_gsl?\n order.unshift(:Java_) if has_java?\n order\n end",
"def classes()\n\t\t\t\tlist = []\n\t\t\t\tdir = Dir.new( path() )\n\t\t\t\t\n\t\t\t\tdir.each do |file|\n\t\t\t\t\tnext if File.directory?( path() + \"/\" + file )\n\t\t\t\t\tnext if ( file[/^([A-Z][A-Za-z]*)+\\.class\\.rb$/] == nil )\n\t\t\t\t\tlist << clazz( $1 )\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\treturn list\n\t\t\tend",
"def patch_files\n Dir[File.join( recipe_dir, \"*.patch\" )].sort\n end",
"def depend_upon(match_name) #, constraint)\n list = []\n each do |name, libs|\n case libs\n when Library\n list << libs if libs.requirements.any?{ |r| match_name == r['name'] } \n else\n libs.each do |lib|\n list << lib if lib.requirements.any?{ |r| match_name == r['name'] } \n end\n end\n end\n list\n end",
"def list_known_classes names = []\n classes = []\n stores.each do |store|\n classes << store.modules\n end\n classes = classes.flatten.uniq.sort\n unless names.empty? then\n filter = Regexp.union names.map { |name| /^#{name}/ }\n classes = classes.grep filter\n end\n puts classes.join(\"\\n\")\n end",
"def recipes\n @_recipes ||= (\n %w[dorc **/*.rake].map { |f| Dir[File.join(DO_PATH, f)] }.flatten +\n %w[./Do ./Dofile].map { |f| File.expand_path(f) } <<\n File.expand_path('../common.rb', __FILE__)\n ).reject { |f| !File.exist?(f) }\n end",
"def recipes_from_cookbook_version(cookbook)\n cookbook.fully_qualified_recipe_names.map do |recipe_name|\n unqualified_name =\n if /::default$/.match?(recipe_name)\n name.to_s\n else\n recipe_name\n end\n\n @recipes[unqualified_name] ||= \"\"\n provides(unqualified_name)\n\n unqualified_name\n end\n end",
"def requires\n @requires ||= @dependencies.map { |e| make_path(e.split(RUBY_PKG_SEP)) }.sort.uniq\n end",
"def card_classes\n model_files = Dir.glob(\"#{Rails.root}/app/lib/#{name.underscore}/*.rb\")\n model_names = model_files.map { |fn| File.basename(fn, '.rb').camelize }\n model_names.map { |mn| \"#{name}::#{mn}\".constantize }.sort_by { |c| [c.try(:raw_cost), c.readable_name] }\n end",
"def fetch_dependencies()\n\t\"berks vendor cookbooks #{(@debug ? '-v' : '-q')}\"\n end",
"def dependencies\n version_req = if options[:version]\n ::Gem::Requirement.create(options[:version])\n else\n ::Gem::Requirement.default\n end\n if gem_dir\n ::Gem.clear_paths; ::Gem.path.unshift(gem_dir)\n ::Gem.source_index.refresh!\n end\n deps = []\n ::Gem.source_index.each do |fullname, gemspec| \n if version_req.satisfied_by?(gemspec.version)\n deps << ::Gem::Dependency.new(gemspec.name, \"= #{gemspec.version}\")\n end\n end\n ::Gem.clear_paths if gem_dir\n deps.sort\n end",
"def get_sorted_module_list classes\n classes.select do |klass|\n klass.display?\n end.sort\n end",
"def list_known_classes names = []\n classes = []\n\n stores.each do |store|\n classes << store.module_names\n end\n\n classes = classes.flatten.uniq.sort\n\n unless names.empty? then\n filter = Regexp.union names.map { |name| /^#{name}/ }\n\n classes = classes.grep filter\n end\n\n page do |io|\n if paging? or io.tty? then\n if names.empty? then\n io.puts \"Classes and Modules known to ri:\"\n else\n io.puts \"Classes and Modules starting with #{names.join ', '}:\"\n end\n io.puts\n end\n\n io.puts classes.join(\"\\n\")\n end\n end",
"def get_requirements\n result = `rake gems 2>&1`\n parse_required(result) + parse_missing(result) + parse_deps(result)\n end",
"def manifest_dependencies()\n as_bundle = Bundle.fromProject(self)\n as_bundle.nil? ? [] : as_bundle.bundles.collect{|b| b.resolve}.compact + as_bundle.imports.collect {|i| i.resolve}.flatten\n end",
"def faker_modules\n FFaker\n .constants\n .reject { |const| UTILS_MODULES.include?(const) }\n .select { |const| FFaker.const_get(const).instance_of?(Module) }\n .sort\n .map { |const| FFaker.const_get(const) }\nend",
"def find_package_cls(package_path, io)\n return [] unless File.extname(package_path) == '.rb'\n\n mod = Module.new\n package_script = io.read package_path\n\n begin\n mod.class_eval package_script, package_path, 1\n rescue Exception => e # rubocop:disable RescueException\n raise ImportScriptError.new package_path, e\n end\n\n # Iterate over all constants/classes defined by the script.\n # If a constant defines a package return it.\n mod.constants.sort\n .map(&mod.method(:const_get))\n .select { |const| !const.nil? && const < Package }\n end",
"def init_gemspecs\n Gem.source_index.map { |_, spec| spec }.sort { |a,b|\n\t(a.name <=> b.name).nonzero? || (b.version <=> a.version)\n }\n end",
"def classes_and_includes_and_extends_for name\n klasses = []\n extends = []\n includes = []\n\n found = @stores.map do |store|\n begin\n klass = store.load_class name\n klasses << klass\n extends << [klass.extends, store] if klass.extends\n includes << [klass.includes, store] if klass.includes\n [store, klass]\n rescue RDoc::Store::MissingFileError\n end\n end.compact\n\n extends.reject! do |modules,| modules.empty? end\n includes.reject! do |modules,| modules.empty? end\n\n [found, klasses, includes, extends]\n end",
"def packages\n Dir[File.join($__HELLO_DIR__, 'packages/*/*.yml')]\n .map do |yml|\n info = YAML.load File.read yml\n info['dir'] = File.dirname yml if info\n info\n end\n .select {|p| p }\n .sort_by {|p| p['priority'] || 10 }\nend",
"def bundler_dependencies_for(bundler_runtime, *groups); end",
"def all_classes_and_modules\n result = []\n ObjectSpace.each_object(Module) { |m| result << m }\n result.sort_by {|m| m.name}\nend",
"def gemspecs; end",
"def ordered_by_deps(apps, processed = Set[])\n ordered = []\n apps.each do |tag, info|\n next if processed.include?(tag)\n\n if deps = Array(info[\"depends-on\"])\n dep_apps = {}\n deps.each do |dep|\n dep_apps[dep] = apps[dep]\n end\n\n processed.add(tag)\n\n ordered += ordered_by_deps(dep_apps, processed)\n ordered << info\n else\n ordered << info\n processed.add(tag)\n end\n end\n\n ordered.each { |app| app.delete(\"depends-on\") }\n\n ordered\n end",
"def get_class_descriptions(klass)\n available_versions.map do |version|\n get_class_description(klass, version)\n end.compact\n end",
"def find_app_helper_classes\n klasses = []\n expression = \"#{Jets.root}app/helpers/**/*\"\n Dir.glob(expression).each do |path|\n next unless File.file?(path)\n class_name = path.sub(\"#{Jets.root}app/helpers/\",\"\").sub(/\\.rb/,'')\n unless class_name == \"application_helper\"\n klasses << class_name.classify.constantize # autoload\n end\n end\n klasses\n end",
"def boot_order\n @boot_order || REXML::XPath.match(@definition, \"//os/boot\").map { |d| d.attributes[\"dev\"].to_sym }\n end",
"def dependent_specs\n runtime_dependencies.map {|dep| dep.to_specs }.flatten\n end",
"def packages\n FileList[package_path('.*')]\n end",
"def find_jars_to_patch()\n all_jars = Dir.glob(File.join(\"**\", \"*.jar\"))\n jars_to_patch = Array.new\n finalized_jars = Array.new\n\n File.open(\"finalized-jarlist.txt\").each_line do |f|\n # get the package name\n\n # +1 to rindex is to get rid of the begining /\n f = f.slice!(f.rindex('/')+1..f.length)\n f = f.slice(0...f.rindex('-'))\n finalized_jars.push(f)\n end\n\n all_jars.each do |jar|\n found = 0\n\n finalized_jars.each do |f|\n if not jar.match(f).nil? then\n found = 1\n break\n end\n end\n\n jars_to_patch.push(jar) if found == 1\n end\n return jars_to_patch\nend",
"def with_fully_qualified_names_and_version_constraints\n map do |recipe_name|\n qualified_recipe = if recipe_name.include?(\"::\")\n recipe_name\n else\n \"#{recipe_name}::default\"\n end\n\n version = @versions[recipe_name]\n qualified_recipe = \"#{qualified_recipe}@#{version}\" if version\n\n qualified_recipe\n end\n end",
"def for_lockfile # :nodoc:\n return if [DefaultRequirement] == @requirements\n\n list = requirements.sort_by do |_, version|\n version\n end.map do |op, version|\n \"#{op} #{version}\"\n end.uniq\n\n \" (#{list.join ', '})\"\n end",
"def legitimize! deps = entries\n specs = []\n\n deps.flatten.each do |dep|\n spec = case dep\n when Gem::Dependency then\n begin\n dep.to_spec\n rescue Gem::LoadError\n nil\n end\n when Isolate::Entry then\n dep.specification\n else\n raise \"unknown dep: #{dep.inspect}\"\n end\n\n if spec then\n specs.concat legitimize!(spec.runtime_dependencies)\n specs << spec\n end\n end\n\n specs.uniq\n end",
"def class_names\n return if @class_names.empty?\n @class_names.uniq.sort\n end",
"def pythons\n deps.map(&:to_formula)\n .select { |f| f.name.match?(/^python@\\d\\.\\d+$/) }\n .sort_by(&:version)\n .map { |f| f.opt_libexec/\"bin/python\" }\n end",
"def dependency_classes\n res = []\n\n eager_loaded_components.keys.each do |aggr|\n res += component_instance(aggr).dependency_classes\n end\n\n res += self.class.class_ancestors\n\n res << self.class\n res.uniq\n end",
"def existing_packages\n paths_by_app = Dir[File.join(config[:packages_dir], '*', '*.{tar.gz,json}')].group_by { |path|\n path.split(File::SEPARATOR)[-2]\n }\n\n Hash[\n paths_by_app.map { |app, paths|\n names_by_base = paths.group_by do |path|\n File.basename(path).sub(/\\.(?:tar\\.gz|json)\\z/, '')\n end\n\n packages = names_by_base.flat_map { |base, names|\n names.map do |name|\n (\n name.end_with?(\".tar.gz\") &&\n names.find { |_| _.end_with?(\".json\") } &&\n base\n ) || nil\n end\n }.compact\n\n [app, packages.sort]\n }\n ]\n end",
"def install_dependencies\n recipe_eval do\n run_context.include_recipe 'chef-sugar::default'\n run_context.include_recipe 'build-essential::default'\n\n case node.platform_family\n when 'debian'\n package 'curl'\n package 'git-core'\n package 'libxml2-dev'\n package 'libxslt-dev'\n package 'zlib1g-dev'\n package 'ncurses-dev'\n package 'libssl-dev'\n when 'freebsd'\n package 'textproc/libxml2'\n package 'textproc/libxslt'\n package 'devel/ncurses'\n when 'mac_os_x'\n run_context.include_recipe 'homebrew::default'\n package 'libxml2'\n package 'libxslt'\n package 'openssl'\n when 'rhel'\n package 'curl'\n package 'bzip2'\n package 'file'\n package 'git'\n package 'libxml2-devel'\n package 'libxslt-devel'\n package 'ncurses-devel'\n package 'zlib-devel'\n package 'openssl-devel'\n end\n end\n end",
"def required_gem_list\n Mack::Utils::GemManager.instance.required_gem_list\n end",
"def require_libraries\n original = class_list\n Util.load_dir Config::ComponentDir + \"/#{@name.downcase}\"\n new = class_list\n\n new_modules = new - original\n new_models = new_modules.select do |m|\n subclass?(m, Derailed::Component::Model) ||\n (defined?(Authlogic) && subclass?(m, Authlogic::Session::Base))\n end\n\n controller_array = new_modules.select do |m|\n subclass?(m, Derailed::Component::Controller)\n end\n\n new_models.each do |m|\n if subclass?(m, Derailed::Component::Model)\n m.full_model_name = \"#{name}::#{m.name}\"\n end\n end\n\n [new_models,controller_array[0]] # we should only have one controller\n end",
"def package_depends_on\n depends_on\n end",
"def dependent_gems(check_dev=true)\n out = []\n Gem::Specification.each do |spec|\n deps = check_dev ? spec.dependencies : spec.runtime_dependencies\n deps.each do |dep|\n if self.satisfies_requirement?(dep)\n sats = []\n find_all_satisfiers(dep) do |sat|\n sats << sat\n end\n out << [spec, dep, sats]\n end\n end\n end\n out\n end",
"def find_dependencies(env)\n args = [] if (env = env.dup).sub!(REGEXP_DEVPKG,'') # are we in compile mode?\n return [[], [], args] if args && env.empty?\n\n require 'rubygems/remote_fetcher'\n @@deps = YAML.load(fetch(env))['gems'] unless defined?(@@deps)\n @@deps.key?(spec.name) or return(args ? [[], [], args] : nil)\n\n # find dependencies\n case deps = @@deps[spec.name]\n when nil, \"*\" # for nil or '*', use the default extension name\n deps = [\"*\"]\n when String # string of space-delimited packages and extensions\n when Array # array of packages and extensions\n when Hash # hash of packages and extensions, indexed by version requirements\n reqs, deps = deps.find do |reqs, info| # deps is an array or space-delimited string\n Gem::Requirement.new(reqs.split(',')).satisfied_by?(spec.version)\n end\n reqs or return # can't find the right version\n deps ||= [\"*\"] # deps are nil, use the default extension name\n end\n deps = deps.strip.split(/\\s+/) if deps.is_a?(String)\n deps = deps.compact.uniq\n\n # helpful variables\n bcwd = Dir.pwd\n benv = File.dirname(env.split(/[?;#]/,2).first)\n name = \"#{spec.full_name}.tar.gz\"\n\n # grok dependencies\n pkgs, exts = [], []\n deps.each do |item|\n if item.include?(\"*\") || item =~ REGEXP_SCHEMA || item.include?(\".tar.gz\")\n exts << item unless args\n elsif item =~ REGEXP_DEVPKG\n pkgs << $' if args\n elsif item =~ REGEXP_DEVARG\n args << $' if args\n else\n pkgs << item unless args\n end\n end\n exts.map! do |item|\n case item\n when \"*\" then item = File.join(benv, name) # use complete default tarball name\n when /\\A\\*/ then item[0,1] = benv # path relative to env variable\n when /\\A[^\\/]/ then item[0,0] = bcwd + \"/\" # path relative to current directory\n end\n item.gsub(\"*\", name) # swap inline wildcards with default tarball name\n end\n [pkgs, exts, args]\n end",
"def get_sorted_module_list( classes )\n\t\tnscounts = classes.keys.inject({}) do |counthash, name|\n\t\t\ttoplevel = name.gsub( /::.*/, '' )\n\t\t\tcounthash[toplevel] ||= 0\n\t\t\tcounthash[toplevel] += 1\n\t\t\t\n\t\t\tcounthash\n\t\tend\n\n\t\t# Sort based on how often the toplevel namespace occurs, and then on the name \n\t\t# of the module -- this works for projects that put their stuff into a \n\t\t# namespace, of course, but doesn't hurt if they don't.\n\t\treturn classes.keys.sort_by do |name| \n\t\t\ttoplevel = name.gsub( /::.*/, '' )\n\t\t\t[\n\t\t\t\tnscounts[ toplevel ] * -1,\n\t\t\t\tname\n\t\t\t]\n\t\tend\n\tend",
"def get_sorted_module_list( classes )\n\t\tnscounts = classes.keys.inject({}) do |counthash, name|\n\t\t\ttoplevel = name.gsub( /::.*/, '' )\n\t\t\tcounthash[toplevel] ||= 0\n\t\t\tcounthash[toplevel] += 1\n\t\t\t\n\t\t\tcounthash\n\t\tend\n\n\t\t# Sort based on how often the toplevel namespace occurs, and then on the name \n\t\t# of the module -- this works for projects that put their stuff into a \n\t\t# namespace, of course, but doesn't hurt if they don't.\n\t\treturn classes.keys.sort_by do |name| \n\t\t\ttoplevel = name.gsub( /::.*/, '' )\n\t\t\t[\n\t\t\t\tnscounts[ toplevel ] * -1,\n\t\t\t\tname\n\t\t\t]\n\t\tend\n\tend",
"def line_order\n [:controller_files, :model_files, :view_files, :lib_files, :controller_specs, :model_specs, :view_specs]\n end",
"def main_package_set\n each_package_set.find(&:main?)\n end",
"def generate_recipes_list\n recipes = YARD::Registry.all(:recipe).uniq.sort_by {|recipe| recipe.Name.to_s}\n generate_full_list(recipes, 'Recipe', 'recipes')\nend",
"def suite_classes\n suite_names.map(&:safe_constantize).compact\n end",
"def install_order(arr)\n result = []\n\n hash_pkg = Hash.new {|k,v| v = []}\n\n arr.each do |tup|\n hash_pkg[tup[0]] += [tup[1]]\n end\n\n (1..hash_pkg.keys.max).each do |pkg|\n result << pkg unless hash_pkg.keys.include?(pkg)\n end\n\n\n until hash_pkg.empty?\n hash_pkg.each do |pkg, dep|\n if dep.all? {|d| result.include?(d)}\n result << pkg\n hash_pkg.delete(pkg)\n end\n end\n end\n\n result\nend",
"def gem_dependencies(rubygem)\n (latest = latest_gemspec(rubygem)) ?\n latest.dependencies.select {|e| e.type == :runtime }.map {|e| e.name} : []\n end",
"def process_project_dependencies\n recipes.each do |rec_obj|\n rec_obj.process_project_dependencies\n end\n end",
"def get_classes\n (attr['class'] || '').downcase.split(' ').sort\n end",
"def disgems\n Recommendable.config.ratable_classes.map { |klass| disgemd_for(klass) }.flatten\n end",
"def set_required_imports file_content\n imports = file_content.scan(every_defined_class_reg_exp)\n\n required_imports = {:packages => [],\n :classes => [],\n :unknowns => []\n }\n\n imports.each do |import|\n if import.match(package_seperator_reg_exp)\n required_imports[:packages] << \"import #{import};\"\n elsif import.match(new_class_reg_exp)\n required_imports[:classes] << import.split(\" \")[1]\n else\n required_imports[:unknowns] << {:import => import,\n :class => @class_name,\n :method => @method_name\n }\n end\n end\n\n if required_imports[:unknowns].size > 0\n puts \"Unknown Classes found\\r\\n\"\n puts required_imports[:unknowns].inspect\n exit\n end\n\n required_imports.each { |key,value| value.uniq! }\n\n required_imports\n end",
"def find_packages\n LockfileParser.read(lockfile_path)\n end",
"def recipe_classes_with_roles(roles)\n # Check to make sure some recipes have been added\n if ordered_recipes.size == 0\n raise Thor::InvocationError, 'no recipes have been defined'\n end\n if (roles.is_a?(Array) && roles.size == 0) || roles == :all\n # Use all classes\n role_classes = ordered_recipes\n else\n # Remove classes that don't fit the roles being used\n role_classes = ordered_recipes.reject do |recipe_class|\n ![roles].flatten.map(&:to_s).include?(recipe_class.class_role)\n end\n end \n end",
"def libraries\n modules = YARD::Registry.all(:module)\n classes = YARD::Registry.all(:class)\n root_definitions = YARD::Registry.all(:method).select { |m| m.path =~ /^root#/ }\n\n classes + modules + root_definitions\n end",
"def extract_dependencies\n FileUtils.cd(working_dir) do\n cmd = [\"require 'yaml';\"]\n cmd << \"dependencies = Merb::BootLoader::Dependencies.dependencies\"\n cmd << \"entries = dependencies.map { |d| d.to_s }\"\n cmd << \"puts YAML.dump(entries)\"\n output = `merb -r \"#{cmd.join(\"\\n\")}\"`\n if index = (lines = output.split(/\\n/)).index('--- ')\n yaml = lines.slice(index, lines.length - 1).join(\"\\n\")\n return parse_dependencies_yaml(yaml)\n end\n end\n return []\n end",
"def dependency_order\n result = []\n disabled = {}\n predecessors = build_predecessors\n while disabled.size < @specs.size\n\tcandidate = @specs.find { |spec|\n\t ! disabled[spec.full_name] &&\n\t active_count(predecessors[spec.full_name], disabled) == 0\n\t}\n\tif candidate\n\t disabled[candidate.full_name] = true\n\t result << candidate\n\telsif candidate = @specs.find { |spec| ! disabled[spec.full_name] }\n\t # This case handles circular dependencies. Just choose a\n\t # candidate and move on.\n\t disabled[candidate.full_name] = true\n\t result << candidate\n\telse\n\t # We should never get here, but just in case we will terminate \n\t # the loop.\n\t break\n\tend\n end\n result\n end",
"def gem_requirements_from_array(what, array)\n array.map do |dep|\n Gem::Dependency.new(what, *dep)\n end\n end",
"def railties_order; end",
"def railties_order; end",
"def classes\n return [] unless classes = self[\"class\"]\n classes.strip.split(/\\s+/)\n end",
"def get_node_classes\n if ENV[\"classes\"]\n ENV[\"classes\"].split(\",\")\n else\n class_dir = File.expand_path(\"../../../modules/govuk/manifests/node\", __FILE__)\n all_class_name = Dir.glob(\"#{class_dir}/s_*.pp\").map { |filepath|\n File.basename(filepath, \".pp\")[2..-1] # Strip leading s_\n }\n all_class_name.reject {|c| $nodes_spec_blacklist_classes.include?(c) }\n end\n end",
"def dependencies(path)\r\n deps = []\r\n open(path) do |file|\r\n deps = file.read.scan(/ [^\\s|\\\\]+/).collect { |s| s.strip }\r\n end\r\n deps.reject!{|s| s.include?(\"/opt\") || s.include?(\"/usr\") || s.include?(\"include/boost\")}\r\n deps\r\nend",
"def cookbook_version_loaders\n @cookbook_version_loaders ||=\n begin\n mash = Mash.new\n all_directories_in_repo_paths.each do |cookbook_path|\n loader = Cookbook::CookbookVersionLoader.new(cookbook_path, chefignore(cookbook_path))\n cookbook_name = loader.cookbook_name\n if mash.key?(cookbook_name)\n raise Chef::Exceptions::CookbookMergingError, \"Cookbook merging is no longer supported, the cookbook named #{cookbook_name} can only appear once in the cookbook_path\"\n end\n\n mash[cookbook_name] = loader\n end\n mash\n end\n end",
"def gems\n provisioner, version = @impl.split('-')\n get_gem_list(provisioner, version)\n end",
"def requires\n sort!\n sources.map {|s| s.requires }.flatten - provides\n end",
"def makena_classes\n Rails.application.eager_load!\n pass = ActiveRecord::Base.descendants.map{|a| a.to_s}\n pass.shift\n pass\n end",
"def engine_eager_load! \n railties.all(&:eager_load!)\n config.eager_load_paths.each do |load_path|\n matcher = /\\A#{Regexp.escape(load_path)}\\/(.*)\\.rb\\Z/\n Dir.glob(\"#{load_path}/**/*.rb\").sort.each do |file|\n # remove the previous class (if exists) and require again (with new load path/order)\n name = file.sub(matcher, '\\1')\n class_name = ActiveSupport::Inflector.camelize name\n Object.send(:remove_const, class_name) if Object.const_defined?(class_name)\n require_dependency name\n end\n end\n end",
"def generate_require_paths\n return configured_require_paths unless gemspec?\n result = []\n gemspecs.each do |file|\n base = File.dirname(file)\n # HACK: Evaluating gemspec files violates the goal of not running\n # workspace code, but this is how Gem::Specification.load does it\n # anyway.\n cmd = ['ruby', '-e', \"require 'rubygems'; require 'json'; spec = eval(File.read('#{file}'), TOPLEVEL_BINDING, '#{file}'); return unless Gem::Specification === spec; puts({name: spec.name, paths: spec.require_paths}.to_json)\"]\n o, e, s = Open3.capture3(*cmd)\n if s.success?\n begin\n hash = o && !o.empty? ? JSON.parse(o.split(\"\\n\").last) : {}\n next if hash.empty?\n @gemnames.push hash['name']\n result.concat(hash['paths'].map { |path| File.join(base, path) })\n rescue StandardError => e\n Solargraph.logger.warn \"Error reading #{file}: [#{e.class}] #{e.message}\"\n end\n else\n Solargraph.logger.warn \"Error reading #{file}\"\n Solargraph.logger.warn e\n end\n end\n result.concat(config.require_paths.map { |p| File.join(directory, p) })\n result.push File.join(directory, 'lib') if result.empty?\n result\n end",
"def all_package_names\n each_autobuild_package.map(&:name)\n end",
"def get_gem_names\n fetcher = Gem::SpecFetcher.fetcher\n\n list, = fetcher.available_specs(:complete)\n\n tuples = list.values.first\n\n tuples.map do |tuple,|\n tuple = tuple.to_a\n case tuple.last\n when Gem::Platform::RUBY then\n tuple[0, 2]\n else\n tuple\n end.join '-'\n end\n end",
"def packages\n @packages ||= []\n end",
"def packages\n @packages ||= []\n end",
"def schema_version_list\n result = []\n Dir.glob(\"#{File.dirname(__FILE__)}/expands/v*.rb\") do |f|\n result << File.basename(f, '.rb')\n end\n result.sort\n end",
"def boring_classes\n return [::Class, *::Class.included_modules,\n ::Module, *::Module.included_modules,\n ::Kernel, *::Kernel.included_modules,\n ::Object, *::Object.included_modules,\n ::BasicObject, *::BasicObject.included_modules].uniq\n end",
"def declare_cookbook_gems\n @flavor.class.do_declare_resources do\n if snippet?('cookbook_base')\n cookbook_gems['foodcritic'] = '~> 4.0'\n cookbook_gems['guard-foodcritic'] = '~> 1.1'\n end\n end\n end",
"def compute_revdeps\n result = Hash.new { |h, k| h[k] = Set.new }\n each_autobuild_package do |pkg|\n pkg.dependencies.each do |pkg_name|\n result[pkg_name] << pkg.name\n end\n pkg.optional_dependencies.each do |pkg_name|\n result[pkg_name] << pkg.name\n end\n pkg.os_packages.each do |pkg_name|\n result[pkg_name] << pkg.name\n end\n end\n result\n end",
"def providers\n before = ObjectSpace.each_object(Class).to_a\n filter_dir_contents(read_dir_contents).each { |f| require f }\n after = ObjectSpace.each_object(Class).to_a\n classes = (after - before).select { |c| c <= ProviderStrategy }\n @strategies.concat(classes.map(&:new))\n end",
"def gem_requirements\n @metadata[:requires].nil? ? [] :\n @metadata[:requires].select { |r| r.gem? }\n end",
"def referenced_libraries\n # TODO: check content type before scanning\n content.scan(%r{\\s*needs\\s+[\\\"\\'](.+)/(.+)[\\\"\\']}).map { |a, b| a + '/' + b }.uniq\n end",
"def class_names\n classes.map &:name\n end",
"def packages\n manifest.each_with_object({}) do |(src, package_name), hsh|\n next if src.nil? || src.empty?\n hsh[package_name] ||= []\n hsh[package_name] << File.join(Licensed::Git.repository_root, src)\n end\n end",
"def dependency_order\n sorted = strongly_connected_components.flatten\n\n result = []\n seen = {}\n\n sorted.each do |spec|\n if index = seen[spec.name] then\n if result[index].version < spec.version then\n result[index] = spec\n end\n else\n seen[spec.name] = result.length\n result << spec\n end\n end\n\n result.reverse\n end",
"def go_pkg_deps(pkgs, root_path)\n deps = []\n pkgs.each do |pkg|\n deps << pkg\n `go list -f '{{ join .Deps \"\\\\n\"}}' #{pkg}`.split(\"\\n\").select do |path|\n if path.start_with? root_path\n deps << path\n end\n end\n end\n return deps.sort.uniq\nend",
"def go_pkg_deps(pkgs, root_path)\n deps = []\n pkgs.each do |pkg|\n deps << pkg\n `go list -f '{{ join .Deps \"\\\\n\"}}' #{pkg}`.split(\"\\n\").select do |path|\n if path.start_with? root_path\n deps << path\n end\n end\n end\n return deps.sort.uniq\nend",
"def get_classes(trans)\n classes = []\n trans.each do |t|\n classes.push(t[:program])\n end\n classes.uniq\n end",
"def prerequisites(version)\n (prerequisite_names[version] || []).map { |package| packages[package] }\n end"
] | [
"0.663816",
"0.663816",
"0.647818",
"0.6027255",
"0.5872339",
"0.57335997",
"0.57302433",
"0.5720733",
"0.57169104",
"0.5702004",
"0.56983083",
"0.56872267",
"0.56674826",
"0.56643623",
"0.5659114",
"0.5616627",
"0.55957377",
"0.5593597",
"0.5582223",
"0.55817837",
"0.5573044",
"0.5550637",
"0.5548523",
"0.554595",
"0.5539615",
"0.553569",
"0.55277467",
"0.5521404",
"0.5513805",
"0.54956526",
"0.54916006",
"0.5462458",
"0.5457688",
"0.5454991",
"0.5442995",
"0.5434134",
"0.5426447",
"0.5420709",
"0.54174024",
"0.5408073",
"0.54078794",
"0.5391874",
"0.53915393",
"0.53895974",
"0.5386534",
"0.5372732",
"0.5358519",
"0.5349633",
"0.5336609",
"0.5324091",
"0.53216904",
"0.5320278",
"0.53094727",
"0.5301624",
"0.5301624",
"0.5292666",
"0.52814686",
"0.5264997",
"0.52632594",
"0.5260297",
"0.52587324",
"0.5245636",
"0.5245039",
"0.5243241",
"0.5243023",
"0.52392304",
"0.5231864",
"0.5223781",
"0.5223738",
"0.5222397",
"0.52193886",
"0.52188593",
"0.52188593",
"0.5217114",
"0.52114975",
"0.52097493",
"0.52041334",
"0.5194952",
"0.5191169",
"0.51810867",
"0.5176134",
"0.51756805",
"0.51663214",
"0.5165002",
"0.5150178",
"0.5150178",
"0.513485",
"0.5132556",
"0.51183933",
"0.51148635",
"0.5109233",
"0.51016414",
"0.5101571",
"0.50893086",
"0.5081448",
"0.5076919",
"0.50769156",
"0.50769156",
"0.5071412",
"0.50692147"
] | 0.79110026 | 0 |
Returns the list of classes that match the current list of roles in the correct run order | def recipe_classes_with_roles(roles)
# Check to make sure some recipes have been added
if ordered_recipes.size == 0
raise Thor::InvocationError, 'no recipes have been defined'
end
if (roles.is_a?(Array) && roles.size == 0) || roles == :all
# Use all classes
role_classes = ordered_recipes
else
# Remove classes that don't fit the roles being used
role_classes = ordered_recipes.reject do |recipe_class|
![roles].flatten.map(&:to_s).include?(recipe_class.class_role)
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def roles\n Jak.role_klass.where(id: grants.pluck(:role_ids).compact.flatten)\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 self.class.roles.map do |name|\n __send__(name)\n end\n end",
"def get_classes_from_role(role, options)\n certname = options[:certname_for_facts]\n global_config = get_global_config\n global_config = find_facts(certname).merge(global_config)\n get_classes_per_scenario(global_config, role)\n end",
"def the_roles\n roles.each.map{|_r| User::ROLES[_r.to_sym] }\n end",
"def get_role_classes_from_scenario(name)\n role_classes = {}\n # iterate through each roles in a scenario\n get_scenario_data(name)['roles'].each do |role_name, values|\n role_classes[role_name] = (values['classes'] || []) + get_classes_from_groups(values['class_groups'])\n end\n role_classes\n end",
"def find_roles *roles\n role_model.where(:name => roles.flatten)\n end",
"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 all_roles_with_changes\n (diff_roles + diff_profile.map do |klass|\n roles_that_include(klass)\n end.flatten).uniq\n end",
"def fetch_current_role_names(current_roles)\n current_role_names = []\n ROLES.keys.each do |role_type|\n current_roles.fetch(role_type, []).each do |current_role|\n role_name = get_role_name(role_type, current_role)\n\n break if role_name.nil?\n\n current_role_names << role_name\n end\n end\n current_role_names\n end",
"def run_list\n self.roles.collect { |role| \"role[#{role}]\" } +\n self.recipes.collect { |recipe| \"recipe[#{recipe}]\" }\n end",
"def roles\n return proposed_snapshot.roles if proposed? \n return active_snapshot.roles if active?\n []\n end",
"def components_in_roles( qroles )\n ( qroles & roles ).inject([]) { |m,r| m += space.role( r ) }\n end",
"def list_known_classes names = []\n classes = []\n stores.each do |store|\n classes << store.modules\n end\n classes = classes.flatten.uniq.sort\n unless names.empty? then\n filter = Regexp.union names.map { |name| /^#{name}/ }\n classes = classes.grep filter\n end\n puts classes.join(\"\\n\")\n end",
"def get_role_classes_from_scenario(name, scope)\n role_classes = {}\n scope = scope.merge({'scenario' => name})\n # iterate through each roles in a scenario\n scenario_data = get_scenario_data(name, scope)\n (scenario_data['roles'] || []).each do |role_name, values|\n role_classes[role_name] = process_classes(values, scope).uniq\n end\n role_classes\n end",
"def pass_on_roles\n r = self.all_roles\n if self.has_access?(:superadmin)\n r = Role.get(Access.roles(:all_users))\n elsif self.has_access?(:admin)\n r = Role.get(Access.roles(:admin_roles))\n elsif self.has_access?(:centeradm)\n r = Role.get(Access.roles(:center_users))\n end\n return (r.is_a?(Array) ? r : [r])\n end",
"def pass_on_roles\n r = self.all_roles\n if self.has_access?(:superadmin)\n r = Role.get(Access.roles(:all_users))\n elsif self.has_access?(:admin)\n r = Role.get(Access.roles(:admin_roles))\n elsif self.has_access?(:centeradm)\n r = Role.get(Access.roles(:center_users))\n end\n return (r.is_a?(Array) ? r : [r])\n end",
"def pass_on_roles\n r = self.roles.to_a\n if self.has_access?(:superadmin)\n r = Role.get(Access.roles(:all_users)).to_a\n elsif self.has_access?(:admin)\n r = Role.get(Access.roles(:admin_roles)).to_a\n elsif self.has_access?(:centeradm)\n r = Role.get(Access.roles(:center_users)).to_a\n end\n return (r.is_a?(Array) ? r : [r])\n end",
"def roles\n Role.group_roles_from_cache(self)\n end",
"def roles_list(role = nil)\n self.role_symbols\n end",
"def get_role_ids()\n server = Rails.cache.read('discord_bot/servers')&.find { |s| s['id'] == self.discord_server.id }\n\n return [] if server.nil?\n\n roles_config = server['exp_roles_config']\n\n return [] if roles_config.nil?\n\n thresholds = roles_config.sort_by { |r| r[0] }\n acquired_roles = []\n\n while thresholds.count > 0 && self.exp > thresholds.first[0] do\n acquired_roles.push(thresholds.shift)\n end\n\n return acquired_roles\n end",
"def all_roles\n result = Array.new\n \n# for role in self.roles\n# result << role.ancestors_and_self\n# end\n \n for group in self.groups\n result << group.all_roles\n end\n \n result.flatten!\n result.uniq!\n \n return result\n end",
"def roles\n self.dig_for_array(\"roles\")\n end",
"def list_known_classes names = []\n classes = []\n\n stores.each do |store|\n classes << store.module_names\n end\n\n classes = classes.flatten.uniq.sort\n\n unless names.empty? then\n filter = Regexp.union names.map { |name| /^#{name}/ }\n\n classes = classes.grep filter\n end\n\n page do |io|\n if paging? or io.tty? then\n if names.empty? then\n io.puts \"Classes and Modules known to ri:\"\n else\n io.puts \"Classes and Modules starting with #{names.join ', '}:\"\n end\n io.puts\n end\n\n io.puts classes.join(\"\\n\")\n end\n end",
"def get_available_roles \n ids = Array.new\n \n current = self.parent_id\n while current\n role = Role.find(current)\n if role\n if not ids.index(role.id)\n ids << role.id\n current = role.parent_id\n end \n end \n end\n return ids\n end",
"def normalize_roles\n self.roles = if self.roles.blank?\n []\n else\n self.class.roles.select { |role_to_check| roles.include?(role_to_check.to_s) }\n end\n end",
"def roles\n Role.all.select do |role|\n role.movie == self\n end\n end",
"def roles\n @declared_roles ||= Hash.new\n end",
"def roles_for(section)\n roles = []\n Section.find_roles.pluck(:name).uniq.each do |role|\n roles += [role] if self.has_role?(role, section)\n end\n roles\n end",
"def find_classes\n puppetClasses = []\n Dir.glob( SpkDashboard::MANIFEST_ROOT + \"/modules/**/*.pp\" ).each do |manifest|\n File.read( manifest ).each do |line|\n foundClass = line.match(/^class (\\S+).*\\{/)\n if foundClass and puppetClasses.include?( foundClass[1] ) == false\n puppetClasses << foundClass[1]\n end\n end\n end\n \n return puppetClasses\n end",
"def select_cmux_support_role_types(roles)\n roles.select { |_, r| ROLE_PORT.keys.map.include?(r[:roleType]) }\n end",
"def classes\n @classes\n end",
"def roles\r\n @roles ||= user_roles.map(&:name)\r\n end",
"def classes\n return [] unless classes = self[\"class\"]\n classes.strip.split(/\\s+/)\n end",
"def get_sorted_module_list classes\n classes.select do |klass|\n klass.display?\n end.sort\n end",
"def roles\n @users = User.order(\"user_name\").all\n end",
"def role_names\n roles.map { |role| role.name.capitalize }\n end",
"def map_available_roles\n roles.each.map &:name\n end",
"def possible_roles\n ([self.role] + DEFAULT_ROLES).uniq.compact.collect { |r| [ r.titleize, r ]}\n end",
"def authorizable_classes\n [].tap do |result|\n ObjectSpace.each_object(Class) do |c|\n next unless c.superclass == ApplicationRecord\n result << c if c.ancestors.include?(Record::Authorizable)\n end\n end\n end",
"def roles\n roles_as_editor + roles_as_reviewer + role_as_admin\n end",
"def matchMethodsInClasses(classList, type, mname)\n res = []\n \n for cname in classList\n cl = findClass(cname)\n res.concat cl.findMethods(mname, type == \"::\")\n# meths.each {|m| res << \"#{cname}#{m.type=='class'?'::':'#'}#{m.name}\" }\n end\n\n return res\n\n @op.putListOfMethodsMatchingName(mname) do\n @op.putMethodList(res)\n end\n end",
"def roles\n roles_from_users\n end",
"def list\n\n @roles = Role.find(:all, :order => 'name')\n\n end",
"def roles\n users.map { |item| item['roles'] }.flatten.uniq\n end",
"def class_names\n return if @class_names.empty?\n @class_names.uniq.sort\n end",
"def super_and_admin_roles\n return roles_include(roles.keys[0..1])\n end",
"def list\n @roles = Role.all(:include => [:groups, :users])\n end",
"def classes\n @classes.values\n end",
"def classes\n @classes.values\n end",
"def roles_for_select\n Role.all.select {|role| can? :add_user, role }.sort.map {|r| [r.name.titleize, r.id] }\n end",
"def my_roles\n @my_roles ||= self.roles.map {|r| r.name}.flatten.freeze\n end",
"def roles\n groups.find(:all, :conditions => {:context => Group::GroupType::ROLE})\n end",
"def collect_anniversary_roles\n role_names = [\"Company Admin\", \"Executive\"]\n roles = []\n role_names.each do |role_name|\n roles << Role.find_by_long_name(role_name)\n end\n return roles\n end",
"def recipes\n (@run_list.to_set - roles.to_set).to_a\n end",
"def get_roles\n Role.all.select {|role| role.character == self}\n end",
"def get_classes\n (attr['class'] || '').downcase.split(' ').sort\n end",
"def roles\n @roles = Role.order(\"name\")\n\t@rights = Right.order(\"name\").map {|r| [r.name, r.id] }\n end",
"def search_node_in_roles( roles )\n roles.each do |r|\n Chef::Log.info \"Searching for '#{self[:fqdn]}' in the '#{r}' role.\"\n if self.role?(r)\n # return true for the first match\n Chef::Log.info \"Whitelisting: Found node '#{self[:fqdn]}' via role '#{r}'.\"\n return true\n end\n end\n\n return false\n\n end",
"def roles(reload = false)\n @roles = nil if reload\n @roles ||=\n Role.find_by_sql ['select * from roles where id in ' +\n self.class.role_assigned_cond(':id'),\n {:id => id}]\n end",
"def roles\n # we can't use abilities as those are not defined when creating a new operator that is not yet saved\n #result = abilities.collect(&:name)\n authorizations.collect{|auth| auth.ability.try(:name)}\n end",
"def roles\n # we can't use abilities as those are not defined when creating a new operator that is not yet saved\n #result = abilities.collect(&:name)\n authorizations.collect{|auth| auth.ability.try(:name)}\n end",
"def index_role_list\n @per_role = {}\n @role_list.each do |role|\n @per_role[role.role_name] ||= []\n @per_role[role.role_name] << role\n end\n\n # then produce a list of names in priority order\n @role_names = @per_role.keys.sort\n end",
"def role_list \n @role_list ||= begin\n (store.display_roles | group_store.display_roles)\n end\n end",
"def roles\n return [] if !subject.respond_to?(roles_list_meth) || roles_of(subject).blank?\n roles_of(subject).flatten\n end",
"def find_more_roles(node, roles)\n\n # find roles depending on field values\n roles.each do |role|\n per_field_name = @field_value_roles[role]\n if per_field_name\n per_field_name.each do |field_name, value_roles|\n value_roles.each do |field_value, child_role|\n if field_value == node[field_name]\n roles << child_role\n end\n end\n end\n end\n end\n\n # find roles depending on field presence\n roles.each do |role|\n per_field_name = @field_presence_roles[role]\n if per_field_name\n per_field_name.each do |field_name, child_role|\n if node.key? field_name\n roles << child_role\n end\n end\n end\n end\n\n # is_a roles\n roles.each do |role|\n other_roles = @is_a_roles[role]\n if other_roles\n other_roles.each { |o| roles << o }\n end\n end\n end",
"def load_roles\n top.roles.clear\n\n # define empty roles for all known ones so tasks don't fail if a role\n # doesn't exist due to a filter\n all_roles = rubber_instances.all_roles\n all_roles += rubber_cfg.environment.known_roles\n all_roles.uniq!\n all_roles.each {|name| top.roles[name.to_sym] = []}\n\n # define capistrano host => role mapping for all instances\n rubber_instances.filtered.each do |ic|\n ic.roles.each do |role|\n opts = Rubber::Util::symbolize_keys(role.options).merge(:platform => ic.platform, :provider => ic.provider)\n msg = \"Auto role: #{role.name.to_sym} => #{ic.full_name}\"\n msg << \", #{opts.inspect}\" if opts.inspect.size > 0\n logger.info msg\n top.role role.name.to_sym, ic.full_name, opts\n end\n end\n end",
"def roles\n\t\t\t\tProxy.new connection, 'role-strategy/strategy'\n\t\t\tend",
"def classes\n\t\tlist = []\n\t\teach_class { |class_constant|\n\t\t\tlist\t<< class_constant\n\t\t}\n\t\treturn list\n\tend",
"def classes()\n\t\t\t\tlist = []\n\t\t\t\tdir = Dir.new( path() )\n\t\t\t\t\n\t\t\t\tdir.each do |file|\n\t\t\t\t\tnext if File.directory?( path() + \"/\" + file )\n\t\t\t\t\tnext if ( file[/^([A-Z][A-Za-z]*)+\\.class\\.rb$/] == nil )\n\t\t\t\t\tlist << clazz( $1 )\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\treturn list\n\t\t\tend",
"def my_assigned_roles(user)\n roles = []\n self.my_roles(user).each do |role|\n design_review_result = self.design_review_results.detect { |drr| drr.role == role }\n roles << role if design_review_result.reviewer == user\n end\n roles\n end",
"def class_names\n classes.map &:name\n end",
"def roles_for_user login\n cu = config['user']\n role_alias = cu[login] || cu[nil]\n role_alias = [ role_alias ] unless Array === role_alias\n roles = [ ]\n role_alias.each do | ra |\n roles.concat config['roles'][ra] || [ ra ]\n end\n roles.uniq!\n roles\n end",
"def role_names\n roles.split(',')\n end",
"def includes(*roles)\n raise DSLError, \"includes only in role blocks\" if @current_role.nil?\n @role_hierarchy[@current_role] ||= []\n @role_hierarchy[@current_role] += roles.flatten\n end",
"def includes(*roles)\n raise DSLError, 'includes only in role blocks' if @current_role.nil?\n @role_hierarchy[@current_role] ||= []\n @role_hierarchy[@current_role] += roles.flatten\n end",
"def build_roles(role)\n results = @machines.reject { |m| [*m['role']].grep(role).empty? }\n rolesarray = []\n results.each do |machine|\n rolesarray.push(machine['name'])\n end\n rolesarray\n end",
"def get_classes(trans)\n classes = []\n trans.each do |t|\n classes.push(t[:program])\n end\n classes.uniq\n end",
"def models\n available_models = Typus::Configuration.config\n models_for_this_user = []\n available_models.to_a.each do |m|\n models_for_this_user << m[0].constantize if m[1]['roles'].include? self.role\n end\n return models_for_this_user\n rescue\n []\n end",
"def classes(name = nil)\n if name\n classes.find(:name => name)\n else\n @classes.flatten\n end\n end",
"def roles_for_vp_and_sysadmin\n\t\tvp_and_sysadmin_roles = []\n\t\tfor role in Role.all\n\t\t\tif role.name.eql?(\"System Admin\") || role.name.eql?(\"VP of Finance\") \n\t\t\t\tvp_and_sysadmin_roles << role\n\t\t\tend\n\t\tend\n\t\treturn vp_and_sysadmin_roles\n\tend",
"def my_roles(user)\n user.roles & self.design_review_results.collect { |drr| drr.role }\n end",
"def role_symbols\n role_map = roles.map do |role|\n role.role.underscore.to_sym\n end\n role_map << :event_manager if self.class.stamper\n role_map.uniq! if role_map\n role_map\n end",
"def roles\n @contents.select { |c| c.is_a?( Symbol ) }\n end",
"def role_select\n @@Roles.list\n end",
"def roles_presented\n roles.join(\", \")\n end",
"def roles?(roles)\n roles.include?(role&.name)\n end",
"def roles\n # rocking this in memory because eager-loading\n roles = object.paper_roles.select { |role|\n role.user_id == scoped_user.id\n }.map(&:description)\n roles << \"My Paper\" if object.user_id == scoped_user.id\n roles\n end",
"def load_roles\n @roles = service_user.identity.roles.keep_if do |role|\n ALLOWED_ROLES.include?(role.name) || user_has_beta_role?(role.name)\n end.sort_by(&:name)\n end",
"def classes\n curriculums = self.qualifications.collect{ |q| q.curriculums }.flatten\n\n unless curriculums.empty?\n curriculums.collect{ |c| c.school_class }.flatten.uniq\n else\n return []\n end\n end",
"def accessible_roles\n index = ROLES.index(self.role)\n roles = User::ROLES[0..index].map{|x| [x.humanize, x]} if index\n return roles\n end",
"def sc_all_classes()\n @all_class_names = @driver.get_sc_object_class_names(abs_path) if @all_class_names.nil?\n return @all_class_names\n end",
"def roles\n raise \"#{subject.inspect} should have a #{roles_list_meth} method\" if !subject.respond_to?(roles_list_meth)\n subj_roles = subject.send(roles_list_meth)\n return [] if subj_roles.blank?\n subj_roles.flatten\n end",
"def full_roles\n r = ''\n if roles\n roles.each do |role|\n r += (role.name+\" \")\n puts role.name\n end\n end\n r\n end",
"def role_symbols\n (roles || []).map {|r| r.title.to_sym}\n end",
"def selectors\n find_related_frbr_objects( :is_selected_by, :which_roles?) \n end",
"def users\n Section.find_roles.pluck(:name).inject(Array.new) do |result, role|\n result += User.with_role(role, self)\n end.uniq\n end",
"def list_known_classes\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 used *rolegroups\n list & rolegroups.to_symbols_uniq\n end"
] | [
"0.6776941",
"0.656379",
"0.6520467",
"0.6483397",
"0.64126897",
"0.6331103",
"0.63098425",
"0.6295739",
"0.6293623",
"0.6227268",
"0.6221702",
"0.61961675",
"0.6187308",
"0.61219615",
"0.6045106",
"0.60402143",
"0.60402143",
"0.6031308",
"0.5972891",
"0.5972758",
"0.59591484",
"0.59410137",
"0.59204733",
"0.58812743",
"0.58629346",
"0.5858676",
"0.58525",
"0.5839133",
"0.58215535",
"0.5800889",
"0.58001935",
"0.5789533",
"0.57878494",
"0.5787446",
"0.5774232",
"0.57728755",
"0.57674885",
"0.5755028",
"0.5736508",
"0.57349324",
"0.57236457",
"0.5717134",
"0.5699774",
"0.5696177",
"0.5694153",
"0.56892145",
"0.56831354",
"0.56688",
"0.5668522",
"0.5668522",
"0.5665865",
"0.56605995",
"0.5654654",
"0.56525946",
"0.56517357",
"0.5642971",
"0.562969",
"0.5627704",
"0.56233436",
"0.5615371",
"0.5602536",
"0.5602536",
"0.55943966",
"0.5572062",
"0.557175",
"0.5544759",
"0.5542241",
"0.55412674",
"0.5530587",
"0.55215317",
"0.5514123",
"0.55066115",
"0.5502686",
"0.5500595",
"0.549417",
"0.5489918",
"0.5483196",
"0.5471841",
"0.5469534",
"0.54688007",
"0.5468108",
"0.5462098",
"0.5454623",
"0.54503745",
"0.544558",
"0.5435834",
"0.54357195",
"0.5429087",
"0.5427453",
"0.5423642",
"0.5421325",
"0.5420058",
"0.54181355",
"0.5411679",
"0.5406763",
"0.5397581",
"0.5392368",
"0.53904295",
"0.5386599",
"0.5383886"
] | 0.7155205 | 0 |
Invokes all recipes that implement the passed in role | def invoke_roles(task_name, roles, options={})
role_classes = self.recipe_classes_with_roles(roles)
# Run the taks on each role class
role_classes.each do |recipe_class|
# This class matches the role, so we should run it
recipe = recipe_class.new([], options)
task = recipe_class.tasks[task_name.to_s]
recipe.invoke_task(task)
# Copy back and updated options
options = recipe.options
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def tell(role_name, method_name, ...)\n if context == self || context.contains?(self)\n context.dispatch(role(role_name), method_name, ...)\n end\n end",
"def method_missing(meth_name, *args, &block)\n raise \"No method named: #{meth_name}\" unless recipe.respond_to? meth_name\n recipe.send(meth_name, *args, &block)\n end",
"def includes_recipe?(recipe)\n # todo expand roles?\n self.run_list.include?(\"#{recipe}\")\n end",
"def ingredient_by_role(role)\n element.ingredient_by_role(role)\n end",
"def run_list\n self.roles.collect { |role| \"role[#{role}]\" } +\n self.recipes.collect { |recipe| \"recipe[#{recipe}]\" }\n end",
"def for_roles *user_roles, &block\n user_roles = user_roles.flat_uniq\n yield if has_roles?(user_roles) && block\n end",
"def each_role(&block)\n unless block_given?\n return enum_for(:each_role, &block)\n end\n\n each_parent_object(Dependency) do |parent|\n yield(parent, parent.roles_of(self))\n end\n end",
"def current_user_has_role(role_ids_or_syms, &block)\r\n yield block if current_user_has_role?(role_ids_or_syms)\r\n end",
"def role(*roles, &block)\n RoleCondition.new(roles) do\n block.call\n end\n end",
"def find_all_for_role(role)\n roles = role.get_parents\n roles << role\n return find_for_role(roles.collect(&:id))\n end",
"def method_missing(method_id, *args)\n\t\tif match = matches_dynamic_role_check?(method_id)\n\t\t\ttokenize_roles(match.captures.first).each do |check|\n\t\t\t\troles.each do |role|\n\t\t\t\t\treturn true if role.name.downcase == check\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn false\n\t\telse\n\t\t\tsuper\n\t\tend\n\tend",
"def method_missing(method, *args)\n begin\n @user.custom_roles.any? { |role| role.send(method.to_sym) }\n rescue NoMethodError\n super\n end\n end",
"def each(&block)\n retractions.each &block\n end",
"def find_by_role(role, single = true, &block)\n find_matching(:role, role, single, block)\n end",
"def accept_role role\n self.roles.push role\n end",
"def run_role(env_vars, extra_vars, role_name, roles_path:, role_skip_facts: true)\n run_via_cli(env_vars, extra_vars, :role_name => role_name, :roles_path => roles_path, :role_skip_facts => role_skip_facts)\n end",
"def recipe_classes_with_roles(roles)\n # Check to make sure some recipes have been added\n if ordered_recipes.size == 0\n raise Thor::InvocationError, 'no recipes have been defined'\n end\n if (roles.is_a?(Array) && roles.size == 0) || roles == :all\n # Use all classes\n role_classes = ordered_recipes\n else\n # Remove classes that don't fit the roles being used\n role_classes = ordered_recipes.reject do |recipe_class|\n ![roles].flatten.map(&:to_s).include?(recipe_class.class_role)\n end\n end \n end",
"def meta_abilities\n User.roles.each do |(k, v)|\n if user.has_role? k\n can \"do_#{k}\".to_sym, :all\n end\n end\n end",
"def reuse_role_if_possible( name, &block )\n unless @roles.has_key?( name )\n @roles[ name ] = block.call()\n end\n @roles[ name ]\n end",
"def requires_role(role)\n yield if current_user && current_user.has_role?(role)\n end",
"def should_require_role(role, *args)\n args = Hash[*args]\n redirect_url = args.delete :redirect_url\n redirect_url ||= '/login'\n args.each do |action, verb|\n should \"require role for '#{action}' action\" do\n if [:put, :delete].include?(verb) # put and delete require an id even if it is a bogus one\n send(verb, action, :id => 1)\n else\n send(verb, action)\n end\n ensure_flash(/permission/i)\n assert_redirected_to(redirect_url)\n end\n end\n end",
"def recipe args=1\n self.summary.recipe args\n end",
"def role(*args)\n cap_role(*args)\n puppet_role(*args)\n end",
"def execute_items(items, scenario, &block)\n items.each {|item| execute_item(scenario, item, &block)}\n end",
"def method_missing(method_sym, *arguments, &block)\n eigenclass = class << self; self; end\n role = Role.find_by(name: method_sym.to_s.tr('?', ''))\n if role\n eigenclass.class_eval do\n define_method(method_sym) do\n role_id == role.id\n end\n end\n else\n super\n end\n send(method_sym)\n end",
"def perform_execute_request(data = {})\n execute_recipe(version, data)\n end",
"def recipes\n (@run_list.to_set - roles.to_set).to_a\n end",
"def method_missing(meth, *args, &block)\n if meth.to_s == \"to_ary\"\n raise NoMethodError\n end\n\n if args.empty? and rp = role_proxy(meth)\n rp\n elsif task = resolve_task(meth)\n task.run(self, *args, &block)\n else\n if args.last.kind_of? Hash\n opts = args.pop\n else\n opts = {}\n end\n str = ([meth] + args.map{|a| escape(a)}).join(' ')\n exec! str, opts, &block\n end\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 stub_role_methods(mock_user, roles)\n roles = [roles] unless roles.is_a?(Array)\n Role::ROLES.each do |role_token|\n role = role_token.to_s # allow a symbol to be passed - e.g., pretend_to_be_authenticated(:role => :admin)\n allow(mock_user).to receive(role.downcase+\"?\").and_return roles.include?(role)\n end\n return mock_user\nend",
"def find_and_authorize(resource, *roles)\n opts = roles.extract_options!\n\n before_action(action_options(opts)) do\n find_resource resource, opts\n\n authorize roles, opts unless roles.empty?\n end\n end",
"def filter_access!\n treat_as get_current_role\n end",
"def change_role(role)\n role_list.each do |old_role|\n remove_role old_role\n end\n puts role\n add_role role\n puts roles\n end",
"def role(role, options = {})\n append_role role, options\n @current_role = role\n yield\n ensure\n @current_role = nil\n end",
"def role(role, options = {})\n append_role role, options\n @current_role = role\n yield\n ensure\n @current_role = nil\n end",
"def handle_admin_role_ids(role)\n current_members = send(role.to_s.pluralize)\n new_members = Person.find(send(\"#{role}_ids\"))\n\n to_add = new_members - current_members\n to_remove = current_members - new_members\n to_add.each do |person|\n person.send(\"is_#{role}=\", [true, self])\n disable_authorization_checks { person.save! }\n end\n to_remove.each do |person|\n person.send(\"is_#{role}=\", [false, self])\n disable_authorization_checks { person.save! }\n end\n end",
"def handle_admin_role_ids(role)\n current_members = send(role.to_s.pluralize)\n new_members = Person.find(send(\"#{role}_ids\"))\n\n to_add = new_members - current_members\n to_remove = current_members - new_members\n to_add.each do |person|\n person.send(\"is_#{role}=\", [true, self])\n disable_authorization_checks { person.save! }\n end\n to_remove.each do |person|\n person.send(\"is_#{role}=\", [false, self])\n disable_authorization_checks { person.save! }\n end\n end",
"def role( symbol, *args )\n if args.empty?\n @roles[ symbol.to_sym ]\n else\n @roles[ symbol.to_sym ] += args.flatten.compact\n end\n end",
"def invoke(*names, &block)\n options = names.last.is_a?(Hash) ? names.pop : {}\n verbose = options.fetch(:verbose, true)\n\n names.each do |name|\n invocations[name] = false\n invocation_blocks[name] = block if block_given?\n\n class_eval <<-METHOD, __FILE__, __LINE__\n def _invoke_#{name.to_s.gsub(/\\W/, '_')}\n klass, command = self.class.prepare_for_invocation(nil, #{name.inspect})\n\n if klass\n say_status :invoke, #{name.inspect}, #{verbose.inspect}\n block = self.class.invocation_blocks[#{name.inspect}]\n _invoke_for_class_method klass, command, &block\n else\n say_status :error, %(#{name.inspect} [not found]), :red\n end\n end\n METHOD\n end\n end",
"def run(context, action)\n @stack.each do |cb, opts|\n next if skip?(cb, action)\n next if opts[:only] && !opts[:only].include?(action)\n next if opts[:except] && opts[:except].include?(action)\n context.send(cb)\n end\n end",
"def add_workflow_responsibilities(role, agents)\n Hyrax::Workflow::PermissionGenerator.call(roles: role,\n workflow: self,\n agents: agents)\n end",
"def acl_for(role = :all, &block)\n @_aclize_acl.setup(role, &block)\n end",
"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 role(role_name)\n context.send(role_name)\n end",
"def for_role(role_name, options=nil)\n @items.values.find_all {|ic| ic.roles.any? {|r| r.name == role_name && (! options || r.options == options)}}\n end",
"def for_role(role_name, options=nil)\n @items.values.find_all {|ic| ic.roles.any? {|r| r.name == role_name && (! options || r.options == options)}}\n end",
"def role_actions?(group_id, role_types)\n puts group_id\n puts role_types\n roles = URole.where(['group_id = ? and uid = ? and role_type = ? and is_revoked = ?', group_id, id, role_types, 0])\n success = true\n success = false if roles.blank?\n success\n end",
"def method_missing(method_id, *args)\n\t\tif match = matches_dynamic_role_check?(method_id)\n\t\t\ttokenize_roles(match.captures.first).each do |check|\n\t\t\t\treturn true if roles.collect{|r| r.name.downcase }.include?(check)\n\t\t\tend\n\t\t\treturn false\n\t\telsif match = matches_dynamic_perm_check?(method_id)\n\t\t\ttokenize_roles(match.captures.first).each do |check|\t\n\t\t\t\treturn true if permissions.collect{|p| p.name.downcase }.include?(check)\n\t\t\tend\n\t\t\treturn false\n\t\telse\n\t\t\tsuper\n\t\tend\n\tend",
"def can_perform_role(name, *keys)\n getRole(name.to_s).isAllowedForKeys(Set.new keys.map { |x|\n x.is_a?(PrivateKey) ? x.public_key : x\n })\n end",
"def grant(*roles)\n self << roles\n reload\n end",
"def things_with_role(thing, role)\n require 'wavefront-sdk/search'\n wfs = Wavefront::Search.new(mk_creds, mk_opts)\n wfs.search(thing,\n conds_to_query([\"roles~#{role}\"]),\n limit: :all, sort_field: :id)\n end",
"def apply_role(role_name)\n role_mapping = self.roles[role_name]\n role_module, obj = role_mapping.role_module, role_mapping.data_object\n obj.extend(role_module)\n obj.instance_variable_set(:@__brassbound_context, self)\n class << obj\n def context\n @__brassbound_context\n end\n end\n self.singleton_class.send(:define_method, role_name) do\n obj\n end\n end",
"def recipes\n # Loop through RecipeCard\n #Find cards for this user\n #Gather recipes on those cards\n self.recipe_cards.map do |recipecard|\n recipecard.recipe\n end\n end",
"def method_missing(method, *args, &block)\n recipe = Recipe.create_recipe(self, method, *args, &block)\n if recipe\n if recipe.enabled # ignore recipe if not enabled (matching feature requirements)\n add_recipe(recipe)\n return recipe\n else\n BRIX11.log(2, \"[#{self}] recipe disabled\")\n return nil\n end\n end\n # calling super will cause error if method being called is invalid\n super\n end",
"def role(name, &block)\n name = name.to_s\n\n unless role = @roles.find{|r| r.name == name}\n role = Salticid::Role.new(name, :salticid => self)\n @roles << role\n end\n\n if block_given?\n role.instance_eval &block\n end\n\n role\n end",
"def role?(*args, **kwargs)\n return false if meta.nil? || meta['roles'].nil?\n if args.any?\n args.reduce(false) { |a, e| a || meta['roles'].include?(e.to_s) }\n else\n kwargs.reduce(false) do |a, (k, v)|\n a ||\n (meta['roles'].is_a?(Array) && meta['roles'].include?(k.to_s)) ||\n (meta['roles'].include?(k.to_s) && meta['roles'][k.to_s].include?(v.to_s))\n end\n end\n end",
"def game_action(command, subj, obj, place, rest)\n setf[\"__#{command}_rest\", rest]\n Lisp.module_eval \"\n def #{command}(subject, object=nil)\n if object.nil?\n subject, object = subject.split\n end\n cond[[and_[eq[$location, #{place.inspect}],\n eq[subject, #{subj.inspect}],\n eq[object, #{obj.inspect}],\n have[#{subj.inspect}]],\n __#{command}_rest],\n [t, f{%w[i cant #{command} like that.]}]]\n end\"\nend",
"def not_for_roles(*user_roles, &block) \n user_roles = user_roles.flat_uniq\n yield if !has_roles?(user_roles) && block\n end",
"def required_roles_for_method(method)\n self.class.required_roles_for_method(method)\n end",
"def available_recipes\n self.user.recipes.select do |recipe|\n recipe.ingredients.all?{|ing| ing.quantity <= self.ingredients.find_by(name: ing.name).quantity}\n end\n end",
"def all\n # returns all recipes\n @recipes\n end",
"def access_role?(*roles, &block)\n settings.permissions.check(access_subject, :have => roles, &block)\n end",
"def recipes\n Recipe.all.select {|recipes| recipes.user == self}\n end",
"def perform\n build_recipes # this returns array of recipes\n self # return the scrapper\n end",
"def toggle_role\n do_toggle_role params[:role]\n end",
"def find_roles *roles\n role_model.where(:name => roles.flatten)\n end",
"def is_role?(*roles)\n roles.include? role\n end",
"def invoke\n execute_only(:invoke)\n end",
"def action_run\n status = @recipe_helper.run(@new_resource.name, @new_resource.tags, @new_resource.attributes, @new_resource.match_all)\n Chef::Log.info \"Recipe executed '#{new_resource.name}' status:#{status}\"\n new_resource.updated_by_last_action(true)\n end",
"def role(name, options = {}, &block)\n final_options = { name: name }.merge(options).merge(scoped_options: scoped_options)\n require_namespace!('role', final_options)\n\n definitions << Matsuri::DSL::Cluster::Role.new(final_options).tap do |role|\n if options[:resources].present? && options[:verbs].present?\n role.resources(options[:resources], names: options[:resource_names], verbs: options[:verbs], api_groups: options[:api_groups])\n end\n\n role.configure(&block)\n end\n end",
"def recipe(&block)\n rules.last.recipe = block\n end",
"def menu_items\n MenuItem.all.select {|item| item.recipe == self}\n end",
"def setup_discover\n return if @recipes.blank?\n \n @recipes.each do |recipe|\n recipe.setup_recipe\n end\n @have_ingredients = current_user.kitchen.have_ingredients\n @starred_ids = current_user.kitchen.starred_meal_ingredient_ids \n @my_meals_ids = current_user.kitchen.my_meals_recipe_ids\n end",
"def compile_everything(role, options)\n certname = options[:certname_for_facts]\n global_config = find_facts(certname).merge(get_global_config)\n class_list = get_classes_per_scenario(global_config, role)\n process_class_data(class_list, global_config, options)\n end",
"def map_rights(fn, service: nil, resource: nil, hyperlink: nil, verb: nil, \n app: nil, context: nil, app_context_acc_fn: nil)\n seen_rights = []\n seen_roles = []\n rsrc = Resource.where(name: resource).first if resource\n cond = rsrc ? {resource_id: rsrc.id} : {}\n # Local function to consider a right. Since this is a Proc (not a lambda), any\n # return in the body will return from the enclosing function (map_rights) rather\n # than from the Proc. This is exactly what we want.\n considerer = Proc.new { |right|\n unless seen_rights.include?(right)\n seen_rights << right\n if (!service || right.service.name == service) &&\n (!resource || right.resource.name == resource) &&\n (!hyperlink || right.hyperlink == '*' || right.hyperlink == hyperlink) &&\n (!verb || right.verb == '*' || right.verb == verb) \n # Only the app and context might differ. Process them if function given.\n app_context_acc_fn.call(right) if app_context_acc_fn\n # Now check if this is a full match. If so, call fn.\n if (!app || right.app == '*' || right.app == app) &&\n (!context || right.context == '*' || right.context == context)\n # If the right authorises the request, return the right, unless a\n # false value returned from fn forces the search to continue.\n return right if fn.call(right)\n end\n end\n end\n }\n roles.each { |role| \n seen_roles << role\n role.rights.where(cond).each { |right| considerer.call(right) } }\n groups.each { |group| \n group.rights.where(cond).each { |right| considerer.call(right) } \n group.roles.each { |role| \n next if seen_roles.include?(role)\n seen_roles << role\n role.rights.where(cond).each { |right| considerer.call(right) } \n }\n }\n false\n end",
"def run_for_all(&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 block.call(the_app.to_sym, the_role.to_sym, rails_env.to_sym)\n end",
"def knifeAddToRunList(rl_entry = nil, type=\"role\", ignore_missing: false, multiple: [])\n self.class.loadChefLib\n return if rl_entry.nil? and multiple.size == 0\n if multiple.size == 0\n multiple = [rl_entry]\n end\n multiple.map! { |entry|\n if !entry.match(/^role|recipe\\[/)\n \"#{type}[#{entry}]\"\n else\n entry\n end\n }\n\n if !ignore_missing\n role_list = nil\n recipe_list = nil\n missing = false\n multiple.each { |entry|\n # Rather than argue about whether to expect a bare entry name or\n # require entry[rolename], let's just accomodate.\n if entry.match(/^role\\[(.+?)\\]/)\n entry_name = Regexp.last_match(1)\n if role_list.nil?\n query=%Q{#{MU::Groomer::Chef.knife} role list};\n role_list = %x{#{query}}\n end\n if !role_list.match(/(^|\\n)#{entry_name}($|\\n)/)\n MU.log \"Attempting to add non-existent #{entry} to #{@server.mu_name}\", MU::WARN\n missing = true\n end\n elsif entry.match(/^recipe\\[(.+?)\\]/)\n entry_name = Regexp.last_match(1)\n if recipe_list.nil?\n query=%Q{#{MU::Groomer::Chef.knife} recipe list};\n recipe_list = %x{#{query}}\n end\n if !recipe_list.match(/(^|\\n)#{entry_name}($|\\n)/)\n MU.log \"Attempting to add non-existent #{entry} to #{@server.mu_name}\", MU::WARN\n missing = true\n end\n end\n\n if missing and !ignore_missing\n raise MuError, \"Can't continue with missing roles/recipes for #{@server.mu_name}\"\n end\n }\n end\n\n rl_string = multiple.join(\",\")\n begin\n query=%Q{#{MU::Groomer::Chef.knife} node run_list add #{@server.mu_name} \"#{rl_string}\"};\n MU.log(\"Adding #{rl_string} to Chef run_list of #{@server.mu_name}\")\n MU.log(\"Running #{query}\", MU::DEBUG)\n output=%x{#{query}}\n # XXX rescue StandardError is bad style\n rescue StandardError => e\n raise MuError, \"FAIL: #{MU::Groomer::Chef.knife} node run_list add #{@server.mu_name} \\\"#{rl_string}\\\": #{e.message} (output was #{output})\"\n end\n end",
"def run_chef(use_solo=true, log_level='info', recipes=[])\n chef_bin = use_solo ? \"chef-solo\" : \"chef-client -z\"\n sudo \"bin/#{chef_bin} --log_level #{log_level} -c solo.rb -j kitchenplan-attributes.json -o #{recipes.join(\",\")}\"\n end",
"def has_role(role_name, authorizable_class, &block)\n badges_model_role_checks[authorizable_class.name] = [] if badges_model_role_checks[authorizable_class.name].nil?\n badges_model_role_checks[authorizable_class.name] << Badges::ModelRoleCheck.new(role_name.to_s, authorizable_class, &block)\n end",
"def recipe_learn?(recipe)\n recipe.is_a?(RPG::Recipe) && @recipes.include?(recipe.id)\n end",
"def interact(&block)\n\t\tinit_tab_complete\n\n\t\t# Run queued commands\n\t\tcommands.delete_if { |ent|\n\t\t\trun_single(ent)\n\t\t\ttrue\n\t\t}\n\n\t\t# Run the interactive loop\n\t\trun { |line|\n\t\t\t# Run the command\n\t\t\trun_single(line)\n\n\t\t\t# If a block was supplied, call it, otherwise return false\n\t\t\tif (block)\n\t\t\t\tblock.call\n\t\t\telse\n\t\t\t\tfalse\n\t\t\tend\n\t\t}\n\tend",
"def role(role)\n @roles = @roles | [@salticid.role(role)]\n end",
"def exec?(roles = [:contest_director, :psa_director])\n roles = [roles] unless roles.kind_of? Array\n\n result = self.admin?\n\n if result\n true\n else\n roles.each do |role|\n result ||= self.has_role?(role) \n end\n end\n\n return result\n end",
"def mod_all\n role = Role.find(params[:id])\n user = User.find(params[:role][:user_id])\n user.roles << role\n\n flash[:notice] = \"La modificacion ha sido realizada correctamente.\"\n\n redirect_to :back\n end",
"def assign_role(role)\n found = false\n find('table[id$=\"gridRole_DXMainTable\"] > tbody').all('tr').map do |row|\n row.all('td').map do |cell|\n cell_data = cell.text.strip\n if cell_data == role\n row.click\n found = true\n end\n break if found\n end\n break if found\n end\n end",
"def each_quest(&block)\r\n @quests.each(&block)\r\n end",
"def remove_role_action(external_user, service_id, role)\n rc = @srv_pool.get(service_id, external_user) do |service|\n unless service.running?\n break OpenNebula::Error.new(\n \"Cannot modify roles in state: #{service.state_str}\"\n )\n end\n\n unless service.roles[role]\n break OpenNebula::Error.new(\"Role #{role} does not exist\")\n end\n\n remove_role(external_user, service, service.roles[role])\n end\n\n Log.error LOG_COMP, rc.message if OpenNebula.is_error?(rc)\n\n rc\n end",
"def process_roles(items=node.run_list.run_list_items.dup)\n if entry = items.shift\n if entry.type == :role && role = inflate_role(entry.name)\n process_roles(role.run_list_for(@environment).run_list_items)\n node.default_attrs = Chef::Mixin::DeepMerge.merge(node.default_attrs, role.default_attributes)\n check_for_state_change \"deep merge of default attribute in role #{entry.name}\"\n node.override_attrs = Chef::Mixin::DeepMerge.merge(node.override_attrs, role.override_attributes)\n check_for_state_change \"deep merge of override attribute in role #{entry.name}\"\n end\n process_roles(items)\n end\n end",
"def perform_if_needed(**action_parameters)\n return if performed?(**action_parameters)\n\n yield\n\n mark_performed(**action_parameters)\n end",
"def instances_for_role(role, state = \"running\")\n instances_for_filter(\"tag:role\", role, state)\n end",
"def cook(&block)\n the_recipes = [\n self.class.standard_recipes,\n self.base_recipe,\n self.recipes,\n (block_given? ? block : nil)\n ].flatten.compact.uniq\n the_recipes.each do |r|\n if r.is_a?(Proc)\n self.cap_config.load(:proc => r)\n else # assume recipe filename\n self.cap_config.load(:file => r)\n end\n end\n @cooked = true\n self.cap_config\n end",
"def recipe(arg=nil)\n set_or_return(\n :recipe,\n arg,\n :kind_of => [ String ]\n )\n\n @cron_resource.command \"rs_run_recipe -n #{arg}\" if arg\n end",
"def user_authorized_for?(user, params = {}, binding = self.binding)\n return true unless Array===@role_requirements\n @role_requirements.each{| role_requirement|\n roles = role_requirement[:roles]\n options = role_requirement[:options]\n # do the options match the params?\n\n # check the action\n if options.has_key?(:only)\n next unless options[:only].include?( (params[:action]||\"index\").to_sym )\n end\n\n if options.has_key?(:except)\n next if options[:except].include?( (params[:action]||\"index\").to_sym)\n end\n\n if options.has_key?(:if)\n # execute the proc. if the procedure returns false, we don't need to authenticate these roles\n next unless ( String===options[:if] ? eval(options[:if], binding) : options[:if].call(params) )\n end\n\n if options.has_key?(:unless)\n # execute the proc. if the procedure returns true, we don't need to authenticate these roles\n next if ( String===options[:unless] ? eval(options[:unless], binding) : options[:unless].call(params) )\n end\n\n # check to see if they have one of the required roles\n passed = false\n roles.each { |role|\n passed = true if user.has_role?(role)\n } unless (! user || user==:false)\n\n return false unless passed\n }\n\n return true\n end",
"def run_role_queue(env_vars, extra_vars, role_name, user_id, queue_opts, roles_path:, role_skip_facts: true)\n run_in_queue(\"run_role\",\n user_id,\n queue_opts,\n [env_vars, extra_vars, role_name, {:roles_path => roles_path, :role_skip_facts => role_skip_facts}])\n end",
"def delete_role_and_associated_nodes\n search_glob = \"#{self.role_name}*\"\n skip_list = Array(self.node_name)\n\n puts \"deleting role with name = '#{search_glob}'\"\n ::Chef::Search::Query\n .new\n .search('role', \"name:#{search_glob}\")\n .first\n .reject { |role| skip_list.include?(role.name)}\n .each { |role| puts role.as_json; role.destroy }\n puts \"deleted role with name = '#{search_glob}'\"\n\n puts \"deleting node with role = '#{search_glob}'\"\n ::Chef::Search::Query\n .new\n .search('node', \"role:#{search_glob}\")\n .first\n .reject { |node| skip_list.any? { |item| node.run_list.include?(item) } }\n .each { |node| puts node['hostname']; node.destroy }\n puts \"deleted node with role = '#{search_glob}'\"\n end",
"def perform\n return if triggers.blank?\n\n # for each trigger matching this item's class\n triggers.each do |trigger|\n # see if any/all conditions match this item's state\n unless ConditionTriggerJoin\n .meets_condtions?(trigger.condition_trigger_joins, item)\n next\n end\n\n # perform all actions associated with this trigger\n trigger.actions.map do |action|\n perform_crud(fetch_records(action), action)\n end\n end\n end",
"def includes_recipe?(recipe_name)\n run_list.include?(recipe_name)\n end",
"def execute(*args)\n puts 'running mutation business logic'\n puts \"name = #{name}\"\n puts \"The Recipe is #{recipe&.name}\"\n\n # Do other logic\n\n end",
"def require_role(roles, options = {})\n options.assert_valid_keys(:if, :unless,\n :for, :only,\n :for_all_except, :except\n )\n\n # only declare that before filter once\n unless (@before_action_declared||=false)\n @before_action_declared=true\n before_action :check_roles\n end\n\n # convert to an array if it isn't already\n roles = [roles] unless Array===roles\n\n options[:only] ||= options[:for] if options[:for]\n options[:except] ||= options[:for_all_except] if options[:for_all_except]\n\n # convert any actions into symbols\n for key in [:only, :except]\n if options.has_key?(key)\n options[key] = [options[key]] unless Array === options[key]\n options[key] = options[key].compact.collect{|v| v.to_sym}\n end\n end\n\n self.role_requirements||=[]\n self.role_requirements << {:roles => roles, :options => options }\n end",
"def user_authorized_for?(user, params = {}, binding = self.binding)\n return true unless Array===self.role_requirements\n self.role_requirements.each{| role_requirement|\n roles = role_requirement[:roles]\n options = role_requirement[:options]\n # do the options match the params?\n\n # check the action\n if options.has_key?(:only)\n next unless options[:only].include?( (params[:action]||\"index\").to_sym )\n end\n\n if options.has_key?(:except)\n next if options[:except].include?( (params[:action]||\"index\").to_sym)\n end\n\n if options.has_key?(:if)\n # execute the proc. if the procedure returns false, we don't need to authenticate these roles\n next unless ( String===options[:if] ? eval(options[:if], binding) : options[:if].call(params) )\n end\n\n if options.has_key?(:unless)\n # execute the proc. if the procedure returns true, we don't need to authenticate these roles\n next if ( String===options[:unless] ? eval(options[:unless], binding) : options[:unless].call(params) )\n end\n\n # check to see if they have one of the required roles\n passed = false\n roles.each { |role|\n passed = true if user.has_role?(role)\n } unless (! user || user==:false)\n\n return false unless passed\n }\n\n return true\n end"
] | [
"0.5542909",
"0.5435228",
"0.5433466",
"0.5427825",
"0.52657735",
"0.5257147",
"0.5225269",
"0.5148291",
"0.50860053",
"0.50795543",
"0.50388676",
"0.50357753",
"0.4998903",
"0.49958935",
"0.49937195",
"0.49792033",
"0.497508",
"0.4946387",
"0.4942964",
"0.4920764",
"0.49185535",
"0.49175465",
"0.49108756",
"0.4903949",
"0.49024844",
"0.48947963",
"0.48902184",
"0.4878343",
"0.48658624",
"0.4854183",
"0.48536363",
"0.4849251",
"0.48306364",
"0.4813892",
"0.4813892",
"0.4807699",
"0.4807699",
"0.4804873",
"0.47985837",
"0.47964352",
"0.4796077",
"0.47839564",
"0.47744685",
"0.4747195",
"0.47460595",
"0.47460595",
"0.47419408",
"0.47350284",
"0.47285718",
"0.47235385",
"0.47194248",
"0.47193316",
"0.47191158",
"0.47167543",
"0.471646",
"0.47144613",
"0.47089195",
"0.47054642",
"0.47046405",
"0.4699336",
"0.46814412",
"0.4667058",
"0.4666113",
"0.46656263",
"0.46632376",
"0.46615872",
"0.46615726",
"0.46587914",
"0.46572432",
"0.46566007",
"0.46550044",
"0.46521387",
"0.46461883",
"0.4645817",
"0.46449757",
"0.46403822",
"0.46395588",
"0.46391997",
"0.4634475",
"0.46327",
"0.46298656",
"0.4626258",
"0.46246594",
"0.4624447",
"0.46212432",
"0.4614228",
"0.4611126",
"0.46088448",
"0.46022075",
"0.45964673",
"0.45949757",
"0.459169",
"0.4589383",
"0.4583083",
"0.45770344",
"0.45766574",
"0.45764756",
"0.45725775",
"0.45725045",
"0.45623264"
] | 0.61740804 | 0 |
GET /air_moistures GET /air_moistures.json | def index
@air_moistures = AirMoisture.all
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @air_qualities = AirQuality.all\n\n render json: @air_qualities\n end",
"def index\n @soil_moistures = SoilMoisture.all\n end",
"def show\n render json: @air_quality\n end",
"def set_air_moisture\n @air_moisture = AirMoisture.find(params[:id])\n end",
"def index\n @captures = Capture.all\n\n render json: @captures\n end",
"def index\n @airplanes = Airplane.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @airplanes }\n end\n end",
"def index\n @mugshots = Mugshot.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @mugshots }\n end\n end",
"def show\r\n @imobiliaria = Imobiliaria.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.json { render json: @imobiliaria }\r\n end\r\n end",
"def show\n @airlin = Airlin.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @airlin }\n end\n end",
"def index\n airlines = Airline.includes(:airplanes).all.page(page).per(per)\n json_response(PageDecorator.decorate(airlines)\n .as_json(airplanes_details: true), :ok)\n end",
"def index\n @movers = Mover.all\n\n render json: @movers\n end",
"def index\n @imagems = Imagem.where(:imovel_id => current_user.imovels {|i| i.id})\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @imagems }\n end\n end",
"def show\n json_response(@airline.decorate.as_json(airplanes_details: true), :ok)\n end",
"def movie_data\n response = RestClient.get(\"critics.api.mks.io/movie-genres\")\n JSON.parse(response)\nend",
"def index\n weathers = Weather.all\n render json: weathers, status: 200\n end",
"def show\n @ami = Ami.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ami }\n end\n end",
"def show\n @air_crew = AirCrew.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @air_crew }\n end\n end",
"def index\n @universes = Universe.all.page(params[:page]).per(25)\n respond_to do |format|\n format.html\n format.json { render json: @universes }\n end\n end",
"def index\n @microroles = Microrole.includes(:verb_coding_frame_microroles).readonly(false).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @microroles }\n end\n end",
"def index\r\n @imobiliarias = Imobiliaria.all\r\n\r\n respond_to do |format|\r\n # format.html # index.html.erb\r\n format.json { render json: @imobiliarias }\r\n end\r\n end",
"def show\n\n @anime = Finder.find_anime_by_id params[:id]\n @anime ||= KiWi.show_anime params[:id]\n\n # binding.pry\n\n render json: @anime\n end",
"def index\n\n @metro_lines = MetroLine.all\n\n render json: @metro_lines\n\n end",
"def show\n @mi = Mi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mi }\n end\n end",
"def index\n @lights = Light.all\n\n render json: @lights\n end",
"def index\n @pictures = Picture.where(foodscape_id: params[:foodscape_id])\n render json: @pictures\n end",
"def index\n @chairs = Chair.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @chairs }\n end\n end",
"def index\n @regimes = Regime.all\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @regimes }\n # end\n end",
"def index\n @shots = Shot.all\n\n render json: @shots\n end",
"def index\n @airs = Air.all\n end",
"def index\n @magissues = Magissue.all\n @magazines = Magazine.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @magissues }\n end\n end",
"def corona_virus\n # endpoint = \"https://corona.lmao.ninja/all\"\n endpoint = 'https://corona.lmao.ninja/v2/all'\n response = HTTParty.get(endpoint)\n data = JSON.parse response.body\n res = data\n result = []\n result<<{\n country: \"world\",\n cases: res[\"cases\"],\n todayCases: res[\"todayCases\"],\n deaths: res[\"deaths\"],\n todayDeaths: res[\"todayDeaths\"],\n recovered: res[\"recovered\"],\n active: res[\"active\"],\n critical: res[\"critical\"],\n casesPerOneMillion: res[\"casesPerOneMillion\"],\n deathsPerOneMillion: res[\"deathsPerOneMillion\"],\n tests: res[\"tests\"],\n testsPerOneMillion: res[\"testsPerOneMillion\"],\n affectedCountries: res[\"affectedCountries\"]\n }\n render json: result\n end",
"def index\n @pictures = @museum.pictures.all #Picture.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pictures }\n end\n end",
"def index\n @cap_image = fetch_cap_image(params['q'])\n\n if @cap_image.nil?\n @cap_image = CapImage.all.first\n flash.now[:alert] = 'Couldn\\'t fetch random image. Here\\'s one from the archives.'\n end\n\n respond_to do |format|\n format.html\n format.json { render json: @cap_image }\n end\n end",
"def index\n @machines = Machine.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @machines }\n end\n end",
"def index\n @recipies = Recipy.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @recipies }\n end\n end",
"def index\n @airlines = Airline.all\n end",
"def index\n @airlines = Airline.all\n end",
"def show\n @moretinymobtrail = Moretinymobtrail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moretinymobtrail }\n end\n end",
"def index\n @objectives = @goal.objectives.all \n render json: @objectives \n end",
"def show\n @material_apoyo = MaterialApoyo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @material_apoyo }\n end\n end",
"def index\n @mini_games = MiniGame.all\n render json: @mini_games, status: :ok\n end",
"def index\n \tif params[:category] == \"METRO\"\n \trender :json => Interest.stops.to_json\n elsif params[:category] == \"Photos\"\n render :json => Interest.panoramio\n \telsif params[:category]\n \t\tcategory_id = Category.find_by_name(params[:category]).id\n \t\trender :json => Interest.find_all_by_category_id(category_id).to_json(:methods => :category_name)\n \telse\n \t\trender :json => Interest.all\n \tend\n\n end",
"def index\n @miles = Mile.all\n end",
"def show\n # proxy to GET /roi/id\n @result = ImageServer.get('/roi/'+params[:id]);\n render :json => @result\n end",
"def index\n @testmonials = Testmonial.all\n\n render json: @testmonials\n end",
"def show\n @agronomiaquimica = Agronomiaquimica.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agronomiaquimica }\n end\n end",
"def show\n @monit = Monit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @monit }\n end\n end",
"def index\n @ivas = Iva.all\n\n render json: @ivas\n end",
"def route\n hitch = Hitch.find(params[:hitch_id])\n render json: hitch.geojson\n end",
"def index\r\n @machines = Machine.all\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.json { render json: @machines }\r\n end\r\n end",
"def index\n @animais = Animai.all\n end",
"def index\n champions = Champion.all\n render json: champions\n end",
"def index\n @itineraryList = Itinerary.all\n render json: @itineraryList, status: 200\n end",
"def index\n @midias = Midia.all\n end",
"def show\n lat = @airport.latitude_deg\n lng = @airport.longitude_deg\n \n @map_markers = Gmaps4rails.build_markers(@airport) do |airport,marker|\n marker.lat lat\n marker.lng lng\n end\n response = RestClient.get \"http://api.openweathermap.org/data/2.5/weather\", :params => {:lat => lat, :lon => lng}\n @weather = Crack::JSON.parse(response.body) \n end",
"def index\n @flights = Flight.all\n render json: @flights\n end",
"def show\n\n @observation = Observation.find(params[:id])\n @coral = Coral.find(params[:coral_id])\n\n @files = Dir.glob(\"app/assets/images/tagged_outlines_thumbs/*\")\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @observation }\n end\n end",
"def create\n @air_moisture = AirMoisture.new(air_moisture_params)\n\n respond_to do |format|\n if @air_moisture.save\n format.html { redirect_to @air_moisture, notice: 'Air moisture was successfully created.' }\n format.json { render :show, status: :created, location: @air_moisture }\n else\n format.html { render :new }\n format.json { render json: @air_moisture.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @maps = Map.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @maps }\n end\n end",
"def show\n @monnaie = Monnaie.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @monnaie }\n end\n end",
"def index\n @lugars = Lugar.all\n\n render json: @lugars\n end",
"def index\n @space_stations = SpaceStation.all\n\n render json: @space_stations, include: :astronauts\n\n end",
"def index\n @mohrs = Mohr.all\n end",
"def show\n\n @moretinymap = Moretinymap.find(params[:id])\n\n @guardmobs = Moretinymob.find_all_by_moretinymap_id_and_is_guard(params[:id], true, :include => :moretinymobinfo)\n @intrudermobs = Moretinymob.find_all_by_moretinymap_id_and_is_guard(params[:id], false, :include => :moretinymobinfo)\n\n @intrudermobtrail = Moretinymobtrail.first(:include => :moretinymob, :conditions => [\"moretinymobs.is_guard = ?\", false])\n\n @mobbattles = Moretinymobbattle.all\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moretinymap }\n end\n end",
"def show\n @materia = Materia.find(params[:id])\n\n render json: @materia\n end",
"def index\n @brochures = Brochure.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @brochures }\n end\n end",
"def index\n @interno_unidads = InternoUnidad.all\n render json: @interno_unidads\n end",
"def show\n @magzine = Magzine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @magzine }\n end\n end",
"def index\n @minerals = Mineral.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @minerals }\n end\n end",
"def show\n @precious_metal = PreciousMetal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @precious_metal }\n end\n end",
"def index\n @warriors = Warrior.all\n render :json => @warriors, :include => [:skills, :equipment_lists,]\n\n end",
"def show\n @origami = Origami.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @origami }\n end\n end",
"def index\n @carbon_monoxides = CarbonMonoxide.all\n render json: @carbon_monoxides\n end",
"def index\n hardware = Hardware.all\n render json: hardware.to_json(:except => [:id])\n end",
"def index\n @military_battle_rounds = Military::BattleRound.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @military_battle_rounds }\n end\n end",
"def show\n @airport = Airport.find(params[:id])\n @airlines = Aircompany.where(airport_id: params[:id])\n respond_to do |format|\n format.html \n format.json { render json: @airport }\n end\n end",
"def index\n\t@instruction = Instruction.find( params[ :instruction_id ] )\n @testimonies = @instruction.testimonies.page( params[ :page ] ).per(20)\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @testimonies }\n end\n end",
"def index\n @alleys = Alley.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @alleys }\n end\n end",
"def index\n @universities = University.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @universities }\n end\n end",
"def show\n render json: @shot\n end",
"def show\n @aroma = Aroma.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @aroma }\n end\n end",
"def show\n @mosttinymobtrail = Mosttinymobtrail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mosttinymobtrail }\n end\n end",
"def index\n #@world_maps = WorldMap.all\n\n respond_to do |format|\n format.html # index.erb.erb\n format.json { render json: @world_maps }\n end\n end",
"def show\n @missionmaker = Missionmaker.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @missionmaker }\n end\n end",
"def index\n @airplanes = Airplane.all\n end",
"def index\n @machines = @location.machines\n @machine = Machine.new\n @titles = Title.all\n\n respond_to do |format|\n format.html {require_user}\n format.json { render json: @machines }\n end\n end",
"def magasin\r\n \tvil = params[:id]\r\n \tmagasin = Market.where(vil_id: vil, type_id: 5)\r\n \trender json: magasin\r\n end",
"def show\n render json: @rock_photo\n end",
"def index\n @appeals = @conference.appeals\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @appeals }\n end\n end",
"def index\n @hours = Hour.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @hours }\n end\n end",
"def index\n @moussaillons = Moussaillon.all\n end",
"def show\n @airplane = Airplane.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @airplane }\n end\n end",
"def index\n @intermediaries = Intermediary.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @intermediaries }\n end\n end",
"def show\n @mini_map_road = MiniMapRoad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mini_map_road }\n end\n end",
"def index\n @marios = Mario.all\n end",
"def show\n @microfilm_reel = MicrofilmReel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @microfilm_reel }\n end\n end",
"def show\n @chair = Chair.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @chair }\n end\n end",
"def show\n @chair = Chair.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @chair }\n end\n end",
"def index\n @modalities = Modality.all\n json_response(@modalities)\n end",
"def index\n @pic_spaces = PicSpace.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pic_spaces }\n end\n end"
] | [
"0.6477318",
"0.6322574",
"0.6238727",
"0.6140732",
"0.6136393",
"0.61150396",
"0.6083614",
"0.60437167",
"0.60434604",
"0.6033698",
"0.60279095",
"0.6005438",
"0.59941566",
"0.5992053",
"0.5980522",
"0.59371537",
"0.59309715",
"0.5927996",
"0.59212065",
"0.59185755",
"0.59071434",
"0.5899847",
"0.5873909",
"0.5867592",
"0.5846736",
"0.58411145",
"0.5831182",
"0.58149505",
"0.5806449",
"0.58040226",
"0.5797546",
"0.57736707",
"0.57506526",
"0.57387984",
"0.5738076",
"0.5730332",
"0.5730332",
"0.5706079",
"0.5698094",
"0.5694121",
"0.5685538",
"0.5684728",
"0.56831443",
"0.56816196",
"0.56775075",
"0.5666947",
"0.5666324",
"0.56560737",
"0.56519115",
"0.564988",
"0.5638154",
"0.56366044",
"0.5631201",
"0.56287223",
"0.56274104",
"0.5627312",
"0.5626768",
"0.56244487",
"0.562372",
"0.5608407",
"0.56031054",
"0.56018186",
"0.5600606",
"0.5596212",
"0.5594819",
"0.5593554",
"0.5592435",
"0.55923706",
"0.5586677",
"0.558631",
"0.55851734",
"0.55822104",
"0.5581255",
"0.5578924",
"0.557847",
"0.5575719",
"0.5575614",
"0.5574519",
"0.5570428",
"0.55669487",
"0.55598074",
"0.5557713",
"0.55547196",
"0.555458",
"0.55532515",
"0.5552385",
"0.5551769",
"0.555016",
"0.5545914",
"0.5543886",
"0.5543838",
"0.55405474",
"0.5537481",
"0.55349535",
"0.55321074",
"0.5529187",
"0.55286247",
"0.55286247",
"0.55283725",
"0.55283016"
] | 0.75258315 | 0 |
GET /air_moistures/1 GET /air_moistures/1.json | def show
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @air_moistures = AirMoisture.all\n end",
"def index\n @air_qualities = AirQuality.all\n\n render json: @air_qualities\n end",
"def show\r\n @imobiliaria = Imobiliaria.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.json { render json: @imobiliaria }\r\n end\r\n end",
"def show\n @mi = Mi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mi }\n end\n end",
"def show\n render json: @air_quality\n end",
"def show\n @ami = Ami.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ami }\n end\n end",
"def show\n @airlin = Airlin.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @airlin }\n end\n end",
"def index\n @soil_moistures = SoilMoisture.all\n end",
"def index\n @mugshots = Mugshot.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @mugshots }\n end\n end",
"def movie_data\n response = RestClient.get(\"critics.api.mks.io/movie-genres\")\n JSON.parse(response)\nend",
"def index\n @imagems = Imagem.where(:imovel_id => current_user.imovels {|i| i.id})\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @imagems }\n end\n end",
"def set_air_moisture\n @air_moisture = AirMoisture.find(params[:id])\n end",
"def index\n @movers = Mover.all\n\n render json: @movers\n end",
"def index\n @captures = Capture.all\n\n render json: @captures\n end",
"def show\n @monit = Monit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @monit }\n end\n end",
"def index\n @airplanes = Airplane.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @airplanes }\n end\n end",
"def show\n @air_crew = AirCrew.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @air_crew }\n end\n end",
"def index\n @microroles = Microrole.includes(:verb_coding_frame_microroles).readonly(false).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @microroles }\n end\n end",
"def show\n\n @anime = Finder.find_anime_by_id params[:id]\n @anime ||= KiWi.show_anime params[:id]\n\n # binding.pry\n\n render json: @anime\n end",
"def index\r\n @imobiliarias = Imobiliaria.all\r\n\r\n respond_to do |format|\r\n # format.html # index.html.erb\r\n format.json { render json: @imobiliarias }\r\n end\r\n end",
"def show\n @monnaie = Monnaie.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @monnaie }\n end\n end",
"def index\n\n @metro_lines = MetroLine.all\n\n render json: @metro_lines\n\n end",
"def show\n @moretinymobtrail = Moretinymobtrail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moretinymobtrail }\n end\n end",
"def show\n # proxy to GET /roi/id\n @result = ImageServer.get('/roi/'+params[:id]);\n render :json => @result\n end",
"def show\n @missionmaker = Missionmaker.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @missionmaker }\n end\n end",
"def show\n @material_apoyo = MaterialApoyo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @material_apoyo }\n end\n end",
"def index\n @pictures = Picture.where(foodscape_id: params[:foodscape_id])\n render json: @pictures\n end",
"def index\n weathers = Weather.all\n render json: weathers, status: 200\n end",
"def show\n @materia = Materia.find(params[:id])\n\n render json: @materia\n end",
"def show\n @microfilm_reel = MicrofilmReel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @microfilm_reel }\n end\n end",
"def show\n @agronomiaquimica = Agronomiaquimica.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agronomiaquimica }\n end\n end",
"def show\n @mini_map_road = MiniMapRoad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mini_map_road }\n end\n end",
"def show\n @precious_metal = PreciousMetal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @precious_metal }\n end\n end",
"def index\n @shots = Shot.all\n\n render json: @shots\n end",
"def show\n json_response(@airline.decorate.as_json(airplanes_details: true), :ok)\n end",
"def show\n @imagem = Imagem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @imagem }\n end\n end",
"def index\n @cap_image = fetch_cap_image(params['q'])\n\n if @cap_image.nil?\n @cap_image = CapImage.all.first\n flash.now[:alert] = 'Couldn\\'t fetch random image. Here\\'s one from the archives.'\n end\n\n respond_to do |format|\n format.html\n format.json { render json: @cap_image }\n end\n end",
"def index\n @magissues = Magissue.all\n @magazines = Magazine.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @magissues }\n end\n end",
"def show\n @magzine = Magzine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @magzine }\n end\n end",
"def index\n @regimes = Regime.all\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @regimes }\n # end\n end",
"def show\n @metum = Metum.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @metum }\n end\n end",
"def index\n @recipies = Recipy.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @recipies }\n end\n end",
"def magasin\r\n \tvil = params[:id]\r\n \tmagasin = Market.where(vil_id: vil, type_id: 5)\r\n \trender json: magasin\r\n end",
"def show\n @mosttinymobtrail = Mosttinymobtrail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mosttinymobtrail }\n end\n end",
"def index\n @machines = Machine.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @machines }\n end\n end",
"def show\n @moresmalltrial = Moresmalltrial.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moresmalltrial }\n end\n end",
"def index\n hardware = Hardware.all\n render json: hardware.to_json(:except => [:id])\n end",
"def index\n @lights = Light.all\n\n render json: @lights\n end",
"def show\n @origami = Origami.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @origami }\n end\n end",
"def index\n @pictures = @museum.pictures.all #Picture.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pictures }\n end\n end",
"def index\n @universes = Universe.all.page(params[:page]).per(25)\n respond_to do |format|\n format.html\n format.json { render json: @universes }\n end\n end",
"def index\n @testmonials = Testmonial.all\n\n render json: @testmonials\n end",
"def show\n @mugshot = Mugshot.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mugshot }\n end\n end",
"def show\n @plate = Plate.find(params[:id])\n\n render json: @plate\n end",
"def index\n @chairs = Chair.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @chairs }\n end\n end",
"def show\n @uchronia = Uchronia.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @uchronia }\n end\n end",
"def index\n airlines = Airline.includes(:airplanes).all.page(page).per(per)\n json_response(PageDecorator.decorate(airlines)\n .as_json(airplanes_details: true), :ok)\n end",
"def index\n @mini_games = MiniGame.all\n render json: @mini_games, status: :ok\n end",
"def show\n @mill = Mill.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mill }\n end\n end",
"def show\n tile = Tile.find(params[:id]) \n render json: tile\n end",
"def show\n @intermediary = Intermediary.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @intermediary }\n end\n end",
"def show\n\n @moretinymap = Moretinymap.find(params[:id])\n\n @guardmobs = Moretinymob.find_all_by_moretinymap_id_and_is_guard(params[:id], true, :include => :moretinymobinfo)\n @intrudermobs = Moretinymob.find_all_by_moretinymap_id_and_is_guard(params[:id], false, :include => :moretinymobinfo)\n\n @intrudermobtrail = Moretinymobtrail.first(:include => :moretinymob, :conditions => [\"moretinymobs.is_guard = ?\", false])\n\n @mobbattles = Moretinymobbattle.all\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moretinymap }\n end\n end",
"def index\n @mohrs = Mohr.all\n end",
"def show\n @moresmallarmorinfo = Moresmallarmorinfo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moresmallarmorinfo }\n end\n end",
"def index\r\n @machines = Machine.all\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.json { render json: @machines }\r\n end\r\n end",
"def show\n @orc = Orc.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @orc }\n end\n end",
"def show\n @aroma = Aroma.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @aroma }\n end\n end",
"def show\n @minicurso = Minicurso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @minicurso }\n end\n end",
"def show\n @mision = Mision.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mision }\n end\n end",
"def index\n\t@instruction = Instruction.find( params[ :instruction_id ] )\n @testimonies = @instruction.testimonies.page( params[ :page ] ).per(20)\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @testimonies }\n end\n end",
"def show\n @monel = Monel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @monel }\n end\n end",
"def show\n @micorpost = Micorpost.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @micorpost }\n end\n end",
"def show\n @plane_photo = PlanePhoto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @plane_photo }\n end\n end",
"def show\n @title = \"Current Medic\"\n @medic = Medic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @medic }\n end\n end",
"def show\n @matricula = Matricula.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @matricula }\n end\n end",
"def show\n @microposr = Microposr.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @microposr }\n end\n end",
"def index\n @carbon_monoxides = CarbonMonoxide.all\n render json: @carbon_monoxides\n end",
"def show\n @airplane = Airplane.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @airplane }\n end\n end",
"def show\n @chair = Chair.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @chair }\n end\n end",
"def show\n @chair = Chair.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @chair }\n end\n end",
"def route\n hitch = Hitch.find(params[:hitch_id])\n render json: hitch.geojson\n end",
"def show\n @remito = Remito.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @remito }\n end\n end",
"def show\n @recipy = Recipy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @recipy }\n end\n end",
"def get\n\t\t\t result = Status.find_by(windmillid: params[:windmillid]) \n \t\t\trender json: [result.as_json(only: [:status,:power,:gen,:frequency,:rotor,:wind,:pitch])]\n\tend",
"def index\n @intermediaries = Intermediary.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @intermediaries }\n end\n end",
"def index\n \tif params[:category] == \"METRO\"\n \trender :json => Interest.stops.to_json\n elsif params[:category] == \"Photos\"\n render :json => Interest.panoramio\n \telsif params[:category]\n \t\tcategory_id = Category.find_by_name(params[:category]).id\n \t\trender :json => Interest.find_all_by_category_id(category_id).to_json(:methods => :category_name)\n \telse\n \t\trender :json => Interest.all\n \tend\n\n end",
"def index\n @objectives = @goal.objectives.all \n render json: @objectives \n end",
"def new\n @m_oil = MOil.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @m_oil }\n end\n end",
"def show\n @joy = Joy.find(params[:id])\n render json: @joy\n end",
"def show\n @areco = Areco.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @areco }\n end\n end",
"def show\n @photo = Photo.find(params[:id])\n\n render json: @photo\n end",
"def new\n @airlin = Airlin.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @airlin }\n end\n end",
"def show\n render json: @rock_photo\n end",
"def index\n @midias = Midia.all\n end",
"def index\n @minerals = Mineral.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @minerals }\n end\n end",
"def show\n render json: @shot\n end",
"def show\n @mattress = Mattress.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mattress }\n end\n end",
"def show\n @mrj = Mrj.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mrj }\n end\n end",
"def show\n @autore = Autore.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @autore }\n end\n end",
"def show\n respond_to do |format|\n format.html\n format.json { render json: @maudio}\n end\n end",
"def show\n @hwm_resource_pic = HwmResourcePic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @hwm_resource_pic }\n end\n end"
] | [
"0.72442585",
"0.6445022",
"0.64213204",
"0.63258666",
"0.6315291",
"0.62367606",
"0.6211252",
"0.62108004",
"0.61827606",
"0.6172943",
"0.6165749",
"0.615278",
"0.61441934",
"0.61220115",
"0.6120221",
"0.61193347",
"0.61040413",
"0.6091801",
"0.6057288",
"0.6049138",
"0.6037803",
"0.6007729",
"0.60054564",
"0.6005301",
"0.59855497",
"0.59849143",
"0.5982721",
"0.59783727",
"0.59667844",
"0.5948411",
"0.5946194",
"0.59386635",
"0.59322864",
"0.5932029",
"0.59210885",
"0.59188986",
"0.59145844",
"0.5914025",
"0.59091425",
"0.5908505",
"0.59065527",
"0.5887438",
"0.5882817",
"0.5869699",
"0.5868602",
"0.5861167",
"0.5854259",
"0.58483076",
"0.58480924",
"0.5847885",
"0.58460814",
"0.58424187",
"0.5842017",
"0.58393306",
"0.58257514",
"0.5824789",
"0.5824557",
"0.5818369",
"0.58125",
"0.58071136",
"0.5802796",
"0.57912594",
"0.5784193",
"0.5775685",
"0.57753813",
"0.57738984",
"0.57667893",
"0.57667804",
"0.57659394",
"0.5755209",
"0.57550967",
"0.57493544",
"0.5742728",
"0.5738919",
"0.5736325",
"0.5736046",
"0.5728475",
"0.572693",
"0.57254755",
"0.57254755",
"0.5725091",
"0.57196087",
"0.57187426",
"0.57187325",
"0.57065797",
"0.57030797",
"0.57029694",
"0.5696725",
"0.5696169",
"0.56945354",
"0.56942767",
"0.56932575",
"0.56924075",
"0.5692373",
"0.5692156",
"0.56912726",
"0.56904465",
"0.56891745",
"0.56878215",
"0.56838626",
"0.56831586"
] | 0.0 | -1 |
POST /air_moistures POST /air_moistures.json | def create
@air_moisture = AirMoisture.new(air_moisture_params)
respond_to do |format|
if @air_moisture.save
format.html { redirect_to @air_moisture, notice: 'Air moisture was successfully created.' }
format.json { render :show, status: :created, location: @air_moisture }
else
format.html { render :new }
format.json { render json: @air_moisture.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @air_moistures = AirMoisture.all\n end",
"def create\n @soil_moisture = SoilMoisture.new(soil_moisture_params)\n\n respond_to do |format|\n if @soil_moisture.save\n format.html { redirect_to @soil_moisture, notice: 'Soil moisture was successfully created.' }\n format.json { render :show, status: :created, location: @soil_moisture }\n else\n format.html { render :new }\n format.json { render json: @soil_moisture.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_air_moisture\n @air_moisture = AirMoisture.find(params[:id])\n end",
"def create\n @air_quality = AirQuality.new(air_quality_params)\n\n if @air_quality.save\n render json: @air_quality, status: :created, location: @air_quality\n else\n render json: @air_quality.errors, status: :unprocessable_entity\n end\n end",
"def create\n @wi_mn_d_max_t_air = WiMnDMaxTAir.new(wi_mn_d_max_t_air_params)\n\n respond_to do |format|\n if @wi_mn_d_max_t_air.save\n format.html { redirect_to @wi_mn_d_max_t_air, notice: 'Wi mn d max t air was successfully created.' }\n format.json { render action: 'show', status: :created, location: @wi_mn_d_max_t_air }\n else\n format.html { render action: 'new' }\n format.json { render json: @wi_mn_d_max_t_air.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @ami = Ami.new(params[:ami])\n\n respond_to do |format|\n if @ami.save\n format.html { redirect_to @ami, notice: 'Ami was successfully created.' }\n format.json { render json: @ami, status: :created, location: @ami }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ami.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @wi_mn_d_min_t_air = WiMnDMinTAir.new(wi_mn_d_min_t_air_params)\n\n respond_to do |format|\n if @wi_mn_d_min_t_air.save\n format.html { redirect_to @wi_mn_d_min_t_air, notice: 'Wi mn d min t air was successfully created.' }\n format.json { render action: 'show', status: :created, location: @wi_mn_d_min_t_air }\n else\n format.html { render action: 'new' }\n format.json { render json: @wi_mn_d_min_t_air.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @wi_mn_d_ave_t_air = WiMnDAveTAir.new(wi_mn_d_ave_t_air_params)\n\n respond_to do |format|\n if @wi_mn_d_ave_t_air.save\n format.html { redirect_to @wi_mn_d_ave_t_air, notice: 'Wi mn d ave t air was successfully created.' }\n format.json { render action: 'show', status: :created, location: @wi_mn_d_ave_t_air }\n else\n format.html { render action: 'new' }\n format.json { render json: @wi_mn_d_ave_t_air.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @air = Air.new(air_params)\n @air.room_id = current_user.id\n respond_to do |format|\n if @air.save\n format.html { redirect_to @air, notice: 'Air was successfully created.' }\n format.json { render :show, status: :created, location: @air }\n else\n format.html { render :new }\n format.json { render json: @air.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @moon = Moon.new(moon_params)\n\n respond_to do |format|\n if @moon.save\n format.html { redirect_to @moon, notice: 'Moon was successfully created.' }\n format.json { render :show, status: :created, location: @moon }\n else\n format.html { render :new }\n format.json { render json: @moon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def air_moisture_params\n params.require(:air_moisture).permit(:min, :max, :disease_id, :cf)\n end",
"def create\n megam_rest.post_promos(to_hash) #WONT BE USED AS OF NOW\n end",
"def create\r\n @imobiliaria = Imobiliaria.new(imobiliaria_params)\r\n\r\n respond_to do |format|\r\n if @imobiliaria.save\r\n format.json { render json: @imobiliaria, status: :created }\r\n else \r\n format.json { render json: @imobiliaria.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def create\n @mile = Mile.new(mile_params)\n\n respond_to do |format|\n if @mile.save\n format.html { redirect_to @mile, notice: 'Mile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @mile }\n else\n format.html { render action: 'new' }\n format.json { render json: @mile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @air_crew = AirCrew.new(params[:air_crew])\n\n respond_to do |format|\n if @air_crew.save\n format.html { redirect_to @air_crew, notice: 'Air crew was successfully created.' }\n format.json { render json: @air_crew, status: :created, location: @air_crew }\n else\n format.html { render action: \"new\" }\n format.json { render json: @air_crew.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @iso = Iso.new(iso_params)\n\n respond_to do |format|\n if @iso.save\n format.html { redirect_to @iso, notice: 'Iso was successfully created.' }\n format.json { render action: 'show', status: :created, location: @iso }\n else\n format.html { render action: 'new' }\n format.json { render json: @iso.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mi = Mi.new(params[:mi])\n\n respond_to do |format|\n if @mi.save\n format.html { redirect_to @mi, notice: 'Mi was successfully created.' }\n format.json { render json: @mi, status: :created, location: @mi }\n else\n format.html { render action: \"new\" }\n format.json { render json: @mi.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @airlin = Airlin.new(params[:airlin])\n\n respond_to do |format|\n if @airlin.save\n format.html { redirect_to @airlin, notice: 'Airlin was successfully created.' }\n format.json { render json: @airlin, status: :created, location: @airlin }\n else\n format.html { render action: \"new\" }\n format.json { render json: @airlin.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @airline = Airline.new(airline_params)\n\n if @airline.save\n json_response(@airline.decorate.as_json(airplanes_details: true),\n :created)\n else\n json_response(@airline.errors, :unprocessable_entity)\n end\n end",
"def create\n @moussaillon = Moussaillon.new(moussaillon_params)\n\n respond_to do |format|\n if @moussaillon.save\n format.html { redirect_to @moussaillon, notice: 'Moussaillon was successfully created.' }\n format.json { render :show, status: :created, location: @moussaillon }\n else\n format.html { render :new }\n format.json { render json: @moussaillon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @animai = Animai.new(animai_params)\n\n respond_to do |format|\n if @animai.save\n format.html { redirect_to @animai, notice: 'Animai was successfully created.' }\n format.json { render :show, status: :created, location: @animai }\n else\n format.html { render :new }\n format.json { render json: @animai.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @anime = Pusher.create_anime(params[:anime])\n\n if @anime.valid?\n render json: @anime, status: :created, location: @anime\n else\n render json: @anime.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @air_moisture.update(air_moisture_params)\n format.html { redirect_to @air_moisture, notice: 'Air moisture was successfully updated.' }\n format.json { render :show, status: :ok, location: @air_moisture }\n else\n format.html { render :edit }\n format.json { render json: @air_moisture.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @plate = Plate.new(params[:plate])\n\n if @plate.save\n render json: @plate, status: :created, location: @plate\n else\n render json: @plate.errors, status: :unprocessable_entity\n end\n end",
"def moip_post\n @nasp_rail = NaspRail.new(params[:nasp_rail])\n\n format.html { redirect_to @nasp_rail, :notice => 'Nova entrada criada com sucesso.' }\n format.json { render :json => @nasp_rail, :status => :created, :location => @nasp_rail }\n end",
"def create\n @sky = Sky.new(sky_params)\n\n respond_to do |format|\n if @sky.save\n format.html { redirect_to @sky, notice: 'Sky was successfully created.' }\n format.json { render :show, status: :created, location: @sky }\n else\n format.html { render :new }\n format.json { render json: @sky.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @precious_metal = PreciousMetal.new(params[:precious_metal])\n\n respond_to do |format|\n if @precious_metal.save\n format.html { redirect_to @precious_metal, :notice => 'Precious metal was successfully created.' }\n format.json { render :json => @precious_metal, :status => :created, :location => @precious_metal }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @precious_metal.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @impressum = Impressum.new(impressum_params)\n\n respond_to do |format|\n if @impressum.save\n format.html { redirect_to @impressum, notice: 'Impressum was successfully created.' }\n format.json { render :show, status: :created, location: @impressum }\n else\n format.html { render :new }\n format.json { render json: @impressum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @shot = Shot.new(shot_params)\n\n if @shot.save\n render json: @shot, status: :created, location: @shot\n else\n render json: @shot.errors, status: :unprocessable_entity\n end\n end",
"def create\n @trail = Trail.new(params[:trail])\n respond_to do |format|\n if @trail.save\n\t@trail.lat_map = elevation(@trail.longitude_start, @trail.latitude_start, @trail.longitude_end, @trail.latitude_end)\n\t@trail.gmap = staticmap_uri(@trail.longitude_start + \",\" + @trail.latitude_start + \"|\"+ @trail.longitude_end + \",\" + @trail.latitude_end)\n\t@trail.save\n format.html { redirect_to @trail, notice: 'Trail was successfully created.' }\n format.json { render json: @trail, status: :created, location: @trail }\n else\n format.html { render action: \"new\" }\n format.json { render json: @trail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @moretinymap = Moretinymap.new(params[:moretinymap])\n\n respond_to do |format|\n if @moretinymap.save\n format.html { redirect_to @moretinymap, notice: 'Moretinymap was successfully created.' }\n format.json { render json: @moretinymap, status: :created, location: @moretinymap }\n else\n format.html { render action: \"new\" }\n format.json { render json: @moretinymap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @airplane = Airplane.new(params[:airplane])\n\n respond_to do |format|\n if @airplane.save\n format.html { redirect_to @airplane, :notice => 'Airplane was successfully created.' }\n format.json { render :json => @airplane, :status => :created, :location => @airplane }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @airplane.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n #When creating a new mission, current point should default to zero\n @mission = Mission.new()\n # @mission = Mission.new({\"name\" => params[:name], \"goal_points\" => params[:goal_points].to_i, \"current_points\" => 0, \"image\" => params[:image]})\n @mission.name = params[:name]\n @mission.goal_points = params[:goal_points].to_i\n @mission.current_points = 0\n @mission.image = params[:image]\n \n \n if @mission.valid? \n @mission.save!\n respond_to do |format|\n format.json { render json: @mission }\n format.xml { render xml: @mission }\n end\n else\n respond_to do |format|\n #format.json { render action: 'index' }\n format.json { render json: @mission.errors,status: :unprocessable_entity }\n \n end\n end\n end",
"def create\n request_image = params[:image]\n url_hash = SecureRandom.urlsafe_base64(6)\n name = url_hash + \"-\" + request_image.original_filename.downcase\n\n File.open(\"#{Rails.root}/public/theta/#{name}\", 'wb') do |f|\n f.write(request_image.read)\n end\n\n theta = Theta.create!(url_hash: url_hash, image_url: name)\n render json: {url: \"http://www.rakugaki.tk/h/#{theta.url_hash}\"}, status: 201\n end",
"def create\n @meteo_datum = MeteoDatum.new(meteodatum_params)\n @meteo_datum.weather_station_id = params[:weather_station_id]\n\n if @meteo_datum.save\n render json: @meteo_datum, status: :created\n else\n render json: @meteo_datum.errors, status: :unprocessable_entity\n end\n end",
"def create\n @arma = Arma.new(params[:arma])\n\n respond_to do |format|\n if @arma.save\n format.html { redirect_to @arma, notice: 'Arma was successfully created.' }\n format.json { render json: @arma, status: :created, location: @arma }\n else\n format.html { render action: \"new\" }\n format.json { render json: @arma.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @action = params[:action_military_retreat_army_action]\n \n army = Military::Army.find(@action[:army_id])\n \n raise NotFoundError.new('army not found') if army.nil?\n raise BadRequestError.new('not owner of army') unless army.owner == current_character\n\n army.battle_retreat = @action[:retreat]\n raise BadRequestError.new('not owner of army') unless army.save \n\n respond_to do |format|\n format.html { redirect_to action_path, notice: 'Retreat army action was successfully executed.' }\n format.json { render json: {}, status: :created }\n end\n end",
"def create\n @micro_area = MicroArea.new(micro_area_params)\n\n respond_to do |format|\n if @micro_area.save\n format.html { redirect_to @micro_area, flash: { success: \"Micro Área criada com sucesso!\" } }\n format.json { render :show, status: :created, location: @micro_area }\n else\n format.html { render :new }\n format.json { render json: @micro_area.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @air_moisture.destroy\n respond_to do |format|\n format.html { redirect_to air_moistures_url, notice: 'Air moisture was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def create\n @moretinymobtrail = Moretinymobtrail.new(params[:moretinymobtrail])\n\n respond_to do |format|\n if @moretinymobtrail.save\n format.html { redirect_to @moretinymobtrail, notice: 'Moretinymobtrail was successfully created.' }\n format.json { render json: @moretinymobtrail, status: :created, location: @moretinymobtrail }\n else\n format.html { render action: \"new\" }\n format.json { render json: @moretinymobtrail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @workout = Workout.new(name: params[:name], steps: params[:steps], description: params[:description], time: params[:time], image_url: params[:image_url], video_url: params[:video_url], running: params[:running], weightlifting: params[:weightlifting], swimming: params[:swimming], circuit_training: params[:circuit_training], cycling: params[:cycling], creator_id: current_athlete.id, workout_creator: current_athlete.username)\n\n if @workout.save\n AthleteWorkout.create(workout_id: @workout.id, athlete_id: current_athlete.id)\n render 'create.json.jbuilder', status: :created\n else\n render json: { errors: @athlete.errors.full_messages }, status: :unprocessable_entity\n end\n end",
"def create\n @motoristum = Motoristum.new(motoristum_params)\n\n respond_to do |format|\n if @motoristum.save\n format.html { redirect_to @motoristum, notice: 'Motoristum was successfully created.' }\n format.json { render :show, status: :created, location: @motoristum }\n else\n format.html { render :new }\n format.json { render json: @motoristum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def createCharities\n\tcharity_list = [\"Direct Relief\", \"Catholic Medical Mission Board\", \"MAP International\", \"United Nations Foundation\", \"The Rotary Foundation of Rotary International\", \"Samaritan's Purse\", \"Institute of International Education\", \"International Rescue Committee\", \"Compassion International\", \"United States Fund for UNICEF\"]\n\tcharity_list.each do |charity|\n\t\tRestClient.post 'http://api.reimaginebanking.com/merchants?key=e0486a76005721ee6d86b140eaea2a40', { \"name\": \"#{charity}\"}.to_json, :content_type => :json, :accept => :json\n\tend\nend",
"def upload\n @mote = mote.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @mote }\n end\n end",
"def create\n @phile = Phile.new(params[:phile])\n\n respond_to do |format|\n if @phile.save\n format.html { redirect_to @phile, notice: 'Phile was successfully created.' }\n format.json { render json: @phile, status: :created, location: @phile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @phile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @immunization = Immunization.new(immunization_params)\n\n respond_to do |format|\n if @immunization.save\n format.html { redirect_to @immunization, notice: 'Immunization was successfully created.' }\n format.json { render :show, status: :created, location: @immunization }\n else\n format.html { render :new }\n format.json { render json: @immunization.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @api_v1_mentorship_interest = Api::V1::MentorshipInterest.new(api_v1_mentorship_interest_params)\n\n respond_to do |format|\n if @api_v1_mentorship_interest.save\n format.html { redirect_to @api_v1_mentorship_interest, notice: 'Mentorship interest was successfully created.' }\n format.json { render :show, status: :created, location: @api_v1_mentorship_interest }\n else\n format.html { render :new }\n format.json { render json: @api_v1_mentorship_interest.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n\n @coral = Coral.find(params[:coral_id])\n @observation = Observation.find(params[:observation_id])\n @area = Area.find(params[:area_id])\n @touch = @area.touches.create(params[:touch])\n\n\n # @touch = Touch.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @touch }\n end\n end",
"def create\n @hair = Hair.new(hair_params)\n\n respond_to do |format|\n if @hair.save\n\n\n format.html { redirect_to @hair, notice: 'Hair was successfully created.' }\n format.json { render :show, status: :created, location: @hair }\n else\n format.html { render :new }\n format.json { render json: @hair.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mariage = Mariage.new(mariage_params)\n\n respond_to do |format|\n if @mariage.save\n format.html { redirect_to @mariage, notice: 'Mariage was successfully created.' }\n format.json { render :show, status: :created, location: @mariage }\n else\n format.html { render :new }\n format.json { render json: @mariage.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @airport = Airport.new(params[:airport])\n\n respond_to do |format|\n if @airport.save\n format.html { redirect_to @airport, notice: 'Airport was successfully created.' }\n format.json { render json: @airport, status: :created, location: @airport }\n else\n format.html { render action: \"new\" }\n format.json { render json: @airport.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @origami = Origami.new(params[:origami])\n\n respond_to do |format|\n if @origami.save\n format.html { redirect_to @origami, notice: 'Origami was successfully created.' }\n format.json { render json: @origami, status: :created, location: @origami }\n else\n format.html { render action: \"new\" }\n format.json { render json: @origami.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @origami = Origami.new(params[:origami])\n\n respond_to do |format|\n if @origami.save\n format.html { redirect_to @origami, notice: 'Origami was successfully created.' }\n format.json { render json: @origami, status: :created, location: @origami }\n else\n format.html { render action: \"new\" }\n format.json { render json: @origami.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @rock_photo = RockPhoto.new(rock_photo_params)\n\n if @rock_photo.save\n render json: @rock_photo, status: :created\n else\n render json: @rock_photo.errors, status: :unprocessable_entity\n end\n end",
"def create\n @omim = Omim.new(omim_params)\n\n respond_to do |format|\n if @omim.save\n format.html { redirect_to @omim, notice: 'Omim was successfully created.' }\n format.json { render :show, status: :created, location: @omim }\n else\n format.html { render :new }\n format.json { render json: @omim.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @tiezi = Tiezi.new(params[:tiezi])\n\n respond_to do |format|\n if @tiezi.save\n format.html { redirect_to @tiezi, notice: 'Tiezi was successfully created.' }\n format.json { render json: @tiezi, status: :created, location: @tiezi }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tiezi.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mini_map_road = MiniMapRoad.new(params[:mini_map_road])\n\n respond_to do |format|\n if @mini_map_road.save\n format.html { redirect_to @mini_map_road, notice: 'Mini map road was successfully created.' }\n format.json { render json: @mini_map_road, status: :created, location: @mini_map_road }\n else\n format.html { render action: \"new\" }\n format.json { render json: @mini_map_road.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mario = Mario.new(mario_params)\n\n respond_to do |format|\n if @mario.save\n format.html { redirect_to @mario, notice: 'Mario was successfully created.' }\n format.json { render :show, status: :created, location: @mario }\n else\n format.html { render :new }\n format.json { render json: @mario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @magictown = Magictown.new(magictown_params)\n\n respond_to do |format|\n if @magictown.save\n format.html { redirect_to @magictown, notice: 'Magictown was successfully created.' }\n format.json { render :show, status: :created, location: @magictown }\n else\n format.html { render :new }\n format.json { render json: @magictown.errors, status: :unprocessable_entity }\n end\n end \n end",
"def create\n @monnaie = Monnaie.new(params[:monnaie])\n\n respond_to do |format|\n if @monnaie.save\n format.html { redirect_to @monnaie, notice: 'Monnaie was successfully created.' }\n format.json { render json: @monnaie, status: :created, location: @monnaie }\n else\n format.html { render action: \"new\" }\n format.json { render json: @monnaie.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @automovile = Automovile.new(automovile_params)\n\n respond_to do |format|\n if @automovile.save\n format.html { redirect_to @automovile, notice: \"Automovile was successfully created.\" }\n format.json { render :show, status: :created, location: @automovile }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @automovile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @floor_ammenity = Floor::Ammenity.new(floor_ammenity_params)\n\n respond_to do |format|\n if @floor_ammenity.save\n format.html { redirect_to @floor_ammenity, notice: 'Ammenity was successfully created.' }\n format.json { render :show, status: :created, location: @floor_ammenity }\n else\n format.html { render :new }\n format.json { render json: @floor_ammenity.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @imakoko = Imakoko.new(imakoko_params)\n\n respond_to do |format|\n if @imakoko.save\n format.html { redirect_to @imakoko, notice: 'Imakoko was successfully created.' }\n format.json { render :show, status: :created, location: @imakoko }\n else\n format.html { render :new }\n format.json { render json: @imakoko.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n # @observation = Observation.new(params[:observation])\n\n @coral = Coral.find(params[:coral_id])\n @observation = @coral.observations.create(observation_params)\n\n respond_to do |format|\n if @observation.save\n format.html { redirect_to coral_path(@coral), flash: {success: 'The observation was successfully created.' } }\n format.json { render json: @observation, status: :created, location: @observation }\n else\n format.html { redirect_to coral_path(@coral), flash: {danger: \"The observation was NOT created. Please make sure the fieldtrip ID is a number and unique.\" } }\n format.json { render json: @observation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @orbit = Orbit.new(orbit_params)\n\n respond_to do |format|\n if @orbit.save\n format.html { redirect_to @orbit, notice: 'Orbit was successfully created.' }\n format.json { render :show, status: :created, location: @orbit }\n else\n format.html { render :new }\n format.json { render json: @orbit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @agronomiaquimica = Agronomiaquimica.new(params[:agronomiaquimica])\n\n respond_to do |format|\n if @agronomiaquimica.save\n format.html { redirect_to @agronomiaquimica, notice: 'Agronomiaquimica was successfully created.' }\n format.json { render json: @agronomiaquimica, status: :created, location: @agronomiaquimica }\n else\n format.html { render action: \"new\" }\n format.json { render json: @agronomiaquimica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @isoform = Isoform.new(params[:isoform])\n\n respond_to do |format|\n if @isoform.save\n format.html { redirect_to @isoform, notice: 'Isoform was successfully created.' }\n format.json { render json: @isoform, status: :created, location: @isoform }\n else\n format.html { render action: \"new\" }\n format.json { render json: @isoform.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @asama_tanim = AsamaTanim.new(asama_tanim_params)\n\n respond_to do |format|\n if @asama_tanim.save\n format.html { redirect_to @asama_tanim, notice: 'Asama tanim was successfully created.' }\n format.json { render :show, status: :created, location: @asama_tanim }\n else\n format.html { render :new }\n format.json { render json: @asama_tanim.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @shot = Shot.new(shot_params)\n @shot.save\n respond_with @shot\n end",
"def new\n @airlin = Airlin.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @airlin }\n end\n end",
"def create\n @magzine = Magzine.new(params[:magzine])\n\n respond_to do |format|\n if @magzine.save\n format.html { redirect_to @magzine, notice: 'Magzine was successfully created.' }\n format.json { render json: @magzine, status: :created, location: @magzine }\n else\n format.html { render action: \"new\" }\n format.json { render json: @magzine.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @maturi = Maturi.new(maturi_params)\n\n respond_to do |format|\n if @maturi.save\n format.html { redirect_to @maturi, notice: 'Maturi was successfully created.' }\n format.json { render :show, status: :created, location: @maturi }\n else\n format.html { render :new }\n format.json { render json: @maturi.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @materia = Materia.new(params[:materia])\n\n if @materia.save\n render json: @materia, status: :created, location: @materia\n else\n render json: @materia.errors, status: :unprocessable_entity\n end\n end",
"def create\n origin = params[:fare][:origin]\n destination = params[:fare][:destination]\n\n \tuber = calculate_uber(origin, destination)\n lyft = calculate_lyft(origin, destination)\n\n if uber and lyft\n render json: [\n {\n company: 'uber', \n id: 1, \n price: uber, \n image: '/assets/uber.png'\n },\n {\n company: 'lyft',\n id: 2,\n price: lyft,\n image: '/assets/lyft.png'\n }], status: 200\n else\n render status: 500\n end\n\n end",
"def create\n unless params[\"tags\"].present? or params[\"tags\"].blank?\n tags = params[\"tags\"].each{|k,v| v}\n tags = tags.map{|k,v| v}\n params[\"tags\"] = tags\n end\n @anime = Anime.new(anime_params)\n if @anime.save\n render :show, status: :created\n else\n render json: @anime.errors, status: :unprocessable_entity\n end\n end",
"def areas\n @area = Area.new(geo_json: params.to_json)\n if @area.save\n json_response([id: @area.id], :created, :geo_json_recieved)\n else\n json_response(nil, :error, :db_error)\n end\n end",
"def create\n @testmonial = Testmonial.new(testmonial_params)\n\n if @testmonial.save\n render json: @testmonial, status: :created\n else\n render json: @testmonial.errors, status: :unprocessable_entity\n end\n end",
"def new\n @air_crew = AirCrew.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @air_crew }\n end\n end",
"def create\n @atm_machine = AtmMachine.new(atm_machine_params)\n\n respond_to do |format|\n if @atm_machine.save\n format.html { redirect_to @atm_machine, notice: 'Atm machine was successfully created.' }\n format.json { render :show, status: :created, location: @atm_machine }\n else\n format.html { render :new }\n format.json { render json: @atm_machine.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @ice_observation = IceObservation.new(ice_observation_params)\n\n respond_to do |format|\n if @ice_observation.save\n format.html { redirect_to @ice_observation, notice: 'Ice observation was successfully created.' }\n format.json { render :show, status: :created, location: @ice_observation }\n else\n format.html { render :new }\n format.json { render json: @ice_observation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @missionmaker = Missionmaker.new(params[:missionmaker])\n\n respond_to do |format|\n if @missionmaker.save\n format.html { redirect_to @missionmaker, notice: 'Missionmaker was successfully created.' }\n format.json { render json: @missionmaker, status: :created, location: @missionmaker }\n else\n format.html { render action: \"new\" }\n format.json { render json: @missionmaker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @equipment_tire = EquipmentTire.new(equipment_tire_params)\n\n respond_to do |format|\n if @equipment_tire.save\n format.html { redirect_to @equipment_tire, notice: 'Equipment tire was successfully created.' }\n format.json { render :show, status: :created, location: @equipment_tire }\n else\n format.html { render :new }\n format.json { render json: @equipment_tire.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @airport = Airport.new(airport_params)\n\n respond_to do |format|\n if @airport.save\n format.html { redirect_to @airport, notice: 'Airport was successfully created.' }\n format.json { render action: 'show', status: :created, location: @airport }\n else\n format.html { render action: 'new' }\n format.json { render json: @airport.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @m_oil = MOil.new(params[:m_oil])\n\n respond_to do |format|\n if @m_oil.save\n #format.html { redirect_to @m_oil, notice: '登録されました。' }\n format.html { redirect_to :controller => \"m_oils\", :action => \"index\" }\n #format.html { redirect_to @m_oil }\n format.json { render json: @m_oil, status: :created, location: @m_oil }\n else\n format.html { render action: \"new\" }\n format.json { render json: @m_oil.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @capture = Capture.new(capture_params)\n @capture.user = current_user\n\n if @capture.save\n render json: @capture, status: :created\n else\n render json: @capture.errors, status: :unprocessable_entity\n end\n ensure\n clean_tempfile\n end",
"def create\n # Read the Matches from the JSON Object\n data = params[:matches]\n matches = data.to_a\n\n MatchCreatorJob.perform_later(matches: matches)\n\n render json: {}, status: :ok\n\n end",
"def create\n @armazena = Armazena.new(armazena_params)\n\n respond_to do |format|\n if @armazena.save\n format.html { redirect_to @armazena, notice: 'Armazena was successfully created.' }\n format.json { render :show, status: :created, location: @armazena }\n else\n format.html { render :new }\n format.json { render json: @armazena.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @tile = Tile.new(params[:tile])\n\n respond_to do |format|\n if @tile.save\n format.html { redirect_to @tile, notice: 'Tile was successfully created.' }\n format.json { render json: @tile, status: :created, location: @tile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mohr = Mohr.new(mohr_params)\n\n respond_to do |format|\n if @mohr.save\n format.html { redirect_to @mohr, notice: 'Mohr was successfully created.' }\n format.json { render :show, status: :created, location: @mohr }\n else\n format.html { render :new }\n format.json { render json: @mohr.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @aki = Aki.new(aki_params)\n\n respond_to do |format|\n if @aki.save\n format.html { redirect_to @aki, notice: 'Aki was successfully created.' }\n format.json { render :show, status: :created, location: @aki }\n else\n format.html { render :new }\n format.json { render json: @aki.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @rozmiar = Rozmiar.new(rozmiar_params)\n\n respond_to do |format|\n if @rozmiar.save\n format.html { redirect_to @rozmiar, notice: 'Rozmiar was successfully created.' }\n format.json { render :show, status: :created, location: @rozmiar }\n else\n format.html { render :new }\n format.json { render json: @rozmiar.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @raindrop = Raindrop.new(raindrop_params)\n\n respond_to do |format|\n if @raindrop.save\n format.html { redirect_to @raindrop, notice: 'Raindrop was successfully created.' }\n format.json { render :show, status: :created, location: @raindrop }\n else\n format.html { render :new }\n format.json { render json: @raindrop.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @jewelrymetal = Jewelrymetal.new(jewelrymetal_params)\n\n respond_to do |format|\n if @jewelrymetal.save\n format.html { redirect_to @jewelrymetal, notice: 'Jewelrymetal was successfully created.' }\n format.json { render :show, status: :created, location: @jewelrymetal }\n else\n format.html { render :new }\n format.json { render json: @jewelrymetal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @air_qualities = AirQuality.all\n\n render json: @air_qualities\n end",
"def create\n @micorpost = Micorpost.new(params[:micorpost])\n\n respond_to do |format|\n if @micorpost.save\n format.html { redirect_to @micorpost, notice: 'Micorpost was successfully created.' }\n format.json { render json: @micorpost, status: :created, location: @micorpost }\n else\n format.html { render action: \"new\" }\n format.json { render json: @micorpost.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @midia = Midia.new(midia_params)\n\n respond_to do |format|\n if @midia.save\n format.html { redirect_to @midia, notice: 'Um novo tipo de mídia foi criado com sucesso.' }\n format.json { render json: @midia, status: :created, location: @midia }\n else\n format.html { render action: \"new\" }\n format.json { render json: @midia.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n\n @coral = Coral.find(params[:coral_id])\n @observation = Observation.find(params[:observation_id])\n @area = Area.find(params[:area_id])\n\n @touches = @area.touches.find(params[:area_id])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @touches }\n end\n end",
"def create\n respond_to do |format|\n if @media_interest.save\n format.html { redirect_to @media_interest, :notice => 'Интересот на медиумот е успешно додаден.' }\n format.json { render :json => @media_interest, :status => :created, :location => @media_interest }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @media_interest.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def submit_form_2122\n validate_json_schema\n\n power_of_attorney = ClaimsApi::PowerOfAttorney.find_using_identifier_and_source(header_md5: header_md5,\n source_name: source_name)\n unless power_of_attorney&.status&.in?(%w[submitted pending])\n power_of_attorney = ClaimsApi::PowerOfAttorney.create(\n status: ClaimsApi::PowerOfAttorney::PENDING,\n auth_headers: auth_headers,\n form_data: form_attributes,\n source_data: source_data,\n header_md5: header_md5\n )\n\n unless power_of_attorney.persisted?\n power_of_attorney = ClaimsApi::PowerOfAttorney.find_by(md5: power_of_attorney.md5)\n end\n\n power_of_attorney.save!\n end\n\n ClaimsApi::PoaUpdater.perform_async(power_of_attorney.id)\n\n render json: power_of_attorney, serializer: ClaimsApi::PowerOfAttorneySerializer\n end",
"def create\n @toy_zone = ToyZone.new(params[:toy_zone])\n\n respond_to do |format|\n if @toy_zone.save\n format.html { redirect_to @toy_zone, :notice => 'Toy zone was successfully created.' }\n format.json { render :json => @toy_zone, :status => :created, :location => @toy_zone }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @toy_zone.errors, :status => :unprocessable_entity }\n end\n end\n end"
] | [
"0.6157518",
"0.6023888",
"0.59428394",
"0.5910758",
"0.5841418",
"0.57893306",
"0.57763255",
"0.5775427",
"0.57316273",
"0.5690711",
"0.56655085",
"0.5650385",
"0.5640944",
"0.56387323",
"0.5595094",
"0.5562408",
"0.555145",
"0.55506915",
"0.5550431",
"0.553902",
"0.55364805",
"0.5507677",
"0.55039716",
"0.5490579",
"0.54795164",
"0.54348767",
"0.54265743",
"0.5419942",
"0.5414127",
"0.54045033",
"0.5396375",
"0.5392352",
"0.53799355",
"0.53737473",
"0.5367686",
"0.53653437",
"0.533736",
"0.53336483",
"0.5321078",
"0.5316289",
"0.5315148",
"0.53054374",
"0.5294672",
"0.5292976",
"0.5289261",
"0.5286018",
"0.5284579",
"0.52785677",
"0.5278399",
"0.5277012",
"0.5275999",
"0.5272562",
"0.5272562",
"0.5269867",
"0.5263029",
"0.52585644",
"0.5258528",
"0.52546316",
"0.52526516",
"0.5246562",
"0.5244782",
"0.5238039",
"0.5234945",
"0.5232451",
"0.52234435",
"0.5222678",
"0.5218773",
"0.5210515",
"0.5205797",
"0.51998794",
"0.51988333",
"0.5188468",
"0.51882017",
"0.5187358",
"0.51862466",
"0.5179924",
"0.5172961",
"0.5166546",
"0.51637214",
"0.5160497",
"0.5158182",
"0.51570827",
"0.51526475",
"0.5151098",
"0.5149823",
"0.51485646",
"0.5145399",
"0.5143171",
"0.5142148",
"0.5141086",
"0.5139871",
"0.51381165",
"0.5137485",
"0.5136692",
"0.5134741",
"0.51339144",
"0.5133342",
"0.5132432",
"0.5126884",
"0.5122646"
] | 0.7118669 | 0 |
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",
"def actualizacion \n fiesta.update (params[:id]) \n render json: fiesta\n end",
"def update\n @impressum = Impressum.find(params[:id])\n\n respond_to do |format|\n if @impressum.update_attributes(params[:impressum])\n format.html { redirect_to impressums_url, notice: 'Impressum was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @impressum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n record = Asset.find(params[:id])\n record.update_attributes(params[:record])\n \n respond_to do |format|\n format.html\n format.json {\n render json: {}\n }\n end\n end",
"def update\n @alumno = Alumno.find(params[:id])\n\n respond_to do |format|\n if @alumno.update_attributes(params[:alumno])\n head :no_content\n else\n render json: @alumno.errors, status: :unprocessable_entity\n end\n end\n end",
"def update\n @ore = Ore.find(params[:id])\n \n respond_to do |format|\n if @ore.update_attributes(params[:ore])\n format.html { redirect_to @ore, notice: 'Ore was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ore.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @wi_mn_d_ave_t_air.update(wi_mn_d_ave_t_air_params)\n format.html { redirect_to @wi_mn_d_ave_t_air, notice: 'Wi mn d ave 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_ave_t_air.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @missionmaker = Missionmaker.find(params[:id])\n\n respond_to do |format|\n if @missionmaker.update_attributes(params[:missionmaker])\n format.html { redirect_to @missionmaker, notice: 'Missionmaker was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @missionmaker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @gommi.update(gommi_params)\n format.html { redirect_to @gommi, notice: 'Gommi was successfully updated.' }\n format.json { render :show, status: :ok, location: @gommi }\n else\n format.html { render :edit }\n format.json { render json: @gommi.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @shot = Shot.find(params[:id])\n\n if @shot.update(shot_params)\n head :no_content\n else\n render json: @shot.errors, status: :unprocessable_entity\n end\n end",
"def jsonapi_update!(attributes)\n assign_jsonapi_attributes(attributes)\n save!\n end",
"def update\n if @airline.update(airline_params)\n json_response(@airline.decorate.as_json(airplanes_details: true),\n :ok)\n else\n json_response(@airline.errors, :unprocessable_entity)\n end\n end",
"def update\n respond_to do |format|\n if @api_v1_initiative_update.update(api_v1_initiative_update_params)\n format.html { redirect_to @api_v1_initiative_update, notice: 'Initiative update was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative_update }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative_update.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @articulo = Articulo.find(params[:id])\n\n respond_to do |format|\n if @articulo.update_attributes(params[:articulo])\n format.html { redirect_to @articulo, notice: 'Articulo was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @articulo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mystic.update(mystic_params)\n format.html { redirect_to @mystic, notice: 'Mystic was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mystic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @moussaillon.update(moussaillon_params)\n format.html { redirect_to @moussaillon, notice: 'Moussaillon was successfully updated.' }\n format.json { render :show, status: :ok, location: @moussaillon }\n else\n format.html { render :edit }\n format.json { render json: @moussaillon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @icome = Icome.find(params[:id])\n\n respond_to do |format|\n if @icome.update_attributes(params[:icome])\n format.html { redirect_to @icome, notice: 'Icome was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @icome.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @kolegiji = Kolegiji.find(params[:id])\n\n respond_to do |format|\n if @kolegiji.update_attributes(params[:kolegiji])\n format.html { redirect_to @kolegiji, notice: 'Kolegiji was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @kolegiji.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mini_map_road = MiniMapRoad.find(params[:id])\n\n respond_to do |format|\n if @mini_map_road.update_attributes(params[:mini_map_road])\n format.html { redirect_to @mini_map_road, notice: 'Mini map road was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mini_map_road.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @metum = Metum.find(params[:id])\n\n respond_to do |format|\n if @metum.update_attributes(params[:metum])\n format.html { redirect_to @metum, notice: 'Metum was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @metum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n trip = Trip.find_by_id(params[:trip_id])\n trip.title = params[:title]\n trip.city = params[:city]\n trip.state = params[:state]\n trip.country = params[:country]\n trip.start_date = params[:start_date]\n trip.end_date = params[:end_date]\n trip.description = params[:description]\n trip.link = params[:link]\n if params[:photo_base]\n trip.photo = params[:photo_base]\n end\n trip.save!\n render json: trip\n end",
"def update\n @monkey = Monkey.find(params[:id])\n\n respond_to do |format|\n if @monkey.update_attributes(params[:monkey])\n format.html { redirect_to @monkey, notice: 'Monkey was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @monkey.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n render json: Company.update(params[\"id\"], params[\"company\"])\n end",
"def update(attrs, path=nil)\n resp = api_client.put(path || url, JSON.dump(attrs))\n refresh(JSON.load(resp.body))\n end",
"def update\n respond_to do |format|\n if @mohr.update(mohr_params)\n format.html { redirect_to @mohr, notice: 'Mohr was successfully updated.' }\n format.json { render :show, status: :ok, location: @mohr }\n else\n format.html { render :edit }\n format.json { render json: @mohr.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @animal = Animal.find(params[:id])\n @species = ['Lion', 'Koala', 'Panda']\n @zoo = Zoo.find(params[:zoo_id])\n\n respond_to do |format|\n\n if @animal.update_attributes(params[:animal])\n format.html { redirect_to zoo_animal_path(params[:zoo_id],@animal.id),\n notice: 'animal was successfully updated.' }\n format.json { head :no_content }\n else\n\n format.html { render action: \"edit\"}\n format.json { render json: @animal.errors,\n status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @jewelrymetal.update(jewelrymetal_params)\n format.html { redirect_to @jewelrymetal, notice: 'Jewelrymetal was successfully updated.' }\n format.json { render :show, status: :ok, location: @jewelrymetal }\n else\n format.html { render :edit }\n format.json { render json: @jewelrymetal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @hoge = Hoge.find(params[:id])\n\n respond_to do |format|\n if @hoge.update_attributes(params[:hoge])\n format.html { redirect_to @hoge, notice: 'Hoge was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hoge.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mou.update(mou_params)\n format.html { redirect_to @mou, notice: 'Mou was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mou.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mugshot = Mugshot.find(params[:id])\n\n respond_to do |format|\n if @mugshot.update_attributes(params[:mugshot])\n format.html { redirect_to @mugshot, notice: 'Mugshot was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mugshot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mario.update(mario_params)\n format.html { redirect_to @mario, notice: 'Mario was successfully updated.' }\n format.json { render :show, status: :ok, location: @mario }\n else\n format.html { render :edit }\n format.json { render json: @mario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @premio = Premio.find(params[:id])\n\n respond_to do |format|\n if @premio.update_attributes(params[:premio])\n format.html { redirect_to @premio, :notice => 'Premio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @premio.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @shot = Shot.find(params[:id])\n\n respond_to do |format|\n if @shot.update_attributes(params[:shot])\n format.html { redirect_to @shot, notice: 'Shot was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @shot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @isoform = Isoform.find(params[:id])\n\n respond_to do |format|\n if @isoform.update_attributes(params[:isoform])\n format.html { redirect_to @isoform, notice: 'Isoform was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @isoform.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\r\n @theoretical_part = TheoreticalPart.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @theoretical_part.update_attributes(params[:theoretical_part])\r\n format.html { redirect_to @theoretical_part, notice: 'Theoretical part was successfully updated.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: \"edit\" }\r\n format.json { render json: @theoretical_part.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def update\n respond_to do |format|\n if @micro_area.update(micro_area_params)\n format.html { redirect_to @micro_area, flash: { success: \"Micro Área atualizada com sucesso!\" } }\n format.json { render :show, status: :ok, location: @micro_area }\n else\n format.html { render :edit }\n format.json { render json: @micro_area.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @iot.update(iot_params)\n format.html { redirect_to @iot, notice: 'Iot was successfully updated.' }\n format.json { render :show, status: :ok, location: @iot }\n else\n format.html { render :edit }\n format.json { render json: @iot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @magissue = Magissue.find(params[:id])\n\n respond_to do |format|\n if @magissue.update_attributes(params[:magissue])\n format.html { redirect_to @magissue, notice: 'Magazine issue was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @magissue.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @tiezi = Tiezi.find(params[:id])\n\n respond_to do |format|\n if @tiezi.update_attributes(params[:tiezi])\n format.html { redirect_to @tiezi, notice: 'Tiezi was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @tiezi.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @formulary = Formulary.find(params[:id])\n\n respond_to do |format|\n if @formulary.update_attributes(params[:formulary])\n format.html { redirect_to @formulary, notice: 'Formulario actualizado exitosamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @formulary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n animal = Animal.find(params[:id])\n\n if validate_params(animal_params)\n animal.update(animal_params)\n render json: animal, status: 200, location: [:api, animal]\n else\n render json: { errors: animal.errors }, status: 422\n end\n end",
"def update\n @intermediary = Intermediary.find(params[:id])\n\n respond_to do |format|\n if @intermediary.update_attributes(params[:intermediary])\n format.html { redirect_to @intermediary, notice: 'Intermediary was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @intermediary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @bowl = Bowl.find(params[:id])\n \n # set bowl modify time\n @bowl.modified = Time.now\n \n respond_to do |format|\n if @bowl.update_attributes(params[:bowl])\n \n Rails.logger.info \"Updating Bowl Contents\"\n \n # remove all contents for this bowl and add new\n @bowl.contents.delete_all(\"bowl_id=\" + @bowl.id)\n \n params.keys.each do |param|\n if param.start_with?(\"input_\") and (params[param] != \"\") \n @bowl.contents.create(:bowl_id => @bowl.id, :dryfruit_id => param[6, 2], :quantity => params[param]) \n end\n end\n\n format.html { redirect_to bowls_path, :notice => 'Bowl was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @bowl.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @autore = Autore.find(params[:id])\n\n respond_to do |format|\n if @autore.update_attributes(params[:autore])\n format.html { redirect_to @autore, notice: 'Autore was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @autore.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @areco = Areco.find(params[:id])\n\n respond_to do |format|\n if @areco.update_attributes(params[:areco])\n format.html { redirect_to @areco, notice: 'Areco was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @areco.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @animai.update(animai_params)\n format.html { redirect_to @animai, notice: 'Animai was successfully updated.' }\n format.json { render :show, status: :ok, location: @animai }\n else\n format.html { render :edit }\n format.json { render json: @animai.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @fluxomatricula = Fluxomatricula.find(params[:id])\n\n respond_to do |format|\n if @fluxomatricula.update_attributes(params[:fluxomatricula])\n format.html { redirect_to @fluxomatricula, notice: 'Fluxomatricula was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fluxomatricula.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @formulary.update(formulary_params)\n format.html { redirect_to formularies_url, alert: I18n.t('activerecord.models.formulary') + I18n.t('helpers_locale.models.updated') }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @formulary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @vehicle_army.update(vehicle_army_params)\n format.html { redirect_to @vehicle_army, notice: (t 'vehicle_armies.title')+(t 'actions.updated') }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @vehicle_army.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @koti = Koti.find(params[:id])\n\n respond_to do |format|\n if @koti.update_attributes(params[:koti])\n format.html { redirect_to @koti, notice: 'Koti was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @koti.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @apoio.update(apoio_params)\n format.html { redirect_to @apoio, notice: 'Apoio was successfully updated.' }\n format.json { render :show, status: :ok, location: @apoio }\n else\n format.html { render :edit }\n format.json { render json: @apoio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(url, data)\n RestClient.put url, data, :content_type => :json\nend",
"def update\n @premio = Premio.find(params[:id])\n\n respond_to do |format|\n if @premio.update_attributes(params[:premio])\n format.html { redirect_to @premio, notice: 'Premio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @premio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @articulo = Articulo.find(params[:id])\n\n respond_to do |format|\n if @articulo.update_attributes(params[:articulo])\n format.html { redirect_to @articulo, notice: 'Articulo se ha actualizado correctamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @articulo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @wing.update(wing_params)\n @wing.floors.each { |f| f.touch }\n format.html { redirect_to @wing, notice: t('.update_ok', item: @wing.name) }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @wing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @my_ministry = MyMinistry.find(params[:id])\n\n respond_to do |format|\n if @my_ministry.update_attributes(params[:my_ministry])\n format.html { redirect_to @my_ministry, notice: 'My ministry was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @my_ministry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @testmonial = Testmonial.find(params[:id])\n\n if @testmonial.update(testmonial_params)\n head :no_content\n else\n render json: @testmonial.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @automovile.update(automovile_params)\n format.html { redirect_to @automovile, notice: \"Automovile was successfully updated.\" }\n format.json { render :show, status: :ok, location: @automovile }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @automovile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @kata.update(kata_params)\n format.html { redirect_to @kata, notice: 'Kata was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @kata.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @homily.update(homily_params)\n \n format.html { redirect_to @homily, notice: 'Homily was successfully updated.' }\n format.json { render :show, status: :ok, location: @homily }\n else\n format.html { render :edit }\n format.json { render json: @homily.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @specie = Specie.find(params[:id])\n\n respond_to do |format|\n if @specie.update_attributes(params[:specie])\n format.html { redirect_to @specie, notice: 'Specie was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @specie.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @imovel.update(imovel_params)\n format.html { redirect_to imovel_path(@imovel), notice: 'Imóvel atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: @imovel }\n else\n format.html { render :edit }\n format.json { render json: @imovel.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @osoba = Osoba.find(params[:id])\n\n if @osoba.update(params[:osoba])\n head :no_content\n else\n render json: @osoba.errors, status: :unprocessable_entity\n end\n end",
"def update\n @aroma = Aroma.find(params[:id])\n\n respond_to do |format|\n if @aroma.update_attributes(params[:aroma])\n format.html { redirect_to @aroma, notice: 'Aroma was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @aroma.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @orbit.update(orbit_params)\n format.html { redirect_to @orbit, notice: 'Orbit was successfully updated.' }\n format.json { render :show, status: :ok, location: @orbit }\n else\n format.html { render :edit }\n format.json { render json: @orbit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n # { clinic: {id: references, \"license_id\"=>nil, \"name\"=>string } }\n \n if @clinic.update_attributes(params[:clinic].except(:api_license_id))\n head :no_content\n else\n render json: clinic.errors.full_messages, status: :unprocessable_entity\n end\n end",
"def update\n @jamaat = Jamaat.find(params[:id])\n\n respond_to do |format|\n if @jamaat.update_attributes(params[:jamaat])\n format.html { redirect_to @jamaat, notice: 'Jamaat was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @jamaat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n photo_params = params[:photo].clone\n if photo_params[:retakeable]\n photo_params[:retakeable] = %(yes true 1).include?(photo_params[:retakeable].to_s.downcase)\n photo_params[:retakeable] = nil if params[:photo][:retakeable] == 'unknown'\n end\n if photo_params[:accessibility]\n photo_params[:accessibility] = nil if params[:photo][:accessibility] == 'unknown'\n end\n respond_to do |format|\n if @photo.update_attributes(photo_params)\n format.html { redirect_to @photo, notice: 'Photo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @touch = Touch.find(params[:id])\n\n respond_to do |format|\n if @touch.update_attributes(touch_params)\n format.html { redirect_to coral_observation_area_path(@touch.area.observation.coral, @touch.area.observation, @touch.area), notice: 'Touch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @touch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @geographic_item.update(geographic_item_params)\n format.html { redirect_to @geographic_item.metamorphosize, notice: 'Geographic item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @geographic_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n render json: Alien.update(params[\"id\"], params[\"alien\"])\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.5896065",
"0.5894697",
"0.5893892",
"0.5889574",
"0.58779013",
"0.58675736",
"0.5865632",
"0.5862321",
"0.58607554",
"0.5850567",
"0.5847947",
"0.58464974",
"0.5841165",
"0.5840407",
"0.58372045",
"0.5833114",
"0.5829188",
"0.5827574",
"0.5826843",
"0.5826522",
"0.58224124",
"0.5820245",
"0.5819037",
"0.58181435",
"0.5816014",
"0.58157533",
"0.5813465",
"0.5811158",
"0.58061653",
"0.5805238",
"0.58012",
"0.57999355",
"0.5799378",
"0.57968885",
"0.5795593",
"0.57925034",
"0.57918596",
"0.5790757",
"0.5788384",
"0.5786745",
"0.5781401",
"0.57800865",
"0.5780007",
"0.5777023",
"0.5776265",
"0.57745814",
"0.5772551",
"0.5770147",
"0.5770114",
"0.57682616",
"0.5766807",
"0.5766292",
"0.57647175",
"0.5763313",
"0.57632804",
"0.576061",
"0.5757981",
"0.57578844",
"0.5756234",
"0.57560617",
"0.5750772",
"0.57483476",
"0.574708",
"0.5746577",
"0.57465476",
"0.5743145",
"0.5741425",
"0.5741129",
"0.57407844",
"0.57382756"
] | 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",
"def destroy\n return if new_record?\n \n @api.delete \"/items/#{shortcode_url}.json\"\n end",
"def destroy\n @uchronia = Uchronia.find(params[:id])\n @uchronia.destroy\n\n respond_to do |format|\n format.html { redirect_to uchronias_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @hoge = Hoge.find(params[:id])\n @hoge.destroy\n\n respond_to do |format|\n format.html { redirect_to hoges_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @record = Asset.find(params[:id])\n @record.trash\n respond_to do |format| \n format.json { head :no_content }\n end\n end",
"def destroy\n @malarium.destroy\n respond_to do |format|\n format.html { redirect_to malaria_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @json.destroy\n respond_to do |format|\n format.html { redirect_to jsons_url, notice: 'Json was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @json.destroy\n respond_to do |format|\n format.html { redirect_to jsons_url, notice: 'Json was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @capa = Capa.find(params[:id])\n @capa.destroy\n\n respond_to do |format|\n format.html { redirect_to capas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @humitemp.destroy\n respond_to do |format|\n format.html { redirect_to humitemps_url, notice: 'Humitemp was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @relogio = Relogio.find(params[:id])\n @relogio.destroy\n\n respond_to do |format|\n format.html { redirect_to relogios_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @automovile.destroy\n respond_to do |format|\n format.html { redirect_to automoviles_url, notice: \"Automovile was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @monkey = Monkey.find(params[:id])\n @monkey.destroy\n\n respond_to do |format|\n format.html { redirect_to monkeys_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @autore = Autore.find(params[:id])\n @autore.destroy\n\n respond_to do |format|\n format.html { redirect_to autores_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @rayon = Rayon.find(params[:id])\n @rayon.destroy\n\n respond_to do |format|\n format.html { redirect_to rayons_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @omim.destroy\n respond_to do |format|\n format.html { redirect_to omims_url, notice: 'Omim was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @metum = Metum.find(params[:id])\n @metum.destroy\n\n respond_to do |format|\n format.html { redirect_to meta_url }\n format.json { head :ok }\n end\n end",
"def delete\n render json: Alien.delete(params[\"id\"])\n end",
"def destroy\n @minicurso = Minicurso.find(params[:id])\n @minicurso.destroy\n\n respond_to do |format|\n format.html { redirect_to minicursos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n id = params[:id]\n @physical_rack = PhysicalRack.any_of({_id: id}, {name: id.gsub('-', '.')}).first\n @physical_rack.destroy\n\n respond_to do |format|\n format.html { redirect_to physical_racks_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @manga = Manga.find(params[:id])\n @manga.destroy\n\n respond_to do |format|\n format.html { redirect_to mangas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @magzine = Magzine.find(params[:id])\n @magzine.destroy\n\n respond_to do |format|\n format.html { redirect_to magzines_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @apologetic.destroy\n respond_to do |format|\n format.html { redirect_to apologetics_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @asthenium.destroy\n respond_to do |format|\n format.html { redirect_to asthenia_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @maturi.destroy\n respond_to do |format|\n format.html { redirect_to maturis_url, notice: 'Maturi was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @story.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @mostsmallroad = Mostsmallroad.find(params[:id])\n @mostsmallroad.destroy\n\n respond_to do |format|\n format.html { redirect_to mostsmallroads_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @phile = Phile.find(params[:id])\n @phile.destroy\n\n respond_to do |format|\n format.html { redirect_to philes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @anything.destroy\n respond_to do |format|\n format.html { redirect_to anythings_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @astronomium.destroy\n respond_to do |format|\n format.html { redirect_to astronomia_url, notice: 'Astronomium was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @gommi.destroy\n respond_to do |format|\n format.html { redirect_to gommis_url, notice: 'Gommi was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n animal = Animal.find(params[:id])\n animal.destroy\n head 204\n end",
"def destroy\n @go_slim = GoSlim.find(params[:id])\n @go_slim.destroy\n\n respond_to do |format|\n format.html { redirect_to go_slims_url }\n format.json { head :no_content }\n end\n end",
"def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend",
"def destroy\n @shot.destroy\n\n head :no_content\n end",
"def destroy\n @monnaie = Monnaie.find(params[:id])\n @monnaie.destroy\n\n respond_to do |format|\n format.html { redirect_to monnaies_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @matome.destroy\n respond_to do |format|\n format.html { redirect_to matomes_url, notice: 'Matome was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @matome.destroy\n respond_to do |format|\n format.html { redirect_to matomes_url, notice: 'Matome was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @unidade_metrica = UnidadeMetrica.find(params[:id])\n @unidade_metrica.destroy\n\n respond_to do |format|\n format.html { redirect_to unidade_metricas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item1 = LineItem1.find(params[:id])\n @line_item1.destroy\n\n respond_to do |format|\n format.html { redirect_to line_item1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @uginuce.sheep.update status:'na farmi'\n @uginuce.destroy\n respond_to do |format|\n format.html { redirect_to uginuces_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @m1.destroy\n respond_to do |format|\n format.html { redirect_to m1s_url, notice: 'M1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @three.destroy\n respond_to do |format|\n format.html { redirect_to threes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dis_generic_monograph.destroy\n respond_to do |format|\n format.html { redirect_to dis_generic_monographs_url, notice: 'Dis generic monograph was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n # @observation = Observation.find(params[:id])\n # @observation.destroy\n\n @coral = Coral.find(params[:coral_id])\n @observation = @coral.observations.find(params[:id])\n @observation.destroy\n # redirect_to coral_path(@coral)\n \n respond_to do |format|\n format.html { redirect_to coral_path(@coral) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @airlin = Airlin.find(params[:id])\n @airlin.destroy\n\n respond_to do |format|\n format.html { redirect_to airlins_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @miscellaneou.destroy\n respond_to do |format|\n format.html { redirect_to miscellaneous_url, notice: 'Accessory was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @microfilm_reel = MicrofilmReel.find(params[:id])\n @microfilm_reel.destroy\n\n respond_to do |format|\n format.html { redirect_to microfilm_reels_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mata_matum.destroy\n respond_to do |format|\n format.html { redirect_to mata_mata_url, notice: 'Mata matum was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @makrana_marble.destroy\n respond_to do |format|\n format.html { redirect_to makrana_marbles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shot = Shot.find(params[:id])\n @shot.destroy\n\n respond_to do |format|\n format.html { redirect_to shots_url }\n format.json { head :no_content }\n end\n end",
"def delete(path)\n RestClient.delete request_base+path\n end",
"def destroy\n @inspiration.destroy\n render json: @inspiration\n end",
"def destroy\n @animai.destroy\n respond_to do |format|\n format.html { redirect_to animais_url, notice: 'Animai was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n RestClient.delete \"#{REST_API_URI}/contents/#{id}.xml\" \n self\n end",
"def destroy\n @moussaillon.destroy\n respond_to do |format|\n format.html { redirect_to moussaillons_url, notice: 'Moussaillon was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n client=Client.find_by_id(params[:id])\n if client != nil\n if client.destroy\n head 204\n end\n else\n head 404\n end\n end",
"def destroy\n @cow.destroy\n respond_to do |format|\n format.html { redirect_to kine_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @climate = Climate.find(params[:id])\n @climate.destroy\n\n respond_to do |format|\n format.html { redirect_to climates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @skydatum = Skydatum.find(params[:id])\n @skydatum.destroy\n\n respond_to do |format|\n format.html { redirect_to skydata_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @walikela.destroy\n respond_to do |format|\n format.html { redirect_to walikelas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @hive = Hive.find(params[:id])\n @hive.destroy\n\n respond_to do |format|\n format.html { redirect_to hives_url }\n format.json { head :no_content }\n end\n end",
"def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end",
"def destroy\n @ruby.destroy\n respond_to do |format|\n format.html { redirect_to rubies_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mill = Mill.find(params[:id])\n @mill.destroy\n\n respond_to do |format|\n format.html { redirect_to mills_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @farmacium.destroy\n respond_to do |format|\n msg = { :status => \"ok\", :message => \"Eliminado!\" }\n format.json { render :json => msg }\n end\n end",
"def destroy\n @moretinymobtrail = Moretinymobtrail.find(params[:id])\n @moretinymobtrail.destroy\n\n respond_to do |format|\n format.html { redirect_to moretinymobtrails_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @homily.destroy\n respond_to do |format|\n format.html { redirect_to homilies_url, notice: 'Homily was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @monit = Monit.find(params[:id])\n @monit.destroy\n\n respond_to do |format|\n format.html { redirect_to monits_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @remedio = Remedio.find(params[:id])\n @remedio.destroy\n\n respond_to do |format|\n format.html { redirect_to remedios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @photo1 = Photo1.find(params[:id])\n @photo1.destroy\n\n respond_to do |format|\n format.html { redirect_to photo1s_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.6723495",
"0.671838",
"0.67159635",
"0.6714027",
"0.670884",
"0.6707844",
"0.6707844",
"0.67071486",
"0.67028594",
"0.6701431",
"0.67003876",
"0.6690376",
"0.6688668",
"0.6688642",
"0.6683596",
"0.6683209",
"0.66815484",
"0.667989",
"0.6677741",
"0.6674368",
"0.6672831",
"0.66715145",
"0.66714555",
"0.6669094",
"0.6666585",
"0.66652423",
"0.6663464",
"0.66611564",
"0.6659323",
"0.66554636",
"0.6649702",
"0.66494936",
"0.6647937",
"0.6646459",
"0.6643548",
"0.66402155",
"0.66402155",
"0.66397905",
"0.6637093",
"0.66330856",
"0.662756",
"0.66263497",
"0.6623194",
"0.66201955",
"0.6618926",
"0.6618678",
"0.6617014",
"0.6616716",
"0.6613673",
"0.6613309",
"0.66131836",
"0.66130316",
"0.66123146",
"0.66096246",
"0.66096157",
"0.66075385",
"0.66070324",
"0.6599682",
"0.65981877",
"0.65981716",
"0.65973413",
"0.6592326",
"0.6592172",
"0.65918136",
"0.65886253",
"0.65879965",
"0.65869534",
"0.6584727",
"0.65846854",
"0.6582407"
] | 0.72552097 | 0 |
Use callbacks to share common setup or constraints between actions. | def set_air_moisture
@air_moisture = AirMoisture.find(params[:id])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def setup_handler\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def workflow\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def setup\n # override and do something appropriate\n end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def setup\n #implement in subclass;\n end",
"def after_set_callback; end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def save_action; end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def setup(&blk)\n @setup_block = blk\n end",
"def default_action; end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend",
"def call\n setup_context\n super\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end"
] | [
"0.6165094",
"0.60450804",
"0.5944413",
"0.5915806",
"0.58885634",
"0.5835225",
"0.5775847",
"0.5700531",
"0.5700531",
"0.56543404",
"0.56209993",
"0.54238355",
"0.5410386",
"0.5410386",
"0.5410386",
"0.5394892",
"0.5377769",
"0.53559244",
"0.5339896",
"0.53388095",
"0.5330087",
"0.5311993",
"0.5297402",
"0.5296789",
"0.52957207",
"0.52596015",
"0.5245442",
"0.5237084",
"0.5237084",
"0.5237084",
"0.5237084",
"0.5237084",
"0.5235431",
"0.5231888",
"0.5226663",
"0.52220625",
"0.5217086",
"0.52137345",
"0.5208314",
"0.5205469",
"0.5175606",
"0.5174914",
"0.5173361",
"0.51662856",
"0.5161792",
"0.51572216",
"0.5153063",
"0.5152982",
"0.5152632",
"0.51435786",
"0.5139829",
"0.51346594",
"0.511372",
"0.511372",
"0.51136476",
"0.51083213",
"0.5108011",
"0.5091935",
"0.5089297",
"0.5081576",
"0.50807106",
"0.50656676",
"0.50548106",
"0.50537366",
"0.505074",
"0.505074",
"0.5033361",
"0.5025158",
"0.5020441",
"0.5015611",
"0.50142473",
"0.5000281",
"0.50001067",
"0.49989453",
"0.4989465",
"0.4989465",
"0.4985425",
"0.49805096",
"0.49795893",
"0.49783278",
"0.49676263",
"0.49656346",
"0.49579078",
"0.4955427",
"0.49554235",
"0.49536413",
"0.49523768",
"0.49457142",
"0.49433607",
"0.4933641",
"0.49320185",
"0.49265638",
"0.49262375",
"0.49259067",
"0.4922456",
"0.49201223",
"0.49165115",
"0.49158815",
"0.49151883",
"0.49149552",
"0.4914386"
] | 0.0 | -1 |
Never trust parameters from the scary internet, only allow the white list through. | def air_moisture_params
params.require(:air_moisture).permit(:min, :max, :disease_id, :cf)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def allow_params_authentication!; end",
"def allowed_params\n ALLOWED_PARAMS\n end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def param_whitelist\n [:role, :title]\n end",
"def expected_permitted_parameter_names; end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end",
"def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end",
"def valid_params_request?; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end",
"def allowed_params\n params.require(:allowed).permit(:email)\n end",
"def permitted_params\n []\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend",
"def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end",
"def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end",
"def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end",
"def safe_params\n params.require(:user).permit(:name)\n end",
"def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def check_params; true; end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def quote_params\n params.permit!\n end",
"def valid_params?; end",
"def paramunold_params\n params.require(:paramunold).permit!\n end",
"def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend",
"def filtered_parameters; end",
"def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end",
"def filtering_params\n params.permit(:email, :name)\n end",
"def check_params\n true\n end",
"def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend",
"def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end",
"def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end",
"def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end",
"def active_code_params\n params[:active_code].permit\n end",
"def filtering_params\n params.permit(:email)\n end",
"def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end",
"def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end",
"def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end",
"def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end",
"def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end",
"def list_params\n params.permit(:name)\n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end",
"def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end",
"def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end",
"def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end",
"def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def url_whitelist; end",
"def admin_social_network_params\n params.require(:social_network).permit!\n end",
"def filter_params\n params.require(:filters).permit(:letters)\n end",
"def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end",
"def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end",
"def sensitive_params=(params)\n @sensitive_params = params\n end",
"def permit_request_params\n params.permit(:address)\n end",
"def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end",
"def secure_params\n params.require(:location).permit(:name)\n end",
"def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end",
"def question_params\n params.require(:survey_question).permit(question_whitelist)\n end",
"def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end",
"def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end",
"def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end",
"def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end",
"def url_params\n params[:url].permit(:full)\n end",
"def backend_user_params\n params.permit!\n end",
"def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend",
"def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end",
"def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end",
"def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end",
"def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end",
"def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end",
"def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end",
"def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end",
"def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end"
] | [
"0.69792545",
"0.6781151",
"0.67419964",
"0.674013",
"0.6734356",
"0.6591046",
"0.6502396",
"0.6496313",
"0.6480641",
"0.6477825",
"0.64565",
"0.6438387",
"0.63791263",
"0.63740575",
"0.6364131",
"0.63192815",
"0.62991166",
"0.62978333",
"0.6292148",
"0.6290449",
"0.6290076",
"0.62894756",
"0.6283177",
"0.6242471",
"0.62382483",
"0.6217549",
"0.6214457",
"0.6209053",
"0.6193042",
"0.6177802",
"0.6174604",
"0.61714715",
"0.6161512",
"0.6151757",
"0.6150663",
"0.61461",
"0.61213595",
"0.611406",
"0.6106206",
"0.6105114",
"0.6089039",
"0.6081015",
"0.6071004",
"0.60620916",
"0.6019971",
"0.601788",
"0.6011056",
"0.6010898",
"0.6005122",
"0.6005122",
"0.6001556",
"0.6001049",
"0.59943926",
"0.5992201",
"0.59909594",
"0.5990628",
"0.5980841",
"0.59669393",
"0.59589154",
"0.5958826",
"0.5957911",
"0.5957385",
"0.5953072",
"0.59526145",
"0.5943361",
"0.59386164",
"0.59375334",
"0.59375334",
"0.5933856",
"0.59292704",
"0.59254247",
"0.5924164",
"0.59167904",
"0.59088355",
"0.5907542",
"0.59064597",
"0.5906243",
"0.5898226",
"0.589687",
"0.5896091",
"0.5894501",
"0.5894289",
"0.5891739",
"0.58860534",
"0.5882406",
"0.587974",
"0.58738774",
"0.5869024",
"0.58679986",
"0.5867561",
"0.5865932",
"0.5864461",
"0.58639693",
"0.58617616",
"0.5861436",
"0.5860451",
"0.58602303",
"0.5854586",
"0.58537364",
"0.5850427",
"0.5850199"
] | 0.0 | -1 |
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",
"def draw_line; draw_horizontal_line(@draw_y + (line_height / 2) - 1, 2); end",
"def build_leg(line, start, stop)\n trip = []\n until start == stop do\n start += (start < stop) ? 1 : - 1\n trip.push line[start]\n end\n return trip\nend",
"def GenSilkLine(x1, y1, x2, y2)\n thickness = GetDim('silkwidth')\n PcbElementLine(x1, y1, x2, y2, thickness)\nend",
"def stops_between_stations (start_line,start_staion ,end_line, end_station )\n \n lines{\n red =[ 'South Station','Park Street', 'Kendall','Central','Harvard', 'Porter', 'Davis', 'Alewife']\ngreen = ['Government Center','Park Street','Boylston','Arlington','Copley','Hynes','Kenmore']\norange =['North Station','Haymarket','Park Street','State','Downtown Crossing','Chinatown','Back Bay','Forest Hills']\n }\n \n\n # return \"You have #{start_station - red_line.index(\"South Station\")} to go \" \n if start_line == end_line # Both dests are in in same line \n return start_line.index(start_staion) - end_line.index(stop_station) # i'd use abs = absloute here to avoid negative values \n\n else puts 'I have no clue what to do here -.-'\n \n end \n \n end",
"def vline x, c, y1 = 0, y2 = w\n line x, y1, x, y2, c\n end",
"def vline x, c, y1 = 0, y2 = w\n line x, y1, x, y2, c\n end",
"def draw_dashed(x_start, y_start, x_end, value, stat_max, stat_min, rotated=false)\n y_interval = @box_size*9\n x_begin = @box_size * 0.7\n stat_interval = stat_max - stat_min\n dash1 = @box_size/5+1\n dash2 = @box_size/2\n dash_array = Array.new\n dash_array << dash1\n dash_array << dash2\n y = ((stat_max-value) / stat_interval) * y_interval\n\t\ty = y_interval - y if rotated\n @canvas.g.translate(x_start, y_start) do |l|\n l.styles(:fill=>'none', :stroke_width=>1, :stroke=>'gray', :fill_opacity=>0.0, :stroke_dasharray=>dash_array)\n l.line(x_begin, y, x_end-x_start, y)\n end\n end",
"def dividing_line; end",
"def line_divider \n puts @header.light_blue\n end",
"def draw_line_markers\n return if @hide_line_markers\n\n # Draw horizontal line markers and annotate with numbers\n number_of_lines = marker_count\n number_of_lines = 1 if number_of_lines == 0\n\n # TODO: Round maximum marker value to a round number like 100, 0.1, 0.5, etc.\n increment = significant(@spread / number_of_lines)\n (0..number_of_lines).each do |index|\n line_diff = (@graph_right - @graph_left) / number_of_lines\n x = @graph_right - (line_diff * index) - 1\n draw_marker_vertical_line(x)\n\n unless @hide_line_numbers\n diff = index - number_of_lines\n marker_label = (BigDecimal(diff.abs.to_s) * BigDecimal(increment.to_s)) + BigDecimal(minimum_value.to_s)\n label = x_axis_label(marker_label, @increment)\n y = @graph_bottom + @label_margin + (labels_caps_height / 2.0)\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_line_markers\n return if @hide_line_markers\n\n @d = @d.stroke_antialias false\n\n if @y_axis_increment.nil?\n # Try to use a number of horizontal lines that will come out even.\n #\n # TODO Do the same for larger numbers...100, 75, 50, 25\n if @marker_count.nil?\n (3..7).each do |lines|\n if @spread % lines == 0.0\n @marker_count = lines\n break\n end\n end\n @marker_count ||= 4\n end\n @increment = (@spread > 0) ? significant(@spread / @marker_count) : 1\n else\n # TODO Make this work for negative values\n @maximum_value = [@maximum_value.ceil, @y_axis_increment].max\n @minimum_value = @minimum_value.floor\n calculate_spread\n\n normalize() # default to false to fix y_axis_increment assignment on line chart\n\n @marker_count = (@spread / @y_axis_increment).to_i\n @increment = @y_axis_increment\n end\n\n (0..@marker_count).each do |index|\n line_diff = (@graph_right - @graph_left) / @marker_count\n x = @graph_right - (line_diff * index) - 1\n @d = @d.fill(@marker_color)\n @d = @d.line(x, @graph_bottom, x, @graph_top)\n diff = index - @marker_count\n marker_label = diff.abs * @increment + @minimum_value\n\n unless @hide_line_numbers\n @d.fill = @font_color\n @d.font = @font if @font\n @d.stroke = 'transparent'\n @d.pointsize = scale_fontsize(@marker_font_size)\n @d.gravity = CenterGravity\n # TODO Center text over line\n @d = @d.annotate_scaled(@base_image,\n 0, 0, # Width of box to draw text in\n x, @graph_bottom + (LABEL_MARGIN * 2.0), # Coordinates of text\n marker_label.to_s, @scale)\n end # unless\n @d = @d.stroke_antialias true\n end\n end",
"def verticalLines\n (0...@width).inject([]) { |arr, column| arr << @modified.column(column) }\n end",
"def show_volume_lines(view, entities)\n # get rays to the 4 corners of the viewing area\n transform = CameraRep.get_transform_from_view(view).inverse\n #length = self.distance_to_back(view)\n #pts = []\n for i in 0..3\n ray = view.pickray(view.corner(i))\n dir = ray[1].transform(transform)\n line = entities.add_cline ORIGIN, dir, \"...\"\n line.start = ORIGIN\n #pts[i] = ORIGIN.offset dir, length\n #entities.add_cline ORIGIN, pts[i], \"...\"\n #if( i > 0 )\n # entities.add_cline pts[i-1], pts[i], \"...\"\n #end\n end\n #entities.add_cline pts[3], pts[0], \"...\"\nend",
"def read_end_stops()\n start_command('F81', false, @status_debug_msg)\n end",
"def print_boundary_line(point1, point2)\n print_times_blank(4)\n print \"#{create_colored_substrings(point1.value)}\"\n print_times_blank(10)\n puts \"#{create_colored_substrings(point2.value)}\"\n nil\n end",
"def how_to_render_lines args\n # Render a horizontal line at the bottom\n args.nokia.lines << { x: 0, y: 0, x2: 83, y2: 0 }\n\n # Render a vertical line at the left\n args.nokia.lines << { x: 0, y: 0, x2: 0, y2: 47 }\n\n # Render a diagonal line starting from the bottom left and going to the top right\n args.nokia.lines << { x: 0, y: 0, x2: 83, y2: 47 }\nend",
"def stop_menu(subway_lines, train)\n\treturn subway_lines[train]\nend",
"def line(length)\r\n puts '-'*length\r\n end",
"def symbol(ds, index, y = 0)\n # Line that always appear\n x = (100 + SPACE) * index\n line(50, 0, 50, 100).translate(x, y)\n # Lines that may or may not appear depending of the digit\n ds.each do |num|\n case num\n when 1\n line(50, 0, 100, 0).translate(x, y) # 1579 -\n when 2\n line(50, 50, 100, 50).translate(x, y) # 289 _\n when 3\n line(50, 0, 100, 50).translate(x, y) # 3 \\\n when 4\n line(50, 50, 100, 0).translate(x, y) # 45 /\n when 5\n line(50, 0, 100, 0).translate(x, y) # 1579 -\n line(50, 50, 100, 0).translate(x, y) # 45 /\n when 6\n line(100, 0, 100, 50).translate(x, y) # 6789 |\n when 7\n line(50, 0, 100, 0).translate(x, y) # 1579 -\n line(100, 0, 100, 50).translate(x, y) # 6789 |\n when 8\n line(100, 0, 100, 50).translate(x, y) # 6789 |\n line(50, 50, 100, 50).translate(x, y) # 289 _\n when 9\n line(50, 0, 100, 0).translate(x, y) # 1579 -\n line(100, 0, 100, 50).translate(x, y) # 6789 |\n line(50, 50, 100, 50).translate(x, y) # 289 _\n when 10\n line(50, 0, 0, 0).translate(x, y) # 1579 -\n when 20\n line(50, 50, 0, 50).translate(x, y) # 289 _\n when 30\n line(50, 0, 0, 50).translate(x, y) # 3 /\n when 40\n line(50, 50, 0, 0).translate(x, y) # 45 \\\n when 50\n line(50, 50, 0, 0).translate(x, y) # 45 \\\n line(50, 0, 0, 0).translate(x, y) # 1579 -\n when 60\n line(0, 50, 0, 0).translate(x, y) # 6789 |\n when 70\n line(0, 50, 0, 0).translate(x, y) # 6789 |\n line(50, 0, 0, 0).translate(x, y) # 1579 -\n when 80\n line(50, 50, 0, 50).translate(x, y) # 289 _\n line(0, 50, 0, 0).translate(x, y) # 6789 |\n when 90\n line(0, 50, 0, 0).translate(x, y) # 6789 |\n line(50, 0, 0, 0).translate(x, y) # 1579 -\n line(50, 50, 0, 50).translate(x, y) # 289 _\n when 100\n line(50, 100, 100, 100).translate(x, y) # 1579 _\n when 200\n line(50, 50, 100, 50).translate(x, y) # 289 -\n when 300\n line(50, 100, 100, 50).translate(x, y) # 3 /\n when 400\n line(50, 50, 100, 100).translate(x, y) # 45 \\\n when 500\n line(50, 50, 100, 100).translate(x, y) # 45 \\\n line(50, 100, 100, 100).translate(x, y) # 1579 _\n when 600\n line(100, 50, 100, 100).translate(x, y) # 6789 |\n when 700\n line(100, 50, 100, 100).translate(x, y) # 6789 |\n line(50, 100, 100, 100).translate(x, y) # 1579 _\n when 800\n line(100, 50, 100, 100).translate(x, y) # 6789 |\n line(50, 50, 100, 50).translate(x, y) # 289 -\n when 900\n line(100, 50, 100, 100).translate(x, y) # 6789 |\n line(50, 100, 100, 100).translate(x, y) # 1579 _\n line(50, 50, 100, 50).translate(x, y) # 289 -\n when 1000\n line(50, 100, 0, 100).translate(x, y) # 1579 _\n when 2000\n line(50, 50, 0, 50).translate(x, y) # 289 -\n when 3000\n line(50, 100, 0, 50).translate(x, y) # 3 \\\n when 4000\n line(50, 50, 0, 100).translate(x, y) # 45 /\n when 5000\n line(50, 50, 0, 100).translate(x, y) # 45 /\n line(50, 100, 0, 100).translate(x, y) # 1579 _\n when 6000\n line(0, 50, 0, 100).translate(x, y) # 6789 |\n when 7000\n line(50, 100, 0, 100).translate(x, y) # 1579 _\n line(0, 50, 0, 100).translate(x, y) # 6789 |\n when 8000\n line(0, 50, 0, 100).translate(x, y) # 6789 |\n line(50, 50, 0, 50).translate(x, y) # 289 -\n when 9000\n line(0, 50, 0, 100).translate(x, y) # 6789 |\n line(50, 100, 0, 100).translate(x, y) # 1579 _\n line(50, 50, 0, 50).translate(x, y) # 289 -\n end\n end\nend",
"def print_separator_line\nline = \"\"\n3.times do\n3.times { line << SEPARATOR[:horizontal] }\nline << SEPARATOR[:cross]\nend\nputs line[0...line.length - 1]\nprint \"\\t\"\nend",
"def draw_eol\n print \"\\r\\e[#{columns - 1}C#{V_SEP}\\n\"\n end",
"def draw\n return if @hidden\n cur_y = @cur_start_y\n @lines.each do |line|\n if cur_y >= (600 - START_Y - FONT_HEIGHT) then\n newline = find_line_length(@lines.shift)\n if newline.length > 1 then\n @lines.unshift(newline[1..-1].join(\" \"))\n else\n if @cur_start_y != START_Y then\n @cur_start_y = START_Y\n else\n @cur_start_y = START_Y + FONT_HEIGHT\n end\n end\n end\n \n line = line[0, @current_pos] if line == @lines.last and !@current\n width = @font.text_width(line)\n if width.to_i >= TEXT_WIDTH then\n # now break down each segment~\n # try to find a word break if possible\n new_lines = find_line_length(line)\n new_lines.each do |l|\n if cur_y >= (600 - START_Y - FONT_HEIGHT) then\n newline = find_line_length(@lines.shift)\n if newline.length > 1 then\n @lines.unshift(newline[1..-1].join(\" \"))\n else\n if @cur_start_y != START_Y then\n @cur_start_y = START_Y\n else\n @cur_start_y = START_Y + FONT_HEIGHT\n end\n end\n end\n \n @font.draw(l, START_X, cur_y, 9)\n cur_y += FONT_HEIGHT\n cur_y += FONT_HEIGHT if l == new_lines.last\n end\n else \n @font.draw(line, START_X, cur_y, 9)\n cur_y += FONT_HEIGHT * 2\n end\n end\n if @current then\n # draw CTC indicator\n img = @ctc[Gosu::milliseconds / 150 % @ctc.size];\n img.draw(720, 520, 10)\n end\n end",
"def spot_legs\n lines = []\n indent = 0\n spacer = @width - @padding\n\n draw_legs(lines, indent, spacer)\n lines\n end",
"def singleTrip (start_station, end_station, line)\n start_index = MTA[line].index(start_station)\n end_index = MTA[line].index(end_station)\n\n if start_index < end_index\n stops = MTA[line][start_index ... end_index]\n num_stops = end_index - start_index\n end\n\n if end_index < start_index\n stops = MTA[line][end_index ... start_index]\n stops = stops.reverse\n num_stops = start_index - end_index\n\n end\n print = \"You must travel through the following stops on the #{line}: #{stops}\"\n # print = \"#{num_stops} in total\"\nend",
"def line_ranges=(_); end",
"def draw_line_markers\n return if @hide_line_markers\n\n\n # have to do this here (AGAIN)... see draw() in this class\n # because this funtion is called before the @radius, @center_x and @center_y are set\n @radius = @graph_height / 2.0\n @center_x = @graph_left + (@graph_width / 2.0)\n @center_y = @graph_top + (@graph_height / 2.0) - 10 # Move graph up a bit\n\n\n # Draw horizontal line markers and annotate with numbers\n @d = @d.stroke(@marker_color)\n @d = @d.stroke_width 1\n\n\n (0..@column_count-1).each do |index|\n rad_pos = index * Math::PI * 2 / @column_count\n\n @d = @d.line(@center_x, @center_y, @center_x + Math::sin(rad_pos) * @radius, @center_y - Math::cos(rad_pos) * @radius)\n\n\n marker_label = labels[index] ? labels[index].to_s : '000'\n\n draw_label(@center_x, @center_y, rad_pos * 360 / (2 * Math::PI), @radius, marker_label)\n end\n end",
"def read_end_stops()\n execute_command('F81', false, @status_debug_msg)\n end",
"def getTripString(line, startStop, endStop) \n lineArray = getLine(line)\n string = \"\" # to save the station \n start_point = lineArray.index(startStop) # save the index of start point\n end_point = lineArray.index(endStop) # save the index of end point\n # p start_point \n # p end_point\n if start_point > end_point\n start_point.downto(end_point) do |j| \n string += \"#{lineArray[j]}, \"\n end\n else\n start_point.upto(end_point) do |j|\n string += \"#{lineArray[j]}, \"\n end \n end \n return string[0...-2] \nend",
"def lineN_stations \n puts \"The list of stations for line N: \"\n puts \"[0] - Time Square\"\n puts \"[1] - 34th\"\n puts \"[2] - 28th\"\n puts \"[3] - 23rd\"\n puts \"[4] - Union Square\"\n puts \"[5] - 8th\"\nend",
"def travel_diff(line1, line2)\n\t\tputs \"You will need to change trains at UNION SQUARE!\"\n\t\tputs \"Board the train at #{$subway_station[$get_on - 1]}\"\n\t\tend_point_diff = line2.index $subway_station[$get_off - 1]\n\t\tstart_point_diff = line2.index $intersect\n\n\t\t### STARTING LINE IS WHICH?\n\t\tif line1 == $line_n\n\t\t\tlist_stops_int(4, line1, line2)\n\t\t\tdirection(start_point_diff, end_point_diff, line2)\n\n\t\telsif line1 == $line_l\n\t\t\tlist_stops_int(2, line1, line2)\n\t\t\tdirection(start_point_diff, end_point_diff, line2)\n\n\t\telsif line1 == $line_6\n\t\t\tlist_stops_int(3, line1, line2)\n\t\t\tdirection(start_point_diff, end_point_diff, line2)\n\t\tend\n\tend",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def line; end",
"def find_stations(si, ei, line) # si is short for start index and ei is short for end index\n if ei >= si\n line_stop_count = ei - si\n passing_stations = line[(si+1)..ei].join(\", \")\n else\n line_stop_count = si - ei\n passing_stations = line[(ei)..(si-1)].reverse.join(\", \")\n end\n return {:num_stops => line_stop_count, :stops => passing_stations}\nend",
"def visible_line_number\n @ev_height\n end",
"def draw_line_markers\n return if @hide_line_markers\n\n increment_scaled = @graph_height.to_f / (@spread / @increment)\n\n # Draw horizontal line markers and annotate with numbers\n (0..marker_count).each do |index|\n y = @graph_top + @graph_height - index.to_f * increment_scaled\n\n line_renderer = Gruff::Renderer::Line.new(renderer, color: @marker_color, shadow_color: @marker_shadow_color)\n line_renderer.render(@graph_left, y, @graph_right, y)\n\n unless @hide_line_numbers\n marker_label = BigDecimal(index.to_s) * BigDecimal(@increment.to_s) + BigDecimal(minimum_value.to_s)\n label = y_axis_label(marker_label, @increment)\n text_renderer = Gruff::Renderer::Text.new(renderer, label, font: @marker_font)\n text_renderer.add_to_render_queue(@graph_left - LABEL_MARGIN, 1.0, 0.0, y, Magick::EastGravity)\n end\n end\n end",
"def vertical_line(options={:start_in => :limit_left, :size => :area_y})\n set RGhost::VerticalLine.new(options)\n end",
"def direction_same_line( line, route )\n journey = route.join(\", \")\n stop_off = route.last\n stop_on = route.first\n\n route.shift\n stops = route.length\n route.pop\n\n if stops >= 1\n puts `clear`\n puts \"-------------------------------------------------------------\"\n puts\n puts \"Your route #{ journey }\"\n puts\n puts \"Take the: #{ line }\" \n puts \"Get on at: #{stop_on}\"\n puts \"Pass through: #{ route.join(\", \") } \"\n puts \"Get off at: #{ stop_off } \"\n puts\n puts \"There are: #{ stops } stops to your destination\"\n puts\n puts \"-------------------------------------------------------------\"\n \n else\n puts \"Your being a dick\"\n puts \"You are getting on at #{stop_off} and getting off at #{stop_off}\"\n end\nend",
"def prevline(distance = 1)\n ConsoleGlitter.escape(\"#{distance}F\")\n end",
"def stops_from_union(station, line)\n\n\tnum_stops = line.index(station) - line.index(\"Union Square\")\n\tnum_stops.abs\nend",
"def good_divider(lines,i)\n above_and_below = lines.rows(0...i)+lines.rows((i+1)..-1)\n segments(lines[i]).all? { |text,range|\n text =~ /^( +|---+)$/ or above_and_below.columns(range).blank?\n }\n end",
"def show_station_lines(show_lines)\n lines = show_lines.map do |station_lines| #iterating over our array\n station_lines.station_lines#name\n end\n puts \"Hello, here are the train line(s) you can take: #{lines.join(\" , \")} line(s).\"\n end",
"def numStops( x , y )\n (x - y).abs\n end",
"def line\n end",
"def line\n end",
"def display_stop_cycles(outname, ops, stamp_columns)\n tab = Array.new(8) { Array.new(12, \"-\") }\n stop_cycle = ops.first.output(outname).collection.get(\"stop_cycle\")\n\n if stop_cycle.present?\n stop_cycle[0].length.times do |cc|\n col = cc+1\n if stamp_columns\n if(stop_cycle[0][cc]>0)\n tab[0][cc] = {content: \"A#{col} cycle #{stop_cycle[0][cc]}\", check: \"true\"}\n (1..stamp_columns - 1).each do |rr|\n row = (rr+\"A\".ord).chr\n tab[rr][cc] = {content: \"cycle #{stop_cycle[0][cc]}\", check: \"false\"} # wells are connected\n end\n end\n else\n stop_cycle.length.times { |rr|\n if(stop_cycle[rr][cc]>0)\n row = (rr+\"A\".ord).chr\n tab[rr][cc] = {content: \"#{row}#{col} cycle #{stop_cycle[rr][cc]}\", check: \"true\"}\n end\n }\n end\n end\n end\n\n return tab\n end",
"def line(x0, y0, x1, y1)\n # clean params\n x0, y0, x1, y1 = x0.to_i, y0.to_i, x1.to_i, y1.to_i\n y0, y1, x0, x1 = y1, y0, x1, x0 if y0>y1\n sx = (dx = x1-x0) < 0 ? -1 : 1 ; dx *= sx ; dy = y1-y0\n\n # special cases\n x0.step(x1,sx) { |x| point x, y0 } and return if dy.zero?\n y0.upto(y1) { |y| point x0, y } and return if dx.zero?\n x0.step(x1,sx) { |x| point x, y0; y0 += 1 } and return if dx==dy\n\n # main loops\n point x0, y0\n\n e_acc = 0\n if dy > dx\n e = (dx << 16) / dy\n y0.upto(y1-1) do\n e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF\n x0 += sx if (e_acc <= e_acc_temp)\n point x0, (y0 += 1), intensity(@color,(w=0xFF-(e_acc >> 8)))\n point x0+sx, y0, intensity(@color,(0xFF-w))\n end\n point x1, y1\n return\n end\n\n e = (dy << 16) / dx\n x0.step(x1-sx,sx) do\n e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF\n y0 += 1 if (e_acc <= e_acc_temp)\n point (x0 += sx), y0, intensity(@color,(w=0xFF-(e_acc >> 8)))\n point x0, y0+1, intensity(@color,(0xFF-w))\n end\n point x1, y1\n end",
"def stops_to(lines, start_stop, end_stop)\n\tstart_line = find_line(lines, start_stop)\n\tend_line = find_line(lines, end_stop)\n\n\tif start_line == end_line # Just calculate the one distance \n\t\treturn line_distance(lines, start_line, start_stop, end_stop)\n\t\n\telse # Calculate distance for each line and direction from US seperately then add\n\t\tfirst_distance = line_distance(lines, start_line, start_stop, \"Union Square\")\n\t\tsecond_distance = line_distance(lines, end_line, \"Union Square\", end_stop)\n\t\treturn first_distance[0] + second_distance[0], first_distance[1] + second_distance[1]\n\tend\nend",
"def stops_to(lines, start_stop, end_stop)\n\tstart_line = find_line(lines, start_stop)\n\tend_line = find_line(lines, end_stop)\n\n\tif start_line == end_line # Just calculate the one distance \n\t\treturn line_distance(lines, start_line, start_stop, end_stop)\n\t\n\telse # Calculate distance for each line and direction from US seperately then add\n\t\tfirst_distance = line_distance(lines, start_line, start_stop, \"Union Square\")\n\t\tsecond_distance = line_distance(lines, end_line, \"Union Square\", end_stop)\n\t\treturn first_distance[0] + second_distance[0], first_distance[1] + second_distance[1]\n\tend\nend",
"def line\n\tputs \"-\" * 100\nend",
"def draw_line(grids, length)\n grid(grids[0], grids[1]).bounding_box() do\n stroke_horizontal_line 0, 470*length, at: 5\n end\n end",
"def whichLine(stop)\n\tif lines[\"n\"].include? 'Times'\n\t\t# puts \"yes\"\n\telse\n\t\t# puts \"no\"\n\tend\nend",
"def lines\n @lines[oy...(oy + bordered_height)] || []\n end",
"def draw_line(index)\n rect = Rect.new(0, 0, 0, 0)\n rect.x += 4\n rect.y += index * WLH\n rect.width = contents.width - 8\n rect.height = WLH\n self.contents.clear_rect(rect)\n self.contents.font.color = normal_color\n self.contents.draw_text(rect, @lines[index])\n end",
"def display_trip(trip, start_line)\n puts \"\\nTrip: \" + Rainbow(\"#{trip[0]}\").green + \" ==> \" + Rainbow(\"#{trip[-1]}\").red\n puts Rainbow(\"********************************\").yellow\n puts Rainbow(\"#{trip.shift}\").green + \": take the \" + Rainbow(\"#{start_line}\").green\n trip[-1] = Rainbow(trip[-1]).red + \": destination reached\"\n puts trip\n puts Rainbow(\"********************************\").yellow\n puts Rainbow(\" Total Stations: #{trip.length} \").black.bg(:white)\n puts \"\\n\\n\"\nend",
"def draw_vertical_stars(start_hash_line, end_hash_line, start_hash_char)\n start_hash_line.upto(end_hash_line) do |line_idx|\n @lines[line_idx][start_hash_char] = STAR_CHAR\n end\n end",
"def linedash(lengths=[10,2], phase=0.0)\n count=lengths.size\n CGContextSetLineDash(@ctx, phase, lengths, count)\n end",
"def open_ended_polyline(arr)\n 0.upto(arr.length - 2) { |i|\n @draw.line(arr[i][0], arr[i][1], arr[i+1][0], arr[i+1][1])\n }\n end"
] | [
"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.55929655",
"0.55839276",
"0.55765694",
"0.55436647",
"0.55291224",
"0.55291224",
"0.55218613",
"0.5512895",
"0.5512032",
"0.5507765",
"0.5502822",
"0.5480503",
"0.54745585",
"0.5456515",
"0.5447297",
"0.5445478",
"0.54331946",
"0.5432745",
"0.542354",
"0.5422275",
"0.5407163",
"0.5406115",
"0.54028046",
"0.53922415",
"0.5372808",
"0.5372517",
"0.5370158",
"0.536498",
"0.5362857",
"0.5355166",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5353339",
"0.5352408",
"0.53515744",
"0.53467894",
"0.5342945",
"0.53346395",
"0.53311086",
"0.53286165",
"0.53180826",
"0.5317079",
"0.53096503",
"0.5306703",
"0.5306703",
"0.5282894",
"0.5277128",
"0.52761936",
"0.52761936",
"0.52708143",
"0.5267993",
"0.5255891",
"0.52485627",
"0.5247392",
"0.52471954",
"0.5242065",
"0.5239563",
"0.5227314"
] | 0.6886917 | 0 |
show total number of stops | def show_total(lines, line1, stops1, line2, stops2)
index1 = []
index2 = []
#get index for first stop
lines.each do |line|
if line[:lines] == line1
index1.push(line[:stops].index(stops1))
if line1 == "f"
index1.push(line[:stops].index("herald_square") + 1)
else
index1.push(line[:stops].index("union_square"))
end
end
end
#get index for second stop
lines.each do |line|
if line[:lines] == line2
index2.push(line[:stops].index(stops2))
if line2 == "f"
index2.push(line[:stops].index("herald_square") + 1)
else
index2.push(line[:stops].index("union_square"))
end
end
end
#calculate number of stops
if index1[0] == index1[1]
index1 = 0
else
index1 = (index1[0] - index1[1]).abs
end
if index2[0] == index2[1]
index2 = 0
else
index2 = (index2[0] - index2[1]).abs
end
puts index1 + index2
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def calculate_stations\n total=($start-$end).abs\n p \"total of stations of your trip is #{total}\"\n end",
"def numStops( x , y )\n (x - y).abs\n end",
"def flight_segment_tally\n all_flights.length\n end",
"def number(bus_stops)\n entries = []\n exits = []\n bus_stops.each { |x| entries << x[0] }\n bus_stops.each { |x| exits << x[1] }\n p entries.inject(&:+) - exits.inject(&:+)\nend",
"def direction_counts\n @direction_counter.each do |direction, count|\n puts \"#{direction.to_s} : #{count}\"\n end\n end",
"def number(bus_stops)\n count = 0\n bus_stops.each { |stop| count += stop[0] -= stop[1] }\n count\nend",
"def getNumCycles()\n return @numCycles\n end",
"def putstops(num)\n\tputs \"Your trip takes #{num} stops!\"\nend",
"def get_num_stops(origin, destination, stops)\n (stops.index(destination) - stops.index(origin)).abs\nend",
"def number(bus_stop)\n people_left = 0\n bus_stop.each do |stop|\n people_left += (stop[0] - stop[1])\n end\n people_left\nend",
"def trip_count\n trips.length\n end",
"def trip_count\n trips.length\n end",
"def trip_count\n trips.length\n end",
"def trip_count\n trips.length\n end",
"def count \n trips.length\n end",
"def total_runs\n return @total_runs\n end",
"def cycle_count\n put('o^')\n get.strip.to_i\n end",
"def total_paths(initial_s)\n reachable_stops(initial_s).count\n end",
"def trips(start, finish, stops1, stops2)\n total_paths = 0\n cycles = all_cycles # all cycles in graph\n (stops1..stops2).each do |stops|\n path, paths = [], []\n visited = [start]\n puts \"\\nSTOPS GOAL = #{stops}\\n\"\n num_paths = trips_dfs(start, finish, stops, visited, path, paths, cycles)\n puts \"\\n--- Total paths for #{stops} stops: #{num_paths}\"\n total_paths += num_paths\n end\n puts \"\\n==> Total paths from #{start} to #{finish}, for #{stops1} to #{stops2} stops: #{total_paths} <==\\n\"\n total_paths\n end",
"def trip_count\n trips.length\n end",
"def number(bus_stops)\n number_passengers = 0\n\n bus_stops.each do |stop|\n number_passengers += stop[0]\n number_passengers -= stop[1]\n end\n number_passengers\nend",
"def length\n return self.stop - self.start + 1\n end",
"def length\n return self.stop - self.start + 1\n end",
"def trip_count()\n self.trips().length()\n end",
"def nofRuns()\n return @runList.size() ;\n end",
"def trip_count\n trips.length\nend",
"def length\r\n return self.stop - self.start + 1\r\n end",
"def count\n run.count\n end",
"def number(bus_stops)\n x = bus_stops.flatten\n ins = x.select.with_index{|_,i| (i+2) % 2 == 0}.inject(:+)\n outs = x.each_slice(2).map(&:last).inject(:+)\n ins - outs\nend",
"def results(stop,start)\n hours = stop.hour - start.hour\n mins = stop.min - start.min\n secs = stop.sec - start.sec\n (mins = mins + 60) && (hours = hours - 1) if mins < 0\n (secs = secs + 60) && (mins = mins - 1) if secs < 0\n puts \"Done in #{hours}:#{mins}:#{secs}\"\n puts \"Got: #{Group.count} groups, #{Category.count} categories, #{Product.count} products\"\n end",
"def length\n stop - start + 1 unless coverage == 0\n end",
"def trip_count\n trips.count\n end",
"def trip_count\n self.trips.length\n end",
"def trip_count\n self.trips.length\n end",
"def stops\n get '/gtfs/stops'\n end",
"def total_stops(line_start, station_start, line_end, station_end)\n\t# if travelling on the same line the number of stops is the differential in array indexes\n if line_start == line_end\n \ttotal_stops = line_start.index(station_start) - line_end.index(station_end)\n\n\t# the next 3 are for when union station is a start or end point in the journey\t\n\t# if union is one of the stops then you onlyu need to calculate the number of stops to other station \t\n elsif\n \tstation_start == station_end\n \ttotal_stops = 0\n\n elsif station_start.include?(\"union\")\n \ttotal_stops = stops_from_union(station_end, line_end)\n\n elsif station_end.include?(\"union\")\n \ttotal_stops = stops_from_union(station_start, line_start)\n\n\t# when journey begins and ends on different lines you add the number of stops from union station\n else\n \ttotal_stops = stops_from_union(station_start, line_start) + stops_from_union(station_end, line_end)\n\n end\n\n\t# total stops needs to be an absolute value\n\ttotal_stops = total_stops.abs\nend",
"def get_running_count\n return @describe_service.services[0].running_count\n end",
"def trip_count\n return self.trips.length\n end",
"def trip_count\n trips.count\n end",
"def num_lights\n\t\t\t@lights.length\n\t\tend",
"def display\n port_total\n display_port\n overall_total\n end",
"def count_distance(departure, arrival, sub)\n\tdeparture_line = get_station_line(sub, departure)\n\tarrival_line = get_station_line(sub, arrival)\n\n\tif departure_line.to_s == 'red_line'\n\t\tdistance_first = (get_station_no(sub, departure) - 2).abs\n\telse \n\t\tdistance_first = (get_station_no(sub, departure) - 3).abs\n\tend\n\t\n\tif arrival_line.to_s == 'red_line'\n\t\tdistance_second = (get_station_no(sub, arrival) - 2).abs\n\telse \n\t\tdistance_second = (get_station_no(sub, arrival) - 3).abs\n\tend\n\treturn distance_first + distance_second\n\nend",
"def number(bus_stops)\r\n item_1 = bus_stops.sum(&:first) #return the sum of first elements in arrays (i.e. people get on the bus)\r\n item_2 = bus_stops.sum(&:last) #return the sum of last elements in arrays (i.e. people get off the bus)\r\n p passengers = item_1 - item_2\r\nend",
"def show_cars_count\n puts \"cars count: #{cars.size}\"\n end",
"def count_stops_in_array(stops_array)\n result = stops_array.length()\n return result\nend",
"def trip_count\n self.trips.size\n end",
"def counts\r\n @counts\r\n end",
"def compute_stops(route)\n route.visited_stops\n end",
"def total_duration\n running_total = 0\n @trips.each do |trip|\n @total_driving_time += trip.duration\n end\n end",
"def stops_from_union(station, line)\n\n\tnum_stops = line.index(station) - line.index(\"Union Square\")\n\tnum_stops.abs\nend",
"def numbers_of_planes\n\t\t@landed_planes.count \n\tend",
"def show_cars_count\n puts \"cars count: #{self.cars.size}\"\n end",
"def singleTrip (start_station, end_station, line)\n start_index = MTA[line].index(start_station)\n end_index = MTA[line].index(end_station)\n\n if start_index < end_index\n stops = MTA[line][start_index ... end_index]\n num_stops = end_index - start_index\n end\n\n if end_index < start_index\n stops = MTA[line][end_index ... start_index]\n stops = stops.reverse\n num_stops = start_index - end_index\n\n end\n print = \"You must travel through the following stops on the #{line}: #{stops}\"\n # print = \"#{num_stops} in total\"\nend",
"def totalDistance\n\t\ti = 0\n\t\tsum = 0\n\t\twhile i < @@walks\n\t\t\tsum += @@distance[i].to_i\n\t\t\ti += 1\n\t\tend\n\t\tputs \"Bark\"\n\t\tif @@walks == 0\n\t\t\tputs \"#{@name}'s owners don't love them. They haven't been on a walk yet :(\"\n\t\telsif @@walks == 1\n\t\t\tputs \"#{@name} has walked #{sum}kms in a single walk\"\n\t\telse\n\t\t\tputs \"#{@name} has already walked #{sum}kms in #{@@walks} walks\"\n\t\tend\n\tend",
"def number(bus_stops)\n bus_stops.reduce(0) do |sum, array|\n sum + array[0] - array[1]\n end\nend",
"def default_stop\n @total ||= 1_000\n end",
"def durations; end",
"def total\n count\n end",
"def steps\n @steps ||= 0\n end",
"def lengths\n frequencies.map { |frequency| (@project.speed_of_sound / (frequency * 2) * 1000).round(0) }\n end",
"def print_report\n # total_bikes = @fleet.count \n # broken_bikes = @fleet.count {|b| b.is_broken?}\n # working_bikes = total_bikes-broken_bikes\n total_people = @people.count\n total_stations = @stations.count\n # show_stations = @stations.each do {|name, capacity| puts \"#{name}, #{capacity}\"}\n #tell me its name and capcity\n # puts \"Total bikes: #{total_bikes}\"\n # puts \"Broken bikes: #{broken_bikes}\"\n # puts \"Working bikes: #{working_bikes}\"\n puts \"Total people: #{total_people}\"\n # puts \"People with bikes: #{people_with_bikes}\"\n puts \"People without bikes #{people_without_bikes.count}\" \n puts \"Number of stations: #{total_stations}\" \n puts \"Stations:\"\n @stations.each do |station|\n puts \"#{station.name}, #{station.capacity}, #{station.bikes.count}\"\n end\n # result = \"total bikes #{total_bikes}\\n\" + \"broken bikes #{broken_bikes}\\n\" + \"working bikes #{working_bikes}\\n\"\n # result + \"total people #{total_people}\\n\" + \"people with bikes #{people_with_bikes}\\n\" + \"people without bikes #{people_without_bikes}\\n\" + \"number of stations #{total_stations}\\n\" + \"stations #{show_stations}\"\n end",
"def trip_count\n self.trips.count\n end",
"def get_size\n @monitors.length\n end",
"def trades_count\n trades.count\n end",
"def run\n # Digits 1,4,7,8 have 2,4,3,7 segments respectively\n @list.map{|line| line[1]}.flatten.map(&:length).filter{|len| [2, 4, 3, 7].include?(len)}.count\n end",
"def next_stop\n @current_stop += 1\n @current_stop = 0 if @current_stop == nr_stops\n @current_stop\n end",
"def stop_revenue(stop, phase, train)\n return 0 if stop.tile.label.to_s == 'HALT' && train.name != '3T' && train.name != '4T'\n\n stop.route_revenue(phase, train)\n end",
"def totalcount\n @totalcount\n end",
"def stats\n\t\t@counts\n\tend",
"def length\n @end - @start\n end",
"def display_stop_cycles(outname, ops, stamp_columns)\n tab = Array.new(8) { Array.new(12, \"-\") }\n stop_cycle = ops.first.output(outname).collection.get(\"stop_cycle\")\n\n if stop_cycle.present?\n stop_cycle[0].length.times do |cc|\n col = cc+1\n if stamp_columns\n if(stop_cycle[0][cc]>0)\n tab[0][cc] = {content: \"A#{col} cycle #{stop_cycle[0][cc]}\", check: \"true\"}\n (1..stamp_columns - 1).each do |rr|\n row = (rr+\"A\".ord).chr\n tab[rr][cc] = {content: \"cycle #{stop_cycle[0][cc]}\", check: \"false\"} # wells are connected\n end\n end\n else\n stop_cycle.length.times { |rr|\n if(stop_cycle[rr][cc]>0)\n row = (rr+\"A\".ord).chr\n tab[rr][cc] = {content: \"#{row}#{col} cycle #{stop_cycle[rr][cc]}\", check: \"true\"}\n end\n }\n end\n end\n end\n\n return tab\n end",
"def need_to_transfer(starting_line, starting_station, ending_line, ending_station)\n transfer_stop_num =\n count_stops(starting_station, \"Union Square\", starting_line) +\n count_stops(\"Union Square\", ending_station, ending_line)\nend",
"def total\n count = 0\n self.total_time_exercise_workouts.each do |ex|\n count += ex.duration\n end\n count\n end",
"def pdf_total_time\n runs.sum(:finish)\n end",
"def number_of_values\n Integer((@upper - @lower) / @step) + 1\n end",
"def total_runs=(value)\n @total_runs = value\n end",
"def step_count listing\n listing.free? ? 2 : !listing.new? ? 2 : 3 rescue 2\n end",
"def off_times\n load_curve.count(&:zero?)\n end",
"def count \n puts \"Tu as scrappé #{@result_scrap.count} élémént(s)\"\n return @result_scrap.count\n end",
"def lesstrips(start, finish, max_distance)\n total_paths, distance = 0, 0\n path, paths = [], []\n visited = [start]\n cycles = all_cycles # all cycles in graph\n puts \"MAX DISTANCE = #{max_distance}\\n\"\n total_paths += lesstrips_dfs(start, finish, max_distance, distance, visited, path, paths, cycles)\n puts \"\\n==> Total paths from #{start} to #{finish}, with distance < #{max_distance}: #{total_paths}\\n\"\n total_paths\n end",
"def total_time; end",
"def total_duration\n self.inject(0) do |accum,trip|\n accum += trip.duration\n accum\n end\n end",
"def segment_count\n @segments.length\n end",
"def set_route_stops\n 0\n end",
"def length\n count(:up)\n end",
"def totalLipidos\n\t\tlip = 0\n\t\ttotal = 0\n\t\t@platos.each do |alimento|\n\t\t\tlip += alimento.lipidos\n\t\tend\n\t\treturn lip.round(2)\n\t\n\tend",
"def find_stations(si, ei, line) # si is short for start index and ei is short for end index\n if ei >= si\n line_stop_count = ei - si\n passing_stations = line[(si+1)..ei].join(\", \")\n else\n line_stop_count = si - ei\n passing_stations = line[(ei)..(si-1)].reverse.join(\", \")\n end\n return {:num_stops => line_stop_count, :stops => passing_stations}\nend",
"def data_count\n @episodes.sum { |_, v| v.length }\n end",
"def length\n @end - @start + 1\n end",
"def num_of_rides(trips)\n return trips.map do |driver, trip|\n \"Driver #{driver} made #{trip.length} rides\"\n end\nend",
"def medicine_time_step_count(lines, use_optimizations = false)\n inverse_rules, target_molecule = parse_inverse_rules_and_molecule(lines)\n find_minimal_time_steps(target_molecule, inverse_rules, use_optimizations)\nend",
"def length_of_all_walks\n self.walks.sum {|walk| walk.length_in_minutes}\n end",
"def total_duration\n duration = 0\n trips.each { |trip| duration += trip.duration }\n return duration\n end",
"def total\n Time.now.to_f - @start\n end",
"def show_total_unattendance_number\n puts 'show_total_unattendance_number'\n total_unattendance_number = @data.inject (0) do |mem, e|\n num_exams = e.size - 1.0\n mem + e.last(num_exams).count('00')\n end\n puts total_unattendance_number.to_s\n end",
"def stop!\n\t\t\tif @started\n\t\t\t\t@total += (Clock.now - @started)\n\t\t\t\t@started = nil\n\t\t\tend\n\t\t\t\n\t\t\treturn @total\n\t\tend",
"def find_total_rides(rides)\n length = rides.length\n return length\nend",
"def count\r\n @pitches.size\r\n end",
"def count\n @count\n end",
"def len\n timevec.length\n end"
] | [
"0.6675247",
"0.6542983",
"0.6333986",
"0.6329348",
"0.6324554",
"0.63127315",
"0.62659895",
"0.6246094",
"0.62302047",
"0.61082006",
"0.6081763",
"0.6075929",
"0.6075929",
"0.6075929",
"0.6068978",
"0.6053711",
"0.6053061",
"0.6048437",
"0.60428387",
"0.60287166",
"0.60040045",
"0.596837",
"0.596837",
"0.5967906",
"0.59481704",
"0.59403574",
"0.59126264",
"0.5890939",
"0.5885592",
"0.5835011",
"0.58312666",
"0.58271646",
"0.58200294",
"0.58200294",
"0.579724",
"0.579076",
"0.57849205",
"0.57764804",
"0.5764268",
"0.5759231",
"0.57496303",
"0.57375145",
"0.57342845",
"0.5732564",
"0.5721503",
"0.5689462",
"0.56870735",
"0.5675541",
"0.5674112",
"0.5674094",
"0.56601",
"0.565855",
"0.5651468",
"0.5643935",
"0.5632155",
"0.56180614",
"0.56134564",
"0.5607198",
"0.5600639",
"0.55900544",
"0.55646497",
"0.55443597",
"0.55428904",
"0.5533925",
"0.5527952",
"0.55253386",
"0.55104554",
"0.5507264",
"0.5501215",
"0.5490593",
"0.5488623",
"0.54812574",
"0.5479132",
"0.5476659",
"0.5474313",
"0.54709756",
"0.54453516",
"0.544437",
"0.5436802",
"0.5434111",
"0.5423377",
"0.54139775",
"0.54087734",
"0.5406738",
"0.53968304",
"0.5392745",
"0.5389487",
"0.5386919",
"0.53667647",
"0.53637075",
"0.5362814",
"0.53603965",
"0.5356006",
"0.5355085",
"0.5354696",
"0.5349054",
"0.53469884",
"0.53415424",
"0.53374904",
"0.53353196"
] | 0.629494 | 6 |
somehow registration does not work out (at least not under windows) the . is also not accepted by unix as seperator | def tag(name)
if $crossover then "_CTX_K_S_#{name}_" else "TEXMFSTART.#{name}" end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def filesystem_safe_name\n name.\n gsub(ReservedCharacters) {|sub| '%%%02X' % sub.ord }.\n gsub(ReservedFilenameRegexp) {|sub| sub.gsub(/[^.]/) {|c| '%%%02X' % c.ord } }\n end",
"def start_registering_extension\n @register_path = caller_files[2]\n end",
"def extname; end",
"def extname; end",
"def extname; end",
"def extname; end",
"def name\n path.gsub(/\\./,'_').gsub(%r{/}, '.').gsub(%r{(^\\.|\\.$)},'')\n end",
"def uniPath(source)\n source.gsub(/\\\\/, File::SEPARATOR)\nend",
"def generate_intended_filename_regex conf\n prefix = \"#{ conf['local_hostname'] }-\\\\d{4}_\\\\d{2}_\\\\d{2}\"\n case conf['type']\n when /dir/\n dir_part = conf['path'].sub(/\\//,'').gsub(/\\//,\"-\")\n return \"#{ prefix }-#{ dir_part }\\\\.tar\\\\.gz\"\n when /mys/\n db_part = conf['database']\n return \"#{ prefix }-#{ db_part }\\\\.sql\\\\.gz\"\n end\nend",
"def remove_extra_slashes\n self.home = StringConstructor.sanitized_filepath self.home\n end",
"def registered?(ext); end",
"def registered?(ext); end",
"def prefix\n (platform_family?('windows') ? 'C:/Chef/' : '/etc/chef/')\nend",
"def cron_dot_d_directory\n end",
"def whereami() [__FILE__] end",
"def makeWindowsPathIntoMinGWPath(path)\n modifiedPath = path.gsub(/\\\\/, '/')\n modifiedPath.gsub(/^(\\w+):[\\\\\\/]/) { \"/#{$1.downcase}/\" }\nend",
"def win_friendly_path(path)\n path.gsub(::File::SEPARATOR, '\\\\\\\\\\\\\\\\') if path\n path.gsub(::File::ALT_SEPARATOR, '\\\\\\\\\\\\\\\\') if path\n # NOTE: regex(\"\\\\\\\\\") is intepreted as regex(\"\\\\\" [escaped backslash] followed by \"\\\\\" [escaped backslash])\n # is intepreted as regex(\\\\)\n # is interpreted as a regex that matches a single literal backslash. --- Ruifeng Ma, May-18-2016\n end",
"def process_name\n\n\t\t::Pantheios::Core.process_name\n\tend",
"def windows_path(path)\n path.gsub(/\\//, '\\\\')\n end",
"def extify(name) # :doc:\n if Gem.win_platform?\n \"#{name}.bat\"\n else\n name\n end\n end",
"def makeWindowsPathIntoMinGWPath(path)\n modified_path = path.tr('\\\\', '/')\n modified_path.gsub(%r{^(\\w+):[\\\\/]}) { \"/#{Regexp.last_match(1).downcase}/\" }\nend",
"def extension_regex\n if @config && @config[:allow_periods_in_identifiers]\n /(\\.[a-z]{2})?(\\.[^\\/\\.]+$)/\n else\n /(\\.[a-z]{2})?(\\.[^\\/]+$)/\n end\n end",
"def klass2file(str)\n\t\t\tstr.split(/::/).map {|c|\n\t\t\t\tc.scan(/[A-Z][a-z0-9]*/).join(\"_\").downcase\n\t\t\t}.join(\"/\")\n\t\tend",
"def win_slashify(path)\n path.gsub(File::SEPARATOR, (File::ALT_SEPARATOR || '\\\\'))\n end",
"def soname(s)\n unless Platform.is_windows?\n @flags.push ['soname', s]\n end\n end",
"def tcp_wrappers_filename\n new_resource.name.gsub(/[\\.~]/, '__')\nend",
"def system_home\n ENV.fetch(\"HOME\").tr(\"\\\\\", \"/\")\nend",
"def name\n \"#{service} // #{login}\"\n end",
"def executable_path; end",
"def gen_inst_id_str(inst_str)\n return inst_str.gsub(/[\\.:\\[\\]]/,'_').upcase\nend",
"def windows_safe_path!(path)\n path.gsub!(File::SEPARATOR, File::ALT_SEPARATOR) if File::ALT_SEPARATOR\n end",
"def clarify_pagefile_name\n case new_resource.path\n # user enters C, C:, C:\\, C:\\\\\n when /^[a-zA-Z]/\n new_resource.path[0] + \":\\\\pagefile.sys\"\n # user enters C:\\pagefile.sys OR c:\\foo\\bar\\pagefile.sys as the path\n when /^[a-zA-Z]:.*.sys/\n new_resource.path\n else\n raise \"#{new_resource.path} does not match the format DRIVE:\\\\path\\\\pagefile.sys for pagefiles. Example: C:\\\\pagefile.sys\"\n end\n end",
"def full_name\n \"#{username}/#{name}\"\n end",
"def win_friendly_path(path)\n path.gsub(::File::SEPARATOR, '\\\\\\\\\\\\\\\\') if path\n # NOTE: regex(\"\\\\\\\\\") is intepreted as regex(\"\\\\\" [escaped backslash] followed by \"\\\\\" [escaped backslash])\n # is intepreted as regex(\\\\)\n # is interpreted as a regex that matches a single literal backslash. --- Ruifeng Ma, May-18-2016\nend",
"def register_config_files\n [Dir.home, Dir.pwd].each do |dir|\n option_parser.config_files.class.supported_extensions.each do |ext|\n option_parser.config_files << Pathname.new(dir).join(\".#{NS.app_name}\", \"scan.#{ext}\").to_s\n end\n end\n end",
"def ext_name(name)\r\n return name.to_s if name.kind_of?(Symbol)\r\n return name.gsub(/\\s/, '_')\r\n end",
"def win_friendly_path(path)\n path&.gsub(::File::SEPARATOR, ::File::ALT_SEPARATOR || '\\\\')\n end",
"def win_friendly_path(path)\n path&.gsub(::File::SEPARATOR, ::File::ALT_SEPARATOR || '\\\\')\n end",
"def path\n name.split(\"::\").join(\"/\").downcase\n end",
"def win_friendly_path(path)\n path.gsub(::File::SEPARATOR, ::File::ALT_SEPARATOR || '\\\\') if path\n end",
"def platform\n self.class.name.split(\"::\").last.gsub(/(?<=[^A-Z])[A-Z]+/, \"-\\\\0\").downcase\n end",
"def test_namefailures\n server = nil\n assert_nothing_raised {\n\n server = Puppet::Network::Handler.fileserver.new(\n\n :Local => true,\n\n :Config => false\n )\n }\n\n [\" \", \"=\" \"+\", \"&\", \"#\", \"*\"].each do |char|\n assert_raise(Puppet::Network::Handler::FileServerError, \"'#{char}' did not throw a failure in fileserver module names\") {\n server.mount(\"/tmp\", \"invalid#{char}name\")\n }\n end\n end",
"def short_name( fn )\n #puts \"Calculate short name for #{fn}\\n\"\n return fn if ARCH != 'w32'\n fn.gsub!( /\\//, \"\\\\\" )\n buffer = ' ' * 260\n length = ShortPName.call( fn, buffer, buffer.size )\n fn = buffer.slice(0..length-1) if length > 0\n fn.gsub!( /\\\\/, '/' )\n return fn\nend",
"def root_dir\n 'gen_passwd'\n end",
"def escape_glob(s)\n s.gsub(/[\\\\\\{\\}\\[\\]\\*\\?]/) { |x| \"\\\\\"+x }\nend",
"def login_user_name\n user_name.tr('.', '')\n end",
"def register(thing, *extensions)\n return if extensions.empty?\n extensions.map! { |ext| ext[0] == ?. ? ext.downcase : \".#{ext.downcase}\" }\n extensions.each { |ext| REGISTRY[ext] = thing }\n EXTENSIONS[thing] = extensions.first\n nil\n end",
"def escaped_file_name(filename)\n\t\tputs \"\\n=> init \" + filename \n\t\tresult = filename.gsub(\" \", \"\\\\ \")\n\t\tputs \"\\n=> init2 \" + result\n\t\tresult2 = result.gsub(\"\\'\", \"\\\\\\\\\\'\")\n\t\tputs \"\\n=> init3 \" + result2\n\t\tresult2\n\tend",
"def adjust_rsync_path(path)\n path.gsub(/^(\\w):/) { \"/cygdrive/#{$1}\" }\n end",
"def unix_name\n 'heads_up'\n end",
"def name\n \"#{bts} // #{login}\"\n end",
"def escape_filename(text)\n # NOTE: only leading [+>] are escaped (according to builtin :h fnameescape).\n # [-] is escaped when it's the only char in a name (to prevent confusion\n # with `cd -` argument)\n text\n .to_s\n .gsub(/([\\t\\n *%$'\"<{\\[\\\\])/, '\\\\\\\\\\1')\n .sub(/^([+>])/, '\\\\\\\\\\1')\n .sub(/^-$/, '\\\\-')\n end",
"def base_filename; class_to_filename(name.gsub(/.*:/, '')); end",
"def homify f = ''\n if f.length == 0 then @homedir\n else \"#{@homedir}/#{f}\" end\n end",
"def test_to_bash_equals_to_s_for_pathnames_without_user_home\n path = Pathname.new( '/usr/local/bin' )\n assert_equal( path.to_s, path.to_bash )\n end",
"def path(name,ext=nil)\n a,filename = File.split(ext.nil? ? super(name) : super(name,ext))\n a,b = File.split(a)\n File.join(a,'catalog_cm_guard',filename)\n end",
"def update_hostname(name)\n File.open(File.join(KVM_MOUNT_POINT, name, 'etc', 'hostname'), 'w') do |file|\n file.puts name.split('.').first\n end\nend",
"def class_to_filename (c)\n c.split(/::/).map {|i| i.gsub(/([A-Z])/, '_\\1').sub(/_/, '').downcase}.\n join('/')\nend",
"def windows_safe_path(*pieces)\n path = File.join(*pieces)\n\n if File::ALT_SEPARATOR\n path.gsub(File::SEPARATOR, File::ALT_SEPARATOR)\n else\n path\n end\n end",
"def updateName(name)\n name_array = name.split(\"\\\\\")\n return name_array[0]\nend",
"def registration_name_matches?(rule)\n rule == \"#{registration_name}.\"\n end",
"def alias_generator (full_name)\n\treturn splitter(full_name.downcase)\nend",
"def clean_name\n global? ? registry.hostname : name\n end",
"def clean_name\n global? ? registry.hostname : name\n end",
"def createValidName(inname)\r\n $LOG.debug \"PpmContext::createValidName( #{inname} )\"\r\n outname = inname.gsub(/[\\s\\/\\\\?*#+]/,'') # Remove illegal chars (replace with underscore).\r\n outname.gsub!(/_+/,\"_\") # Replace consecutive uscores with single uscore.\r\n outname.gsub!(/\\./,\"-\") # Replace period with dash.\r\n outname.gsub!(/[\\(\\)\\$]/,\"\") # Remove L & R Parens, dollar signs.\r\n outname.gsub!(/\\%/,\"Perc\") # Replace '%' with Perc.\r\n\r\n outname\r\n end",
"def fix_drive_letter(path); end",
"def update_lib_path_file\r\n pathname = (@rootdir + '\\\\' + @libfile).downcase\r\n fw = File.new(pathname + '.new', 'w')\r\n f = File.new(pathname)\r\n f.each {|l|\r\n line = l.chomp.chomp(';')\r\n if File.basename(line.downcase, '.pbl') == @applpbl.downcase\r\n puts l\r\n fw.puts l\r\n else \r\n puts line.gsub(File.basename(line),File.basename(line,'.pbl')) + '\\\\' + File.basename(line) + ';'\r\n fw.puts line.gsub(File.basename(line),File.basename(line,'.pbl')) + '\\\\' + File.basename(line) + ';'\r\n #puts line =~ /\\\\([^\\\\])+$/\r\n #puts line[/\\\\([^\\\\])+$/]\r\n end \r\n }\r\nend",
"def _escape (addr)\n addr =~ /\\\\./ ? addr\n : addr =~ /\\.\\*/ ? addr.gsub(/\\*/, '\\d+').gsub(/\\./, '\\.')\n : Regexp.escape(addr)\nend",
"def add_ext(str,ext)\n ( str.strip=~/\\.#{ext}$/ ) ? str.strip : \"#{str.strip}.#{ext}\"\n end",
"def rsync_path_escape( path )\n if (@os == :mac)\n # '\"' + path + '\"'\n path\n else\n # Adapt to other OSs if necessary\n # '\"' + path + '\"'\n path\n end\n end",
"def dotted_ext(ext)\n ext = ext.to_s and (ext.empty? or ext.start_with?('.')) ? ext : \".#{ext}\"\n end",
"def basename_without_ext; end",
"def persp_and_ext_for_basename(path)\n [main_name(path).sub('resource-epo-',''), File.extname(path)]\n end",
"def search(f_name) \r\n yield ENV['PATH'].split(';').map {|p| File.join p, f_name}.find {|p| File.file? p and File.executable? p}\r\nend",
"def util_fake_extension(spec, name = \"a\", script = nil)\n mkrf_conf = File.join(\"ext\", name, \"mkrf_conf.rb\")\n\n spec.extensions << mkrf_conf\n\n dir = spec.gem_dir\n FileUtils.mkdir_p dir\n\n Dir.chdir dir do\n FileUtils.mkdir_p File.dirname(mkrf_conf)\n File.open mkrf_conf, \"w\" do |f|\n if script\n f.write script\n else\n f.write <<-EOF\n File.open 'Rakefile', 'w' do |rf| rf.puts \"task :default\" end\n EOF\n end\n end\n end\n end",
"def windows?\n ::File::ALT_SEPARATOR == '\\\\'\n end",
"def unique_path\n unique_name.split(\"/\") rescue [unique_name]\n end",
"def file_name\n \"#{full_name}.gem\"\n end",
"def createValidName(inname)\r\n outname = inname.gsub(/[\\s\\/\\\\?*#+]/,'') # Remove illegal chars (replace with underscore).\r\n outname.gsub!(/_+/,\"_\") # Replace consecutive uscores with single uscore.\r\n outname.gsub!(/\\./,\"-\") # Replace period with dash.\r\n\r\n outname\r\n end",
"def split_filename(fn)\n fn.split(/[\\/\\\\]/)\n end",
"def basename_for_persp_and_ext(persp, ext)\n \"resource-epo-#{persp}#{ext}\"\n end",
"def util_fake_extension(spec, name = \"a\", script = nil)\n mkrf_conf = File.join(\"ext\", name, \"mkrf_conf.rb\")\n\n spec.extensions << mkrf_conf\n\n dir = spec.gem_dir\n FileUtils.mkdir_p dir\n\n Dir.chdir dir do\n FileUtils.mkdir_p File.dirname(mkrf_conf)\n File.open mkrf_conf, \"w\" do |f|\n if script\n f.write script\n else\n f.write <<~EOF\n File.write('Rakefile', \"task :default\")\n EOF\n end\n end\n end\n end",
"def search_paths\n if Facter::Util::Config.is_windows?\n ENV['PATH'].split(File::PATH_SEPARATOR)\n else\n # Make sure facter is usable even for non-root users. Most commands\n # in /sbin (like ifconfig) can be run as non priviledged users as\n # long as they do not modify anything - which we do not do with facter\n ENV['PATH'].split(File::PATH_SEPARATOR) + [ '/sbin', '/usr/sbin' ]\n end\n end",
"def real_name; end",
"def fix_drive_letter path\r\n return path unless path.match(/^[a-z]:/)\r\n path[0].upcase + path[1..-1]\r\n end",
"def authorized? name\n\t$master_regex ||= /^#{$master.gsub('.','\\.')}(\\/.*)?$/\n\tname.to_s =~ $master_regex\nend",
"def set_fullname(fullname)\n fullname = fullname.gsub(/\\\\([0-9]{1,3})/) do $1.to_i.chr end\n fullname = fullname.scan(/(?:[^\\\\.]|\\\\\\.)+/).map do |part|\n part.gsub \"\\\\.\", '.'\n end\n\n @name = fullname[0]\n @type = fullname[1, 2].join '.'\n @domain = fullname[3..-1].map { |part| part.sub '.', '\\\\.' }.join('.') + '.'\n end",
"def resource_uid(*keys)\n keys.join('\\\\')\n end",
"def class_to_basefile class_name\n\t\t\treturn \"#{base_dir}/#{class_name.gsub(\"::\", \"/\")}\"\n\t\tend",
"def sanitized_dirname\n @remote.gsub(/[^@\\w\\.-]/, '-')\n end",
"def read_platform_from_file(path:)\n path.basename.to_s.split('.').first\n end",
"def regexify(glob)\n glob.gsub! '.', '\\\\.'\n rx = glob.split '*'\n rs = '^' + rx[0]\n rs << '.*'\n rs << rx[-1] if rx.length == 2\n rs << '$'\n Regexp.new rs\nend",
"def registry_path\n fail NotImplementedError\n end",
"def dir_name(name)\n name = name.dup\n name.gsub!(\":\", VAGRANT_COLON) if Util::Platform.windows?\n name.gsub!(\"/\", VAGRANT_SLASH)\n name\n end",
"def escape_glob\n self.class.new(escape_glob_string)\n end",
"def defang_i_paddr(address)\n address.gsub('.', '[.]')\nend",
"def extname( fn )\n ::File.extname(fn).tr('.', '')\n end",
"def mangle_name(name)\r\n name.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'\\1_\\2').gsub(/([a-z\\d])([A-Z])/,'\\1 \\2')\r\n end",
"def file_name(s)\n s.gsub(/[\\s\\\\\\/]/, '_')\n end",
"def fixed_name(file, bad_name)\n if (file.dylib? || file.mach_o_bundle?) && (file.parent + bad_name).exist?\n \"@loader_path/#{bad_name}\"\n elsif file.mach_o_executable? && (lib + bad_name).exist?\n \"#{lib}/#{bad_name}\"\n elsif (abs_name = find_dylib(Pathname.new(bad_name).basename)) && abs_name.exist?\n abs_name.to_s\n else\n opoo \"Could not fix #{bad_name} in #{file}\"\n bad_name\n end\n end",
"def pid_file\n felix_home_to_pid_file(@felix_home)\n end"
] | [
"0.57724786",
"0.55778706",
"0.5521576",
"0.5521576",
"0.5521576",
"0.5521576",
"0.55095315",
"0.55071396",
"0.54648894",
"0.54400605",
"0.5389148",
"0.5389148",
"0.5381623",
"0.5356727",
"0.5327964",
"0.5285881",
"0.5278135",
"0.52696717",
"0.5261767",
"0.5251551",
"0.52435434",
"0.52397877",
"0.5237623",
"0.52209127",
"0.5212859",
"0.5207137",
"0.5194682",
"0.5184635",
"0.5182862",
"0.51754",
"0.5164503",
"0.51609427",
"0.515385",
"0.5152243",
"0.51439655",
"0.51432604",
"0.5139058",
"0.5139058",
"0.51252437",
"0.510903",
"0.5099316",
"0.5097104",
"0.5081922",
"0.5074668",
"0.5043833",
"0.5038844",
"0.5035057",
"0.50323874",
"0.50300413",
"0.5015941",
"0.500898",
"0.50072545",
"0.50050807",
"0.50013256",
"0.4999526",
"0.49975663",
"0.49953043",
"0.49884748",
"0.49800664",
"0.49783617",
"0.49740982",
"0.4963857",
"0.49623677",
"0.49623677",
"0.49609798",
"0.4958123",
"0.4955871",
"0.49492332",
"0.4946881",
"0.49429154",
"0.4942701",
"0.4933973",
"0.49337506",
"0.49329647",
"0.4927821",
"0.49255306",
"0.49213055",
"0.4918783",
"0.49051386",
"0.4904813",
"0.4904624",
"0.49034584",
"0.48997363",
"0.4898012",
"0.489794",
"0.48954743",
"0.48923147",
"0.4889674",
"0.4885272",
"0.48748502",
"0.48736057",
"0.4867574",
"0.48669934",
"0.4865956",
"0.4864095",
"0.4863032",
"0.48536274",
"0.4852584",
"0.4851011",
"0.48480642",
"0.4848016"
] | 0.0 | -1 |
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 !@trips.blank? 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 !@trips.blank?\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",
"def search_passengers(search, academic_year_id)\n return [] unless search[:route_id].present?\n conditions = {:receiver_type => search[:passenger]}\n route_type = \"#{search[:route_type]}_route_id\".to_sym\n conditions[route_type] = search[:route_id]\n include = (search[:passenger] == \"Student\" ? {:receiver => {:batch => :course}} : {:receiver => :employee_department})\n stop_method = \"#{search[:route_type]}_stop\".to_sym\n Transport.in_academic_year(academic_year_id).all(:conditions => conditions, :include => [stop_method, include])\n end",
"def stops_for_route(route_id)\n stop_ids = @db[:stop_times].\n select(:stop_id).\n where(:trip_id => trips_for_route_today(route_id))\n\n stops = @db[:stops].\n select(:stop_id, :stop_name).\n where(:stop_id => stop_ids).\n order(:stop_name).\n all\n\n stops.map { |stop| { :route_id => route_id}.merge(stop) }\n end",
"def compute_other_paths(routes, route)\n routes\n .reject { |r| r == route }\n .select { |r| train_type(route.train) == train_type(r.train) }\n .flat_map(&:paths)\n end",
"def trips\n flight = Flight.where(\"id = ?\", params[:id]).take\n if flight.nil?\n render :json => {errors: \"404\"}, :status => 404\n else\n respond_with( flight.trips )\n end\n end",
"def find_my_routes(*args)\n bounds = args[0][:bounds].nil? ? default_coordinates : args[0][:bounds].dup\n routes = case args[0][:filter]\n when \"recommended\"\n Route.where(:\"overview_points.latlng\".within(:box) => bounds).where(visibility: 'recommended')\n when \"liked\"\n # TODO need to build this\n else # 'my' or blank\n Route.where(:\"overview_points.latlng\".within(:box) => bounds).where(owner_id: id)\n end\n end",
"def services\n Service.where(agency: agencies)\n end",
"def trips\n trips = RideShare::Trip.trips_by_rider(@id)\n if trips != nil\n return trips\n else\n return []\n end\n end",
"def trips\n Trip.all.select{ |trip| trip.guest == self}\n end",
"def search\n if params[:user_only] and current_user.blank?\n render json: {\n error: \"Must authenticate user for user_only route search.\"\n }\n return\n end\n Rails.logger.debug \"Search got params: #{params}\"\n # Pagination\n per_page = params[:per_page] || 10\n per_page = per_page.to_i\n\n page_num = params[:page_num] || 1\n page_num = page_num.to_i\n\n offset = page_num * per_page - per_page\n\n # Location\n if params[:start_maidenhead]\n start_maidenhead = params[:start_maidenhead]\n elsif params[:source_lat] and params[:source_long]\n start_maidenhead = Maidenhead.to_maidenhead(params[:source_lat].to_f, params[:source_long].to_f, 4)\n end\n\n if params[:end_maidenhead]\n end_maidenhead = params[:end_maidenhead]\n elsif params[:dest_lat] and params[:dest_long]\n end_maidenhead = Maidenhead.to_maidenhead(params[:dest_lat].to_f, params[:dest_long].to_f, 4)\n end\n\n # Where clause\n condition = {}\n condition[:start_maidenhead] = start_maidenhead if start_maidenhead.present?\n condition[:end_maidenhead] = end_maidenhead if end_maidenhead.present?\n condition[:user_id] = current_user.id if params[:user_only].present?\n\n # Group by Similarity rather than start/end points if both points provided\n if start_maidenhead and end_maidenhead\n # Get all uses and group into routes by similarity\n Rails.logger.debug \"Searching for routes from #{start_maidenhead} to #{end_maidenhead}\"\n all_uses = Route.where(condition).order('start_time DESC').limit(per_page).offset(offset)\n routes = all_uses.inject([]) do |routes, use|\n if routes.blank?\n routes << use\n else\n use_found = routes.any? { |route| use.is_similar?(route) }\n routes << use unless use_found\n end\n routes\n end\n\n # Summarise routes\n summaries = routes.inject([]) do |all_summaries, route|\n all_summaries << route.summary\n end\n else\n routes = Route.where(condition)\n .select('start_maidenhead, end_maidenhead, MAX(start_time) as start_time')\n .group(:start_maidenhead, :end_maidenhead)\n .order('start_time DESC')\n .limit(per_page)\n .offset(offset)\n\n if params[:user_only]\n summaries = routes.inject([]) do |all_summaries, route|\n all_summaries << Route.summarise_routes(route.start_maidenhead, route.end_maidenhead, current_user)\n end\n else\n summaries = routes.inject([]) do |all_summaries, route|\n all_summaries << Route.summarise_routes(route.start_maidenhead, route.end_maidenhead, nil)\n end\n end\n end\n\n render json: {\n routes: summaries\n }\n end",
"def search_routes(current_user,booked_routes)\n\n select_clause= 'routes.*, (routes.tempo_percorrenza/60) AS ore, (routes.tempo_percorrenza%60) AS min, vehicles.comfort, vehicles.tipo_mezzo, drivers.rating_medio'\n if current_user.nil?\n where_clause='data_ora_partenza > NOW()'\n else\n where_clause='data_ora_partenza > NOW() AND routes.driver_id != ? ', current_user\n end\n\n\n routes = Route.select(select_clause).joins(:vehicle).joins(:driver).where(where_clause).joins(:vehicle)\n\n routes = routes.where(\"routes.deleted IS NOT TRUE\")\n routes = routes.where(\"routes.id NOT IN (?)\",booked_routes)\n routes = routes.where([\"citta_partenza ILIKE ?\",\"%#{c_partenza}\"])\n routes = routes.where([\"citta_arrivo ILIKE ?\",\"%#{c_arrivo}\"])\n routes = routes.where([\"data_ora_partenza >= ?\", data_ora]) if data_ora.present?\n routes = routes.joins(:driver).where([\"drivers.rating_medio >= ?\",rating]) if rating.present?\n routes = routes.where([\"costo <= ?\",costo]) if costo.present?\n routes = routes.joins(:vehicle).where([\"vehicles.tipo_mezzo ILIKE ?\",\"%#{tipo_mezzo}\"]) if !tipo_mezzo.eql?('Altro')\n routes = routes.joins(:vehicle).where([\"vehicles.comfort >= ?\",comfort]) if comfort.present?\n routes = routes.joins(:vehicle).where([\"n_passeggeri < vehicles.posti\"])\n\n sorder=define_order(sort_order)\n\n routes = routes.order(costo: sorder) if sort_attribute.eql?('Costo')\n routes = routes.order(tempo_percorrenza: sorder) if sort_attribute.eql?('Tempo di percorrenza')\n routes = routes.joins(:vehicle).order(comfort: sorder) if sort_attribute.eql?('Comfort')\n\n routes\n\n end",
"def index\n @txdotlights = Txdotlight.all.paginate(:per_page =>15, :page => params[:page])\n .where(\"intersection ILIKE ?\",\"%#{params[:address_search]}%\").where(\"name ILIKE ?\",\"%#{params[:name_search]}%\").where(\"callback ILIKE ?\",\"%#{params[:phone_search]}%\").where(\"unitassigned ILIKE ?\",\"%#{params[:unit_search]}%\")\n end",
"def trips \n Trip.all.select do |ti|\n ti.guest == self\n end\n end",
"def set_route\n #zeroday is probably the day you seeded your DB\n zeroday = DateTime.parse('2015-12-02')\n params[:end] ||= params[:start].to_i + 1\n\n if params[:end].to_i < params[:start].to_i\n params[:end] = params[:start].to_i + 1\n end\n\n @whichRoute = params[:id]\n @startHour = params[:start].to_i\n @endHour = params[:end].to_i\n\n # @whichRoute = 10867\n # @startHour = 12\n # @endHour = 13\n\n allStops = StopTime.includes({trip: :route}, :stop).where( arrival_time: (zeroday.change( { hour: @startHour } )..zeroday.change( { hour: @endHour } )) )\n myRoutesTrips = Array.new\n #only look at trips that happen on the weekdays (serivce_id == 1)\n Trip.where(route_id: @whichRoute, service_id: 1).each do |trip|\n myRoutesTrips.push(trip.id)\n end\n\n @stoptimesOnMyRoute = allStops.where(trip_id: myRoutesTrips)\n\n end",
"def trips\n @trips = Trip.all.select do |trip|\n trip.guest == self\n end\n end",
"def get_trip_listing \n\t\t@trip = Trip.find_by(_id: trip_params[:trip_id])\n\t\tif current_user.trips_driving.include?(trip_params[:trip_id]) || current_user.past_trips_driven.include?(trip_params[:trip_id])\n\t\t\t@user_requests = User.where(:_id.in => @trip.user_requests).map { |user|\n\t\t\t\tuser = {\n\t\t\t\t\t_id: user.id,\n\t\t\t\t\tfirst_name: user.first_name,\n\t\t\t\t\tlast_name: user.last_name,\n\t\t\t\t\tfacebook_link: user.facebook_link,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\tphone_number: user.phone_number\n\t\t\t\t}\n\t\t\t}\n\t\t\t@accepted_users = User.where(:_id.in => @trip.accepted_users).map { |user| \n\t\t\t\tuser = {\n\t\t\t\t\t_id: user.id,\n\t\t\t\t\tfirst_name: user.first_name,\n\t\t\t\t\tlast_name: user.last_name,\n\t\t\t\t\tfacebook_link: user.facebook_link,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\tphone_number: user.phone_number\n\t\t\t\t}\n\t\t\t}\n\t\t\trender json: {\n\t\t\t\tstatus: 'success',\n\t\t\t\ttrip: {\n\t\t\t\t\ttrip_details: @trip,\n\t\t\t\t\tuser_requests: @user_requests,\n\t\t\t\t\taccepted_users: @accepted_users\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\trender json: {\n\t\t\t\tstatus: 'error',\n\t\t\t\tmessage: 'This user is not the driver for this trip'\n\t\t\t}\n\t\tend\n\tend",
"def index\n #@trips = Trip.all\n # @user_name = @trip.user.name\n if :start_date.nil? && :origin.present? && :destiny.present?\n @trips = Trip.where(start_date: params[:start_date]).where('origin LIKE ?', \"%#{params[:origin]}%\").where('destiny LIKE ?', \"%#{params[:destiny]}%\")\n #@trips = Trip.where('origin LIKE ?', \"%#{params[:origin]}%\").where('destiny LIKE ?', \"%#{params[:destiny]}%\")\n elsif :origin.present? && :destiny.blank?\n # @trips = Trip.where('origin LIKE ?', \"%#{params[:origin]}%\").where('destiny LIKE ?', \"%#{params[:destiny]}%\")\n # if :start_date.blank?\n @trips = Trip.where('origin LIKE ?', \"%#{params[:origin]}%\")\n elsif :origin.present? && :destiny.present?\n @trips = Trip.where('origin LIKE ?', \"%#{params[:origin]}%\").where('destiny LIKE ?', \"%#{params[:destiny]}%\")\n # if :start_date.blank?\n # @trips = Trip.where('origin LIKE ?', \"%#{params[:origin]}%\")\n elsif :destiny.present? \n @trips = Trip.where('destiny LIKE ?', \"%#{params[:destiny]}%\")\n # else\n # @trips = @trips.where('origin LIKE ?', \"%#{params[:origin]}%\")\n # end\n # elsif :destiny.present?\n # @trips = Trip.where('destiny LIKE ?', \"%#{params[:destiny]}%\")\n #elsif :origin.present?\n # @trips = Trip.where('origin LIKE ?', \"%#{params[:origin]}%\")\n else\n @trips = Trip.all\n end\n end",
"def find_possible_trips(starting_route, starting_time, max_stops, stops_visited=[])\n self.class.possible_trips.clear\n traverse_stops(starting_route, starting_time, max_stops, stops_visited=[])\n self.class.possible_trips.dup #.uniq\n end",
"def trips\n arr = []\n Trips.all.each do |trip|\n if trip.guest == self\n arr << trip\n end\n end\n arr\nend",
"def getRouteId\n @user_route_ids = []\n stop_routes_array = JSON.parse(File.read(STOP_ROUTES))\n for stop in stop_routes_array\n if stop[\"stop_id\"] == @user_stop_id\n @user_route_ids = stop[\"route_ids\"]\n end\n end\n\n for route in @user_route_ids\n @one_user_route = route\n puts \"user route is #{@one_user_route}\"\n return getAllTripIds(route)\n end\n end",
"def trips\n @trip_requests = current_user.trip_requests.trips.paginate(page:params[:page], per_page:20)\n json_response(@trip_requests)\n end",
"def results\n # @search_result = Recipe.where(\"name like ?\", \"%#{params[:search]}%\")\n\n @search_result = Recipe.joins(:food_items).joins(:directions).where(\"food_items.name ILIKE ? OR recipes.name ILIKE ? OR directions.instruction ILIKE ?\", \"%#{params[:search]}%\", \"%#{params[:search]}%\", \"%#{params[:search]}%\").distinct\n \n end",
"def trips\n #will find upcoming trips/reservations for guests\n Reservation.where(guest_id: self.id)\n end",
"def search(origin)\n\n route = @db[@table] \\\n .filter{ST_Contains(:Geometry, ST_Transform(MakePoint(origin.lng, origin.lat, 4326), 2277))} \\\n .fetch_one\n\n return nil unless route\n\n case @type\n\n when :GARBAGE\n # uses :SERVICE_DA (day of week, e.g. \"Wednesday\")\n next_service = self.class.next_service(START_DATE, route[:SERVICE_DA])\n service_period = :DAY\n recurrence = :WEEKLY\n\n when :YARD_TRIMMING\n # uses :AREA_SERVI (day of week, e.g. \"Wednesday\")\n next_service = self.class.next_service(START_DATE, route[:AREA_SERVI])\n service_period = :DAY\n recurrence = :WEEKLY\n\n when :RECYCLE\n # uses :SERVICE_DA (day of week, e.g. \"Wednesday\") and :SERVICE_WE (\"A\" or \"B\")\n raise \"column :SERVICE_DA undefined\" unless route.has_key?(:SERVICE_DA)\n raise \"column :SERVICE_WE undefined\" unless route.has_key?(:SERVICE_WE)\n start_date_offset = RECYCLING_PICKUP_OFFSET[route[:SERVICE_WE].strip]\n raise \"bad SERVICE_WE value \\\"#{route[:SERVICE_WE]}\\\"\" unless start_date_offset\n next_service = self.class.next_service(START_DATE + start_date_offset, route[:SERVICE_DA], 2)\n service_period = :DAY\n recurrence = :BIWEEKLY\n\n when :BRUSH, :BULKY\n # uses :NEXT_SERVI (timestamp, e.g. 2456474.5)\n raise \"column :NEXT_SERVI undefined\" unless route.has_key?(:NEXT_SERVI)\n next_service = Date.jd(route[:NEXT_SERVI])\n\tif ($time_now || Time.now) >= (next_service+7).to_time\n\t next_service += BIANNUAL_INCREMENT\n\tend\n service_period = :WEEK\n recurrence = :BIANNUAL\n\n else\n raise \"unknown collection type #{type}\"\n\n end\n\n # deterine if service date should slip due to holiday\n if service_period == :DAY\n slip_days = self.class.holiday_slip(next_service)\n next_service += slip_days unless slip_days.nil?\n else\n slip_days = nil\n end\n\n {\n :type => @type,\n :route => route[:ROUTE_NAME].strip.upcase,\n :next_service => {\n :timestamp => next_service.to_time.to_i * 1000,\n :date => next_service.strftime(\"%m/%d/%Y\"),\n :day => next_service.strftime(\"%a\"),\n :slip => slip_days,\n :status => self.class.status(next_service, service_period),\n :period => service_period,\n :recurrence => recurrence,\n },\n }\n\n end",
"def trips\n get '/gtfs/trips'\n end",
"def searched_items\n # search by city_section if that param is passed in (convert city_section string name to key for db lookup first)\n #if params[:city_section]\n # @the_things = DonorPickup.city_section_is(params[:city_section]).paginate(default_pagination_params)\n # return\n #end\n \n \n @the_things = DonorPickup.first_name_like(params[:search_first_name]).\n last_name_like(params[:search_last_name]).\n address_like(params[:search_address]).\n with_state(params[:search_state]).\n with_priority(params[:search_priority]).\n is_pending(params[:search_pending]).\n city_section_is(params[:search_city_section]).\n for_pickup_date_range(params[:search_pickup_time_lowest], params[:search_pickup_time_highest]).\n select{ |dp| params[:search_item_id].blank? ? true : dp.has_this_item?(params[:search_item_id].to_i)}.\n paginate(default_pagination_params)\n \n end",
"def drivers\n driver_ids = trips.map { |trip| trip.driver_id }\n driver_ids.sort!.uniq! # sort by ascending id and remove any duplicates\n # find the driver instances matching the given driver ids\n driver_ids.map { |driver_id| Driver.find(driver_id)}\n end",
"def search\n return @transactions.select{|el| el.created_at.to_s.starts_with?(params[:search_transaction]) || \n el.id.to_s.starts_with?(params[:search_transaction]) || \n el.sender_id.to_s.starts_with?(params[:search_transaction]) || \n el.receiver_id.to_s.starts_with?(params[:search_transaction]) || \n el.amount.to_s.starts_with?(params[:search_transaction])}\n end",
"def trip_filters\n elems = []\n TimeFilterHelper.time_filters.each do |tf|\n elems << {\n :id => 100 + tf[:id],\n :value => tf[:value]\n }\n end\n TripPurpose.all.each do |tp|\n elems << {\n :id => tp.id,\n :value => tp\n } \n end\n return elems \n end",
"def index\n @restaurantes_proximos = Array.new\n @found_foods = Array.new\n\n if params[:search]\n\n restaurants = Array.new\n\n params[:search].split().each do |tag|\n Tag.where(nome: tag).pluck(:prato_id).each() do |food_id|\n Prato.where(id: food_id).pluck(:id, :restaurante_id).each do |food|\n @found_foods << Prato.find(food[0])\n\n unless restaurants.include?(food[1])\n restaurants << food[1]\n end\n end\n end\n end\n\n @restaurantes_proximos = RestaurantesProximo.where(\"restaurante_id IN (?)\", restaurants)\n end\n end",
"def get_routing_matches(operation_map, output_item_id)\n ofv = operation_map.output_for(output_item_id)\n operation_map.item_inputs.select { |ifv| ifv.field_type&.routing == ofv.field_type&.routing }\n end",
"def find_location\n @locations = Location.where('trip_id IS ?', nil).order(created_at: :desc).paginate(page: params[:page], per_page: 15)\n end",
"def personal_trips\n @personal_trips = trips.where(driver_id: 0)\n end",
"def accepted_trips\n trip_ids = self.user_trips.where(state: \"accepted\").map(&:trip_id)\n Trip.where(id: trip_ids)\n end",
"def in_preroute_groups\n PrerouteGroup.all(:joins => \"inner join racc_route as route on route.route_name = racc_preroute_group.route_name and route.app_id = racc_preroute_group.app_id inner join racc_route_destination_xref as xref on xref.route_id = route.route_id inner join racc_destination as dest on dest.destination_id = xref.destination_id\",\n :conditions => [\"dest.destination_id = :dest_id\", {:dest_id => self.destination_id}])\n end",
"def matches\n @same_location = Ride.where(\"lower(start) like ? AND lower(destination) like ? AND id != ?\", self.start.downcase, self.destination.downcase, self.id)\n @same_location.where(\"start_time between ? and ? or end_time between ? and ?\", self.start_time, self.end_time, self.start_time, self.end_time)\n end",
"def stop_times_by_trip_id(trip_id)\n get \"/gtfs/stopTimes/tripId/#{trip_id}\"\n end",
"def listings \n Trip.all.select {|trip| trip.guest == self}.map { |trip| trip.listing}\n\n end",
"def depatures_by_route(route, stop_id)\n departures('departures/byroute/' + CGI.escape(route) + '/' + CGI.escape(stop_id))\n end",
"def search_trip(city_start, city_end, date)\n dputs __method__.to_s\n req = setup_http_request($search_req, @cookie, {:url_arg => [city_start, city_end, CGI.escape(date)]})\n res = @http.request(req)\n res=JSON.parse(res.body)['html']['results'].force_encoding('utf-8')\n results = []\n url = res.scan(/<meta itemprop=\"url\" content=\"([^>]*)\">/).flatten\n user = res.scan(/<div class=\"user-info\">\\s*<h2 class=\"username\">(.*)<\\/h2>\\s*/)#(.*)<br \\/>\\s*<\\/div>/)\n user = res.scan(/<strong class=\"MemberCard-name u-block\">([^<]*)<\\/strong>/).flatten\n user_bis = res.scan(/<h2 class=\"ProfileCard-info ProfileCard-info--name u-truncate\">\\s*(.*)\\s*<\\/h2>/).flatten\n users = user+user_bis\n #prefs = res.scan(/ <div class=\\\"preferences-container\\\">\\s*((?:<span class=\"[^ ]* prefs tip\" title=\".*\"><\\/span>)*)\\s*((?:<span class=\"[^ ]* prefs tip\" title=\".*\"><\\/span>)*)\\s*((?:<span class=\"[^ ]* prefs tip\" title=\".*\"><\\/span>)*)\\s*((?:<span class=\"[^ ]* prefs tip\" title=\".*\"><\\/span>)*)/)\n trip_time = res.scan(/<h3 class=\"time light-gray\" itemprop=\"startDate\" content=\"([^\"]*)\">\\s*(.*)\\s*<\\/h3>/)\n trip = res.scan(/<span class=\"from trip-roads-stop\">(.*)<\\/span>\\s*<span class=\"arrow-ie\">.*<\\/span>\\s*<span class=\"trip-roads-stop\">([^<]*)<\\/span>/)\n start = res.scan(/<dd class=\"js-tip-custom\" title=\"D.part\">\\s*(.*)\\s*<\\/dd>/).flatten\n stop = res.scan(/<dd class=\"js-tip-custom\" title=\"Arriv.e\">\\s*(.*)\\s*<\\/dd>/).flatten\n #car = res.scan(/<dd class=\"js-tip-custom\" title=\"Arriv.e\">\\s*.*\\s*<\\/dd>\\s*<\\/dl>\\s*((?:<dl class=\"car-type\" [^>]*>\\s*<dt>V.hicule : <strong>.*<\\/strong><\\/dt>)){0,1}/)\n #car = res.scan(/Véhicule : <strong>(.*)<\\/strong><\\/dt>/)\n place = res.scan(/<div class=\"availability\">\\s*<strong>(.*)<\\/strong>(?: <span>.*<\\/span>){0,1}/).flatten\n price = res.scan(/<div class=\"price price-[^\"]+\" itemprop=\"location\">\\s*<strong>\\s*<span class=\"\" >\\s*(\\d+)*<span class=\"size20\">(,[^<]*)<\\/span>/)\n acceptation = res.scan(/title=\"Acceptation : ([^\"]+)\"/).flatten\n url.each_with_index{|u, ind|\n results[ind] = {\n :url => u[ind],\n :user => users[ind],\n #:preferences => prefs[ind].map{|p| p.scan(/<span class=\".*\" title=\"(.*)\"><\\/span>/)}.flatten,\n :time => trip_time[ind].join(\" \"),\n :trip => trip[ind].join(\" -> \"),\n :start => start[ind],\n :stop => stop[ind],\n #:car => car[ind].first ==nil ? \"no info\" : car[ind].first.scan(/hicule : <strong>(.*)<\\/strong>/).flatten.first,\n :place => place[ind]==\"Complet\" ? \"Complet\" : \"%s disponible(s)\"%place[ind],\n :price => \"%s\" % price[ind].join(\"\"),\n :acceptation => acceptation[ind]\n }\n }\n puts \"[+] Got results\"\n results\n end",
"def trip_filters\n elems = []\n TimeFilterHelper.time_filters.each do |tf|\n elems << {\n :id => 100 + tf[:id],\n :value => tf[:value]\n }\n end\n TripPurpose.all.each do |tp|\n elems << {\n :id => tp.id,\n :value => TranslationEngine.translate_text(tp.name)\n }\n end\n return elems\n end",
"def filter_departures(departure_times,bartroute_options)\n\t\t# Filter the results of the real-time departures to find those that match the \n\t\t# route options. \n\n\t\tfiltered_departure_times = {}\n\n\t\tdeparture_times.each do |station,times|\n\t\t\tbartroute_options.each do |bartroute_station,v|\n\t\t\t\tif station == bartroute_station\n#\t\t\t\t\tstation_name = Bartstation.where(\"short_name = '#{bartroute_station}'\").pluck(\"station_name\")[0]\n\t\t\t\t\tstation_name = bartroute_station\n\t\t\t\t\tfiltered_departure_times[station_name] = times\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\treturn filtered_departure_times\n\tend",
"def listings\n @listings = trips.select do |trip|\n trip.listings\n end\n end",
"def index\n @genericcallouts = Genericcallout.all.paginate(:per_page =>15, :page => params[:page])\n .where(\"address ILIKE ?\",\"%#{params[:address_search]}%\").where(\"name ILIKE ?\",\"%#{params[:name_search]}%\").where(\"callback ILIKE ?\",\"%#{params[:phone_search]}%\").where(\"unitassigned ILIKE ?\",\"%#{params[:unit_search]}%\")\n end",
"def find_local_services(chosen_city_object, chosen_service_object_id)\n available_services = chosen_city_object.desired_service_deals(chosen_service_object_id) # creates an array deals on selected service & city\n end",
"def find_routes_for_from_and_to(from_city,to_city)\n\n # Finding all the line color routes where a souce city belongs\n line_route_ids = CityRoute.where(city_id: from_city).distinct.pluck(:line_color_route_id)\n \n @line_id = [] #For holding the line color route id after filtering\n \n line_route_ids.each do |a|\n\n if LineColorRoute.find_by(id: a).is_active\n\n # checking whether destination exits on that particular line route or not\n var_to = LineColorRoute.find(a).city_routes.where(city_id: to_city)\n if var_to.present? \n var_from = LineColorRoute.find(a).city_routes.where(city_id: from_city)\n\n\n #checking the allowed direction of travel and saving the valid result in @line_id\n if (var_to.last.id - var_from.first.id) > 0\n # p \"------There is a route(#{LineColorRoute.find(a).name})--------------\"\n @line_id << a\n end \n else\n # p \"-------error----------\"\n end\n\n end\n\n end\n end",
"def index\n @trip_routes = TripRoute.all\n end",
"def listings\n trips.map {|trip| trip.listing}\nend",
"def search\n @routes_title = \"Routes\"\n\n @order = params[:order] || 'name'\n @page = params[:page] || '1'\n @asc = params[:asc] || 'asc'\n\n @routes = Route.search(params[:search]).all(:include => [:waypoints, :user, :comments, :favoriters]).paginate(\n :paginate => '10',\n :page => @page,\n :order => @order + \" \" + @asc)\n\n # Versión de searchlogic pero implica modificar la paginación\n # se debe utilizar la que implemente searchlogic\n # @routes = Route.all(:include => :locations,\n # :conditions =>compute_searchlogic_conditions(params[:search]),\n # :per_page => 10,\n # :page => @page,\n # :order_by => @order,\n # :order_as => @asc\n # )\n\n respond_to do |format|\n format.html { render :template => \"routes/index\"}\n format.xml { render :xml => @routes }\n end\n end",
"def listings\n self.trips.map {|trip| trip.listing}.uniq\n end",
"def serviceIndex\n myService = Service.find_by_id(params[:id])\n @serviceSessions = Session.where(service_id: myService.id, is_completed: false)\n end",
"def listings\n arr = []\n Trips.all.each do |trip|\n if trip.guest == self\n arr << trip.listing\n end\n end\n arr\n end",
"def trulia_listings(company_id, search_params)\n\t\tsearch_params[:has_primary_agent] = 1\n\t\tsearch_params[:exclusive] = 1\n\t\t# search_params[:is_hide_on_website] = 1\n\t\tsearch_params[:must_have_description] = 1\n\t\tsearch_params[:must_have_streeteasy_flag] = 1\n\t\tsearch_params[:has_hide_from_agent] = 1\n\t\tpull_data(company_id, search_params)\n\tend",
"def listings\n Trip.all.map do |trip|\n if trip.guest == self\n return trip.listing\n end\n end\n end",
"def index\n sanitized = whitelist(params, :index)\n\n # Extract travels\n if sanitized[:user_id]\n # As to Rails 4 doesn't have support for OR operator\n # @travels = Travels::Travel.submitted.where(\"customer_id = ? OR performer_id = ?\", sanitized[:user_id], sanitized[:user_id])\n @travels = Travels::Travel.of(current_user)\n else\n @travels = Travels::Travel.all\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { as_json @travels }\n end\n end",
"def listings\n Trip.all.select do |listing|\n listing.guest == self\n end\n end",
"def search_directions\n @query = 1\n @error = 0\n @departure_address = params[:departure_address]\n @arrival_address = params[:arrival_address]\n bus_transit = params[:bus_transit]\n train_transit = params[:train_transit]\n metra_transit = params[:metra_transit]\n @preferred = params[:preferred]\n apikey = \"AIzaSyCDeWWmT-KYmsgSz9d2vCy0KcOmJe114y4\"\n\n if @departure_address != \"\" && @arrival_address != \"\"\n url_safe_dep = URI.encode(@departure_address)\n url_safe_arr = URI.encode(@arrival_address)\n @type_transport = ''\n\n if !bus_transit.nil?\n @type_transport = bus_transit\n end\n\n if !train_transit.nil?\n @type_transport += \"|\" + train_transit\n end\n\n if !metra_transit.nil?\n @type_transport += \"|\" + metra_transit\n end\n\n if !@type_transport != '' && !@preferred.nil? && @preferred != \"\"\n url_safe_typ = URI.encode(@type_transport)\n url_safe_pref = URI.encode(@preferred)\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true&transit_mode=#{@url_safe_typ}&transit_routing_preference=#{url_safe_pref}&key=#{apikey}\"\n\n elsif !@type_transport != ''\n url_safe_typ = URI.encode(@type_transport)\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true&transit_mode=#{url_safe_typ}&key=#{apikey}\"\n\n elsif !@preferred.nil? && @preferred != \"\"\n url_safe_pref = URI.encode(@preferred)\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true&transit_routing_preference=#{url_safe_pref}&key=#{apikey}\"\n else\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true\"\n end\n\n @directions = JSON.parse(open(apiLink).read, object_class: OpenStruct)\n\n if @directions.status == \"OK\"\n @routes = @directions.routes\n @error = 0\n else\n @message = \"No station found, try again\"\n @error = 1\n end\n else\n @message = \"Please enter a value for departure and arrival address\"\n @error = 1\n end\n\n #render :json => @routes\n render 'directions'\n end",
"def query_by_date\n # find the wdays of the trip\n dates = dates_to_wdays(\n Date.parse(params[:from]),\n Date.parse(params[:to])\n )\n\n # find schedules that fit the wdays of the trip\n schedules = Schedule.where.overlap(wdays: dates)\n\n respond_with TripsBySchedulePresenter.new(schedules).as_json\n end",
"def index\n if params[:route_point_id]\n @search = Order.available_for_user(current_user).belongs_to_route_point(params[:route_point_id]).search(params[:q])\n @orders = @search.result.page(params[:page]).per(current_user.list_page_size)\n else\n @search = Order.available_for_user(current_user).search(params[:q])\n @orders = @search.result.page(params[:page]).per(current_user.list_page_size)\n end \n \n @managers = Manager.all\n @warehouses = Warehouse.all\n @price_lists = PriceList.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @orders }\n format.xml # index.xml.erb\n end\n end",
"def index\n @services = Service.active.without_referrer.order_by(position: :asc)\n @referrer_services = Service.active.with_referrer.order_by(position: :asc) if current_user&.referrer?\n # brand querying\n if brand\n @services = @services.with_brand(brand)\n @referrer_services = @referrer_services.with_brand(brand) if current_user&.referrer?\n end\n\n @brand_filters = Brand.with_services.order_by(position: :asc).used_as_filters\n end",
"def filtering_params(params)\n params.slice(:desired_location, :max_price_dollars, :tour_name, :earliest_start, :latest_end, :min_seats)\n end",
"def trips \n Trips.all.each do |trip|\n trip \n end \n\n #return to airbnb\n \n\n\n \nend",
"def find_trip\n @trip = Trip.find(params[:id])\n end",
"def index\r\n if params[:group_name]\r\n @trips = Trip.search(params[:group_name])\r\n else\r\n @trips = Trip.all\r\n end\r\n end",
"def all_trips\n return Rideshare::Trip.find_trip_by_rider(@id)\n end",
"def filter_by_area\n loc_ids=Area.new(params[:area_tl],params[:area_br]).locations.collect {|loc| loc.id}\n @locations=@locations.where(id: loc_ids)\n end",
"def load_triphops\n\n sid_numbers = load_service_ids\n\n triphops = {}\n print \"Querying Triphops\\n\"\n stop_times = conn.exec <<-SQL\n SELECT t1.trip_id,\n t1.stop_id AS from_id,\n t2.stop_id AS to_id,\n t1.departure_time,\n t2.arrival_time,\n-- t1.stop_sequence,\n gtf_trips.service_id\n FROM gtf_stop_times AS t1,\n gtf_stop_times AS t2,\n gtf_trips\n WHERE t2.trip_id = t1.trip_id AND\n t2.stop_sequence = t1.stop_sequence+1 AND\n t1.trip_id = gtf_trips.trip_id\n ORDER BY trip_id, t1.stop_sequence\n SQL\n print \"done\\n\"\n\n #load frequencies from frequencies table\n frequencies = load_frequencies\n\n print \"Interpolating and sorting triphops\\n\"\n n=stop_times.num_tuples\n i=0\n prev_timed=0\n stop_times.each do |trip_id, from_id, to_id, departure_time, arrival_time, service_id|\n if departure_time then\n # Looks for dep=something arr=something pattern, which triggers regular behaviour\n if arrival_time then\n schedule_key = [from_id, to_id, sid_numbers[service_id]]\n triphops[schedule_key] ||= []\n dt = GoogleTransitFeed::parse_time( departure_time )\n at = GoogleTransitFeed::parse_time( arrival_time )\n # If the trip has an associated frequency\n if frequencies[trip_id] then\n frequencies[trip_id].each do |f|\n triphops[schedule_key] << [dt + f, at + f , trip_id ]\n end\n else\n triphops[schedule_key] << [dt, at, trip_id ]\n end\n # Looks for dep=something arr=nil pattern\n else # if arrival_time\n prev_timed=i\n end # if arrival_time\n else # if departure_time\n # Looks for dep=nil arr=something pattern which triggers interpolation\n if arrival_time then\n first_time = GoogleTransitFeed::parse_time( stop_times[prev_timed][3] )\n last_time = GoogleTransitFeed::parse_time( stop_times[i][4] )\n # The time step is linearly interpolated (not based on distance)\n step = (last_time-first_time)/(i-prev_timed+1)\n dep_time = first_time\n arr_time = dep_time + step\n # Interpolate times and feed triphops hash\n for j in prev_timed..i\n schedule_key = [stop_times[j][1], stop_times[j][2], sid_numbers[service_id]]\n triphops[schedule_key] ||= []\n # If the trip has an associated frequency\n if frequencies[trip_id] then\n frequencies[trip_id].each do |f|\n triphops[schedule_key] << [dep_time + f, arr_time + f, trip_id ]\n end\n else\n triphops[schedule_key] << [dep_time, arr_time, trip_id ]\n end\n dep_time = arr_time\n arr_time += step\n end\n end # if arrival_time\n\n end # if departure_time\n i += 1\n if i%1000==0 then $stderr.print( sprintf( \"\\rChecked %d/%d trip hops (%d%%)\", i, n, (i.to_f/n)*100 ) ) end\n end #stop_times.each\n $stderr.print( \"...done\\n\" )\n\n return triphops\n end",
"def filterHotDogStandsByFoodPreferences(httpRequestParameters)\n # Only apply the filters if the user has selected what foods they prefer.\n if httpRequestParameters[\"selectedFoods\"][\"length\"].to_i > 0\n httpRequestParameters[\"selectedFoods\"][\"values\"].each do |foodIndex|\n # Upon every preferred food selected, if the user has specified a price range, apply a filter that not only\n # checks to see if the food exists in the set of food prices, but also to see if the food price is within\n # the price range the user has specified. Otherwise, only apply the filter to see if the food exists in\n # the set of food prices.\n if httpRequestParameters[\"isAPriceRangeSpecified\"] === \"true\"\n @searchQuery = @searchQuery.where(\"exists (select * from food_prices where food_id = ? and \" + \\\n \"food_prices.hot_dog_stands_id = hot_dog_stands.id and food_prices.price >= ? and food_prices.price <= ?)\", \\\n foodIndex, httpRequestParameters[\"minimumItemPrice\"].to_f, httpRequestParameters[\"maximumItemPrice\"].to_f)\n else\n @searchQuery = @searchQuery.where(\"exists (select * from food_prices where food_id = ? and \" + \\\n \"food_prices.hot_dog_stands_id = hot_dog_stands.id)\", foodIndex)\n end\n end\n end\n end",
"def search_route_point\n (lat, lon) = params[:point].split(\",\")\n radius = params[:radius]\n\n results = Route.select(\"distinct name_route, cod_route\")\n .where(\"ST_DWithin('POINT(#{lat} #{lon})', path, ?)\", \"#{radius}\")\n render json: results\n end",
"def search(transactions)\n return transactions.select{|el| el.sender_id.to_s.starts_with?(params[:search_transaction]) || \n el.receiver_id.to_s.starts_with?(params[:search_transaction]) || \n el.amount.to_s.starts_with?(params[:search_transaction]) || \n el.created_at.to_s.starts_with?(params[:search_transaction])}\n end",
"def rentals_search(options = {}, &block)\n ids = Array(options.delete(:ids))\n path = reject_blank_values([\"rentals\", ids.join(\",\"), \"search\"]).join(\"/\")\n defaults = { request_method: :post }\n paginate path, defaults.merge(options), &block\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.5392964",
"0.5306047",
"0.5303117",
"0.52990925",
"0.5284211",
"0.5277499",
"0.52070683",
"0.52033746",
"0.52005994",
"0.51754236",
"0.51743317",
"0.5171799",
"0.5163706",
"0.51628643",
"0.51563436",
"0.5154582",
"0.5138584",
"0.5108432",
"0.5101181",
"0.50881505",
"0.50664556",
"0.50609887",
"0.50361097",
"0.50267845",
"0.49952883",
"0.4994407",
"0.49891353",
"0.49877325",
"0.4963319",
"0.49556708",
"0.49553633",
"0.49463814",
"0.4946289",
"0.49215257",
"0.49141422",
"0.49013153",
"0.4897678",
"0.48783398",
"0.48679543",
"0.4862317",
"0.4852679",
"0.48491102",
"0.48447353",
"0.48430893",
"0.48387983",
"0.48182812",
"0.48111606",
"0.4804058",
"0.4796455",
"0.47960457",
"0.47951558",
"0.47912142",
"0.47826067",
"0.47820014",
"0.47757283",
"0.47752452",
"0.47702208",
"0.47620487",
"0.4752464",
"0.47395462",
"0.47386986",
"0.4725688",
"0.4719011",
"0.47136343",
"0.47088233",
"0.47008896",
"0.46949622",
"0.46930707",
"0.46842727",
"0.4681847"
] | 0.8140789 | 0 |
FYI The methods below are basically just glorified getters from the | def trips(opts = {})
begin
ret_stops = @gtfs_parser.parse_file(@data_dir + @@trips_file)
rescue CSV::MalformedCSVError
raise "InvalidCSV"
end
ret_stops
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def getters; end",
"def private; end",
"def methods; end",
"def methods; end",
"def methods; end",
"def methods; end",
"def get()\n \n end",
"def getter_method_names; end",
"def specie; end",
"def specie; end",
"def specie; end",
"def specie; end",
"def properties; end",
"def properties; end",
"def properties; end",
"def properties; end",
"def properties; end",
"def properties; end",
"def properties; end",
"def properties; end",
"def methods() end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attributes; end",
"def attribute; end",
"def attribute; end",
"def attribute; end",
"def attribute; end",
"def attribute; end",
"def attribute; end",
"def attribute; end",
"def transferred_properties; end",
"def transferred_properties; end",
"def probers; end",
"def who_we_are\r\n end",
"def formation; end",
"def get_actual\n end",
"def implementation; end",
"def implementation; end",
"def attr_reader(*)\n end",
"def reflection; end",
"def reflection; end",
"def custom; end",
"def custom; end",
"def get(object); end",
"def get\n raise NotImplementedError\n end",
"def values_for_properties; end",
"def fields; end",
"def fields; end",
"def fields; end",
"def inspect()\n #This is a stub, used for indexing\n end",
"def value() end",
"def overrides; end",
"def get; end",
"def public; end",
"def public; end",
"def extra; end",
"def attr; end",
"def getc()\n #This is a stub, used for indexing\n end",
"def details; end",
"def operations; end",
"def operations; end",
"def public_method; end",
"def accessibility; end",
"def private_method\n end",
"def internal_methods; end",
"def delegate_object_reader_method; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def value; end",
"def instance_methods; end",
"def get_info\n end",
"def get_info\n end",
"def get_info\n end"
] | [
"0.7597988",
"0.7509741",
"0.667236",
"0.667236",
"0.667236",
"0.667236",
"0.65832084",
"0.65743643",
"0.6520891",
"0.6520891",
"0.6520891",
"0.6520891",
"0.64719146",
"0.64719146",
"0.64719146",
"0.64719146",
"0.64719146",
"0.64719146",
"0.64719146",
"0.64719146",
"0.6423191",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.6358467",
"0.63310933",
"0.63310933",
"0.63310933",
"0.63310933",
"0.63310933",
"0.63310933",
"0.63310933",
"0.6281339",
"0.6281339",
"0.6247895",
"0.6237244",
"0.61732435",
"0.61666495",
"0.61633146",
"0.61633146",
"0.61547947",
"0.61392677",
"0.61392677",
"0.6138421",
"0.6138421",
"0.6135491",
"0.61311424",
"0.6126978",
"0.6099471",
"0.6099471",
"0.6099471",
"0.6097819",
"0.6080955",
"0.607961",
"0.60539347",
"0.6046436",
"0.6046436",
"0.6034529",
"0.6028252",
"0.60260624",
"0.6016556",
"0.6007279",
"0.6007279",
"0.6005766",
"0.60045725",
"0.5999609",
"0.59978634",
"0.5984444",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5970578",
"0.5948567",
"0.593296",
"0.593296",
"0.593296"
] | 0.0 | -1 |
private def user_params params.require(:user).permit(:firstName, :lastName, ) end | def show
if (session[:user_id] == nil)
flash[:alert] = "You are not logged in";
redirect_to login_path
else
@user = User.find(session[:user_id])
@events = @user.events
@points = @user.getPoints
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def user_params\n params.require(:user).permit(:first_name, :last_name)\n end",
"def user_params\n params.require(:user).permit(:firstname, :lastname)\n end",
"def user_params\n params.require(:user).permit(:email, :password, :password_confirmation, :firstName, :lastName) \n end",
"def user_params\n params[:user].permit(\n :first_name,\n :last_name\n )\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name)\n end",
"def user_params\n params.require(:user).permit(:first_name, :surname)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :username, :email)\n end",
"def user_params\n params.require(:field).permit(:first_name, :last_name)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password)\n end",
"def user_params\n params.permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.require(:user).permit(:firstname, :lastname, :email, :password)\n end",
"def user_params\n params.require(:user).permit(:id, :firstName, :lastName, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password,\n :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password,\n :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password )\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password,)\n end",
"def user_params\n params.require(:user).permit(:email, :name, :firstname)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.require(:user).permit :first_name, :last_name, :email, :password\n end",
"def user_params\n params\n .require(:user)\n .permit(\n :title,\n :first_name,\n :last_name,\n )\n end",
"def user_params\n params.require(:users).permit(:_id, :firstName, :lastName, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :username, :password)\n end",
"def user_params\n\t\tparams.permit(:first_name, :last_name, :email, :password, :password_confirmation)\n\tend",
"def user_params\n\t\tparams.permit(:first_name, :last_name, :email, :password, :password_confirmation)\n\tend",
"def user_params\n params.require(:user).permit(:firstname, :lastname, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:email, :first_name, :last_name)\n end",
"def user_params\n \tparams.require(:user).permit(:first_name, :last_name, :email, :phone, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:firstName, :lastName, :email, :password, :password_confirmation, :userType, :dob, :bio)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :nickname)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :password, :phone)\n end",
"def user_params\n params.require(:user).permit(:username,\n :email, \n :password,\n :password_confirmation,\n :firstname,\n :lastname,)\n end",
"def user_params\n params.permit(:first_name, :last_name, :gender, :phone)\n end",
"def user_attributes\n params.permit(:first_name,\n :last_name, :description)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password,\n :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:username, :password, :firstname, :lastname, :email)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :user_name, :email, :password)\n end",
"def user_params\n params.require(:user).permit :email, :password, :password_confirmation, :first_name, :last_name, :other_name\n end",
"def user_params\n params.require(:user).permit :email, :password, :password_confirmation, :first_name, :last_name, :other_name\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :display_name, :street_address, :zip, :city, :state, :email, :phone)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :birth_date, :gender, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :description, :email, :password) #devise is requiring email and password FYI!\n end",
"def user_params\n params.require(:user).permit(:id, :first_name, :last_name, :email, :username)\n end",
"def user_params\n params.require(:user).permit(:username, :firstname, :lastname, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:email, :password, :first_name, :last_name)\n end",
"def user_params\n params.require(:user)\n .permit(:first_name, :last_name, :email, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(\n :username,\n :first_name, \n :mid_name, \n :last_name,\n :email,\n :birthday,\n :cellphone_number,\n :telephone_number,\n :address,\n :date_start,\n :gender\n )\n end",
"def user_params\n params.require(:user).permit(\n :first_name,\n :last_name,\n :email,\n :tel_no,\n :username,\n :password\n )\n end",
"def user_params\n params.require(:user).permit(:full_name, :username)\n end",
"def user_params\n params.require(:user).permit(:firstname, :lastname, :phone_number, :mobile_number)\n end",
"def user_params\n params.require(:user).permit(\n :first_name, :middle_name, :last_name, :suffix, :date_of_birth,\n :gender, :phone, :permission_to_text, :email, :permission_to_email,\n :address_line_1, :address_line_2, :city, :state, :zip_code,\n :license_plate, :seniors_in_household, :adults_in_household,\n :children_in_household\n )\n end",
"def user_params\n # NOTE: name is allowed because one field exists on signup\n params.require(:user).permit(:name, :first_name, :last_name, :email, :password, :password_confirmation, :phone)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password)\n \n # Basically, it works like this, we require the 'user' key, so this throws out an error if we don't get that, which we are given from the form. Next, we chain the .permit, after that .require, so after requiring the 'user' key from the associative array format that the data is sent over in, we permit/allow or choose which keys will be sent through, anything not in the permit section will just be ignored and lost.\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :zipcode, :password, :password_confirmation)\n end",
"def user_params\n\t\t\tparams.require(:user).permit(:username, :first_name, :last_name, :password, :password_confirmation)\n\t\tend",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :username, :email, :password, :city, :state, :birth_year, :birth_day, :about_me)\n end",
"def user_params\n params.require(:user).permit(:fname, :lname, :email, :password)\n end",
"def user_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation, :first_name, :last_name)\n end",
"def user_params\n params.require(:user).permit(:email, :password, :birthday, :firstname)\n end",
"def user_params\n params.require(:user).permit(:username, :first_name, :last_name, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :phone_number, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:firstname, :lastname, :displayname, :mobile_number, :email, :phone_number, :country_code )\n end",
"def user_params\n params.require(:user).permit(:email, :password, :password_confirmation, :first_name, :last_name, :description)\n end",
"def user_params\n params.require(:user).permit(:name, :last_name, :email, :password, :phone)\n end",
"def user_params\n params.require(:user).permit(:name, :last_name, :email, :password, :phone)\n end",
"def user_params\n params.require(:user).permit(:fName, :lName, :age)\n end",
"def user_params\n params.require(:user).permit(:email, :password, :first_name, :last_name, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(:email, :username, :password, :password_confirmation, :familyname, :givenname)\n end",
"def new_user_params\n params[:user].permit(:first_name, :last_name, :email)\n end",
"def user_params\n params.fetch(:user, {}).permit(:first_name, :last_name, :email, :birthdate, :address1, :address2, :city, :state, :zip, :phone, :emergency_contact, :emergency_phonera)\n end",
"def user_params\n params.require(:user).permit(:name, :last_name, :age, :email, :notes)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :phone, :description, :admin)\n end",
"def user_params\n params.require(:user).permit(:first_name, :admin)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :street, :neighborhood,\n\t\t\t\t\t\t\t\t\t:city, :state, :zip_code, :telephone,\n\t\t\t\t\t\t\t\t\t:people_living, :rooms, :wall_material, :roof_material,\n\t\t\t\t\t\t\t\t\t:floor_material, :build_yourself, :store)\n end",
"def user_params\n params.require(:user).permit(:firstname, :lastname, :email, :role, :password, :active)\n end",
"def user_params\n params.require(:user).permit(:username, :fullname, :email)\n end",
"def user_params\n params.require(:user).permit(:fullname, :email, :username, :password)\n end",
"def user_params\n params.require(:user).permit(:firstName, :lastName, :pin, :email, :password, :password_confirmation, :role)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :username, :email, :admin, :password, :password_confirmation, :activated)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :phone, :position, :salary, :department)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :bio, :photo_url)\n end",
"def user_params\n params.require(:user).permit(:display_name, :family_name, :first_name, :email, :student_number, :phone, :password, :password_confirmation)\n end",
"def user_params\n params.require(:user).permit(\n :firstName, \n :lastName, \n :email, \n :password, \n :password_confirmation, \n :ethAdd, \n :bitAdd, \n :estimatedContribution, \n :phoneNumber,\n :address1,\n :address2,\n :city,\n :state,\n :zipCode,\n :dob,\n :citizenship,\n :ethAdd,\n :socialsecurity,\n :equityOwners,\n :entityType)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :username, :dob, :profile_picture, :email, :password, :password_confirmation, :admin)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, \n :middle_name, :gender, :age, :birthday, :anniversary, :occupancy, \n :marital_status, :mobile, :region, :country, :state, :city, :street,\n :address, :pincode, :latitude, :locality, :longitude, :accuracy, :altitude)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name,\n :email, :password, :password_confirmation, :omniauth)\n end",
"def user_params\n params.require(:user).permit(:first_name, :last_name, :country_code, :phone_number, :avatar, :description, :password_digest, :password, :password_confirmation)\n end"
] | [
"0.94102263",
"0.9395141",
"0.93017864",
"0.93015873",
"0.9288069",
"0.9209122",
"0.92067933",
"0.9199963",
"0.91942114",
"0.91783005",
"0.91783005",
"0.91783005",
"0.91783005",
"0.91672474",
"0.91672474",
"0.9137191",
"0.91322863",
"0.91108054",
"0.90707314",
"0.9061668",
"0.905426",
"0.905426",
"0.90540206",
"0.9044305",
"0.90440434",
"0.90438133",
"0.9041935",
"0.90359294",
"0.901868",
"0.90179974",
"0.90175635",
"0.90136623",
"0.90136623",
"0.9009954",
"0.8990702",
"0.89841706",
"0.89676",
"0.8963583",
"0.8963583",
"0.8963583",
"0.8963583",
"0.89628196",
"0.8950497",
"0.89464366",
"0.8935096",
"0.8924231",
"0.8921507",
"0.8914952",
"0.89140713",
"0.89127344",
"0.88988143",
"0.887015",
"0.887015",
"0.88572973",
"0.8856327",
"0.88514704",
"0.884884",
"0.8847727",
"0.88355845",
"0.8822396",
"0.8821015",
"0.8811966",
"0.88070375",
"0.8795026",
"0.8792155",
"0.87834847",
"0.87828684",
"0.8782582",
"0.8777643",
"0.87773705",
"0.87712336",
"0.8761919",
"0.8761203",
"0.87563294",
"0.8736991",
"0.87348235",
"0.8729208",
"0.8720748",
"0.8720748",
"0.87133193",
"0.8713249",
"0.8704532",
"0.8694859",
"0.86901015",
"0.8674816",
"0.86731213",
"0.86644804",
"0.8661834",
"0.8660826",
"0.8659744",
"0.86469555",
"0.8642159",
"0.86401016",
"0.86399084",
"0.86329174",
"0.862848",
"0.86266345",
"0.8626255",
"0.8625143",
"0.86237156",
"0.86078215"
] | 0.0 | -1 |
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",
"def read_html\n array = nodes.to_a\n array.each_with_index do |node, index|\n header = (index.modulo(10) == 0) ? \"<h2>!!!!!SLOW DOWN AND ENUNCIATE!!!!!</h2>\" : \"\"\n anchor = \"<a id=section_#{index} href=/pages/#{self.id}/edit?section=#{index}>#{index}</a>\"\n type = nodes.at(index).name\n array[index]=nodes.at(index).replace \"#{header}<#{type}>#{anchor} #{nodes.at(index).inner_html}</#{type}>\"\n end\n array.map(&:to_html).join\n end",
"def print_text_statistics (text)\n\n=begin\n\t\ttext = ''\n\t\tline_count = 0\n\t\tFile.open(\"text.txt\").each do |line|\n\n\t\t\tline_count += 1\n\t\t\ttext << line\n\t\tend #Here I'm using the File class's .open(dir) to open up a file\n\t\t #that is located at an specific directory and then I'm looping\n\t\t #trough its content with a .each{} method.\n\t\t#puts \"#{line_count} lines\"\n=end\n\n\t#the File class has a method that allows you to read the lines on a text file more efficiently\n\t#it has the .readlines(dir); this method returns an array with the readed file\n\tstop_words = %w{the a by on for of are just with but and to the my I has some in}\n\tline = File.readlines(text[0]) #receives the parameter passed on the command line and holds it into the first \n\t #position of the ARGV array. This is an special array\n\tline_count = line.size\n\ttext = line.join\n\ttotal_characters = text.length\n\ttotal_characters_nospace = text.gsub(/\\s+/,'').length\n\tword_count = text.split.length\n\tparagraph_count = text.split(/\\n\\n/).length\n\tsentence_count = text.split(/\\?|\\.|!/).length\n\tall_words = text.scan(/\\w+/)\n\tgood_words = all_words.select {|word| !stop_words.include?(word)} #the .select method can be applied to arrays,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #hases and ranges and is used to return an object of those types\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #that stiesfied the conditional statement written whithin the blockb (it's a filter)\n\tgood_percentage = ((good_words.length.to_f/all_words.length.to_f)*100).to_i\n\tsentences = text.gsub(/\\s+/,' ').strip.split(/\\?|\\.|!/) #strip deletes the first and the last blank strip of spaces\n\tsentences_sorted = sentences.sort_by { |sentence| sentence.length } #sort an array, hash or range, by defining \n\t #a condition whithin the block. array.sort_by { |item| <condition> }\n\tone_third = sentences_sorted.length/3\n\tideal_sentences = sentences_sorted.slice(one_third, one_third + 1).select { |sentence| sentence =~ /is|are/}\n\n\tputs \"#{line_count} lines\"\n\tputs \"#{total_characters} characters\"\n\tputs \"#{total_characters_nospace} characters (excluding spaces)\"\n\tputs \"#{word_count} words\"\n\tputs \"#{paragraph_count} paragraphs\"\n\tputs \"#{sentence_count} sentences\"\n\tputs \"#{(sentence_count/paragraph_count).to_f} sentences per paragraph (average)\"\n\tputs \"#{(word_count/paragraph_count).to_f} words per paragraph (average)\"\n\tputs \"#{good_percentage}% of words are non fluff-words\"\n\tputs \"Summary:\\n\\n#{ideal_sentences.join('.')}\"\n\tputs \"-- End of analysis\"\n\nend",
"def generate_html\n # the individual descriptions for files and classes\n gen_into(@files)\n gen_into(@classes)\n # and the index files\n gen_file_index\n gen_class_index\n gen_method_index\n gen_main_index\n\n # this method is defined in the template file\n write_extra_pages if defined? write_extra_pages\n end",
"def ris(document)\n\t\t\tprint \".\"\n\t\t\t# Store raw HTML into local variable\n\t\t\t# Based on MIME type, invoke the proper processing modules\n\t\t\tcase document.content_type\n\t\t\t\twhen \"text/html\"\n\t\t\t\t\tlink_extractor(document)\n\t\t\t\t\tprocess_html(document)\n\t\t\t\t\tpage_meta(document)\n\t\t\t\telse\n\t\t\t\t\tprint \"... not HTML, skipping...\"\n\t\t\tend\n\t\tend",
"def htmlise(m)\n m2 = m.gsub(/<hr>[ \\r]*\\n/,'<hr>').\n gsub(/\\\\\\][ \\r]*\\n/,'\\] ').\n gsub(/\\$\\$[ \\r]*\\n/,'$$ ').\n gsub(/<\\/h2>[ \\r]*\\n/,'</h2>').\n gsub(/<\\/h3>[ \\r]*\\n/,'</h3>').\n gsub(/<\\/h4>[ \\r]*\\n/,'</h4>').\n gsub(/<\\/ol>[ \\r]*\\n/, '</ol>').\n gsub(/\\n[ \\r]*<\\/ol>/, '</ol>').\n gsub(/<\\/ul>[ \\r]*\\n/, '</ul>').\n gsub(/\\n[ \\r]*<\\/ul>/, '</ul>').\n gsub(/\\n[ \\r]*<li>/, '<li>').\n gsub(/<evidence>[ \\r]*\\n/, '<evidence>').\n gsub(/<\\/evidence>[ \\r]*\\n/, '</evidence>').\n gsub(/<evidence>/, '<div class=\"evidence\">').\n gsub(/<\\/evidence>/, '</div>').\n gsub(/<\\/result>[ \\r]*\\n/, '</result>').\n gsub(/<\\/proof>[ \\r]*\\n/, '</proof>').\n gsub(/<\\/remark>[ \\r]*\\n/, '</remark>').\n gsub(/<statement>[ \\r]*\\n/, '<statement>')\n \n while m2.sub!(/<result>(.*?)<statement>(.*?)<\\/result>/mi) {\"<div class='result-title'>#{$1}</div><div class='result-content'>#{$2}</div>\"}\n end\n \n while m2.sub!(/<proof>(.*?)<statement>(.*?)<\\/proof>/mi) {\"<div class='proof-title'>#{$1}</div><div class='proof-content'>#{$2}</div>\"}\n end\n \n while m2.sub!(/<remark>(.*?)<statement>(.*?)<\\/remark>/mi) {\"<div class='remark-title'>#{$1}</div><div class='remark-content'>#{$2}</div>\"}\n end\n \n return m2.gsub(/\\n/, '<br/>')\n end",
"def score\n documented = @files.inject(0) {|sum, file| sum += file.total_documented }\n total = @files.inject(0) {|sum, file| sum += file.total_entities }\n ((documented.to_f / total) * 100).to_i\n end",
"def replace(content)\n \n # pre-structuring\n content.gsub!( /^(\\w.*)\\n(\\w.*)/ ) { \"#{$1} #{$2}\" } # remove single line breaks between text in order to avoid false paragraph markup\n content.gsub!( /<!--/ ) { \"--\" } # replace opening html commentaries\n content.gsub!( /-->/ ) { \"--\" } # replace closing html commentaries\n \n # templates\n content.gsub!( /\\{\\{Zitat\\|(.*)\\|.*\\}\\}\\s*$\\n/ ) { \"\\{p\\}\\\"#{$1}\\\"\\{/p\\}\\n\" } # citation\n content.gsub!( /\\{\\{.*(Finale Version).*\\}\\}/ ) { \"{status}<font color=\\\"#FF0000\\\">#{$1}</font>{/status}<br>\" } # final version\n content.gsub!( /\\{\\{Vorlage:(Dokument.*)\\n*(.*)\\}\\}/ ) { \"{status}<font color=\\\"#FF0000\\\">#{$1} #{$2}</font>{/status}<br>\" } # document status\n content.gsub!( /\\{\\{.*\\}\\} *$/ ) { '' } # remove single line templates\n content.gsub!( /\\{\\{.*\\n?.*\\}\\} *$/ ) { '' } # remove all remaining templates\n \n # tags\n content.gsub!( /<nowiki>(.*?)<\\/nowiki>/ ) { \"<pre>#{$1}</pre>\" }\n content.gsub!( /^ +(.*)/ ) { \"<pre>#{$1}</pre>\" }\n\n # special markup of qualidative data analysis\n content = content + \"\\n\\n{!end}\"\n \n # categories\n content.gsub!( /\\[\\[Kategorie:(.*?)\\]\\]/i ) { \"{category}<font color=\\\"#FF0000\\\">Kategorie:#{$1}</font>{/category}<br>\" }\n \n # images\n content.gsub!( /\\[\\[Bild:(.*?)\\]\\]/i ) { \"{image}Bild:#{$1.gsub!(/.*\\|/,'')}{/image}<br>\"} # Bild:lpscreen.jpg|thumb|Bereichseite des Landesportals\n\n # bold\n content.gsub!(/'''(.*?)'''/) {\"<strong>#{$1}</strong>\"}\n content.gsub!(/'''(.*?)$/) {\"<strong>#{$1}</strong>\"}\n\n # italics\n content.gsub!(/''(.*?)''/) {\"<em>#{$1}</em>\"}\n content.gsub!(/''(.*?)$/) {\"<em>#{$1}</em>\"}\n\n # headings\n 6.downto(1) { |i| content.gsub!( /^={#{i}}(.*?)={#{i}} *$/ ) { \"<h#{i}>\\{h>#{i}\\}#{$1}\\{/h>#{i}\\}</h#{i}>\" } }\n \n # links, internal\n content.gsub!( /\\[\\[([^\\[\\n]*?)\\| *(.*?)\\]\\]/ ) { \"<a class=\\\"internal\\\" href=\\\"#{$1}\\\">#{$2}</a>\" } # with piped text\n content.gsub!( /\\[\\[(.*?)\\]\\]/ ) { \"<a class=\\\"internal\\\" href=\\\"#{$1}\\\">#{$1}</a>\" } # without piped text\n\n # links, external\n content.gsub!( /\\[([^\\[\\n]*?)\\| *(.*?)\\]/ ) { \"<a class=\\\"external\\\" href=\\\"#{$1}\\\">#{$2}</a>\" } # with piped text\n content.gsub!( /\\[(.*?)\\]/ ) { \"<a class=\\\"external\\\" href=\\\"#{$1}\\\">#{$1}</a>\" } # without piped text\n \n # lists\n content.gsub!(/^:+/,'') # remove forced indenting\n content.gsub!( /^((?:\\*.*\\n+)+)/ ) { \"\\{l>ul\\}<ul>\\n#{$1.split(/\\n/).collect { |line| \"<li>#{line.gsub!(/^\\*/,'')}</li>\\n\" }.join}</ul>\\{/l>ul\\}<br>\\n\" } # first level ul\n content.gsub!( /^((?:#.*\\n+)+)/ ) { \"\\{l>ol\\}<ol>\\n#{$1.split(/\\n/).collect { |line| \"<li>#{line.gsub!(/^#/,'')}</li>\\n\" }.join}</ol>\\{/l>ol\\}<br>\\n\" } # first level ol\n content.gsub!( /<li>\\s*<\\/li>\\n/ ) { '' } # remove empty list entries (this may occur if first-level wiki-lists are entered with \\n\\n; they look like a single list when, in fact, they are but multiple single lists)\n content.gsub!( /^((?:<li>\\*.*\\n+)+)/ ) { \"<ul>\\n#{$1.gsub(/^<li>\\*/,\"<li>\")}</ul>\\n\" } # second level ul\n content.gsub!( /^((?:<li>#.*\\n+)+)/ ) { \"<ol>\\n#{$1.gsub(/^<li>#/,\"<li>\")}</ol>\\n\" } # second level ol\n content.gsub!( /^((?:<li>\\*.*\\n+)+)/ ) { \"<ul>\\n#{$1.gsub(/^<li>\\*/,\"<li>\")}</ul>\\n\" } # third level ul\n content.gsub!( /^((?:<li>#.*\\n+)+)/ ) { \"<ol>\\n#{$1.gsub(/^<li>#/,\"<li>\")}</ol>\\n\" } # third level ol\n\n # tables\n # the table conversion barely works, cf. http://johbuc6.coconia.net/doku.php/mediawiki2html_machine/code?DokuWiki=7c542b97df2bc0f82fec0f4875265a20 for an implementation in PHP\n content.gsub!( /^\\{\\|(.*)/ ) { \"\\{table\\}\\n<table #{$1}>\" }\n content.gsub!( /\\|\\}/ ) { \"</table>\\n\\{/table\\}\" }\n content.gsub!( /^\\|-(.*)/ ) { \"<tr>#{$1}\" }\n content.gsub!( /^!(.*?)\\|(.*)/ ) { \"<th #{$1}>#{$2}</th>\" } # table header with piped markup\n content.gsub!( /^!(.*)/ ) { \"<th>#{$1}</th>\" } # table header without piped markup\n content.gsub!( /^\\|(.*?)\\|(.*)/ ) { \"<td #{$1}>#{$2}\" } # table data with piped markup\n content.gsub!( /^\\|(.*)/ ) { \"<td>#{$1}\" } # table data without piped markup\n \n # line breaks\n content.gsub!( /(^(?:\\w|<strong|<em|<a|\\\").*)\\n\\s*\\n/ ) {\"<p>\\{p\\}#{$1}\\{/p\\}</p>\\n\"}\n \n # special markup of qualidative data analysis\n content.gsub!( /(\\{id\\}.*\\{\\/title\\})/ ) { \"<p><strong><em>#{$1.gsub(/_/,' ')}</em></strong></p>\" }\n \n# //$html = nl2br($html);\n# \t// line breaks\n# \t$html = preg_replace('/[\\n\\r]{4}/',\"<br/><br/>\",$html);\n# \t$html = preg_replace('/[\\n\\r]{2}/',\"<br/>\",$html);\n\n# \t$html = preg_replace('/[>]<br\\/>[<]/',\"><\",$html);\n \n# // allowed tags\n# \t$html = preg_replace('/<(\\/?)(small|sup|sub|u)>/','<${1}${2}>',$html);\n#\n# \t$html = preg_replace('/\\n*<br *\\/?>\\n*/',\"\\n\",$html);\n# \t$html = preg_replace('/<(\\/?)(math|pre|code|nowiki)>/','<${1}pre>',$html);\n# \t$html = preg_replace('/<!--/','<!--',$html);\n# \t$html = preg_replace('/-->/',' -->',$html);\n# \n return content\n\nend",
"def process!(document); end",
"def site_description\n headings = @doc.xpath(\"//h3[@class='clearl']\")\n content_sections = @doc.xpath(\"//h3[@class='clearl']/following-sibling::p[1]\")\n content = \"\"\n headings.zip(content_sections).each do |h, c| \n unless (c.to_s().squeeze().empty?)\n content << \"<h3>#{sanitize(h.to_s)}</h3>\" \n content << \"<p>#{sanitize(c.to_s)}\"\n end\n end\n rhtml = IO.read(File.expand_path(\"site_description.rhtml\", File.dirname(__FILE__)))\n content_html = Erubis::Eruby.new(rhtml)\n content_html.result(:content => content)\n end",
"def parse_data(page)\n if $debug\n puts 'Opening local file.'\n begin\n f = File.open(\"html/research-it.html\")\n doc = Nokogiri::HTML(f)\n f.close\n rescue\n puts \"Failed to open research-it.html file.\"\n end\n else\n puts \"Opening: #{page}\"\n doc = Nokogiri::HTML(open(page))\n end\n\n doc.xpath('//h3/a').each do |record|\n url = record['href']\n name = record.content\n $lessons[url] = {}\n $lessons[url]['name'] = name\n page = Nokogiri::HTML(open(url))\n desc = page.xpath('//p')[1].content\n if desc == ''\n $lessons[url]['short_description'] = 'No description available at this time.'\n else\n $lessons[url]['short_description'] = desc\n end\n end\n\nend",
"def doc_text_info\n extra_javascript 'docs'\n @bugs = sorted_bugs\n end",
"def visiting(page, url, &block)\n body = fetch(url)\n doc = Nokogiri.parse(body)\n docs.push doc\n node = doc.at_xpath(page.content_xpath) or raise Error, \"Couldn't find content at <#{page.content_xpath}>!\"\n content_html = node.to_html\n content_md5 = Url.md5(content_html)\n if u = Url.where(:url => url).first\n # We've scraped this URL before.\n if u.content_md5 == content_md5\n # The content of this page hasn't changed since we last scraped it,\n # so no need to scrape it again\n logger.info \"(Already scraped <#{url}>, and it hasn't changed since last scrape)\"\n else\n # The content of the page *has* changed since we last scraped it,\n # so just update the signature of the content\n logger.info \"Already scraped <#{url}>, but it's changed since last scrape, so updating md5\"\n yield\n u.content_md5 = content_md5\n u.save!\n end\n else\n logger.info \"Haven't scraped <#{url}> yet, content md5 is #{content_md5}\"\n yield\n # We haven't scraped this URL yet, so add it to the database.\n Url.create!(:url => url, :body => body, :content_md5 => content_md5)\n end\n docs.pop\n rescue Error => e\n logger.error e\n end",
"def preprocessMarkdownForHTML(markdown)\n output = \"\"\n inInstructions = false\n \n markdown.split(\"\\n\").each do |line|\n # parse an instructions list\n # use a dummy HTML tag so our final regex doesn't get stuck in an infinite loop replacing itself\n instructionsMatch = line.match(/^>>\\s*(.*?)$/)\n if instructionsMatch\n if not inInstructions\n output += \"<instructions>\\n\"\n end\n output += instructionsMatch[1] + \"\\n\"\n inInstructions = true\n next # don't try to parse anything else\n elsif inInstructions\n output += \"</instructions>\\n\"\n inInstructions = false\n end\n\n # parse headers and page IDs\n headerMatch = line.match(/^(#+)\\s+(.*?)\\s+@@(.*?)$/)\n if headerMatch\n headerLevel = headerMatch[1].length.to_s\n headerTitle = headerMatch[2]\n headerID = headerMatch[3]\n node = nodeWithID(headerID, $doc.toc.rootNode)\n if not node\n puts \"ERROR: Couldn't find node with ID #{headerID}\"\n exit 1\n end\n output += \"<h#{headerLevel}><a name=\\\"#{headerID}\\\">#{node.levelPrefix} #{headerTitle}</a></h#{headerLevel}>\\n\"\n next\n end\n \n # parse links to page IDs and replace with links to the real .htm file\n while 1\n linkMatch = line.match(/\\[.*?\\]\\((@@(.*?))\\)/)\n if linkMatch\n linkID = linkMatch[2]\n linkValue = linkToPageIDFrom(linkID, \"_PAGE_\") # use dummy value\n if not linkValue\n puts \"ERROR: Invalid link ID \\\"#{linkID}\\\"\"\n exit 1\n end\n line[linkMatch[1]] = linkValue\n else\n break\n end\n end\n \n # parse image and label combo\n imgLabelMatch = line.match(/!!\\[(.*?)\\]\\((.*?)\\)/)\n if imgLabelMatch\n label = imgLabelMatch[1]\n imgPath = imgLabelMatch[2]\n \n # read the image and width height to force the size on images for better loading\n # when viewing the files in the boot DVD. there are some issues where anchor jump\n # links don't always jump to the right place on the boot DVD and apparently forcing\n # the image sizes allows the pages to jump properly.\n \t\timgWidth = 0\n \t\timgHeight = 1\n \t\tbegin\n \t\t data = nil\n \t\t if (imgPath =~ /.png$/)\n \t\t data = IO.read($pagesDir + \"/\" + imgPath, 8, 16).unpack('NN')\n\t\t else\n\t\t puts \"ERROR: Unsupported image type: #{imgPath}\"\n\t\t exit 1\n\t end\n \t\t if (data)\n \t\t imgWidth = data[0]\n \t\t imgHeight = data[1]\n\t\t end\n\t\t rescue\n\t end\n imgWidthHeightAttrs = \"\"\n if imgWidth != 0 and imgHeight != 0\n imgWidthHeightAttrs = \" width=\\\"#{imgWidth}\\\" height=\\\"#{imgHeight}\\\"\"\n end\n\n output += \"<p class=\\\"imageAndLabel\\\"><img src=\\\"#{imgPath}\\\" alt=\\\"\" + CGI::escapeHTML(label) + \"\\\"#{imgWidthHeightAttrs}/><br/><em>\" + CGI::escapeHTML(label) + \"</em></p>\\n\"\n next\n end\n \n # parse warning paragraphs\n warningMatch = line.match(/^!!\\s+(.*?)$/)\n if warningMatch\n output += \"<warning>\\n\" + warningMatch[1] + \"\\n<\\/warning>\\n\"\n next\n end\n \n output += line + \"\\n\"\n end\n \n # close off an open instructions div\n if inInstructions\n output += \"</instructions>\\n\"\n end\n \n # Markdown doesn't allow processing of markup within block-level tags such as <div>, so we have to manually process the markup.\n # We call preprocessMarkdownForHTML() to properly process our custom markup within these custom block elements.\n # An extra newline is added to force a paragraph\n while 1\n instructionsMatch = output.match(/(<instructions>)(.*?)(<\\/instructions>)/m)\n if instructionsMatch\n output[instructionsMatch[1]] = \"<div class=\\\"instructions\\\">\"\n output[instructionsMatch[2]] = markdownToHTML(preprocessMarkdownForHTML(\"\\n\"+instructionsMatch[2]))\n output[instructionsMatch[3]] = \"</div>\"\n else\n break\n end\n end\n \n while 1\n warningMatch = output.match(/(<warning>)\\s*(.*?)(<\\/warning>)/m)\n if warningMatch\n output[warningMatch[1]] = \"<div class=\\\"warning\\\"><div class=\\\"warningBody\\\"><div class=\\\"warningImg\\\"></div><div class=\\\"warningContent\\\">\"\n output[warningMatch[2]] = markdownToHTML(preprocessMarkdownForHTML(\"\\n\"+warningMatch[2]))\n output[warningMatch[3]] = \"</div></div></div>\"\n else\n break\n end\n end\n \n return output\nend",
"def review_chunks\n doc.flat_map do |page|\n page.css('div div')\n .children\n .select { |x| x.name == 'div' || x.name == 'small' }\n .map(&:text)\n .reject { |x| x.empty? || x.include?('googleFillSlot') }\n .each_slice(3)\n .take(@limit)\n end\n end",
"def create_wrappers\n return if @elements_have_been_wrapped\n\n elements = fragment.children\n\n # The different groups of elements\n mapping = []\n\n # The current bucket of elements that is being\n # collected, will get reset whenever it runs into\n # an element that is a greater heading rank\n bucket = []\n\n current_level = Util.level(elements.first)\n\n elements.each_cons(2) do |element, next_element|\n bucket << element\n\n # We will have run into a greater header, so close up the bucket\n # and put it into the mapping\n if Util.is_header?(next_element) && Util.level(next_element) >= current_level\n mapping.push([current_level, bucket])\n bucket = []\n end\n\n if Util.is_header?(element)\n current_level = Util.level(element)\n end\n end\n\n # we never ended up reaching a header, so close up and move on\n if !mapping.include?(bucket)\n mapping.push([current_level, bucket])\n end\n\n base_fragment = Nokogiri::HTML.fragment(\"<div class='brief top level' />\")\n\n mapping.map! do |item|\n level, group = item\n group.reject! { |i| i.text == \"\\n\" }\n\n #puts \"Mapping! #{ level } group length: #{ group.length }\"\n\n if level == 0\n #puts \"== Condition A\"\n base_fragment = fragment = Nokogiri::HTML.fragment(\"<div class='brief top level'>#{ group.map(&:to_html).join('') }</div>\")\n elsif level <= lowest_level\n #puts \"== Condition B\"\n fragment = Nokogiri::HTML.fragment(\"<section>#{ group.map(&:to_html).join('') }</section>\")\n elsif level > lowest_level\n #puts \"== Condition C\"\n # should be able to look at the document section mappings and\n # apply custom css classes to these based on the name of the section\n fragment = Nokogiri::HTML.fragment(\"<article>#{ group.map(&:to_html).join('') }</article>\")\n end\n\n [level, [fragment]]\n end\n\n begin\n self.fragment = Brief::Document::Section::Builder.run(mapping, low: lowest_level, high: highest_level)\n rescue Brief::Document::Section::BuilderError\n ##puts \"== Error, returning default fragment: #{ $! }\"\n @fragment\n end\n end",
"def get_detailed_info(html)\n result = {}\n page = Nokogiri::HTML(html)\n result[:img] = extract_image(page)\n # No easy identifiers, so get where the section starts, where the next section starts, and look at all tables in between\n # TODO: Use XPath to use less code\n start_elem = page.css('span.mw-headline[id^=\"Persona_3\"]').last\n elem = start_elem.parent.next\n until elem.name == 'h3' || elem.name == 'h2' || elem.nil? # Reached next game, next section or EOF\n if elem.name == 'table'\n result.merge!(extract_table_info elem)\n elsif elem.name == 'div' && elem[:class] =~ /tabber/\n elem.css('.tabbertab > table').each do |table|\n result.merge!(extract_table_info table)\n end\n end\n\n elem = elem.next\n end\n\n result\n end",
"def setup\n @html_parser = Hatemile::Util::Html::NokogiriLib::NokogiriHTMLDOMParser.new(\n \"<!DOCTYPE html>\n <html>\n <head>\n <title>HaTeMiLe Tests</title>\n <meta charset=\\\"UTF-8\\\" />\n </head>\n <body>\n <section>\n <header></header>\n <article>\n \\n\n </article>\n <footer><!-- Footer --></footer>\n </section>\n <span attribute=\\\"value\\\" data-attribute=\\\"custom_value\\\">\n <!-- Comment -->\n Text node\n <strong>Strong text</strong>\n <hr />\n </span>\n <div></div>\n <p>\n <del>Deleted text</del>\n </p>\n <table>\n <thead><tr>\n <th>Table header</th>\n </tr></thead>\n <tbody>\n <tr>\n <td>Table <ins>cell</ins></td>\n </tr>\n </tbody>\n <tfoot><!-- Table footer --></tfoot>\n </table>\n <ul>\n <li id=\\\"li-1\\\">1</li>\n <li id=\\\"li-3\\\">3</li>\n </ul>\n <ol>\n <li>1</li>\n <li>2</li>\n <li>3</li>\n <li>4</li>\n <li>5</li>\n </ol>\n #{ASIDE_CONTENT}\n <form>\n <label>\n Text:\n <input type=\\\"text\\\" name=\\\"number\\\" />\n </label>\n </form>\n <h1></h1>\n <h2></h2>\n </body>\n </html>\"\n )\n end",
"def scan\n comment = RDoc::Comment.new @content, @top_level\n comment.format = 'markdown'\n\n @top_level.comment = comment\n end",
"def parse_html(pdoc, data)\n src = ::Nokogiri::HTML(data)\n pdoc.properties[:title] = src.title\n extract_plaintext(src.root, pdoc)\n\n # css, js, images\n src.xpath('//link[@rel=\"stylesheet\"]').each do |t|\n pdoc.add_ext_ref(t[:href], PlanR::ParsedDocument::REF_STYLE)\n end\n\n src.xpath('//script[@src]').each do |t|\n pdoc.add_ext_ref(t[:src], PlanR::ParsedDocument::REF_SCRIPT)\n end\n\n src.xpath('//img[@src]').each do |t|\n pdoc.add_ext_ref(t[:src], PlanR::ParsedDocument::REF_IMAGE)\n end\n\n # links\n src.xpath('//a[@href]').each do |t|\n next if (t[:href].start_with? '#')\n next if (t[:href].start_with? 'mailto:')\n pdoc.add_ext_ref(t[:href], PlanR::ParsedDocument::REF_DOC)\n end\n\n # metadata\n meta = {}\n src.xpath('//meta').each do |t|\n last_name = name = value = nil\n t.attributes.each do |key, attr|\n if attr.name == 'content'\n value = attr.value\n elsif attr.name == 'name'\n name = attr.value\n else\n last_name = attr.value\n end\n end\n name = last_name if not name\n meta[name.downcase] = value if name && value\n end\n meta.fetch('keywords', '').split(',').each do |keyword|\n pdoc.keywords << keyword\n end\n pdoc.properties[:content_type] = meta.fetch('content-type', '')\n pdoc.properties[:description] = meta.fetch('description', '')\n end",
"def contents()\n html = Nokogiri::HTML(@markdown_document.to_html())\n\n # Fixup refs to other markdown documents\n html.css(\"a\").each do |anchor|\n anchor[\"href\"] = anchor[\"href\"].sub(%r{\\.md$}, \".html\")\n end\n\n # Since we transform device-specific $device/README.md pages into\n # discrete $device.html, we need to fixup cross-linking into its namespace\n # This could be generalized some more, to be fixed once we have other internal links to mismatched README.md/index.html locations.\n if File.dirname(relative_output) == \"devices\"\n html.css(\"a\").each do |anchor|\n if anchor[\"href\"].match(%r{\\.\\./[^\\.]+$})\n anchor[\"href\"] = anchor[\"href\"].sub(%r{\\.\\./}, \"devices/\") + \".html\"\n end\n end\n end\n\n # Since Nokogiri produces a complete document from our fragment, we\n # have to pick only what's in the body; so strip the body added tags and higher-up tags.\n html\n .at_css(\"body\").to_s()\n .sub(%r{^<body>}, \"\").sub(%r{</body>$}, \"\")\n end",
"def report\n if @coverage_level > 0 then\n extend RDoc::Text\n end\n\n if @coverage_level.zero? then\n calculate\n\n return great_job if @num_items == @doc_items\n end\n\n ucm = @store.unique_classes_and_modules\n\n report = RDoc::Markup::Document.new\n report << RDoc::Markup::Paragraph.new('The following items are not documented:')\n report << RDoc::Markup::BlankLine.new\n\n ucm.sort.each do |cm|\n body = report_class_module(cm) {\n [\n report_constants(cm),\n report_attributes(cm),\n report_methods(cm),\n ].compact\n }\n\n report << body if body\n end\n\n if @coverage_level > 0 then\n calculate\n\n return great_job if @num_items == @doc_items\n end\n\n report\n end",
"def custom_display_as_html(code, file_url)\n begin\n review_scores = self.scores\n\n #********************Learning Targets******************\n code = code + \"<h2>Learning Targets</h2><hr>\"\n if review_scores[0].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> They state what the reader should know or be able to do after reading the lesson<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> They state what the reader should know or be able to do after reading the lesson<br/>\" \n end\n\n if review_scores[1].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> They are specific<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> They are specific<br/>\"\n end\n\n if review_scores[2].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> They are appropriate and reasonable i.e. not too easy or too difficult for TLED 301 students<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> They are appropriate and reasonable i.e. not too easy or too difficult for TLED 301 students<br/>\"\n end\n\n if review_scores[3].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> They are observable i.e. you wouldn't have to look inside the readers' head to know if they met this target<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> They are observable i.e. you wouldn't have to look inside the readers' head to know if they met this target<br/>\"\n end\n\n code = code + \"<br/><i>Number of Learning Targets: </i>#{review_scores[4].comments.gsub(/\\\"/,'"').to_s}<br/>\"\n code = code + \"<br/><i>Grade: </i>#{review_scores[5].comments.gsub(/\\\"/,'"').to_s}<br/>\"\n code = code + \"<br/><i>Comment: </i> <dl><dd>#{review_scores[6].comments.gsub(/\\\"/,'"').to_s}</dl></dd>\"\n\n #*******************Content************************\n code = code + \"<h2>Content</h2><hr>\"\n code = code + \"<i>File:</i>\"\n if file_url.nil?\n code = code + \"File has not been uploaded<br/>\"\n else\n code = code + file_url.to_s + \"<br/>\"\n end\n \n code = code + \"<i>Compliment:</i>\"\n code = code + \"<ul><li>#{review_scores[8].comments.gsub(/\\\"/,'"').to_s}</li><li>#{review_scores[9].comments.gsub(/\\\"/,'"').to_s}</li></ul>\"\n code = code + \"<i>Suggestion:</i>\"\n code = code + \"<ul><li>#{review_scores[10].comments.gsub(/\\\"/,'"').to_s}</li><li>#{review_scores[11].comments.gsub(/\\\"/,'"').to_s}</li></ul>\"\n\n #*******************Sources and Use of Source Material************************\n code = code + \"<h2>Sources and Use of Source Material</h2><hr>\"\n code = code + \"<br/>How many sources are in the references list?: #{review_scores[12].comments.gsub(/\\\"/,'"').to_s}<br/>\"\n code = code + \"<br/>List the range of publication years for all sources, e.g. 1998-2006: <b>#{review_scores[13].comments.gsub(/\\\"/,'"').to_s} - #{review_scores[14].comments.gsub(/\\\"/,'"').to_s}</b><br/><br/>\"\n\n if review_scores[15].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> It lists all the sources in a section labeled \\\"References\\\"<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> It lists all the sources in a section labeled \\\"References\\\"<br/>\"\n end\n\n if review_scores[16].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The author cites each of these sources in the lesson<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The author cites each of these sources in the lesson<br/>\"\n end\n\n if review_scores[17].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The citations are in APA format<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The citations are in APA format<br/>\"\n end\n\n if review_scores[18].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The author cites at least 2 scholarly sources<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The author cites at least 2 scholarly sources<br/>\"\n end\n\n if review_scores[19].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> Most of the sources are current (less than 5 years old)<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> Most of the sources are current (less than 5 years old)<br/>\"\n end\n\n if review_scores[20].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> Taken together the sources represent a good balance of potential references for this topic<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> Taken together the sources represent a good balance of potential references for this topic<br/>\"\n end\n\n if review_scores[21].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The sources represent different viewpoints<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The sources represent different viewpoints<br/>\"\n end\n\n code = code + \"<br/><b>What other sources or perspectives might the author want to consider?</b><br/>\"\n code = code + \"<dl><dd>#{review_scores[22].comments.gsub(/\\\"/,'"').to_s}</dl></dd>\"\n \n if review_scores[23].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> All materials (such as tables, graphs, images or videos created by other people or organizations) posted are in the lesson in accordance with the Attribution-Noncommercial-Share Alike 3.0 Unported license, or compatible. <br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> All materials (such as tables, graphs, images or videos created by other people or organizations) posted are in the lesson in accordance with the Attribution-Noncommercial-Share Alike 3.0 Unported license, or compatible<br/>\"\n end\n\n code = code + \"<br/><b>If not, which one(s) may infringe copyrights, or what areas of text may need citations, revisions or elaboration?</b><br/>\"\n code = code + \"<dl><dd>#{review_scores[24].comments.gsub(/\\\"/,'"').to_s}</dl></dd>\"\n\n code = code + \"<br/>Please make a comment about the sources. Explain how the author can improve the use of sources in the lesson.<br/>\"\n code = code + \"<dl><dd>#{review_scores[25].comments.gsub(/\\\"/,'"').to_s}</dl></dd>\"\n\n #*******************Multiple Choice Questions************************\n code = code + \"<h2>Multiple Choice Questions</h2><hr>\"\n if review_scores[26].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> There are 4 multiple-choice questions<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> There are 4 multiple-choice questions<br/>\"\n end\n\n if review_scores[27].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> They each have four answer choices (A-D)<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> They each have four answer choices (A-D)<br/>\"\n end\n\n if review_scores[28].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> There is a single correct (aka: not opinion-based) answer for each question<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> There is a single correct (aka: not opinion-based) answer for each question<br/>\"\n end\n\n if review_scores[29].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The questions assess the learning target(s)<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The questions assess the learning target(s)<br/>\"\n end\n\n if review_scores[30].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The questions are appropriate and reasonable (not too easy and not too difficult)<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The questions are appropriate and reasonable (not too easy and not too difficult)<br/>\"\n end\n\n if review_scores[31].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The foils (the response options that are NOT the answer) are reasonable i.e. they are not very obviously incorrect answers<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The foils (the response options that are NOT the answer) are reasonable i.e. they are not very obviously incorrect answers<br/>\"\n end\n\n if review_scores[32].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The response options are listed in alphabetical order<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The response options are listed in alphabetical order<br/>\"\n end\n\n if review_scores[33].comments == \"1\"\n code = code + \"<img src=\\\"/images/Check-icon.png\\\"> The correct answers are provided and listed BELOW all the questions<br/>\"\n else\n code = code + \"<img src=\\\"/images/delete_icon.png\\\"> The correct answers are provided and listed BELOW all the questions<br/>\"\n end\n\n code = code + \"<br/><h3>Questions</h3>\"\n\n code = code + \"<i>Type: </i><b>#{review_scores[34].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[35].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[36].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n code = code + \"<i>Type: </i><b>#{review_scores[37].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[38].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[39].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n code = code + \"<i>Type: </i><b>#{review_scores[40].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[41].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[42].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n code = code + \"<i>Type: </i><b>#{review_scores[43].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[44].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[45].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n\n #*******************Rubric************************\n code = code + \"<h2>Rubric</h2><hr>\"\n\n code = code + \"<h3>Importance</h3>\"\n code = code +\n \"<div align=\\\"center\\\">The information selected by the author:</div><table class='general'>\n <tr>\n <th>5 - Very Important </th>\n <th>4 - Quite Important </th>\n <th>3 - Some Importance </th>\n <th>2 - Little Importance</th>\n <th>1 - No Importance </th>\n </tr>\n <tr>\"\n\n code = code + \"<td><ul>\"\n if review_scores[46].comments == \"1\"\n code = code + \"<li>Is very important for future teachers to know</li>\"\n end\n if review_scores[47].comments == \"1\"\n code = code + \"<li>Is based on researched information</li>\"\n end\n if review_scores[48].comments == \"1\"\n code = code + \"<li>Is highly relevant to current educational practice</li>\"\n end\n if review_scores[49].comments == \"1\"\n code = code + \"<li>Provides an excellent overview and in-depth discussion of key issues</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[50].comments == \"1\"\n code = code + \"<li>Is relevant to future teachers</li>\"\n end\n if review_scores[51].comments == \"1\"\n code = code + \"<li>Is mostly based on researched information</li>\"\n end\n if review_scores[52].comments == \"1\"\n code = code + \"<li>Is applicable to today's schools</li>\"\n end\n if review_scores[53].comments == \"1\"\n code = code + \"<li>Provides a good overview and explores a few key ideas</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[54].comments == \"1\"\n code = code + \"<li>Has useful points but some irrelevant information</li>\"\n end\n if review_scores[55].comments == \"1\"\n code = code + \"<li>Is half research; half the author's opinion</li>\"\n end\n if review_scores[56].comments == \"1\"\n code = code + \"<li>Is partially out-dated or may not reflect current practice</li>\"\n end\n if review_scores[57].comments == \"1\"\n code = code + \"<li>Contains good information but yields an incomplete understanding</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[58].comments == \"1\"\n code = code + \"<li>Has one useful point</li>\"\n end\n if review_scores[59].comments == \"1\"\n code = code + \"<li>Is mostly the author's opinion.</li>\"\n end\n if review_scores[60].comments == \"1\"\n code = code + \"<li>Is mostly irrelevant in today's schools</li>\"\n end\n if review_scores[61].comments == \"1\"\n code = code + \"<li>Focused on unimportant subtopics OR is overly general</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\" \n if review_scores[62].comments == \"1\"\n code = code + \"<li>Is not relevant to future teachers</li>\"\n end\n if review_scores[63].comments == \"1\"\n code = code + \"<li>Is entirely the author's opinion</li>\"\n end\n if review_scores[64].comments == \"1\"\n code = code + \"<li>Is obsolete</li>\"\n end\n if review_scores[65].comments == \"1\"\n code = code + \"<li>Lacks any substantive information</li>\"\n end\n code = code + \"</ul></td></tr>\"\n\n code = code + \"</table>\"\n\n code = code + \"<h3>Interest</h3>\"\n code = code +\n \"<div align=\\\"center\\\">To attract and maintain attention, the lesson has:</div><table class='general'>\n <tr>\n <th>5 - Extremely Interesting </th>\n <th>4 - Quite Interesting </th>\n <th>3 - Reasonably Interesting </th>\n <th>2 - Little Interest</th>\n <th>1 - No Interest </th>\n </tr>\n <tr>\"\n\n code = code + \"<td><ul>\"\n if review_scores[66].comments == \"1\"\n code = code + \"<li>A sidebar with new information that was motivating to read/view</li>\"\n end\n if review_scores[67].comments == \"1\"\n code = code + \"<li>Many creative, attractive visuals and engaging, interactive elements</li>\"\n end\n if review_scores[68].comments == \"1\"\n code = code + \"<li>Multiple perspectives</li>\"\n end\n if review_scores[69].comments == \"1\"\n code = code + \"<li>Insightful interpretation & analysis throughout</li>\"\n end\n if review_scores[70].comments == \"1\"\n code = code + \"<li>Many compelling examples that support the main points (it \\\"shows\\\" not just \\\"tells\\\")</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[71].comments == \"1\"\n code = code + \"<li>A sidebar that adds something new to the lesson</li>\"\n end\n if review_scores[72].comments == \"1\"\n code = code + \"<li>A few effective visuals or interactive elements</li>\"\n end\n if review_scores[73].comments == \"1\"\n code = code + \"<li>At least one interesting, fresh perspective</li>\"\n end\n if review_scores[74].comments == \"1\"\n code = code + \"<li>Frequent interpretation and analysis</li>\"\n end\n if review_scores[75].comments == \"1\"\n code = code + \"<li>Clearly explained and well supported points</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[76].comments == \"1\"\n code = code + \"<li>A sidebar that repeats what is in the lesson</li>\"\n end\n if review_scores[77].comments == \"1\"\n code = code + \"<li>An effective visual or interactive element</li>\"\n end\n if review_scores[78].comments == \"1\"\n code = code + \"<li>One reasonable (possibly typical) perspective</li>\"\n end\n if review_scores[79].comments == \"1\"\n code = code + \"<li>Some interpretation and analysis</li>\"\n end\n if review_scores[80].comments == \"1\"\n code = code + \"<li>Supported points</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[81].comments == \"1\"\n code = code + \"<li>A quote, link, etc. included as a sidebar, but that is not in a textbox</li>\"\n end\n if review_scores[82].comments == \"1\"\n code = code + \"<li>Visuals or interactive elements that are distracting</li>\"\n end\n if review_scores[83].comments == \"1\"\n code = code + \"<li>Only a biased perspective</li>\"\n end\n if review_scores[84].comments == \"1\"\n code = code + \"<li>Minimal analysis or interpretation</li>\"\n end\n if review_scores[85].comments == \"1\"\n code = code + \"<li>At least one clear and supported point</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[86].comments == \"1\"\n code = code + \"<li>No side bar included</li>\"\n end\n if review_scores[87].comments == \"1\"\n code = code + \"<li>No visuals or interactive elements</li>\"\n end\n if review_scores[88].comments == \"1\"\n code = code + \"<li>No perspective is acknowledged</li>\"\n end\n if review_scores[89].comments == \"1\"\n code = code + \"<li>No analysis or interpretation</li>\"\n end\n if review_scores[90].comments == \"1\"\n code = code + \"<li>No well-supported points</li>\"\n end\n code = code + \"</ul></td></tr>\"\n\n code = code + \"</table>\"\n\n code = code + \"<h3>Credibility</h3>\"\n\n code = code +\n \"<div align=\\\"center\\\">To demonstrate its credibility the lesson:</div><table class='general'>\n <tr>\n <th>5 - Completely Credible </th>\n <th>4 - Substantial Credibility </th>\n <th>3 - Reasonable Credibility </th>\n <th>2 - Limited Credibility</th>\n <th>1 - Not Credible </th>\n </tr>\n <tr>\"\n\n code = code + \"<td><ul>\"\n if review_scores[91].comments == \"1\"\n code = code + \"<li>Cites 5 or more diverse, reputable sources in proper APA format</li>\"\n end\n if review_scores[92].comments == \"1\"\n code = code + \"<li>Provides citations for all presented information</li>\"\n end\n if review_scores[93].comments == \"1\"\n code = code + \"<li>Readily identifies bias: both the author's own and others</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[94].comments == \"1\"\n code = code + \"<li>Cites 5 or more diverse, reputable sources with few APA errors</li>\"\n end\n if review_scores[95].comments == \"1\"\n code = code + \"<li>Provides citations for most information</li>\"\n end\n if review_scores[96].comments == \"1\"\n code = code + \"<li>Clearly differentiates between opinion and fact</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[97].comments == \"1\"\n code = code + \"<li>Cites 5 or more reputable sources</li>\"\n end\n if review_scores[98].comments == \"1\"\n code = code + \"<li>Supports some claims with citation</li>\"\n end\n if review_scores[99].comments == \"1\"\n code = code + \"<li>Occasionally states opinion as fact</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[100].comments == \"1\"\n code = code + \"<li>Cites 4 or more reputable sources</li>\"\n end\n if review_scores[101].comments == \"1\"\n code = code + \"<li>Has several unsupported claims</li>\"\n end\n if review_scores[102].comments == \"1\"\n code = code + \"<li>Routinely states opinion as fact and fails to acknowledge bias</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[103].comments == \"1\"\n code = code + \"<li>Cites 3 or fewer reputable sources</li>\"\n end\n if review_scores[104].comments == \"1\"\n code = code + \"<li>Has mostly unsupported claims</li>\"\n end\n if review_scores[105].comments == \"1\"\n code = code + \"<li>Is very biased and contains almost entirely opinions</li>\"\n end\n\n code = code + \"</ul></td></tr>\"\n\n code = code + \"</table>\"\n\n\n code = code + \"<h3>Pedagogy</h3>\"\n\n code = code +\n \"<div align=\\\"center\\\">To help guide the reader:</div><table class='general'>\n <tr>\n <th>5 - Superior </th>\n <th>4 - Effective </th>\n <th>3 - Acceptable </th>\n <th>2 - Deficient</th>\n <th>1 - Absent </th>\n </tr>\n <tr>\"\n\n code = code + \"<td><ul>\"\n if review_scores[106].comments == \"1\"\n code = code + \"<li>Specific, appropriate, observable learning targets establish the purpose of the lesson</li>\"\n end\n if review_scores[107].comments == \"1\"\n code = code + \"<li>The lesson accomplishes its established goals</li>\"\n end\n if review_scores[108].comments == \"1\"\n code = code + \"<li>Excellent knowledge and application MC questions align with learning targets and assess important content</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[109].comments == \"1\"\n code = code + \"<li>Specific and reasonable learning targets are stated</li>\"\n end\n if review_scores[110].comments == \"1\"\n code = code + \"<li>The lesson partially meets its established goals</li>\"\n end\n if review_scores[111].comments == \"1\"\n code = code + \"<li>Well constructed MC questions assess important content</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[112].comments == \"1\"\n code = code + \"<li>Reasonable learning targets are stated</li>\"\n end\n if review_scores[113].comments == \"1\"\n code = code + \"<li>The content relates to its goals</li>\"\n end\n if review_scores[114].comments == \"1\"\n code = code + \"<li>MC questions assess important content</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[115].comments == \"1\"\n code = code + \"<li>A learning target is included</li>\"\n end\n if review_scores[116].comments == \"1\"\n code = code + \"<li>Content does not achieve its goal, or goal is unclear</li>\"\n end\n if review_scores[117].comments == \"1\"\n code = code + \"<li>4 questions are included</li>\"\n end\n\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[118].comments == \"1\"\n code = code + \"<li>Learning target is missing/ not actually a learning target</li>\"\n end\n if review_scores[119].comments == \"1\"\n code = code + \"<li>Lesson has no goal/ content is unfocused</li>\"\n end\n if review_scores[120].comments == \"1\"\n code = code + \"<li>Questions are missing</li>\"\n end\n\n code = code + \"</ul></td></tr>\"\n\n code = code + \"</table>\"\n code = code + \"<h3>Writing Quality</h3>\"\n\n code = code +\n \"<div align=\\\"center\\\">The writing:</div><table class='general'>\n <tr>\n <th>5 - Excellently Written </th>\n <th>4 - Well Written </th>\n <th>3 - Reasonably Written </th>\n <th>2 - Fairly Written</th>\n <th>1 - Poorly Written </th>\n </tr>\n <tr>\"\n\n code = code + \"<td><ul>\"\n if review_scores[121].comments == \"1\"\n code = code + \"<li>Is focused, organized, and easy to read throughout</li>\"\n end\n if review_scores[122].comments == \"1\"\n code = code + \"<li>Uses rich, descriptive vocabulary and a variety of effective sentence structures</li>\"\n end\n if review_scores[123].comments == \"1\"\n code = code + \"<li>Contains few to no mechanical errors</li>\"\n end\n if review_scores[124].comments == \"1\"\n code = code + \"<li>Has an effective introduction and a conclusion that synthesizes all of the material presented</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[125].comments == \"1\"\n code = code + \"<li>Is organized and flows well</li>\"\n end\n if review_scores[126].comments == \"1\"\n code = code + \"<li>Uses effective vocabulary and sentence structures</li>\"\n end\n if review_scores[127].comments == \"1\"\n code = code + \"<li>Contains a few minor mechanical errors</li>\"\n end\n if review_scores[128].comments == \"1\"\n code = code + \"<li>Has an effective introduction and conclusion based on included information</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[129].comments == \"1\"\n code = code + \"<li>Is mostly organized</li>\"\n end\n if review_scores[130].comments == \"1\"\n code = code + \"<li>Uses properly constructed sentences</li>\"\n end\n if review_scores[131].comments == \"1\"\n code = code + \"<li>Has a few distracting errors</li>\"\n end\n if review_scores[132].comments == \"1\"\n code = code + \"<li>Includes an introduction and a conclusion</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[133].comments == \"1\"\n code = code + \"<li>Can be difficult to follow</li>\"\n end\n if review_scores[134].comments == \"1\"\n code = code + \"<li>Contains several awkward sentences</li>\"\n end\n if review_scores[135].comments == \"1\"\n code = code + \"<li>Has several distracting errors</li>\"\n end\n if review_scores[136].comments == \"1\"\n code = code + \"<li>Lacks either an introduction or a conclusion</li>\"\n end\n code = code + \"</ul></td>\"\n\n code = code + \"<td><ul>\"\n if review_scores[137].comments == \"1\"\n code = code + \"<li>Has minimal organization</li>\"\n end\n if review_scores[138].comments == \"1\"\n code = code + \"<li>Has many poorly constructed sentences</li>\"\n end\n if review_scores[139].comments == \"1\"\n code = code + \"<li>Has many mechanical errors that inhibit comprehension</li>\"\n end\n if review_scores[140].comments == \"1\"\n code = code + \"<li>Has neither a clear introduction nor a conclusion</li>\"\n end\n code = code + \"</ul></td></tr>\"\n\n code = code + \"</table>\"\n\n #*******************Ratings************************\n code = code + \"<h2>Ratings</h2><hr>\"\n\n code = code + \"<h3>Importance</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[141].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[142].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n code = code + \"<h3>Interest</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[143].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[144].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n code = code + \"<h3>Credibility</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[145].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[146].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n code = code + \"<h3>Pedagogy</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[147].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[148].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n\n code = code + \"<h3>Writing Quality</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[149].comments.gsub(/\\\"/,'"').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[150].comments.gsub(/\\\"/,'"').to_s}</dl></dd><br/>\"\n rescue\n code += \"Error \" + $! \n end \n code\nend",
"def parse_html(user,parent_dagr)\n url = \"\"\n url += parent_dagr.storage_path + \"/\" + parent_dagr.name\n puts url\n page = Nokogiri::HTML(open(url))\n \n return_string = \"\"\n #add all video and adeo files\n page.css(\"source\").each do |element|\n file_name = element[\"src\"]\n file_name = add_element(user,parent_dagr,file_name,parent_dagr.storage_path,nil)\n return_string += file_name + \", \"\n end\n \n #add all images\n page.css(\"img\").each do |element|\n file_name = element[\"src\"]\n file_name = add_element(user,parent_dagr,file_name,parent_dagr.storage_path,nil)\n return_string += file_name + \", \"\n end\n \n #add all javascript\n page.css(\"script\").each do |element|\n file_name = element[\"src\"]\n if file_name\n file_name = add_element(user,parent_dagr,file_name,parent_dagr.storage_path,nil)\n return_string += file_name + \", \"\n end\n end\n \n #add all html documents\n page.css(\"a\").each do |element|\n puts element.text\n url = element[\"href\"]\n # if url pointed to html document\n #if /.html\\z/ =~ url \n file_name = add_element(user,parent_dagr,url,parent_dagr.storage_path,element.text)\n return_string += file_name + \", \" \n #end\n end\n \n return return_string\n end",
"def process_markdown_inside_elements(doc)\n # find span elements or elements with 'markdown' attribute\n elts = @fragment.css(\"[markdown]\")\n\n d = @fragment.children.first\n if d && HTML_INLINE_ELEMS.include?(d.name)\n elts << d unless d.attribute('markdown')\n elts += span_descendents(d)\n end\n\n elts.each do |e|\n how = e['markdown']\n e.remove_attribute('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.xpath(\"./text()\").each do |original_text|\n s = CGI.escapeHTML(original_text.text)\n unless s.strip.empty?\n parsed = parse_blocks ? doc.parse_text_as_markdown(s) : doc.parse_span(s)\n\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 # Nokogiri collapses consecutive Text nodes, so replace it by a dummy element\n guard = Nokogiri::XML::Element.new('guard', @fragment)\n original_text.replace(guard)\n el.children_to_html.each do |x|\n guard.before(x.to_s)\n end\n guard.remove\n end\n end\n end\n end",
"def process_oldstyle_html contents\n\tdoc = Nokogiri::HTML(contents)\n\n\t# the HIB page keeps each entry in a div with class 'row'\n\t# plus a name based on the game name.\n\tdoc.css('div.row').each do |div|\n\t\tname = div['class'].sub(/\\s*row\\s*/,'')\n\t\troot = get_root name\n\t\tdiv.css('.downloads').each do |dd|\n\t\t\ttype = dd['class'].gsub(/\\s*(downloads|show)\\s*/,'')\n\t\t\tdd.css('.download').each do |dl|\n\t\t\t\taa = dl.css('a.a').first\n\t\t\t\tlink = aa['href']\n\t\t\t\tbtlink = aa['data-bt']\n\t\t\t\tif btlink.empty?\n\t\t\t\t\tbtlink = nil\n\t\t\t\tend\n\t\t\t\tmd5 = dl.css('a.dlmd5').first['href'].sub(/^#/,'') rescue nil\n\t\t\t\tts = dl.css('a.dldate').first['data-timestamp'] rescue nil\n\t\t\t\tsavepath = File.join(root, type)\n\n\t\t\t\tdl = true\n\n\t\t\t\tif link[-1] == '/'\n\t\t\t\t\tSTDERR.puts \"# No automatic downloads for #{savepath}, go to #{link}\"\n\t\t\t\t\tdl = false\n\t\t\t\tend\n\n\t\t\t\t$dirs << savepath\n\t\t\t\tif dl\n\t\t\t\t\tfname = get_filename link\n\t\t\t\t\tfkey = fname.intern\n\t\t\t\t\t$files[fkey] << Game.new(fname, md5, savepath, link, btlink)#, ts)\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend",
"def parsed\n @parsed ||= Nokogiri::HTML(@document.to_s)\n rescue Exception => e\n @exception_log << e\n end",
"def g\n link = params[:link]\n @cont = Cont.where(:link => link)\n\t@cont = @cont.first\n\tif @cont.nil?\n\t p 'extracting .............'\n\t error_type = 0 #success\n\t content = ''\n\t html = ''\n\t error_msg = ''\n\t title = ''\n\t #st = Time.now\n\t begin\n a = open(link); p \"header charset: #{a.charset}\"\n text = a.read; p \"text encoding: #{text.encoding.to_s}\"\n\t #p \"get raw html time: #{Time.now - st}\"\n\t\tenc = a.meta['content-encoding']\n\t\tif enc == 'gzip' || enc == 'inflate'\n\t\t text = uncompress(text, enc)\n cs = get_charset(text); p \"ziped charset: #{cs}\"\n\t\t text = text.force_encoding(cs).encode('UTF-8')\n text = text.sub(cs, 'UTF-8')\n\t\tend\n cs = get_charset(text); p \"charset: #{cs}\"\n\t\thtml = text\n\t\tif \"iso-8859-1\".casecmp(cs) == 0 || \"utf-8\".casecmp(text.encoding.to_s) !=0\n\t\t if \"utf-8\".casecmp(cs) != 0 && \"utf-8\".casecmp(text.encoding.to_s) !=0\n\t\t p 'wrong charset, change'\n\t\t html = text.force_encoding('GBK').encode('UTF-8')\n\t\t end\n\t\tend\n\t\thtml = html.force_encoding('utf-8')\n html = html.sub(cs, 'UTF-8')\n\t rescue => e\n\t error_type = 1 #HTML error\n\t\terror_msg = e.message.to_s\n\t\tp e.message\n\t\tp e.backtrace\n\t end\n\t #p \"get html time: #{Time.now - st}\"\n\n st = Time.now\t \n\t if error_type == 0\n\t begin \n# doc = Readability::Document.new(html, :debug=>true)\n doc = Readability::Document.new(html)\n content = doc.content\n\t\t title = trim_title(doc.html.title)\n rescue => e\n\t\t error_type = 2 # READABILITY ERROR\n\t\t error_msg = e.message.to_s\n\t\t p e.message\n\t\t p e.backtrace\n\t\tend\n\t end\n\t p \"get readability time: #{Time.now - st}\"\n\n @cont = Cont.new(\n\t :link => link,\n\t :html => '', #html,\n\t :content => content,\n\t\t:title => title,\n\t :error_type => error_type,\n\t :error_msg => error_msg\n\t )\n @cont.save\n\tend\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cont }\n end\n end",
"def parse(document_xml)\n @xml = Nokogiri::XML(document_xml)\n\n # Iterate over each element node and dispatch it to the appropriate parser\n @xml.xpath('//w:body').children.each do |node|\n case node.name\n when 'p'\n no_numbering_prop = node.xpath('.//w:numPr').length.zero? || node.xpath('.//w:numPr/w:ilvl | .//w:numPr/w:numId').length.zero?\n not_multiparagraph_list_item = (@buffer.is_a?(Swordfish::Node::List) ? node.xpath('.//w:ind[@w:left]').length.zero? : true)\n if no_numbering_prop && not_multiparagraph_list_item\n # Regular paragraph\n # (The buffer check makes sure that this isn't an indented paragraph immediately after a list item,\n # which means we're most likely dealing with a multi-paragraph list item)\n flush\n @swordfish_doc.append _node_parse_paragraph(node)\n elsif node.xpath('.//w:numPr/ancestor::w:pPrChange').length.zero?\n # List paragraph\n # (must have a numPr node, but cannot have a pPrChange ancestor, since that means\n # we are just looking at historical changes)\n # (Don't flush because we need to first ensure the list is fully parsed)\n _node_parse_list(node)\n end\n when 'tbl'\n flush\n @swordfish_doc.append _node_parse_table(node)\n end\n end\n flush\n end",
"def parse_content_from_yuletide_file(story)\n @doc = Nokogiri::HTML.parse(story) rescue \"\"\n content_table = (@doc/\"table[@class='form']/tr/td[2]\")\n content = \"\"\n unless content_table\n content = (@doc/\"body\").inner_html\n else\n centers = content_table.css(\"center\")\n centers[0].remove\n # trying to remove comment links at the bottom\n if !centers[-1].nil? && centers[-1].to_html.match(/<!-- COMMENTLINK START -->/)\n centers[-1].remove\n end\n content = content_table.inner_html\n end\n \n @storyparser ||= StoryParser.new\n content = @storyparser.clean_storytext(content)\n content.gsub!(/<a href=\"\\//, '<a href=\"http://yuletidetreasure.org/')\n content\n end",
"def see_yields\n obtained_yields = []\n user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'\n\n begin\n document = Nokogiri::HTML(open(self.url, \"User-Agent\" => user_agent))\n white_list_sanitizer = Rails::Html::WhiteListSanitizer.new\n\n document.css(self.content).each do |element|\n obtained_yields << white_list_sanitizer.sanitize(element.to_html)\n end\n rescue => e\n obtained_yields << 'Parsing error'\n obtained_yields << e.inspect if Rails.env.development?\n end\n\n obtained_yields\n end",
"def parse!\n md = File.read(filename)\n doc = Kramdown::Document.new(md, input: 'GFM')\n\n # extract toc\n toc_start, toc_end = Danger::Toc::Extractor.convert(doc.root).first\n @has_toc = toc_start && toc_end\n @toc = md.split(\"\\n\")[toc_start, toc_end - toc_start - 1].reject(&:empty?) if @has_toc\n\n # construct toc\n @headers = Danger::Toc::Constructors.current.convert(doc.root).first\n end",
"def parsed_document\n @parsed_document ||= Nokogiri::HTML(document)\n\n rescue Exception => e\n warn 'An exception occurred while trying to scrape the page!'\n warn e.message\n end",
"def parse_text(filename, content)\n # break into comments and non-comments with line numbers\n content = \"/** */\" + content if content[0..2] != \"/**\"\n recs = []\n lineno = 1\n openblock = false\n\n content.split(/\\/\\*\\*/).each do |chunk|\n c, b = chunk.split(/[ \\t]*\\*\\//, 2)\n next unless c || b\n\n lineno += c.scan(\"\\n\").length if c\n\n # special handling for /**< ... */ inline comments or\n # for /** ... */ inside an open block\n if openblock || c[0] == ?<\n c = c.sub(/^</, '').strip\n\n so_far = recs[-1][:body]\n last_line = so_far[ so_far.rindex(\"\\n\")+1 .. -1 ].strip.chomp(\",\").chomp(\";\")\n if last_line.empty? && b =~ /^([^;]+)\\;/ # apply to this line instead\n last_line = $1.strip.chomp(\",\").chomp(\";\")\n end\n\n if !last_line.empty?\n recs[-1][:inlines] ||= []\n recs[-1][:inlines] << [ last_line, c ]\n if b\n recs[-1][:body] += b\n lineno += b.scan(\"\\n\").length\n openblock = false if b =~ /\\}/\n end\n next\n end\n end\n\n # make comment have a uniform \" *\" prefix if needed\n if c !~ /\\A[ \\t]*\\n/ && c =~ /^(\\s*\\*)/\n c = $1 + c\n end\n\n # check for unterminated { brace (to handle inline comments later)\n openblock = true if b =~ /\\{[^\\}]+\\Z/\n\n recs << {\n :file => filename,\n :line => lineno + (b.start_with?(\"\\n\") ? 1 : 0),\n :body => b,\n :rawComments => cleanup_comment(c),\n }\n\n lineno += b.scan(\"\\n\").length if b\n end\n\n # try parsers on each chunk of commented header\n recs.each do |r|\n r[:body].strip!\n r[:rawComments].strip!\n r[:lineto] = r[:line] + r[:body].scan(\"\\n\").length\n parse_declaration_block(r)\n end\n\n recs\n end",
"def parse_markup\n @html = PARSER.parse(@markup, :base_heading_level => 1)\n end",
"def wiki_parse(content)\n #City which has a population based on United States Census\n population = /Population[[^>]*?>]+?<\\/tr>\\s*<tr class=\"mergedrow\">[[^>]*?>]+?<td>([\\d|,]*)[^\\d|^,]/.match(content)\n \n if population != nil\n #puts population\n popu = population[1].delete(',')\n popu\n else\n #In most case, the wiki page displays the data from census in a table.\n #However, in some case, some cities, e.g Hollywood, do not provide the data table.\n #Therefore, the program tries to retrive the population in the content by searching keyowrd 'population' and the number followed.\n population = /[Pp]opulation[^<|^>]*?([\\d|,]+)/.match(content)\n #puts \"2\"\n #puts population[1]\n if population != nil\n popu = population[1].delete(',')\n popu\n else\n popu = nil\n popu\n end\n end\n end",
"def html_contents\n layout_contents\n end",
"def analyze( res )\n print_debug \"Started for response with request ID: ##{res.request.id}\"\n\n page_data = @page.to_hash\n page_data[:cookies] = find_new( :cookies )\n\n # if the response body is the same as the page body and\n # no new cookies have appeared there's no reason to analyze the page\n if res.body == @page.body && !@updated && @page.url == @parser.url\n print_debug 'Page hasn\\'t changed.'\n return\n end\n\n [ :forms, :links ].each { |type| page_data[type] = find_new( type ) }\n\n if @updated\n page_data[:url] = @parser.url\n page_data[:query_vars] = @parser.link_vars( @parser.url )\n page_data[:code] = res.code\n page_data[:method] = res.request.method.to_s.upcase\n page_data[:body] = res.body\n page_data[:document] = @parser.doc\n page_data[:response_headers] = res.headers_hash\n\n @trainings_per_url[@parser.url] += 1\n\n page = Page.new( page_data )\n Platform::Manager.fingerprint( page ) if Options.fingerprint?\n\n @on_new_page_blocks.each { |block| block.call page }\n\n # feed the page back to the framework\n @framework.push_to_page_queue( page )\n\n @updated = false\n end\n\n print_debug 'Training complete.'\n end",
"def text_wikimedia_html page\n html = @client.text_wikimedia_html page\n # normalize html by removing <!-- html comments -->\n doc = Nokogiri.HTML html\n (doc.xpath '//comment()').remove\n doc.inner_html\n end",
"def extract_chapter(article)\n article_url = @lfs_base_url + \"/#{@lfs_branch}/\" + article\n puts \"fetching : #{article_url} .. \"\n article_content= Nokogiri::HTML(open(article_url))\n\n script = Array.new\n article_content.css('pre.userinput').each {|my_match|script << my_match.content}\n \n script = NIL unless script.size > 0\n script\n \nend",
"def initialize(dataset, options = {})\n # Save the dataset and options\n @dataset = dataset\n normalize_options(options)\n\n # Compute all df and tfs, and the type/token values for the dataset\n compute_df_tf\n\n # Pick out the set of words we'll analyze\n pick_words\n\n # Prep the data containers\n @blocks = []\n @block_stats = []\n \n # If we're split_across, we can now compute block_size from num_blocks\n # and vice versa\n if @split_across\n compute_block_size(@num_dataset_tokens)\n end\n\n # Set up the initial block\n @block_num = 0\n clear_block(false)\n \n # Process all of the documents\n @dataset.entries.each do |e|\n @current_doc = Document.find_with_fulltext e.shasum\n tv = @current_doc.term_vectors\n\n # If we aren't splitting across, then we have to completely clear\n # out all the count information for every document, and we have to\n # compute how many/how big the blocks should be for this document\n unless @split_across\n @block_num = 0\n compute_block_size(tv.values.map { |x| x[\"tf\"] }.reduce(:+))\n end\n \n # Create a single array that has the words in the document sorted\n # by position\n sorted_words = []\n tv.each do |word, hash|\n next unless @word_list.include? word\n \n hash[:positions].each do |p|\n sorted_words << [ word, p ]\n end\n end\n sorted_words.sort! { |a, b| a[1] <=> b[1] }\n sorted_words.map! { |x| x[0] }\n \n # Do the processing for this document\n sorted_words.each do |word|\n @block[word] += 1\n @block_tokens += 1\n \n if @block[word] == 1\n @block_types += 1\n end\n \n @block_counter += 1\n \n # If the block size doesn't divide evenly into the number of blocks\n # that we want, we want to consume the remainder one at a time over\n # the course of all the blocks, and *not* leave it until the end, or\n # else we wind up with one block that contains all the remainder,\n # despite the fact that we were trying to divide evenly.\n check_size = @block_size\n if @num_remainder_blocks != 0\n check_size = @block_size + 1\n end\n \n if @block_counter >= check_size\n @num_remainder_blocks -= 1 if @num_remainder_blocks != 0\n clear_block\n end\n end\n \n # If we're not splitting across, we need to make sure the last block\n # for this doc, if there's anything in it, has been added to the list.\n if !@split_across && @block_counter != 0\n clear_block\n end\n end\n \n # If we are splitting across, we need to put the last block into the\n # list\n if @split_across && @block_counter != 0\n clear_block\n end\n end",
"def doc\n # get_html beforehand for good output messages\n html = get_html\n print \"Parsing doc...\"\n doc = Nokogiri::HTML(html)\n puts \"done.\"\n puts\n doc\n end",
"def html\n if FUNCTION != 'none'\n if self.md.value != nil\n hm = self.md.value\n else\n hm = INDEX\n end\n @me = YAML.load(self.yaml.value)\n [\n ERB.new(HEAD).result(binding),\n Kramdown::Document.new(ERB.new(hm).result(binding)).to_html,\n \"</body></html>\"\n ].flatten.join('')\n end\n end",
"def html_summarize(text, length = 30, omission = '...')\n return '' if text.blank?\n snippet(strip_tags(text), length, omission)\n end",
"def find_num_of_reviews(html_file)\n html_file.search(\".review-count > span\")[0].inner_text\nend",
"def show\n @problem = Problem.find(params[:id])\n @submission = Submission.new(params[:submission])\n @str = Nokogiri::HTML(File.open(\"Problems/Codeforces/#{@problem.pid}.txt\", \"r+\"))\n\n\n\n# Get Time Limit\n @str_tml = @str.css(\"html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div.header div.time-limit\").text\n @tml = @str_tml.gsub!(/\\D/, \"\").to_i * 1000\n\n# Get Memory Limit\n @str_mml = @str.css(\"html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div.header div.memory-limit\").text\n @mml = @str_mml.gsub!(/\\D/, \"\").to_i\n\n# Get Description\n @str_des = @str.css(\"html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div:nth-child(2) p,\n html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div:nth-child(2) ul\")\n\n# Get Input\n @str_input = @str.css(\"html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div.input-specification p,\n html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div.input-specification ul\")\n\n# Get Output\n @str_output = @str.css(\"html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div.output-specification p,\n html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div.output-specification ul\")\n\n# Get Sample\n @str_sample = @str.css(\"html body div#body div div#content.content-with-sidebar div.problemindexholder div.ttypography div.problem-statement div.sample-tests div.sample-test\")\n\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @problem }\n end\n end",
"def html_parser; end",
"def get_sentences(html)\n # var html = (typeof el==\"string\") ? el : el.innerHTML;\n\n # exclusion lists\n mrsList = \"Mr,Ms,Mrs,Miss,Msr,Dr,Gov,Pres,Sen,Prof,Gen,Rep,St,Messrs,Col,Sr,Jf,Ph,Sgt,Mgr,Fr,Rev,No,Jr,Snr\"\n topList = \"A,B,C,D,E,F,G,H,I,J,K,L,M,m,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,etc,oz,cf,viz,sc,ca,Ave,St\"\n geoList = \"Calif,Mass,Penn,AK,AL,AR,AS,AZ,CA,CO,CT,DC,DE,FL,FM,GA,GU,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MH,MI,MN,MO,MP,MS,MT,NC,ND,NE,NH,NJ,NM,NV,NY,OH,OK,OR,PA,PR,PW,RI,SC,SD,TN,TX,UT,VA,VI,VT,WA,WI,WV,WY,AE,AA,AP,NYC,GB,IRL,IE,UK,GB,FR\"\n numList = \"0,1,2,3,4,5,6,7,8,9\"\n webList = \"aero,asia,biz,cat,com,coop,edu,gov,info,int,jobs,mil,mobi,museum,name,net,org,pro,tel,travel,xxx\"\n extList = \"www\"\n d = \"__DOT__\"\n\n # cleanup \".\" that should not be used for sentence splitting\n list = (topList+\",\"+geoList+\",\"+numList+\",\"+extList)\n # html = html.replace(new RegExp((\" \"+list[i]+\"\\\\.\"), \"g\"), (\" \"+list[i]+d))\n regexp = Regexp.new \" (#{list.gsub(/,/,\"|\")})\\\\.\"\n html = html.gsub(regexp){|match| \" #{match}#{d}\"}\n # puts regexp.inspect\n\n list = (mrsList+\",\"+numList)\n # html = html.replace(new RegExp((list[i]+\"\\\\.\"), \"g\"), (list[i]+d))\n regexp = Regexp.new \"(#{list.gsub(/,/,\"|\")})\\\\.\"\n html = html.gsub(regexp){|match| \"#{match}#{d}\"}\n\n list = webList\n # html = html.replace(new RegExp((\"\\\\.\"+list[i]), \"g\"), (d+list[i]))\n regexp = Regexp.new \"\\\\.(#{list.gsub(/,/,\"|\")})\"\n html = html.gsub(regexp){|match| \"#{d}#{match}\"}\n\n # split sentences\n lines = clean_array(html.split('. '))\n return lines\n end",
"def scrape_1_page(page)\n p \"scraping a page\" #{link.href}\" \n blog_date_1 = nil #the first part of the pubDate field goes into here\n blog_body = nil #the body text goes here\n blog_date_2 = nil #the second part of the pubDate field goes into here\n comments_arr = nil #temporary storage for comments before they get added to main document\n \n #select on td id=maincontent\n page.search('#maincontent')[0].each_child{ |child|\n \n if @max_blog_entries != nil and @curr_blog_entries >= @max_blog_entries\n @completed = true\n p \"reached max_blog_entries=#{@max_blog_entries}\"\n return\n end\n \n if child.search('.blogheader').length != 0\n blog_date_1 = convert_xanga_header_to_wordpress_date(child.inner_html)\n p \"blog head #{blog_date_1}\" \n #this is first part of date-time\n\n elsif child.search('.blogbody').length != 0\n #TODO: extract comments, number of views for blog\n \n #this is body of the blog\n blog_body = sanitize_blog_body(child.search(\"td\")[1].inner_html)\n \n p \"blog body=#{blog_body}\"\n \n #extract the date of blog for archiving purposes\n #inside class blogbody, lives a class smalltext, and we want the inner_html of the second <a href> tag\n blog_date_2 = convert_to_usable_time(child.search('.blogbody')[0].search('.smalltext')[0].search(\"a\")[1].inner_html)\n \n #create teh new document out of blogheader and blogfooter\n doc = create_new_xml_blog( blog_body, blog_date_1 + blog_date_2 )\n \n #catch comments here\n #inside class blogbody, lives a class smalltext, and we want the inner_html of the fifth <a href> tag\n if child.search('.blogbody')[0].search('.smalltext')[0].search(\"a\")[4].inner_html != \"add comments\"\n comments_arr =scrape_comments( Hpricot::Elements[ child.search('.blogbody')[0].search('.smalltext')[0].search(\"a\")[4] ].attr(\"href\") )\n comments_arr.each { |comment| \n doc.search(\"item\").append(comment.inner_html.to_s)\n #p \"adding comment here #{comment.inner_html.to_s}\"\n }\n #dump_page(doc)\n end\n\n #add resulting document to the @doc object already created\n @doc.search(\"channel\").append(doc.inner_html.to_s) \n\n @curr_blog_entries += 1\n end\n \n }\n end",
"def processSimpleStructure( doc, linelist )\r\n\r\n pages = 0\r\n lines = 0\r\n\r\n # process the list of pages\r\n doc.elements.each('//milestone') do | page |\r\n\r\n #puts page.attributes\r\n folio = page.attributes[\"entity\"]\r\n pages += 1\r\n\r\n nextnode = page.next_sibling_node( )\r\n while nextnode != nil do\r\n if ( nextnode.kind_of? REXML::Text ) == false\r\n case nextnode.name\r\n when \"l\"\r\n processLineNode( nextnode, folio, linelist )\r\n lines += 1\r\n\r\n when \"milestone\"\r\n break\r\n\r\n else\r\n puts \"UNPROCESSED TAG in processSimpleStructure #{nextnode.name}\"\r\n end\r\n else\r\n # nothing else of interest here so this is not an error\r\n #puts \"UNEXPECTED TEXT TAG in processSimpleStructure #{nextnode.value}\"\r\n end\r\n nextnode = nextnode.next_sibling_node()\r\n end\r\n end\r\n puts \"Processed #{pages} pages, #{lines} lines\"\r\n end",
"def parse_html(html_body)\t\n #puts \"Parsing the html content: #{html_body}. Return DOM \" if @verbose\n\t\tbegin\n doc = Nokogiri::HTML(html_body)\n\t\t\t#puts \"Successfully crawling the url: #{url_object.base_uri.to_s}\" if @verbose\n\t\t\t#puts \"doc: #{doc}\" if @verbose\n\t\t\treturn doc\n rescue => ee\n puts \"Exception on method #{__method__}: #{ee}\" if @verbose\n return nil\n end\n\tend",
"def parse_page\n @doc = Nokogiri::HTML(@html)\n end",
"def call\n doc.search('pre').each do |pre|\n process_pre_tag(pre)\n end\n\n doc\n end",
"def parse_body\n return if @doc\n\n @doc = Nokogiri.XML(self.body)\n values = {}\n values[:title] = @doc.attributes['title'].text rescue nil\n @doc.search('background').each do |bkelt|\n if bkelt.attributes['image']\n @background_image = bkelt.attributes['image']\n end\n end\n values[:pages] = @doc.search(\"page\").collect {|xml| Page.new(xml)}\n\n @title = values[:title]\n @pages = values[:pages]\n @pages.each_with_index {|page,idx| page.number = idx}\n end",
"def completed_text_extraction\n end",
"def index_file(file, pages_dir, stopwords, file_data)\n # Removing the dir from the file name\n # begin\n actual_name = file.gsub(pages_dir, \"\")\n # rescue NoMethodError\n# actual_name = badpage.html\n \n\n # Resetting the file path\n file_path = \"\"\n file_path = File.expand_path(\".\") + \"/\" + file\n\n print \"Parsing HTML document: \" + actual_name + \" \\n\"\n\n # Finding all the tokens in the file\n tokens = find_tokens(file_path)\n\n # Getting the page title, word count, and page url\n page_title = get_title(file_path)\n word_count = tokens.length\n page_url = file_data[actual_name]\n\n # Updating the docindex hash\n $docindex[file.gsub(pages_dir, \"\")] = [word_count, page_title, page_url]\n\n # Removing the stop words and getting the stem words in the file\n tokens = remove_stop_tokens(tokens, stopwords)\n tokens = stem_tokens(tokens)\n\n # Creating the invindex hash table\n for token in tokens\n begin\n if $invindex.member?(token)\n if $invindex[token].member?(actual_name)\n $invindex[token][actual_name] += 1\n else\n $invindex[token][actual_name] = 1\n end\n else\n $invindex[token] = {actual_name => 1}\n end\n # end\n# rescue NoMethodError\n # puts \"NoMethodError\"\n end\n #puts file_name\n # title = nil\n end\n #end\nend",
"def scan\n @time_cache = {}\n\n entries = parse_entries\n grouped_entries = group_entries entries\n\n doc = create_document grouped_entries\n\n @top_level.comment = doc\n\n @top_level\n end",
"def index_page_scrape(html, r_url, resource)\n count = Selector.where(scrape_resource_id: resource.id, top_level: true).reduce(0) do |acc, ts|\n # an array of all the top-level items for a given tag. these are nokogiri nodes\n blocks = html.css(ts.selector)\n\n blocks.each do |block| # iterates over Nokogiri nodeset for given css selector\n # logger.info \"scraping index page with block: #{block}\"\n\n # creates a model with default scrape resource info set\n # logger.info 'CREATING NEW TEMPLATE MODEL'\n new_model = ts.model.new(scrape_resource_id: resource.id,\n url: r_url.url,\n institution_id: resource.institution_id,\n public: true)\n\n iterate_children(ts, block, new_model)\n\n # saves new model and increments count if it was inputted\n acc + 1 if validate_and_save(new_model)\n end # end items iteration\n end # end selector iteration\n count\n end",
"def process_link(link, dir, spamCalc, index)\n page = retrieve_page(link)\n if page\n fileName = index.to_s + '.html'\n path = File.join(dir, fileName)\n page.save(path.to_s)\n scoreAndFilename = []\n score = spamCalc.evaluate_document(page.body)\n scoreAndFilename.push(score)\n scoreAndFilename.push(fileName)\n $index[link] = scoreAndFilename\n return [page, score]\n else\n return nil\n end\nend",
"def process_detail_html_pages\n start = Time.now\n\n # get all ids\n # - need this to get image id for image url\n all_ids = CSV.read(\"#{@listings_folder}/merged_ids.csv\")[1..-1]\n\n # get list of html files\n html_files = Dir.glob(\"#{@details_folder}/*.html\")\n remaining_files = []\n\n if html_files.nil? || html_files.length == 0\n puts \"NO HTML FILES EXIST TO PROCESS!\"\n exit\n end\n\n # get csv data, if not exist, create it\n if !File.exist?(@csv_data)\n CSV.open(@csv_data, 'wb') do |csv|\n # headers\n csv << @csv_headers\n end\n end\n csv_data = CSV.read(@csv_data)\n\n # if there is data that is already processed,\n # get the processed ids so we do process them again\n remaining_files = if csv_data.length > 0\n # first column is ids\n html_files - csv_data[1..-1].map{|x| \"#{@details_folder}/#{x[0]}.html\"}\n else\n html_files\n end\n\n # get rid of the csv data\n # - reduce memory load\n csv_data = nil\n\n # for each file\n # - open it in nokogiri\n # - pull out the data\n # - append to csv\n if remaining_files.length == 0\n puts \"there are NO files to process\"\n else\n puts \"there are #{remaining_files.length} files to process\"\n\n remaining_files.each_with_index do |file, index|\n row_data = []\n\n if index%50 == 0\n puts \"#{index} files processed so far in #{((Time.now-start)/60).round(2)} minutes\\n\\n\"\n end\n\n # open in nokogiri\n doc = File.open(file) { |f| Nokogiri::XML(f) }\n\n ###################\n # process the data\n # - id\n row_data << process_value(doc.css('#id_res'))\n\n # - last name\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Фамилия\") + .card_param-result'))\n\n # - first name\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Имя\") + .card_param-result'))\n\n # - middle name\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Отчество\") + .card_param-result'))\n\n # - birth_date\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Дата рождения/Возраст\") + .card_param-result'))\n\n # - place of birth\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Место рождения\") + .card_param-result'))\n\n # - date/place of recruitment\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Дата и место призыва\") + .card_param-result'))\n\n # - last place of service\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Последнее место службы\") + .card_param-result'))\n\n # - military rank\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Воинское звание\") + .card_param-result'))\n\n # - death reason\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Причина выбытия\") + .card_param-result'))\n\n # - death date\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Дата выбытия\") + .card_param-result'))\n\n # - initial burial location\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Первичное место захоронения\") + .card_param-result'))\n\n # - source name\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Название источника донесения\") + .card_param-result'))\n\n # - source fund number\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Номер фонда источника информации\") + .card_param-result'))\n\n # - source description number\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Номер описи источника информации\") + .card_param-result'))\n\n # - source file number\n row_data << process_value(doc.css('.card_parameter .card_param-title:contains(\"Номер дела источника информации\") + .card_param-result'))\n\n # - source image url\n # - use the image id from the listings csv file to build the url\n record = all_ids.select{|x| x[0] == row_data[0]}.first\n if record.nil? || record[1].nil? || record[1] == ''\n row_data << nil\n else\n row_data << \"#{@image_url}#{record[1]}\"\n end\n\n\n ###################\n # append to the csv\n CSV.open(@csv_data, 'a') do |csv|\n csv << row_data\n end\n end\n end\nend",
"def content_from(html, url)\n \n def extract_pre_from(html)\n regex = /<pre.*?>.*?<\\/pre>/m\n pre_list = html.scan regex\n html.gsub! regex, 'DUMMY-STRING'\n [pre_list, html]\n end\n\n def add_domain(html, domain)\n html.gsub! /a href=\\\"(\\/.*?\\\")/, \"a href=\\\"#{domain}\\\\1\"\n html.gsub! /img src=\\\"(\\/.*?\\\")/, \"img src=\\\"#{domain}\\\\1\"\n html\n end\n\n def add_pre(html, pre_list)\n pre_list.each do |p|\n html.sub!('DUMMY-STRING', p)\n end\n html\n end\n \n pre_list, replaced = extract_pre_from html\n params = { :tags => %w[div span p a b i pre h1 h2 h3 h4 h5 h6 strong small em\n blockquote ul ol li img],\n :attributes => %w[href src] }\n html = HtmlPress.press Readability::Document.new(replaced, params).content\n domain = domain_of url\n output = add_pre(add_domain(html, domain), pre_list)\n output = sanitize_with_img output\n output.gsub /<img /, \"<img onError=\\\"this.style.display='none';\\\" \"\n \n end",
"def scan\n comment = RDoc::Comment.new @content, @top_level\n comment.format = 'rd'\n\n @top_level.comment = comment\n end",
"def parsed_document\n @parsed_document ||= Nokogiri::HTML(document)\n rescue Exception => e\n add_fatal_error \"Parsing exception: #{e.message}\"\n end",
"def presentable_html(html)\n # sanitize edited, tags: %w(body p span a h1 h2 h3 h4 h5 h6 ul ol li) if work.file_content_html %> -->\n # doc = Nokogiri::HTML(html_junk)\n # body = doc.at_xpath(\"//body\")\n # body.css('*').remove_attr('class')\n # edited = body.to_html\n return raw html\n end",
"def page_sentiment (positive, negative)\n totalwords = 0\n count = 0.0\n sentimentwords = 0.0\n if(@thewords)\n #This is the main loop, if each word is positive or negative in the document adjust variables accordingly.\n @thewords.each do |word|\n totalwords+= 1\n if positive.map(&:downcase).include? word[0].downcase\n # puts word[0]\n count +=word[1]\n sentimentwords +=word[1]\n elsif negative.map(&:downcase).include? word[0].downcase\n # puts word[0]\n count -=word[1]\n sentimentwords +=word[1]\n end\n end\n end\n ratio = count/sentimentwords\n if (ratio > 0.10)\n count = 1\n elsif (ratio < -0.10)\n count = -1\n else\n count = 0\n end\n return count\n end",
"def work_examples!\n @html.css('pre').each do |pre|\n lines = pre.content.split(\"\\n\")\n first_line = lines.first.to_s.strip\n next unless first_line.match(/^# ([A-Za-z]+)$/i)\n\n sections = split_lines(lines)\n example = Example.new sections\n @examples.push example\n template = Tilt.new(Ifdoc.root('data', 'templates', 'example.haml'))\n\n pre.after(template.render(example))\n pre.remove\n end\n end",
"def post_analyze!\n contents = File.open(self.name, 'r').readlines\n exelines = 0\n contents.each_with_index do |line, num|\n sline = line.strip\n \n case sline\n when '', /^#/\n lines << num + 1\n when /^\\s*(?:end|\\})\\s*(?:#.*)?$/, /^(public|private|protected)/,\n /^(?:begin\\s*(?:#.*)?|ensure\\s*(?:#.*)?|else\\s*(?:#.*)?)$/,\n /^(?:rescue)/, /^case\\s*(?:#.*)?$/, /^(\\)|\\]|\\})(?:#.*)?$/\n lines << num + 1\n exelines += 1\n else\n exelines += 1\n end\n \n end\n \n @coverage_percent = (exelines.to_f / contents.size) * 100.0\n end",
"def check_html(url, refs)\n file = get_internal_file(url)\n html = file ? Fs.read(file) : get_http(url)\n\n if html.nil?\n add_invalid_url(url, refs)\n return\n end\n\n add_valid_url(url, refs)\n return if url[0] != \"/\"\n\n # self site path\n if !same_domain_site_path?(url)\n return\n end\n\n # self site and mobile path\n if !@check_mobile && mobile_url?(url)\n return\n end\n\n begin\n html = NKF.nkf \"-w\", html\n\n # scan layout_yield offset\n html.scan(/<!-- layout_yield -->(.*?)<!-- \\/layout_yield -->/m)\n yield_start, yield_end = Regexp.last_match.offset(0) if Regexp.last_match\n yield_start ||= html.size\n yield_end ||= 0\n\n # remove href in comment\n html.gsub!(/<!--.*?-->/m) { |m| \" \" * m.size }\n\n html.scan(/\\shref=\"([^\"]+)\"/i) do |m|\n offset = Regexp.last_match.offset(0)\n href_start, href_end = offset\n inner_yield = (href_start > yield_start && href_end < yield_end)\n\n next_url = m[0]\n next_url = next_url.sub(/^#{::Regexp.escape(@base_url)}/, \"/\")\n next_url = next_url.sub(/#.*/, \"\")\n\n next unless valid_url(next_url)\n\n internal = (next_url[0] != \"/\" && next_url !~ /^https?:/)\n next_url = File.expand_path next_url, url.sub(/[^\\/]*?$/, \"\") if internal\n next_url = Addressable::URI.encode(next_url) if next_url.match?(/[^-_.!~*'()\\w;\\/?:@&=+$,%#]/)\n\n next_url = @ref_string.new(next_url, offset: offset, inner_yield: inner_yield)\n\n if @results[next_url] == 1\n next\n elsif @results[next_url] == 0\n add_invalid_url(next_url, [url])\n else\n @urls[next_url] ||= []\n @urls[next_url] << url\n end\n end\n rescue => e\n Rails.logger.error(e.message)\n add_invalid_url(url, refs)\n end\n end",
"def parse_html(old_dom, path_to_article)\n # ToC and lead-in\n # NOTE: ToC may prove to be a problem because it appears in the left-hand column on the page. we may want to do some JS node swapping onDOMReady. ignoring it for now.\n # 1) get children of <ul class=\"acm\">\n # 2) remove lead-in pound-down if present (first LI)\n # 3) get .inner_html of second <p> after <a name=\"lead-in\"></a> if A exists\n\n toc_node = (old_dom/\"ul.acm\")[0]\n toc_node.children.reject! { |el| (el/\"//a[@href='#lead-in']\").length > 0 }\n\n # the (4) is because of the whitespace nodes in between the element nodes\n # NOTE: the nodes_at method is a bit noisy and outputs some text in the console. weird.\n leadin_node = (old_dom/\"//a[@name='lead-in']\")\n leadin = leadin_node.length > 0 ? remove_whitespace(leadin_node[0].nodes_at(4).inner_html) : \"\"\n\n # journal name\n # 1) get .inner_html of <div class=\"jrnl\">\n\n journal_name = remove_whitespace((old_dom/\".jrnl\")[0].inner_html)\n\n # vol, issue, page #\n # 1) get .inner_html of <div class=\"iss\">\n\n vol_issue_page = remove_whitespace((old_dom/\".iss\")[0].inner_html)\n\n # full-text Anchor / Heading structure (observed)\n # \n # lead-in => extracted\n # body-1 => kept intact, back-to-top removed\n # body-n => kept intact\n # references => kept intact\n # authorinfo => kept intact\n # footnotes => kept intact\n # figures => kept intact\n # tables => kept intact\n # sidebar-1 => kept intact\n # sidebar-n => kept intact\n # permission => kept intact, back-to-top removed\n\n # \"body-n\" section headings / back to top look like this:\n # \n # <a name=\"body-3\"></a>\n # <p>\n # <a href=\"#top\"><img src=\"http://portal.acm.org/img/arrowu.gif\" border=\"0\" alt=\"back to top\"> </a>\n # <b>Moderator</b>\n # </p>\n # \n # 1) attempt to find each <a name=\"body-n\"></a> element\n # 2) immediately after element is the P that contains the back to top link and B tag with the section heading\n # NOTE: body-1 does not have a B tag in the P (i've seen it referenced as \"Introduction\" or \"Article\" in the ToC)... remove it.\n # 3) get inner_html of B tag\n # 4) remove P tag\n # 5) insert new back to top link before A tag\n # <p class=\"totop\"><a href=\"#PageTop\">Back to Top</a></p>\n # 6) insert new Hx tag (with contents of the B tag) after A tag \n # NOTE: we may want it in Hx tag, or give the Hx tag the ID of the old A tag and remove the A tag altogether... we'll see\n\n # known headings look like this:\n # \n # <a name=\"authorinfo\"></a>\n # <p>\n # <a href=\"#top\"><img src=\"http://portal.acm.org/img/arrowu.gif\" border=\"0\" alt=\"back to top\"> </a>\n # <b>Author</b>\n # </p>\n # \n # (same as body-n headings except we replace them with slightly different Hx tags... TBD exactly)\n\n known_headings = %w(references authorinfo footnotes figures tables permission)\n body_regex = /^body-\\d+$/\n sidebar_regex = /^sidebar-\\d+$/\n back_to_top = %{<p class=\"totop\"><a href=\"#PageTop\">Back to Top</a></p>\\n\\n}\n\n (old_dom/\"//a[@name]\").each do |anchor|\n next unless known_headings.include?(anchor['name']) || anchor['name'].match(body_regex) || anchor['name'].match(sidebar_regex)\n\n # the (2) is because of the whitespace nodes in between the element nodes\n p = anchor.nodes_at(2)\n\n if anchor['name'] == \"body-1\"\n p.remove\n\n elsif anchor['name'] == \"permission\"\n p.remove\n anchor.before(%{<hr class=\"Separator\" />\\n})\n\n else\n heading = remove_whitespace((p/'b')[0].inner_html)\n p.remove\n # put the back-to-top link in between the comments so the soon-to-be-created DIV doesn't wrap it\n anchor.nodes_at(-2).before(back_to_top)\n classname = known_headings.include?(anchor['name']) ? ' class=\"known-headings\"' : \"\"\n anchor.after(%{\\n<h3#{classname}>#{heading}</h3>})\n end\n end\n \n # Fix Article figures and tables\n HtmlMaid.fix_figures_and_tables(old_dom)\n \n # We just gave the figures \"back to top\" link the wrong class name. Fix:\n (old_dom/\".ThumbnailParagraph\").each do |thumb_para|\n thumb_para.set_attribute :class, \"totop\" if thumb_para.inner_text.downcase.eql?(\"back to top\")\n end\n \n # Rewrites URLs and img SRCs to point to deliveryimages.org\n HtmlMaid.change_link_and_img_paths(old_dom, path_to_article)\n \n # final processing\n # 1) body.inner_html\n # 2) remove everything up to <!-- BEGIN BODY-1 -->\n\n html = (old_dom/:body).inner_html.gsub(/^.+(<!-- BEGIN BODY-1 -->)/m, '\\\\1')\n\n # add DIVs around known sections for styling purposes\n # \n # FIXME: this can probably be optimized by avoiding the ruby interator \n # and using regexp groups and backreferences to pull out the individual items\n known_headings.each do |heading|\n re = Regexp.new(\"(<!-- BEGIN #{heading.upcase} -->)(.+)(<!-- END #{heading.upcase} -->)\", Regexp::MULTILINE)\n html = html.gsub(re, %{\\\\1\\n<div id=\"article-#{heading}\">\\n\\\\2\\n</div>\\n\\\\3})\n end\n\n # do the same for sidebars, albeit a bit more complicated regex-wise\n html = html.gsub(/(<!-- BEGIN (SIDEBAR-(\\d)) -->)\\s*(<a name=\"(sidebar-\\3)\"><\\/a>)(.+)(<!-- END \\2 -->)/m, %{\\\\1\\n<div class=\"ArticleSidebar\" id=\"article-\\\\5\">\\n\\\\4\\n\\\\6\\n</div>\\n\\\\7})\n \n # Why don't all tables and figures get a \"back to top\" link? Not sure, \n # but let's give it one... unless it's a black sheep that already has one.\n \n # Now we're going to be evil and RE-parse this stuff to safely re-insert\n # some back to top links for figures and tables...\n \n new_dom = Hpricot(html)\n \n # Find the DIVs that are now wrapping the figures and tables. \n \n figures_div = new_dom.at(\"#article-figures\")\n tables_div = new_dom.at(\"#article-tables\")\n \n if figures_div\n # Don't add double back-to-top links!\n unless figures_div.children_of_type(\"p\").last.get_attribute(:class).eql?(\"totop\")\n # Just to be paranoid, let's also make sure they didn't sneak one in\n # after the wrapping div, either...\n unless figures_div.next_sibling.name.eql?(\"p\") and figures_div.next_sibling['class'].eql?(\"totop\")\n \n # Swap the ENTIRE div for the div + totop link\n # Why can't Hpricot just insert a string after an Hpricot::Elem?\n # ... I'll add that to my hpricot_extensions wish list.\n \n figures_div.swap(figures_div.to_html + '<p class=\"totop\"><a href=\"#PageTop\">Back to top</a></p>')\n end\n end\n end\n \n # Rinse, repeat\n if tables_div\n unless tables_div.children_of_type(\"p\").last.get_attribute(:class).eql?(\"totop\")\n unless tables_div.next_sibling.name.eql?(\"p\") and tables_div.next_sibling['class'].eql?(\"totop\")\n tables_div.swap(tables_div.to_html + '<p class=\"totop\"><a href=\"#PageTop\">Back to top</a></p>')\n end\n end\n end\n \n # OK, back to packaging this up...\n html = new_dom.to_html\n \n return {\n :full_text => html,\n :leadin => leadin,\n :journal_name => journal_name,\n :vol_issue_page => vol_issue_page,\n :toc => toc_node.inner_html\n }\n\n ensure\n toc_node = nil\n old_dom = nil\n leadin_node = nil\n GC.start\n end",
"def parse_file(file)\n comment_symbol = \"//\"\n comment_matcher = Regexp.new('^\\\\s*' + comment_symbol + '\\\\s?')\n comment_filter = Regexp.new('(^#![/]|^\\\\s*#\\\\{)')\n\n docs_text = code_text = '';\n has_code = false\n \n if @filename\n #puts \"FILE: #{@filename}\" #debugging\n #get file as one string for class detecting\n f = File.new(@filename)\n text = f.read\n f.close\n \n code = IO.readlines(@filename)\n code.each_with_index do |line, index|\n if comment_matcher.match(line) and !comment_filter.match(line) \n if has_code\n save_section(docs_text, code_text)\n \n #reset docs and code\n docs_text = code_text = ''\n has_code = false\n end\n\n #docs_text += line.sub(comment_matcher, '') + \"\\n\"\n docs_text += line.sub(comment_matcher, '')\n else\n #remove tabs\n #line.gsub!(\"\\t\", \"\")\n line.gsub!(\"\\t\", \" \")\n\n #remove newlines\n line.gsub!(/\\n+/, \"\")\n\n #remove whitespace\n line.gsub!(/$\\s+/, \"\")\n line.gsub!(/^\\s+/, \"\")\n\n line = line.gsub('\\t', \"\").gsub('\\n',\"\").gsub(/\\s+1/,\"\")\n\n has_code = true\n code_text += line + \"\\n\"\n #code_text += line\n \n if line.match(/(class|public|private)\\s+((?!boost)\\w+\\s*)(\\s+|;|:|\\{)?/)\n keyword = $2\n thirdComponent = $3\n #remove all beginning and trailling whitespace\n keyword = keyword.gsub(/^\\s+/, \"\").gsub(/\\s+$/, \"\")\n\n pKeyword = PotionKeyword.new(keyword)\n pKeyword.origin = @filename.split('/').last\n #puts \"\\tChecking #{pKeyword.word}...\" #debugging\n if @master_list_ref.contains_keyword(keyword) == false && thirdComponent != \";\" && keyword.length > 1\n @master_list_ref.keywords << pKeyword \n #puts \"\\tMatched Line: #{line}\" #debugging\n #puts \"\\tAdded #{keyword} to the master list\\n\\n\" #debugging\n end\n end\n end\n end\n\n save_section(docs_text, code_text)\n end\n end",
"def ml_scrape(body_ml, url, result_xpaths, max_results = nil, \n res_href_append = nil, result_filter = nil, result_matcher = nil, \n content_max_length = nil)\n\n result_xpaths = [ result_xpaths ] unless result_xpaths.class == Array\n max_results = MAX_RESULTS if max_results > MAX_RESULTS\n\n @log.debug \"ml_scraping for #{max_results} results with \" +\n \"'#{result_xpaths.join(', ')}' in #{body_ml.length} bytes \" +\n \"from #{url}\"\n\n ret=[]\n doc = Nokogiri.parse(body_ml)\n result_xpaths.each do |result_xpath|\n @log.debug \"result_xpath: #{result_xpath}\"\n counter = max_results\n doc.search(result_xpath).each do |link|\n @log.debug \"to match on link: \" + PP.singleline_pp(link, '')\n if result_matcher.nil? or not link.search(result_matcher).empty?\n if counter > 0\n @log.debug \"matched: \" + PP.singleline_pp(result_matcher, '')\n # ...in case no 'href' attr. for tag\n result_href = link.content if result_filter\n\n if link['href'] && link['href'].start_with?(\"/\")\n uri = Addressable::URI.parse url\n result_href = uri.omit(:user, :password) + link['href']\n\n elsif link['href']\n result_href = link['href']\n end\n\n\n if link.content == nil || link.content == \"\"\n content = result_href\n elsif not link.element_children.empty?\n content = link.element_children.first.content\n link.element_children[1..-1].each { |c| content << \", #{c.content}\" }\n else\n content = link.content\n end\n\n @log.debug \"content: \" + PP.singleline_pp(content, '')\n if content && result_filter\n content = CGI.unescape(content.gsub(Regexp.new(result_filter), \n '\\1'))\n end\n\n @log.debug \"counter: #{counter}, content: #{content}, href+: \" +\n \"#{result_href}#{res_href_append}\"\n ret.push(\"#{truncate(content,\n :length => content_max_length || CONTENT_MAX_LENGTH,\n :separator => ' ')} \" + \"#{result_href}#{res_href_append}\")\n counter -= 1\n end\n end\n end\n end\n\n ret\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.52547604",
"0.52386737",
"0.52342325",
"0.52181685",
"0.5208144",
"0.5203867",
"0.51812726",
"0.5179793",
"0.51780254",
"0.5174067",
"0.5172267",
"0.51695466",
"0.5151634",
"0.51492923",
"0.5145439",
"0.51366687",
"0.5119612",
"0.51191264",
"0.5114773",
"0.5111858",
"0.510888",
"0.51048535",
"0.50920224",
"0.5085439",
"0.508261",
"0.5069779",
"0.50653905",
"0.50569487",
"0.50532323",
"0.5048001",
"0.5047563",
"0.50462705",
"0.50379133",
"0.50337744",
"0.5032874",
"0.50327206",
"0.5030936",
"0.502361",
"0.5021521",
"0.50149673",
"0.50103164",
"0.50088954",
"0.50058734",
"0.50005597",
"0.4996511",
"0.4994905",
"0.4990385",
"0.49883965",
"0.49778557",
"0.49759194",
"0.4971686",
"0.49644482",
"0.49508584",
"0.49499008",
"0.49495253",
"0.4935548",
"0.49325186",
"0.49244243",
"0.49229607",
"0.49189332",
"0.49076238",
"0.49061373",
"0.49013668",
"0.49002045",
"0.4898456",
"0.48942626",
"0.48926562",
"0.48904455",
"0.48872647",
"0.48756835"
] | 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 !@schema.tag_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",
"def useless?\n content.nil? and children.empty?\n end",
"def test_block_empty\n check(C::Block, <<-EOS)\n | {\n | }\n EOS\n end",
"def empty_content?(element)\n element.texts.join.blank?\n end",
"def text_node?(element)\n !element.text? && element.all? {|c| c.text?}\n end",
"def content_for?(symbol)\n !content_blocks[symbol].empty?\n end",
"def text_content?\n @node.children.all?(&:text?)\n 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 has_tag?(name); end",
"def is_tagged?\n ! @tags.empty?\n end",
"def test_no_tag\n @tag.on_root('t002.txt', nil)\n @tag.after_root('t002.txt', nil)\n assert_equal '1', @tag.tag_page_db['t002_, __no_tag_']\n end",
"def text_content?\n @node.children.all? {|c| c.text?}\n end",
"def xhtml_block?(method, arguments)\n if XHTML_TAG_NAMES.include?(method.to_s)\n last = arguments.last\n last.is_a?(Hash) && last[:type].to_s == \"xhtml\"\n end\n end",
"def is_tagged?\n ! @tags.empty?\n end",
"def blocks?\n !@blocks.empty?\n end",
"def have_empty_tag tag, options = {}\n have_tag(tag, options.merge(:blank => true))\n end",
"def text_element?(node)\n node.element? && node.attributes.empty? && node.children.size == 1 && node.children.first.text?\n end",
"def mid_block_keyword?(text)\n text[MID_BLOCK_KEYWORD_REGEX, 1]\n end",
"def is_block_valid?(hash)\n if @block_index.block_header_in_index?(hash)\n return true\n end\n !Toshi::Models::Block.main_or_side_branch.where(hsh: hash).empty?\n end",
"def hastag1?\n ! @tag1.empty?\n end",
"def if_tag(tag_name, content, html_options={},condition=!content.blank?)\n content_tag(tag_name, content, html_options) if condition\nend",
"def is_block_processed?(hash)\n # we try to reprocess orphans\n Toshi::Models::Block.where(hsh: hash).exclude(branch: Toshi::Models::Block::ORPHAN_BRANCH).any?\n end",
"def modified?\n return true if @text.blank? || @parent_post.blank?\n\n parent_text = Nokogiri::HTML::fragment(@parent_post.cooked).text.delete(QuoteComparer.whitespace)\n text = @text.delete(QuoteComparer.whitespace)\n\n !parent_text.include?(text)\n end",
"def contains_heredoc?(node)\n node.each_descendant(:str, :xstr, :dstr).any?(&:heredoc?)\n end",
"def open_tag?(tag)\n !close_tag?(tag)\n end",
"def no_tags label\n return label.gsub(/\\<.+\\/?\\>/,'')\n end",
"def tag\n @tag ||= page.tags(true).detect{|t| t.is_cms_block? && t.identifier == identifier}\n end",
"def parse_blocks(el, text = T.unsafe(nil)); end",
"def text_node?(node)\n node.name == \"text\"\n end",
"def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end",
"def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end",
"def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end",
"def is_not(&block)\n [:is_not, block]\n end",
"def is_not(&block)\n [:is_not, block]\n end",
"def empty_tags\n ['area', 'base', 'br', 'col', 'frame', \n 'hr', 'img', 'input', 'link', 'meta']\n end",
"def empty_tags\n ['area', 'base', 'br', 'hr', 'img', 'input', 'link', 'meta']\n end",
"def inside_ignorable_element(n)\n while not n.kind_of? Nokogiri::HTML::Document and n.kind_of? Nokogiri::XML::Node and n.parent() != nil\n if ignorable_element(n)\n return true\n else\n n = n.parent\n end\n end\n false\n end",
"def hastag2?\n ! @tag2.empty?\n end",
"def stripped_text_blocks\n stripped = []\n text_blocks.each do |tb|\n if \"Boston Police Department\" == tb && %r{^\\d+/\\d+/\\d{4} } =~ stripped.last\n # skip\n stripped.pop\n elsif /, Police Commissioner/ =~ tb\n # skip\n elsif /^Selected & Sorted By:/ =~ tb\n # skip\n elsif /^Record Count:/ =~ tb\n # skip\n stripped.pop if /^\\d+$/ =~ stripped.last\n elsif /^(Date:|Reported|Occurred)$/ =~ tb\n # skip\n else\n stripped << tb\n end\n end\n stripped\n end",
"def test_tags_include_all_filter_tags?(test_tags)\n (@filter_tags - test_tags).empty?\n end",
"def close_tag?(tag)\n tag.include?(\"</\") ? true : false\n end",
"def non_printable_node?(node)\n %w[style head title meta script].include?(node.name.downcase)\n end",
"def text?\n @contents[0] == :text\n end",
"def block_word?(string)\n up_string = string.upcase\n BLOCKS.none? { |block| up_string.count(block) >= 2 }\nend",
"def only_allowed_in_parent_tags?\n !@definition[:only_in].nil?\n end",
"def text_element_valid? node\n node.traverse do |self_or_descendant|\n if self_or_descendant.text?\n begin\n if find_elmt_index(self_or_descendant).nil?\n throw \"Text element for '#{self_or_descendant.text}' can't be found in elmt_bounds.\"\n end\n rescue Exception => exc\n return false\n end\n return false unless nknode_valid?(self_or_descendant)\n end\n end\n return true\n end",
"def element_is_opening_tag?\n self[:is_tag] && !self[:closing_tag]\n end",
"def strip_html(text)\n unless text.nil?\n strip_tags(text)\n end\n end",
"def before_appending( parsestate )\n\t\tcondtag = parsestate.node_stack.reverse.find do |node|\n\t\t\tcase node\n\t\t\twhen Inversion::Template::IfTag,\n\t\t\t Inversion::Template::CommentTag\n\t\t\t\tbreak node\n\t\t\twhen Inversion::Template::ContainerTag\n\t\t\t\traise Inversion::ParseError, \"'%s' tags can't have '%s' clauses\" %\n\t\t\t\t\t[ node.tagname.downcase, self.tagname.downcase ]\n\t\t\tend\n\t\tend\n\n\t\tunless condtag\n\t\t\traise Inversion::ParseError, \"orphaned '%s' tag\" % [ self.tagname.downcase ]\n\t\tend\n\tend",
"def element_does_not_contain_text(locator, text)\n return true unless selenium.is_element_present(locator)\n return !get_inner_html(locator).include?(text)\n end",
"def xhtml_block?(method, arguments); end",
"def has_no_meta_tag?(name, content)\n has_no_selector?(:xpath, \"/html/head/meta#{meta_tag_locator(name, content)}\", visible: false)\n end",
"def element_does_not_contain_text(locator, text)\n return true unless is_element_present(locator)\n return !element(locator).contains?(text)\n end",
"def has_tags?\n tags.is_a?(Hash) ? false : true\n end",
"def no_245_has_ak?\n no_fields?(tag: '245', complex_subfields: [[:has, code: /[ak]/]])\n end",
"def blank_body?\n Sanitize.clean(self.body).gsub(/[ | ]/, '').blank? \n end",
"def has_no?(name, tag)\n element_is_visible(name, tag, @klass, false)\n end",
"def guard_text( text )\n # todo/fix 2: note we need to differentiate between blocks and inline\n # thus, to avoid runs - use guard_block (add a leading newline to avoid getting include in block that goes before)\n \n # todo/fix: remove wrap_markup; replace w/ guard_text\n # why: text might be css, js, not just html\n \n ### !!!!!!!!!!!!\n ## todo: add print depreciation warning\n \n wrap_markup( text )\n end",
"def block_word?(string)\n string_cap = string.upcase\n spelling_blocks = \"BO GT VI XK RE LY DQ FS ZM CP JW NA HU\"\n spelling_blocks.split.none? { |block| string_cap.count(block) >=2}\nend",
"def has_content?\n ( not self.title.nil? and not self.title.length == 0 ) or \n (not self.description.nil? and not self.description.length == 0 ) or \n (not self.teaser.nil? and not self.teaser.length == 0 )\n end",
"def allowed_child?(tag)\n if @allowed_children.include?(tag.name)\n true\n elsif @allowed_children.include?(:_inline) && tag.type == :inline\n true\n elsif @allowed_children.include?(:_block) && tag.type == :block\n true\n else\n false\n end\n end",
"def has_text?; end",
"def paragraphs?\n false\n end",
"def tag_unused?(tag)\n self.tag_used_k_times?(tag, 0)\n end",
"def isDummyNode?(node) \n return node.name == Tag_Dummy ;\n end",
"def correct_tags?\n missing_tags?\n unwanted_tags?\n duplicate_tags?\n end",
"def blank?\n !!processed_content.match(/\\A(^\\s+$)*\\z/)\n end",
"def do_not_wrap?(node)\n node.ignored? ||\n (node.moved_to && node.moved_to != self.code) ||\n !node.public? ||\n (node.is_a?(RbGCCXML::Struct) && node.incomplete?) ||\n node.is_a?(RbGCCXML::FundamentalType)\n end",
"def code_text?(paragraph)\n paragraph.text.gsub!(/#{CODE_END}/, '')\n end",
"def empty?\n @text.empty?\n end",
"def rendering_non_html?(p = nil)\n !rendering_html?(p)\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.5429501",
"0.54218876",
"0.54118973",
"0.54115003",
"0.5402306",
"0.5398122",
"0.538372",
"0.5369894",
"0.5369196",
"0.5357104",
"0.53494805",
"0.53466064",
"0.53407305",
"0.5321649",
"0.5320366",
"0.5318242",
"0.5311883",
"0.52975434",
"0.52947587",
"0.5284196",
"0.5283328",
"0.52689606",
"0.5262497",
"0.52531916",
"0.52442855",
"0.52262735",
"0.52232254",
"0.52167076",
"0.52155435",
"0.52155435",
"0.52155435",
"0.51943785",
"0.51943785",
"0.5182947",
"0.51740247",
"0.51664764",
"0.51659244",
"0.5130237",
"0.51272905",
"0.5119484",
"0.51184225",
"0.5101625",
"0.5095654",
"0.50933224",
"0.5075276",
"0.5066689",
"0.50583416",
"0.5040299",
"0.5037193",
"0.50296855",
"0.5026167",
"0.5025171",
"0.5019763",
"0.50160635",
"0.4996987",
"0.49965328",
"0.49923754",
"0.49885038",
"0.49867517",
"0.4985193",
"0.4973262",
"0.49705985",
"0.4970009",
"0.49676555",
"0.49671605",
"0.49590847",
"0.49557894",
"0.495508",
"0.49539232",
"0.49538553"
] | 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\t@log.debug \"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\t@log.debug \"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\t@log.debug \"Finding blocks with the strict regex...\"\n\t\t\trval.gsub!( StrictBlockRegexp, &tokenize )\n\n\t\t\t@log.debug \"Finding blocks with the loose regex...\"\n\t\t\trval.gsub!( LooseBlockRegexp, &tokenize )\n\n\t\t\t@log.debug \"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('<', \"<\").gsub('>', \">\")\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",
"def ignore_links\n @link_rules.reject\n end",
"def strip_html_tags!\n @raw.gsub!(/<[^>]+?>/, ' ')\n end",
"def cleaned s, whitelist=%w[ref]\r\n\ts ||= ''\r\n\twhitelist << '---' # prevent empty (?!) in regexes\r\n\t\r\n\ts.gsub(/'{2,3}/, '').gsub(/<(?!#{whitelist.join '|'})(?!\\/(?:#{whitelist.join '|'}))[^>]+>/, '')\r\nend",
"def extractTags()\n line = @lines[@currentLine]\n re = /\\[([^\\[]+)\\]/m\n while line =~ re\n @currentBlock.addTag($~[1])\n line = line.sub(re, '')\n end\n end",
"def strip_tags_delicately\n self.gsub(/<.[^<]*>/, ' ')\n end",
"def find_relative_uris markdown_tree\n uris = _find_links_in_markdown_tree markdown_tree.root\n uris.delete_if do |uri|\n # http://stackoverflow.com/questions/1805761/check-if-url-is-valid-ruby\n # delete if we detect that it's an actual absolute uri\n abs_url = (uri =~ /\\A#{URI::regexp}+\\z/) != nil\n $logger.debug(\"Deleting absolute uri: '#{uri}'\") if abs_url\n abs_url\n end\n # TODO: How do I want to deal with something that has tags?\n # For instance if the only link to another file is 'goober/goo.md#some_tag'\n # To deal with a link that potentially has a tag in it\n # We'll just try both options. The one without the tag and the one with the tag\n return uris\nend",
"def html_filter_annotate_bare_links\n @html.search('a[@href]').each do |node|\n href = node.attributes['href'].content\n text = node.inner_text\n\n next unless href == text || href[0] == '#' ||\n CGI.unescapeHTML(href) == \"mailto:#{CGI.unescapeHTML(text)}\"\n\n node.set_attribute('data-bare-link', 'true')\n end\n end",
"def stripped_text_blocks\n stripped = []\n text_blocks.each do |tb|\n if \"Boston Police Department\" == tb && %r{^\\d+/\\d+/\\d{4} } =~ stripped.last\n # skip\n stripped.pop\n elsif /, Police Commissioner/ =~ tb\n # skip\n elsif /^Selected & Sorted By:/ =~ tb\n # skip\n elsif /^Record Count:/ =~ tb\n # skip\n stripped.pop if /^\\d+$/ =~ stripped.last\n elsif /^(Date:|Reported|Occurred)$/ =~ tb\n # skip\n else\n stripped << tb\n end\n end\n stripped\n end",
"def strip_html(allow)\n str = self.strip || ''\n allow_arr = allow.join('|')\n str = str.gsub(/<\\s*/,'<')\n str = str.gsub(/<\\/\\s*/,'</')\n # First part of | prevents matches of </allowed. Second case prevents matches of <allowed\n # and keeps the / chacter from matching the ?! allowed.\n str.gsub(/<(\\/(?!(#{allow_arr}))|(?!(\\/|#{allow_arr})))[^>]*?>/mi,'')\n end",
"def clean_html(doc)\n\n # Remove font tags\n doc.xpath('//font').each do |node|\n node.children.each do |child|\n child.parent = node.parent\n end\n node.remove\n end\n\n # Remove path to links:\n doc.xpath('//a').each do |node|\n href = node.attr(\"href\")\n href =~ /([^\\/]*)$/\n node.set_attribute(\"href\", $1)\n end\n\n # Remove <br> tags within li elements\n doc.xpath('//li').each do |li|\n li.xpath('//br').each do |br|\n br.remove\n end\n end\n\n # Remove <p> tags within li elements\n doc.xpath('//li').each do |li|\n li.xpath('//p').each do |p|\n p.children.each do |child|\n child.parent = p.parent\n end\n p.remove\n end\n end\n\n return doc\n end",
"def strip_html (s)\ns.gsub(/<[^>]*(>+|\\s*\\z)/m, '');\nend",
"def block_docbook_lists( text )\n orig_text = text.dup\n delimiter = \"\"\n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ LISTS_CONTENT_RE \n tl,continuation,atts,content = $~[1..4]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</para></listitem>\\n</#{ lD( depth[i] ) }>\\n\"\n depth.pop\n end\n end\n if depth.last.length == tl.length\n lines[line_id - 1] << \"</para></listitem>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = docbook_pba( atts )\n atts = shelve( atts ) if atts\n delimiter = lD(tl)\n lines[line_id] = \"<#{ delimiter }#{ atts }>\\n<listitem><para>#{ content.gsub(\"<\",\"<\").gsub(\">\",\">\") }\"\n else\n lines[line_id] = \"<listitem><para>#{ content.gsub(\"<\",\"<\").gsub(\">\",\">\") }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</para></listitem>\\n</#{ lD( v ) }>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n text != orig_text\n end",
"def block_textile_lists( text ) \n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ LISTS_CONTENT_RE \n tl,atts,content = $~[1..3]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</li>\\n\\t</#{ lT( depth[i] ) }l>\\n\\t\"\n depth.pop\n end\n end\n if depth.last and depth.last.length == tl.length\n lines[line_id - 1] << '</li>'\n end\n end\n unless depth.last == tl\n depth << tl\n atts = pba( atts )\n atts = shelve( atts ) if atts\n lines[line_id] = \"\\t<#{ lT(tl) }l#{ atts }>\\n\\t<li>#{ content }\"\n else\n lines[line_id] = \"\\t\\t<li>#{ content }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</li>\\n\\t</#{ lT( v ) }l>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n end",
"def clean_article_body\n get_source_selectors.each do |selector|\n if @page.search(selector).present?\n @page = page.search(selector)\n break\n end\n end\n # Strip unwanted spaces and newlines.\n @page.collect {|elt| elt.content.strip.gsub(/\\n|\\r/, '').gsub(/\\ +/, ' ')}.join(' ')\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 test_link_syntax_is_not_processed_within_code_blocks\n markdown = @markdown.render(\" This is a code block\\n This is a link [[1]] inside\\n\")\n html_equal \"<pre class=\\\"prettyprint\\\"><code>This is a code block\\nThis is a link [[1]] inside\\n</code></pre>\\n\",\n markdown\n end",
"def remove_cruft(string)\n string.gsub(/<a [^>]*>([^<]*)<\\/a>/, '\\1').gsub('[?]', '')\n end",
"def clean_inline_css(url)\n premailer = Premailer.new(url, :adapter => :nokogiri, :escape_url_attributes => false)\n premailer.to_inline_css.gsub(\"Drop Content Blocks Here\", \"\")\n end",
"def remove_unwanted_nodes!\n # Search for and remove all unwanted nodes\n unwanted_nodes = {\n \"WSJ\" => ['span.article-chiclet'],\n \"BBC\" => ['p.media-message', 'p.date', 'p.disclaimer', 'div.comment-introduction', 'noscript'],\n \"Japan Today\" => ['div#article_content p.article_smalltext'],\n \"South China Morning Post\" => ['div.subtitle', 'div.subline-ticks', 'div.subscribe-wrapper'],\n \"Tokyo Reporter\" => ['p.posttags', 'div.single_postmeta', 'div.sharedaddy']\n }\n # Only remove unwanted nodes if they're present in the hash.\n if unwanted_nodes[@source].present?\n unwanted_nodes[@source].each {|node| @page.search(node).remove}\n end\n end",
"def remove_lonely_nodes\n @nodes.delete_if { |n| (@sourcelinks[n].empty? && @destlinks[n].empty?) }\n self\n end",
"def clean_up_contents()\n # very minimal\n # elements = ['p', 'b', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], attributes={})\n\n if self.contents?\n html = self.contents\n email_regex = /<p>Email:\\s+((\\w|\\-|\\_|\\.)+\\@((\\w|\\-|\\_)+\\.)+[a-zA-Z]{2,})/i\n\n html.gsub! /\\[endif\\]--/ , ''\n html.gsub! /[\\n|\\r]/ , ' '\n html.gsub! / / , ' '\n\n # this will convert UNICODE into ASCII. \n #It will also strip any possiblity of using a foreign language!\n #converter = Iconv.new('ASCII//IGNORE//TRANSLIT', 'UTF-8') \n #html = converter.iconv(html).unpack('U*').select{ |cp| cp < 127 }.pack('U*')\n # keep only the things we want.\n unless (Sanitize::Config::RELAXED[:attributes][\"table\"].include?(\"align\"))\n Sanitize::Config::RELAXED[:attributes][\"table\"] << \"align\"\n end\n\n config = Sanitize::Config::RELAXED\n if (html.encoding.name == 'ASCII-8BIT')\n config[:output_encoding] = 'ASCII'\n end\n html = Sanitize.clean( html, config)\n\n # butt up any tags\n html.gsub! />\\s+</ , '><'\n\n #remove email address lines\n html.gsub! email_regex , '<p>'\n\n # post sanitize cleanup of empty blocks\n # the order of removal is import - this is the way word stacks these elements\n html.gsub! /<i><\\/i>/ , ''\n html.gsub! /<b><\\/b>/ , ''\n html.gsub! /<\\/b><b>/ , ''\n html.gsub! /<p><\\/p>/ , ''\n html.gsub! /<p><b><\\/b><\\/p>/ , ''\n\n # misc - fix butted times\n html.gsub! /(\\d)am / , '\\1 am '\n html.gsub! /(\\d)pm / , '\\1 pm '\n # misc - remove multiple space that may cause doc specific regexs to fail (in dates for example)\n html.gsub! /\\s+/ , ' '\n\n # add new lines at the end of lines\n html.gsub! /<\\/(p|h\\d|dt|dd|dl)>/, '</\\1>' + \"\\n\"\n html.gsub! /<dl>/ , '<dl>' + \"\\n\"\n\n self.contents = html\n end\n end",
"def replace_nodes\n doc.xpath(\".//text()\").each do |node|\n next if has_ancestor?(node, ignored_ancestor_tags)\n\n content = node.to_html\n html = yield content, node\n\n next if html == content || html.nil?\n if html.length == 0\n node.parent.remove\n else\n node.replace(html)\n end\n end\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_first_link(content)\n \n #Remove curly braces\n while content =~ /\\{\\{[^\\{\\\\}]+?\\}\\}/\n\t content.gsub!(/\\{\\{[^\\{\\}]+?\\}\\}/,'')\n end\n #remove info box\n content.sub!(/^\\{\\|[^\\{\\}]+?\\n\\|\\}\\n/,'')\n #remove anything in parens\n #content.gsub!(/\\(.*\\)/,'')\n content.gsub!(/(\\(.*\\))(?=^(?:(?!\\[\\])))/,'')\n #remove bold and italicized text\n content.gsub!(/'''''(.+?)'''''/,'')\n #remove italic text\n content.gsub!(/''(.+?)''/,'')\n #remove images and file links\n content.gsub!(/\\[\\[Image:.*?\\]\\]/,'')\n content.gsub!(/\\[\\[File:.*?\\]\\]/,'')\n content.gsub!(/\\[\\[image:.*?\\]\\]/,'')\n content.gsub!(/\\[\\[file:.*?\\]\\]/,'')\n #remove any link with colons in it\n #content.gsub!(/\\[\\[.*?:.*?\\]\\]/,'')\n #gets the first link\n content = content.slice(/\\[\\[.*?\\]\\]/)\n #replaces spaces with underscores (for correct resolving of links)\n content.gsub!(\" \",'_')\n #removes the trailing description (for correct resolving of links)\n content = content.gsub(/\\|.*?\\]\\]/,']]')\n return content\n end",
"def strip_tags(html)\n strip(Sanitize.clean(html, :elements => [], :attributes => []))\n end",
"def htmlify_except(nodes)\n nodes.reduce(to_html) do |output, node|\n output.gsub(node.to_html, node.to_xhtml)\n end\n end",
"def normalise_html(html)\n Nokogiri::HTML5.fragment(html).to_s.gsub(\"\\n\", \"\")\n end",
"def strip_tags(html)\n return html if html.blank?\n if html.index(\"<\")\n text = \"\"\n tokenizer = ::HTML::Tokenizer.new(html)\n while token = tokenizer.next\n node = ::HTML::Node.parse(nil, 0, 0, token, false)\n # result is only the content of any Text nodes\n text << node.to_s if node.class == ::HTML::Text\n end\n # strip any comments, and if they have a newline at the end (ie. line with\n # only a comment) strip that too\n text.gsub(/<!--(.*?)-->[\\n]?/m, \"\")\n else\n html # already plain text\n end\n end",
"def footer_tags_for(news_article)\n if news_article.tag_list.size > 0\n \"<ul class='link_tag'>#{news_article.tag_list.map {|t| \"<li>#{link_to(t,news_tag_path(t))}</li>\"}}</ul>\"\n else\n \"<span>untagged article</span>\"\n end\n end",
"def get_tags_n_text_from_article(article_id)\n s = resolve_redirects_n_read(article_id)\n return [[], nil] if s.nil?\n\n s = \"<article>\" + s + \"</article>\"\n reader = Nokogiri::XML::Reader(s)\n text = \"\"\n reader.each do |node|\n if node.name == \"text\" &&\n node.node_type == Nokogiri::XML::Reader::TYPE_ELEMENT\n text = node.inner_xml\n end\n end\n\n # Lets get only the stuff till the first subsection \"==\"\n #summary_text = text.gsub /^==.*/m, ''\n\n # Remove headings\n text.gsub! /\\=\\=\\=\\=.*?\\=\\=\\=/, ''\n text.gsub! /\\=\\=\\=.*?\\=\\=\\=/, ''\n text.gsub! /\\=\\=.*?\\=\\=/, ''\n # Remove references\n text.gsub! /<ref>.*?<\\/ref>/, ''\n text.gsub! /<ref;.*?>/, ''\n text.gsub! /<ref.*?>/, ''\n # Remove all Category links\n text.gsub! /\\[\\[Category:.*?\\]\\]/, ''\n # Remove everything between < and >\n text.gsub! /<.*?>/, ''\n # Remove this crappy nowrap markup\n text.gsub! /{{nowrap end}}}}/, ''\n # Remove everything in {{ }} - citation/references\n text.gsub! /{{.*?}}/, ''\n # Remove everything in {{ ^}} - Infobox\n text.gsub! /{{Infobox.*?^}}/m, ''\n text.gsub! /{{Persondata.*?^}}/m, ''\n # Convert [[Alps|Alpine]] to [[Alpine]]\n text.gsub! /\\[\\[[^\\[]*?\\|(.*?)\\]\\]/, '[[\\1]]'\n # Get tags - all stuff which is in [[ ]]\n link_tags = text.scan /\\[\\[(.*?)\\]\\]/\n # get the strings out of the arrays\n link_tags.map! { |e| e[0] }\n # Remove tags which have \"|\" or \"[\" or \"]\"\n link_tags.reject! { |e| e =~ /\\||\\[|\\]/}\n # Convert all tags to lowercase\n link_tags.map! { |e| e.downcase }\n \n # Convert [[Alpine]] to Alpine\n text.gsub! /\\[\\[(.*?)\\]\\]/, '\\1'\n # Remove ''' '''\n text.gsub! /\\'\\'\\'(.*?)\\'\\'\\'/, '\\1'\n # Remove '' ''\n text.gsub! /\\'\\'(.*?)\\'\\'/, '\\1'\n # Remove \" and *\n text.gsub! /\"|\\*/, ''\n # Remove ( )\n text.gsub! /\\(|\\)/, ''\n # Remove anything with [ ] - usually links etc\n text.gsub! /\\[.*?\\]/, ''\n # Remove any remaining }}\n text.gsub! /}}/, ''\n\n # Replace newlines with spaces\n text.gsub! /\\n/, ' '\n\n return link_tags, text\n \n rescue Exception => e\n print \" !!! get_tags_n_text_from_article(): #{e}\\n\"\n return [[], nil]\n end",
"def strip_bbcode(string); end",
"def block_textile_lists( text )\n orig_text = text.dup\n \n # Take care of _*'s and _#'s to turn them into paragraphs\n text.gsub!(/([\\*#] )((.*?\\n\\s*_[\\*#].*?)+)/) do |m|\n \"#{$1}<p>\"+$2.split(/_[\\*#]/).map{|w|w.strip}.delete_if{|w|w.empty?}.join(\"</p><p>\")+\"</p>\"\n end\n \n @last_line ||= -1\n \n text.gsub!( LISTS_RE ) do |match|\n if text =~ /^#([_0-9]+).*/m\n if $1 == $1.to_i.to_s # then it is a number, so use it\n @last_line = $1.to_i - 2\n end\n else\n @last_line = -1\n end\n lines = match.split( /\\n/ )\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ LISTS_CONTENT_RE \n \n tl,continuation,atts,content = $~[1..4]\n @last_line += 1 if tl.length == 1\n \n unless depth.last.nil?\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</li>\\n#{\"\\t\"*(depth.size-1)}</#{ lT( depth[i] ) }l>\"\n depth.pop\n tab_in = true\n end\n end\n if depth.last && depth.last.length == tl.length\n lines[line_id - 1] << \"</li>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = pba( atts )\n atts << \" start=\\\"#{@last_line + 1}\\\"\" if lT(tl) == \"o\" && !continuation.empty? && @last_line > 0\n atts = shelve( atts ) if atts\n lines[line_id] = \"#{\"\\t\"*(depth.size-1)}<#{ lT(tl) }l#{ atts }>\\n#{\"\\t\"*depth.size}<li>#{ content }\"\n else\n lines[line_id] = \"#{\"\\t\"*depth.size}<li>#{ content }\"\n end\n elsif line =~ /^([_]+)(#{A}#{C}) (.*)$/m\n @last_line += 1\n tl = \"u\"\n atts,content = $~[2..3]\n \n unless depth.last.nil?\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</li>\\n#{\"\\t\"*(depth.size-1)}</#{ lT( depth[i] ) }l>\"\n depth.pop\n tab_in = true\n end\n end\n if depth.last and depth.last.length == tl.length\n lines[line_id - 1] << \"</li>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = pba( atts )\n atts = shelve( \"#{atts} style=\\\"list-style-type:none;\\\"\" )\n lines[line_id] = \"#{\"\\t\"*(depth.size-1)}<#{ lT(tl) }l#{ atts }>\\n#{\"\\t\"*depth.size}<li>#{ content }\"\n else\n lines[line_id] = \"#{\"\\t\"*depth.size}<li>#{ content }\"\n end\n end\n \n if line_id == lines.length - 1\n tabs = depth.size-1\n depth.reverse.delete_if do |v|\n lines[-1] << \"</li>\\n#{\"\\t\"*tabs}</#{ lT( v ) }l>\"\n tabs -= 1\n end\n end\n end\n lines.join( \"\\n\" )\n end\n \n text != orig_text\n end",
"def html_remove\n gsub(/<\\/?[^>]+>/, '')\n end",
"def block_html(raw)\n raw = unindent(raw)\n\n if md = raw.match(/\\<(.+?)\\>(.*)\\<(\\/.+?)\\>/m)\n open_tag, content, close_tag = md.captures\n \"<#{open_tag}>\\n#{recursive_render(unindent(content))}<#{close_tag}>\"\n else\n raw\n end\n end",
"def strip_html\n gsub(HTML_TAG_PATTERN, \"\")\n end",
"def block_docbook_simple_lists( text )\n orig_text = text.dup\n delimiter = \"\"\n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ /^([_]+)(#{A}#{C}) (.*)$/m\n tl,atts,content = $~[1..4]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</member>\\n</simplelist>\\n\"\n depth.pop\n end\n end\n if depth.last.length == tl.length\n lines[line_id - 1] << \"</member>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = docbook_pba( atts )\n atts = shelve( atts ) if atts\n lines[line_id] = \"<simplelist#{ atts }>\\n<member>#{ content.gsub(\"<\",\"<\").gsub(\">\",\">\") }\"\n else\n lines[line_id] = \"<member>#{ content.gsub(\"<\",\"<\").gsub(\">\",\">\") }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</member>\\n</simplelist>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n text != orig_text\n end",
"def parse_non_direct_links(wiki_text)\n wiki_text.gsub!(%r{\\[\\[[^\\[\\]]*?:([^\\[]|\\[\\[[^\\[]*\\]\\])*?\\]\\]}im, \"\")\n wiki_text\n end",
"def strip_extra_content(item, locale=I18n.locale)\n strip_tags(exclude_base64(raw_value(item, locale)))\n end",
"def strip_external_links(text)\n link_stripper = Loofah.fragment(text)\n\n link_stripper.scrub!(Loofah::Scrubber.new do |node|\n next unless node.name == 'a'\n\n begin\n uri = URI(node['href'].to_s.strip)\n rescue URI::InvalidURIError\n node.replace(node.inner_text)\n next\n end\n\n next if uri.relative?\n\n domain = ActionDispatch::Http::URL.extract_domain(\n uri.host.to_s, ActionDispatch::Http::URL.tld_length\n )\n\n node.replace(node.inner_text) unless domain == request.domain\n end)\n\n link_stripper.inner_html\n end",
"def anonymous_blocklists; end",
"def filter_links(links)\n filtered_links = links.map do |link|\n next unless link.include?(\"data\") #TODO: Extract into query parameter\n link\n end.compact\n\n #TODO: Extract into exclusion array parameter - Could I pull in file size and exclude equal size files?\n filtered_links -= [\"/pub/time.series/ch/ch.data.0.Current\"] #Duplicate of ch.data.1.AllData - 3.3 GB\n filtered_links -= [\"/pub/time.series/cs/cs.data.0.Current\"] #Duplicate of cs.data.1.AllData - 3.1 GB\n\n filtered_links.reject { |link| link =~ /(dataset|datatype|dataelement|dataclass|data.type|data_type|tdata|dataseries)/ }\n end",
"def strip_textile(x)\n x = x.gsub(/<.+?>/,'')\n x = x.gsub(/\\\"(.*?)\\\":http:\\/\\/([^ ]*)( )?/,'\\1 ') unless x.blank?\n x\n end",
"def strip_html(str,allow=['dm','dl'])\n str = str.strip || ''\n allow_arr = allow.join('|') << '|\\/'\n str.gsub(/<(\\/|\\s)*[^(#{allow_arr})][^>]*>/,'').strip\n end",
"def sanitize_text(text)\n doc = Nokogiri::HTML.fragment(text)\n UNSUPPORTED_HTML_TAGS.each do |tag|\n doc.search(tag).each(&:remove)\n end\n doc.inner_html\n end",
"def has_only_tags?(block)\n block.gsub(/<[^>]*>/im, '').strip.length == 0\n end",
"def clean!(html)\n @whitelist_nodes = []\n fragment = Nokogiri::HTML::DocumentFragment.parse(html)\n clean_node!(fragment)\n @whitelist_nodes = []\n\n output_method_params = {:encoding => 'utf-8', :indent => 0}\n\n if @config[:output] == :xhtml\n output_method = fragment.method(:to_xhtml)\n output_method_params[:save_with] = Nokogiri::XML::Node::SaveOptions::AS_XHTML\n elsif @config[:output] == :html\n output_method = fragment.method(:to_html)\n else\n raise Error, \"unsupported output format: #{@config[:output]}\"\n end\n\n result = output_method.call(output_method_params)\n\n # Ensure that the result is always a UTF-8 string in Ruby 1.9, no matter\n # what. Nokogiri seems to return empty strings as ASCII for some reason.\n result.force_encoding('utf-8') if RUBY_VERSION >= '1.9'\n\n return result == html ? nil : html[0, html.length] = result\n end",
"def remove_for_block(block)\n tx_hashes = []\n\n block.tx.each{|tx|\n tx_hashes << tx.hash\n # remove any now conflicted txs from the memory pool --\n # these are txs which spend outputs spent by txs in this new block. why would this happen?\n # maybe a tx in the block wasn't relayed to us but an associated double-spend was.\n self.remove_conflicts(tx)\n }\n\n # TODO: should probably transfer timestamps and other information\n Toshi::Models::UnconfirmedTransaction.remove_for_block(tx_hashes)\n Toshi::Models::UnconfirmedRawTransaction.where(hsh: tx_hashes).delete\n\n # make sure the transactions are on the tip pool (if they previously existed.)\n Toshi::Models::Transaction.where(hsh: tx_hashes)\n .update(pool: Toshi::Models::Transaction::TIP_POOL)\n end",
"def remove_tags_container(t, c)\n l, r = container_array(c)\n t.gsub!(l, '')\n t.gsub!(r, '')\n t\n end",
"def sanitize_excerpt(html, okTags)\n # no closing tag necessary for these\n soloTags = [\"br\",\"hr\"]\n\n # Build hash of allowed tags with allowed attributes\n tags = okTags.downcase().split(',').collect!{ |s| s.split(' ') }\n allowed = Hash.new\n tags.each do |s|\n key = s.shift\n allowed[key] = s\n end\n\n # Analyze all <> elements\n stack = Array.new\n result = html.gsub( /(<.*?>)/m ) do | element |\n if element =~ /\\A<\\/(\\w+)/ then\n # </tag>\n tag = $1.downcase\n if allowed.include?(tag) && stack.include?(tag) then\n # If allowed and on the stack\n # Then pop down the stack\n top = stack.pop\n out = \"</#{top}>\"\n until top == tag do\n top = stack.pop\n out << \"</#{top}>\"\n end\n out\n end\n elsif element =~ /\\A<(\\w+)\\s*\\/>/\n # <tag />\n tag = $1.downcase\n if allowed.include?(tag) then\n \"<#{tag} />\"\n end\n elsif element =~ /\\A<(\\w+)/ then\n # <tag ...>\n tag = $1.downcase\n if allowed.include?(tag) then\n if ! soloTags.include?(tag) then\n stack.push(tag)\n end\n if allowed[tag].length == 0 then\n # no allowed attributes\n \"<#{tag}>\"\n else\n # allowed attributes?\n out = \"<#{tag}\"\n while ( $' =~ /(\\w+)=(\"[^\"]+\")/ )\n attr = $1.downcase\n valu = $2\n if allowed[tag].include?(attr) then\n out << \" #{attr}=#{valu}\"\n end\n end\n out << \">\"\n end\n end\n end\n end\n\n # eat up unmatched leading >\n while result.sub!(/\\A([^<]*)>/m) { $1 } do end\n\n # eat up unmatched trailing <\n while result.sub!(/<([^>]*)\\Z/m) { $1 } do end\n\n # clean up the stack\n if stack.length > 0 then\n result << \"</#{stack.reverse.join('></')}>\"\n end\n\n result\n end",
"def remove_html_tag(tag_name); end",
"def strip_textile(x)\r\n x = x.gsub(/<.+?>/,'')\r\n x = x.gsub(/\\\"(.*?)\\\":http:\\/\\/([^ ]*)( )?/,'\\1 ') unless x.blank?\r\n x\r\n end",
"def remove_image_link_tag\n @caption_node\n .children\n .first\n .content = @caption_node.content.sub(href_regexp, '').strip\n end",
"def unfiltered_content; end",
"def unfiltered_content; end",
"def unfiltered_content; end",
"def fragment(tags); end",
"def blocklists; end",
"def test_unflatten_link\r\n link = @link_list.add_link(@perfind, @proc) \r\n \r\n data = link.flatten_data\r\n \r\n @link_list.remove_link(link)\r\n \r\n livelink = @link_list.link_from_data(data)\r\n \r\n assert_equal(link.from, livelink.from) \r\n assert_equal(link.to, livelink.to) \r\n end",
"def tags_to_remove\n linked_tags - current_tags\n end",
"def parse_unpaired_tags(wiki_text)\n wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, \"\")\n wiki_text\n end",
"def unlinked\n reject(&:linked?)\n end",
"def tags_to_remove\n return @tags_to_remove\n end",
"def asset_link_filter(asset_array)\n asset_array.select do |asset|\n asset.split(//).last != '/'\n end\n # TODO: also filter out .html endings\n end",
"def LinksToRemove\n\t\t\n\t\t#removing unwanted links\n\t\t@nodes.each do |nodeA|\n\t\t\t@nodes.each do |nodeB|\n\n\t\t\t\tif nodeA==nodeB\n\t\t\t\t\tnext\n\t\t\t\tend\n\n\t\t\t\ttempLink=Link.new(nodeA,nodeB)\n\t\t\t\trevTempLink=Link.new(nodeB,nodeA)\n\n\t\t\t\t#check if this link has been requested\n\t\t \t\treqLink=false \n\t\t \t\t@links.each do |link|\n\t\t\t \t\tif Equals(tempLink, link)\n\t\t\t \t\t\treqLink=true\n\t\t\t \t\tend\n\t\t \t\tend\n\t\t \n\t\t \t\tif not reqLink and (nodeA.type==\"R\" and nodeB.type==\"R\")\n\t\t\t\t\tputs(\"Removing link between node #{nodeA.id} and #{nodeB.id}\\n\")\n\t\t\t\t\t@killedLinks << tempLink\n\t\t \t\tend\n\n\n\t\t\tend\n\t\tend \n\n\t\treturn @killedLinks\n\n\tend",
"def replace(node_or_tags); end",
"def replace(node_or_tags); end",
"def each_non_tag(str)\n full_str = ''\n tag_delimit = /(<(?:(?!<).)*>)/ # use non-capturing group w/ negative lookahead\n str.split(tag_delimit).each do |token|\n if token.start_with? '<'\n full_str << token # don't process tags\n else\n full_str << yield(token)\n end\n end\n return full_str\n end",
"def extractLinks(page)\n\tbase_wiki_url = \"https://en.wikipedia.org\"\n\tlinks = page.search(\"//a\")\n\tlinks = links.map{|item| item[\"href\"]}\n\n\t#Appending with base_wiki_page to make it full fledged page.\n\tlinks = links.map{|link| base_wiki_url+link.to_s}\n\n\treturn stripUnwantedLinksBasedOnCondition(links)\nend",
"def blocks_for_block_size\n # We're already done with the last block behavior, if we wanted a small\n # last block, or if we only generated a single block\n return block_list if block_list.size <= 1 || last_block == :small_last\n\n case last_block\n when :truncate_all\n # Implemented in add_for_block_size\n nil\n when :small_last\n # Implemented just above\n nil\n when :truncate_last\n block_list.pop\n else # default to :big_last behavior\n last = block_list.pop\n block_list.last.words.concat(last.words)\n end\n\n block_list\n end",
"def new_blocks_attributes\n return [] if @new_blocks_attributes.empty?\n\n blocks_attributes = if @new_blocks_attributes.is_a?(Hash)\n @new_blocks_attributes.values\n else\n @new_blocks_attributes\n end\n\n if home_page? || footer?\n return blocks_attributes + include_srcset_block(blk_attrs: blocks_attributes)\n end\n\n convert_content_to_html(blocks_attributes)\n\n blocks_attributes\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.54912704",
"0.54819405",
"0.5441688",
"0.5440111",
"0.54335415",
"0.5428309",
"0.5425164",
"0.5419859",
"0.5417663",
"0.5411438",
"0.54076326",
"0.5406821",
"0.5398799",
"0.5397429",
"0.53767323",
"0.53539234",
"0.534324",
"0.5326933",
"0.5326912",
"0.5326545",
"0.53220916",
"0.532073",
"0.5315621",
"0.5309591",
"0.52864903",
"0.52829325",
"0.5271133",
"0.5249871",
"0.52422297",
"0.5230726",
"0.5228414",
"0.5225975",
"0.5225825",
"0.52083206",
"0.5202228",
"0.520187",
"0.51982445",
"0.51882833",
"0.51811737",
"0.5173756",
"0.5165253",
"0.51636136",
"0.5162285",
"0.516101",
"0.5157736",
"0.51538306",
"0.51514614",
"0.5147409",
"0.51375836",
"0.5131808",
"0.51154244",
"0.51108694",
"0.51056284",
"0.51056284",
"0.51056284",
"0.51054704",
"0.5098186",
"0.50892836",
"0.5075689",
"0.5068907",
"0.5065667",
"0.5053056",
"0.50499165",
"0.5046214",
"0.50225097",
"0.50225097",
"0.50187767",
"0.50185573",
"0.5018376",
"0.50182885"
] | 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\t@links.key? 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\t@client.linked?\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 !@blocks.empty?\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",
"def check_only_links\n end",
"def allowed_types\n [NetBlock]\nend",
"def acceptable_link_format?(link)\n begin\n return false if link.to_s.match(/#/) || link.uri.to_s.empty? # handles anchor links within the page\n scheme = link.uri.scheme\n return false if (!scheme.nil?) && (scheme != 'http') && (scheme != 'https') # eliminates non http,https, or relative links\n # prevents download of media files, should be a better way to do this than by explicit checks for each type\n return false if link.to_s.match(/.pdf|.jgp|.jgp2|.png|.gif/)\n rescue\n return false\n end\n true\n end",
"def iterating_block?(node); end",
"def list?; return stype == :list; end",
"def valid_link(link)\n\t\t!link.nil? and !link.empty?\n\tend",
"def in_list?\n !my_position.nil?\n end",
"def in_list?\n !my_position.nil?\n end",
"def blocklists; end",
"def linked\n select(&:linked?)\n end",
"def block_valid?(args = {})\n block = Block.find_by(id: args[:block_id])\n previous_block = block.previous_block\n neighbor_blocks_valid?(block, previous_block)\n end",
"def check_listing\n unless @listing.context == :listing\n warn block: @listing, message: <<~LOG.strip\n #{LAYOUT_DESCRIPTION} but the first block was a #{@listing.context}.\n LOG\n return false\n end\n\n validate_listing_langauge\n end",
"def in_list?\n !send(:position).nil?\n end",
"def block_is_haml?(block)\n eval('_hamlout', block.binding)\n true\n rescue\n false\n end",
"def in_list?\n !send(position_column).nil?\n end",
"def has_link?(link_rel)\n c = self.links.select {|l| l[link_rel] }.count\n c == 0 ? false : true\n end",
"def valid_links\n\t\tself.links.select {|l| l.parent_id != nil && l.child_id != nil}\n\tend",
"def list_type\n if self.type != :list\n raise NodeError, \"can't get list_type for non-list\"\n end\n CMark.node_get_list_type(@pointer)\n end",
"def isitLink?(message)\n uri = URI.parse(message)\n %w( http https ).include?(uri.scheme)\n rescue URI::BadURIError\n false\n rescue URI::InvalidURIError\n false\n end",
"def in_list?\n !not_in_list?\n end",
"def uplink_has_network_of_type?(uplink, type)\n uplink_networks(uplink).map do |network|\n network[\"type\"].downcase\n end.include?(type.downcase)\n end",
"def isLinkedin?\n self.category =~ /(linkedin|linked-in)/i\n end",
"def dir_link?(link)\n link.content.match?(%r{\\/$}) ||\n link[:href].match?(%r{^(?!((http|https):\\/\\/|\\.{2}|\\/|\\?)).*\\/$})\n end",
"def handled_labeled_list(line, level, margin, offset, prefix)\n prefix_length = prefix.length\n text = line.text\n flag = nil\n\n case prefix\n when /^\\[/ then\n flag = :LABELED\n prefix = prefix[1, prefix.length-2]\n when /:$/ then\n flag = :NOTE\n prefix.chop!\n else\n raise \"Invalid List Type: #{self.inspect}\"\n end\n\n # body is on the next line\n if text.length <= offset then\n original_line = line\n line = @lines.next\n return false unless line\n text = line.text\n\n for i in 0..margin\n if text[i] != SPACE\n @lines.unget\n return false\n end\n end\n\n i = margin\n i += 1 while text[i] == SPACE\n\n if i >= text.length then\n @lines.unget\n return false\n else\n offset = i\n prefix_length = 0\n\n if text[offset..-1] =~ SIMPLE_LIST_RE then\n @lines.unget\n line = original_line\n line.text = ''\n else\n @lines.delete original_line\n end\n end\n end\n\n line.stamp :LIST, level+1, prefix, flag\n text[margin, prefix_length] = \" \" * prefix_length\n assign_types_to_lines(offset, level + 1)\n return true\n end",
"def can_accept?(linkage)\n if (linkage.second_position == 0)\n return true\n end\n ! self.attachment_position_consumed?(linkage.second_position)\n end",
"def relevant_fulltext_link?(link)\n relevant_links.map { |x| link[:url].include?(x) }.any?\n end",
"def symlink?\n @symlink\n end",
"def symlink?\n false\n end",
"def directed?() false; end",
"def what_links_heres_ok?\n what_links_here_except_obsolete_combinations.empty?\n end",
"def linode?(node = __getnode)\n node.key?(\"linode\")\n end",
"def directed?\n true\n end",
"def id_link?\n @url[0] == '#'\n end",
"def is_compromised\n\t\tif (!@head) then return end\n\t\ttype = @head.get_item().class\n\t\tcurrent = @head\n\t\twhile (current)\n\t\t\tif (!(current.get_item().is_a?(type))) then return true end\n\t\t\tcurrent = current.get_next()\n\t\tend\n\t\treturn false\n\tend",
"def attlistdecl?\n @contents[0] == :attlistdecl\n end",
"def symlink?() end",
"def auto_linked?(left, right)\n (left =~ AUTO_LINK_CRE[0] and right =~ AUTO_LINK_CRE[1]) or\n (left.rindex(AUTO_LINK_CRE[2]) and $' !~ AUTO_LINK_CRE[3])\n end",
"def tag_list_attribute?(attribute)\n attribute.to_s.ends_with?('_list')\n end",
"def show_all_link?\n @show_all_link\n end",
"def is_platform_block?(key)\n raise 'No key given'.red unless key\n\n return false if (self.runner.blocks[nil][key.to_sym] rescue false)\n return true if self.runner.blocks[key.to_sym].kind_of?Hash\n\n raise \"Could not find '#{key}'. Available lanes: #{self.runner.available_lanes.join(', ')}\".red\n end",
"def is_inventory_linked?\n if RoomTypeInventoryLink.find_by_room_type_from_id(self.id).blank?\n false\n else\n true\n end\n end",
"def valid?\n blocks = Block.all.order(id: :asc).to_a\n blocks[1..-1].each.with_index(1) do |block, index|\n return false unless neighbor_blocks_valid?(block, blocks[index - 1])\n end\n true\n end",
"def symlink?\n !!@symlink ||= false\n end",
"def auto_linked?(left, right)\n (left =~ AUTO_LINK_CRE[0] and right =~ AUTO_LINK_CRE[1]) or\n (left.rindex(AUTO_LINK_CRE[2]) and $' !~ AUTO_LINK_CRE[3])\n end",
"def isCyclical?(list_node)\n\tslow = list_node\n\tfast = list_node\n\n\t# Checks if the node exists and has a next node\n\twhile fast != nil && fast.next_node != nil do\n\t\tslow = slow.next_node\n\t\tfast = fast.next_node.next_node\n\t\treturn true if slow == fast\n\tend\n\treturn false\nend",
"def is_node?(); @type == GRT_NODE; end",
"def directed?\n false\n end",
"def allowed_types\n [ Entities::NetBlock]\nend",
"def allowed_types\n [ Entities::NetBlock]\nend",
"def is_nodetype?(); @type == GRT_NODETYPE; end",
"def blocked?\n return (@ref.blocked == \"true\") ? true : false\n end",
"def directed_only?\n true\n end",
"def parse_link_definition\n return false if @src[3].to_s =~ /[ \\t]+[\"']/\n @src.pos += @src.matched_size\n link_id, link_url, link_title = normalize_link_id(@src[1]), @src[2] || @src[3], @src[5]\n if @link_defs[link_id]\n warning(\"Duplicate link ID '#{link_id}' on line #{@src.current_line_number} - overwriting\")\n end\n @tree.children << new_block_el(:eob, :link_def)\n @link_defs[link_id] = [link_url, link_title, @tree.children.last]\n true\n end",
"def show_in_child_list?\n\t\t\ttrue\n\t\tend",
"def sane_structure?\n structure.nil? || (structure.to_s =~ Structure::STRUCTURE_PATTERN && !ancestor_ids.include?(self.id))\n end",
"def list_type\n case @node.name\n when 'ol' then :ordered\n when 'ul' then :unordered\n end\n end",
"def collection?(l)\n return @lists.key?(l) || l.list?\n end",
"def definition? following_another = false\n element_names == %w[list] and title = definition_title and\n following_another || list.element_names == %w[t]\n end",
"def in_special_list?(list_type=nil)\n if list_type.nil?\n @in_special_list ? true : false\n else\n @in_special_list == list_type\n end\n end",
"def auto_linked?(left, right)\n (left =~ AUTO_LINK_CRE[0] and right =~ AUTO_LINK_CRE[1]) or\n (left.rindex(AUTO_LINK_CRE[2]) and $' !~ AUTO_LINK_CRE[3])\n end",
"def is_block_valid?(hash)\n if @block_index.block_header_in_index?(hash)\n return true\n end\n !Toshi::Models::Block.main_or_side_branch.where(hsh: hash).empty?\n end",
"def array_node?(node)\n node.attributes['type'] == 'collection'\n end",
"def is_block?(pnl)\n x = pnl[0]\n y = pnl[1]\n empty?([x, y]) && empty?([x+1, y]) && empty?([x, y+1]) && empty?([x+1, y+1])\n end",
"def multiline?(node); end",
"def guest_and_restricted_link?\n guest? && @record.fulltext_link[:url] == 'detail'\n end",
"def partial?\n\t\t\tlinks.by(:rel)['alternate'].any? do |l|\n\t\t\t\tl[3]=='application/atom+xml'||l[3]=='application/atom+xml;type=entry'\n\t\t\tend\n\t\tend",
"def block_is_type?(block)\n is_type? || (block && eval('defined?(__in_erb_template)', block.binding))\n end",
"def is_valid_list(l)\n props = @graph.properties(l)\n #puts \"is_valid_list: #{props.inspect}\" if ::RdfContext::debug?\n return false unless props.has_key?(RDF_NS.first.to_s) || l == RDF_NS.nil\n while l && l != RDF_NS.nil do\n #puts \"is_valid_list(length): #{props.length}\" if ::RdfContext::debug?\n return false unless props.has_key?(RDF_NS.first.to_s) && props.has_key?(RDF_NS.rest.to_s)\n n = props[RDF_NS.rest.to_s]\n #puts \"is_valid_list(n): #{n.inspect}\" if ::RdfContext::debug?\n return false unless n.is_a?(Array) && n.length == 1\n l = n.first\n props = @graph.properties(l)\n end\n #puts \"is_valid_list: valid\" if ::RdfContext::debug?\n true\n end",
"def loop?\n l = @head\n t = @head\n\n while l\n l = l.next.next\n t = t.next\n return true if l == t\n end\n false\n end",
"def input?; @link_type == 'IN'; 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.5592775",
"0.5558941",
"0.5543632",
"0.55423295",
"0.55390203",
"0.5520511",
"0.5515102",
"0.5515102",
"0.55101585",
"0.55014",
"0.5453721",
"0.5442784",
"0.5435725",
"0.5413413",
"0.54130095",
"0.5408052",
"0.53946054",
"0.5384542",
"0.53837025",
"0.53609425",
"0.53522766",
"0.5350618",
"0.53444046",
"0.5342156",
"0.53240657",
"0.53149277",
"0.5311821",
"0.530704",
"0.5298126",
"0.5294444",
"0.52871865",
"0.5286832",
"0.5285816",
"0.5284062",
"0.52825636",
"0.5262642",
"0.5256187",
"0.52507997",
"0.52452004",
"0.52347445",
"0.5233938",
"0.5231597",
"0.52230906",
"0.522052",
"0.519491",
"0.5188352",
"0.5172641",
"0.5172607",
"0.5172607",
"0.51721555",
"0.5168165",
"0.51662683",
"0.51620036",
"0.5158202",
"0.51478326",
"0.5144664",
"0.5143726",
"0.5142964",
"0.51393753",
"0.5138302",
"0.5135707",
"0.51339465",
"0.51123786",
"0.51088953",
"0.5105343",
"0.5103677",
"0.5102924",
"0.5098379",
"0.50920194",
"0.5076247"
] | 0.6971343 | 0 |
Estimates how much degree of link list | def evaluate_list(list)
return 1 if list.length == 0
hit = 0
list.each do |line|
hit +=1 if line =~ /<a\s+href=(['"]?)([^"'\s]+)\1/imn
end
return 9 * (1.0 * hit / list.length) ** 2 + 1
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def n_degree(node, counts=false, k=2)\n d = n_indegree(node,counts,k) + n_outdegree(node,counts,k)\n if l=@links[[node,node]]\n # to be repaired!\n case counts\n when true, :add\n d -= l.weight\n when false, nil, :nodes\n d -= 1\n else\n raise \"fixme: no self links for these degrees allowed currently\"\n end\n end\n d\n end",
"def degree(v) in_degree(v); end",
"def in_degree(node)\n @pred[node].length\n end",
"def in_degree\n @in_edges.length\n end",
"def degree; end",
"def degree\n self.in_degree + self.out_degree\n end",
"def degree node\n d = 0\n if (@connections[node].is_a? (Array)) && nodes.include?(node)\n d = @connections[node].count\n if @connections[node].include?(node)\n d += 1\n end\n end\n return d\n end",
"def in_degree(node)\n self[node].length\n end",
"def degree(node)\n in_degree(node) + out_degree(node)\n end",
"def chain_link_percent\n product = 1.0\n self.map(&:link_percent).each do |i|\n product = product*i\n end\n product\n end",
"def out_degree(node)\n @adj[node].length\n end",
"def out_degree(vertex)\n\tend",
"def n_indegree(node, counts=false, k=2)\n n_inoutdegree(node, @destlinks, counts, k)\n end",
"def degree(x, direction = :all)\n r = Hash.new(0)\n (0..@store.size).each do |i|\n r[:in] += 1 if connected?(i, x)\n r[:out] += 1 if connected?(x, i)\n end\n r[:all] = r[:in] + r[:out]\n return r[direction] / 2 if undirected?\n r[direction]\n end",
"def out_degree(source)\n h = @pathway.graph[source]\n h ? h.size : 0\n end",
"def degrees\n Enumerator.new(@structure.length) do |y|\n nodes.each do |node|\n y << [node, degree(node)]\n end\n end\n end",
"def in_degree(v)\n r = 0\n each_in_neighbor(v) { |u| r += 1 }\n r\n end",
"def calc_total_weight\n @weight + @node_link.calc_total_weight\n end",
"def out_degree(v)\n r = 0\n each_adjacent(v) { |u| r += 1 }\n r\n end",
"def out_degree\n @out_edges.length\n end",
"def get_out_degree(url, topic)\n\tout_degree_url = \"#{url}/wiki/Special:WhatLinksHere/#{topic}?limit=5000\"\n\tout_degree_string=\"\"\n\topen(out_degree_url) { |data| \n\t\tout_degree_string = data.read\n\t}\n\n\tlist_regex = /<ul id=\"mw-whatlinkshere-list\">.*?<\\/ul>View/m\n\tout_degree_string = list_regex.match(out_degree_string).to_s\n\tout_links = filter_links(out_degree_string)\n\treturn out_links.length\nend",
"def outDegree( name )\n if (@vertices.has_key? name)\n\t\treturn @vertices[name].size\n\telse\n\t\treturn 0\n\tend\n end",
"def degree()\n return self.rep.length\n end",
"def degrees(counts=false, k=2)\n h = Hash.new { |h,k| h[k] = [0,0,0] }\n @nodes.each { |n|\n h[n] = [n_outdegree(n,counts,k), n_indegree(n,counts,k), n_degree(n,counts,k)]\n }\n h\n end",
"def in_degree(vertex)\n\tend",
"def degree(vertex)\n\tend",
"def load_factor\n counter = 0\n @items.each do |item|\n if item != nil && item.kind_of?(LinkedList) == false\n counter += 1\n elsif item != nil && item.kind_of?(LinkedList) == true\n temp_node = item.head\n while temp_node != nil\n counter += 1\n temp_node = temp_node.next\n end\n else\n next\n end\n end\n return counter.to_f / size\n end",
"def outDegree( name )\n\tif vertex?( name )\n\t\treturn @vertices[ name ].size\n\tend\n\treturn 0\n end",
"def link(p1, p2)\n return [1, 0, p1.first] if p1.first == p2.first\n k = (p2.last - p1.last) * 1.0 / (p2.first - p1.first)\n [-k, 1, p1.last - k * p1.first]\nend",
"def load_factor\n total_size = 0\n @items.each do |list|\n unless list == nil\n node = list.head\n while node != nil\n total_size += 1\n node = node.next\n end\n end\n end\n total_size.to_f / @items.count\n end",
"def clustering_coefficient(node)\n node = node?(node)\n return 0 if node.nil?\n\n neighbors = node.neighbors\n return 0.0 if (neighbors.size < 2)\n nlinks = 0\n neighbors.each do |a|\n neighbors.each do |b|\n nlinks += 1 if a != b && edge?(a, b)\n end\n end\n\n return nlinks.to_f / (neighbors.size * (neighbors.size - 1))\n end",
"def clustering_coefficient(node)\n node = node?(node)\n return 0 if node.nil?\n\n neighbors = node.neighbors\n return 0.0 if (neighbors.size < 2)\n nlinks = 0\n neighbors.each do |a|\n neighbors.each do |b|\n nlinks += 1 if a != b && edge?(a, b)\n end\n end\n\n return nlinks.to_f / (neighbors.size * (neighbors.size - 1))\n end",
"def link_calculate(count)\n num_chunks = (count**0.5).ceil\n min_links_in_chunk = (count/num_chunks).floor if num_chunks > 0\n max_links = min_links_in_chunk + 1 if min_links_in_chunk.present?\n return max_links \n end",
"def estimate_authority_score(guid,authority)\n out_degrees,in_degrees = @driver.degrees\n weight = 1.0\n if @driver.out_link?(guid)\n weight += 1.0/out_degrees\n end\n weight += @driver.directs(guid).to_f/@driver.total_directs\n weight * authority\n end",
"def inDegree( name )\n\t\n\tcount = 0\n if @vertices.has_key? name\n\t @vertices.each { |key,v| count+=1 if self.edge?(key,name) }\n\t end\n\treturn count\n end",
"def load_factor\n total = 0.0\n @items.each do |item|\n if item.is_a? Node\n total = total + 1\n elsif item.is_a? LinkedList\n total = total + item.length\n end\n end\n total.to_f / @size.to_f\n end",
"def degree(v)\n in_degree(v) + out_degree(v)\n end",
"def find_degrees_edges\n raise RuntimeError, \"Call filter_graph_by_users before find_degrees\" unless File.exist? @graph_filename\n \n # Open graph file and read in undirected edges\n puts \"Reading in edges from graph & calculating in/outdegree...\"\n edges = {}\n degrees = {}\n File.open(@c.graph,\"r\").each do |l|\n parts = l.split(' ',3)\n id1,id2 = parts[0].to_i, parts[1].to_i\n degrees[id2] ||= [0,0]\n degrees[id1] ||= [0,0]\n degrees[id2][0] += 1\n degrees[id1][1] += 1\n #id1,id2 = id2,id1 if id2 < id1\n edges[id1] ||= Set.new\n edges[id1].add id2\n end\n \n # Write in-degree count to file\n puts \"Writing in/out-degree to file...\"\n File.open(@c.degrees+\"~\", \"w\") do |f|\n degrees.each do |k,v|\n f.puts \"#{k} #{v[0]} #{v[1]}\"\n end\n end\n File.rename(@c.degrees+\"~\", @c.degrees)\n \n # Count in-degrees & loop through edges and count and write to file\n puts \"Writing directed edges to file...\"\n File.open(@people_edge_filename+\"~\", \"w\") do |f|\n edges.each do |k,v|\n v.each do |k2|\n f.puts \"#{k} #{k2}\"\n # degrees[k] ||= 0\n # degrees[k2] ||= 0\n # degrees[k] += 1\n # degrees[k2] += 1\n end\n end\n end\n File.rename(@people_edge_filename+\"~\", @people_edge_filename)\n \n end",
"def n_outdegree(node, counts=false, k=2)\n n_inoutdegree(node, @sourcelinks, counts, k)\n end",
"def out_degree(node)\n @structure.count { |_source, dest| dest.include? node }\n end",
"def solve_math_attempt\n\n # 0 jolt charging outlet\n outlet = JoltageAdapter.new(0)\n @adapters.push(outlet)\n\n # final jump to device\n dev = Device.new(@adapters)\n @adapters.push(dev)\n\n @adapters.sort_by! {|adapter| adapter.joltage}\n\n\n # we only care about the joltages\n available_joltages = @adapters.map { |adapter| adapter.joltage }\n\n count = 0\n\n available_joltages.each do |joltage|\n\n # p joltage\n\n can_link_to = available_joltages.select do |node|\n diff = node - joltage\n diff <= 3 && diff > 0\n end\n\n is_linked_to = available_joltages.select do |node|\n diff = joltage - node\n diff <= 3 && diff > 0\n end\n\n # count += can_link_to.size\n # count *= is_linked_to.size\n\n impact = (can_link_to.size) * (is_linked_to.size) - 1\n\n puts \"Adapter #{joltage} impact: #{impact}\"\n\n count += impact unless impact <= 0\n\n\n\n\n # puts 2**(can_link_to.size-1) unless (can_link_to.size - 1 <= 0)\n\n # puts \"Joltage #{joltage} can link to #{can_link_to}, size #{can_link_to.size}\"\n\n # puts \"Increasing current count of #{count} by #{can_link_to.size}\"\n # count *= 2**(can_link_to.size-1) unless can_link_to.size <= 0\n\n\n end\n puts \"COUNT: #{count}\"\n # puts count.class\n # p count\n\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 inDegree( name )\n\tcount = 0\n if vertex?( name )\n\t\t@vertices.each_key{ |key| if edge?( key, name ) then count += 1 end}\n\tend\n\treturn count\n end",
"def edge_count\n @adjacency_list.flatten.count / 2\n end",
"def percent_passes; end",
"def percent_passes; end",
"def indirect_percent(target_id)\n (pathways(target_id).map(&:make_pairs).map(&:chain_link_percent).sum)*100.0\n end",
"def links_total(page)\n\t\tnonadword_count_total(page) + adword_count_total(page)\n\tend",
"def degrees_for_distance(radius, desired_distance)\r\n# # # # # # # # # #\r\n degree_inc = 0.01\r\n last_degree_inc = degree_inc\r\n if (radius == 0)\r\n return nil\r\n end\r\n ci = calc_circumference(radius)\r\n ratio = desired_distance / calc_circumference(radius)\r\n answer = 360 * ratio\r\n return answer\r\n \r\n #cp = calc_point_from_angle(0,0, 0, radius)\r\n #cp2 = calc_point_from_angle(0,0, 1.0, radius)\r\n #dist_for_single_degree = calc_distance(cp.x,cp.y, cp2.x,cp2.y)\r\n #num_degrees_fit_in_distance = desired_distance / dist_for_single_degree\r\n #return num_degrees_fit_in_distance\r\nend",
"def degree(x, direction = :all)\n r = Hash.new(0)\n vertexes.each do |i|\n r[:in] += 1 if connected?(i, x)\n r[:out] += 1 if connected?(x, i)\n end\n r[:all] = r[:in] + r[:out]\n r[direction]\n end",
"def num_similar_links\n num_elements(\".sim a\")\n end",
"def network_link_speed_in_bytes\n return @network_link_speed_in_bytes\n end",
"def ll_size()\n return @num_nodes\n end",
"def offer_degree?\n institution_of_higher_learning_indicator || non_college_degree_indicator\n end",
"def test_messages_per_degree_in\n msgs = {1 => 10.0, 2 => 13.0, 3 => 15.0}\n degs = {1 => 2.0, 2 => 1.0, 3 => 3.0 }\n msgedges = { [1,2] => 5.0, [2,3] => 6.0, [1,3] => 7.0 }\n r = ReciprocityHeuristics::MessagesPerDegreeDecision.new(@c, msgs, degs, msgedges, :in)\n assert_equal(0.0,r.result(1,2,:rec))\n assert_equal(0.4,r.result(1,3,:rec))\n assert_equal(0.8,r.result(1,3,:unr))\n assert_equal(1.0,r.result_directed(1,3,:unr))\n assert_equal(2.0,r.result_directed(1,3,:rec))\n assert_equal(8.0/15,r.result_directed(3,1,:unr))\n assert_equal(0.8,r.result_directed(3,1,:rec))\n assert_equal(5.0,r.result_directed_onesided(1,3,:unr))\n assert_equal(5.0,r.result_directed_onesided(1,3,:rec))\n assert_equal(5.0,r.result_directed_v(1,3,:unr))\n assert_equal(10.0,r.result_directed_v(1,3,:rec))\n end",
"def degrees\n\t\t@degrees ||= cardinal.keys.sort + [360.0]\n\tend",
"def lipidsPercent()\n\t\t\t\tplato = @alimentsList.head\n\t\t\t\tgrams = @gramsList.head\n\t\t\t\ttotalEnergy = 0.0\n\t\t\t\ttotalLipidsEnergy = 0.0\n\n\t\t\t\twhile plato != nil\n\t\t\t\t\ttotalEnergy += (plato.value.get_energia * grams.value) / 100\n\t\t\t\t\ttotalLipidsEnergy += (plato.value.get_energia_lipidos * grams.value) / 100\n\n\t\t\t\t\tplato = plato.next\n\t\t\t\t\tgrams = grams.next\n\t\t\t\tend\n\n\t\t\t\treturn (totalLipidsEnergy * 100) / totalEnergy\n\t\t\tend",
"def list_size()\n counter = 0\n temp_node = @head #start traversting from first elemnt\n until temp_node == nil #stop when reach end of list\n temp_node = temp_node.link #step though list with link variable\n counter += 1\n end\n counter\n end",
"def weight; end",
"def porcentaje_glucidos\n auxNodo1 = @lista_alimentos.head\n auxNodo2 = @gramos.head\n porcentaje_gluc = 0\n while(auxNodo1 != nil && auxNodo2 != nil)\n porcentaje_gluc += (auxNodo1.value.glucidos * auxNodo2.value) / 100\n auxNodo1 = auxNodo1.next\n auxNodo2 = auxNodo2.next\n end\n return porcentaje_gluc.round(1)\n end",
"def list_size(list)\n return 0 if list.head.nil?\n 1 + list_size(LinkedList.new(list.head.link))\nend",
"def getNodeWeights()\n # (two possible sources: flipped and negated, so \n # add them for each node)\n \n tabRead(@edges){|arr|\n ordered = [arr[0],arr[2]].sort\n @allEdgeWeightScores[ordered.join(\"--\")] += arr[3].to_f\n @nodeList[arr[0]] = 1\n @nodeList[arr[2]] = 1\n }\nend",
"def load_factor\n count = 0.0\n @items.each{ |ele|\n next unless ele\n count += 1\n until ele.next == nil\n ele = ele.next\n count += 1\n end\n }\n count/size\n end",
"def get_degree note\n relative_note = note - @tonic # we are only concerned with the note relative to the tonic\n octave = (relative_note.to_i / 12) - 1\n index = @intervals.index(@intervals.find{|n| n >= relative_note % 12})\n return \"#{((octave + 1) * @intervals.size) + 7}#\" unless index # if index is nil, it means note is a sharpened 7th index... we add 1 to octave to account for the -1st octave\n degree = index + 1\n approximate_degree = ((octave + 1) * 7) + degree\n accidental = ACCIDENTALS[relative_note - (((octave + 1) * 12) + @intervals[index])]\n return \"#{approximate_degree}#{accidental}\"\n end",
"def navy_rank; end",
"def deg_vertex v\n\n\t\tdeg=0\n\n\t\t# Store vertex v as temp variable\n\t\ttmp = v\n\n\t\t# For all Edges, check their points to see if v.label is in them. If it is, increment\n\t\tfor i in 0..@Edges.length-1\n\t\t\tif @Edges[i].points[0] == v.label\n\t\t\t\tdeg+=1\n\t\t\tend\n\t\t\tif @Edges[i].points[1] == v.label\n\t\t\t\tdeg+=1\n\t\t\tend\n\t\tend\n\n\t\t# Return number of degrees\n\t\treturn deg\n\tend",
"def estimate_hub_score(guid,hub)\n out_degrees,in_degrees = @driver.degrees\n weight = 1.0\n if @driver.in_link?(guid)\n weight += 1.0/in_degrees\n end\n weight += @driver.directs(guid).to_f/@driver.total_directs\n weight * hub\n end",
"def number_of_edges\n @adj.values.map(&:length).inject(:+)\n end",
"def prob_of_connection num_nodes, num_edges\n num_edges / combination(num_nodes, 2).to_f\n end",
"def degrees_of_separation(start_node, destination_node)\n start_node_id = start_node[\"self\"].split('/').last.to_i\n destination_node_id = destination_node[\"self\"].split('/').last.to_i\n @neo.execute_query(\"START me=node({start_node_id}),\n them=node({destination_node_id})\n MATCH path = allShortestPaths( me-[?*]->them )\n RETURN length(path), extract(person in nodes(path) : person.name)\",\n {:start_node_id => start_node_id,\n :destination_node_id => destination_node_id })[\"data\"]\nend",
"def clustering_coefficient\n n = vertices.size\n # vertices.inject(0) { |cc, vertex|\n # cc + (vertex.clustering_coefficient / n)\n # }\n sum_of_local_clustering_coefficient = vertices.inject(0) { |cc, vertex|\n cc + (vertex.clustering_coefficient)\n }\n sum_of_local_clustering_coefficient / n\n end",
"def view_probability(indirect_votes)\n max = 0\n indirect_votes.each do |iv|\n if iv.direct_vote? and not iv.removed_vote?\n return 0\n else\n max = [iv.view_probability, max].max\n end\n end\n max\n end",
"def count_sparsity\n (1 - count_edge.to_f/(count_user*count_item))*100\n end",
"def memer_degree\n\t\tstats = self.stats\n\t\tif stats[:general_stats].values.inject(0,:+) == 0\n\t\t\treturn \"Boring memer\"\n\t\tend\n\t\tnouns = {\n\t\t\t\"replier\" => stats[:general_stats][:comments_count], \n\t\t\t\"memer\" => stats[:general_stats][:memes_count], \n\t\t\t\"reposter\" => stats[:general_stats][:posts_count], \n\t\t\t\"reacter\" => stats[:general_stats][:reactions_count]\n\t\t}\n\t\tadjectives = {swipe_up: \"Wholesome\", swipe_down: \"Normie\", swipe_left: \"Dank\", swipe_right: \"Boring\"}\n\n\t\tuser_noun = nouns.max_by{|k,v| v }[0]\n\t\tuser_adjective = (stats[:general_stats][:reaction_counts])? adjectives[stats[:reactions_stats].max_by{|k,v| v }[0]] : \"Boring\"\n\t\tuser_adjective + \" \" + user_noun\n\tend",
"def get_dominant_allele_probability(k, m, n)\r\n poblation = k + m + n\r\n probs = {}\r\n probs[\"mn\"] = ( (m.to_f/poblation)*(n.to_f/(poblation - 1)) + (n.to_f/poblation)*(m.to_f/(poblation -1)) ) * 0.5\r\n probs[\"kn\"] = ( (k.to_f/poblation)*(n.to_f/(poblation - 1)) + (n.to_f/poblation)*(k.to_f/(poblation - 1)) ) * 1\r\n probs[\"km\"] = ( (k.to_f/poblation)*(m.to_f/(poblation - 1)) + (m.to_f/poblation)*(k.to_f/(poblation - 1)) ) * 1\r\n probs[\"kk\"] = ( (k.to_f/poblation)*((k.to_f - 1)/(poblation - 1))) * 1\r\n probs[\"mm\"] = ( (m.to_f/poblation)*((m.to_f - 1)/(poblation - 1))) * 0.75\r\n return (probs.values.sum()).round(5)\r\nend",
"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 gradians\n self * Math::PI / 200.0\n end",
"def calculate_oneway\n return false if !graph.acyclic?\n segments = graph.labels.values\n all_count = segments.select {|s| s}.size\n oneway_count = segments.select {|s| s and s.way.oneway?}.size\n return oneway_count.to_f / all_count.to_f >= 0.9\n end",
"def depth_of_index(link)\n self.avoid_zero_division(1, self.avoid_zero_division(self.depth_of_page_in_url(link), @dpus.values.max))\n end",
"def adjBalance\n\t\t0\n\tend",
"def calculate_page_rank(iterations=20)\n # zero everyone's page rank out\n Url.update_all(\"page_rank = 1.0\")\n\n iterations.times do |i|\n puts \"Iteration #{i}\"\n Url.find(:all).each do |url|\n pr = 0.15\n \n # loop through all the pages that link to this one\n Link.find(:all,\n :select => \"DISTINCT from_id\",\n :conditions => { :to_id => url.id }) do |link|\n from_id = link.from_id\n # get the page rank of the linker\n linking_pr = Url.find_by_id(from_id).page_rank\n \n # get the total number of links from the linker\n linking_count = Link.count(:conditions => { :from_id => from_id })\n\n pr += 0.85 * (linking_pr / linking_count)\n end\n\n Url.update_all([\"page_rank = ?\", pr], [\"id = ?\", url.id])\n end\n end\n end",
"def percentage_of_passives\n calculator.percentage_of_passives\n end",
"def porcentajeGlucidos\r\n total_glucidos = 0.0\r\n la = @listaAlimentos.head\r\n lg = @listaGramos.head\r\n while la != nil do\r\n total_glucidos += (la.value.carbohidratos * lg.value) / 100\r\n la = la.next\r\n lg = lg.next\r\n end\r\n total_gramos = listaGramos.reduce(:+)\r\n porcentajeGlucidos = ((total_glucidos / total_gramos)*100).round(2)\r\n end",
"def lip\n grtotal = 0\n sum = 0\n\t\t#itera en las dos listas a la vez para poder calcular las \n #lipidos dependiendo de la cantidad y tambien suma\n #todas las cantidades para poder calcular el porcentaje\n #despues\n @lista.zip(@listagr).each do |normal, gr|\n grtotal += gr\n cant = gr/1000.0\n sum += normal.lip*cant\n end\n (sum*100)/grtotal\n end",
"def eficiencia_energetica\n auxNodo1 = @lista_alimentos.head\n auxNodo2 = @gramos.head\n eficiencia_total = 0\n while(auxNodo1 != nil && auxNodo2 != nil)\n eficiencia_total += ((auxNodo1.value.terreno * auxNodo1.value.gei) / auxNodo1.value.terreno + auxNodo1.value.gei ) * auxNodo2.value\n auxNodo1 = auxNodo1.next\n auxNodo2 = auxNodo2.next\n end\n return eficiencia_total.round(1)\n end",
"def get_grade(user)\n chain_grade = 1\n for link in get_chain_as_links()\n chain_grade *= link.get_grade(user)\n end\n\n chain_grade\n end",
"def covered_strength; end",
"def test_in_degree\n setup_test_tree\n\n assert_equal(0, @root.in_degree, \"Root's in-degree should be zero\")\n assert_equal(1, @child1.in_degree, \"Child 1's in-degree should be 1\")\n assert_equal(1, @child2.in_degree, \"Child 2's in-degree should be 1\")\n assert_equal(1, @child3.in_degree, \"Child 3's in-degree should be 1\")\n assert_equal(1, @child4.in_degree, \"Child 4's in-degree should be 1\")\n end",
"def geidiario\n auxNodo1 = @lista_alimentos.head\n auxNodo2 = @gramos.head\n geitotal = 0\n while(auxNodo1 != nil && auxNodo2 != nil)\n geitotal += (auxNodo1.value.gei * auxNodo2.value) / 100\n auxNodo1 = auxNodo1.next\n auxNodo2 = auxNodo2.next\n end\n return geitotal.round(1)\n end",
"def depth_of_page_in_url(link)\n @dpus[link]\n end",
"def points\n\t\tpoints = 0\n\t\tassignments.each do |assignment|\n\t\t\tpoints += assignment.worth\n\t\tend\n\t\treturn points\n\tend",
"def weight\n 0\n end",
"def analyze\n max_chain = 0\n min_chain = @count\n num_chains = 0\n @table.each do |node|\n chain_length = 0\n num_chains += 1 if node\n while node\n node = node.next\n chain_length += 1\n end\n max_chain = chain_length if max_chain < chain_length\n min_chain = chain_length if chain_length < min_chain\n end\n return \"Load factor: #{1.0*@count/@table.size}\\n\" +\n \"Table density: #{1.0*num_chains/@table.size}\\n\" +\n \"Mimumum chain: #{min_chain}\\n\" +\n \"Maximum chain: #{max_chain}\"\n end",
"def load_factor\n node_count = 0.0\n \n @items.each do |item|\n if item != nil\n current_node = item.head\n while current_node != nil\n node_count += 1\n current_node = current_node.next\n end\n end\n end\n @max_load_factor = (node_count / @items.size)\n if @max_load_factor > 0.70\n self.resize\n self.load_factor\n else\n @max_load_factor\n end\n end",
"def calc_access\n perf_acc = performances.collect{|p| p.access_determination }\n # FIXME: for some inexplicable reason this hangs indefinitely\n # track_acc = tracks.collect{|t| t.access_determination }\n tracks = performances.collect{|p| p.tracks}.flatten\n track_acc = tracks.collect{|t| t.access_determination}.flatten\n work_acc = tracks.collect{|t| t.works }.flatten.uniq.collect{|w| w.access_determination }\n all = (perf_acc + track_acc + work_acc).uniq\n if all.include? AccessDeterminationHelper::RESTRICTED_ACCESS\n AccessDeterminationHelper::RESTRICTED_ACCESS\n elsif all.include? AccessDeterminationHelper::IU_ACCESS\n AccessDeterminationHelper::IU_ACCESS\n elsif all.include? AccessDeterminationHelper::DEFAULT_ACCESS\n AccessDeterminationHelper::DEFAULT_ACCESS\n elsif all.include? AccessDeterminationHelper::WORLD_WIDE_ACCESS\n AccessDeterminationHelper::WORLD_WIDE_ACCESS\n else\n AccessDeterminationHelper::DEFAULT_ACCESS\n end\n end",
"def porcentaje_lipidos\n auxNodo1 = @lista_alimentos.head\n auxNodo2 = @gramos.head\n porcentaje_lip = 0\n while(auxNodo1 != nil && auxNodo2 != nil)\n porcentaje_lip += (auxNodo1.value.lipidos * auxNodo2.value) / 100\n auxNodo1 = auxNodo1.next\n auxNodo2 = auxNodo2.next\n end\n return porcentaje_lip.round(1)\n end",
"def eulerian_path(graph)\n # We can just use the eulerian cycle problem by just choosing the \n # first node which has greater outdegree than indegree\n\n node = graph.keys[0]\n in_degrees = {}\n graph.values.flatten.each do |val|\n in_degrees[val] = 0 unless in_degrees.has_key?(val)\n in_degrees[val] += 1\n end\n # puts in_degrees.to_s\n graph.each do |k,v|\n if in_degrees.has_key?(k) and v.length > in_degrees[k]\n node = k\n break\n end\n unless in_degrees.has_key?(k)\n node = k\n break\n end\n end\n stack = [node]\n cycle = []\n while (not stack.empty?)\n node = stack[-1]\n if graph.has_key?(node)\n new_node = graph[node][0]\n # puts \"New node:\" + new_node\n stack << new_node\n if graph[node].length > 1\n graph[node].delete(new_node)\n else\n graph.delete(node)\n end\n else\n cycle.unshift(stack.pop)\n # puts stack.join(\" \")\n end\n end\n\n return cycle \n end",
"def size\n head\n rounds = 1\n while !@current_node.next.nil? do\n self.next_node\n rounds += 1\n end\n rounds\n end",
"def conv_radian_to_degree(aNum)\r\n# - - - - - - - - - - - - - - - - - - - -\r\n return (aNum * Radian_to_degree_mult)\r\nend",
"def shortest_degrees_of_separation(entity)\n @@neo = Neography::Rest.new\n self_node = self.get_node\n entity_node = entity.get_node\n if self_node && entity_node\n paths = []\n self_node.shortest_path_to(entity_node).incoming(:friends).depth(5).nodes.each do |path|\n # path << node.object_type.safe_constantize.find(node[\"object_id\"])\n in_between = path.map{|n| begin n.object_type.safe_constantize.find(n[:object_id]).id rescue Exception end }\n path = {length: path.size-1, users: in_between}\n paths << path\n # puts \"#{(path.size - 1)} degrees: \" + path.map{|n| begin n.object_type.safe_constantize.find(n[:object_id]).name rescue Exception end }.join(\" => friends =>\") \n end\n paths\n end\n end",
"def weight\n 2 # ounces\n end"
] | [
"0.69526744",
"0.64286536",
"0.63070405",
"0.6292629",
"0.6245483",
"0.6236725",
"0.621429",
"0.6208246",
"0.6104611",
"0.60904217",
"0.6069165",
"0.6044643",
"0.60417974",
"0.6020638",
"0.5985121",
"0.59732026",
"0.5939222",
"0.5925733",
"0.5900319",
"0.5884814",
"0.5870445",
"0.58313096",
"0.5828983",
"0.5771452",
"0.5769791",
"0.57663244",
"0.5728691",
"0.5724823",
"0.5724681",
"0.57181436",
"0.57065856",
"0.57065856",
"0.56830823",
"0.5655603",
"0.5614731",
"0.56130534",
"0.55817693",
"0.55500305",
"0.5532639",
"0.5529353",
"0.5516093",
"0.5471474",
"0.5468844",
"0.5467649",
"0.54543895",
"0.54543895",
"0.5439188",
"0.53651094",
"0.5360742",
"0.53541946",
"0.5334593",
"0.5299085",
"0.5287398",
"0.52815604",
"0.5272247",
"0.523674",
"0.5228209",
"0.5227493",
"0.521348",
"0.5180373",
"0.5176673",
"0.51741135",
"0.5158094",
"0.51527756",
"0.5150056",
"0.5130613",
"0.51185954",
"0.51076496",
"0.50872695",
"0.5083403",
"0.50802046",
"0.5077824",
"0.5073934",
"0.5071219",
"0.5064666",
"0.50515336",
"0.5041239",
"0.50371826",
"0.50334775",
"0.5031138",
"0.5026726",
"0.5012973",
"0.50067633",
"0.50056964",
"0.5005512",
"0.4999832",
"0.49950218",
"0.49943405",
"0.4991919",
"0.49889427",
"0.49833828",
"0.49729082",
"0.49726757",
"0.49671513",
"0.4952364",
"0.49502337",
"0.4932593",
"0.49236423",
"0.49225104",
"0.49219143",
"0.49194205"
] | 0.0 | -1 |
Removes all html tags and attributes from html | def strip_tags(html)
strip(Sanitize.clean(html, :elements => [], :attributes => []))
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def strip_html\n gsub(HTML_TAG_PATTERN, \"\")\n end",
"def strip_tags(html); end",
"def strip_tags(html); end",
"def strip_tags(html); end",
"def html_remove\n gsub(/<\\/?[^>]+>/, '')\n end",
"def remove_html_tag(tag_name); end",
"def strip_tags(html)\n return html if html.blank?\n if html.index(\"<\")\n text = \"\"\n tokenizer = ::HTML::Tokenizer.new(html)\n while token = tokenizer.next\n node = ::HTML::Node.parse(nil, 0, 0, token, false)\n # result is only the content of any Text nodes\n text << node.to_s if node.class == ::HTML::Text\n end\n # strip any comments, and if they have a newline at the end (ie. line with\n # only a comment) strip that too\n text.gsub(/<!--(.*?)-->[\\n]?/m, \"\")\n else\n html # already plain text\n end\n end",
"def strip_tags(html)\n html.gsub(/<\\/?[^>]*>/, \"\") if html\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 strip_html( html )\n html.gsub(/<\\/?[^>]*>/, '')\n end",
"def strip_html_tags!\n @raw.gsub!(/<[^>]+?>/, ' ')\n end",
"def strip_html(str)\n str.gsub HTML_TAG, \"\" if str\n end",
"def strip_html_tags(text)\n return text.gsub!(/(<[^>]*>)|\\n|\\t/s) {\" \"}\n end",
"def strip_html(text)\n unless text.nil?\n strip_tags(text)\n end\n end",
"def normalise(html)\n doc = Nokogiri::HTML(html)\n body = doc.xpath('//body')\n\n body.xpath('//script').each {|s| s.remove}\n body.xpath('//comment()').each {|c| c.remove}\n body.xpath('//text()').find_all {|t| t.to_s.strip == ''}.map(&:remove)\n body.xpath('//header').remove\n body.xpath('//footer').remove\n body.xpath('//div[@id = \"global-cookie-message\"]').remove\n body.xpath('//div[@id = \"global-header-bar\"]').remove\n body.xpath('//div[@class = \"phase-banner-alpha\"]').remove\n body.xpath('//@class').remove\n body.xpath('//@id').remove\n body.xpath('//a').xpath('//@href').remove\n body.xpath('//label').xpath('//@for').remove\n body.xpath('//input').xpath('//@name').remove\n body.xpath('//input').xpath('//@value').remove\n\n remove_attributes(body, 'data')\n remove_attributes(body, 'aria')\n\n body.to_s\n .gsub(/>\\s+/, '>')\n .gsub(/\\s+</, '<')\n .gsub('><', \">\\n<\")\n end",
"def strip_html (s)\ns.gsub(/<[^>]*(>+|\\s*\\z)/m, '');\nend",
"def clean_html\n cleaned = ConverterMachine.clean_html(self) # => {html: clean html, css: Nokogiri extracted <style>...</style>}\n self.update_attributes!(file_content_html: cleaned[:html], file_content_css: cleaned[:css])\n end",
"def clean_html(doc)\n\n # Remove font tags\n doc.xpath('//font').each do |node|\n node.children.each do |child|\n child.parent = node.parent\n end\n node.remove\n end\n\n # Remove path to links:\n doc.xpath('//a').each do |node|\n href = node.attr(\"href\")\n href =~ /([^\\/]*)$/\n node.set_attribute(\"href\", $1)\n end\n\n # Remove <br> tags within li elements\n doc.xpath('//li').each do |li|\n li.xpath('//br').each do |br|\n br.remove\n end\n end\n\n # Remove <p> tags within li elements\n doc.xpath('//li').each do |li|\n li.xpath('//p').each do |p|\n p.children.each do |child|\n child.parent = p.parent\n end\n p.remove\n end\n end\n\n return doc\n end",
"def strip_tags(html)\n Sanitize.clean(html.strip).strip\n end",
"def strip_tags(html)\n Sanitize.clean(html.strip).strip\n end",
"def strip_tags_delicately\n self.gsub(/<.[^<]*>/, ' ')\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('<', \"<\").gsub('>', \">\")\n end\n end",
"def xhtml_sanitize(html)\n return html unless sanitizeable?(html)\n tokenizer = HTML::Tokenizer.new(html.to_utf8)\n results = []\n\n while token = tokenizer.next\n node = XHTML::Node.parse(nil, 0, 0, token, false)\n results << case node.tag?\n when true\n if ALLOWED_ELEMENTS.include?(node.name)\n process_attributes_for node\n node.to_s\n else\n node.to_s.gsub(/</, \"<\").gsub(/>/, \">\")\n end\n else\n node.to_s.unescapeHTML.escapeHTML\n end\n end\n\n results.join\n end",
"def strip_links(html); end",
"def strip_links(html); end",
"def strip_links(html); end",
"def sanitize_text(text)\n doc = Nokogiri::HTML.fragment(text)\n UNSUPPORTED_HTML_TAGS.each do |tag|\n doc.search(tag).each(&:remove)\n end\n doc.inner_html\n end",
"def strip_html(allow)\n str = self.strip || ''\n allow_arr = allow.join('|')\n str = str.gsub(/<\\s*/,'<')\n str = str.gsub(/<\\/\\s*/,'</')\n # First part of | prevents matches of </allowed. Second case prevents matches of <allowed\n # and keeps the / chacter from matching the ?! allowed.\n str.gsub(/<(\\/(?!(#{allow_arr}))|(?!(\\/|#{allow_arr})))[^>]*?>/mi,'')\n end",
"def strip_html(string=\"\")\n begin\n string = strip_tags(string)\n string = string.gsub(/<\\/?[^>]*>/, \"\")\n string = string.gsub(/\\&+\\w*\\;/, \" \") # replace with a space\n string.html_safe\n rescue\n raw(\"<!-- error stripping html from: #{string} -->\")\n end\n end",
"def normalise_html(html)\n Nokogiri::HTML5.fragment(html).to_s.gsub(\"\\n\", \"\")\n end",
"def strip_html(string)\n # FIXME will need something more sophisticated than this, because it sucks\n string.gsub(/<[^>]*(>+|\\s*\\z)/m, '').strip\n end",
"def sanitize_html( html, okTags='' )\n\n return if html.blank?\n\n # no closing tag necessary for these\n soloTags = [\"br\",\"hr\"]\n\n # Build hash of allowed tags with allowed attributes\n tags = okTags.downcase().split(',').collect!{ |s| s.split(' ') }\n allowed = Hash.new\n tags.each do |s|\n key = s.shift\n allowed[key] = s\n end\n\n # Analyze all <> elements\n stack = Array.new\n result = html.gsub( /(<.*?>)/m ) do | element |\n if element =~ /\\A<\\/(\\w+)/ then\n # </tag>\n tag = $1.downcase\n if allowed.include?(tag) && stack.include?(tag) then\n # If allowed and on the stack\n # Then pop down the stack\n top = stack.pop\n out = \"</#{top}>\"\n until top == tag do\n top = stack.pop\n out << \"</#{top}>\"\n end\n out\n end\n\n elsif element =~ /\\A<(\\w+)\\s*\\/>/\n # <tag />\n tag = $1.downcase\n if allowed.include?(tag) then\n \"<#{tag} />\"\n end\n\n elsif element =~ /\\A<(\\w+)/ then\n # <tag ...>\n tag = $1.downcase\n if allowed.include?(tag) then\n if ! soloTags.include?(tag) then\n stack.push(tag)\n end\n if allowed[tag].length == 0 then\n # no allowed attributes\n \"<#{tag}>\"\n else\n # allowed attributes?\n out = \"<#{tag}\"\n while ( $' =~ /(\\w+)=(\"[^\"]+\")/ )\n attr = $1.downcase\n valu = $2\n if allowed[tag].include?(attr) then\n out << \" #{attr}=#{valu}\"\n end\n end\n out << \">\"\n end\n end\n end\n end\n\n # eat up unmatched leading >\n while result.sub!(/\\A([^<]*)>/m) { $1 } do end\n\n # eat up unmatched trailing <\n while result.sub!(/<([^>]*)\\Z/m) { $1 } do end\n\n # clean up the stack\n if stack.length > 0 then\n result << \"</#{stack.reverse.join('></')}>\"\n end\n\n result\n end",
"def sanitize(html)\n doc = Nokogiri::HTML::DocumentFragment.parse(html)\n if Mako.config.sanitize_images\n doc.css('img').each do |n|\n begin\n n.name = 'a'\n n.content = n['alt'] ? \"📷 #{n['alt']}\" : '📷 Image'\n n['href'] = URI.parse(n['src']).absolutize!(uri)\n rescue URI::InvalidURIError\n # if there's a problem, just ignore it\n next\n end\n end\n end\n doc.css('h1,h2,h3,h4,h5,h6').each { |n| n.name = 'p'; n.set_attribute('class', 'bold') }\n doc.to_s\n end",
"def htmlClean(html)\n html\nend",
"def reverse_html_tags\n self.gsub('<', \"<\").gsub('>', \">\")\n end",
"def sanitize_html\n self.data = self.class.clean_html(self.data) unless self.data.nil?\n end",
"def clean_html\n HTML::WhiteListSanitizer.allowed_protocols << 'data'\n self.content = ActionController::Base.helpers.sanitize(self.body, :tags => ALLOWED_TAGS, :attributes => ALLOWED_ATTRIBUTES)\n end",
"def strip_html(string=\"\")\n begin\n string = string.gsub(/<\\/?[^>]*>/, \"\")\n string = string.gsub(/\\&+\\w*\\;/, \" \") # replace with a space\n string.html_safe\n rescue\n raw(\"<!-- error stripping html from: #{string} -->\")\n end\n end",
"def strip_html(string=\"\")\n begin\n string = string.gsub(/<\\/?[^>]*>/, \"\")\n string = string.gsub(/\\&+\\w*\\;/, \" \") # replace with a space\n string.html_safe\n rescue\n raw(\"<!-- error stripping html from: #{string} -->\")\n end\n end",
"def clean(html)\n dupe = html.dup\n clean!(dupe) || dupe\n end",
"def text\n html.gsub(REGEX_TAGS, \"\")\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 strip_attributes(doc)\n attrs = %w[data-tralics-id data-label data-number data-chapter\n role aria-readonly target]\n doc.tap do\n attrs.each do |attr|\n doc.xpath(\"//@#{attr}\").remove\n end\n end\n end",
"def strip_html(text)\n Nokogiri::HTML.fragment(text).content\n end",
"def rm_single_tags(str)\n str.gsub(/<[^<>]*\\/>/, \"\")\n end",
"def pre_sanitize(html)\n html = Nokogiri::HTML.fragment(html)\n HTML_TRANSFORMS.each do |orig, new|\n html.xpath(\".//#{orig}\").each { |node| node.name = new }\n end\n html.to_html\n end",
"def clean(html)\n return unless html\n\n # Make a whitelist of acceptable elements and attributes.\n sanitize_options = {\n elements: %w{div span p a ul ol li h1 h2 h3 h4\n pre em sup table tbody thead tr td img code strong\n blockquote small br section aside},\n remove_contents: %w{script},\n attributes: {\n 'div' => %w{id class data-tralics-id data-number data-chapter},\n 'a' => %w{id class href target rel},\n 'span' => %w{id class style},\n 'ol' => %w{id class},\n 'ul' => %w{id class},\n 'li' => %w{id class},\n 'sup' => %w{id class},\n 'h1' => %w{id class},\n 'h2' => %w{id class},\n 'h3' => %w{id class},\n 'h4' => %w{id class},\n 'img' => %w{id class src alt},\n 'em' => %w{id class},\n 'code' => %w{id class},\n 'section' => %w{id class},\n 'aside' => %w{id class},\n 'blockquote' => %w{id class},\n 'br' => %w{id class},\n 'strong' => %w{id class},\n 'table' => %w{id class},\n 'tbody' => %w{id class},\n 'tr' => %w{id class},\n 'td' => %w{id class colspan}\n },\n css: {\n properties: %w{color height width}\n },\n protocols: {\n 'a' => {'href' => [:relative, 'http', 'https', 'mailto']},\n 'img' => {'src' => [:relative, 'http', 'https']}\n },\n output: :xhtml\n }\n\n Sanitize.clean(html.force_encoding(\"UTF-8\"), sanitize_options)\n end",
"def strip_html(param_string)\n param_string.gsub!('<', '<')\n param_string.gsub!('>', '>')\n param_string.gsub(/\\\"/,\""\")\n return param_string\n end",
"def parse_html(html)\n cleaned = html.gsub(/\\n/, '').gsub(/>\\s*</m, '><').gsub /\\x00/, ''\n doc = Nokogiri::HTML(cleaned, nil, nil, Nokogiri::XML::ParseOptions.new.default_html.noblanks)\n # remove all 'script' and 'style' nodes from the document\n doc.css('style').each {|n| n.remove }\n doc.css('script').each {|n| n.remove }\n doc\n end",
"def strip_doctype_html(input)\n input.to_s.gsub(Regexp.new(DOCTYPE_HTML), NOTHING)\n end",
"def sanitize(html)\n HTML5::HTMLParser.\n parse_fragment(html, :tokenizer => HTML5::HTMLSanitizer, :encoding => 'utf-8').\n to_s\n end",
"def sanitize(html)\n HTML5::HTMLParser.\n parse_fragment(html, :tokenizer => HTML5::HTMLSanitizer, :encoding => 'utf-8').\n to_s\n end",
"def strip_html(str,allow=['dm','dl'])\n str = str.strip || ''\n allow_arr = allow.join('|') << '|\\/'\n str.gsub(/<(\\/|\\s)*[^(#{allow_arr})][^>]*>/,'').strip\n end",
"def strip_html(text)\n @name =\n # Remove HTML from the text\n Sanitize.clean(text).\n # Replace newlines with a space\n gsub(/\\n|\\r/, ' ').\n # Replaces runs of spaces by a single space\n squeeze(' ').\n # Remove leading and trailing whitespace\n strip\nend",
"def strip_tags string\n string.gsub(/<\\/?[^>]*>/, \"\")\nend",
"def clean_html(options={:url => nil})\n use_http_get = true\n call_api('clean-html', options, use_http_get)\n end",
"def strip_style_tag (s)\ns.gsub(/<style.*<\\/style>/i, '');\nend",
"def sanitize_as_html!\n Engine.clean!(self)\n end",
"def sanitize_as_html!\n Engine.clean!(self)\n end",
"def htmlify_except(nodes)\n nodes.reduce(to_html) do |output, node|\n output.gsub(node.to_html, node.to_xhtml)\n end\n end",
"def rewrite_html (html_file)\n\t\tdoc = Nokogiri::HTML(open(html_file))\n\t\tUNNECESARY_HTML_NODES.each do |node_path|\n \tnode = doc.xpath(node_path)\n \tnode.remove\n \t\tend\n \t\tFile.open(html_file,'w') { |file| doc.write_html_to file }\n\tend",
"def sanitize(html, options = {})\n msclean(html, options)\n end",
"def clean!(html)\n @whitelist_nodes = []\n fragment = Nokogiri::HTML::DocumentFragment.parse(html)\n clean_node!(fragment)\n @whitelist_nodes = []\n\n output_method_params = {:encoding => 'utf-8', :indent => 0}\n\n if @config[:output] == :xhtml\n output_method = fragment.method(:to_xhtml)\n output_method_params[:save_with] = Nokogiri::XML::Node::SaveOptions::AS_XHTML\n elsif @config[:output] == :html\n output_method = fragment.method(:to_html)\n else\n raise Error, \"unsupported output format: #{@config[:output]}\"\n end\n\n result = output_method.call(output_method_params)\n\n # Ensure that the result is always a UTF-8 string in Ruby 1.9, no matter\n # what. Nokogiri seems to return empty strings as ASCII for some reason.\n result.force_encoding('utf-8') if RUBY_VERSION >= '1.9'\n\n return result == html ? nil : html[0, html.length] = result\n end",
"def clean_up_contents()\n # very minimal\n # elements = ['p', 'b', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], attributes={})\n\n if self.contents?\n html = self.contents\n email_regex = /<p>Email:\\s+((\\w|\\-|\\_|\\.)+\\@((\\w|\\-|\\_)+\\.)+[a-zA-Z]{2,})/i\n\n html.gsub! /\\[endif\\]--/ , ''\n html.gsub! /[\\n|\\r]/ , ' '\n html.gsub! / / , ' '\n\n # this will convert UNICODE into ASCII. \n #It will also strip any possiblity of using a foreign language!\n #converter = Iconv.new('ASCII//IGNORE//TRANSLIT', 'UTF-8') \n #html = converter.iconv(html).unpack('U*').select{ |cp| cp < 127 }.pack('U*')\n # keep only the things we want.\n unless (Sanitize::Config::RELAXED[:attributes][\"table\"].include?(\"align\"))\n Sanitize::Config::RELAXED[:attributes][\"table\"] << \"align\"\n end\n\n config = Sanitize::Config::RELAXED\n if (html.encoding.name == 'ASCII-8BIT')\n config[:output_encoding] = 'ASCII'\n end\n html = Sanitize.clean( html, config)\n\n # butt up any tags\n html.gsub! />\\s+</ , '><'\n\n #remove email address lines\n html.gsub! email_regex , '<p>'\n\n # post sanitize cleanup of empty blocks\n # the order of removal is import - this is the way word stacks these elements\n html.gsub! /<i><\\/i>/ , ''\n html.gsub! /<b><\\/b>/ , ''\n html.gsub! /<\\/b><b>/ , ''\n html.gsub! /<p><\\/p>/ , ''\n html.gsub! /<p><b><\\/b><\\/p>/ , ''\n\n # misc - fix butted times\n html.gsub! /(\\d)am / , '\\1 am '\n html.gsub! /(\\d)pm / , '\\1 pm '\n # misc - remove multiple space that may cause doc specific regexs to fail (in dates for example)\n html.gsub! /\\s+/ , ' '\n\n # add new lines at the end of lines\n html.gsub! /<\\/(p|h\\d|dt|dd|dl)>/, '</\\1>' + \"\\n\"\n html.gsub! /<dl>/ , '<dl>' + \"\\n\"\n\n self.contents = html\n end\n end",
"def html_mask_stuff!(html)\n self.mask_special_emails!(html)\n self.remove_privacy_sensitive_things!(html)\n end",
"def remove_comments(raw_html)\n raw_html.gsub(/<!--(.*?)-->/, \"\")\n end",
"def clean_up_text\n text.gsub!(/<br/, \"\\n<br\")\n text.gsub!(/<p/, \"\\n<p\")\n text.gsub!(/<\\/?span(.*?)?>/, '')\n text.gsub!(/<\\/?div(.*?)?>/, '')\n end",
"def clean_html(html)\n Sanitize.clean(html) rescue html\n end",
"def app_sanitize(html)\n sanitize(html, attributes: %w[style])\n end",
"def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end",
"def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end",
"def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end",
"def destroy_tag(*tags)\n tags.each do |tag|\n gsub! Regexp.new(\"<\\s*#{tag}[^>]*>.*?<\\s*\\/#{tag}\\s*>\", Regexp::IGNORECASE + Regexp:: MULTILINE), ''\n end\n end",
"def strip_tags(line)\n line.gsub(/<\\/?[^>]*>/, \"\")\n 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 sanitize!(html, options = {})\n msclean!(html, options)\n end",
"def edit_text_remove_html(request, opts = {})\n data, _status_code, _headers = edit_text_remove_html_with_http_info(request, opts)\n data\n end",
"def remove_html\n FileUtils.rm(Dir.glob(path('epub/OEBPS/*.html')))\n FileUtils.rm(Dir.glob(path('epub/OEBPS/*.xhtml')))\n end",
"def wp_strip_all_tags(string, remove_breaks = false)\n string = string.gsub(/<(script|style)[^>]*?>.*?<\\/\\\\1>/, '')\n string = strip_tags(string)\n\n if remove_breaks\n string = string.gsub(/[\\r\\n\\t ]+/, ' ')\n end\n string.strip\n end",
"def to_html\n __html__.dup.scrub!(:escape).to_html\n end",
"def normalise_html(html)\n Nokogiri::HTML5.fragment(html).to_s\n end",
"def sanitize_excerpt(html, okTags)\n # no closing tag necessary for these\n soloTags = [\"br\",\"hr\"]\n\n # Build hash of allowed tags with allowed attributes\n tags = okTags.downcase().split(',').collect!{ |s| s.split(' ') }\n allowed = Hash.new\n tags.each do |s|\n key = s.shift\n allowed[key] = s\n end\n\n # Analyze all <> elements\n stack = Array.new\n result = html.gsub( /(<.*?>)/m ) do | element |\n if element =~ /\\A<\\/(\\w+)/ then\n # </tag>\n tag = $1.downcase\n if allowed.include?(tag) && stack.include?(tag) then\n # If allowed and on the stack\n # Then pop down the stack\n top = stack.pop\n out = \"</#{top}>\"\n until top == tag do\n top = stack.pop\n out << \"</#{top}>\"\n end\n out\n end\n elsif element =~ /\\A<(\\w+)\\s*\\/>/\n # <tag />\n tag = $1.downcase\n if allowed.include?(tag) then\n \"<#{tag} />\"\n end\n elsif element =~ /\\A<(\\w+)/ then\n # <tag ...>\n tag = $1.downcase\n if allowed.include?(tag) then\n if ! soloTags.include?(tag) then\n stack.push(tag)\n end\n if allowed[tag].length == 0 then\n # no allowed attributes\n \"<#{tag}>\"\n else\n # allowed attributes?\n out = \"<#{tag}\"\n while ( $' =~ /(\\w+)=(\"[^\"]+\")/ )\n attr = $1.downcase\n valu = $2\n if allowed[tag].include?(attr) then\n out << \" #{attr}=#{valu}\"\n end\n end\n out << \">\"\n end\n end\n end\n end\n\n # eat up unmatched leading >\n while result.sub!(/\\A([^<]*)>/m) { $1 } do end\n\n # eat up unmatched trailing <\n while result.sub!(/<([^>]*)\\Z/m) { $1 } do end\n\n # clean up the stack\n if stack.length > 0 then\n result << \"</#{stack.reverse.join('></')}>\"\n end\n\n result\n end",
"def clean_html(str)\n\t str = str.gsub(/<script(.*)>(.*)<\\/script>/i, \"\")\n\t str = str.gsub(/<frame(.*)>(.*)<\\/frame>/i, \"\")\n\t str = str.gsub(/<iframe(.*)>(.*)<\\/iframe>/i, \"\")\n\t\n\t return str\n end",
"def strip_tags(str)\n str.gsub(/\\</, \"<\").gsub(/\\>/, \">\").gsub(/\\&/, \"&\")\n end",
"def initialize_html_tags; end",
"def normalize_html_attributes(attrs = {}) \n return if attrs.blank?\n attrs.delete(:newline) # remove newline from attributes\n # look for data attrs\n if value = attrs.delete(:data)\n # NB!! convert key to symbol for [].sort\n value.each { |k, v| attrs[:\"data-#{k.to_s}\"] = v } \n end\n attrs.each do |name, val|\n if boolean_attribute?(name)\n val == true ? attrs[name] = name : attrs.delete(name)\n end\n end\n return attrs.empty? ? '' : ' ' + attrs.to_html_attributes\n end",
"def strip_links\n gsub(%r{</?a.*?>}, \"\")\n end",
"def safe_xhtml_sanitize(html, options = {})\n sanitized = xhtml_sanitize(html.purify)\n doc = Nokogiri::XML::Document.parse(\"<div xmlns='http://www.w3.org/1999/xhtml'>#{sanitized}</div>\", nil, (options[:encoding] || 'UTF-8'), 0)\n sanitized = doc.root.children.to_xml(:indent => (options[:indent] || 2), :save_with => 2 )\n rescue Nokogiri::XML::SyntaxError\n sanitized = sanitized.escapeHTML\n end",
"def permitted_html_tags; end",
"def cleanup(node)\n node = node.root if ::Nokogiri::XML::Document === node\n # remove unwanted tags\n node.xpath(\"//*[@jam='erase']\").each do |n|\n unwrap(n)\n end\n # remove jam attributes\n\n #\n node\n end",
"def sanitize!\n\t\t\t@doc.downcase!\n\t\t\t@doc.gsub!(/<style.*?\\/style>/m, '')\n\t\t\t@doc.gsub!(/<script.*?\\/script>/m, '')\n\t\t\t@doc.gsub!(/<.*?>/m, ' ')\n\t\t\t@doc.gsub!(/\\s+/, ' ')\n\t\tend",
"def strip_html_from_description\n self.description = ActionView::Base.full_sanitizer.sanitize(description)\n end",
"def clean()\n #strip all illegal content here. (scripts, shit that will break layout, etc.)\n end",
"def strip_tags_custom\n ActionController::Base.helpers.strip_tags(self)\n end",
"def sanitize(text)\n return nil if text.nil? || text.empty?\n string = text.to_s # ensure we have a string\n\n doc = Nokogiri::HTML.parse(text)\n\n doc.xpath('//@style').remove\n doc.xpath('//@class').remove\n doc.xpath('//@id').remove\n doc.xpath('//@font-size').remove\n doc.xpath('//@color').remove\n doc.xpath('//@size').remove\n doc.xpath('//@face').remove\n doc.xpath('//@bgcolor').remove\n doc.xpath('//comment()').remove\n\n # remove \"bad\" elements\n doc.css('script, link, img, style').each { |node| node.remove }\n\n # convert all <div>s to <p>s\n doc.css('div').each do |div|\n node = doc.create_element 'p'\n node.inner_html = div.inner_html\n div.replace(node)\n end\n\n # remove <font> and <span> tags, but preserve their content\n doc.css('font, span').each do |node|\n node.swap(node.children)\n end\n\n # removing tags leaves dangling text nodes that should really be merged, so let's\n # re-build the document\n doc = Nokogiri::HTML.parse(doc.to_s)\n\n # wrap orphaned text nodes in <p> tags\n doc.css('html body').children.each do |orphan|\n if orphan.class == Nokogiri::XML::Text && !orphan.text.strip.gsub(Envelope::Message::ALL_SPACES, '').empty?\n node = doc.create_element 'p'\n node.inner_html = orphan.text\n orphan.replace(node)\n end\n end\n\n # remove all <p><br><p>\n doc.css('p br').each do |node|\n node.remove\n end\n\n # convert all new lines to br and trim content\n doc.css('p').each do |node|\n node.inner_html = node.inner_html.gsub(\"\\n\", '<br>').strip\n end\n\n # remove empty tags\n doc.css('html body > *').each do |node|\n unless %w(br p).include?(node.name)\n node.remove if node.inner_html.gsub(Envelope::Message::ALL_SPACES, '').empty?\n end\n end\n\n doc.css('html body > *').to_s.gsub(/[\\n\\t]+?/, '')\n end",
"def html_escape(options={})\n except = options[:except] || %w()\n close_tags\n @modified_string.gsub!(/<\\/?(.*?)(\\s.*?)?\\/?>/) do |tag|\n if except.include?($1)\n # sanitize attributes\n tag.gsub(/\\s(.+?)=('|\").*?\\2(?=.*?>)/) do |a|\n [\"href\", \"src\", \"lang\"].include?($1) ? a : \"\"\n end\n else\n h(tag)\n end\n end\n # Convert all unclosed left tag brackets (<) into <\n @modified_string.gsub!(/<+([^>]*)\\Z/, '<\\1')\n # Convert all unopened right tag brackets (>) into >\n @modified_string.gsub!(/\\A([^<]*)>+/, '\\1>')\n self\n end",
"def text_only(html)\n Nokogiri::HTML.parse(html).text.gsub(/\\A\\p{Space}+|\\p{Space}+\\z/, '')\n .strip\n end",
"def correct_unclosed_html_tags(element)\n [:i, :sup].each do |tag|\n strip_stray_close_tags(element,tag)\n append_missing_close_tags(element,tag)\n end\n end",
"def permitted_html_tags=(_arg0); end",
"def remove_paragraph_tags mytext\n mytext.sub!(/^<p>\\s*<\\/p>/,\"\")\n mytext.sub!(/(<br>)*<p>\\s*<\\/p>$/,\"\")\n mytext.sub!(/^<p>/,'')\n mytext.sub!(/<\\/p>?/,'')\n return mytext\n end"
] | [
"0.8129619",
"0.80492145",
"0.80492145",
"0.80492145",
"0.78930527",
"0.76796126",
"0.76238716",
"0.7623648",
"0.7594436",
"0.7538369",
"0.75369114",
"0.7335301",
"0.7327459",
"0.72364163",
"0.7226362",
"0.7218428",
"0.71832067",
"0.71705854",
"0.7168116",
"0.7168116",
"0.70703626",
"0.69665474",
"0.6937557",
"0.6848229",
"0.6848229",
"0.6848229",
"0.6845221",
"0.68446606",
"0.6811118",
"0.6777678",
"0.6775972",
"0.67745847",
"0.6772003",
"0.6749902",
"0.67362255",
"0.66565275",
"0.66556185",
"0.66360515",
"0.66360515",
"0.66321003",
"0.66027105",
"0.65965325",
"0.65769035",
"0.6526791",
"0.6520878",
"0.6519788",
"0.6481583",
"0.6480108",
"0.6462666",
"0.6460248",
"0.6453595",
"0.6453595",
"0.6450441",
"0.6435694",
"0.64010364",
"0.6390053",
"0.63598174",
"0.63480085",
"0.63480085",
"0.63390297",
"0.6333894",
"0.6324099",
"0.6305961",
"0.6294844",
"0.62887",
"0.62817025",
"0.6274157",
"0.62716514",
"0.62644506",
"0.62227005",
"0.62227005",
"0.62227005",
"0.62019706",
"0.61895275",
"0.61807126",
"0.61774",
"0.6129053",
"0.6120573",
"0.6117147",
"0.6101903",
"0.6101608",
"0.6100895",
"0.6098561",
"0.6073511",
"0.6066774",
"0.6059495",
"0.60353845",
"0.6029548",
"0.60226685",
"0.60121894",
"0.5995503",
"0.59744066",
"0.59685457",
"0.5967411",
"0.5952074",
"0.59516203",
"0.59418803",
"0.5939733",
"0.5935347",
"0.5921411"
] | 0.8016258 | 4 |
optional methods below, wheeeeee | def preferred_vendor
# returns the vendor with the highest revenue
vendors.max_by {|vendor| FarMar::Vendor.find(vendor.id).revenue}
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def private; end",
"def probers; end",
"def optional; end",
"def extra; end",
"def custom; end",
"def custom; end",
"def specie; end",
"def specie; end",
"def specie; end",
"def specie; end",
"def missing; end",
"def missing?; end",
"def who_we_are\r\n end",
"def ignores; end",
"def schubert; end",
"def weber; end",
"def suivre; end",
"def missed?; end",
"def implementation; end",
"def implementation; end",
"def extra_args; end",
"def internal; end",
"def internal?; end",
"def operations; end",
"def operations; end",
"def extra=(_arg0); end",
"def used?; end",
"def placebo?; false end",
"def informational?; end",
"def specialty; end",
"def overrides; end",
"def overload; end",
"def probers=(_arg0); end",
"def ibu; end",
"def maybe; end",
"def methods; end",
"def methods; end",
"def methods; end",
"def methods; end",
"def anchored; end",
"def silly_adjective; end",
"def required; end",
"def required; end",
"def required; end",
"def extended(*) end",
"def formation; end",
"def ignore; end",
"def whiny=(_arg0); end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def internship_passed; end",
"def wrapper; end",
"def refutal()\n end",
"def pass; end",
"def pass; end",
"def explicit?; end",
"def isolated; end",
"def isolated; end",
"def fallbacks=(_arg0); end",
"def missing?; false; end",
"def required_defaults; end",
"def operation; end",
"def isolated?; end",
"def isolated?; end",
"def returns; end",
"def usable?; end",
"def methods() end",
"def hints; end",
"def caveats; nil end",
"def caveats; nil end",
"def terpene; end",
"def strategy; end",
"def semact?; false; end",
"def optional_positionals; end",
"def fallbacks; end",
"def fallbacks; end",
"def none?; end",
"def none?; end",
"def none?; end",
"def flag; end",
"def berlioz; end",
"def safe_by_default; end",
"def extra_state; end",
"def awaken!\n\t\traise 'Not implemented'\n\tend",
"def checks; end",
"def incomplete\r\n\r\n end",
"def extra; @extra; end",
"def respond(); end",
"def usage; end",
"def usage; end",
"def r; end"
] | [
"0.7547798",
"0.7169128",
"0.7168276",
"0.7073493",
"0.68971825",
"0.68971825",
"0.6857012",
"0.6857012",
"0.6857012",
"0.6857012",
"0.68427056",
"0.68347",
"0.67881846",
"0.66595197",
"0.6634924",
"0.65769935",
"0.6560613",
"0.6551691",
"0.64930123",
"0.64930123",
"0.64723665",
"0.6453558",
"0.6449973",
"0.6417365",
"0.6417365",
"0.6404396",
"0.6392556",
"0.63804734",
"0.63368803",
"0.6330104",
"0.6310914",
"0.6306901",
"0.6298258",
"0.62974733",
"0.6288272",
"0.6270668",
"0.6270668",
"0.6270668",
"0.6270668",
"0.6256017",
"0.62508625",
"0.6243928",
"0.6243928",
"0.6243928",
"0.62414426",
"0.6222332",
"0.62202376",
"0.6220056",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62105155",
"0.62070835",
"0.61942434",
"0.6172202",
"0.6168562",
"0.6168562",
"0.6167512",
"0.6162523",
"0.6162523",
"0.6161681",
"0.61558175",
"0.6149832",
"0.61485577",
"0.61398107",
"0.61398107",
"0.6134413",
"0.6130662",
"0.6124383",
"0.6118208",
"0.6114942",
"0.6114942",
"0.6114359",
"0.61084867",
"0.60978854",
"0.6093228",
"0.6086898",
"0.6086898",
"0.60832775",
"0.60832775",
"0.60832775",
"0.608295",
"0.6078743",
"0.60732186",
"0.60574484",
"0.6050807",
"0.60463184",
"0.6044923",
"0.604034",
"0.60401416",
"0.6038561",
"0.6038561",
"0.60385203"
] | 0.0 | -1 |
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! /­/, ''\n str\n end",
"def sanitize(text)\n text.squeeze\n text.capitalize!\n text.gsub!('&', '&')\n text.gsub!('<', '<')\n text.gsub!('>', '>')\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('&', '&')\n text.gsub('\\'', ''')\n text.gsub('\"', '"')\n text.gsub('<', '<')\n text.gsub('>', '>')\n text\n end",
"def html_escape(clean_me)\n clean_me.to_s.gsub(/[&\"<>]/) do |special|\n { '&' => '&',\n '>' => '>',\n '<' => '<',\n '\"' => '"' }[special]\n end\n end",
"def sanitize_refpt1 refpt1\n refpt1.strip.gsub(\".\", \"\")\n end",
"def esc(str)\n str = str.to_s.gsub(\"&\", \"&\")\n str = str.gsub(\"\\\"\", \"'\")\n str = str.gsub(\"\\\"\", \""\")\n str = str.gsub(\"<\", \"<\")\n str.gsub(\">\", \">\")\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('&', '&')\n .gsub('\"', '"')\n .gsub('<', '<')\n .gsub('>', '>')\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",
"def uri_escape(input); end",
"def convert_string(item)\n CGI.escapeHTML(item).\n \n \n # convert -- to em-dash, (-- to en-dash)\n gsub(/---?/, '—'). #gsub(/--/, '–').\n\n # convert ... to elipsis (and make sure .... becomes .<elipsis>)\n gsub(/\\.\\.\\.\\./, '.…').gsub(/\\.\\.\\./, '…').\n\n # convert single closing quote\n gsub(%r{([^ \\t\\r\\n\\[\\{\\(])\\'}) { \"#$1’\" }.\n gsub(%r{\\'(?=\\W|s\\b)}) { \"’\" }.\n\n # convert single opening quote\n gsub(/'/, '‘').\n\n # convert double closing quote\n gsub(%r{([^ \\t\\r\\n\\[\\{\\(])\\'(?=\\W)}) { \"#$1”\" }.\n\n # convert double opening quote\n gsub(/'/, '“').\n\n # convert copyright\n gsub(/\\(c\\)/, '©').\n\n # convert and registered trademark\n gsub(/\\(r\\)/, '®')\n\n end",
"def safe_filename( filename )\n ret = filename\n\n # remove commas\n ret = ret.gsub( /,/, '' )\n\n # remove colons\n ret = ret.gsub( /:/, '' )\n\n # change spaces to underscores\n ret = ret.gsub( / /, '_' )\n\n return ret\n end",
"def esc(inString)\n #2015-04-04 BN: gsub stumbles on apostrophes so I created a unique treatment for them\n # from http://stackoverflow.com/questions/8929218/how-to-replace-an-apostrophe-using-gsub\n inString = inString.gsub(/[']/, \"\\\\\\\\\\'\")\n\n #For each of the characters in the list of characters to be escaped\n $eChars.each do |thisChar|\n #Replace every instance of thisChar with thisChar appended to an\n #escape character. We have to escape the escape to use it\n inString = inString.gsub(thisChar, \"\\\\\"+thisChar)\n end\n return inString\nend",
"def sanitize_filename\n name = self.strip\n #--- get only the filename, not the whole path\n name.gsub! /^.*(\\\\|\\/)/, ''\n\n #--- Finally, replace all non alphanumeric, underscore or periods with underscore\n name.gsub! /[^\\w\\.\\-]/, '_'\n return name\n end",
"def strip_html_quote_entities(text)\n text.gsub(/&.dquo;/, '')\n end",
"def sanitize_tag(in_tag)\n in_tag.gsub(/[^\\w%=\\-\\\\+]+/,\"\")\n end",
"def likeEscape( str )\n str.gsub( \"\\\\\", \"\\\\\\\\\" ).gsub( \"%\", \"\\%\" ).gsub( \"_\", \"\\_\" )\n end",
"def unescape(input)\n CGI.unescapeHTML(input) rescue input\n end",
"def unescaped_path\n path_info.split(/(%25|%2F)/i).each_slice(2).map { |v, m| CGI.unescape(v) << (m || '') }.join('')\n end",
"def slugorize\n result = self.downcase\n result.gsub!(/&(\\d)+;/, '') # Ditch Entities\n result.gsub!('&', 'and') # Replace & with 'and'\n result.gsub!(/['\"]/, '') # replace quotes by nothing\n result.gsub!(/\\W/, ' ') # strip all non word chars\n result.gsub!(/\\ +/, '-') # replace all white space sections with a dash\n result.gsub!(/(-)$/, '') # trim dashes\n result.gsub!(/^(-)/, '') # trim dashes\n result\n end",
"def clean_client_field(data)\n data = data.to_s\n data.gsub!(/[\\^`|~\\\"']/, '')\n data.gsub!(/[{<]/, '(')\n data.gsub!(/[}>]/, ')')\n data.gsub!(/&/, 'and')\n data[0...100]\n end",
"def safe_escape(uri); end",
"def fix_double_escape(escaped)\n escaped.gsub(/&([a-z]+|(#\\d+));/i) { \"&#{$1};\" }\n end",
"def sanitize_path\n gsub(/[\\/: ]/,'_')\n end",
"def cgi_escape(string)\n CGI.escape(string).gsub(\"+\", \" \")\n end",
"def clean(text = nil, escape_ampersands_twice = false)\n text.gsub!(\" \", \" \")\n converted = convert_html(text)\n entity_converted = convert_entities(converted)\n # puts \"entity_converted: #{entity_converted}\"\n escaped = escape(entity_converted)\n # escaped = escaped.gsub(/&/, '\\\\\\\\&')\n escaped = escaped.gsub(\"&\", \"\\&\")\n escaped = escaped.gsub(/&/, '\\\\\\\\&') if escape_ampersands_twice\n # puts \"escaped: #{escaped}\"\n # puts \"\\n\"\n escaped\n end",
"def slugorize\n\t result = self.downcase\n\t result.gsub!(/&(\\d)+;/, '') # Ditch Entities\n\t result.gsub!('&', 'and') # Replace & with 'and'\n\t result.gsub!(/['\"]/, '') # replace quotes by nothing\n\t result.gsub!(/\\W/, ' ') # strip all non word chars\n\t result.gsub!(/\\ +/, '-') # replace all white space sections with a dash\n\t result.gsub!(/(-)$/, '') # trim dashes\n\t result.gsub!(/^(-)/, '') # trim dashes\n\t result\n\tend",
"def bad_sanitize(str)\n str.gsub(/'/,\"''\")\nend",
"def strip_bad_chars(text)\n text.gsub!(/\"/, \"'\");\n text.gsub!(/\\u2018/, \"'\");\n text.gsub!(/[”“]/, '\"');\n text.gsub!(/’/, \"'\");\n return text\nend",
"def unescape_html\n CGI.unescapeHTML(self)\n end",
"def to_url\n val = self.strip_tags!\n val = val.gsub(/[ —_\\/]/, '-')#TODO: длинный пробел не работает\n val = val.gsub(/[+.,!?@#$%^&*()\\[\\]{}:;\\/\\\\|<>\"']/, '') #TODO: больше символов!\n val.downcase\n end",
"def escape(str)\n CGI.escape(str)\n end",
"def escape_special_chars(data)\n data = data.dup\n data.gsub! /&/n , \"&\"\n data.gsub! /\\\"/n , \""\"\n data.gsub! />/n , \">\"\n data.gsub! /</n , \"<\"\n data.gsub! /'/ , \"'\"\n return data\n end",
"def cleanup_new(string)\n string.tr(' -/:-@[-`{-~',' ')\nend",
"def stripsub(text)\n return (text.strip).gsub(\"'\",\"''\").gsub(\"’\", \"''\")\n end",
"def sanitize_html(content)\n require 'cgi'\n CGI.escapeHTML(content)\n end",
"def sanitize(name)\n name = name.scrub\n name = name.tr(\"\\\\\", \"/\") # work-around for IE\n name = File.basename(name)\n name = name.gsub(sanitize_regexp, \"_\")\n name = \"_#{name}\" if name =~ /\\A\\.+\\z/\n name = \"unnamed\" if name.size.zero?\n name.mb_chars.to_s\n end",
"def html_escape(s)\n CGI.escapeHTML(s.to_s)\n end",
"def clean(string)\n string.gsub(/[',.!?:;]['s]/, \"\")\n\nend",
"def sanitize(url)\n\t\t\tURI.encode url.strip.gsub('[', '%5B').gsub(']', '%5D')\n\t\tend",
"def sanitize(str)\n str.gsub(%r{[\\\\/*?\"<>|\\s,#]:}, '').downcase\n end",
"def safe_encode(string)\n CGI::escape(string).gsub(/\\+/, '%20')\n end",
"def strip_and_convert(str)\n CGI.unescapeHTML(strip_tags(str))\n end",
"def sanitize_filename(filename)\n filename.gsub(/.*[\\/\\\\]/, '')\n end",
"def sanitize_filename(filename)\n filename.gsub(/.*[\\/\\\\]/, '')\n end",
"def sanitize_filename(filename)\n filename.gsub(/.*[\\/\\\\]/, '')\n end",
"def sanitize_filename(filename)\n filename.gsub(/.*[\\/\\\\]/, '')\n end",
"def sanitize(filename)\r\n # Bad as defined by wikipedia: https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words\r\n # Also have to escape the backslash\r\n bad_chars = [ '/', '\\\\', '?', '%', '*', ':', '|', '\"', '<', '>', '.', ' ' ]\r\n bad_chars.each do |bad_char|\r\n filename.gsub!(bad_char, '_')\r\n end\r\n filename.gsub!(/[éèë]/i, 'e')\r\n filename.gsub!(/[âà]/i, 'a')\r\n filename.gsub!(/[ïìî]/i, 'i')\r\n filename.gsub!(/[ùû]/i, 'u')\r\n filename\r\nend",
"def sanitize_email(email)\n email.gsub(/@/, \"_at_\").gsub(/\\./, \"_dot_\")\n end",
"def escape(s)\n URI.encode_www_form_component(s)\n end",
"def htmlEscape(string)\n return string.gsub('&', '&').gsub('>', '>').gsub('<', '<')\nend",
"def uri_escape\n CGI.escape(self)\n end",
"def handle_special_characters(text)\n\n if text.include?(\"'\") then\n text.gsub!(\"'\",\"_\")\n end\n if text.include?(\"\\\\\") then\n text.gsub!(\"\\\\\",\"_\")\n end\n\n text\n end",
"def full_escape str\n str = str.gsub(\"+\",\"%2B\")\n str = ERB::Util.url_encode(str)\n\n if str[0] && str[0] == \".\"\n str = \"%2E\" + str[1..-1]\n end\n\n str\n end",
"def sanitized_string(string)\n text = Sanitize.fragment(string.to_s).squish\n CGI.unescapeHTML(text).gsub(/ /, ' ')\n end",
"def path_safe(txt)\n txt.gsub(\" \", \"_\").gsub(/\\,|\\[|\\]/,\"\")\n end",
"def unescape(string)\n result = CGI.unescapeHTML(string)\n result.gsub!(/!-(.*?)-!/, '\\1')\n return result\n end",
"def sanitize_filename(filename)\n filename.strip.gsub(/[^0-9A-Za-z.\\-]|\\s/, '_')\n end",
"def sanitize(options={})\n coder = HTMLEntities.new()\n \n #lowercase it\n encoded = self.downcase()\n \n #convert special chars to html entities\n encoded = coder.encode(encoded, :named)\n \n #replace spaces by _ (underscore)\n encoded = encoded.gsub(/\\s+/i, '_')\n \n while ((found = encoded.match(/&([^&;]+);/i)))\n #char without accent, is the first in the html entity definition\n char = found[1][0]\n \n char_ord = coder.decode(found[0]).ord()\n if ( (char_ord >= 192 && char_ord <= 214) ||\n (char_ord >= 216 && char_ord <= 223) ||\n (char_ord >= 224 && char_ord <= 246) ||\n (char_ord >= 248 && char_ord <= 255)\n )\n #valid character\n else\n char = \"_\"\n end\n \n #replace encoded\n encoded = encoded.gsub(/#{ Regexp.escape(found[0]) }/, char)\n end\n \n return encoded\n end",
"def scrub\n self.gsub(/[^a-zA-Z\\s0-9\\.]/, '').gsub(/\\t/, ' ').gsub(/\\r/, ' ').gsub(/\\s\\s/, '').lstrip.rstrip\n end",
"def e(value)\n CGI.escape(value)\n end",
"def remove_weird_characters(content)\n content.force_encoding('utf-8').gsub //, ''\n end",
"def sanitize(file_name, replacement=\"_\")\n # See http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words\n return file_name.gsub(/[\\/|\\0|\\\\\\?%\\*:\"<>]/, replacement)\n end",
"def sanitize_path(path)\n newpath = path.gsub(/\\/+/, '/')\n while newpath.gsub!(%r{([^/]+)/\\.\\./?}) { |match|\n $1 == '..' ? match : ''\n } do end\n newpath.gsub(%r{/\\./}, '/').sub(%r{/\\.\\z}, '/')\n end",
"def escape_field( field )\n return html_escape( field ).gsub( \"\\\\\", \"\\" )\n end",
"def sanitize_extension_val(value)\n output = \"\"\n\n value = value.to_s.gsub(/\\r\\n/, \"\\n\")\n\n value.each_char{|c|\n case c\n when \"\\\\\", \"=\"\n output += \"\\\\\" + c\n when \"\\n\", \"\\r\"\n output += \"\\\\n\"\n else\n output += c\n end\n }\n\n return output\n end",
"def sanitize_extension_key(value)\n value.to_s\n .gsub(/[^a-zA-Z0-9]/, \"\")\n end",
"def safe_output(input)\n sanitize Nokogiri::HTML.fragment(CGI.unescapeHTML(input)).to_s\n end",
"def unescaped_xml_without_soft_hyphens\n str = ::CGI.unescapeHTML local_copy.encoded_io.read\n local_copy.encoded_io.rewind\n # get rid of MS Office baddies\n str.gsub! SOFT_HYPHEN, ''\n str\n end",
"def safe *things\n\t\t\tappend! CGI.escapeHTML(things.map(&:to_s).join(\"\\n\"))\n\t\tend",
"def esc(word)\n word.gsub(\"&\", \"&\").gsub(\"<\", \"<\")\n end",
"def sanitize_like(string, escape_character = \"\\\\\")\n pattern = Regexp.union(escape_character, \"%\", \"_\")\n string.gsub(pattern) { |x| [escape_character, x].join }\nend",
"def clean_chars(options = {})\n str = self\n str = str.gsub(',', ' ') unless options[:keep_commas]\n str = str.gsub('.', ' ') unless options[:keep_periods]\n str = str.gsub(/ +/, ' ')\n str = str.strip\n\n str = str.split('').map do |char|\n char if char.normal_char?\n end.compact.join\n\n str = str.gsub(/ +/, ' ').strip\n str\n end",
"def cln(str, dot = true)\n str.gsub!('/', '_')\n str.gsub!(':', '_')\n str.gsub!('?', '_')\n str.gsub!(/\\.$/, '_') if dot\n str \nend",
"def data_cleansing(data)\n # Removes extra spaces, commas, dollar sign etc.\n data = data.strip.split('')\n (data - [',', '%', ' ', '$']).join\nend",
"def sanitize(text)\n text.gsub('<', '<').gsub('>', '>')\n end",
"def cleaned(txt)\n\t\ttxt.gsub(/[(,\\'.#)]/, '')\n\tend",
"def cleaned(txt)\n\t\ttxt.gsub(/[(,\\'.#)]/, '')\n\tend",
"def _encode(source)\n source.gsub(' ','_').gsub(/%.<.+?>/) { |match|\n CGI.escape(match[3..-2]).gsub('%', match[1..1])\n }\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.6005921",
"0.60011256",
"0.5975809",
"0.5950715",
"0.59500986",
"0.5944952",
"0.5942587",
"0.5938947",
"0.59366494",
"0.5931163",
"0.59279",
"0.59231",
"0.59221864",
"0.59215325",
"0.59192187",
"0.59155494",
"0.59095246",
"0.5901524",
"0.5894784",
"0.58864784",
"0.5880001",
"0.58736783",
"0.5860948",
"0.5860007",
"0.5859961",
"0.58499676",
"0.58494204",
"0.58453107",
"0.58428097",
"0.58386785",
"0.58380926",
"0.5836603",
"0.58290637",
"0.5827",
"0.5825539",
"0.5825539",
"0.5825539",
"0.5825539",
"0.5825399",
"0.5823723",
"0.58236754",
"0.5819038",
"0.5818047",
"0.5817619",
"0.58170813",
"0.58069766",
"0.58049816",
"0.58040655",
"0.5803973",
"0.58025974",
"0.5799413",
"0.5794678",
"0.57922137",
"0.57896453",
"0.57883024",
"0.57797265",
"0.5779317",
"0.5776883",
"0.5773988",
"0.57623935",
"0.5761316",
"0.5759221",
"0.57583517",
"0.57494974",
"0.5749227",
"0.5748977",
"0.5743346",
"0.57383823",
"0.57383823",
"0.57369137"
] | 0.74023795 | 0 |
FIXME a lot more could be done with "by citations". identities gives summaries of the most popular works as well as other descriptive information like subject headings. This might be able to be used for enhancing metadata. | def extract_works(doc)
works = []
doc.search("by/citation/title").each_with_index do |t, i|
works << t.inner_text
break if @num_of_works == i + 1
end
return nil if works.blank?
"most widely held #{works.length == 1 ? "work" : "works"}: " + works.join("; ")
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def known_identities; end",
"def author_identities_set\n author_identities.map do |ident|\n normalize_author_identity(ident.first_name, ident.middle_name || 'None',\n ident.last_name, ident.institution || 'None')\n end.to_s\n end",
"def doi_metadata\n # This must be mock_doi rather than any identifier defined in the object.\n # Otherwise users could manually specify a different identifier and\n # change records they're not supposed to.\n data = {:identifier => mock_doi}\n \n data[:alternate_identifier] = identifier.map do |identifier|\n next if identifier == full_mock_doi\n guess_identifier_type(identifier)\n end .compact\n\n if respond_to? :doi_published and doi_published\n data[:publication_year] = \"#{doi_published.year}\"\n else\n data[:publication_year] = \"#{Time.new.year}\"\n end\n\n data[:subject] =\n (subject.to_a.map do |e|\n { scheme:'FAST', schemeURI: 'http://fast.oclc.org/', label: e }\n end) +\n (tag.to_a.map do |e|\n { scheme: nil, schemeURI: nil, label: e}\n end)\n\n creator_role=Sufia.config.contributor_roles['Creator']\n data[:creator] = ((contributors_sorted.select do |c|\n c.role.include? creator_role\n end).select do |c|\n !c.marked_for_destruction?\n end).map do |c|\n { name: c.contributor_name.first,\n affiliation: c.affiliation\n }\n end\n\n data[:abstract] = abstract.to_a\n data[:research_methods] = research_methods.to_a\n data[:description] = description.to_a\n data[:funder] = funder.to_a\n data[:contributor] = contributors_sorted.reduce([]) do |a,c|\n # Creator role is converted to nil in contributor_role_to_datacite and then removed with compact\n next a if c.marked_for_destruction?\n roles=c.role.map do |r| contributor_role_to_datacite r end\n roles.compact!\n next a if roles.empty?\n roles.sort! # Roles must be sorted, otherwise authors might change arbitrarily\n roles.each do |r|\n a << {\n name: c.contributor_name.first,\n affiliation: c.affiliation,\n contributor_type: r\n }\n end\n a\n end\n\n\n data[:relatedIdentifier] = related_url.map do |url|\n # related field is now titled cited by, so use that as the relation type\n (guess_identifier_type url).tap do |ident| ident[:relation_type]='IsCitedBy' end\n end\n\n if self.class == GenericFile\n data[:title] = title\n data[:resource_type] = Sufia.config.resource_types_to_datacite[resource_type.first] # Only maping first choice from the list\n data[:size] = [content.size]\n data[:format] = [content.mime_type]\n data[:date_uploaded] = date_uploaded.strftime('%Y-%m-%d')\n data[:rights] = rights.map do |frights|\n {rights: Sufia.config.cc_licenses_reverse[frights], rightsURI: frights}\n end\n else #Add Collection metadata\n data[:title] = [title] # Collection returns string, XML builder expects array\n # FixMe: construct << {contributor, email}\n if not date_created.empty?\n data[:date_created] = Date.parse(date_created.first.to_s).strftime('%Y-%m-%d') unless date_created.empty?\n end\n data[:resource_type] = Sufia.config.resource_types_to_datacite['Collection']\n\n #Add members metadata\n# \t\t\tdata[:rights] = rights.map do |crights|\n# \t\t\t\t{rights: \"Collection rights - \" + Sufia.config.cc_licenses_reverse[crights], rightsURI: crights }\n# \t\t\tend\n# members.reduce(data[:rights]) do |a,mobj|\n data[:rights] = members.reduce([]) do |a,mobj|\n if member_visible? mobj\n if mobj.content.original_name.nil? then filename = mobj.id else filename = mobj.content.original_name end\n if mobj.rights.any?\n a << { # Do we allow for multiple licensing?\n rights: filename + \" - \" + Sufia.config.cc_licenses_reverse[mobj.rights[0]],\n rightsURI: mobj.rights[0]\n }\n else\n a\n end\n else\n a\n end\n end\n\n data[:format] = members.reduce([]) do |a,mobj|\n if member_visible? mobj\n if mobj.content.original_name.nil? then filename = mobj.id else filename = mobj.content.original_name end\n if mobj.content.mime_type.nil? then a end\n a << (filename + \" - \" + mobj.content.mime_type)\n else\n a\n end\n end\n\n data[:size] = members.reduce([]) do |a,mobj|\n if member_visible? mobj\n if mobj.content.original_name.nil? then filename = mobj.id else filename = mobj.content.original_name end\n if mobj.content.size then a end\n a << \"#{filename} - #{mobj.content.size}\"# Should we preatyfier file size in bytes?\n else\n a\n end\n end\n\n\n members.reduce(data[:relatedIdentifier]) do |a,mobj|\n if member_visible? mobj and mobj.respond_to? :doi_landing_page #FixMe: only public objects\n a << { id: mobj.doi_landing_page, id_type: 'URL', relation_type: 'HasPart' }\n else\n a\n end\n end\n end\n return data\n end",
"def primary_terms\n [:title, :description, :creator, :source, :date_created, :date, :rights,\n :language, :identifier, :bibliographic_citation, :rights_holder,\n :coverage, :subject]\n end",
"def identities\n \n return ::IdentifiesAs.object_identities( self ) \n \n end",
"def identifiers\n ret = {}\n ret['issn'] = @issn unless @issn.nil? or @issn == ''\n ret['eissn'] = @eissn unless @eissn.nil? or @eissn == ''\n ret['isbn'] = @isbn unless @isbn.nil? or @isbn == ''\n ret['eisbn'] = @eisbn unless @eisbn.nil? or @eisbn == ''\n ret['oclc'] = @oclc unless @oclc.nil? or @oclc == ''\n ret['lccn'] = @lccn unless @lccn.nil? or @lccn == ''\n ret['doi'] = @doi unless @doi.nil? or @doi == ''\n ret['pmid'] = @pmid unless @pmid.nil? or @pmid == ''\n ret['coden'] = @coden unless @coden.nil? or @coden == ''\n ret['sici'] = @sici unless @sici.nil? or @sici == ''\n ret['bici'] = @bici unless @bici.nil? or @bici == ''\n ret['document_id'] = @document_id unless @document_id.nil? or @document_id == ''\n ret['dissertation_number'] = @dissertation_number unless @dissertation_number.nil? or @dissertation_number == ''\n ret['bibcode'] = @bibcode unless @bibcode.nil? or @bibcode == ''\n ret['eric'] = @eric unless @eric.nil? or @eric == ''\n ret['oai'] = @oai unless @oai.nil? or @oai == ''\n ret['nbn'] = @nbn unless @nbn.nil? or @nbn == ''\n ret['hdl'] = @hdl unless @hdl.nil? or @hdl == '' \n ret['naxos'] = @naxos unless @naxos.nil? or @naxos == '' \n ret\n end",
"def identifiers\n {'issn' => @issn, 'eissn' => @eissn, 'isbn' => @isbn, 'eisbn' => @eisbn, 'oclc' => @oclc, 'lccn' => @lccn, 'doi' => @doi,\n 'svc_specific_id_1' => @svc_specific_id_1, 'svc_specific_id_2' => @svc_specific_id_2, 'svc_specific_id_3' => @svc_specific_id_3}\n end",
"def chicago_citation(record)\n # more than 10, only the first seven should be listed in the bibliography, followed by et al.\n ## less than four, list all, first author: last name, first name, others first name last name\n # and before the last author ##\n authors = get_all_authors(record)\n author_text = \"\"\n unless authors[:primary_authors].blank?\n if authors[:primary_authors].length > 10\n authors[:primary_authors].each_with_index do |author, index|\n if index < 7\n if index == 0\n author_text << \"#{author}\"\n if author.ends_with?(\",\")\n author_text << \" \"\n else\n author_text << \", \"\n end\n else\n author_text << \"#{name_reverse(author)}, \"\n end\n end\n end\n author_text << \" et al.\"\n elsif authors[:primary_authors].length > 1\n authors[:primary_authors].each_with_index do |author, index|\n if index == 0\n author_text << \"#{author}\"\n if author.ends_with?(\",\")\n author_text << \" \"\n else\n author_text << \", \"\n end\n elsif index + 1 == authors[:primary_authors].length\n author_text << \"and #{name_reverse(author).gsub(/\\,.$/, '')}\"\n else\n author_text << \"#{name_reverse(author)}, \"\n end\n end\n else\n author_text << authors[:primary_authors].first.gsub(/\\,.$/, '')\n end\n else\n temp_authors = []\n authors[:translators].each do |translator|\n temp_authors << [translator, \"trans.\"]\n end\n authors[:editors].each do |editor|\n temp_authors << [editor, \"ed.\"]\n end\n authors[:compilers].each do |compiler|\n temp_authors << [compiler, \"comp.\"]\n end\n\n unless temp_authors.blank?\n if temp_authors.length > 10\n temp_authors.each_with_index do |author, index|\n if index < 7\n author_text << \"#{author.first} #{author.last} \"\n end\n end\n author_text << \" et al.\"\n elsif temp_authors.length > 1\n temp_authors.each_with_index do |author, index|\n if index == 0\n author_text << \"#{author.first} #{author.last}, \"\n elsif index + 1 == temp_authors.length\n author_text << \"and #{name_reverse(author.first)} #{author.last}\"\n else\n author_text << \"#{name_reverse(author.first)} #{author.last}, \"\n end\n end\n else\n author_text << \"#{temp_authors.first.first} #{temp_authors.first.last}\"\n end\n end\n end\n\n unless author_text.blank?\n author_text = author_text.gsub(/\\,$/, \"\")\n if author_text[-1, 1] != \".\"\n author_text += \". \"\n else\n author_text += \" \"\n end\n end\n # Get Pub Date\n pub_date = setup_pub_date(record) unless setup_pub_date(record).nil?\n\n # Get volumes\n\n # setup title info\n title = setup_title_info(record)\n\n\n if !authors[:primary_authors].blank? and (!authors[:translators].blank? or !authors[:editors].blank? or !authors[:compilers].blank?)\n additional_title << \"Translated by #{authors[:translators].collect {|name| name_reverse(name)}.join(\" and \")}. \" unless authors[:translators].blank?\n additional_title << \"Edited by #{authors[:editors].collect {|name| name_reverse(name)}.join(\" and \")}. \" unless authors[:editors].blank?\n additional_title << \"Compiled by #{authors[:compilers].collect {|name| name_reverse(name)}.join(\" and \")}. \" unless authors[:compilers].blank?\n end\n\n edition = \"\"\n edition << setup_edition(record) unless setup_edition(record).nil?\n\n pub_info = setup_pub_info(record) unless setup_pub_info(record).nil?\n\n\n citation = \"\"\n citation << \"#{author_text}\" unless author_text.blank?\n\n citation << \"<i>#{title}</i> \" unless title.blank?\n citation << \"#{edition} \" unless edition.blank?\n\n # add volumes information if not null\n volumes = volumes_info(record) unless volumes_info(record).blank?\n volumes = volumes.gsub(\"volumes\", \"vols. \") unless volumes.nil?\n citation << volumes unless volumes.blank?\n\n is_sound = is_sound_disc(record)\n sound_info = physical_description_sound(record)\n\n\n citation << \"#{pub_info}\" unless pub_info.blank? || is_sound\n citation << \"#{sound_info}\" unless sound_info.nil?\n if pub_date.blank? && (!pub_info.blank? || !sound_info.nil?)\n citation << \".\"\n elsif !pub_date.blank? && (!pub_info.blank? || !sound_info.nil?)\n citation << \", #{pub_date}.\"\n elsif !pub_date.blank? && pub_info.blank? && sound_info.nil?\n citation << \"#{pub_date}.\"\n end\n unless citation.blank?\n if citation[-1, 1] != \".\"\n citation += \".\"\n end\n end\n citation\n end",
"def get_identifiers\n identifiers = publication_identifiers.map{|pi| pi.identifier_value}\n identifiers.push(self.isbn) unless !self.isbn\n identifiers.push(self.issn) unless !self.issn\n identifiers.push(self.eissn) unless !self.eissn\n identifiers.push(self.article_number) unless !self.article_number\n return identifiers\n end",
"def collect_people_information\n ### People information\n mark_data_people_information = Array.new\n people_information = @case_details[:case][:system][:people]\n\n mark_data_people_information << 'Answer the following about each person present in the evidence on the system'\n people_information.each do | person_category, person_information |\n mark_data_people_information << person_category.capitalize\n person_information.each { | key, value | mark_data_people_information << \"-#{key.capitalize}::#{value}\" }\n mark_data_people_information << ''\n end\n\n return mark_data_people_information\n end",
"def all_subjects\n observations + profile_users + glossary_terms\n end",
"def description_from_identifiers\n self.identifiers.joins(:identifier_type).order('identifier_types.priority DESC').first&.content_redacted\n end",
"def show_subjects\n @kw_by_code_keys.each{|key|\t# Iterate thru tags in the same order we read them\n # For this instance (parent ID) of this tag...\n pid, tag = key\n\n h_tag = @kw_by_code[key]\n next unless h_tag['a']\n\n h_tag['a'].each{|s|\n subject = s.sub(/ *thesis *$/i, '')\t# Remove \"thesis\" from end of 695.a\n puts \" <meta tagcode=\\\"subjects.fixed1\\\">#{subject}</meta>\"\n }\n }\n end",
"def get_author_and_year\n return ([self.author_string] + [self.year_integer]).compact.join(', ') if self.rank.nil?\n rank = self.rank_class\n\n if rank.nomenclatural_code == :iczn\n misapplication = TaxonNameRelationship.where_subject_is_taxon_name(self).\n with_type_string('TaxonNameRelationship::Iczn::Invalidating::Usage::Misapplication')\n a = [self.author_string]\n\n if a[0] =~ /^\\(.+\\)$/ # (Author)\n a[0] = a[0][1..-2]\n p = true\n else\n p = false\n end\n\n ay = (a + [self.year_integer]).compact.join(', ')\n obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name\n\n unless misapplication.empty? || obj.author_string.blank?\n ay += ' nec ' + ([obj.author_string] + [obj.year_integer]).compact.join(', ')\n end\n\n if SPECIES_RANK_NAMES_ICZN.include?(rank.to_s)\n if p\n ay = '(' + ay + ')' unless ay.empty?\n else\n og = self.original_genus\n cg = self.ancestor_at_rank('genus')\n unless og.nil? || cg.nil?\n ay = '(' + ay + ')' unless ay.empty? if og.name != cg.name\n end\n #((self.original_genus.name != self.ancestor_at_rank('genus').name) && !self.original_genus.name.to_s.empty?)\n end\n end\n\n elsif rank.nomenclatural_code == :icn\n basionym = TaxonNameRelationship.where_object_is_taxon_name(self).\n with_type_string('TaxonNameRelationship::Icn::Unaccepting::Usage::Basionym')\n misapplication = TaxonNameRelationship.where_subject_is_taxon_name(self).\n with_type_string('TaxonNameRelationship::Icn::Unaccepting::Usage::Misapplication')\n b_sub = basionym.empty? ? nil : basionym.first.subject_taxon_name\n m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name\n\n\n t = [self.author_string]\n t += ['(' + self.year_integer.to_s + ')'] unless self.year_integer.nil?\n ay = t.compact.join(' ')\n\n unless basionym.empty? || b_sub.author_string.blank?\n ay = '(' + b_sub.author_string + ') ' + ay\n end\n unless misapplication.empty? || m_obj.author_string.blank?\n ay += ' nec ' + [m_obj.author_string]\n t += ['(' + m_obj.year_integer.to_s + ')'] unless m_obj.year_integer.nil?\n end\n else\n ay = ([self.author_string] + [self.year_integer]).compact.join(' ')\n end\n ay\n end",
"def publication_info\n\n {:type => :content, :id => id}\n\n end",
"def prepare_identities_from_data; end",
"def recip_heading\n\t\tidentity.name.titleize.pluralize\n\tend",
"def subauthorities\n SUBAUTHORITIES.keys\n end",
"def first_author_publications_cnt()\n self.investigator_abstracts.first_author_abstracts.length\n end",
"def text\n #[@organism, @symbol, @description, @aka, @protnames, @summary,@comentaries.join(\". \")].join(\". \") \n [@symbol, @description, @aka, @protnames, @summary].flatten.join(\". \") \n end",
"def piedata\n\t\tlist = Array.new\n\t\tlabel = self.descriptions.joins(:identity).group(\"identities.name\").order(\"identities.name\").count\n\t\tlabel.each do |key, val|\n\t\t\th = Hash.new\n\t\t\th[:label] = key\n\t\t\th[:value] = val\n\t\t\tlist << h\n\t\tend\n\t\treturn list\n\tend",
"def info\n \t{\n \t\t:id => self.id,\n \t\t:content => self.content,\n \t\t:votes => self.votes,\n \t\t:user => self.user,\n \t\t:subject_id => self.subject_id,\n \t\t:c_type => self.c_type,\n\n \t}\n end",
"def primary_terms\n [:title, :description, :source, :rights_note]\n end",
"def identities\n identities = []\n @known_identities = Hash.new\n\n ensure_agent\n if @agent\n @agent.identities.each do |key|\n identities.push key\n @known_identities[ key ] = { :from => :agent }\n end\n end\n\n @key_files.each do |file|\n if @key_existence_tester.readable?( file )\n begin\n key = @keys.load_public_key( file + \".pub\" )\n identities.push key\n @known_identities[ key ] = { :from => :file, :file => file }\n rescue Exception => e\n @log.warn \"could not load public key file \" +\n \"'#{file}.pub' (#{e.message} [#{e.class}])\" if @log.warn?\n end\n end\n end\n\n identities\n end",
"def identities\n results = @ordered.keys.sort\n return results\n end",
"def author_info\n self.authors.map(&:full_name).join(', ')\n end",
"def metadata_cities(structure)\n place = []\n courses = structure.courses\n\n place << 'A domicile' if courses.where(type: 'Course::Private').any?\n if (public_courses = courses.where.not(type: 'Course::Private')).any?\n place += public_courses.flat_map(&:places).flat_map(&:city).uniq.map(&:name).sort\n end\n\n place.first(3).to_sentence\n end",
"def citations\n Footnote.where(noted_id: id).where(slug: '')\n end",
"def represented\n candidates = contact_actors(:direction => :sent).map(&:id)\n\n contact_subjects(:direction => :received) do |q|\n q.joins(:sent_ties => { :relation => :permissions }).\n merge(Permission.represent).\n where(:id => candidates)\n end\n end",
"def chicago_citation(marc)\n authors = get_all_authors(marc)\n author_text = \"\"\n\n # If there are secondary (i.e. from 700 fields) authors, add them to\n # primary authors only if there are no corporate, meeting, primary authors\n if !authors[:primary_authors].blank?\n authors[:primary_authors] += authors[:secondary_authors] unless authors[:secondary_authors].blank?\n elsif !authors[:secondary_authors].blank?\n authors[:primary_authors] = authors[:secondary_authors] if (authors[:corporate_authors].blank? and authors[:meeting_authors].blank?)\n end\n\n # Work with primary authors first\n if !authors[:primary_authors].blank?\n\n # Handle differently if there are more then 10 authors (use et al.)\n if authors[:primary_authors].length > 10\n authors[:primary_authors].each_with_index do |author,index|\n # For the first 7 authors...\n if index < 7\n if index == 0\n author_text << \"#{author}\"\n if author.ends_with?(\",\")\n author_text << \" \"\n else\n author_text << \", \"\n end\n else\n author_text << \"#{name_reverse(author)}, \"\n end\n end\n end\n author_text << \" et al.\"\n # If there are at least 2 primary authors\n elsif authors[:primary_authors].length > 1\n authors[:primary_authors].each_with_index do |author,index|\n if index == 0\n author_text << \"#{author}\"\n if author.ends_with?(\",\")\n author_text << \" \"\n else\n author_text << \", \"\n end\n elsif index + 1 == authors[:primary_authors].length\n author_text << \"and #{name_reverse(author)}.\"\n else\n author_text << \"#{name_reverse(author)}, \"\n end\n end\n else\n # Only 1 primary author\n author_text << authors[:primary_authors].first\n end\n elsif !authors[:corporate_authors].blank?\n # This is a simplistic assumption that the first corp author entry\n # is the only one of interest (and it's not too long)\n author_text << authors[:corporate_authors].first + '.'\n elsif !authors[:meeting_authors].blank?\n # This is a simplistic assumption that the first corp author entry\n # is the only one of interest (and it's not too long)\n author_text << authors[:meeting_authors].first + '.'\n else\n # Secondary authors: translators, editors, compilers\n temp_authors = []\n authors[:translators].each do |translator|\n temp_authors << [translator, \"trans.\"]\n end\n authors[:editors].each do |editor|\n temp_authors << [editor, \"ed.\"]\n end\n authors[:compilers].each do |compiler|\n temp_authors << [compiler, \"comp.\"]\n end\n\n unless temp_authors.blank?\n if temp_authors.length > 10\n temp_authors.each_with_index do |author,index|\n if index < 7\n author_text << \"#{author.first} #{author.last} \"\n end\n end\n author_text << \" et al.\"\n elsif temp_authors.length > 1\n temp_authors.each_with_index do |author,index|\n if index == 0\n author_text << \"#{author.first} #{author.last}, \"\n elsif index + 1 == temp_authors.length\n author_text << \"and #{name_reverse(author.first)} #{author.last}\"\n else\n author_text << \"#{name_reverse(author.first)} #{author.last}, \"\n end\n end\n else\n author_text << \"#{temp_authors.first.first} #{temp_authors.first.last}\"\n end\n end\n end\n title = \"\"\n additional_title = \"\"\n section_title = \"\"\n if marc[\"245\"] and (marc[\"245\"][\"a\"] or marc[\"245\"][\"b\"])\n title << citation_title(clean_end_punctuation(marc[\"245\"][\"a\"]).strip) if marc[\"245\"][\"a\"]\n title << \": #{citation_title(clean_end_punctuation(marc[\"245\"][\"b\"]).strip)}\" if marc[\"245\"][\"b\"]\n end\n if marc[\"245\"] and (marc[\"245\"][\"n\"] or marc[\"245\"][\"p\"])\n section_title << citation_title(clean_end_punctuation(marc[\"245\"][\"n\"])) if marc[\"245\"][\"n\"]\n if marc[\"245\"][\"p\"]\n section_title << \", <i>#{citation_title(clean_end_punctuation(marc[\"245\"][\"p\"]))}.</i>\"\n elsif marc[\"245\"][\"n\"]\n section_title << \".\"\n end\n end\n\n if !authors[:primary_authors].blank? and (!authors[:translators].blank? or !authors[:editors].blank? or !authors[:compilers].blank?)\n additional_title << \"Translated by #{authors[:translators].collect{|name| name_reverse(name)}.join(\" and \")}. \" unless authors[:translators].blank?\n additional_title << \"Edited by #{authors[:editors].collect{|name| name_reverse(name)}.join(\" and \")}. \" unless authors[:editors].blank?\n additional_title << \"Compiled by #{authors[:compilers].collect{|name| name_reverse(name)}.join(\" and \")}. \" unless authors[:compilers].blank?\n end\n\n edition = \"\"\n edition << setup_edition(marc) unless setup_edition(marc).nil?\n\n pub_info = \"\"\n if marc[\"260\"] and (marc[\"260\"][\"a\"] or marc[\"260\"][\"b\"])\n pub_info << clean_end_punctuation(marc[\"260\"][\"a\"]).strip if marc[\"260\"][\"a\"]\n pub_info << \": #{clean_end_punctuation(marc[\"260\"][\"b\"]).strip}\" if marc[\"260\"][\"b\"]\n pub_info << \", #{setup_pub_date(marc)}\" if marc[\"260\"][\"c\"]\n elsif marc[\"264\"] and (marc[\"264\"][\"a\"] or marc[\"264\"][\"b\"])\n pub_info << clean_end_punctuation(marc[\"264\"][\"a\"]).strip if marc[\"264\"][\"a\"]\n pub_info << \": #{clean_end_punctuation(marc[\"264\"][\"b\"]).strip}\" if marc[\"264\"][\"b\"]\n pub_info << \", #{setup_pub_date(marc)}\" if marc[\"264\"][\"c\"]\n elsif marc[\"502\"] and marc[\"502\"][\"a\"] # MARC 502 is the Dissertation Note. This holds the correct pub info for these types of records.\n pub_info << marc[\"502\"][\"a\"]\n elsif marc[\"502\"] and (marc[\"502\"][\"b\"] or marc[\"502\"][\"c\"] or marc[\"502\"][\"d\"]) #sometimes the dissertation note is encoded in pieces in the $b $c and $d sub fields instead of lumped into the $a\n pub_info << \"#{marc[\"502\"][\"b\"]}, #{marc[\"502\"][\"c\"]}, #{clean_end_punctuation(marc[\"502\"][\"d\"])}\"\n end\n\n citation = \"\"\n citation << \"#{author_text} \" unless author_text.blank?\n citation << \"<i>#{title}.</i> \" unless title.blank?\n citation << \"#{section_title} \" unless section_title.blank?\n citation << \"#{additional_title} \" unless additional_title.blank?\n citation << \"#{edition} \" unless edition.blank?\n citation << \"#{pub_info}.\" unless pub_info.blank?\n citation\n end",
"def normalize_author_identity(first_name, middle_name, last_name, institution)\n \"First: #{first_name} Middle: #{middle_name} Last: #{last_name} Institution: #{institution}\"\n end",
"def idols_data\n\n\t\t[[ \"Last name\", \"First name\", \"Description\" ]] + [[ @view_context.number_to_currency(1), 2, 3] ] +\n\t\t@idols.map { |idol| [idol.last_name, idol.first_name, idol.talents.first.description] }\n\n\tend",
"def identifiers; end",
"def person_relator_terms\n {\n \"aut\" => \"Author\",\n \"cre\" => \"Creator\",\n \"edt\" => \"Editor\",\n \"phg\" => \"Photographer\", \n \"mdl\" => \"Module leader\",\n \"spr\" => \"Sponsor\",\n \"sup\" => \"Supervisor\" \n }\n end",
"def story_author_names\n self.authors.map{|x| x.name}.to_sentence\n end",
"def header article\r\n\t\tarticle.attributes.keys.join(', ')\r\n\tend",
"def add_info_on_tag_ids\n desc_hash = Notion.where(locale: @lecture.locale || I18n.default_locale)\n .pluck(:title, :tag_id, :aliased_tag_id)\n .map { |x| [x.first.downcase, x.second || x.third] }\n .select { |x| x.first.in?(@content_descriptions.map(&:downcase)) }\n .to_h\n @content.each do |c|\n c['tag_id'] = desc_hash[c['description'].downcase]\n end\n end",
"def coauthors\n works.collect(&:pseuds).flatten.uniq - pseuds\n end",
"def citations\n CounterCitation.citations(stash_identifier: self)\n end",
"def citations\n CounterCitation.citations(stash_identifier: self)\n end",
"def collect_crime_information\n ### Crime information\n mark_data_crime_information = Array.new\n crime_information = @case_details[:case][:system][:crime]\n\n mark_data_crime_information << 'Answer the following about each crime present in the evidence on the system'\n crime_information.each do | key, value | mark_data_crime_information << \"-#{key.capitalize}::#{value}\"\n end\n mark_data_crime_information << ''\n\n return mark_data_crime_information\n end",
"def handle_subjects(subjects)\n subjects.each do |link|\n subject = link['_resolved']\n term, *terms = subject['terms']\n ind1 = ' '\n code, *ind2 = case term['term_type']\n when 'uniform_title'\n value = term['term'].split(\" \")[0]\n first_indicator = '0'\n if value\n hsh = {}\n hsh['A'] = '2'\n hsh['An'] = '3'\n hsh['The'] = '4'\n articles = []\n articles = hsh.keys\n first_indicator = hsh[value] if articles.include?(value)\n end\n ['630', first_indicator, source_to_code(subject['source'])]\n when 'temporal'\n ['648', source_to_code(subject['source'])]\n when 'topical'\n ['650', source_to_code(subject['source'])]\n when 'geographic', 'cultural_context'\n ['651', source_to_code(subject['source'])]\n when 'genre_form', 'style_period'\n ['655', source_to_code(subject['source'])]\n when 'occupation'\n ['656', '7']\n when 'function'\n ['656', '7']\n else\n ['650', source_to_code(subject['source'])]\n end\n\n sfs = [['a', term['term']]]\n\n terms.each do |t|\n tag = case t['term_type']\n when 'uniform_title'; 't'\n when 'genre_form', 'style_period'; 'v'\n when 'topical', 'cultural_context'; 'x'\n when 'temporal'; 'y'\n when 'geographic'; 'z'\n end\n sfs << [tag, t['term']]\n end\n\n # code borrowed from Yale to export subject authority id\n unless subject['authority_id'].nil?\n sfs << ['0', subject['authority_id']]\n end\n\n \n # N.B. ind2 is an array at this point.\n if ind2[0] == '7'\n sfs << ['2', subject['source']]\n end\n\n # adding this code snippet because I'm making ind2 an array\n # for code 630 if the title begins with an article\n if (ind2.is_a?(Array) && code == '630')\n ind1, ind2 = ind2\n else\n ind2 = ind2[0]\n end\n\n df!(code, ind1, ind2).with_sfs(*sfs)\n end\n end",
"def subject\n area_of_study\n end",
"def merge_info\n num_obs = observations.count\n num_namings = namings.count\n \"#{:NAME.l} ##{id}: #{real_search_name} [o=#{num_obs}, n=#{num_namings}]\"\n end",
"def tags\n\t\t@tags = @identities = Identity.sorted_alphabetic.decorate\n\tend",
"def get_all_authors(record)\n translator_code = \"trl\"; editor_code = \"edt\"; compiler_code = \"com\"\n primary_authors = []; translators = []; editors = []; compilers = []\n corporate_authors = []; meeting_authors = []; secondary_authors = []\n record.find_all{|f| f.tag === \"100\" }.each do |field|\n primary_authors << field[\"a\"] if field[\"a\"]\n end\n record.find_all{|f| f.tag === '110' || f.tag === '710'}.each do |field|\n corporate_authors << (field['a'] ? field['a'] : '') +\n (field['b'] ? ' ' + field['b'] : '')\n end\n record.find_all{|f| f.tag === '111' || f.tag === '711' }.each do |field|\n meeting_authors << (field['a'] ? field['a'] : '') +\n (field['q'] ? ' ' + field['q'] : '')\n end\n record.find_all{|f| f.tag === \"700\" }.each do |field|\n if field[\"a\"]\n relators = []\n relators << clean_end_punctuation(field[\"e\"]) if field[\"e\"]\n relators << clean_end_punctuation(field[\"4\"]) if field[\"4\"]\n if relators.include?(translator_code)\n translators << field[\"a\"]\n elsif relators.include?(editor_code)\n editors << field[\"a\"]\n elsif relators.include?(compiler_code)\n compilers << field[\"a\"]\n else\n secondary_authors << field[\"a\"]\n end\n end\n end\n\n primary_authors.each_with_index do |a,i|\n primary_authors[i] = a.gsub(/[\\.,]$/,'')\n end\n secondary_authors.each_with_index do |a,i|\n secondary_authors[i] = a.gsub(/[\\.,]$/,'')\n end\n\n {:primary_authors => primary_authors, :corporate_authors => corporate_authors, :translators => translators, :editors => editors, :compilers => compilers,\n :secondary_authors => secondary_authors, :meeting_authors => meeting_authors }\n end",
"def list_citizens\n\t\tputs \"\"\n\t\t@citizens.each do |citizen|\n\t\t\tprint \"#{citizen.voter_id}\\t#{citizen.class}, #{citizen.name}, \"\n\t\t\tputs case citizen\n\t\t\twhen Person then citizen.politics\n\t\t\twhen Politician then citizen.party\n\t\t\tend\n\t\tend\n\t\tputs \"No citizens yet!\" if @citizens.none?\n\tend",
"def overview\n case id\n when \"CDN-REALESTATE\"\n \"ETFs that provide exposure to the Canadian Real Estate market - broadly distributed across the country.\"\n when \"COMMODITIES\"\n \"ETFs that provide exposure to various commodities - generally considered as input to a growing economy.\"\n when \"US-LGCAP-STOCK\"\n \"ETFs that provide exposure to the equity of large, U.S. based companies.\"\n when \"US-LONG-GOV-BOND\"\n \"ETFs that provide exposure to U.S. Government debt, with long maturities.\"\n when \"INTL-REALESTATE\"\n \"ETFs that provide exposure to the International Real Estate market - broadly distributed across the globe.\"\n when \"US-REALESTATE\"\n \"ETFs that provide exposure to the U.S. Real Estate market - broadly distributed across the country.\"\n when \"US-SHORT-CORP-BOND\"\n \"ETFs that provide exposure to U.S. Corporate debt, with short maturities.\"\n when \"CDN-LONG-BOND\"\n \"ETFs that provide exposure to Canadian Corporate debt, with long maturities.\"\n when \"CDN-SHORT-BOND\"\n \"ETFs that provide exposure to Canadian Corporate debt, with short maturities.\"\n when \"US-SMCAP-STOCK\"\n \"ETFs that provide exposure to the equity of smaller U.S. based companies.\"\n when \"INTL-BOND\"\n \"ETFs that provide exposure to International Government & Corporate debt, with varying maturities.\"\n when \"US-SHORT-GOVT-BOND\"\n \"ETFs that provide exposure to U.S. Government debt, with shorter maturities.\"\n when \"US-MED-CORP-BOND\"\n \"ETFs that provide exposure to U.S. Corporate debt, with medium maturities.\"\n when \"CDN-STOCK\"\n \"ETFs that provide exposure to the equity of Canadian companies.\"\n when \"US-MED-GOV-BOND\"\n \"ETFs that provide exposure to U.S. Government debt, with medium maturities.\"\n when \"EMERG-STOCK\"\n \"ETFs that provide exposure to the equity of companies based in countries classified as Emerging Markets.\"\n when \"US-LONG-CORP-BOND\"\n \"ETFs that provide exposure to U.S. Corporate debt, with longer maturities.\"\n when \"INTL-STOCK\"\n \"ETFs that provide exposure to the equity of companies based in Europe, Asia and the Far East (EAFE).\"\n else\n raise \"Asset class overview not prepared.\"\n end\n end",
"def identities\n render json: current_user.identities\n end",
"def all_article_titles_with_authors\n @all = {}\n search_techcrunch[\"articles\"].each do |hash|\n author = hash[\"author\"]\n title = hash[\"title\"]\n @all[title] = author\n end\n return @all\n end",
"def forfatter(*arg)\n self.get_authors.map{ |a| a[\"sn\"] + \", \" +a[\"gn\"] }\n end",
"def get_all_authors(record)\n translator_code = \"trl\"; editor_code = \"edt\"; compiler_code = \"com\"\n primary_authors = []; translators = []; editors = []; compilers = []\n record.find_all {|f| f.tag === \"100\"}.each do |field|\n primary_authors << field[\"a\"] if field[\"a\"]\n end\n record.find_all {|f| f.tag === \"700\"}.each do |field|\n if field[\"a\"]\n relators = []\n relators << clean_end_punctuation(field[\"e\"]) if field[\"e\"]\n relators << clean_end_punctuation(field[\"4\"]) if field[\"4\"]\n if relators.include?(translator_code)\n translators << field[\"a\"]\n elsif relators.include?(editor_code)\n editors << field[\"a\"]\n elsif relators.include?(compiler_code)\n compilers << field[\"a\"]\n else\n primary_authors << field[\"a\"] unless primary_authors.include?(field[\"a\"])\n end\n end\n end\n {:primary_authors => primary_authors, :translators => translators, :editors => editors, :compilers => compilers}\n end",
"def author_hash; end",
"def metadata_subject(structure)\n structure.subjects.first.name\n end",
"def alpha_toc\n attributes = SECTIONS.collect { |s| s['attributes'] }.flatten\n # -> ['author', 'autorequire', ...]\n attr_map = attributes.partition_by { |a| a[0,1] }\n # -> { 'a' => ['author', ...], 'b' => ... }\n attributes = attr_map.collect { |letter, attrs|\n [letter.upcase, attrs.sort]\n }.sort_by { |l, _| l }\n # -> [ ['A', ['author', ...], ...]\n attributes = attributes.collect { |letter, attrs|\n \"* *#{letter}* \" << attrs.collect { |a| _link(a) }.join(SEPSTRING)\n } # -> [ 'A author | autorequire', 'B bindir', ...]\n puts attributes.join(\"\\n\")\nend",
"def above_fold_terms\n [:maker,\n :date_original,\n :date_published,\n :resource_type,\n :genre_string,\n :identifier,\n :rights,\n ]\n end",
"def score_metadata(edition)\n oclcnum = edition[\"oclc_numbers\"].collect {|i| i.to_i}.max unless edition[\"oclc_numbers\"].blank?\n oclcnum = nil if oclcnum == 0\n\n score = 0\n [\"title\", \"publish_places\", \"publishers\", \"publish_date\", \"isbn_10\", \"isbn_13\", \"lccn\"].each do |key|\n score = score + 1 unless edition[key].blank?\n end\n\n return {:oclcnum => oclcnum, :numfields => score}\n end",
"def primary_terms\n [:title, :creator, :description, :license]\n end",
"def first_author_publications_cnt()\n self.investigator_abstracts.find(:all,\n :conditions => [\"is_first_author = :is_first_author and end_date is null\",\n {:is_first_author => true}] ).length\n end",
"def header article\n \"title, summary, source, date, guid, isPermaLink\"\n end",
"def info_and_interview_details\n details = {}\n details[:interview_schedules] = interviews.select{|interview| interview.interview_date > Date.current}.sort_by(&:interview_date).first(2).pluck(:description)\n details[:info] = [name, email]\n details[:questions] = questions.pluck(:question)\n details\n end",
"def specialty\n self.dig_for_string(\"agentSummary\", \"specialty\")\n end",
"def show_all_authors\n @all = []\n search_techcrunch[\"articles\"].each do |article|\n @all << article[\"author\"]\n end\n unique_array = @all.uniq!.sort\n puts \"#{dashes}\\n\"\n unique_array.each_with_index do |author, index| puts \"#{index+1}. #{author}\"\n end\n return nil\n end",
"def attribution\n user = roles.creator.first&.user\n user = roles.administrator.not_creator.first&.user if user.blank?\n return [] if user.blank?\n\n text = user&.name(false)\n orcid = user.identifier_for_scheme(scheme: 'orcid')\n if orcid.present?\n text += format(' - <strong>ORCID:</strong> <a href=\"%{orcid_url}\" target=\"_blank\">%{orcid}</a>',\n orcid_url: orcid.value, orcid: orcid.value_without_scheme_prefix)\n end\n text\n end",
"def metadata(articles)\n c = articles.map do |article|\n article.data.category\n end.uniq.sort\n l = articles.map do |article|\n article.lang\n end.uniq.sort\n t = articles.reduce(Set.new()) do |p, n|\n p + n.tags\n end.to_a.sort\n cl = {}# whether to show category for a lang\n articles.each do |article|\n cl[article.data.category] ||= {} \n cl[article.data.category][article.lang] = true\n end\n {categories: c, langs: l, tags: t, category_lang: cl}.to_json\n end",
"def popularities\n result = {}\n @courses.each do |cl|\n result[cl.name] = Hash.new(0)\n end\n @students.each do |student|\n student.each_with_index do |course_choice, i|\n result[course_choice.name][i] += 1\n end\n end\n result\n end",
"def metadata\n out_hash = {}.with_indifferent_access\n %i[doi upload_type publication_date title creators description access_right license\n keywords notes related_identifiers method locations communities].each do |meth|\n next if meth == 'doi' && @dataset_type != :data\n\n result = send(meth)\n out_hash[meth] = result unless result.blank?\n end\n out_hash\n end",
"def print_info(info)\n bio = []\n committees = []\n info.each do |li|\n if li.include?(\"ommittee\")\n committees << li\n else\n bio << li\n end\n end\n puts \"---------------------- Personal Bio ----------------------\"\n bio.each do |li|\n puts li\n end\n puts \"\"\n puts \"------------------------ Committees ------------------------\"\n committees.each do |li|\n puts li\n end\n puts \"\"\n end",
"def to_hash\n {\n :titles => @titles,\n :creators => @creators.map(&:to_hash),\n :subjects => @subjects,\n :description => @description,\n :publisher => @publisher,\n :contributors => @contributors.map(&:to_hash),\n :dates => @dates.map(&:to_hash),\n :identifiers => @identifiers.map(&:to_hash),\n :source => @source,\n :languages => @languages,\n :rights => @rights,\n :drm_protected => @drm_protected,\n :cover => @cover,\n }\n end",
"def attendees_by_craft_interest\n a1 = []\n results = Hash.new(a1)\n @attendees.each do |attendee|\n attendee.interests.each do |interest|\n if results[interest] == []\n results[interest] = attendee.name\n else\n results[interest] = a1 << attendee.name\n end\n end\n end\n # require \"pry\"; binding.pry\n results\n end",
"def exams_statistics\n end",
"def index\n @identities = Identity.all\n end",
"def index\n @identities = Identity.all\n end",
"def extract_citations(doc, object)\n authorities = (doc/'/authority')\n authorities.each do |authority|\n is = MmsIntegration::Document.find(authority.inner_text)\n cit = Citation.create(:info_source_id => is.id, :citable=> object)\n end\n\n end",
"def to_s\n\t\t\"#{title}, by #{authors.join(', ')}\"\n\tend",
"def general_info\n return <<HERE\n Manuscript Title: #{self.title}<br />\n Manuscript Type: #{self.manuscript_type.name}<br />\n Main Subject Category: #{self.article_section.article_section_name}<br />\n Manuscript Counts<br />\n Pages: #{self.num_pages}<br />\n References: #{self.num_refs}<br />\n Tables: #{self.num_tables}<br />\n Figures: #{self.num_figures}<br />\n Supplemental Materials: #{self.num_suppl_mtrls}<br />\n Co-Authors: #{self.coauthors.count}<br />\nHERE\n end",
"def interactive_info(i)\n info = [];\n (2013..2019).each{|year|\n info << i.interactive_page.lightweight_activity.runs.where(updated_at: Date.new(year)..Date.new(year+1)).count\n }\n info << i.interactive_page.lightweight_activity.runs.where(updated_at: Date.new(2020)..Date.today).count\n\n info << i.interactive_page.lightweight_activity.runs.count\n info << i.id\n info << i.interactive_page.lightweight_activity.id\n info << i.url\n info\nend",
"def attribute_survey\n heading = proc { |str| %{\\n\\nh3. <a name=\"#{str}\">#{str}</a>\\n\\n} }\n subheading = proc { |str| \"\\n\\nh4. #{str}\\n\\n\" }\n pre = proc { |str| \"<pre>\\n#{str}\\n</pre>\\n\" }\n para = proc { |str| str.gsub(/\\n/, \"\\n\\n\") }\n toclink = \"\\n<em>Goto #{_link('toc', 'Table of Contents')}</em>\"\n ATTRIBUTES.sort_by { |a| a['name'] }.each do |a|\n a = OpenStruct.new(a)\n puts \"\\n----\\n\"\n puts heading[a.name]\n puts _metadata(a)\n puts subheading['Description']\n puts _resolve_links(a.description)\n puts subheading['Usage']\n puts pre[a.usage.strip.gsub(/^/, ' ')]\n if a.notes\n puts subheading['Notes']\n puts _resolve_links(para[a.notes.strip])\n end\n puts toclink\n end\nend",
"def secondary_terms\n [:creator,\n :contributor,\n :keyword,\n :license,\n :publisher,\n :date_created,\n :subject,\n :language,\n :identifier,\n :based_near,\n :campus,\n :related_url,\n :resource_type]\n end",
"def index\n authorize Title\n @titles_public = Title.where(public: true).order(:name)\n @titles_no_public = Title.where(public: false).order(:name)\n\n user_titles = User.pluck(:ldap_attributes).map{|j| j['title'].split(',') }.flatten\n\n @result = user_titles.each_with_object(Hash.new(0)) { |title,counts| counts[title] += 1 }\n\n end",
"def display_article_authors(article, with_info=false)\n authors = article.authors.map{|author| author.gplus_profile.blank? ? author.name : link_to(author.name, author.gplus_profile)}.to_sentence(two_words_connector: \" & \", last_word_connector: \" & \").html_safe\n if with_info\n authors += (\" — \" + article.authors.map{|author| content_tag(:span, \"#{author.description}\", class: 'author_description') }.join(\" — \")).html_safe\n end\n authors\n end",
"def associate_authors\n publication = @publication\n # project = publication.project || current_user.person.projects.first\n association = {}\n publication.non_seek_authors.each do |author|\n matches = []\n #Get author by last name\n last_name_matches = Person.find_all_by_last_name(author.last_name)\n matches = last_name_matches\n #If no results, try searching by normalised name, taken from grouped_pagination.rb\n if matches.size < 1\n text = author.last_name\n #handle the characters that can't be handled through normalization\n %w[ØO].each do |s|\n text.gsub!(/[#{s[0..-2]}]/, s[-1..-1])\n end\n \n codepoints = text.mb_chars.normalize(:d).split(//u)\n ascii=codepoints.map(&:to_s).reject{|e| e.length > 1}.join\n \n last_name_matches = Person.find_all_by_last_name(ascii)\n matches = last_name_matches\n end\n \n #If more than one result, filter by project\n # if matches.size > 1\n # project_matches = matches.select{|p| p.projects.include?(project)}\n # if project_matches.size >= 1 #use this result unless it resulted in no matches\n # matches = project_matches\n # end\n # end \n \n #If more than one result, filter by first initial\n if matches.size > 1\n first_and_last_name_matches = matches.select{|p| p.first_name.at(0).upcase == author.first_name.at(0).upcase}\n if first_and_last_name_matches.size >= 1 #use this result unless it resulted in no matches\n matches = first_and_last_name_matches\n end\n end\n\n #Take the first match as the guess\n association[author.id] = matches.first\n end\n \n @author_associations = association\n end",
"def categorized_list\n %w[artist copyright character meta general]\n end",
"def descMetadata_display_fields\n [:identifier, :title, :alternative, :creator, :contributor, :description, :abstract,\n :toc, :publisher, :source, :date, :date_created, :date_copyrighted,\n :date_submitted, :date_accepted, :date_issued, :date_available,\n :date_modified, :language, :type, :format, :extent, :medium, :persname,\n :corpname, :geogname, :subject, :genre, :provenance, :rights,\n :access_rights, :rights_holder, :license, :replaces, :isReplacedBy,\n :hasFormat, :isFormatOf, :hasPart, :isPartOf, :accrualPolicy, :audience,\n :references, :spatial, :bibliographic_citation, :temporal, :funder,\n :resolution, :bitdepth, :colorspace, :filesize]\n end",
"def members_commonest_data2\n data = [['Ethnicity', 'Male', 'Female']]\n members.group(\"meta_info->>'ethnicity'\").pluck(\"meta_info->>'ethnicity'\").delete_empty.each do |v|\n data << [v.to_s.titleize, members.where(\"meta_info->>'ethnicity' = ?\", v.to_s).male.count, members.where(\"meta_info->>'ethnicity' = ?\", v.to_s).female.count]\n end\n data\n end",
"def articles\r\n ARTICLE[@climate_service.clothes]\r\n end",
"def import_author_identities_set(import_settings)\n import_settings.map do |import_setting|\n # ensure that we have a *new* identity worth saving\n next unless author_identity_different?(import_setting_to_attribs(import_setting))\n\n normalize_author_identity(import_setting['firstName'], import_setting.fetch('middleName', 'None'),\n import_setting['lastName'], import_setting.fetch('institution', 'None'))\n end.compact.to_s # we need to compact to reject the nils we get from skipping identities that are identical to the primary\n end",
"def show\n author_count = @journal.journal_authors.count\n author_map = @journal.journal_authors.each_with_index.map{|a, i|\n if i == 0\n if a.first_name.blank?\n \"#{a.last_name}\"\n else\n \"#{a.last_name}, #{a.first_name.strip.first}.\"\n end\n elsif i < author_count -1\n if a.first_name.blank?\n \", #{a.last_name}\"\n else\n \", #{a.last_name}, #{a.first_name.strip.first}.\"\n end\n else\n if a.first_name.blank?\n \" & #{a.last_name},\"\n else\n \" & #{a.last_name}, #{a.first_name.strip.first}. \"\n end\n end\n }.compact\n @author_string = author_map.join(\"\")\n top = @journal.page_range_end\n vol = \" vol. #{@journal.journal_volume},\" unless @journal.journal_volume.blank?\n jo = \" no. #{@journal.journal_number},\" unless @journal.journal_volume.blank?\n #@first = \"#{@author_string} #{@journal.publication_year.strftime('%Y')}, '#{@journal.article_title}',\"\n #@ital = \"#{@journal.journal_title},\"\n #@rest = \"vol. #{@journal.journal_volume}, no. #{@journal.journal_number}, pp. #{@journal.page_range_start}-#{top}.\"\n @ref = \"#{@author_string} #{@journal.publication_year.strftime('%Y')}, '#{@journal.article_title}', <i>#{@journal.journal_title}</i>,#{vol}#{jo} pp. #{@journal.page_range_start}-#{top}.\"\n end",
"def index\n @seniorities = Seniority.order(:sort_index).all\n end",
"def stars\n details.css(\"div.plot_summary_wrapper span[itemprop='actors'] a[href^='/name/nm']\").map do |node|\n imdb_id = node['href'].parse_imdb_id\n name = node.text.strip\n\n [imdb_id, name]\n end.map do |values|\n Spotlite::Person.new(*values)\n end\n end",
"def to_hash\n {\n :titles => @titles,\n :creators => @creators.map(&:to_hash),\n :subjects => @subjects,\n :description => @description,\n :publisher => @publisher,\n :contributors => @contributors.map(&:to_hash),\n :dates => @dates.map(&:to_hash),\n :identifiers => @identifiers.map(&:to_hash),\n :source => @source,\n :languages => @languages,\n :rights => @rights,\n :drm_protected => @drm_protected\n }\n end",
"def authors\n ret = {}\n @doc.css('map authors').children.each do |ch|\n uuid = ch.attr('uuid')\n role = ch.attr('role')\n next if uuid.blank?\n ret[uuid.gsub('-', '')] = ''\n if !role.blank?\n ret[uuid] = \" <i>(#{role})</i>\"\n end\n end\n ret\n end",
"def leech_story_info\n doc = Nokogiri::HTML(open(\"#{FicSourceURL}/s/#{@fic_id}\"), \"UTF-8\") \n # get author name\n author = doc.xpath(\"//table[@id='gui_table1i']/tbody/tr[1]/td[1]/a[1]\").first.inner_text\n # get story title\n title = doc.xpath(\"//table[@id='gui_table1i']/tbody/tr[1]/td[1]/b[1]\").first.inner_text\n {:title => title, :author => author}\n end",
"def generate_zotero_defaults\n xml = Nokogiri::XML(@datastreams[\"zotero\"]) \n id_hash = {}\n # no public or private tag -> private per tcramer, 11/28\n id_hash[\"access_display\"] ||= [\"Private\"]\n id_hash[\"access_facet\"] ||= [\"Private\"]\n id_hash[\"public_b\"] ||= ['false'] \n id_hash[\"identifiers_s\"] ||= [@pid]\n id_hash[\"identifiers_t\"] ||= [@pid]\n \n xml.search(\"//dcterms:LCC\").each do |id| \n id_hash[\"identifiers_s\"] << id.content.strip\n id_hash[\"identifiers_t\"] << id.content.strip\n end\n \n series = \"Accession 2005-101\"\n id_hash[\"identifiers_s\"].each do |id|\n if id.include?(\"SC340_1986\") \n series = \"Accession 1986-052\"\n end\n end\n \n [\"facet\", \"display\", \"s\", \"t\", \"sort\"].each {|v| id_hash[\"series_#{v}\"] ||= []; id_hash[\"series_#{v}\"] << series }\n return id_hash\n end",
"def pubannos(data)\n \n result = JSON.parse(data)\n \n if result.has_key? 'Error'\n raise BioInterchange::Exceptions::InputFormatError, 'Error parsing the JSON input file: #{result[\"Error\"]}'\n end\n \n \n text = result['text']\n #doc_uri = \"http://pubannotation.dbcls.jp/pmdocs/\" + result['pmid'].to_s\n doc_uri = result['docurl']\n \n doc = Document.new(doc_uri)\n docContent = Content.new(0, text.length, Content::DOCUMENT, @process)\n docContent.setContext(doc)\n doc.add(docContent)\n \n #so our document requires content of type document or abstract\n #should it hold the content string?\n\n #hash to remember annotation in case they are needed for building upon based on ids later\n contents = {}\n\n if result['catanns']\n result['catanns'].each do |annot| \n start_offset = 0\n end_offset = 0\n if annot['span']\n start_offset = annot['span']['begin']\n end_offset = annot['span']['end']\n elsif annot['begin'] and annot['end']\n start_offset = annot['begin']\n end_offset = annot['end']\n end\n length = end_offset - start_offset\n\n category = annot['category']\n id = annot['id']\n \n entity = text.slice(start_offset..end_offset)\n \n #phrase = type for NE\n con = Content.new(start_offset, length, Content::PHRASE, @process)\n con.setContext(doc)\n doc.add(con)\n\n contents[id] = con \n \n #set process.date = updated_time?\n end\n end\n \n if result['insanns']\n result['insanns'].each do |annot|\n \n #unsure what to do about this (con1), 'E1' is the ID of something not created yet.\n #it is perhaps a case of making a new content, but with what params...?\n #need to conform what this is refering to with JDK\n con1 = nil \n con2 = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'subClassOf'\n type = ContentConnection::SUBCLASS\n end\n connection = ContentConnection.new(con1, con2, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n if result['relanns']\n result['relanns'].each do |annot|\n con1 = contents[annot['subject']] \n con2 = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'equivalentTo'\n type = ContentConnection::EQUIVALENCE\n when 'themeOf'\n type = ContentConnection::THEME\n end\n connection = ContentConnection.new(con1, con2, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n if result['modanns']\n result['modanns'].each do |annot|\n \n #in this case, it is a modification of an already existing content object (speculation/negation). \n con = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'Speculation'\n type = ContentConnection::SPECULATION\n when 'Negation'\n type = ContentConnection::NEGATION\n end\n connection = ContentConnection.new(con, nil, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n doc\n end",
"def to_authoring_hash\n hash = to_hash\n hash[:id] = id\n hash[:linked_interactive_id] = linked_interactive_id\n hash[:linked_interactive_type] = linked_interactive_type\n hash[:aspect_ratio] = aspect_ratio\n hash[:interactive_item_id] = interactive_item_id\n hash[:linked_interactive_item_id] = linked_interactive_item_id\n # Note that linked_interactives is independent from linked_interactive_id and linked_interactive_type fields\n hash[:linked_interactives] = linked_interactives_list\n hash\n end",
"def identifying_string\n @identifying_string ||= \"#{name}, Co. #{county}\"\n end",
"def full_citation\n \"#{name}, #{cite1} (#{date_decided.year})\"\n end",
"def details\n return \"ID = #{@id}\\n\" + \n \"Name = #{@name}\\n\" + \n \"Topic = #{@topic}\\n\" + \n \"Member Count = #{@member_count}\"\n end",
"def authorities\r\n ptr = Api.proj_get_authorities_from_database(self.context)\r\n Strings.new(ptr)\r\n end",
"def actors_hash\n search_by_itemprop_hash 'actors'\n end"
] | [
"0.6208201",
"0.6206581",
"0.61612713",
"0.60307264",
"0.60089326",
"0.59893966",
"0.5927606",
"0.5844971",
"0.57987094",
"0.578479",
"0.5783206",
"0.5743252",
"0.5741871",
"0.57245195",
"0.5666496",
"0.5633242",
"0.5633153",
"0.5630021",
"0.56274056",
"0.5617466",
"0.56087434",
"0.5593966",
"0.5581131",
"0.55773354",
"0.5572285",
"0.55657965",
"0.55480564",
"0.55336815",
"0.5532323",
"0.55191493",
"0.55164456",
"0.55133533",
"0.5509208",
"0.54840845",
"0.54801345",
"0.54755443",
"0.5462762",
"0.5454095",
"0.543714",
"0.543714",
"0.54264766",
"0.54224116",
"0.5394708",
"0.5386084",
"0.5380508",
"0.53655714",
"0.53645635",
"0.53584075",
"0.53574485",
"0.5354469",
"0.535202",
"0.5321911",
"0.53061974",
"0.52884275",
"0.5285451",
"0.52825594",
"0.52802455",
"0.5279796",
"0.52624446",
"0.5259035",
"0.52571607",
"0.5245666",
"0.52429134",
"0.52097833",
"0.5194333",
"0.5186415",
"0.5181406",
"0.5179566",
"0.5175298",
"0.51664776",
"0.51643",
"0.51627326",
"0.51627326",
"0.51583767",
"0.5155576",
"0.51457345",
"0.5142098",
"0.51405925",
"0.51334924",
"0.5133259",
"0.5129854",
"0.5126212",
"0.51259947",
"0.51197493",
"0.511561",
"0.51140475",
"0.51104736",
"0.5108712",
"0.51085615",
"0.5100763",
"0.5098031",
"0.5097699",
"0.5093638",
"0.50934756",
"0.5093018",
"0.5091625",
"0.50821394",
"0.50814223",
"0.50767875",
"0.50761265",
"0.50681055"
] | 0.0 | -1 |
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",
"def url=(_); end",
"def u(str)\n str.to_url\nend",
"def makeURL(path)\n \"#{self.api_endpt + path}?token=#{self.token}\"\n end",
"def uri(the_url)\n case @url_method\n when :graphical\n self.class.uri_graphical(the_url)\n when :text\n case the_url.to_s\n when /^http/\n puts \"USER ACTION: please enter this url in a browser:\\n\"+the_url.to_s.red()+\"\\n\"\n else\n puts \"USER ACTION: open this:\\n\"+the_url.to_s.red()+\"\\n\"\n end\n else\n raise StandardError,\"unsupported url open method: #{@url_method}\"\n end\n end",
"def consume_url; end",
"def create_uri url\n uri = URI.parse url\n uri.user = @login\n uri.password = @password\n uri\n end",
"def open(url)\n Net::HTTP.get(URI.parse(url))\nend",
"def open(url)\n Net::HTTP.get(URI.parse(url))\nend",
"def make_url(apipath)\n @base_url + \"/api/open-v1.0/\" + apipath\n end",
"def create\n @url = params[:url]\n token = SecureRandom.hex(4)\n @tiny_token = Url.create(\n url: @url,\n token: token,\n domain: \"#{ENV['HOSTNAME']}/#{token}\" \n )\n redirect_to url_path(token)\n \n end",
"def build_call_url(word)\r\n\t\t\tURI.parse(URI.escape(base_url + word))\r\n\t\tend",
"def open_url(term)\n Defcli.open_in_browser search_url(term, :api => false)\n end",
"def chorus_url\n /ju=(.*)&/.match(@openx_url)[1]\n end",
"def alma_build_openurl(query)\n query_defaults = {\n rfr_id: 'info:sid/primo.exlibrisgroup.com',\n }\n\n URI::HTTPS.build(\n host: alma_domain,\n path: \"/view/uresolver/#{alma_institution_code}/openurl\",\n query: query_defaults.merge(query).to_query).to_s\n end",
"def open_url(url)\n url = url.is_a?(NSURL) ? url : NSURL.URLWithString(url)\n request = NSURLRequest.requestWithURL(url, cachePolicy: NSURLRequestUseProtocolCachePolicy, timeoutInterval: 20)\n web.loadRequest request\n end",
"def url_for(string); end",
"def url\n end",
"def build_tiny_url\n self.tiny_url = Token.generate_url\n end",
"def make_url(params) #:nodoc:\n super params.merge(:output => \"xml\", :oe => 'utf8', :ll => @ll, :spn => @spn, :sensor => false)\n end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def url; end",
"def open_target( url )\n\tnewt = Target.new(url)\n\tnewt.open\n\t[ newt.status, newt.uri, newt.ip, newt.body, newt.headers, newt.raw_headers ]\nend",
"def add_ril(url,title)\n begin\n ril_api_url='https://readitlaterlist.com/v2/add'\n\n #パラメタ\n params=Hash::new\n params['apikey']=ENV['RIL_API_KEY']\n params['username']=ENV['RIL_USER']\n params['password']=ENV['RIL_PASS'] \n params['url']=url\n params['title']=title\n \n agent = Mechanize.new\n page = agent.post(ril_api_url,params)\n #p page.header()\n return page.code\n rescue => err\n $logger.error \"RILへの登録でエラーが発生しました。\"\n exit\n end\n\nend",
"def open_in_browser\n puts url\n `#{open} #{url}`\n end",
"def create_short_url\n rand_url = ('a'..'z').to_a.shuffle[0..5].join\n self.short_url = \"#{rand_url}\"\n end",
"def setup_http_request(obj, cookie=nil, args={})\n if args.has_key?(:url) and args[:url] != nil\n if args[:url].scan(/%[s|d]/).length > 0\n if args[:url].scan(/%[s|d]/).length != args[:url_arg].length\n ALERT.call(caller_locations, __callee__, \"URL contains %d '%%s' or '%%d' argument... Fix your code\" % args[:url].scan(/%[s|d]/).length)\n exit 2\n end\n req = obj[:method].new(args[:url] % args[:url_arg])\n else\n req = obj[:method].new(args[:url])\n end\n else\n if args.has_key?(:url_arg)\n if obj[:url].scan(/%[s|d]/).length > 0\n if obj[:url].scan(/%[s|d]/).length != args[:url_arg].length\n ALERT.call(caller_locations, __callee__, \"URL contains %d '%%s' or '%%d' argument... Fix your code\" % obj[:url].scan(/%[s|d]/).length)\n exit 2\n end\n req = obj[:method].new(obj[:url] % args[:url_arg])\n else\n req = obj[:method].new(obj[:url])\n end\n else\n req = obj[:method].new(obj[:url])\n end\n end\n req[\"Host\"] = \"www.blablacar.fr\"\n req[\"origin\"] = \"https://www.blablacar.fr\"\n req[\"User-Agent\"] = \"Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0\"\n req[\"Accept\"] = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\"\n if obj.has_key?(:referer)\n req['Referer'] = obj[:referer]\n else\n req[\"Referer\"] = \"https://www.blablacar.fr/dashboard\"\n end\n req.add_field(\"Connection\", \"keep-alive\")\n if cookie\n req.add_field(\"Cookie\", cookie)\n end\n if obj.has_key?(:header)\n obj[:header].each_slice(2).map{|h|\n req.add_field(h[0], h[1])\n }\n end\n if obj.has_key?(:data)\n if obj[:data].scan(/%[s|d]/).length > 0\n if obj[:data].scan(/%[s|d]/).length != args[:arg].length\n ALERT.call(caller_locations, __callee__, \"Body request contains %d '%%s' or '%%d' argument... Fix your code\" % obj[:data].scan(/%[s|d]/).length)\n exit 2\n else\n req.body = obj[:data] % args[:arg]\n end\n else\n req.body = obj[:data]\n end\n req['Content-Length'] = req.body.length\n end\n req\nend",
"def url(path, params = T.unsafe(nil)); end",
"def to_openurl\n return nil if openurl_disabled\n\n BentoSearch::OpenurlCreator.new(self).to_openurl\n end",
"def build_uri\n print \"building uri object...\"\n @uri = URI::HTTP.build({\n :host => \"lb.#{@datacenter}.reachlocal.com\",\n :path => \"\",\n :port => \"\",\n :scheme => \"http\",\n :fragment => \"\"\n })\n print \"done!\\n\"\n end",
"def make_request_uri(uri, opts); end",
"def url_generic\n url_constructor\n end",
"def create_short_url(url_params) \n url = Url.new(url_params)\n url.suffix= url.create_suffix(url_params[:longurl],0)\n while url.unique(url.suffix) == false\n url.suffix = url.create_suffix(url_params[:longurl],1)\n end\n domain = Domainatrix.parse(url_params[:longurl]).domain + '.' + Domainatrix.parse(url_params[:longurl]).public_suffix\n short_domain = ShortDomain.where(domain: domain).first[:prefix]\n url.shorturl = \"http://\" + short_domain +'/'+ url.suffix\n if url.save\n return url\n else\n return nil\n end\n end",
"def XOgoto (url)\n\t\tbegin\n\t\t\t$pfd.tstart( url)\n @wwBrws.goto( url)\n\t\t\tres= OK\n\t\trescue\n\t\t\tmsg= 'Cannot reach URL: '+url.to_s\n\t\t\tres= setResCritical (msg)\n\n#\t\t\t$pfd.calcApplRes(false,('Cannot reach URL. Parm: /'+url+'/'), url.to_s)\n#\t\t\tres= CRITICAL\n#\t\t\tself.XOtakeScreenShot\n\t\tend\n\t\treturnRes (res )\n\tend",
"def create_http_connection(uri); end",
"def get_my_html_from_open_uri(u)\n hdrs = {\"User-Agent\"=>\"Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\", \"Accept-Charset\"=>\"utf-8\", \"Connection\"=>\"Keep-Alive\", \"Accept\"=>\"text/html\"}\n my_html = \"\"\n begin\n open(u, hdrs).each {|s| my_html << s}\n rescue\n my_html = \"<html><body><p /><b>hello world</b></body></html>\"\n end\n return my_html\n end",
"def get_my_html_from_open_uri(u)\n hdrs = {\"User-Agent\"=>\"Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\", \"Accept-Charset\"=>\"utf-8\", \"Connection\"=>\"Keep-Alive\", \"Accept\"=>\"text/html\"}\n my_html = \"\"\n begin\n open(u, hdrs).each {|s| my_html << s}\n rescue\n my_html = \"<html><body><p /><b>hello world</b></body></html>\"\n end\n return my_html\n end",
"def get_my_html_from_open_uri(u)\n hdrs = {\"User-Agent\"=>\"Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\", \"Accept-Charset\"=>\"utf-8\", \"Connection\"=>\"Keep-Alive\", \"Accept\"=>\"text/html\"}\n my_html = \"\"\n begin\n open(u, hdrs).each {|s| my_html << s}\n rescue\n my_html = \"<html><body><p /><b>hello world</b></body></html>\"\n end\n return my_html\n end",
"def build\n params = @params_map.map do |k, v|\n open_url_key = open_url_params_map[k] || k.to_s\n \"#{open_url_key}=#{v}\"\n end.join('&')\n open_url = @resolver_url + '?' + params\n UmdOpenUrl.logger.debug do\n # Filter out the wskey parameter value\n logged_url = open_url.sub(/wskey=.*?&/, 'wskey=###&')\n UmdOpenUrl.logger.debug(\"UmdOpenUrl::Builder.build - open_url: #{logged_url}\")\n end\n open_url\n end",
"def do_open(url, options = {:auth_needed => false})\n\n\t\tauth_needed = options.delete :auth_needed\n options = options.merge({:http_basic_authentication => [username, password]}) if auth_needed\n options = options.merge({'me2_application_key'=> config['app_key']}) if auth_needed\n\n open(url, options)\n end",
"def utf_page(url)\t\n Hpricot(Iconv.new('utf-8', 'windows-1257').iconv(open(@@WWW+url).read))\n end",
"def link_url(url, title = T.unsafe(nil), params = T.unsafe(nil)); end",
"def link_url(url, title = T.unsafe(nil), params = T.unsafe(nil)); end",
"def create\n @url = Url.new(url_params)\n\n Url.transaction do\n @url.save\n #write base 62 method\n @url.short_url = generate_base62_short_url(@url.id)\n if @url.save\n render json: @url, status: :created, root: :url\n else\n render json: @url.errors, status: :unprocessable_entity\n end\n end\n end",
"def open_url(url)\n @ole.OpenURL(url)\n end",
"def create_url\n uri = Addressable::URI.new\n uri.query_values = properties\n \"#{ BASE_URI }#{ Hubspotter.configuration.portal_id }#{ create_endpoint }#{ uri.query }\"\n end",
"def redirect(url); end",
"def request(url)\n\t\tTyphoeus::Request.new( url, \n\t\t\tfollowlocation: true, \n\t\t\theaders: {\"User-Agent\" => BrowserHeader.random}, \n\t\t\tcookiefile: config[:cookie][:file],\n\t\t\tcookiejar: config[:cookie][:file]\n\t\t)\n\tend",
"def url_create(state_code, city_name)\n 'http://en.m.wikipedia.org/wiki/' + self.url_suffix_create(state_code, city_name)\n end",
"def initialize\n @url_s = 'https://deezerdevs-deezer.p.rapidapi.com/search?q='\n\n end",
"def open(uri_s, options = T.unsafe(nil), &error_block); end",
"def create\n # decode url to remove duplicacy in case of same url encoded and decoded\n url = URI.decode(params[:url])\n # check if url already exists in db\n mini_url = MiniUrlHelper.check_existing_url(url, current_user)\n unless mini_url\n mini_url = MiniUrl.new\n mini_url.url = url\n # a check to handle invalid expiry time\n begin\n mini_url.expiry = DateTime.parse(params[:expiry])\n rescue ArgumentError => e\n logger.error \"Invalid expiry time.\"\n end\n mini_url.user = current_user if current_user\n # call method to generate unique code and save into db\n # raise exception in case of some error\n unless mini_url.generate_unique_code\n raise Exceptions::SavingError.new(mini_url.errors)\n end\n end\n short_url = \"#{BASE_URL}/#{mini_url.url_code}\"\n render json: {short_url: short_url}, status: 201\n rescue Exceptions::SavingError => e\n render json: {error: e}, status: 400\n end",
"def url\n end",
"def http=(_arg0); 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.58361703",
"0.5822619",
"0.58197945",
"0.5806166",
"0.580313",
"0.5802951",
"0.5799544",
"0.5799544",
"0.579819",
"0.57882196",
"0.57833344",
"0.57756174",
"0.5773462",
"0.5770027",
"0.5749832",
"0.5724192",
"0.57192343",
"0.57179797",
"0.5715001",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.57004535",
"0.5680988",
"0.5654934",
"0.5630322",
"0.5627603",
"0.5621959",
"0.56015474",
"0.5601511",
"0.5596909",
"0.5596236",
"0.5592431",
"0.55713737",
"0.55689764",
"0.55661684",
"0.5549084",
"0.5549084",
"0.5549084",
"0.55469424",
"0.55405295",
"0.55362713",
"0.55321014",
"0.55313194",
"0.55312884",
"0.5524031",
"0.5523531",
"0.5519113",
"0.5518264",
"0.55142015",
"0.55089957",
"0.5504226",
"0.5491421",
"0.5490443",
"0.5490277"
] | 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",
"def set_cocktail\n @cocktail = Cocktail.find(params[:id])\n end",
"def print\n Catpix::print_image self.url,\n :limit_x => 0.2,\n :limit_y => 0,\n :center_x => false,\n :center_y => false,\n :bg => \"white\",\n :bg_fill => false \n end",
"def slurl\n position = JSON.parse(self.position)\n href = \"https://maps.secondlife.com/secondlife/#{region}/#{position['x'].round}/\" \\\n \"#{position['y'].round}/#{position['z'].round}/\"\n text = \"#{region} (#{position['x'].round}, \" \\\n \"#{position['y'].round}, #{position['z'].round})\"\n h.link_to(text, href)\n end",
"def fetchCats(dataDir, minConfidence)\n return NellELoad.allCategories(dataDir, minConfidence, NellE::STRICT_TRAINING_CAT_FILENAMES)\nend",
"def frontcover_url\n if @collateral_detail\n @collateral_detail.frontcover_url\n end\n end",
"def image_url_tco(link_url)\n service_url = link_url_redirect link_url\n find_image_url service_url\n end",
"def gather_uri(key = nil, cat = nil, val = nil)\n uri = \"http://jservice.io/api/\"\n if !key.nil? && !cat.nil?\n category = return_categories(key)\n category = category.select {|c| c[\"title\"] == cat}[0] if category.kind_of? Array\n uri += \"clues?category=#{category['id']}\"\n if !val.nil?\n uri += \"&value=#{val}\"\n end\n else\n uri += \"random?count=1\"\n end\n uri\nend",
"def display_img_url(url)\n url.sub(/s90$/, 's360') \n # recipe_response = Faraday.get(\"http://api.yummly.com/v1/api/recipe/#{id}\",\n # _app_id: ENV['YUMMLY_APP_ID'],\n # _app_key: ENV['YUMMLY_APP_KEY'])\n # image = JSON.parse(recipe_response.body)['images'].try(:first)\n # image['hostedLargeUrl'].present? ? image['hostedLargeUrl'] : image['hostedMediumUrl'] if image.present?\n end",
"def accessory_category_identifier\n @configuration.category_identifier\n end",
"def category_url\n revision.category_url\n end",
"def WorldCatCheckControlNumbers(opts={})\n sRecord = \"\"\n @LastResponseCode = \"\"\n base_uri = WORLDCAT_METADATA_CHECK_CONTROL_NUMBERS_URI\n helper = Helper.new(:wskey => @wskey, :secret => @secret, :principalID=>@principalID, :principalDNS => @principalDNS)\n\n base_uri += \"?oclcNumbers=\" + opts[:oclcNumber]\n response = helper.MakeHTTPRequest(:url => base_uri, :method => \"GET\", :accept => \"application/atom+json\")\n @debug_info = helper.debug_string + \"\\n\\n\" + base_uri\n @LastResponseCode = response\n sRecord = response\n return sRecord\n end",
"def link_to_google_earth(content, id)\n link_to(content, \"http://maps.google.co.uk?t=f&q=http://openplaques.org/plaques/\" + id.to_s + \".kml\")\n end",
"def set_cocktail\n @cocktail = Cocktail.find(params[:id])\n end",
"def roads_and_libraries(n, c_lib, c_road, cities)\n \nend",
"def ajax_catalog_link_and_source\n instance_id = params['instanceId']\n url = ENV['OKAPI_URL']\n tenant = ENV['OKAPI_TENANT']\n # Get instance HRID (e.g., bibid) for the record\n response = CUL::FOLIO::Edge.instance_record(url, tenant, folio_token, instance_id)\n link = nil\n source = nil\n if response[:code] < 300\n source = response[:instance]['source']\n # Try to identify ILL items and set source manually -- it's 'FOLIO' in the actual record.\n source = 'ill' if ill_item?(response[:instance])\n\n # Ignore Borrow Direct records for the link -- they have an HRID that looks like a legit bibid, but\n # it's something else BD-related. We can't link to those. But now, most sources are either MARC or\n # FOLIO. A FOLIO source indicates that this was a locally-created record -- e.g., for a temporary record\n # for a BD/ReShare item. Most of the others appear to be MARC-source. This is probably not entirely accurate,\n # but we can filter out the FOLIO records and probably get things right most of the time.\n link = \"https://newcatalog.library.cornell.edu/catalog/#{response[:instance]['hrid']}\" if source == 'MARC'\n end\n render json: { link: link, source: source }\n end",
"def catalog_number\n model.labels.first.catno\n end",
"def find_owner_cat\n @cat = @owner.cats.find_by!(id: params[:id]) if @owner\n end",
"def clothing_item_result_links\n if @country != DE\n @browser.div(:id => \"ctl00_contentBody_productListingSection\").links(:class => \"img\")\n else\n @browser.div(:id => \"ctl00_contentBody_productListingSection\").links(:class => \"img\")\n end\n end",
"def open_lid_image\n image_path(image_name: params[:open_lid_image])\n end",
"def icon\n if (@place[\"categories\"][0] != nil)\n @place[\"categories\"][0][\"icon\"][\"prefix\"] + \"64\" + @place[\"categories\"][0][\"icon\"][\"suffix\"]\n else\n \"https://ss1.4sqi.net/img/categories_v2/building/default_64.png\"\n end\n end",
"def show\n @catogory = Catogory.find(params[:id])\n end",
"def category; end",
"def cp_l\n end",
"def find_normal_image\n return \"Pictures/pcn%04d.png\" % (80 + id)\n end",
"def get_highreslink(bibl_uuid, image_id)\n url = \"#{@server_url}/items/#{bibl_uuid}.json?per_page=500\"\n json = self.get_json(url)\n \n highreslink = nil\n\n json[\"nyplAPI\"][\"response\"][\"capture\"].each do | capture|\n if capture[\"imageID\"] == image_id\n highreslink = capture[\"highResLink\"]\n break \n end #if\n end if json[\"nyplAPI\"][\"response\"][\"numResults\"].to_i > 0 \n\n return highreslink\n end",
"def cover_art\n if @cover_art.nil?\n @cover_art = container.img(:class, 's-access-image').src\n end\n\n @cover_art\n end",
"def main_photo cut\n return self.photos.first.image.url(cut) unless self.photos.empty?\n \n ConfigValue.default_image_for_model(:room_types, cut)\n end",
"def browse_otu_link(object)\n return nil if object.nil?\n otu = object.metamorphosize\n content_tag(:div, '', 'data-taxon-name' => object_tag(otu), 'data-redirect' => 'true', 'data-id' => otu.id, 'data-klass' => object.class.base_class.name.to_s, 'data-otu-button' => 'true')\n end",
"def masterpiece\n if arts.empty?\n \"BioCorgi.jpg\"\n else\n arts.first.location\n end\n end",
"def picture\n if local_picture.nil?\n category.picture if category\n else\n local_picture\n end\n end",
"def smallworld_image(*args, &block)\n Smallworld::Image.define_smallworld_image(*args, &block)\nend",
"def og_url\n \"http://gaymerconnect.com/groups/#{url}\"\n end",
"def goth_image_full_tag(goth)\n\t\timage = image_path \"goths/#{goth.name}.jpg\"\n\t\turl = \"#{root_url.chomp('/')}#{image}\"\n\t\timage_tag url, :alt => goth.name, :title => goth.name\n\tend",
"def get_rand_circuit(name=\"circvit\")\n \n name=name.upcase.scan(/[A-Z]/).join.scan(/[^U]/).join.split(//)\n \n \n family= %w{will belief desire}\n family=family.shuffle\n \n fill = Magick::HatchFill.new(\"Transparent\", \"LightGreen\")\n \n i = Magick::ImageList.new \n i.new_image(333, 333, fill){ self.background_color = \"Transparent\" }\n gc = Magick::Draw.new\n \n \n gc.gravity(Magick::CenterGravity)\n gc.stroke(\"#33cc33\")\n gc.fill(\"#222222\")\n gc.stroke_width(20)\n gc.circle(167, 167, 167, 20)\n gc.stroke(\"#3333cc\")\n gc.fill(\"transparent\")\n gc.stroke_width(2)\n gc.circle(167, 167, 167, 25)\n gc.circle(167, 167, 167, 15)\n gc.circle(167, 167, 167, 22)\n gc.circle(167, 167, 167, 17)\n gc.draw(i)\n\n (0..name.length-1).each do |n|\n i.new_image(333, 333){ self.background_color = \"Transparent\" }\n gc = Magick::Draw.new \n gc.stroke(\"transparent\")\n gc.fill(\"transparent\")\n \n gc.pointsize = (52 + (rand(23)) )\n \n gc.gravity(Magick::CenterGravity)\n f=rand(3)\n gc.font= \"#{Rails.root}/app/assets/fonts/akho#{family[f]}.ttf\" \n gc.text((-rand(72) + rand(72)), (-rand(72) + rand(72)), name[n]).rotate(rand(360))\n gc.fill('red')\n gc.text((-rand(72) + rand(72)), (-rand(72) + rand(72)), name[n]).rotate(rand(360))\n gc.draw(i)\n \n end\n \n \n @Circuit=i.flatten_images\n @Circuit.format = 'png'\n \n \n @circuit_file = \"#{Rails.root}/tmp/circuit-#{name.join}-#{Time.now.to_i}-#{Process.pid}.png\"\n \n \n @Circuit.write('png:'+ @circuit_file)\n \n \n \n \n\n @data_uri = Base64.encode64(@Circuit.to_blob).gsub(/\\n/, \"\") \n @image_tag = '<img alt=\"preview\" src=\"data:image/png;base64,%s\">' % @data_uri\n \n end",
"def cl_photo\n if photo?\n photo\n else\n 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSb0kZ2CA6D46RXZVJ3dvJPusC66fBq1uENE8jN3q8golJ73Ayd'\n end\n end",
"def from_standard_cat_id(cat_id)\n cat_id + 2000\n end",
"def section_built_with(cloc, site_config)\n s = %(\n <div class=\"col-md-5\">\n #{Kramdown::Document.new(site_config['about'].gsub('[English](README.md) [Deutsche](lang/README.de.md)', '')).to_html}\n </div>\n <div class=\"col-md-7\">\n <h3>#{site_config['homepage_subheading4']}</h3>\n <pre>\n <code>\n #{cloc}\n </code>\n </pre>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-sm-12\" id=\"d3pie_chart_div_homepage_all\"></div>\n </div>\n <div class=\"row\">\n <div class=\"col-sm-12\" id=\"d3pie_chart_div_homepage_mit\"></div>\n </div>)\n Dir['python/images/*'].map do |image|\n s += %(\n <div class=\"row\">\n <img class=\"img-responsive\" src=\"#{image}\" alt=\"#{image.split('/').last.split('.').first.capitalize.split('-').join ' '}\">\n </div>)\n end\n s\nend",
"def print\n Catpix::print_image self.img_url,\n :limit_x => 1.0,\n :limit_y => 0,\n :center_x => true,\n :center_y => true,\n :bg => \"white\",\n :bg_fill => true,\n :resolution => \"low\"\n end",
"def set_loc_image\n @loc_image = LocImage.find(params[:id])\n end",
"def cpl\n end",
"def set_cog\n @cog = Cog.find(params[:id])\n end",
"def show\n cf_get(path: \"/organizations/#{org_id}\")\n end",
"def set_custom_camo_hat\n @custom_camo_hat = CustomCamoHat.find(params[:id])\n end",
"def object_category\n \"CN=Group,CN=Schema,CN=Configuration,#{ActiveLdap::Base.base}\"\n end",
"def find_home_image\n return \"Pictures/pct%04d.png\" % (80 + id)\n end",
"def to_tex\n q_url = \"http://dream.misasa.okayama-u.ac.jp/?q=\"\n basename = File.basename(image.name,\".*\")\n lines = []\n lines << \"\\\\begin{overpic}[width=0.49\\\\textwidth]{#{basename}}\"\n lines << \"\\\\put(1,74){\\\\colorbox{white}{(\\\\sublabel{#{basename}}) \\\\href{#{q_url}#{image.global_id}}{#{basename}}}}\"\n lines << \"%%(\\\\subref{#{basename}}) \\\\nolinkurl{#{basename}}\"\n lines << \"\\\\color{red}\"\n\n surface.surface_images.each do |osurface_image|\n oimage = osurface_image.image\n #image_region\n opixels = oimage.spots.map{|spot| [spot.spot_x, spot.spot_y]}\n worlds = oimage.pixel_pairs_on_world(opixels)\n pixels = image.world_pairs_on_pixel(worlds)\n oimage.spots.each_with_index do |spot, idx|\n length = image.length\n height = image.height\n x = \"%.1f\" % (pixels[idx][0] / length * 100)\n y = \"%.1f\" % (height.to_f / length * 100 - pixels[idx][1] / length * 100)\n line = \"\\\\put(#{x},#{y})\"\n line += \"{\\\\footnotesize \\\\circle{0.7} \\\\href{#{q_url}#{spot.target_uid}}{#{spot.name}}}\"\n line += \" % #{spot.target_uid}\" if spot.target_uid\n line += \" % \\\\vs(#{(\"%.1f\" % worlds[idx][0])}, #{(\"%.1f\" % worlds[idx][1])})\"\n lines << line\n end\n end\n\n width_on_stage = image.transform_length(image.width / image.length * 100)\n scale_length_on_stage = 10 ** (Math::log10(width_on_stage).round - 1)\n scale_length_on_image = image.transform_length(scale_length_on_stage, :world2xy).round\n lines << \"%%scale #{(\"%.0f\" % scale_length_on_stage)}\\ micro meter\"\n lines << \"\\\\put(1,1){\\\\line(1,0){#{(\"%.1f\" % scale_length_on_image)}}}\"\n\n lines << \"\\\\end{overpic}\"\n\n lines.join(\"\\n\")\n end",
"def random_cocktail\n\trand_cocktail_url = open(\"https://www.thecocktaildb.com/api/json/v1/1/random.php\").read\n\trand_cocktail_json = JSON.parse(rand_cocktail_url)\n\trand_cocktail_json[\"drinks\"][0]\nend",
"def show\n @cover_cat = CoverCat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cover_cat }\n end\n end",
"def collins_asset\n @host.collins_asset\n end",
"def show\n @otml_category = OtrunkExample::OtmlCategory.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @otml_category }\n end\n end",
"def carto_reference\n return unless public? && download_types.try(:[], :geojson).present?\n Geoblacklight::GeojsonDownload.new(self).url_with_params\n end",
"def link\n @link ||= \"#{IMAGE_URL}#{id}.#{IMAGE_EXTENSION}\"\n end",
"def show\n @cat = Cat.find(params[:id])\n @pictures = Picture.where(\"title LIKE '\"+@cat.id.to_s+\"'\")\n end",
"def additional_brief_location_note(document, _location)\n # Law records need a link back to their native catalog\n if document && document.in_pegasus?\n return content_tag(:span, pegasus_item_link(document, 'Search Results'), class: 'url_link_note')\n end\n end",
"def host_opens_door(car_location)\n case car_location\n when 2\n 3 # the only unpicked door with a goat\n when 3\n 2 # the only unpicked door with a goat\n else\n random.rand(2..3)\n end\n end",
"def display_resource(club)\n club.name\n end",
"def orcid_display_format\n return if orcid.blank?\n # orcid uri shoudl ALWAYS be http://\n orcid_uri.gsub('http://', '')\n end",
"def category_links(category)\n links = \"\"\n iterated_cat = category\n if iterated_cat.parent.nil?\n links = insert_category_link(links,iterated_cat)\n else \n i = 0\n while !iterated_cat.parent.nil? and iterated_cat != Sfcatnode.root\n links = insert_category_link(links,iterated_cat)\n iterated_cat = iterated_cat.parent\n i+= 1\n end\n end\n links.insert(0,\"#{link_to('All Solutions', :action => 'index')}\")\n end",
"def cover_image\n end",
"def cl_image_path(source, options = {})\r\n options = options.clone\r\n url = cloudinary_url_internal(source, options)\r\n image_path_without_cloudinary(url)\r\n end",
"def may_add_category_image(main_image)\n if main_image.present?\n if main_image.variable?\n # return main_image.variant(resize_to_limit: [1280, 1280]).processed.service_url rescue nil\n return main_image.service_url rescue nil\n else\n # TODO: log this exception\n return nil\n end\n else\n nil\n end\n end",
"def get_url(doc, type)\n id = doc.id.to_s\n 'https://scholarworks.calstate.edu/concern/' + type + '/' + id\n end",
"def collar_size_links\n if @country != DE\n @browser.div(:id => \"collar\").ul(:class => \"navList\").links(:href => ALL_SHIRTS_IDENTIFIER_LANG_EN)\n else\n @browser.div(:id => \"collar\").ul(:class => \"navList\").links(:href => ALL_SHIRTS_IDENTIFIER_LANG_DE)\n end\n end",
"def fancy_clu\n clu_obj = CLU.new\n @clu.each { |pixel| clu_obj.array.push(pixel) }\n return clu_obj\n end",
"def ccore(name)\n \"http://clojure.github.com/clojure/clojure.#{name}-api.html\"\n end",
"def image\n MAIN_CDN + \"headshots/current/168x168/#{@id}.jpg\"\n end",
"def test_possible_location_from_cathedral_if_rand_is_one\r\n\t\toakland = City::new\r\n\t\trand_val = 1\r\n\t\tmuseum = oakland.generate_cathedral_locs(oakland, rand_val)\r\n\r\n\t\tassert_equal museum[0], \"Museum\"\r\n\t\tassert_equal museum[1][0], \"Bar St.\"\r\n\tend",
"def select_industry_category\n\t\t@industry_categories = IndustryCategory.all.joins(:countries).where(\"countries.id = ?\", session[:country].id).order \"position\"\n\t\t@watch = \"IndustryCategory\"\n\n \t@title_content = 'Servicios para tu Matrimonio'\n \t@meta_description_content = 'Encuentra todos los servicios y productos que necesitas para la organización de tu matrimonio y aprovecha las oportunidades especiales que tenemos para ti'\n\n\tend",
"def get_oclcs(member_id, hdfn, conn)\n hdf = Hathidata::Data.new(hdfn);\n\n if hdf.exists? then\n $log.i(\"#{hdf.path} already exists, skipping method #{__method__}.\");\n return hdf.path;\n elsif hdf.backup? then\n $log.i(\"Backup of #{overlapf.path} already exists. Skipping method #{__method__}.\");\n return hdf.path;\n end\n\n hdf.open('w');\n sql = \"SELECT DISTINCT oclc FROM holdings_memberitem WHERE member_id = ?\";\n sth = conn.prepare(sql);\n\n $log.d(sql.sub('?', member_id));\n\n count_lines = 0;\n sth.query(member_id) do |row|\n hdf.file.puts row['oclc'];\n count_lines += 1;\n if count_lines % 100000 == 0 then \n $log.d(\"#{count_lines} oclcs output\");\n end\n end\n hdf.close();\n\n return hdf.path;\nend",
"def cl\n field_fetch('CL')\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.47386396",
"0.47246528",
"0.47105557",
"0.47081062",
"0.47053087",
"0.46997362",
"0.46992594",
"0.46943504",
"0.46924785",
"0.46771502",
"0.46602565",
"0.46564877",
"0.46531516",
"0.464929",
"0.46467102",
"0.46400186",
"0.46352595",
"0.46219504",
"0.4601316",
"0.45882976",
"0.45871684",
"0.45820147",
"0.45802656",
"0.45705923",
"0.4567661",
"0.45540732",
"0.4549811",
"0.45422786",
"0.45402387",
"0.45366418",
"0.4530738",
"0.45277214",
"0.45230436",
"0.45178816",
"0.45173305",
"0.4510828",
"0.45091376",
"0.45053098",
"0.4503864",
"0.4498143",
"0.44934347",
"0.44924888",
"0.44872993",
"0.44835246",
"0.44789827",
"0.44784996",
"0.4474624",
"0.44634658",
"0.44581047",
"0.4454744",
"0.4448218",
"0.44460666",
"0.44460243",
"0.44414318",
"0.4439562",
"0.44385093",
"0.4426276",
"0.4420439",
"0.4419162",
"0.4417877",
"0.44175673",
"0.44117168",
"0.44116783",
"0.44095773",
"0.4409419",
"0.44074267",
"0.44012895",
"0.4398501",
"0.43934628",
"0.43913993"
] | 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",
"def csvReader(file, headers)\n begin\n csvTable = CSV.read(file, {col_sep:\"\\t\", quote_char:\"\\0\", headers:headers})\n rescue ArgumentError\n puts \"Error: Unsupported encoding, tabulated/CSV file must be in UTF-8 format.\"\n abort\n end\n parsedObj = OpenStruct.new()\n parsedObj.rowArray = []\n parsedObj.belArray = []\n csvTable.each do |row|\n unless row.length == 0\n current = OpenStruct.new()\n current.bel_id = row[0]\n current.bel_id.slice! \"BEL:\"\n current.bel = row[1]\n current.sentence = row[2]\n current.sentence_id = row[3]\n current.sentence_id.slice! \"SEN:\"\n current.pmid = row[4]\n parsedObj.rowArray << current\n parsedObj.belArray << row[1]\n end\n end\n parsedObj.linecount = csvTable.length\n return parsedObj\nend",
"def OLDview_data db, sql, options\n outputfile = options[:output_to]\n formatting = options[:formatting]\n headers = options[:headers]\n #str = db.get_data sql\n rs = db.execute_query sql\n str = rs.content\n columns = rs.columns\n #puts \"SQL: #{sql}.\\nstr: #{str.size}\"\n data = []\n if headers\n data << columns.join(\"\\t\")\n end\n str.each {|line| data << line.join(\"\\t\"); }\n #puts \"Rows: #{data.size}\"\n require 'tempfile'\n tmpfile = Tempfile.new('SQL.XXXXXX')\n filename = tmpfile.path\n filename = Shellwords.escape(filename)\n #puts \"Writing to #{filename}\"\n tmpfile.write(data.join(\"\\n\"))\n tmpfile.close # need to flush, otherwise write is buffered\n headerstr=nil\n if formatting\n headerstr = \"-H\" unless headers\n # sometimes this can be slow, and it can fault on UTF-8 chars\n system(\"cat #{filename} | term-table.rb #{headerstr} | sponge #{filename}\")\n end\n if outputfile\n #puts \"comes here\"\n system(\"cp #{filename} #{outputfile}\")\n filename = outputfile\n end\n system \"wc -l #{filename}\" if $opt_debug\n \n #system \"$EDITOR #{filename}\"\n system \"vim -c ':set nowrap' #{filename}\"\n tmpfile.close\n tmpfile.unlink\nend",
"def table_csv_string(options = {})\n opt = {\n :klass => nil,\n :header_row => true\n }.merge!(options)\n str = ''\n \n return false if !opt[:klass]\n\n klass_name = opt[:klass].name\n tbl = ActiveSupport::Inflector.tableize(opt[:klass].name.to_s)\n\n cols = []\n sql = ''\n\n if klass_name == \"Person\" \n cols = %w(id last_name first_name middle_name login)\n else\n cols = opt[:klass].columns.map(&:name) \n end\n\n cols_str = cols.join(\", \")\n\n case opt[:klass].name\n when \"Person\"\n sql = \"SELECT #{cols_str} FROM people p INNER JOIN people_projs pp on p.id = pp.person_id WHERE pp.proj_id = #{self.id};\"\n when \"Ref\"\n cols_str = cols.collect{|c| \"r.#{c}\"}.join(\", \") # refs shared across projects, be more explicit for the join table\n sql = \"SELECT #{cols_str} FROM refs r INNER JOIN projs_refs pr on r.id = pr.ref_id WHERE pr.proj_id = #{self.id};\"\n when \"TaxonName\"\n sql = \"SELECT #{cols_str} FROM taxon_names WHERE #{self.sql_for_taxon_names}\"\n when \"Author\"\n sql = \"SELECT #{cols_str} FROM authors a WHERE a.ref_id IN (SELECT r.id FROM refs r INNER JOIN projs_refs pr on r.id = pr.ref_id WHERE pr.proj_id = #{self.id})\"\n when \"ChrState\"\n sql = \"SELECT #{cols_str} FROM chr_states cs WHERE cs.chr_id IN (SELECT chrs.id from chrs WHERE chrs.proj_id = #{self.id})\" \n # when \"Identifier\"\n # sql = \"SELECT #{cols_str} FROM identifiers si WHERE si.specimen_id IN (SELECT specimens.id from specimens WHERE specimens.proj_id = #{self.id})\"\n when \"SpecimenDetermination\"\n sql = \"SELECT #{cols_str} FROM specimen_determinations sd WHERE sd.specimen_id IN (SELECT specimens.id from specimens WHERE specimens.proj_id = #{self.id})\"\n\n else\n sql = \"SELECT #{cols_str} FROM #{tbl}\" \n end\n\n # add the project level restrictions if they exist\n sql << \" WHERE proj_id = #{self.id}\" if opt[:klass].columns.collect{|c| c.name}.include?(\"proj_id\")\n\n # build the str\n str << cols.join(\"\\t\") if opt[:header_row]# the header row\n str << \"\\n\"\n\n ActiveRecord::Base.connection.select_rows(sql).each do |row| \n # not filtering for tab characters here, likely should\n str << row.collect{|c| c == nil ? nil : c.gsub(/\\n|\\r\\n|\\r/, '\\n')}.join(\"\\t\") + \"\\n\"\n end\n str\n end",
"def csv=(klass); end",
"def parse_csv\n raise InvalidStateError, \"#{state.inspect} is not a valid Data state for method 'to_csv'\" unless state == :raw\n\n file_options = @options[:file_options]\n parse_options = @options[:parse_options]\n\n begin\n csv = CSVWrapper.parse(@content, parse_options)\n csv = csv.drop(1) if file_options[:has_headers] == true # drop the first row if it is a header\n rescue => e\n Logger.new(@options).print(@path, :parse, e)\n end\n\n @state = :parsed\n Data.new(@path, csv, @state, @options)\n end",
"def to_csv\n initialize_generator\n csv_report_generator.records = pull_join\n csv_report_generator.generate_report\n end",
"def make_history_csv\n FileUtils.mkdir_p(@@csv_location.dirname) unless Dir.exist?(csv_location.dirname)\n create_stub_csv_file unless File.exist?(@@csv_location)\n end",
"def create_csv &block\n file = create_tempfile \"csv\"\n CSV.open file.path, \"w\", &block\n file\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 make_testdata_reworked_csv_file\n create_column_headers_index_hash \n create_row_headers_index_hash \n clear_testdata_reworked_file\n CSV.open('testdata_reworked.csv', \"wb\") do |csv|\n CSV.foreach('testdata.csv', {headers: true}) do |row| \n row[0] = @column_hash.key(row[0].to_i)\n row[1] = @row_hash.key(row[1].to_i)\n csv << row\n end\n end\nend",
"def load\n csv = csv_data\n @data = TableFu.new(csv_data, @table_opts[:column_options] || {})\n if @table_opts[:faceting]\n @data.col_opts[:ignored] = [@table_opts[:faceting][:facet_by]]\n @facets = @data.faceted_by @table_opts[:faceting][:facet_by]\n end\n @data.delete_rows! @table_opts[:dead_rows] if @table_opts[:dead_rows]\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 create_stub_csv_file\n File.rm(@@csv_location) if File.exist?(@@csv_location)\n CSV.open(@@csv_location, 'w') do |row|\n row << @@csv_headers\n end\n end",
"def format_csv\n data.match(TIDE_REGEX)[1].gsub('<br>', \"\\n\").gsub(';', ',')\n end",
"def table_1\n @table1 = read_table(File.join(FILE_PATH, \"Lgr_prelim_FPKM.txt\"))\n #send_file(File.join(FILE_PATH, \"Lgr_prelim_FPKM.txt\"), :type => 'text/csv', :disposition => 'inline')\n end",
"def assign_csv_report\n unless @csv.nil?\n csv_header = ['Time', 'Req/s', 'Avg. resp. (ms)']\n @csvexport = Ralphttp::CsvExport.new(csv_header)\n end\n end",
"def donation_report_csv\n if date_format_check\n\n filter_by_account, account_id = account_filter\n\n csv_string = FasterCSV.generate do |csv|\n\n if filter_by_account\n filter_conditions = \"AND finance_transaction_receipt_records.fee_account_id #{account_id == nil ? 'IS' : '='} ?\"\n filter_values = [account_id]\n else\n filter_conditions = \"\"\n filter_values = []\n end\n\n category_id = FinanceTransactionCategory.find_by_name(\"Donation\").id\n @donations = FinanceDonation.all(:joins => {:transaction => :transaction_receipt},\n :order => 'finance_transactions.transaction_date desc',\n :conditions => [\"(finance_transactions.transaction_date BETWEEN ? AND ?) AND category_id = ?\n #{filter_conditions}\", @start_date, @end_date, category_id] + filter_values,\n :select => \"finance_donations.*, CONCAT(IFNULL(transaction_receipts.receipt_sequence, ''),\n transaction_receipts.receipt_number) AS receipt_no,\n finance_transactions.voucher_no\")\n\n csv << [t('donations')]\n csv << [t('start_date'), format_date(@start_date)]\n csv << [t('end_date'), format_date(@end_date)]\n csv << [t('fee_account_text'), \"#{@account_name}\"] if @accounts_enabled\n csv << \"\"\n cols = [t('donor'), ('amount'), t('receipt_or_voucher_no'), t('date_text')]\n csv << cols\n\n total = 0\n\n @donations.each do |d|\n csv << [d.donor, precision_label(d.amount.to_f), d.receipt_no.nil? ? d.voucher_no : d.receipt_no,\n format_date(d.transaction_date)]\n total += d.amount.to_f\n end\n\n csv << [t('net_income'), precision_label(total)]\n end\n\n filename = \"#{t('donations')}-#{format_date(@start_date)}-#{format_date(@end_date)}.csv\"\n send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present', :filename => filename)\n end\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 initialize\n @table = [] # Array contains Arrays of Strings\n @col = 0\n @row = 0\n @total_time = 0\n @total_records = 0\n # omitting separators for now\n end",
"def before_csv_render\n before_render\n end",
"def parse_csv(path)\n require 'csv'\n\n str = Nitro::Template.new.render(File.read(path))\n\n reader = CSV::Reader.create(str)\n header = reader.shift\n\n reader.each_with_index do |row, i|\n data = {}\n row.each_with_index do |cell, j|\n data[header[j].to_s.strip] = cell.to_s.strip\n end\n self[\"#{@name}_#{i+1}\"] = obj = instantiate(data)\n @objects << obj\n end\n end",
"def to_csv( separateur = ':' )\n DBC.require( separateur.size == 1, \"#{self}.to_csv: separateur invalide: #{separateur}\" )\n [numero.to_s,\n vie,\n attaque,\n defense,\n tete,\n tetedefense,\n torse,\n torsedefense,\n mains,\n mainsdefense,\n pantalons,\n pantalonsdefense,\n bottes,\n bottesdefense,\n arme,\n armeattaque,\n type.to_s,\n nom,\n puissance\n ].join(separateur)\n end",
"def csv_export_rawtable(table_name, data_array, options = {})\n column_definitions = []\n eval(\"#{table_name}.content_columns\").each do |column|\n column_definitions << [column.name, column.name]\n end\n csv_export(column_definitions, data_array, options)\n end",
"def from_csv path, opts={}\n daru_options, opts = from_csv_prepare_opts opts\n\n # Preprocess headers for detecting and correcting repetition in\n # case the :headers option is not specified.\n hsh =\n if opts[:headers]\n from_csv_hash_with_headers(path, opts)\n else\n from_csv_hash(path, opts)\n .tap { |hash| daru_options[:order] = hash.keys }\n end\n\n Daru::DataFrame.new(hsh,daru_options)\n end",
"def create_csv\n CSV.open('./data/slcsp.csv', 'wb') do |csv|\n csv << ['zipcode', 'rate']\n end\n build_csv\n end",
"def csv_to_table\n\t\tpath = File.join(Rails.root, \"db/seed_data\")\n\t\tDir.foreach(path) do |file|\n\t\t\tif file.include?(\".csv\")\n\t\t\t\theader_row = nil\n\t\t\t\tmodel = File.basename(file, File.extname(file)).camelcase.constantize\n\t\t\t\tmodel.delete_all\n\t\t\t\tCSV.foreach(File.join(path,file)) do |row|\n\t\t\t\t\tif header_row.nil?\n\t\t\t\t\t\theader_row = row\n\t\t\t\t\t\tnext\n\t\t\t\t\tend\n\t\t\t\t\tattributes = {}\n\t\t\t\t\trow.each_index do |i|\n\t\t\t\t\t\tattributes[header_row[i].to_sym] = row[i]\n\t\t\t\t\tend\n\t\t\t\t\tmodel.create!(attributes)\n\t\t\t\tend\n\t\t\tend\n\n\t\tend\n\tend",
"def csv_to_table\n\t\tpath = File.join(Rails.root, \"db/seed_data\")\n\t\tDir.foreach(path) do |file|\n\t\t\tif file.include?(\".csv\")\n\t\t\t\theader_row = nil\n\t\t\t\tmodel = File.basename(file, File.extname(file)).camelcase.constantize\n\t\t\t\tmodel.delete_all\n\t\t\t\tCSV.foreach(File.join(path,file)) do |row|\n\t\t\t\t\tif header_row.nil?\n\t\t\t\t\t\theader_row = row\n\t\t\t\t\t\tnext\n\t\t\t\t\tend\n\t\t\t\t\tattributes = {}\n\t\t\t\t\trow.each_index do |i|\n\t\t\t\t\t\tattributes[header_row[i].to_sym] = row[i]\n\t\t\t\t\tend\n\t\t\t\t\tmodel.create!(attributes)\n\t\t\t\tend\n\t\t\tend\n\n\t\tend\n\tend",
"def from_csv path, opts={}\n daru_options, opts = from_csv_prepare_opts opts\n # Preprocess headers for detecting and correcting repetition in\n # case the :headers option is not specified.\n hsh =\n if opts[:headers]\n from_csv_hash_with_headers(path, opts)\n else\n from_csv_hash(path, opts)\n .tap { |hash| daru_options[:order] = hash.keys }\n end\n Daru::DataFrame.new(hsh,daru_options)\n end",
"def climate_dump\r\n\ttableMetadata = LsrsClimate.where(:WarehouseName=>params[:table]).first\r\n\toutputCsvFile = File.open(\"/development/data/climate/#{params[:table]}.txt\", 'w')\r\n\toutputCsvFile.puts '--- #YAML'\r\n\toutputCsvFile.puts 'Title: \"' + tableMetadata.Title_en + '\"'\r\n\toutputCsvFile.puts 'Geography: \"Polygons\"'\r\n\toutputCsvFile.puts 'Framework: \"' + tableMetadata.PolygonTable + '\"'\r\n\toutputCsvFile.puts 'Timeframe: \"???\"'\r\n\toutputCsvFile.puts 'Origin: \"Observations???\"'\r\n\toutputCsvFile.puts 'Description: \"???\"'\r\n\toutputCsvFile.puts '--- #TSV'\r\n\toutputCsvFile.puts \"id\tlong\tlat\telev\ttmax01\ttmax02\ttmax03\ttmax04\ttmax05\ttmax06\ttmax07\ttmax08\ttmax09\ttmax10\ttmax11\ttmax12\ttmin01\ttmin02\ttmin03\ttmin04\ttmin05\ttmin06\ttmin07\ttmin08\ttmin09\ttmin10\ttmin11\ttmin12\tptot01\tptot02\tptot03\tptot04\tptot05\tptot06\tptot07\tptot08\tptot09\tptot10\tptot11\tptot12\"\r\n\trecords = eval(params[:table].capitalize).all\r\n\tfor r in records do\r\n\t\toutputCsvFile.puts \"#{r.id}\t#{r.long}\tlat\telev\ttmax01\ttmax02\ttmax03\ttmax04\ttmax05\ttmax06\ttmax07\ttmax08\ttmax09\ttmax10\ttmax11\ttmax12\ttmin01\ttmin02\ttmin03\ttmin04\ttmin05\ttmin06\ttmin07\ttmin08\ttmin09\ttmin10\ttmin11\ttmin12\tptot01\tptot02\tptot03\tptot04\tptot05\tptot06\tptot07\tptot08\tptot09\tptot10\tptot11\tptot12\"\r\n\tend\r\n\toutputCsvFile.close\r\n\t\t\r\n\t\r\nend",
"def generate(with_headers: true)\n @file = Tempfile.new([row_model_class.name, \".csv\"])\n CSV.open(file.path, \"wb\") do |csv|\n @csv = csv\n row_model_class.setup(csv, context, with_headers: with_headers)\n yield Proxy.new(self)\n end\n ensure\n @csv = nil\n end",
"def initialize(csv_in_filename, era_year_handle, rmid_from_era_year_handles_string)\n @in_file = csv_in_filename\n verify_in_file\n\n @db_conn = PG::Connection.connect(DB_CONNECT_INFO)\t# Connect to the DB\n @era_year_handle = era_year_handle\n verify_era_year_handle\n\n @rmid_from_era_year_handles_string = rmid_from_era_year_handles_string\n if @rmid_from_era_year_handles_string == 'any'\n @rmid_from_era_year_handles = nil\n @rmid_from_era_year_handles_regex = nil\n else\n @rmid_from_era_year_handles = rmid_from_era_year_handles_string.split(',')\n @rmid_from_era_year_handles_regex = \"^(#{@rmid_from_era_year_handles.join('|')})$\"\n end\n verify_rmid_from_era_year_handles\n\n @csv_out_headers = nil\n @csv_out_data = nil\n @handles_by_prefix = {}\t\t# Cache for collection-handles\n convert\n @db_conn.close if @db_conn\n end",
"def load_csv(csv_file_or_object, table_name, log_name = nil)\n log_name ||= \"load_csv '#{csv_file_or_object.kind_of?(CSV::Table) ? 'CSV Object' : csv_file_or_object }', 'table_name'\"\n csv_object = case csv_file_or_object\n when String then Slacker.get_csv(csv_file_or_object)\n when CSV::Table then csv_file_or_object\n when Array then Slacker.hash_array_to_csv(csv_file_or_object)\n end\n\n Slacker.load_csv(example, csv_object, table_name, log_name)\n end",
"def render_as_csv(issue_list)\n # puts \"rendering issues as CVS:\"\n # pp issue_list\n ::CSV.generate do |csv|\n csv << CSV_HEADER\n issue_list.each do |issue|\n row = []\n CSV_HEADER.each do |column|\n method = column.downcase.underscore.to_sym\n value = if CSV_MAP[column]\n CSV_MAP[column][client, issue]\n else\n begin\n issue.to_h[method]\n rescue StandardError\n nil\n end\n end\n value = value.strip if value.is_a?(String)\n row << value\n end\n csv << row\n bar&.advance\n end\n bar.finish\n end\n end",
"def prepare_data\n data = CSV.read('input.csv', { col_sep: SEPARATOR })\n\n CSV.open('output.csv','wb') do |csv|\n data.each do |row|\n csv << prepare_row(row)\n end\n end\n\n rescue Errno::ENOENT\n puts 'No valid input.csv file present'\n end",
"def csv_parsed\n transform_to_hash(@csv_array, @header)\n end",
"def generate_csv\n csv_string = CSV.generate do |csv|\n csv << [\"Sl no.\",\"Scheme\",\"IP no.\", \"Patient name\", \"UHID no.\", \"Reg no.\", \"DOA\", \"DOS\", \"DOD\", \"Plan of treatment\", \"Approved Amount\",\"Claim Amount\", \"TDS\",\"Net Amount\",\"Hospital charges\",\"Medicine charges\",\"Implant charges\"]\n sl_no = 1\n @claims.each do |claim|\n csv <<[sl_no,\"#{claim.scheme rescue \"\"}\",\"#{claim.ip_no rescue \"\"}\",\"#{claim.patient_name rescue \"\"}\",\"#{claim.uhid_no rescue \"\"}\",\"#{claim.reg_no rescue \"\"}\",\"#{claim.date_of_admission}\",\"#{claim.date_of_surgery}\",\"#{claim.date_of_discharge}\",\"#{claim.plan_of_treatment rescue \"\"}\",(claim.approved_amount rescue 0.0),(claim.claim_amount rescue 0.0),(claim.tds_amount rescue 0.0),(claim.net_amount rescue 0.0),(claim.hospital_charge rescue 0.0),(claim.medicine_charge rescue 0.0),(claim.implant_charge rescue 0.0)]\n sl_no +=1\n end\n end\n csv_string\n end",
"def initialize(path, normalizer = KEY_NORMALIZER)\n @path = Pathname.new(path)\n\n @table = CSV.table(@path.to_s, {\n converters: [YEAR_NORMALIZER, :all],\n header_converters: [normalizer]\n })\n\n @headers = @table.headers\n rescue InvalidKeyError\n raise BlankCSVHeaderError.new(path)\n end",
"def touch_csv(csv_file_or_object, fields, field_generators = {})\n Slacker.touch_csv(csv_file_or_object, fields, field_generators)\n end",
"def build_composite_data_table(data_dir)\n file_paths = Dir.glob(File.join(data_dir, \"CFE_[A-Z][0-9][0-9]_VX.csv\"))\n \n # pp file_paths\n \n # sort file paths in ascending order of year/month - from oldest to most recent\n file_paths = file_paths.sort_by do |path|\n file_name = File.basename(path)\n match = file_name.match(/CFE_([A-Z])([0-9][0-9])_VX.csv/)\n month_code = match[1]\n year = match[2]\n \"#{year}/#{month_code}\"\n end\n \n all_lines = file_paths.map.with_index do |file_path, i|\n lines = File.readlines(file_path)\n if i == 0\n lines\n else\n lines.drop_while {|line| !(line =~ /^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}/) }\n end\n end\n \n all_lines = all_lines.flatten.map(&:strip).reject{|line| line.empty? }.join(\"\\n\")\n\n puts 'Saving vix_futures.csv'\n file_name = File.join(DataDir, \"vix_futures.csv\")\n File.write(file_name, all_lines)\nend",
"def process_csv_file(filename, no_of_unique,delimiter)\n @arr_unique = Array.new{hash.new}\n @arr_details = Array.new(@no_of_columns){{\"int\" => 0, \"float\" => 0, \"date\" => 0, \"datetime\" => 0, \"string\" => 0, \"max_value\" => 0, \"min_value\" => 0}}\n total_chunks = SmarterCSV.process(filename, {:col_sep => delimiter, :chunk_size => 200, :remove_empty_values => false, :remove_zero_values => false}) do |chunk|\n for i in 0..@headers.length-1\n arr = chunk.map{|x| x[@headers[i].to_sym]}\n if(@arr_unique[i].to_a.empty?)\n @arr_unique[i] = arr.uniq\n elsif(@arr_unique[i].size < no_of_unique.to_i+2)\n @arr_unique[i] |= arr.uniq\n elsif (arr.uniq.include?(nil) && !@arr_unique[i].include?(nil))\n @arr_unique[i].push(nil)\n elsif (arr.uniq.include?(\"NULL\") && !@arr_unique[i].include?(\"NULL\"))\n @arr_unique[i].push(\"NULL\")\n elsif (arr.uniq.include?(\"\\N\") && !@arr_unique[i].include?(\"\\N\"))\n @arr_unique[i].push(\"\\N\") \n elsif (arr.uniq.include?(\"\") && !@arr_unique[i].include?(\"\"))\n @arr_unique[i].push(\"\")\n elsif (arr.uniq.include?(\" \") && !@arr_unique[i].include?(\" \"))\n @arr_unique[i].push(\" \")\n end \n arr.each do |field|\n field_type = get_datatype(field)\n count = @arr_details[i][field_type]\n @arr_details[i][field_type] = count+1\n if(field != nil)\n begin\n if(@header_datatype[i] == \"int\" || @header_datatype[i] == \"float\") \n if(@arr_details[i][\"max_value\"] < field)\n @arr_details[i][\"max_value\"] = field\n end\n if(@arr_details[i][\"min_value\"] > field || @arr_details[i][\"min_value\"] == 0)\n @arr_details[i][\"min_value\"] = field\n end\n else\n if(@arr_details[i][\"max_value\"] < field.to_s.length)\n @arr_details[i][\"max_value\"] = field.to_s.length\n end\n if(@arr_details[i][\"min_value\"] > field.to_s.length || @arr_details[i][\"min_value\"] == 0)\n @arr_details[i][\"min_value\"] = field.to_s.length\n end\n end\n rescue Exception => e\n end\n end\n end\n end\n end\n end",
"def convert_csv(path, table_name)\n \n # csv file has a header row\n header_row = true\n\n # delimiter for csv file\n delimiter = ','\n\n # variable used to skip header row\n skip_row = true\n\n\n CSV.open(path, 'r', delimiter ) do |row|\n\n row.each_with_index do |col,index|\n if col==nil then \n row[index]='NULL'\n else\n \n col.gsub!(\"'\",\"`\")\n row[index] = \"'#{ col }'\"\n end\n end\n\n # Are we reading the header row of the csv file?\n if header_row\n row.each_with_index do |col,index|\n row[index] = \"\\\"#{ col.gsub(\"'\",'').gsub(/\\s+/,'') }\\\"\"\n end\n header_row = false\n print \"INSERT INTO #{table_name} (#{row.join delimiter }) VALUES\"\n next\n end\n\n # Only skip the first (header) row\n if skip_row == true\n # dont skip further rows\n skip_row = false\n else\n # Print end of line insert delimeter\n puts delimiter\n end\n \n # Print to stdout\n print \"(#{row.join delimiter})\"\n \n end\nend",
"def initialize(csv, importer)\n @source_csv = CSV.read(csv, headers: true)\n @is_for_bulkrax = importer == 'bulkrax'\n @fileset_model_or_type = @is_for_bulkrax ? 'FileSet' : 'fileset'\n directory = File.dirname(csv)\n extension = File.extname(csv)\n filename = File.basename(csv, extension)\n @processed_csv = File.join(directory, filename + \"-processed.csv\")\n @merged_headers = exclusion_guard(additional_headers + @source_csv.headers)\n @tree = {}\n end",
"def period_csv\n CSV.generate do |csv|\n report_details.each { |a| csv.add_row(a) }\n csv.add_row [] # Blank row\n time_period_table.each { |a| csv.add_row(a) }\n end\n end",
"def render(result)\n headers = [:msgid,:file,:line,:short_desc,:long_desc,:details]\n data = CSV.generate(\"\", :row_sep => \"\\r\\n\", :headers => headers, :write_headers => true) do |csv|\n result.each do |row|\n csv << row.values_at(*headers)\n end\n end\n @io << data\n end",
"def create\n @csv = Csv.new(params[:csv])\n\n send_data @csv.csv_from_xml, filename: \"import.csv\", type: 'text/csv', disposition: \"attachment\" and return\n #send_data @csv.csv_from_html, filename: \"import.csv\", type: 'text/csv', disposition: \"attachment\" and return\n\n\n\n #respond_to do |format|\n #if @csv.save\n # format.csv { send_data @csv_from_html, filename: \"import.csv\", type: 'text/csv', disposition: \"attachment\" }\n # format.html { redirect_to root_url, notice: 'CSV was successfully created.' }\n #format.json { render json: @csv, status: :created, location: @csv }\n #else\n # format.html { render action: \"new\" }\n # format.json { render json: @csv.errors, status: :unprocessable_entity }\n #end\n #end\n end",
"def render_csv\n report = report_for_rendering\n filename = filename_timestamp(report.title)\n disable_client_cache\n send_data(report.to_csv, :filename => \"#{filename}.csv\")\n end",
"def direct_import_from_csv(dataset, opts = {:to => nil, :delimiter => nil, :header => nil})\n delimiter = opts[:delimiter] || \",\"\n header = \"HEADER\" if opts[:header] == true\n table = opts[:to].table_name\n raise TypeError if dataset.class != String\n ActiveRecord::Base.connection.execute(\"COPY #{table} FROM '#{dataset}' DELIMITER \\'#{delimiter}\\' CSV #{header}\")\n end",
"def render_csv(data,headers,filename)\n csv_writer = ::CSV::Writer.generate(output = '')\n csv_writer << headers.split(',')\n data.each {|row| csv_writer << row}\n\t\tsend_data(output, :type => \"text/plain\", :filename => \"#{filename}\")\n end",
"def render_csv(data,headers,filename)\n csv_writer = ::CSV::Writer.generate(output = '')\n csv_writer << headers.split(',')\n data.each {|row| csv_writer << row}\n\t\tsend_data(output, :type => \"text/plain\", :filename => \"#{filename}\")\n end",
"def shift\n #########################################################################\n ### This method is purposefully kept a bit long as simple conditional ###\n ### checks are faster than numerous (expensive) method calls. ###\n #########################################################################\n\n # handle headers not based on document content\n if header_row? and @return_headers and\n [Array, String].include? @use_headers.class\n if @unconverted_fields\n return add_unconverted_fields(parse_headers, Array.new)\n else\n return parse_headers\n end\n end\n\n #\n # it can take multiple calls to <tt>@io.gets()</tt> to get a full line,\n # because of \\r and/or \\n characters embedded in quoted fields\n #\n in_extended_col = false\n csv = Array.new\n\n loop do\n # add another read to the line\n unless parse = @io.gets(@row_sep)\n return nil\n end\n\n if in_extended_col\n @line.concat(parse)\n else\n @line = parse.clone\n end\n\n begin\n parse.sub!(@parsers[:line_end], \"\")\n rescue ArgumentError\n unless parse.valid_encoding?\n message = \"Invalid byte sequence in #{parse.encoding}\"\n raise MalformedCSVError.new(message, lineno + 1)\n end\n raise\n end\n\n if csv.empty?\n #\n # I believe a blank line should be an <tt>Array.new</tt>, not Ruby 1.8\n # HBCSV's <tt>[nil]</tt>\n #\n if parse.empty?\n @lineno += 1\n if @skip_blanks\n next\n elsif @unconverted_fields\n return add_unconverted_fields(Array.new, Array.new)\n elsif @use_headers\n return self.class::Row.new(@headers, Array.new)\n else\n return Array.new\n end\n end\n end\n\n next if @skip_lines and @skip_lines.match parse\n\n parts = parse.split(@col_sep_split_separator, -1)\n if parts.empty?\n if in_extended_col\n csv[-1] << @col_sep # will be replaced with a @row_sep after the parts.each loop\n else\n csv << nil\n end\n end\n\n # This loop is the hot path of csv parsing. Some things may be non-dry\n # for a reason. Make sure to benchmark when refactoring.\n parts.each do |part|\n if in_extended_col\n # If we are continuing a previous column\n if part.end_with?(@quote_char) && part.count(@quote_char) % 2 != 0\n # extended column ends\n csv.last << part[0..-2]\n if csv.last.match?(@parsers[:stray_quote])\n raise MalformedCSVError.new(\"Missing or stray quote\",\n lineno + 1)\n end\n csv.last.gsub!(@double_quote_char, @quote_char)\n in_extended_col = false\n else\n csv.last << part << @col_sep\n end\n elsif part.start_with?(@quote_char)\n # If we are starting a new quoted column\n if part.count(@quote_char) % 2 != 0\n # start an extended column\n csv << (part[1..-1] << @col_sep)\n in_extended_col = true\n elsif part.end_with?(@quote_char)\n # regular quoted column\n csv << part[1..-2]\n if csv.last.match?(@parsers[:stray_quote])\n raise MalformedCSVError.new(\"Missing or stray quote\",\n lineno + 1)\n end\n csv.last.gsub!(@double_quote_char, @quote_char)\n elsif @liberal_parsing\n csv << part\n else\n raise MalformedCSVError.new(\"Missing or stray quote\",\n lineno + 1)\n end\n elsif part.match?(@parsers[:quote_or_nl])\n # Unquoted field with bad characters.\n if part.match?(@parsers[:nl_or_lf])\n message = \"Unquoted fields do not allow \\\\r or \\\\n\"\n raise MalformedCSVError.new(message, lineno + 1)\n else\n if @liberal_parsing\n csv << part\n else\n raise MalformedCSVError.new(\"Illegal quoting\", lineno + 1)\n end\n end\n else\n # Regular ole unquoted field.\n csv << (part.empty? ? nil : part)\n end\n end\n\n # Replace tacked on @col_sep with @row_sep if we are still in an extended\n # column.\n csv[-1][-1] = @row_sep if in_extended_col\n\n if in_extended_col\n # if we're at eof?(), a quoted field wasn't closed...\n if @io.eof?\n raise MalformedCSVError.new(\"Unclosed quoted field\",\n lineno + 1)\n elsif @field_size_limit and csv.last.size >= @field_size_limit\n raise MalformedCSVError.new(\"Field size exceeded\",\n lineno + 1)\n end\n # otherwise, we need to loop and pull some more data to complete the row\n else\n @lineno += 1\n\n # save fields unconverted fields, if needed...\n unconverted = csv.dup if @unconverted_fields\n\n if @use_headers\n # parse out header rows and handle HBCSV::Row conversions...\n csv = parse_headers(csv)\n else\n # convert fields, if needed...\n csv = convert_fields(csv)\n end\n\n # inject unconverted fields and accessor, if requested...\n if @unconverted_fields and not csv.respond_to? :unconverted_fields\n add_unconverted_fields(csv, unconverted)\n end\n\n # return the results\n break csv\n end\n end\n end",
"def csv_download\n filename = sprintf(\"%s-%s.csv\",\n model_name,\n Time.now.strftime(\"%Y%m%d-%H%M%S\"))\n file = Tempfile.new(filename, Settings.edgarj.csv_dir)\n csv_visitor = EdgarjHelper::CsvVisitor.new(view_context)\n file.write CSV.generate_line(model.columns.map{|c| c.name})\n for rec in user_scoped.where(page_info.record.conditions).\n order(\n page_info.order_by.blank? ?\n nil :\n page_info.order_by + ' ' + page_info.dir) do\n array = []\n for col in model.columns do\n array << csv_visitor.visit_column(rec, col)\n end\n file.write CSV.generate_line(array)\n end\n file.close \n File.chmod(Settings.edgarj.csv_permission, file.path)\n send_file(file.path, {\n type: 'text/csv',\n filename: filename})\n #file.close(true)\n end",
"def create_csv()\n hashes = Transaction.all_as_hashes\n CSV.generate do |csv|\n # Adds the keys as headings on the first line\n csv << hashes.first.keys\n # Iterates through the transactions and populates CSV\n hashes.each do |hash|\n csv << hash.values\n end\n end\n end",
"def csv_data\n @csv_data ||= compute_csv_data\n end",
"def genCsvSpeed()\n csv = [] ;\n to_a.each{|analyzer|\n csv.push(analyzer.genCsvRowSpeed()) ;\n }\n return csv ;\n end",
"def prepare_data \n table=Array.new\n flag=true\n flag2=false\n count=0 \n @reader.pages.each_with_index do |page,i| \n break if i >= @page \n #(?!([a-zA-Z\\-0-9]+))\n #text = page.text.gsub(/\\n\\s{1}+[0-9]{1}+,[0-9]\\s{1}+/,' ')\n rows=page.text.split(/\\n/) \n rows.each_with_index do|row,ind|\n temp=row.split(/\\s{2}+/)\n \n if temp.length == 1 && temp[0].include?('-')\n flag2=true\n rows[ind+1].insert(0, temp[0]) if !rows[ind+1].nil?\n flag2=false;\n end\n if temp.length >9\n temp.delete_at(1) \n end \n if temp.length ==9\n table << temp unless (temp.empty? || row.include?(\"Portfolio Name\"))\n \n end\n if flag && row.include?(\"Portfolio Name\")\n non_standardized_header row\n flag=false\n end\n end\t \n end \n return table\n end",
"def readTSVline(l, sep=nil)\n\n sep = detectSeperator if sep.nil?\n\n #row = CSV.parse_line(l, :col_sep => seperator).collect{|x|\n row = l.split(sep).collect{|x|\n if ! x.nil?\n x.strip;\n end\n }\n\n ### Pick specify elements of that table\n #name, id, lastVisitDate, lastAttendedDate, meetupsAttended, profileURL, lastDonationAmount, lastDonationDate = readTSVline(seperator)\n [0, 3, 6, 7, 12, 18, 19, 21].map {|i| row[i]}\nend",
"def initialize(table, path = nil)\n @headers = table.headers\n @path = Pathname(path) if path\n @table = table\n\n # Delete the header row for the internal representation. This will be (re-)created when saved.\n @table.delete(0)\n\n raise(BlankCSVHeaderError, path || '<no path>') if @headers.any?(&:nil?)\n end",
"def to_csv_by_template(created_plans, sep = ',')\n template_names = lambda do |plns|\n unique = Set.new\n plns.each do |created_plan|\n created_plan.by_template&.each do |name_count|\n unique.add(name_count.fetch('name'))\n end\n end\n unique.to_a\n end.call(created_plans)\n\n data = created_plans.map do |created_plan|\n tuple = { Date: created_plan.date.strftime('%b %Y') }\n template_names.each_with_object(tuple) do |name, acc|\n acc[name] = 0\n end\n created_plan.by_template&.each do |name_count|\n tuple[name_count.fetch('name')] = name_count.fetch('count')\n end\n tuple[:Count] = created_plan.count\n tuple\n end\n Csvable.from_array_of_hashes(data, false, sep)\n end",
"def translate_csv csv, options\n fields_to_convert = options[:convert]\n fields_to_convert = [fields_to_convert].compact unless fields_to_convert.is_a?(Array)\n\n fields_to_translate = options[:translate]\n fields_to_translate = [fields_to_translate].compact unless fields_to_translate.is_a?(Array)\n to = options[:to] || 'en'\n from_country_code = options[:from]\n from = fields_to_translate.empty? ? nil : language(country(from_country_code))\n translator = self.new(from, to)\n\n items = Morph.from_csv csv, 'Item'\n keys = items.first.class.morph_attributes.select {|x| !x.to_s[/^t_/] }\n\n items.each do |item|\n keys.each do |key|\n translator.translate_value(item, key) if fields_to_translate.include?(key) \n translator.convert_value(item, key) if fields_to_convert.include?(key)\n end\n end\n\n keys = keys.map do |key|\n if fields_to_translate.include?(key) || fields_to_convert.include?(key)\n [\"t_#{key}\", key]\n else\n key\n end\n end.flatten\n\n output = FasterCSV.generate do |csv|\n csv << keys.collect(&:to_s)\n items.each do |item|\n csv << keys.collect { |key| item.respond_to?(key) ? item.send(key) : nil }\n end\n end\n end",
"def generate_csv\n\n fields = @resource.typus_fields_for(:csv)\n\n require 'csv'\n if CSV.const_defined?(:Reader)\n # Old CSV version so we enable faster CSV.\n begin\n require 'fastercsv'\n rescue Exception => error\n raise error.message\n end\n csv = FasterCSV\n else\n csv = CSV\n end\n\n filename = Rails.root.join(\"tmp\", \"export-#{@resource.to_resource}-#{Time.now.utc.to_s(:number)}.csv\")\n\n options = { :conditions => @conditions, :batch_size => 1000 }\n\n csv.open(filename, 'w', :col_sep => ';') do |csv|\n csv << fields.keys\n @resource.find_in_batches(options) do |records|\n records.each do |record|\n csv << fields.map do |key, value|\n case value\n when :transversal\n a, b = key.split(\".\")\n record.send(a).send(b)\n when :belongs_to\n record.send(key).to_label\n else\n record.send(key)\n end\n end\n end\n end\n end\n\n send_file filename\n\n end",
"def csv_string\n CSV.generate do |csv|\n header.write_header csv\n records.each {|r| r.write_record csv}\n end\n end",
"def index\n @datatable = InventoryMovementsDatatable.new\n respond_to do |format|\n format.html\n format.csv do\n day_before_start_date = (@imr_start_date <= @initial_date) ? DateTime.now.end_of_day : (@imr_start_date.to_datetime - 1.day).end_of_day\n ekanek = Organisation::EKANEK_ORG\n a3m = Organisation::A3M_ORG\n params[:organisation_id] = params[:organisation_id].to_i\n\n # \"Brand Name\", \"Brand Owner\", \"Item Name\", \"Item Type\", \"MRP\", \"GWP/Surprise\"\n brand_name_hash, brand_owner_hash, name_hash, item_type_hash, mrp_hash, gwp_surprise_hash = Sku.create_item_detail_hashes\n\n # Opening Stock\n organisation_ids = params[:organisation_id] == 0 ? [ekanek.id, a3m.id] : params[:organisation_id]\n opening_stock_quantity_hash, opening_stock_value_hash = InventoryItem.create_opening_stock_hashes(day_before_start_date, organisation_ids)\n\n organisation_ids = (params[:organisation_id].in? [0, ekanek.id]) ? [ekanek.id, a3m.id] : params[:organisation_id]\n # Total Purchase = 1. Putaway GRN Items\n sku_purchased_quantity_hash, sku_purchased_value_hash = InventoryItem.create_purchased_hashes(@imr_start_date, @imr_end_date, organisation_ids)\n # Bad purchase = 1. Putaway GRN Items Bad\n sku_bad_qty_purchased_hash, sku_bad_value_purchased_hash = InventoryItem.create_bad_purchased_hashes(@imr_start_date, @imr_end_date, organisation_ids)\n\n organisation_id = params[:organisation_id] == 0 ? a3m.id : params[:organisation_id]\n # 2. Putaway Returned by Customers\n sku_quantity_returned_by_customers_hash, sku_value_returned_by_customers_hash = InventoryItem.create_returned_by_customer_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # 2. Putaway Returned by Customers Bad\n sku_qty_bad_stock_returned_by_customer_hash, sku_value_bad_stock_returned_by_customer_hash = InventoryItem.create_bad_returned_by_customer_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # Sold\n sku_quantity_sold_hash, sku_value_sold_hash = InventoryItem.create_sold_hashes(@imr_start_date, @imr_end_date, organisation_id)\n\n # Gatepasses\n organisation_id = params[:organisation_id] == 0 ? ekanek.id : params[:organisation_id]\n sku_quantity_returned_to_vendor_hash, sku_value_returned_to_vendor_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'rtv', organisation_id)\n sku_self_consumed_quantity_hash, sku_self_consumed_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'self_consumption', organisation_id)\n sku_quantity_sent_for_brand_collabs_hash, sku_value_sent_for_brand_collabs_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'brand_collabs', organisation_id)\n sku_quantity_sent_to_agency_hash, sku_value_sent_to_agency_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'agency', organisation_id)\n sku_gift_quantity_hash, sku_gift_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'gift', organisation_id)\n sku_quantity_liquidated_hash, sku_value_liquidated_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'liquidation', organisation_id)\n sku_stock_transfer_quantity_hash, sku_stock_transfer_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'stock_transfer', organisation_id)\n # Bad Gatepasses\n sku_bad_qty_gatepass_hash, sku_bad_value_gatepass_hash = InventoryItem.create_bad_gatepass_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # Blocked Qty\n sku_blocked_qty_hash = Inventory.create_sku_blocked_qty_hash\n\n require 'csv'\n filename = \n case params[:organisation_id].to_i\n when 0\n 'Consolidated-IMR.csv'\n when ekanek.id\n 'EkAnek-IMR.csv'\n when a3m.id\n 'A3M-IMR.csv'\n end\n\n CSV.open(\"#{filename}\", \"wb\") do |response_csv|\n response_csv << [\"SKU ID\", \"Brand Name\", \"Brand Owner\", \"Item Name\", \"Item Type\", \"MRP\", \"GWP/Surprise\", \"Opening Stock Qty\", \"Opening Stock Value\", \"Qty Purchased\", \"Value Purchased\",\n \"Qty Returned By Customer\", \"Value Returned By Customer\", \"Total Putaway Qty\", \"Total Putaway Value\",\n \"Qty Sold\", \"Value Sold\", \"Qty Returned to Vendor\", \"Value Returned to Vendor\", \"Qty Used for Self Consumption\",\n \"Value Used for Self Consumption\", \"Qty used for Brand Collabs\", \"Value used for Brand Collabs\", \"Qty sent to Agency\",\n \"Value sent to Agency\", \"Qty used as Gift\", \"Value used as Gift\", \"Qty Liquidated\", \"Value Liquidated\",\n \"Stock Transfer Qty\", \"Stock Transfer Value\", \"Gatepass Bad Qty\", \"Gatepass Bad Value\", \"Total Gatepass\", \"Total Gatepass Value\", \"Stock Adjustment\",\n \"Closing Stock Qty\", \"Closing Stock Value\" , \"Good Qty\", \"Good Qty Value\", \"Bad Qty\", \"Bad Qty Value\", \"Qty Blocked\"]\n\n skus = InventoryItem.pluck(:sku_id).uniq\n skus.each do |sku_id|\n report = []\n report << sku_id\n sku = Sku.find sku_id\n\n report << brand_name_hash[sku_id]\n report << brand_owner_hash[sku_id]\n report << name_hash[sku_id]\n report << item_type_hash[sku_id]\n report << mrp_hash[sku_id]\n report << gwp_surprise_hash[sku_id]\n\n opening_stock_quantity = (@imr_start_date <= @initial_date) ? 0 : opening_stock_quantity_hash[sku_id].to_i\n opening_stock_value = (@imr_start_date <= @initial_date) ? 0 : opening_stock_value_hash[sku_id].to_f\n report << opening_stock_quantity\n report << opening_stock_value\n report << sku_purchased_quantity_hash[sku_id].to_i\n report << sku_purchased_value_hash[sku_id].to_f\n report << sku_quantity_returned_by_customers_hash[sku_id].to_i\n report << sku_value_returned_by_customers_hash[sku_id].to_f\n total_putaway_qty = sku_purchased_quantity_hash[sku_id].to_i + sku_quantity_returned_by_customers_hash[sku_id].to_i\n total_putaway_value = sku_purchased_value_hash[sku_id].to_f + sku_value_returned_by_customers_hash[sku_id].to_f\n report << total_putaway_qty\n report << total_putaway_value\n report << sku_quantity_sold_hash[sku_id].to_i\n report << sku_value_sold_hash[sku_id].to_f\n report << sku_quantity_returned_to_vendor_hash[sku_id].to_i\n report << sku_value_returned_to_vendor_hash[sku_id].to_f\n report << sku_self_consumed_quantity_hash[sku_id].to_i\n report << sku_self_consumed_value_hash[sku_id].to_f\n report << sku_quantity_sent_for_brand_collabs_hash[sku_id].to_i\n report << sku_value_sent_for_brand_collabs_hash[sku_id].to_f\n report << sku_quantity_sent_to_agency_hash[sku_id].to_i\n report << sku_value_sent_to_agency_hash[sku_id].to_f\n report << sku_gift_quantity_hash[sku_id].to_i\n report << sku_gift_value_hash[sku_id].to_f\n report << sku_quantity_liquidated_hash[sku_id].to_i\n report << sku_value_liquidated_hash[sku_id].to_f\n report << sku_stock_transfer_quantity_hash[sku_id].to_i\n report << sku_stock_transfer_value_hash[sku_id].to_f\n report << sku_bad_qty_gatepass_hash[sku_id].to_i\n report << sku_bad_value_gatepass_hash[sku_id].to_f\n total_gp_qty = sku_quantity_returned_to_vendor_hash[sku_id].to_i +\n sku_self_consumed_quantity_hash[sku_id].to_i +\n sku_quantity_sent_for_brand_collabs_hash[sku_id].to_i +\n sku_quantity_sent_to_agency_hash[sku_id].to_i +\n sku_gift_quantity_hash[sku_id].to_i +\n sku_quantity_liquidated_hash[sku_id].to_i +\n sku_stock_transfer_quantity_hash[sku_id].to_i +\n sku_bad_qty_gatepass_hash[sku_id].to_i\n total_gp_value = sku_value_returned_to_vendor_hash[sku_id].to_f +\n sku_self_consumed_value_hash[sku_id].to_f +\n sku_value_sent_for_brand_collabs_hash[sku_id].to_f +\n sku_value_sent_to_agency_hash[sku_id].to_f +\n sku_gift_value_hash[sku_id].to_f +\n sku_value_liquidated_hash[sku_id].to_f +\n sku_stock_transfer_value_hash[sku_id].to_f +\n sku_bad_value_gatepass_hash[sku_id].to_f\n report << total_gp_qty\n report << total_gp_value\n report << 0 # stock adjustment 0 for now\n\n inwarded_quantity = total_putaway_qty\n inwarded_value = total_putaway_value\n\n outwarded_quantity = sku_quantity_sold_hash[sku_id].to_i + total_gp_qty\n outwarded_value = sku_value_sold_hash[sku_id].to_f + total_gp_value\n\n closing_stock_quantity = opening_stock_quantity + inwarded_quantity - outwarded_quantity\n closing_stock_value = opening_stock_value + inwarded_value - outwarded_value\n\n # total_bad = putaway_grn_bad + putaway_return_bad - gatepass_bad\n bad_qty = sku_bad_qty_purchased_hash[sku_id].to_i +\n sku_qty_bad_stock_returned_by_customer_hash[sku_id].to_i -\n sku_bad_qty_gatepass_hash[sku_id].to_i\n bad_stock_value = sku_bad_value_purchased_hash[sku_id].to_f +\n sku_value_bad_stock_returned_by_customer_hash[sku_id].to_f -\n sku_bad_value_gatepass_hash[sku_id].to_f\n\n good_qty = closing_stock_quantity - bad_qty\n good_stock_value = closing_stock_value - bad_stock_value\n\n report << closing_stock_quantity\n report << closing_stock_value\n report << good_qty\n report << good_stock_value\n report << bad_qty\n report << bad_stock_value\n report << sku_blocked_qty_hash[sku_id].to_i\n response_csv << report\n end\n\n send_file(\n \"#{filename}\",\n filename: \"#{filename}\",\n )\n end\n end\n end\n end",
"def define_csv_format(options={})\n \n ###############################\n # QUALITIES OF INPUT CSV FILE\n \n # indicate which columns contain valid data\n # leftmost column is 0\n @data_columns = [0,4,8]\n \n # number of lines per group in input file\n @num_lines_per_linegroup = 5\n \n # indicate what values per row\n # should be 0 to @num_lines_per_linegroup-1\n @input_data_rows = {0 => :name,\n 1 => :elder,\n 2 => :address,\n 3 => :city_state_zip, # occasionally this is more of the address\n 4 => :extra, # occasionally this is the city/state/zip! \n }\n \n # Output data fields\n # Used as data for Google Maps,\n # and used to access data itself via keys\n @output_fields = {:name => \"Name\", # key matches @input_data_rows\n :elder => \"Elder\", # key matches @input_data_rows\n :address => \"Address\", # key matches @input_data_rows\n :city_state_zip => \"City_State_Zip\", # key matches @input_data_rows\n :city => \"City\", # generated from city_state_zip above\n :state => \"State\", # generated from city_state_zip above\n :zip => \"Zip\", # generated from city_state_zip above\n :area => \"Area\", # generated based on zip code\n }\n \n # Hash here used to give warning if someone is assigned to wrong elder!\n # also should match data input -- eventually want this to come from external file?\n @elders = [\"Daniel Hadad\",\n \"Mark De Young\",\n \"Ernie Johnson\",\n \"Joshua Konkle\",\n \"Charles Whitsel\",\n \"Ethan Cruz\",\n \"Ross Davis\",\n \"Don Hilsberg\",\n \"Paul Hunt\",\n \"Gary Jordan\",\n \"Tim Horn\",\n \"Kelly Holligan\",\n \"Steve Hutton\",\n \"John Ritchie\",\n ]\n \n # extra list of names to help find elders themselves in the database (need to use hash above instead...)\n # or break down the name to remove spouse name\n @elders2 = [\"Dan Hadad\",\n ]\n \n # if needing to sub elder in the data\n # format: old_elder => new_elder\n @elder_sub = {\n }\n \n ###############################\n \nend",
"def generate(opts={})\n nd = normalized_data\n ::CSV.generate(opts) do |csv|\n # set header row\n csv << nd[:headers]\n nd[:values].each do |row|\n csv << row\n end\n end\n end",
"def build_csv()\n\t\tconcat_path = \"#{@location}/#{@name}.csv\"\n\n\t\tCSV.open(concat_path, 'wb') do |csv_line|\n\t\t\t\t\t\n\t\t\theaders = ['movie_date', 'title', 'lifetime_gross_sales']\n\t\t\tcsv_line << headers\n\n\t\t\t@cage.each do |cage|\n\t\t\t\tcsv_line << [cage[:movie_date], cage[:title], cage[:life_time_gross]]\n\t\t\tend\n\t\tend\n\tend",
"def csv_options\n memo = other_options.slice(*PASSTHROUGH_CSV_SETTINGS)\n memo[:skip_blanks] = !keep_blank_rows\n memo[:headers] ||= headers\n memo[:col_sep] ||= delimiter\n memo\n end",
"def generate_csv\n\n fields = @resource[:class].typus_fields_for(:csv).collect { |i| i.first }\n\n require 'csv'\n if CSV.const_defined?(:Reader)\n # Old CSV version so we enable faster CSV.\n begin\n require 'fastercsv'\n rescue Exception => error\n raise error.message\n end\n csv = FasterCSV\n else\n csv = CSV\n end\n\n filename = \"#{Rails.root}/tmp/export-#{@resource[:self]}-#{Time.now.utc.to_s(:number)}.csv\"\n\n options = { :conditions => @conditions, :batch_size => 1000 }\n\n csv.open(filename, 'w', :col_sep => ';') do |csv|\n csv << fields\n @resource[:class].find_in_batches(options) do |records|\n records.each do |record|\n csv << fields.map { |f| record.send(f) }\n end\n end\n end\n\n send_file filename\n\n end",
"def render(model, data)\n \n CSVOutputFormat.new(model, data).run\n \n end",
"def create_csv_for_GH(csv_data)\n\n csv_string = CSV.open(\"#{$basefile}GH.csv\", \"wb\") do |csv|\n\n csv_data.each do |hash|\n csv << hash\n\n end\n end\n end",
"def to_tsv\n CSV.generate( :col_sep => \"\\t\" ) { |csv| to_a.each { |r| csv << r } }\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.5112891",
"0.50787735",
"0.5074242",
"0.505903",
"0.5058754",
"0.504443",
"0.5030106",
"0.5008375",
"0.49935776",
"0.49922055",
"0.49810445",
"0.49598756",
"0.49569026",
"0.49381387",
"0.49294624",
"0.49237737",
"0.49184304",
"0.49106944",
"0.49022564",
"0.48977098",
"0.48954076",
"0.48889706",
"0.48831365",
"0.4874625",
"0.4871233",
"0.4870947",
"0.4869227",
"0.48582068",
"0.48524344",
"0.48491704",
"0.48380196",
"0.48369694",
"0.48328727",
"0.48322734",
"0.48302156",
"0.48136163",
"0.48076314",
"0.4805198",
"0.48026058",
"0.47984573",
"0.47953507",
"0.47877443",
"0.47865883",
"0.47849384",
"0.47803408",
"0.47771323",
"0.47731966",
"0.47625917",
"0.47625917",
"0.4755683",
"0.4754422",
"0.47523582",
"0.47507736",
"0.47501564",
"0.4749674",
"0.47468048",
"0.47459522",
"0.47441122",
"0.47400805",
"0.4738042",
"0.47348574",
"0.47343525",
"0.472518",
"0.471967",
"0.47193152",
"0.47146964",
"0.47085556",
"0.4707641",
"0.46948746",
"0.46937943"
] | 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 = \" \" 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",
"def generate_table(name, data_set1, data_set2 , data_set3, data_set4 , assignment_names,data_set1_name , data_set2_name, data_set3_name, data_set4_name )\n table = \"#{name}\"\n\n table << \"<br/><table border='1' align='left'>\"\n\n table << \"<tr><td></td>\"\n assignment_names.each_with_index do |assignment,index|\n table << \"<td>(#{index+1})#{assignment}</td>\"\n end\n\n color = '#'+COLOR_1+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set1_name}</td>\"\n data_set1.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n color = '#'+COLOR_2+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set2_name}</td>\"\n data_set2.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n if(data_set3)\n color = '#'+COLOR_3+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set3_name}</td>\"\n data_set3.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n if(data_set4)\n color = '#'+COLOR_4+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set4_name}</td>\"\n data_set4.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n table << \"</tr></table>\"\n @table = table\n end",
"def 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 status_table(checkers)\n content_tag(:table, border: 1) do\n concat status_header\n checkers.each { |checker| concat status_row(checker) }\n end\n end",
"def datagrid_table(report, *args)\n datagrid_renderer.table(report, *args)\n end",
"def print_datafiles_table(parent, button=true)\n s = \"<table class=\\\"tight_table\\\">\"\n s+=\" <tr>\"\n s+=\" <th align=\\\"left\\\">Data Files</th>\"\n s+=\" </tr>\"\n if(!parent.data_files.empty?)\n for df in parent.data_files\n s+=\" <tr><td> #{link_to(df.filedata_file_name, df, :target => 'blank')} </td></tr>\"\n end\n else\n s+=\" <tr>\"\n s+=\" <td>No Data Files</td>\"\n s+=\" </tr>\"\n end\n s+=\" <tr>\"\n if(button)\n s+=\" <td> #{my_button_to \"New Data File\", new_data_file_path, [@component]} </td>\"\n end\n s+=\" </tr>\"\n s+=\" </table>\"\n return s\n end",
"def OLDview_data db, sql, options\n outputfile = options[:output_to]\n formatting = options[:formatting]\n headers = options[:headers]\n #str = db.get_data sql\n rs = db.execute_query sql\n str = rs.content\n columns = rs.columns\n #puts \"SQL: #{sql}.\\nstr: #{str.size}\"\n data = []\n if headers\n data << columns.join(\"\\t\")\n end\n str.each {|line| data << line.join(\"\\t\"); }\n #puts \"Rows: #{data.size}\"\n require 'tempfile'\n tmpfile = Tempfile.new('SQL.XXXXXX')\n filename = tmpfile.path\n filename = Shellwords.escape(filename)\n #puts \"Writing to #{filename}\"\n tmpfile.write(data.join(\"\\n\"))\n tmpfile.close # need to flush, otherwise write is buffered\n headerstr=nil\n if formatting\n headerstr = \"-H\" unless headers\n # sometimes this can be slow, and it can fault on UTF-8 chars\n system(\"cat #{filename} | term-table.rb #{headerstr} | sponge #{filename}\")\n end\n if outputfile\n #puts \"comes here\"\n system(\"cp #{filename} #{outputfile}\")\n filename = outputfile\n end\n system \"wc -l #{filename}\" if $opt_debug\n \n #system \"$EDITOR #{filename}\"\n system \"vim -c ':set nowrap' #{filename}\"\n tmpfile.close\n tmpfile.unlink\nend",
"def create_confluence_table_html(data)\n\t\txm = Builder::XmlMarkup.new(:indent => 2)\n\t\txm.table {\n\t\t xm.tr { data[0].keys.each { |key| xm.th(key)}}\n\t\t data.each { |row| xm.tr { row.values.each { |value| xm.td(value)}}}\n\t\t}\n\n\t\treturn \"#{xm}\"\t\t\n\tend",
"def to_html\n htmlString = %{<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">}\n htmlString += %{<tr>}\n LineCounter.columnNames.each { |name| htmlString += %{<th>#{name}</th>} }\n htmlString += %{</tr>}\n self.each do |result|\n htmlString += %{<tr>}\n result.to_a.each { |cell| htmlString += %{<td>#{cell}</td> } }\n htmlString += %{</tr>}\n end\n htmlString += %{</table>}\n htmlString += %{<p><em>Generated by } +\n %{<a href=\"http://countloc.rubyforge.org\">countloc</a> version #{VERSION} } +\n %{on #{Time.now.asctime}</em></p>}\n end",
"def summary_table\n update_now_date_time\n calc_difference\n labels = [DueText.period, ' ', DueText.duration, DueText.measure]\n rows = summary_array\n puts tabulate(labels, rows, { 'indent' => 4, 'style' => 'fancy' })\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 table_for(*args, &block)\n tags = {\n :table => :table,\n :thead => :thead,\n :tbody => :tbody,\n :tfoot => :tfoot,\n :tr => :tr,\n :th => :th,\n :td => :td\n }\n ft_generate_html tags, *args, &block\n end",
"def build_report_body\n draw_table(data, :width => 600)\n end",
"def generate_sorted_table(request)\n\t\t# Get the rank to highlight from the query string\n\t\trank_to_highlight = request.GET()[\"rank\"].to_i\n\t\t# Generate table HTML\n\t\ttable_content = \"<table>\"\n\t\t@albums.each do |album|\n\t\t\tif album[@@COL_RANK] == rank_to_highlight\n\t\t\t\ttable_content += \"<tr id=\\\"highlight\\\"><td>#{album[@@COL_RANK]}</td>\"\n\t\t\telse\n\t\t\t\ttable_content += \"<tr><td>#{album[@@COL_RANK]}</td>\"\n\t\t\tend\n\t\t\ttable_content += \"<td>#{album[@@COL_NAME]}</td><td>#{album[@@COL_YEAR]}</td></tr>\"\n\t\tend\n\t\ttable_content += \"</table>\"\n\tend",
"def run_report\n comparison_values.tap do |results|\n display_report(results)\n end\n end",
"def table \n table = data.map do |slot|\n slot.position.to_s.ljust(12) + slot.license_plate.ljust(19) + slot.color + \"\\n\" if slot\n end.join('')\n end",
"def admin_round_table(year, round)\n # TODO move to controller\n nba_playoff_matchups =\n NbaPlayoffMatchup.includes(:nba_team1)\n .includes(:nba_team2)\n .includes(:winning_nba_team)\n .where(year: year, round: round)\n .order(:position)\n if (nba_playoff_matchups.empty?)\n return \"\"\n end\n\n tags = []\n tags << content_tag(:h4, \"Round \" + round.to_s)\n content_tag(:table, class: TABLE_CLASS) do\n tags << content_tag(:thead,\n content_tag(:tr,\n COL_NAMES.collect { |name| content_tag(:th, name)}.join.html_safe))\n tags << content_tag(:tbody) do\n nba_playoff_matchups.each do |nba_playoff_matchup|\n tags << nba_playoff_matchup_row(nba_playoff_matchup).html_safe\n end\n end #content_tag :tbody\n tags.join.html_safe \n end #content_tag :table\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 table(b, rain_fall_type, _year, ji, compare,legend)\n dataset = rain_fall_type.tr('_', ' ')\n \n if rain_fall_type == \"#{rain_fall_type}\"\n \n hash_data = ji.map do |el|\n # if el.to_s == legend\n # { title: legend.tr('_', ' '), field: el, headerFilter: true }\n # else\n # { title: el.to_s.tr('_', ' '), field: el }\n # end\n { title: legend.tr('_', ' '), field: el, headerFilter: true }\n { title: el.to_s.tr('_', ' '), field: el, headerFilter: true }\n end\n else\n if compare == 'None'\n hash_data = [\n { title: legend.tr('_', ' '), field: legend, headerFilter: true },\n { title: dataset, field: rain_fall_type, headerFilter: true }\n ]\n else\n hash_data = [\n # {title:compare, field:compare, sorter:\"string\", },\n { title: legend.tr('_', ' '), field: legend, headerFilter: true },\n \n { title: dataset, field: rain_fall_type, headerFilter: true }\n ]\n end\n end\n \n data = { column: hash_data, data: b }\n data\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 table(opts = { print: true })\n require \"inspec/ui_table_helper\"\n\n the_table = TableHelper.new\n yield(the_table)\n\n colorizer = proc do |data, row, _col|\n if color? && row == 0\n ANSI_CODES[:bold] + ANSI_CODES[:color][:white] + data.to_s + ANSI_CODES[:reset]\n else\n data\n end\n end\n render_mode = color? ? :unicode : :ascii\n padding = [0, 1, 0, 1] # T R B L\n result = the_table.render(render_mode, filter: colorizer, padding: padding) + \"\\n\"\n print_or_return(result, opts[:print])\n end",
"def show\n @working_change = WorkingChange.find(params[:id])\n @sql = working_change_sql @working_change\n respond_to do |format|\n format.html\n format.csv { send_data @working_change.csv }\n format.xls\n end\n end",
"def render_rows\n [header.indices, *(records.map &:values)]\n end",
"def format_color_table(colors)\n capture_haml do\n haml_tag :table, class: 'table color-table' do\n haml_tag :tr, {} do\n color_width = (100 / colors.count).floor\n colors.each do |color|\n next if color[:hex].nil?\n\n lightdark = color_contrast color[:hex]\n csscolor = \"background:#{color[:hex]};\" \\\n \"color:##{lightdark ? '000' : 'fff'};\"\n\n tag_opts = { style: csscolor,\n class: \"brand-color-#{color[:name].parameterize}\",\n width: \"#{color_width}%\" }\n\n haml_tag :td, tag_opts do\n haml_tag :strong, color[:name]\n haml_tag :ul do\n haml_tag :li, \"Hex: #{color[:hex]}\"\n haml_tag :li, \"RGB: #{color[:rgb]}\" if color[:rgb]\n haml_tag :li, \"CMYK: #{color[:cmyk]}\" if color[:cmyk]\n haml_tag :li, \"Pantone #{color[:pantone]}\" if color[:pantone]\n end\n end\n end\n end\n end\n end\n end",
"def build_report_body\n draw_table(data, :width => 700)\n end",
"def init_table(data=[], options={})\n # TODO : create data array from the df and vector data. So that\n # we can directly use the array.(No need to create df or vector and\n # generate the html table using to_html)\n if data.is_a?(Array)\n data_name = 'series_data'+ SecureRandom.uuid\n data =\n if data.all? { |e| e.class==Array }\n Daru::DataFrame.rows(data, name: data_name)\n else\n Daru::Vector.new(data, name: data_name)\n end\n end\n # options[:data] = data_in_array unless data_in_array.empty?\n @table = Daru::DataTables::DataTable.new(options)\n @data = data\n @table\n end",
"def render(data = template, ctx = { })\n @notes = @entries.\n select { |e| e.year == @date.year && e.month == @date.month }.\n sort { |e1, e2| e2.date <=> e1.date }\n\n @older_notes = @entries.\n sort { |e1, e2| e2.date <=> e1.date }.\n select do |e|\n if e.year == @date.year\n e.month < @date.month\n else\n e.year < @date.year\n end\n end\n\n @newer_notes = @entries.\n sort { |e1, e2| e2.date <=> e1.date }.\n select do |e|\n if e.year == @date.year\n e.month > @date.month\n else\n e.year > @date.year\n end\n end\n\n if @older_notes.any? || @newer_notes.any?\n @pagination = Pagination.new.tap do |pagination|\n pagination.previous_link = Link.new(@older_notes.last.date) if @older_notes.any?\n pagination.next_link = Link.new(@newer_notes.first.date) if @newer_notes.any?\n end\n end\n\n super\n end",
"def history_report(rows)\n table = Terminal::Table.new :headings => ['Date','Exercise', 'Set', 'Weight', 'Reps'], \n :title => \"Exercise Log History\",\n :rows => rows \n puts table\nend",
"def recent_records_table\n rows = @recent_records.reverse.collect { | rec |\n stringifier = RecordStringifier.new(rec)\n state = if rec.running?\n b(\"running\")\n elsif rec.paused?\n \"paused\"\n else\n ''\n end\n tr({:bgcolor => BodyBlueFill},\n td(stringifier.full_job_name),\n td(stringifier.start_date_time),\n td(stringifier.cumulative_hours),\n td(state)) }\n \n table({:align => 'center', :width => '66%', :border => \"1\",\n :cellspacing => \"0\", :cellpadding => \"3\"},\n tr({:bgcolor => HeaderBlueFill},\n td({:align => \"center\", :colspan => \"4\" },\n 'Recent Records')),\n *rows)\n end",
"def table(b, rain_fall_type, _year, ji, compare)\n dataset = rain_fall_type.tr('_', ' ')\n dataset_compare = compare.tr('_', ' ')\n hash_data = if rain_fall_type == 'All'\n ji.map do |el|\n if el.to_s == 'Year'\n { title: 'Year', field: el, headerFilter: true }\n else\n { title: el.to_s.tr('_', ' '), field: el }\n end\n end\n else\n\n hash_data = if compare == 'None'\n [\n { title: 'Year', field: 'Year', headerFilter: true },\n { title: dataset, field: rain_fall_type }\n\n ]\n else\n [{ title: 'Year', field: 'Year', headerFilter: true },\n { title: dataset, field: rain_fall_type },\n { title: dataset_compare, field: compare }]\n end\n end\n\n data = { column: hash_data, data: b }\n data\n end",
"def show_table(table, repository: nil, nested: nil)\n\n columns = %w(Item Value)\n prefix = repository ? \"about-#{repository}\" : 'about'\n div_opt = { class: \"#{prefix}-table-container\" }\n table_opt = { class: \"#{prefix}-table\" }\n\n if table.is_a?(Hash)\n # Turn off <thead> if nested.\n table_opt[:class] += ' nested' if nested\n thead = !nested\n colgroup = true\n else\n # Translate the array into a key/value pair form that will be iterated\n # over the same way a Hash is.\n unless table.is_a?(Array)\n logger.warn { \"#{__method__}: #{table.class}: should be Enumerable\" }\n end\n table = Array.wrap(table).map { |v| [nil, v] }\n thead = colgroup = false\n end\n\n # The <table> element inside a container.\n content_tag(:div, div_opt) do\n content_tag(:table, table_opt) do\n\n # Define columns with a distinct CSS class for styling.\n colgroup &&=\n content_tag(:colgroup) do\n (1..columns.size).map { |i|\n content_tag(:col, '', class: \"col#{i}\")\n }.join.html_safe\n end\n\n # Table header if requested and table is a hash.\n thead &&=\n content_tag(:thead) do\n columns.map { |x|\n content_tag(:th, h(x), class: 'heading')\n }.join.html_safe\n end\n\n # Table body in which Enumerable values are handled as nested tables.\n tbody =\n content_tag(:tbody) do\n table.map { |k, v|\n nested_table =\n case v\n when Hash then v.present?\n when Array then v.first.is_a?(Enumerable) || (v.size > 2)\n end\n content_tag(:tr) do\n k = k&.to_s\n v = nested_table ? show_table(v, nested: true) : v.inspect\n [k, v].map { |x|\n content_tag(:td, h(x), class: 'cell') if x\n }.join.html_safe\n end\n }.join(\"\\n\").html_safe\n end\n\n [colgroup, thead, tbody].reject(&:blank?).join(\"\\n\").html_safe\n end\n end\n end",
"def monolith_table(groups, metadata)\n checkmark = \" <span style='color: limegreen'>✔</span>\"\n\n # TODO: The checkmark crap below needs to be abstracted.\n formatters = {\n 'New' => proc { |f, l| ['', '', l] },\n 'Updated' => proc { |f, l| ['', '', l + (metadata[f]['installed'].any? ? checkmark : '' ) ] },\n 'Renamed' => proc { |f, l| [\"#{metadata[f]['oldname']}\" + (metadata[f]['installed'].any? ? checkmark : '' ), \"→\", l ] }\n }\n\n table = HTML::Table.new do |t|\n t.align = 'center'\n end\n\n groups.each do |group_name, members|\n title = Table::Row.new do |r|\n r.content = ['', '', group_name]\n end\n title.class_ = 'title'\n table.push title\n\n formatter = formatters[group_name]\n\n members.each do |formula|\n content = Table::Row.new do |r|\n link = \"<a href=#{metadata[formula]['homepage']}>#{formula}</a>\"\n r.content = formatter.call(formula, link).push(\n h(metadata[formula]['desc'])\n )\n r.first.class_ = 'name'\n end\n table.push content\n end\n end\n\n table\nend",
"def export_diff_two_table(case_name, current, expect, error_list)\n pathname = get_path_name(case_name, @report_directory)\n \n book = Spreadsheet::Workbook.new\n sheet1 = book.create_worksheet :name=> case_name\n \n sheet1.row(0).push \"Current Test Table\"\n sheet1.row(0).default_format = @titile_format\n \n curr_row_idx = sheet1.last_row_index + 1 \n export_two_table_to_excel(curr_row_idx, sheet1, current)\n\n idx = sheet1.last_row_index + 1\n sheet1.row(idx).push \"Expect Table\"\n sheet1.row(idx).default_format = @titile_format\n \n expect_row_idx = sheet1.last_row_index + 1 \n export_two_table_to_excel(expect_row_idx, sheet1, expect)\n \n if !error_list.nil?\n handle_error_list(curr_row_idx, expect_row_idx, sheet1, error_list[0])\n handle_error_list(curr_row_idx + current[0].length + 1, expect_row_idx + expect[0].length + 1, sheet1, error_list[1])\n end\n book.write(pathname)\n end",
"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 apply_template\n apply_table_format_template(template.table)\n apply_grouping_format_template(template.grouping)\n end",
"def export_diff_one_table(case_name, current, expect, error_list)\n pathname = get_path_name(case_name, @report_directory)\n \n book = Spreadsheet::Workbook.new\n sheet1 = book.create_worksheet :name=> case_name\n \n sheet1.row(0).push \"Current Test Table\"\n sheet1.row(0).default_format = @titile_format\n\n curr_row_idx = sheet1.last_row_index + 1 \n export_table_to_excel(curr_row_idx, sheet1, current)\n \n idx = sheet1.last_row_index + 1 \n sheet1.row(idx).push \"Expect Table\"\n sheet1.row(idx).default_format = @titile_format\n \n expect_row_idx = sheet1.last_row_index + 1\n export_table_to_excel(expect_row_idx, sheet1, expect)\n \n handle_error_list(curr_row_idx, expect_row_idx, sheet1, error_list)\n book.write(pathname)\n end",
"def render_history(flows,account_omrl,currency_spec,options = {})\n config = {\n :language => OpenMoneyDefaultLanguage,\n :sort_order => nil\n }.update(options)\n history_row = currency_spec['history_row']\n\n f = []\n language = config[:language]\n field_specs = currency_spec[\"fields\"]\n\n # load the fspecs into a has to be used in rendering the values\n field_names_as_symbols = []\n fspecs = {}\n field_specs.keys.each {|field| fspecs[field] = get_field_spec(field,field_specs)}\n \n flows.each do |flow|\n the_flow = {}\n used_fields = {}\n flow_attributes = flow.get_specification\n history_row.each do |cell|\n if cell =~ /:([a-zA-Z0-9_-]+)(\\((.*)\\))*/\n field = $1\n used_fields[field] = 1\n params = $3\n if field =~ /^_/\n cell_value = case field\n when '_date'\n flow.created_at\n when '_with'\n flow.specification_attribute('declaring_account') == @account_omrl ? render_field_value(flow,'accepting_account',fspecs['accepting_account'],language) : render_field_value(flow,'declaring_account',fspecs['declaring_account'],language)\n when '_balance'\n 'NA'\n when '_volume'\n 'NA'\n when '_if_with_accepter'\n flow.specification_attribute('accepting_account') == @account_omrl ? render_field_value(flow,params,fspecs[params],language) : ''\n when '_if_with_declarer'\n flow.specification_attribute('declaring_account') == @account_omrl ? render_field_value(flow,params,fspecs[params],language) : ''\n else\n \"#{field} not implemented\"\n end\n else \n cell_value = render_field_value(flow,field,fspecs[field],language)\n end\n the_flow[field.intern] = cell_value\n end\n end\n (field_specs.keys - the_flow.keys {|fi| fi.to_s}).each {|fl| the_flow[fl.intern] = render_field_value(flow,fl,fspecs[fl],language)}\n f << the_flow\n end\n \n# sort_order = config[:sort_order]\n# if sort_order =~ /^-(.*)/\n# reverse = true\n# sort_order = $1\n# end\n# if sort_order == nil or sort_order == ''\n# flows = flows.sort_by {|a| a.created_at}.reverse\n# else\n# flows = flows.sort_by {|a| a.specification_attribute(sort_order)}\n# end\n# flows = flows.reverse if reverse\n f = f.reverse\n history_header = get_language_translated_spec(currency_spec,'history_header',language)\n [f,history_header]\n end",
"def display\n\t\tdisplay_headers\n\t\t@rows.each do |row|\n\t\t\tdisplay_row(row)\n\t\tend\n\tend",
"def index\n @tariffs = Tariff.all\n\n connection = ActiveRecord::Base.connection\n quantitative = []\n categorical = []\n values = []\n Tariff.first.properties.each do |k,v|\n if v.is_a? String\n r1 = connection.select_all(\"SELECT properties->>'\" + k + \"' AS property FROM tariffs\").rows\n categorical << r1 if r1.uniq.length > 1\n else\n r2 = connection.select_all(\"SELECT properties->>'\" + k + \"' AS property FROM tariffs\").rows.flatten\n values << r2.collect{|s| s.to_i}\n quantitative << k\n end\n end\n\n temp = categorical.flatten.uniq\n rows = sequence(temp.length)\n\n @header = temp # | quantitative\n @rows = rows # | values\n\n # @test = values\n\n #data_set = Daru::DataFrame.from_csv \"logistic_mle.csv\"\n #glm = Statsample::GLM.compute data_set, :y, :logistic, {constant: 1, algorithm: :mle}\n\n # Options hash specifying addition of an extra constants\n # vector all of whose values is '1' and also specifying\n # that the MLE algorithm is to be used.\n\n #@test = glm.coefficients\n #=> [0.3270, 0.8147, -0.4031,-5.3658]\n #puts glm.standard_error\n #=> [0.4390, 0.4270, 0.3819,1.9045]\n #puts glm.log_likelihood\n\n\n #p sequence(3) #=>[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]\n end",
"def data_sorter\n @file_data.each do |row|\n @trips << Trip.new(row[1], row[2], row[3], row[4]).log_to_driver if row[0] == \"Trip\"\n @drivers << Driver.new(row[1]) if row[0] == \"Driver\"\n end\n end",
"def ar_index_table_data\n returning(\"\") do |result|\n \n for resource in @resources\n columns= [ar_label(resource)]\n\n controller.ardata.fields.for_index.each_with_index do |column_title, index|\n next if not @display_current_ar_index_table_column[index]\n columns << ar_get_resource_value(resource, column_title[0])\n end\n\n columns << ar_show_link(resource) if controller.ardata.links.include? :show\n columns << ar_edit_link(resource) if controller.ardata.links.include? :edit\n columns << ar_destroy_link(resource) if controller.ardata.links.include? :destroy\n\n columns= columns.map{|elem| content_tag :td, elem}.join(\"\\n \")\n columns= \"\\n #{columns}\\n \"\n\n result << \"\\n #{content_tag(:tr, columns, :class => cycle(\"even\", \"odd\")) }\\n\" \n end\n\n #Die!! Array :) See ar_index_table_headers\n @display_current_ar_index_table_column= nil\n end\n end",
"def prepare_report_detail()\n Ruport::Data::Table.new( :column_names => self.class.report_detail_symbols() ) { |t|\n t << self.to_a_s( self.class.report_detail_symbols(), CONVERTED_FLOAT2STRING_FIXED_PRECISION, 8 )\n percentage_amount = 0.0\n if self.patient && self.patient.is_a_firm? && self.patient.is_fiscal?\n account_percent = AppParameterCustomizations.get_receipt_account_percent()\n percentage_amount = self.account_percentage_amount( account_percent )\n t << ['',\n I18n.t(:vat_withholding),\n \"#{Format.float_value( account_percent, 0, CONVERTED_PERCENT2STRING_FIXED_LENGTH )} %\",\n Format.float_value( percentage_amount, 2, CONVERTED_FLOAT2STRING_FIXED_LENGTH )\n ]\n end\n costs = self.get_additional_cost_totals()\n total_amount = (self.net_price() + percentage_amount + costs[:positive] - costs[:negative])\n t << ['',\n '',\n \"<i>#{I18n.t(:to_be_payed, {:scope=>[:receipt]})}:</i>\",\n \"<b>#{Format.float_value( total_amount, 2, CONVERTED_FLOAT2STRING_FIXED_LENGTH )}</b>\"\n ]\n }\n end",
"def export_diff_table_to_file(current, expect)\n error_list = @compareTable.get_error()\n export_table.export_diff_one_table(get_case_name(), current, expect, error_list)\n end",
"def index\n @diffs = Diff.all\n end",
"def index\n @diffs = Diff.all\n end",
"def build_report\n puts \"building performance test comparison report...\"\n puts\n\n # load template\n report = File.read(@template_path)\n\n # metrics result\n result_comparison_table = extract_table_from_csv2html_output(@result_comparison_path)\n\n # atop summary\n atop_summary_comparison_table = extract_table_from_csv2html_output(@atop_summary_comparison_path)\n\n # atop detail\n # TODO: enable\n # atop_detail_comparison_table = extract_table(@atop_detail_comparison_path)\n\n # replace tables (do this first since table data may include parameters)\n report = report.gsub(\"$RESULT_COMPARISON_TABLE\", result_comparison_table)\n report = report.gsub(\"$ATOP_SUMMARY_COMPARISON_TABLE\", atop_summary_comparison_table)\n\n # TODO: enable\n # report = report.gsub(\"$ATOP_DETAIL_TABLE\", atop_detail_table)\n\n # replace parameters\n report = replace_parameters(report)\n\n # write report\n puts \"writing report to #{@output_path}\"\n\n File.write(@output_path, report)\nend",
"def show\n @study = Study.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @study }\n #format.csv {send_data @study.samples.to_csv, :filename => \"#{@study.identifier}_samples.csv\"}\n format.csv { send_data @study.samples_for_csv, :filename => \"#{@study.identifier}_samples.csv\"} \n #format.pdf { render :layout => false }\n #format.csv { send_data @study.samples.to_csv(), :filename => \"#{@study.identifier}_samples.csv\" }\n #format.tsv { send_data @study.samples.to_tsv(), :filename => \"#{@study.samples}_samples.tsv\" }\n end\n\n # TODO\n\n # # create a unique PDF filename\n # pdf_uuid = UUIDTools::UUID.timestamp_create().to_s\n # pdf_uuid_filename = Rails.root.join('app/assets/images/labels', \"#{pdf_uuid}.pdf\").to_s\n\n # # create a pdf but don't display it\n # pdf_file = render_to_string :pdf => pdf_uuid_filename, \n # :template => 'plans/show.pdf.erb' ,\n # :layout => 'pdf',\n # :save_only => true\n # # save to a file\n # File.open(pdf_uuid_filename, 'wb') do |file|\n # file << pdf_file\n # end\n # # create full URL path to created file \n # @plan.url = request.url[0, request.url.index(\"plans\")] + 'pdf/' + CGI::escape(\"#{pdf_uuid}.pdf\")\n # @plan.save!\n # # render the page again with the link being displayed\n # redirect_to :back\n\n end",
"def index\n @datatable = InventoryMovementsDatatable.new\n respond_to do |format|\n format.html\n format.csv do\n day_before_start_date = (@imr_start_date <= @initial_date) ? DateTime.now.end_of_day : (@imr_start_date.to_datetime - 1.day).end_of_day\n ekanek = Organisation::EKANEK_ORG\n a3m = Organisation::A3M_ORG\n params[:organisation_id] = params[:organisation_id].to_i\n\n # \"Brand Name\", \"Brand Owner\", \"Item Name\", \"Item Type\", \"MRP\", \"GWP/Surprise\"\n brand_name_hash, brand_owner_hash, name_hash, item_type_hash, mrp_hash, gwp_surprise_hash = Sku.create_item_detail_hashes\n\n # Opening Stock\n organisation_ids = params[:organisation_id] == 0 ? [ekanek.id, a3m.id] : params[:organisation_id]\n opening_stock_quantity_hash, opening_stock_value_hash = InventoryItem.create_opening_stock_hashes(day_before_start_date, organisation_ids)\n\n organisation_ids = (params[:organisation_id].in? [0, ekanek.id]) ? [ekanek.id, a3m.id] : params[:organisation_id]\n # Total Purchase = 1. Putaway GRN Items\n sku_purchased_quantity_hash, sku_purchased_value_hash = InventoryItem.create_purchased_hashes(@imr_start_date, @imr_end_date, organisation_ids)\n # Bad purchase = 1. Putaway GRN Items Bad\n sku_bad_qty_purchased_hash, sku_bad_value_purchased_hash = InventoryItem.create_bad_purchased_hashes(@imr_start_date, @imr_end_date, organisation_ids)\n\n organisation_id = params[:organisation_id] == 0 ? a3m.id : params[:organisation_id]\n # 2. Putaway Returned by Customers\n sku_quantity_returned_by_customers_hash, sku_value_returned_by_customers_hash = InventoryItem.create_returned_by_customer_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # 2. Putaway Returned by Customers Bad\n sku_qty_bad_stock_returned_by_customer_hash, sku_value_bad_stock_returned_by_customer_hash = InventoryItem.create_bad_returned_by_customer_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # Sold\n sku_quantity_sold_hash, sku_value_sold_hash = InventoryItem.create_sold_hashes(@imr_start_date, @imr_end_date, organisation_id)\n\n # Gatepasses\n organisation_id = params[:organisation_id] == 0 ? ekanek.id : params[:organisation_id]\n sku_quantity_returned_to_vendor_hash, sku_value_returned_to_vendor_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'rtv', organisation_id)\n sku_self_consumed_quantity_hash, sku_self_consumed_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'self_consumption', organisation_id)\n sku_quantity_sent_for_brand_collabs_hash, sku_value_sent_for_brand_collabs_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'brand_collabs', organisation_id)\n sku_quantity_sent_to_agency_hash, sku_value_sent_to_agency_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'agency', organisation_id)\n sku_gift_quantity_hash, sku_gift_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'gift', organisation_id)\n sku_quantity_liquidated_hash, sku_value_liquidated_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'liquidation', organisation_id)\n sku_stock_transfer_quantity_hash, sku_stock_transfer_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'stock_transfer', organisation_id)\n # Bad Gatepasses\n sku_bad_qty_gatepass_hash, sku_bad_value_gatepass_hash = InventoryItem.create_bad_gatepass_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # Blocked Qty\n sku_blocked_qty_hash = Inventory.create_sku_blocked_qty_hash\n\n require 'csv'\n filename = \n case params[:organisation_id].to_i\n when 0\n 'Consolidated-IMR.csv'\n when ekanek.id\n 'EkAnek-IMR.csv'\n when a3m.id\n 'A3M-IMR.csv'\n end\n\n CSV.open(\"#{filename}\", \"wb\") do |response_csv|\n response_csv << [\"SKU ID\", \"Brand Name\", \"Brand Owner\", \"Item Name\", \"Item Type\", \"MRP\", \"GWP/Surprise\", \"Opening Stock Qty\", \"Opening Stock Value\", \"Qty Purchased\", \"Value Purchased\",\n \"Qty Returned By Customer\", \"Value Returned By Customer\", \"Total Putaway Qty\", \"Total Putaway Value\",\n \"Qty Sold\", \"Value Sold\", \"Qty Returned to Vendor\", \"Value Returned to Vendor\", \"Qty Used for Self Consumption\",\n \"Value Used for Self Consumption\", \"Qty used for Brand Collabs\", \"Value used for Brand Collabs\", \"Qty sent to Agency\",\n \"Value sent to Agency\", \"Qty used as Gift\", \"Value used as Gift\", \"Qty Liquidated\", \"Value Liquidated\",\n \"Stock Transfer Qty\", \"Stock Transfer Value\", \"Gatepass Bad Qty\", \"Gatepass Bad Value\", \"Total Gatepass\", \"Total Gatepass Value\", \"Stock Adjustment\",\n \"Closing Stock Qty\", \"Closing Stock Value\" , \"Good Qty\", \"Good Qty Value\", \"Bad Qty\", \"Bad Qty Value\", \"Qty Blocked\"]\n\n skus = InventoryItem.pluck(:sku_id).uniq\n skus.each do |sku_id|\n report = []\n report << sku_id\n sku = Sku.find sku_id\n\n report << brand_name_hash[sku_id]\n report << brand_owner_hash[sku_id]\n report << name_hash[sku_id]\n report << item_type_hash[sku_id]\n report << mrp_hash[sku_id]\n report << gwp_surprise_hash[sku_id]\n\n opening_stock_quantity = (@imr_start_date <= @initial_date) ? 0 : opening_stock_quantity_hash[sku_id].to_i\n opening_stock_value = (@imr_start_date <= @initial_date) ? 0 : opening_stock_value_hash[sku_id].to_f\n report << opening_stock_quantity\n report << opening_stock_value\n report << sku_purchased_quantity_hash[sku_id].to_i\n report << sku_purchased_value_hash[sku_id].to_f\n report << sku_quantity_returned_by_customers_hash[sku_id].to_i\n report << sku_value_returned_by_customers_hash[sku_id].to_f\n total_putaway_qty = sku_purchased_quantity_hash[sku_id].to_i + sku_quantity_returned_by_customers_hash[sku_id].to_i\n total_putaway_value = sku_purchased_value_hash[sku_id].to_f + sku_value_returned_by_customers_hash[sku_id].to_f\n report << total_putaway_qty\n report << total_putaway_value\n report << sku_quantity_sold_hash[sku_id].to_i\n report << sku_value_sold_hash[sku_id].to_f\n report << sku_quantity_returned_to_vendor_hash[sku_id].to_i\n report << sku_value_returned_to_vendor_hash[sku_id].to_f\n report << sku_self_consumed_quantity_hash[sku_id].to_i\n report << sku_self_consumed_value_hash[sku_id].to_f\n report << sku_quantity_sent_for_brand_collabs_hash[sku_id].to_i\n report << sku_value_sent_for_brand_collabs_hash[sku_id].to_f\n report << sku_quantity_sent_to_agency_hash[sku_id].to_i\n report << sku_value_sent_to_agency_hash[sku_id].to_f\n report << sku_gift_quantity_hash[sku_id].to_i\n report << sku_gift_value_hash[sku_id].to_f\n report << sku_quantity_liquidated_hash[sku_id].to_i\n report << sku_value_liquidated_hash[sku_id].to_f\n report << sku_stock_transfer_quantity_hash[sku_id].to_i\n report << sku_stock_transfer_value_hash[sku_id].to_f\n report << sku_bad_qty_gatepass_hash[sku_id].to_i\n report << sku_bad_value_gatepass_hash[sku_id].to_f\n total_gp_qty = sku_quantity_returned_to_vendor_hash[sku_id].to_i +\n sku_self_consumed_quantity_hash[sku_id].to_i +\n sku_quantity_sent_for_brand_collabs_hash[sku_id].to_i +\n sku_quantity_sent_to_agency_hash[sku_id].to_i +\n sku_gift_quantity_hash[sku_id].to_i +\n sku_quantity_liquidated_hash[sku_id].to_i +\n sku_stock_transfer_quantity_hash[sku_id].to_i +\n sku_bad_qty_gatepass_hash[sku_id].to_i\n total_gp_value = sku_value_returned_to_vendor_hash[sku_id].to_f +\n sku_self_consumed_value_hash[sku_id].to_f +\n sku_value_sent_for_brand_collabs_hash[sku_id].to_f +\n sku_value_sent_to_agency_hash[sku_id].to_f +\n sku_gift_value_hash[sku_id].to_f +\n sku_value_liquidated_hash[sku_id].to_f +\n sku_stock_transfer_value_hash[sku_id].to_f +\n sku_bad_value_gatepass_hash[sku_id].to_f\n report << total_gp_qty\n report << total_gp_value\n report << 0 # stock adjustment 0 for now\n\n inwarded_quantity = total_putaway_qty\n inwarded_value = total_putaway_value\n\n outwarded_quantity = sku_quantity_sold_hash[sku_id].to_i + total_gp_qty\n outwarded_value = sku_value_sold_hash[sku_id].to_f + total_gp_value\n\n closing_stock_quantity = opening_stock_quantity + inwarded_quantity - outwarded_quantity\n closing_stock_value = opening_stock_value + inwarded_value - outwarded_value\n\n # total_bad = putaway_grn_bad + putaway_return_bad - gatepass_bad\n bad_qty = sku_bad_qty_purchased_hash[sku_id].to_i +\n sku_qty_bad_stock_returned_by_customer_hash[sku_id].to_i -\n sku_bad_qty_gatepass_hash[sku_id].to_i\n bad_stock_value = sku_bad_value_purchased_hash[sku_id].to_f +\n sku_value_bad_stock_returned_by_customer_hash[sku_id].to_f -\n sku_bad_value_gatepass_hash[sku_id].to_f\n\n good_qty = closing_stock_quantity - bad_qty\n good_stock_value = closing_stock_value - bad_stock_value\n\n report << closing_stock_quantity\n report << closing_stock_value\n report << good_qty\n report << good_stock_value\n report << bad_qty\n report << bad_stock_value\n report << sku_blocked_qty_hash[sku_id].to_i\n response_csv << report\n end\n\n send_file(\n \"#{filename}\",\n filename: \"#{filename}\",\n )\n end\n end\n end\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 diff(table, wait_time = Capybara.default_max_wait_time, ignore_case: false)\n to_table = self.to_table\n\n if ignore_case == true\n table = Cucumber::MultilineArgument::DataTable.from(downcase_array(table.raw))\n to_table = downcase_array(to_table)\n end\n\n table.diff!(to_table) || true\n end",
"def index\n @tariffs = Tariff.order(:id)\n\n respond_to do |format|\n format.html\n format.csv { send_data @tariffs.to_csv(:col_sep => \";\") }\n end\n end",
"def show\n @header = Tariff.column_names\n @tariff = Tariff.find(params[:id])\n end",
"def table(rows = [],options = {}, &block)\n Wizport::Rtf::Table.new(self, rows, options, &block)\n end",
"def EXCEL_TABLE(objects, *arguments)\n DebugTable.new(objects, arguments, :tsv)\n end",
"def show\n @table_header = @project.table_header\n @records = @project.get_table_class.all\n end",
"def print_temp_table()\n\n #Allocate an array holder to collect all relevant user input data\n rows = []\n\n # Allocate top row for heading\n rows << [\"Day\", \"Cel.\", \"Fahr.\"]\n\n # Add in a line\n rows << :separator\n\n # Put all data into temp_data obtained via temperature record array holder\n @temperature_record.each do |temp_data|\n\n # Push all data into row array holder\n rows << [\n # Define local variable for each array's key\n # array[:id] is for accessing a value from a Hash\n # by using :id as a key\n temp_data[:day],\n\n # Using temperature_as_color method to colorize data\n temperature_as_color(temp_data[:celcius], :celcius),\n temperature_as_color(temp_data[:fahrenheit], :fahrenheit)\n ]\n end\n\n table = Terminal::Table.new :title => \"Melbourne Weekly Weather\", :rows => rows\nend",
"def details_data\n# column_widths = @settings.collect{|s| pdf.width_of(s[:header].last, :size => pdf.font_size) + 5 }\n\n font_size = pdf.font_size\n padding = (cell_padding + cell_border_width)*2\n @rows.collect do |r|\n @settings.collect{|s|\n content = \"\"\n align = :left\n contents = []\n \n if s[:header].first == \"remark\"\n content = r.remark.to_s\n contents += content.split(/\\r?\\n/)\n elsif s[:header].first == \"revision_no\"\n case r\n when HeaderRow\n content = r.latest_revision_no.to_s\n when RevisionRow\n content = r.rev_no.to_s\n when DetailRow\n content = r.revision_row.rev_no.to_s\n end\n contents << content\n else\n field = Field.field_by_row(s[:header].first, r)\n actual_row = Field.row_by_field(field, r)\n content = Field.value_by_field_name(field, actual_row) unless actual_row.nil?\n contents += content.to_s.split(/\\r?\\n/)\n\n case field\n when Fields::Formula, Fields::Accumulation\n align = :right\n else\n case field.custom_field\n when CustomFields::NumericField\n align = :right\n when CustomFields::DateTimeField\n align = :center\n end\n end\n end\n \n max_content_width = contents.collect{|c| pdf.width_of(c, :size => font_size) }.max\n\n width = max_content_width.to_i + padding\n \n {\n :content => content,\n :align => align,\n :width => width\n }\n }\n end\n end",
"def show_difference\n hash = params[\"dates\"]\n datetime_start = get_datetime_from_hash(hash, \"date_start\")\n datetime_end = get_datetime_from_hash(hash, \"date_end\")\n\n snapshot_data_start = get_snapshot_data_at_datetime(datetime_start)\n snapshot_data_end = get_snapshot_data_at_datetime(datetime_end)\n\n @difference_data = snapshot_data_end\n snapshot_data_start.each do |currency, value|\n @difference_data[currency] -= value\n end\n\n @start_date = datetime_start.strftime(\"%m/%d/%Y %I:%M%p\")\n @end_date = datetime_end.strftime(\"%m/%d/%Y %I:%M%p\")\n end",
"def show\n render layout: 'diff'\n end",
"def test_to_html\n df = Rover::DataFrame.new({\"a\" => [1, 2, 3], \"b\" => [\"one\", \"two\", \"three\"]})\n assert_match \"<table>\", df.to_html\n end",
"def display_volume_table items, cult_vol, media_vol\n volume_table = [[\"Cuvette Number\", \"Item ID\", \"Culture Volume to add (uL)\", \"#{MEDIA_TYPE} Media Volume to add (uL)\"]]\n \n first_row = [\"0\", \"N/A\", \"0\", \"#{MAX_CUVETTE_VOLUME}\"]\n volume_table.push(first_row)\n \n i = 1\n items.each do |item|\n curr_row = []\n curr_row.push(i.to_s)\n curr_row.push(item.id.to_s)\n curr_row.push(cult_vol)\n curr_row.push(media_vol)\n volume_table.push(curr_row)\n i += 1\n end\n \n # Displays volume table\n show do\n title \"Fill Plastic Cuvettes\"\n \n note \"Follow the table below to label each cuvette a number for each item id.\"\n table volume_table\n end \n \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 summary_row(args={})\n\n\t\tif args[\"root\"] =~ /order/\n\t\t\t\n\t\t\tinference = \"-\"\n\t\t\t\n\t\t\trange_name = \"-\"\n\t\t\t\n\t\t\tabnormal = \"-\"\n\n\t\t\t## so there is no applicable range\n\t\t\t## as no tag has been assigned.\n\t\t\tif applicable_range = self.ranges[0]\n\t\t\t\tinference = applicable_range.get_inference\n\t\t\t\trange_name = applicable_range.get_display_name\n\t\t\t\tabnormal = applicable_range.is_abnormal?\n\t\t\tend\n\t\t\t## this nees to be set as an accessor.\n\t\t\t## <div class=\"verify edit_nested_object\" data-id=' + self.unique_id_for_form_divs + '>Verify</div>\n\t\t\t'\n\t\t\t\t<thead>\n\t\t <tr>\n\t\t <th>' + self.name + '</th>\n\t\t <th>' + (self.result_raw || DEFAULT_RESULT) + '</th>\n\t\t <th>' + (self.units || DEFAULT_UNITS) + '</th>\n\t\t <th>' + (applicable_range.get_normal_biological_interval || \"-\") + '</th>\n\t\t <th>' + (inference || '') + '</th>\n\t\t <th>' + self.is_verification_done?.to_s + '</th>\n\t\t <th><div class=\"add_result_manually edit_nested_object\" data-id=' + self.unique_id_for_form_divs + '>Add Result Manually</div>\n\t\t </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<tr>\n\t\t\t\t\t<td>' + self.name + '</td>\n\t\t\t\t\t<td>' + self.lis_code + '</td>\n\t\t\t\t\t<td>' + self.description + '</td>\n\t\t\t\t\t<td>' + self.ranges.size.to_s + '</td>\n\t\t\t\t\t<td><div class=\"edit_nested_object\" data-id=' + self.unique_id_for_form_divs + '>Edit</div></td>\n\t\t\t\t</tr>\n\t\t\t'\n\t\tend\n\tend",
"def report(*args)\n options = args.first\n sort_order = options && options[:sort]\n if sort_order && !sort_order.eql?(:ascending) && !sort_order.eql?(:descending)\n raise(ArgumentError.new('Invalid configuration, use [:ascending, :descending]'))\n end\n\n check_auth(options)\n\n items = coverage_items\n items.select! { |item| file_in_changeset?(item.file) }\n items.each(&method(:update_item))\n items.sort_by! do |item|\n if sort_order.eql?(:ascending)\n item.total\n else\n -item.total\n end\n end\n items.each(&method(:add_entry))\n\n return if @table.size.zero?\n\n markdown(\"#{TABLE_TITLE}\\n\\n#{@table.to_markdown}\")\n end",
"def format_output_without_CSV\r\n\t\theadings = [] << \"Run\"\r\n\t\trows = []\r\n\t\t@parameters.each_with_index {|p,i| headings << \"F#{i+1}\"}\r\n\t\t@runs.each_with_index {|r,i| temp = [\"#{i+1}\"]; temp += r; rows << temp}\r\n\t\t@output_table = Terminal::Table.new :title => \"IPO Algorithm tests output\", :headings => headings, :rows => rows\r\n\tend",
"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 draw_summary_table\n header = [\"Date\", \"Issue Number\", \n \"Total Subscribers\", \"Change in Subscribers\"]\n\n body = report.table(:date,:number,:count,:delta)\n\n document.table([header]+body) do |t|\n t.header = true\n t.style(t.columns(1..-1)) { |c| c.align = :right }\n end\n end",
"def table_for(collection, options = {}, *attr_list)\n actions = false\n classes = options[:classes] || \"\"\n model_class_name = options[:model_name] || collection.name\n table_id = options[:id] || model_class_name.tableize\n table_klazz = model_class_name.constantize\n table_headers = []\n\n attr_list.flatten.each do |attr_name|\n if attr_name.class == Hash && !attr_name[:actions].nil?\n actions = attr_name[:actions]\n else\n header_content = table_klazz.human_attribute_name(attr_name)\n header = content_tag(:th, header_content)\n table_headers << header\n end\n end\n\n if actions\n table_headers << content_tag(:th, t('actions'), class: 'table_actions')\n end\n\n thead = content_tag :thead, content_tag(:tr, table_headers.join(\" \").html_safe)\n table_content = \"\"\n if options[:partial].present?\n table_content = render partial: options[:partial], collection: collection\n else\n table_content = render collection\n end\n tbody = content_tag :tbody, table_content\n table = content_tag(:table, \"#{thead} #{tbody}\".html_safe, id: table_id, class: \"table table-hover #{classes}\")\n table.html_safe\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_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\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"
] | [
"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.52401084",
"0.5211076",
"0.5200542",
"0.5172456",
"0.51660675",
"0.51659536",
"0.51529455",
"0.51481134",
"0.5139302",
"0.51327974",
"0.5131676",
"0.51307225",
"0.51123315",
"0.5111932",
"0.51116866",
"0.51112705",
"0.511074",
"0.51095474",
"0.51026547",
"0.51019776",
"0.5096815",
"0.5096142",
"0.50939053",
"0.50859416",
"0.50827426",
"0.50812435",
"0.50741875",
"0.5069534",
"0.5063967",
"0.50607896",
"0.5060091",
"0.5045962",
"0.50457287",
"0.5035697",
"0.5035107",
"0.5033343",
"0.5031613",
"0.50183123",
"0.5013961",
"0.5012516",
"0.5009778",
"0.5009769",
"0.4995415",
"0.4995415",
"0.49940938",
"0.4981597",
"0.49786028",
"0.4978137",
"0.4973873",
"0.4970672",
"0.49700776",
"0.49682763",
"0.49645472",
"0.49583912",
"0.4955425",
"0.49512294",
"0.49432352",
"0.49415058",
"0.49412853",
"0.49391517",
"0.49277216",
"0.49164096",
"0.49156162",
"0.49152333",
"0.49130917",
"0.4913004",
"0.4912047",
"0.4896721",
"0.48963696",
"0.4894374"
] | 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",
"def generate_sorted_table(request)\n\t\t# Get the rank to highlight from the query string\n\t\trank_to_highlight = request.GET()[\"rank\"].to_i\n\t\t# Generate table HTML\n\t\ttable_content = \"<table>\"\n\t\t@albums.each do |album|\n\t\t\tif album[@@COL_RANK] == rank_to_highlight\n\t\t\t\ttable_content += \"<tr id=\\\"highlight\\\"><td>#{album[@@COL_RANK]}</td>\"\n\t\t\telse\n\t\t\t\ttable_content += \"<tr><td>#{album[@@COL_RANK]}</td>\"\n\t\t\tend\n\t\t\ttable_content += \"<td>#{album[@@COL_NAME]}</td><td>#{album[@@COL_YEAR]}</td></tr>\"\n\t\tend\n\t\ttable_content += \"</table>\"\n\tend",
"def show\n render layout: 'diff'\n end",
"def add_divider_row_to_table\n table << \" -\"\n size.times { table << '-----' }\n table << \"\\n\"\n end",
"def render(model, data)\n \n CSVOutputFormat.new(model, data).run\n \n end",
"def admin_round_table(year, round)\n # TODO move to controller\n nba_playoff_matchups =\n NbaPlayoffMatchup.includes(:nba_team1)\n .includes(:nba_team2)\n .includes(:winning_nba_team)\n .where(year: year, round: round)\n .order(:position)\n if (nba_playoff_matchups.empty?)\n return \"\"\n end\n\n tags = []\n tags << content_tag(:h4, \"Round \" + round.to_s)\n content_tag(:table, class: TABLE_CLASS) do\n tags << content_tag(:thead,\n content_tag(:tr,\n COL_NAMES.collect { |name| content_tag(:th, name)}.join.html_safe))\n tags << content_tag(:tbody) do\n nba_playoff_matchups.each do |nba_playoff_matchup|\n tags << nba_playoff_matchup_row(nba_playoff_matchup).html_safe\n end\n end #content_tag :tbody\n tags.join.html_safe \n end #content_tag :table\n end",
"def table_for(value, options = {}, &block)\n view(value, options.merge(:as => :table), &block)\n end",
"def show\n @working_change = WorkingChange.find(params[:id])\n @sql = working_change_sql @working_change\n respond_to do |format|\n format.html\n format.csv { send_data @working_change.csv }\n format.xls\n end\n end",
"def print_datafiles_table(parent, button=true)\n s = \"<table class=\\\"tight_table\\\">\"\n s+=\" <tr>\"\n s+=\" <th align=\\\"left\\\">Data Files</th>\"\n s+=\" </tr>\"\n if(!parent.data_files.empty?)\n for df in parent.data_files\n s+=\" <tr><td> #{link_to(df.filedata_file_name, df, :target => 'blank')} </td></tr>\"\n end\n else\n s+=\" <tr>\"\n s+=\" <td>No Data Files</td>\"\n s+=\" </tr>\"\n end\n s+=\" <tr>\"\n if(button)\n s+=\" <td> #{my_button_to \"New Data File\", new_data_file_path, [@component]} </td>\"\n end\n s+=\" </tr>\"\n s+=\" </table>\"\n return s\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 table_list(objetos, show_all_actions = true, options = {})\n render :partial => '/admin/shared/table_list', :locals => { :objetos => objetos, :show_all_actions => show_all_actions, :options => options }\n end",
"def OLDview_data db, sql, options\n outputfile = options[:output_to]\n formatting = options[:formatting]\n headers = options[:headers]\n #str = db.get_data sql\n rs = db.execute_query sql\n str = rs.content\n columns = rs.columns\n #puts \"SQL: #{sql}.\\nstr: #{str.size}\"\n data = []\n if headers\n data << columns.join(\"\\t\")\n end\n str.each {|line| data << line.join(\"\\t\"); }\n #puts \"Rows: #{data.size}\"\n require 'tempfile'\n tmpfile = Tempfile.new('SQL.XXXXXX')\n filename = tmpfile.path\n filename = Shellwords.escape(filename)\n #puts \"Writing to #{filename}\"\n tmpfile.write(data.join(\"\\n\"))\n tmpfile.close # need to flush, otherwise write is buffered\n headerstr=nil\n if formatting\n headerstr = \"-H\" unless headers\n # sometimes this can be slow, and it can fault on UTF-8 chars\n system(\"cat #{filename} | term-table.rb #{headerstr} | sponge #{filename}\")\n end\n if outputfile\n #puts \"comes here\"\n system(\"cp #{filename} #{outputfile}\")\n filename = outputfile\n end\n system \"wc -l #{filename}\" if $opt_debug\n \n #system \"$EDITOR #{filename}\"\n system \"vim -c ':set nowrap' #{filename}\"\n tmpfile.close\n tmpfile.unlink\nend",
"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 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 index\n @datatable = ComplainsDatatable.new view_context\n end",
"def display_branch_list\n table = build_table_view\n\n puts \"\\n\\n\"\n puts table\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 diffsplit( path, options={})\n\t\tvert = \"vertical\" if options[:vertical]\n\t\tVim::command(\"#{vert} diffsplit #{path}\")\n\tend",
"def _draw_2_lane(&block)\n result = @left ? @vc.tag(:tr, nil, true) : ''.html_safe\n result += yield\n result += '</tr>'.html_safe if !@left\n @left = !@left # flip it\n result\n end",
"def diff_template= table\n @diff_template = table\n end",
"def view_team\n @participant = AssignmentParticipant.find(params[:id])\n @assignment = @participant.assignment\n @team = @participant.team\n @team_id = @team.id\n @questions = {}\n questionnaires = @assignment.questionnaires\n retrieve_questions questionnaires\n @pscore = @participant.scores(@questions)\n @vmlist = []\n\n # loop through each questionnaire, and populate the view model for all data necessary\n # to render the html tables.\n counter_for_same_rubric = 0\n questionnaires.each do |questionnaire|\n @round = nil\n if @assignment.varying_rubrics_by_round? && questionnaire.type == \"ReviewQuestionnaire\"\n questionnaires = AssignmentQuestionnaire.where(assignment_id: @assignment.id, questionnaire_id: questionnaire.id)\n if questionnaires.count > 1\n @round = questionnaires[counter_for_same_rubric].used_in_round\n counter_for_same_rubric += 1\n else\n @round = questionnaires[0].used_in_round\n counter_for_same_rubric = 0\n end\n end\n vm = VmQuestionResponse.new(questionnaire, @assignment, @round)\n vmquestions = questionnaire.questions\n vm.add_questions(vmquestions)\n vm.add_team_members(@team)\n vm.add_reviews(@participant, @team, @assignment.varying_rubrics_by_round?)\n vm.get_number_of_comments_greater_than_10_words\n @vmlist << vm\n end\n @current_role_name = current_role_name\n end",
"def show\n @study = Study.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @study }\n #format.csv {send_data @study.samples.to_csv, :filename => \"#{@study.identifier}_samples.csv\"}\n format.csv { send_data @study.samples_for_csv, :filename => \"#{@study.identifier}_samples.csv\"} \n #format.pdf { render :layout => false }\n #format.csv { send_data @study.samples.to_csv(), :filename => \"#{@study.identifier}_samples.csv\" }\n #format.tsv { send_data @study.samples.to_tsv(), :filename => \"#{@study.samples}_samples.tsv\" }\n end\n\n # TODO\n\n # # create a unique PDF filename\n # pdf_uuid = UUIDTools::UUID.timestamp_create().to_s\n # pdf_uuid_filename = Rails.root.join('app/assets/images/labels', \"#{pdf_uuid}.pdf\").to_s\n\n # # create a pdf but don't display it\n # pdf_file = render_to_string :pdf => pdf_uuid_filename, \n # :template => 'plans/show.pdf.erb' ,\n # :layout => 'pdf',\n # :save_only => true\n # # save to a file\n # File.open(pdf_uuid_filename, 'wb') do |file|\n # file << pdf_file\n # end\n # # create full URL path to created file \n # @plan.url = request.url[0, request.url.index(\"plans\")] + 'pdf/' + CGI::escape(\"#{pdf_uuid}.pdf\")\n # @plan.save!\n # # render the page again with the link being displayed\n # redirect_to :back\n\n end",
"def tableView(tableView, rowViewForRow:row)\n FBSidePanelTableRowView.new\n end",
"def format!\n tables.map { |t|\n SimpleReports::TableFormatter.new(t).format_table!\n }\n end",
"def index\n @diffs = Diff.all\n end",
"def index\n @diffs = Diff.all\n end",
"def index\n @splits = Split.all\n end",
"def table\n @max_cols = []\n @col_width = []\n @col_event = []\n (0..(num_days-1)).each do |day|\n @max_cols[day] = calc_max_cols(0, NUM_HALF_HOURS,day)\n if @max_cols[day] == 0\n @max_cols[day] = 1\n end\n @col_width[day] = (100.0/(num_days*@max_cols[day]) + 0.5).to_i\n @col_event << {}\n end\n @all_day_max = calc_all_day_max\n calc_event_rows\n content_tag :div do\n all_day_table + hour_table\n end\n end",
"def show\n @number_of_strengths = @swot_table.strength.split(',').length\n @number_of_weakness = @swot_table.weakness.split(',').length\n @number_of_opportunities = @swot_table.opportunity.split(',').length\n @number_of_threats = @swot_table.threats.split(',').length\n\n if @number_of_strengths > 0 or @number_of_weakness > 0 or @number_of_opportunities > 0 or @number_of_threats > 0\n if ((@number_of_strengths + (@number_of_opportunities / 2)) - (@number_of_weakness + (@number_of_threats / 2))) > 0\n @swot_result = 2\n elsif ((@number_of_strengths + (@number_of_opportunities / 2)) - (@number_of_weakness + (@number_of_threats / 2))) == 0\n @swot_result = 1\n else @swot_result = 0\n end\n end\n\n respond_to do |format|\n format.html\n format.pdf do\n render template: 'swot_tables/show',\n pdf: 'swot',\n viewport_size: '1280x1024'\n end\n end\n end",
"def index\r\n \r\n if !@selected_event.nil? && !@selected_data_template.nil?\r\n \r\n # hash of master items column names as keys, value is number of times used in all templates\r\n # so that we can sort and show the most used columns first\r\n mi_cols = {}\r\n \r\n @template_cols_by_template_id = []\r\n col_names_sha1 = []\r\n \r\n # Determine master items columns (all unique column names across templates)\r\n @ea_data_templates.each_with_index do |template, k|\r\n \r\n tcols = Set.new\r\n template.data_template_columns.each do |col|\r\n tcols.add(col.sha1_name)\r\n end\r\n \r\n @template_cols_by_template_id[template.id] = tcols\r\n \r\n template.data_template_columns.each_with_index do |col, index|\r\n col_name_sha1 = col.sha1_name\r\n col_names_sha1.push col_name_sha1 unless col_names_sha1.include?(col_name_sha1)\r\n if ! mi_cols.has_key?(col.name)\r\n mi_cols[col.name] = 10000 - col.order - (100 * k) # give weight based on template and template column order\r\n else\r\n # column already exists, so increment our column occurrence hash value counter\r\n mi_cols[col.name] = mi_cols[col.name] + 10000\r\n end\r\n end\r\n end\r\n \r\n # Sort the master items columns so that frequently used columns are shown first\r\n # technically we are doing a reverse value-based hash sort here\r\n # see http://corelib.rubyonrails.org/classes/Hash.html#M000705\r\n # results (sorted_cols) in a nested array with the hash contents sorted\r\n # col[0] is now the column name\r\n # col[1] is the column weighting computed above for the col order\r\n @sorted_cols = mi_cols.sort { |a,b| b[1] <=> a[1] }\r\n \r\n # Set col[3] to the sha1 hash of the column name as this is used throughout the view\r\n # for paging/sorting and in the master items DB query to properly handle column names with special characters\r\n @sorted_cols.each do |col|\r\n col[3] = Digest::SHA1.hexdigest(col[0])\r\n end\r\n \r\n order_string = (! params[:sort_by].nil? && (col_names_sha1.include?(params[:sort_by]) || Item::SYSTEM_COLS.include?(params[:sort_by]))) ?\r\n \"`#{params[:sort_by]}` #{params[:sort_type].upcase}\" : nil\r\n \r\n # get template items\r\n sql = Item.generate_master_items_query( @selected_event, order_string )\r\n \r\n # Run said sql to get the items\r\n @items = Item.paginate_by_sql( sql , :page => params[:page] ) unless sql.nil?\r\n \r\n end\r\n \r\n respond_to do |format|\r\n format.html # master_items.html.erb\r\n end\r\n \r\n end",
"def render\n buffer = []\n _guess_col_widths\n rows = @list.size.to_s.length\n @rows = rows\n _prepare_format\n \n str = \"\"\n if @numbering\n str = \" \"*(rows+1)+@y\n end\n str << @fmstr % @columns\n buffer << str\n #puts \"-\" * str.length\n buffer << separator\n if @list\n if @numbering\n @fmstr = \"%#{rows}d \"+ @y + @fmstr\n end\n #@list.each { |e| puts e.join(@y) }\n count = 0\n @list.each_with_index { |r,i| \n value = convert_value_to_text r, count\n buffer << value\n count += 1\n }\n end\n buffer\n end",
"def 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 to_html \n PrettyDiff::HtmlGenerator.generate_diff(chunks)\n end",
"def index\n @submissions = Submission.all\n respond_to do |format|\n format.html\n format.csv { send_data @submissions.as_csv }\n format.xls { send_data @submissions.as_csv(col_sep: \"\\t\") }\n end\n end",
"def show_statistics\n render partial: \"show_statistics_tab\"\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 = \" \" 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 index\n sort = params[:sort_column] || 'id'\n if params[:reverse] == \"true\"\n sort = \"#{sort} DESC\"\n end\n \n @rss_url = response_rss_url(@questionnaire)\n \n @responses = @questionnaire.valid_responses.paginate :page => params[:page]\n \n default_columns = [\"title\", \"submitted_at\", \"notes\"]\n default_columns += @questionnaire.special_field_associations.select { |sfa| sfa.purpose != 'name' }.collect { |sfa| sfa.question }\n default_columns.push(\"id\")\n \n @columns = []\n 1.upto(5) do |i|\n colspec = params[\"column_#{i}\".to_sym]\n thiscol = if colspec\n if md = /^question_(\\d+)$/.match(colspec)\n q = Question.find(md[1])\n if q and q.questionnaire == @questionnaire\n q\n end\n elsif [:id, :submitted_at, :notes].include?(colspec.to_sym)\n colspec\n end\n end\n if thiscol.nil?\n thiscol = default_columns.shift\n end\n @columns.push(thiscol) if thiscol\n end\n\n respond_to do |format|\n format.html { }\n format.js do\n render :update do |page|\n page.replace_html 'responses', :partial => 'response_table'\n end\n end\n format.rss do \n if params[:secret] != @questionnaire.rss_secret\n throw \"Provided secret does not match questionnaire\"\n end\n render :layout => false\n end\n format.csv do\n @responses = @questionnaire.valid_responses\n @columns = @questionnaire.fields\n #@columns = @questionnaire.decorators\n \n stream_csv(@questionnaire.title + \".csv\") do |csv|\n if params[:rotate] == 'true'\n \tcsv << ([\"Nombre\"]+[\"N Trab\"]+[\"Nivel\"]+[\"Modalidad\"])\n csv << ([\"id\"] + @responses.collect { |r| r.id })\n @columns.each do |col|\n csv << ([col.caption] + @responses.collect do |r|\n a = r.answer_for_question(col)\n if a\n a.output_value\n #else\n # \"\"\n end\n end)\n end\n else\n \tcolumnas = []\n \t#ĘCada respuesta en una fila\n \t@questionnaire.valid_responses.each do |resp|\n \t\ti = 0\n \t\t@questionnaire.rows_title.each do |question|\n\t\t\t\tend\n\n \t\t@questionnaire.rows.each do |question|\n \t\t\ti = 0\n \t\t\tagregado = false\n \t\t\t\n \t\t\t\tif question.type =~ /Questions::FormaHead/ \n \t\t\t\t\t\n \t\t\t\t\ti += 1\n \t\t\t\t\tif i == 1 && !agregado\n \t\t\t\t\t\t#i = 0\n \t\t\t\t\t\t#csv << columnas\n \t\t\t\t\t\t#columnas = []\n \t\t\t\t\t\tcolumnas += [question.caption]\n \t\t\t\t\t\tagregado = true\n \t\t\t\t\telsif i != 1 && agregado\n \t\t\t\t\t\tcolumnas += [question.caption]\n \t\t\t\t\t\tif i == 4\n \t\t\t\t\t\t\ti = 0\n \t\t\t\t\t\tend\n \t\t\t\t\tend\t\t\n \t\t\t\telsif question.type =~ /Questions::FormaLab/\n \t\t\t\tend\n \t\tend\n\n# \t\t\tfila = []\n# \t \t\tanswer = resp.answer_for_question(question)\n# \t\t\tif question.type =~ /Questions::Forma/\n# \t \t\t\tif question.type =~/Questions::FormaLab/\n# \t \t \t\tfila +=\t[question.caption]\n# \t\telsif question.type =~/Questions::FormaHead/\n# \t \t\t\t\tfila += [question.caption]\n# \t \t\t\telse\n# \t \t\t\t\tvalue = if answer\n# \t\t\t\t\t\t\tif not @editing\n# \t\t\t\t\t\t\tanswer.output_value\n# \t\t\t\t\t\t\telse\n# \t\t\t\t\t\t\tanswer.value\n# \t\t\t\t\t\t\tend\n# \t\t\t\t\t\telse\n# \t\t\t\t\t\t\t\"\"\n# \t\t\t\t\t\tend\n# \t\t\tfila += [value]\n# \t\tend\n# \t\t\ti = i + 1\n# \t\t\tif i == 4\n# \t\t\t\tcsv << fila\n# \t\t\t\ti = 0\n# \t\t\tend \n# \t\telse\n# \t\t value = if answer\n# \t\t\t\t\t\tif not @editing\n# \t\t\t\t\t\tanswer.output_value\n# \t\t\t\t\t\telse\n# \t\t\t\t\t\tanswer.value\n# \t\t\t\t\t\tend\n# \t\t\t\t\telse\n# \t\t\t\t\t\tnil\n# \t\t\t\t\tend\n# \t\t#fila << value\n# \t\t#csv << render_answer(question, answer)\n# \t\tcsv << [value]\n# \t\tend\n# \t\tend\n\t\t\tend\n\t\t\tcsv << columnas\n \t# #ĘCada respuesta en una fila\n # csv << ([\"id\"] + @columns.collect { |c| c.caption })\n# @responses.each do |resp|\n# csv << ([resp.id] + @columns.collect do |c|\n# a = resp.answer_for_question(c)\n# if a\n# a.output_value\n# #else\n# # \"\"\n# end\n# end)\n# end\n end\n end\n end\n end\n end",
"def before_csv_render\n before_render\n end",
"def export_diff_two_table(case_name, current, expect, error_list)\n pathname = get_path_name(case_name, @report_directory)\n \n book = Spreadsheet::Workbook.new\n sheet1 = book.create_worksheet :name=> case_name\n \n sheet1.row(0).push \"Current Test Table\"\n sheet1.row(0).default_format = @titile_format\n \n curr_row_idx = sheet1.last_row_index + 1 \n export_two_table_to_excel(curr_row_idx, sheet1, current)\n\n idx = sheet1.last_row_index + 1\n sheet1.row(idx).push \"Expect Table\"\n sheet1.row(idx).default_format = @titile_format\n \n expect_row_idx = sheet1.last_row_index + 1 \n export_two_table_to_excel(expect_row_idx, sheet1, expect)\n \n if !error_list.nil?\n handle_error_list(curr_row_idx, expect_row_idx, sheet1, error_list[0])\n handle_error_list(curr_row_idx + current[0].length + 1, expect_row_idx + expect[0].length + 1, sheet1, error_list[1])\n end\n book.write(pathname)\n end",
"def render_collection_as_tabular_list(collection, method_name, label, options = {})\n block_formatting = options.fetch(:block_formatting, false)\n template_type = options.fetch(:template, 'table')\n template = begin\n if template_type == 'dl'\n { tag: 'dd', opener: %(<dt>#{label}</dt>), closer: '' }\n else\n { tag: 'li', opener: %(<tr><th>#{label}</th>\\n<td><ul class=\"tabular\">), closer: '</ul></td></tr>' }\n end\n end\n markup = ''\n\n markup << template.fetch(:opener)\n tag = template.fetch(:tag)\n [collection].flatten.compact.each do |value|\n if respond_to?(\"__render_tabular_list_item_for_#{method_name}\", true) # Need to check for private methods\n markup << send(\"__render_tabular_list_item_for_#{method_name}\", method_name, value, block_formatting, tag, options)\n else\n markup << __render_tabular_list_item(method_name, value, block_formatting, tag, options)\n end\n end\n markup << template.fetch(:closer)\n markup.html_safe\n end",
"def index\n @test_splits = TestSplit.all\n end",
"def split_reactions(outname, ops, composition, stamp_columns)\n coll = ops.first.output(outname).collection\n\n step_1 = \"Place <b>#{coll}-#{TEST}</b> and <b>#{coll}-#{REAL}</b>\"\n step_1 += \" in the same orientation on the bench\"\n\n if stamp_columns.is_a?(Numeric) && stamp_columns > 1\n step_2 = \"Transfer <b>#{composition.qty_display}</b> of\"\n step_2 += \" reaction mix from each microfuge tube\"\n step_2 += \" to the corresponding tube in\"\n step_2 += \" <b>#{coll}-#{TEST}</b>\"\n\n step_3 = \"Transfer <b>#{stamp_columns} #{composition.qty_display} aliquots</b> of\"\n step_3 += \" reaction mix from each microfuge tube\"\n step_3 += \" to the corresponding <b>column</b> in\"\n step_3 += \" <b>#{coll}-#{REAL}</b>\"\n else\n step_2 = \"Transfer <b>#{composition.qty_display}</b> of\"\n step_2 += \" reaction mix from each tube in\"\n step_2 += \" <b>#{coll}-#{TEST}</b> to the corresponding tube in\"\n step_2 += \" <b>#{coll}-#{REAL}</b>\"\n\n step_3 = \"\"\n end\n\n show do\n title \"Split Reactions\"\n check step_1\n check step_2\n check step_3 if step_3.present?\n end\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 display_volume_table items, cult_vol, media_vol\n volume_table = [[\"Cuvette Number\", \"Item ID\", \"Culture Volume to add (uL)\", \"#{MEDIA_TYPE} Media Volume to add (uL)\"]]\n \n first_row = [\"0\", \"N/A\", \"0\", \"#{MAX_CUVETTE_VOLUME}\"]\n volume_table.push(first_row)\n \n i = 1\n items.each do |item|\n curr_row = []\n curr_row.push(i.to_s)\n curr_row.push(item.id.to_s)\n curr_row.push(cult_vol)\n curr_row.push(media_vol)\n volume_table.push(curr_row)\n i += 1\n end\n \n # Displays volume table\n show do\n title \"Fill Plastic Cuvettes\"\n \n note \"Follow the table below to label each cuvette a number for each item id.\"\n table volume_table\n end \n \n end",
"def render_data_grid\n unless block_given?\n return content_tag(:div, render(partial: 'grid', locals: { grid: @grid }), data: { 'controller' => 'grid', 'form' => 'grid_form' }, class: 'grid-container')\n end\n\n content_tag(:div, data: { 'controller' => 'grid', 'form' => 'grid_form' }, class: 'grid-container') do\n yield\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 index\n @tariffs = Tariff.order(:id)\n\n respond_to do |format|\n format.html\n format.csv { send_data @tariffs.to_csv(:col_sep => \";\") }\n end\n end",
"def display\n\t\tdisplay_headers\n\t\t@rows.each do |row|\n\t\t\tdisplay_row(row)\n\t\tend\n\tend",
"def render_data(data)\n # calculate quartiles for plot, use this as data\n @data_quartiles = DATA.collect { |row|\n data = quartiles(row[1])\n OpenStruct.new(\n :name => row[0],\n :q0 => data[0],\n :q1 => data[1],\n :q2 => data[2],\n :q3 => data[3],\n :q4 => data[4],\n :index => 0\n ) \n }\n # NOTE: need index to lay out coloumns horizontally\n @data_quartiles.each_with_index { |d, i|\n d.index = i\n }\n # find limits of data so we know where axes are\n data_min = @data_quartiles.collect { |col| col.q0 }.min()\n data_max = @data_quartiles.collect { |col| col.q4 }.max()\n bounds = bounds([data_min, data_max])\n plot_range = bounds[1] - bounds[0]\n\n \n # make area for plotting\n # left, etc. set padding so actual size is ht/wt + padding\n vis = pv.Panel.new()\n .width(@canvas_wt)\n .height(@canvas_ht)\n .margin(@margin)\n .left(30)\n .bottom(20)\n .top(10)\n .right(10)\n \n # adhoc guess at bar width\n bar_width = @plot_wt / @data_quartiles.size() * 0.8\n \n # scaling to position datapoints in plot\n vert = pv.Scale.linear(bounds[0], bounds[1]).range(0, @plot_ht)\n horiz = pv.Scale.linear(0, @data_quartiles.size()).range(0, @plot_wt)\n\n # where to draw labels on graph\n label_ticks = vert.ticks.each_slice(4).map(&:first)\n\n # make horizontal lines:\n # - what values are drawn\n # - where the bottom of it appears\n # - what color to make the line\n # - the width of the line\n # - antialias it?\n # - add a label\n # - where does label appear relative to line\n # - how is the text aligned in own space\n # - align text vertically (\"top\" looks like \"middle\")\n # - what appears in the label\n vis.add(pv.Rule)\n .data(vert.ticks()) \n .bottom(lambda {|d| vert.scale(d)}) \n .strokeStyle(lambda { |d| label_ticks.member?(d) ? \"black\" : \"lightblue\" })\n .line_width(lambda { |d| label_ticks.member?(d) ? 0.5 : 0.1 })\n .antialias(true)\n .add(pv.Label) \n .left(0) \n .textAlign(\"right\")\n .textBaseline(\"top\")\n .text(lambda {|d| label_ticks.member?(d) ? sprintf(\"%0.2f\", d) : '' }) \n \n # y (vertical) axis\n vis.add(pv.Rule)\n .data([0])\n .left(horiz.scale(0))\n .bottom(@margin)\n .strokeStyle(\"black\")\n \n # make the main body of boxplot\n vis.add(pv.Rule)\n .data(@data_quartiles)\n .left(lambda {|d| horiz.scale(d.index + 0.5) })\n .bottom(lambda {|d| vert.scale(d.q1)})\n .lineWidth(bar_width)\n .height(lambda {|d| vert.scale(d.q3) - vert.scale(d.q1)})\n .strokeStyle(@bar_clr)\n\n # add bottom labels\n vis.add(pv.Label)\n .data(@data_quartiles)\n .left(lambda {|d| horiz.scale(d.index + 0.5) })\n .bottom(0)\n .text_baseline(\"top\")\n .text_margin(15)\n .textAlign(\"center\")\n .text(lambda {|d| d.name })\n\n # make the whisker \n vis.add(pv.Rule)\n .data(@data_quartiles)\n .left(lambda {|d| horiz.scale(d.index + 0.5)})\n .bottom(lambda {|d| vert.scale(d.q0)})\n .lineWidth(1)\n .height(lambda {|d| vert.scale(d.q4) - vert.scale(d.q0)})\n .strokeStyle(@bar_clr)\n\n # make the median line \n vis.add(pv.Rule)\n .data(@data_quartiles)\n .left(lambda {|d| horiz.scale(d.index + 0.5)})\n .bottom(lambda {|d| vert.scale(d.q2)})\n .height(1)\n .lineWidth(bar_width)\n .strokeStyle(\"white\")\n \n vis.render()\n return vis.to_svg()\n end",
"def show_table(table, repository: nil, nested: nil)\n\n columns = %w(Item Value)\n prefix = repository ? \"about-#{repository}\" : 'about'\n div_opt = { class: \"#{prefix}-table-container\" }\n table_opt = { class: \"#{prefix}-table\" }\n\n if table.is_a?(Hash)\n # Turn off <thead> if nested.\n table_opt[:class] += ' nested' if nested\n thead = !nested\n colgroup = true\n else\n # Translate the array into a key/value pair form that will be iterated\n # over the same way a Hash is.\n unless table.is_a?(Array)\n logger.warn { \"#{__method__}: #{table.class}: should be Enumerable\" }\n end\n table = Array.wrap(table).map { |v| [nil, v] }\n thead = colgroup = false\n end\n\n # The <table> element inside a container.\n content_tag(:div, div_opt) do\n content_tag(:table, table_opt) do\n\n # Define columns with a distinct CSS class for styling.\n colgroup &&=\n content_tag(:colgroup) do\n (1..columns.size).map { |i|\n content_tag(:col, '', class: \"col#{i}\")\n }.join.html_safe\n end\n\n # Table header if requested and table is a hash.\n thead &&=\n content_tag(:thead) do\n columns.map { |x|\n content_tag(:th, h(x), class: 'heading')\n }.join.html_safe\n end\n\n # Table body in which Enumerable values are handled as nested tables.\n tbody =\n content_tag(:tbody) do\n table.map { |k, v|\n nested_table =\n case v\n when Hash then v.present?\n when Array then v.first.is_a?(Enumerable) || (v.size > 2)\n end\n content_tag(:tr) do\n k = k&.to_s\n v = nested_table ? show_table(v, nested: true) : v.inspect\n [k, v].map { |x|\n content_tag(:td, h(x), class: 'cell') if x\n }.join.html_safe\n end\n }.join(\"\\n\").html_safe\n end\n\n [colgroup, thead, tbody].reject(&:blank?).join(\"\\n\").html_safe\n end\n end\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 table_test\n @pdf.table( [[\"foo\", \"bar\", \"bazbaz\"], [\"1\", \"2\", \"3\"], [\"1\", \"2\", \"3\"], [\"1\", \"2\", \"3\"]],\n :cell_style => { :padding => 12 }, :width => @pdf.bounds.width)\n\n @pdf.move_down 12\n \n @pdf.table([[\"foo\", \"bar \" * 15, \"baz\"],\n [\"baz\", \"bar\", \"foo \" * 15]], :cell_style => { :padding => 12 }) do\n cells.borders = []\n\n # Use the row() and style() methods to select and style a row.\n style row(0), :border_width => 2, :borders => [:bottom]\n\n # The style method can take a block, allowing you to customize\n # properties per-cell.\n style(columns(0..1)) { |cell| cell.borders |= [:right] }\n end\n \n header = %w[Name Occupation]\n data = [\"Bender Bending Rodriguez\", \"Bender\"]\n\n @pdf.table([header] + [data] * 50, :header => true) do\n #row(0).style(:font_style => :bold, :background_color => 'cccccc')\n end\n\n end",
"def ltab\n horizontals_reset\n @vertical = @layout.createBaselineGroup(true, false)\n end",
"def gen_view(filename, addr_from, addr_to, line_from, line_to, split_files, row_div_arg, addr_div_arg, verbose = false)\n\tputs \"\\nGenerating preview ...\"\n\t\n\tbegin\n\t\th = {}\n\t\trow = -1\n\t\t\n\t\tputs \"\\n\\tFilling hash tree ...\" if verbose # fill hash tree\n\t\tFile.open(filename, 'rb').each do |line|\n\t\t\trow += 1\n\t\t\tnext if row < line_from\n\t\t\t\n\t\t\twords = line.split(/\\W+/)\n\t\t\taddr = words[1].hex\n\t\t\tnext if addr < addr_from or addr > addr_to\n\t\t\t\n\t\t\tnode = h\n\t\t\t\n\t\t\t(2*GS[:addr_len]-1).downto(0) do |i|\n\t\t\t\tk = ((addr >> (4*i)) & 0xf)\n\t\t\t\tnode[k] = {} unless node.has_key? k\n\t\t\t\tnode = node[k]\n\t\t\tend\n\t\t\t\n\t\t\tnode[:data] = [] if node[:data].nil?\n\t\t\tnode[:data] << {row: row, addr: addr, length: words[2].hex, val: 1}\n\t\t\t\n\t\t\tnode[:dumb0] = 0; node[:dumb1] = 0; node[:dumb2] = 0; node[:dumb3] = 0; node[:dumb4] = 0; node[:dumb5] = 0; node[:dumb6] = 0; node[:dumb7] = 0; node[:dumb8] = 0; node[:dumb9] = 0; node[:dumba] = 0; node[:dumbb] = 0; node[:dumbc] = 0; node[:dumbd] = 0; node[:dumbe] = 0; node[:dumbf] = 0;\n\t\t\t\n\t\t\tbreak if row > line_to\n\t\tend\n\t\t\n\t\trow_div = row_div_arg.nil? ? ((row - line_from)/GRAPH_HEIGHT + 1) : row_div_arg.hex\n\t\t\n\t\tputs \"\\tSplitting tree ...\" if verbose # find important nodes\n\t\tnodes = [h]\n\t\tsingletons = []\n\t\tbegin\n\t\t\t# find a node with minimum subnodes\n\t\t\tminimal = nodes.min_by{|node|node.length}\n\t\t\tbreak if minimal.has_key?(:data) or (nodes.length + minimal.length - 2 > split_files)\n\t\t\t# replace it with these nodes\n\t\t\tnodes.delete_if{|node|node == minimal}\n\t\t\tminimal.each do |key, value|\n\t\t\t\tnodes << value\n\t\t\tend\n\t\t\t# go deeper if any node has single subnode\n\t\t\tbegin\n\t\t\t\tchange = false\n\t\t\t\tnodes.select{|no|no.length == 1}.each do |single|\n\t\t\t\t\tnodes.delete_if{|node|node == single}\n\t\t\t\t\tnodes << single.values.first\n\t\t\t\t\tchange = true\n\t\t\t\tend\n\t\t\tend while change\n\t\t\t# move singletons\n\t\t\tnodes.select{|no|no.has_key? :data}.each do |singleton|\n\t\t\t\tnodes.delete_if{|node|node == singleton}\n\t\t\t\tsingletons << singleton\n\t\t\tend\n\t\tend while nodes.length < split_files\n\t\t\n\t\tfilenames = []\n\t\tputs \"\\tGenerating plots ...\" if verbose # generate plots\n\t\tnodes.each do |node|\n\t\t\tputs \"\\t----------------\\n\\tStarting new node\" if verbose\n\t\t\tstart = node\n\t\t\tstop = node\n\t\t\twhile not start.has_key? :data\n\t\t\t\tstart = start[start.keys.sort.first]\n\t\t\tend\n\t\t\twhile not stop.has_key? :data\n\t\t\t\tstop = stop[stop.keys.sort.last]\n\t\t\tend\n\t\t\tstart_addr = start[:data].first[:addr]\n\t\t\tstop_addr = stop[:data].first[:addr]\n\t\t\t\n\t\t\taddr_div = addr_div_arg.nil? ? ((stop_addr - start_addr)/GRAPH_WIDTH + 1) : addr_div_arg.hex\n\t\t\t\n\t\t\tputs \"\\tAdding points to %0#{2*GS[:addr_len]}x--%0#{2*GS[:addr_len]}x\" % [start_addr, stop_addr] if verbose\n\t\t\tp = Plot.new\n\t\t\t\n\t\t\tadd_node_to_plot(node, p, start_addr, line_from, addr_div, row_div)\n\t\t\t\n\t\t\tputs \"\\tTop line: #{line_from}\\n\\tLines per pixel: #{row_div}\\n\\tLeftmost address: #{\"0x%x\" % start_addr}\\n\\tAddresses per pixel: #{addr_div}\" if verbose\n\t\t\t\n\t\t\tputs \"\\tPlotting %0#{2*GS[:addr_len]}x--%0#{2*GS[:addr_len]}x\" % [start_addr, stop_addr] if verbose\n\t\t\toutfile = \"#{filename}__%0#{2*GS[:addr_len]}x--%0#{2*GS[:addr_len]}x__#{row_div}x#{addr_div}.png\" % [start_addr, stop_addr]\n\t\t\tp.plot(outfile)\n\t\t\tfilenames << outfile\n\t\tend\n\t\t\n\t\treturn filenames\n\t\t\n\trescue Errno::ENOENT\n\t\t$stderr.puts \"File '\" + filename + \"' does not exist!\"\n\tend\nend",
"def split_tsv(tsv_file_name)\n main_file = File.open tsv_file_name\n # Get the headers and store them for later\n headers = main_file.gets\n # Count the number of lines in the file\n length_of_file = 0\n main_file.each_line do\n length_of_file += 1\n end\n main_file.close\n # Split the main tsv into several smaller tsvs. First figure out how many.\n number_of_tsvs = ((length_of_file.to_f)/(50000.to_f)).ceil\n sub_tsvs = Array.new\n file_names = Array.new\n # Create each file and write the headers to each\n number_of_tsvs.times do |i|\n file_name = Rails.root.join('db', 'subsets', 'data_' + (i+1).to_s + '.tsv')\n file_names << file_name\n # Delete the sub file if it already exists and regenerate\n File.delete file_name if File.file? file_name\n tsv = File.open file_name, 'w'\n tsv.write headers\n sub_tsvs << tsv\n end\n # Write 50000 lines to each file\n i = 0\n main_file = File.open tsv_file_name\n main_file.each_line do |line|\n sub_tsvs[((i.to_f)/(50000.to_f)).floor].write line if i > 0\n i += 1\n end\n # Close each sub tsv file\n sub_tsvs.each do |file|\n file.close\n end\n # Return the list of file names\n file_names\nend",
"def index\n #obtiene todos los registros de la tabla client\n #cambiar el 5 por el numero de elementos por pagiba\n @clients = Client.order(sort_column + \" \" + sort_diection).search(params[:search]).paginate(:per_page => 30, :page => params[:page])\n \n\n respond_to do |format|\n format.html\n format.json { render json: @clients }\n format.csv { send_data text: @clients.to_csv }\n format.xls \n format.pdf {render template: 'clients/reporte', pdf: 'Clientes', layout: 'pdf.html'}#, header: { right: 'Página [page] de [topage]' }}\n end\n end",
"def weafam_search_logs\n @search_service_logs = SearchServiceLogs.order('id DESC')\n respond_to do |format|\n format.html\n format.csv { render text: @search_service_logs.to_csv(:col_sep => \"\\t\") }\n format.xls { send_data @search_service_logs.to_csv(col_sep: \"\\t\") }\n end\n\n # respond_to do |format|\n # format.csv { render csv: @search_service_logs.to_csv }\n # # format.xls {render xls: 'weafam_search_logs',filename: \"weafam_search_logs.xls\"}\n # format.xls {render xls: 'weafam_search_logs',filename: \"weafam_search_logs.xls\"}\n # # format.xls { send_data @weafam_stats.to_csv(col_sep: \"\\t\") }\n # format.xlsx {render xlsx: 'download',filename: \"payments.xlsx\"}\n #\n # end\n\n end",
"def datagrid_table(report, *args)\n datagrid_renderer.table(report, *args)\n end",
"def index\n @sub_data_tables = SubDataTable.all\n end",
"def index\n @loads = @loads.group_by(&:genuine?)[true]\n @loads_by_date = @loads.group_by(&:date)\n # @date = params[:date] || @loads_by_date.keys.sort.last\n @date = params[:date] || 2020\n @loads = @loads_by_date[@date.to_i]\n @title = \"Timetable\"\n# @title = \"Provisional #{@title}\" if @date.to_i > 2019\n\n respond_to do |format|\n format.html # index.html.erb\n format.csv { send_data Load.to_csv(@loads) }\n format.json { render json: @loads }\n format.xls { send_data Load.to_xls(@loads), content_type: 'application/vnd.ms-excel' }\n end\n end",
"def index\n @datatable = InventoryMovementsDatatable.new\n respond_to do |format|\n format.html\n format.csv do\n day_before_start_date = (@imr_start_date <= @initial_date) ? DateTime.now.end_of_day : (@imr_start_date.to_datetime - 1.day).end_of_day\n ekanek = Organisation::EKANEK_ORG\n a3m = Organisation::A3M_ORG\n params[:organisation_id] = params[:organisation_id].to_i\n\n # \"Brand Name\", \"Brand Owner\", \"Item Name\", \"Item Type\", \"MRP\", \"GWP/Surprise\"\n brand_name_hash, brand_owner_hash, name_hash, item_type_hash, mrp_hash, gwp_surprise_hash = Sku.create_item_detail_hashes\n\n # Opening Stock\n organisation_ids = params[:organisation_id] == 0 ? [ekanek.id, a3m.id] : params[:organisation_id]\n opening_stock_quantity_hash, opening_stock_value_hash = InventoryItem.create_opening_stock_hashes(day_before_start_date, organisation_ids)\n\n organisation_ids = (params[:organisation_id].in? [0, ekanek.id]) ? [ekanek.id, a3m.id] : params[:organisation_id]\n # Total Purchase = 1. Putaway GRN Items\n sku_purchased_quantity_hash, sku_purchased_value_hash = InventoryItem.create_purchased_hashes(@imr_start_date, @imr_end_date, organisation_ids)\n # Bad purchase = 1. Putaway GRN Items Bad\n sku_bad_qty_purchased_hash, sku_bad_value_purchased_hash = InventoryItem.create_bad_purchased_hashes(@imr_start_date, @imr_end_date, organisation_ids)\n\n organisation_id = params[:organisation_id] == 0 ? a3m.id : params[:organisation_id]\n # 2. Putaway Returned by Customers\n sku_quantity_returned_by_customers_hash, sku_value_returned_by_customers_hash = InventoryItem.create_returned_by_customer_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # 2. Putaway Returned by Customers Bad\n sku_qty_bad_stock_returned_by_customer_hash, sku_value_bad_stock_returned_by_customer_hash = InventoryItem.create_bad_returned_by_customer_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # Sold\n sku_quantity_sold_hash, sku_value_sold_hash = InventoryItem.create_sold_hashes(@imr_start_date, @imr_end_date, organisation_id)\n\n # Gatepasses\n organisation_id = params[:organisation_id] == 0 ? ekanek.id : params[:organisation_id]\n sku_quantity_returned_to_vendor_hash, sku_value_returned_to_vendor_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'rtv', organisation_id)\n sku_self_consumed_quantity_hash, sku_self_consumed_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'self_consumption', organisation_id)\n sku_quantity_sent_for_brand_collabs_hash, sku_value_sent_for_brand_collabs_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'brand_collabs', organisation_id)\n sku_quantity_sent_to_agency_hash, sku_value_sent_to_agency_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'agency', organisation_id)\n sku_gift_quantity_hash, sku_gift_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'gift', organisation_id)\n sku_quantity_liquidated_hash, sku_value_liquidated_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'liquidation', organisation_id)\n sku_stock_transfer_quantity_hash, sku_stock_transfer_value_hash = InventoryItem.create_gatepass_reason_hashes(@imr_start_date, @imr_end_date, 'stock_transfer', organisation_id)\n # Bad Gatepasses\n sku_bad_qty_gatepass_hash, sku_bad_value_gatepass_hash = InventoryItem.create_bad_gatepass_hashes(@imr_start_date, @imr_end_date, organisation_id)\n # Blocked Qty\n sku_blocked_qty_hash = Inventory.create_sku_blocked_qty_hash\n\n require 'csv'\n filename = \n case params[:organisation_id].to_i\n when 0\n 'Consolidated-IMR.csv'\n when ekanek.id\n 'EkAnek-IMR.csv'\n when a3m.id\n 'A3M-IMR.csv'\n end\n\n CSV.open(\"#{filename}\", \"wb\") do |response_csv|\n response_csv << [\"SKU ID\", \"Brand Name\", \"Brand Owner\", \"Item Name\", \"Item Type\", \"MRP\", \"GWP/Surprise\", \"Opening Stock Qty\", \"Opening Stock Value\", \"Qty Purchased\", \"Value Purchased\",\n \"Qty Returned By Customer\", \"Value Returned By Customer\", \"Total Putaway Qty\", \"Total Putaway Value\",\n \"Qty Sold\", \"Value Sold\", \"Qty Returned to Vendor\", \"Value Returned to Vendor\", \"Qty Used for Self Consumption\",\n \"Value Used for Self Consumption\", \"Qty used for Brand Collabs\", \"Value used for Brand Collabs\", \"Qty sent to Agency\",\n \"Value sent to Agency\", \"Qty used as Gift\", \"Value used as Gift\", \"Qty Liquidated\", \"Value Liquidated\",\n \"Stock Transfer Qty\", \"Stock Transfer Value\", \"Gatepass Bad Qty\", \"Gatepass Bad Value\", \"Total Gatepass\", \"Total Gatepass Value\", \"Stock Adjustment\",\n \"Closing Stock Qty\", \"Closing Stock Value\" , \"Good Qty\", \"Good Qty Value\", \"Bad Qty\", \"Bad Qty Value\", \"Qty Blocked\"]\n\n skus = InventoryItem.pluck(:sku_id).uniq\n skus.each do |sku_id|\n report = []\n report << sku_id\n sku = Sku.find sku_id\n\n report << brand_name_hash[sku_id]\n report << brand_owner_hash[sku_id]\n report << name_hash[sku_id]\n report << item_type_hash[sku_id]\n report << mrp_hash[sku_id]\n report << gwp_surprise_hash[sku_id]\n\n opening_stock_quantity = (@imr_start_date <= @initial_date) ? 0 : opening_stock_quantity_hash[sku_id].to_i\n opening_stock_value = (@imr_start_date <= @initial_date) ? 0 : opening_stock_value_hash[sku_id].to_f\n report << opening_stock_quantity\n report << opening_stock_value\n report << sku_purchased_quantity_hash[sku_id].to_i\n report << sku_purchased_value_hash[sku_id].to_f\n report << sku_quantity_returned_by_customers_hash[sku_id].to_i\n report << sku_value_returned_by_customers_hash[sku_id].to_f\n total_putaway_qty = sku_purchased_quantity_hash[sku_id].to_i + sku_quantity_returned_by_customers_hash[sku_id].to_i\n total_putaway_value = sku_purchased_value_hash[sku_id].to_f + sku_value_returned_by_customers_hash[sku_id].to_f\n report << total_putaway_qty\n report << total_putaway_value\n report << sku_quantity_sold_hash[sku_id].to_i\n report << sku_value_sold_hash[sku_id].to_f\n report << sku_quantity_returned_to_vendor_hash[sku_id].to_i\n report << sku_value_returned_to_vendor_hash[sku_id].to_f\n report << sku_self_consumed_quantity_hash[sku_id].to_i\n report << sku_self_consumed_value_hash[sku_id].to_f\n report << sku_quantity_sent_for_brand_collabs_hash[sku_id].to_i\n report << sku_value_sent_for_brand_collabs_hash[sku_id].to_f\n report << sku_quantity_sent_to_agency_hash[sku_id].to_i\n report << sku_value_sent_to_agency_hash[sku_id].to_f\n report << sku_gift_quantity_hash[sku_id].to_i\n report << sku_gift_value_hash[sku_id].to_f\n report << sku_quantity_liquidated_hash[sku_id].to_i\n report << sku_value_liquidated_hash[sku_id].to_f\n report << sku_stock_transfer_quantity_hash[sku_id].to_i\n report << sku_stock_transfer_value_hash[sku_id].to_f\n report << sku_bad_qty_gatepass_hash[sku_id].to_i\n report << sku_bad_value_gatepass_hash[sku_id].to_f\n total_gp_qty = sku_quantity_returned_to_vendor_hash[sku_id].to_i +\n sku_self_consumed_quantity_hash[sku_id].to_i +\n sku_quantity_sent_for_brand_collabs_hash[sku_id].to_i +\n sku_quantity_sent_to_agency_hash[sku_id].to_i +\n sku_gift_quantity_hash[sku_id].to_i +\n sku_quantity_liquidated_hash[sku_id].to_i +\n sku_stock_transfer_quantity_hash[sku_id].to_i +\n sku_bad_qty_gatepass_hash[sku_id].to_i\n total_gp_value = sku_value_returned_to_vendor_hash[sku_id].to_f +\n sku_self_consumed_value_hash[sku_id].to_f +\n sku_value_sent_for_brand_collabs_hash[sku_id].to_f +\n sku_value_sent_to_agency_hash[sku_id].to_f +\n sku_gift_value_hash[sku_id].to_f +\n sku_value_liquidated_hash[sku_id].to_f +\n sku_stock_transfer_value_hash[sku_id].to_f +\n sku_bad_value_gatepass_hash[sku_id].to_f\n report << total_gp_qty\n report << total_gp_value\n report << 0 # stock adjustment 0 for now\n\n inwarded_quantity = total_putaway_qty\n inwarded_value = total_putaway_value\n\n outwarded_quantity = sku_quantity_sold_hash[sku_id].to_i + total_gp_qty\n outwarded_value = sku_value_sold_hash[sku_id].to_f + total_gp_value\n\n closing_stock_quantity = opening_stock_quantity + inwarded_quantity - outwarded_quantity\n closing_stock_value = opening_stock_value + inwarded_value - outwarded_value\n\n # total_bad = putaway_grn_bad + putaway_return_bad - gatepass_bad\n bad_qty = sku_bad_qty_purchased_hash[sku_id].to_i +\n sku_qty_bad_stock_returned_by_customer_hash[sku_id].to_i -\n sku_bad_qty_gatepass_hash[sku_id].to_i\n bad_stock_value = sku_bad_value_purchased_hash[sku_id].to_f +\n sku_value_bad_stock_returned_by_customer_hash[sku_id].to_f -\n sku_bad_value_gatepass_hash[sku_id].to_f\n\n good_qty = closing_stock_quantity - bad_qty\n good_stock_value = closing_stock_value - bad_stock_value\n\n report << closing_stock_quantity\n report << closing_stock_value\n report << good_qty\n report << good_stock_value\n report << bad_qty\n report << bad_stock_value\n report << sku_blocked_qty_hash[sku_id].to_i\n response_csv << report\n end\n\n send_file(\n \"#{filename}\",\n filename: \"#{filename}\",\n )\n end\n end\n end\n end",
"def diff(table, wait_time = Capybara.default_max_wait_time, ignore_case: false)\n to_table = self.to_table\n\n if ignore_case == true\n table = Cucumber::MultilineArgument::DataTable.from(downcase_array(table.raw))\n to_table = downcase_array(to_table)\n end\n\n table.diff!(to_table) || true\n end",
"def table_1\n @table1 = read_table(File.join(FILE_PATH, \"Lgr_prelim_FPKM.txt\"))\n #send_file(File.join(FILE_PATH, \"Lgr_prelim_FPKM.txt\"), :type => 'text/csv', :disposition => 'inline')\n end",
"def index\n @currentunits = Currentunit.all\n respond_to do |format|\n format.html\n format.csv { send_data @currentunits.to_csv }\n format.xls { send_data @currentunits.to_csv(col_sep: \"\\t\")}\n end\n end",
"def draw_table new_header=:keep_header\n if @column_widths\n table @data, header: true, position: :center, column_widths: @column_widths\n else\n table @data, header: true, position: :center\n end\n\n if new_header.is_a?(Array)\n @data = [new_header]\n @header = new_header\n elsif new_header == :keep_header\n @data = [@header]\n else\n @data = []\n end\n\n move_down 20\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Produce some output for the ERB template\n @sections = []\n\n @space_to_thermal_zone_section = {}\n @sections << @space_to_thermal_zone_section\n @space_to_thermal_zone_section[:title] = \"Mapping Spaces to ThermalZones\"\n space_tz_tables = []\n @space_to_thermal_zone_section[:tables] = space_tz_tables\n space_tz_table = {}\n space_tz_table[:title] = 'Space to Thermal Zones'\n columns = ['Space', 'Zone']\n space_tz_table[:header] = columns\n space_tz_table[:data] = []\n model.getSpaces.each do |s|\n tz = 'None'\n if !s.thermalZone.empty?\n tz = s.thermalZone.get.nameString\n end\n space_tz_table[:data] << [s.nameString, tz]\n end\n space_tz_tables << space_tz_table\n\n @space_lpd_section = {}\n @sections << @space_lpd_section\n @space_lpd_section[:title] = \"Spaces LPD\"\n lpd_tables = []\n @space_lpd_section[:tables] = lpd_tables\n lpd_table = {}\n lpd_table[:title] = 'Space to Thermal Zones'\n columns = ['Space', 'LPD']\n lpd_table[:header] = columns\n lpd_table[:units] = ['', 'W/m2']\n lpd_table[:chart_type] = 'vertical_grouped_bar'\n lpd_table[:chart] = []\n lpd_table[:data] = []\n lpd_table[:chart_attributes] = { label_x: 'Space Name', value: 'LPD (W/m2' }\n model.getSpaces.each do |s|\n lpd_table[:data] << [s.nameString, s.lightingPowerPerFloorArea]\n lpd_table[:chart] << JSON.generate(label_x: s.nameString, value: s.lightingPowerPerFloorArea)\n end\n lpd_tables << lpd_table\n\n\n # read in template\n template_name = \"report.html.erb\"\n html_in_path = \"#{File.dirname(__FILE__)}/resources/#{template_name}\"\n html_in = File.open(html_in_path, 'r') { |f| f.read }\n\n # configure template with variable values\n # And enable trim mode\n renderer = ERB.new(html_in, nil, '-')\n html_out = renderer.result(binding)\n runner.registerWarning(@sections.to_s)\n # either /tmp/osmodel-1622719126-1/ApplyMeasureNow\n # or ./<model_companion_dir>/\n rootDir = runner.workflow.absoluteRootDir.to_s\n\n html_out_path = 'report.html'\n if (File.basename(rootDir) == 'ApplyMeasureNow')\n html_out_path = File.absolute_path(\n File.join(rootDir, '..', 'resources', 'reports', html_out_path))\n else\n html_out_path = File.absolute_path(\n File.join(rootDir, 'reports', html_out_path))\n end\n outDir = File.dirname(html_out_path)\n if !File.exists?(outDir)\n FileUtils.mkdir_p(outDir)\n end\n\n runner.registerWarning(\"File.dirname(__FILE__)=#{File.dirname(__FILE__)}\")\n runner.registerWarning(\"html_out_path=#{html_out_path}\")\n runner.registerWarning(\"File.realpath('./')=#{File.realpath('./')}\")\n runner.registerWarning(\"File.absolute_path('.')=#{File.absolute_path('.')}\")\n runner.registerWarning(\"runner.workflow.absoluteRootDir=#{runner.workflow.absoluteRootDir}\")\n runner.registerWarning(\"runner.workflow.filePaths=#{runner.workflow.filePaths.map{|p| p.to_s}}\")\n\n File.open(html_out_path, 'w') do |file|\n file << html_out\n # make sure data is written to the disk one way or the other\n begin\n file.fsync\n rescue\n file.flush\n end\n end\n\n # report final condition of model\n runner.registerFinalCondition(\"Saved HTML to #{html_out_path}.\")\n\n return true\n end",
"def show_column\n @dataset = Dataset.find(params[:dataset_id])\n @variable = Variable.find(params[:variable_id])\n @data = ActiveRecord::Base.connection.select_all(\"SELECT var#{@dataset.identifierccode1_var} as ccode, var#{@dataset.identifieryear_var} as year, var#{@variable.var_id} as data from dataset_#{@dataset.id} ORDER BY var#{@dataset.identifierccode1_var} , var#{@dataset.identifieryear_var} \")\n @pays = ActiveRecord::Base.connection.select_values(\"SELECT var#{@dataset.identifierccode1_var} as ccode from dataset_#{@dataset.id} group by var#{@dataset.identifierccode1_var} ORDER BY var#{@dataset.identifierccode1_var} ASC\")\n @annees = ActiveRecord::Base.connection.select_values(\"SELECT var#{@dataset.identifieryear_var} as annee from dataset_#{@dataset.id} group by var#{@dataset.identifieryear_var} ORDER BY var#{@dataset.identifieryear_var} ASC\")\n @tableau = Array.new\n for annee in @annees\n @tableau[annee.to_i] = Hash.new()\n @pays.each do |pays|\n @tableau[annee.to_i][pays.to_i] = \"#\"\n end\n end\n \n for ligne in @data # pour chaque ligne (annee-pays) du tableau de donnees\n @tableau[ligne['year'].to_i][ligne['ccode'].to_i] = case when ligne['data'] == nil then nil else ligne['data'].to_f end\n end\n render :inline => @tableau[1870..2003].to_json + @annees.to_json\n end",
"def generate_table(name, data_set1, data_set2 , data_set3, data_set4 , assignment_names,data_set1_name , data_set2_name, data_set3_name, data_set4_name )\n table = \"#{name}\"\n\n table << \"<br/><table border='1' align='left'>\"\n\n table << \"<tr><td></td>\"\n assignment_names.each_with_index do |assignment,index|\n table << \"<td>(#{index+1})#{assignment}</td>\"\n end\n\n color = '#'+COLOR_1+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set1_name}</td>\"\n data_set1.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n color = '#'+COLOR_2+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set2_name}</td>\"\n data_set2.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n if(data_set3)\n color = '#'+COLOR_3+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set3_name}</td>\"\n data_set3.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n if(data_set4)\n color = '#'+COLOR_4+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set4_name}</td>\"\n data_set4.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n table << \"</tr></table>\"\n @table = table\n end",
"def employee_tables\n @record.employees.each do |employee|\n h3 employee.full_name\n info_table(employee)\n contacts_table(employee)\n end\n end",
"def index\n @differents = Different.all\n end",
"def index\n @departamento = Departamento.new\n @departamentos = Departamento.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @departamentos }\n format.xls { send_data @departamentos.to_xls(\n :columns => [ :id, :descripcion, :pais, :created_at, :updated_at],\n :headers => [ \"ID\", \"Descripcion\", \"Pais\", \"Fecha de Creacion\", \"Fecha de actualizacion\"] ),\n :filename => 'departamento.xls' }\n format.pdf { render_departamento_list(@departamentos) }\n end\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.4883502",
"0.48813608",
"0.4879545",
"0.48583278",
"0.48506108",
"0.48342782",
"0.48188177",
"0.48187333",
"0.4817584",
"0.48160848",
"0.4813984",
"0.480516",
"0.48039618",
"0.48000497",
"0.4795213",
"0.47947976",
"0.47903544",
"0.4789713",
"0.4786454",
"0.4780799",
"0.4775766",
"0.47748762",
"0.4774256",
"0.47738752",
"0.47738752",
"0.4767503",
"0.47668412",
"0.47663498",
"0.47553477",
"0.47536227",
"0.47535118",
"0.47508007",
"0.47458956",
"0.4744386",
"0.47364652",
"0.47358444",
"0.4731434",
"0.47200617",
"0.47165075",
"0.47025707",
"0.46971244",
"0.4694802",
"0.4691968",
"0.46913096",
"0.46862894",
"0.46738675",
"0.46559128",
"0.4644672",
"0.46386513",
"0.46218586",
"0.4620691",
"0.46188608",
"0.46183392",
"0.4617621",
"0.4610442",
"0.46099508",
"0.4609489",
"0.46058425",
"0.45949957",
"0.45878",
"0.45871514",
"0.45857653",
"0.4579592",
"0.45762634",
"0.45709333",
"0.45708603",
"0.4570664",
"0.4566257",
"0.4565252",
"0.4565118"
] | 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 # pk=@pkList.join(',')\n # # add index\n # q=\"create index ix_#{tableName}t on #{tableName} (#{pk},branch_name);\"\n # pp q\n # DBConn.exec(q)\n end",
"def rebuild_table\n @database.execute(\"SELECT ZICCLOUDSYNCINGOBJECT.ZMERGEABLEDATA1 \" +\n \"FROM ZICCLOUDSYNCINGOBJECT \" +\n \"WHERE ZICCLOUDSYNCINGOBJECT.ZIDENTIFIER=?\",\n @uuid) do |row|\n\n # Extract the blob\n gzipped_data = row[\"ZMERGEABLEDATA1\"]\n zlib_inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 16)\n gunzipped_data = zlib_inflater.inflate(gzipped_data)\n\n # Read the protobuff\n mergabledata_proto = MergableDataProto.decode(gunzipped_data)\n\n # Build list of key items\n @key_items = Array.new\n mergabledata_proto.mergable_data_object.mergeable_data_object_data.mergeable_data_object_key_item.each do |key_item|\n @key_items.push(key_item)\n end\n\n # Build list of type items\n @type_items = Array.new\n mergabledata_proto.mergable_data_object.mergeable_data_object_data.mergeable_data_object_type_item.each do |type_item|\n @type_items.push(type_item)\n end\n\n # Build list of uuid items\n @uuid_items = Array.new\n mergabledata_proto.mergable_data_object.mergeable_data_object_data.mergeable_data_object_uuid_item.each do |uuid_item|\n @uuid_items.push(uuid_item)\n end\n\n # Build Array of objects\n @table_objects = Array.new\n mergabledata_proto.mergable_data_object.mergeable_data_object_data.mergeable_data_object_entry.each do |mergeable_data_object_entry|\n @table_objects.push(mergeable_data_object_entry)\n\n # Best way I've found to set the table direction\n if mergeable_data_object_entry.custom_map\n if mergeable_data_object_entry.custom_map.map_entry.first.key == @key_items.index(\"crTableColumnDirection\") + 1 #Oddly seems to correspond to 'self'\n @table_direction = mergeable_data_object_entry.custom_map.map_entry.first.value.string_value\n end\n end\n end\n\n # Find the first ICTable, which shuld be the root, and execute\n mergabledata_proto.mergable_data_object.mergeable_data_object_data.mergeable_data_object_entry.each do |mergeable_data_object_entry|\n if mergeable_data_object_entry.custom_map and @type_items[mergeable_data_object_entry.custom_map.type] == \"com.apple.notes.ICTable\"\n parse_table(mergeable_data_object_entry)\n end\n end\n end\n end",
"def left_table; table_sync.left_table; end",
"def right_table; table_sync.right_table; end",
"def test_table_too\n return <<HERE;\n 2 3 5 7 11\n 2 4 6 10 14 22\n 3 6 9 15 21 33\n 5 10 15 25 35 55\n 7 14 21 35 49 77\n 11 22 33 55 77 121\nHERE\nend",
"def rebuild(table); end",
"def table\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 split_job() \n number_of_real_process = @cores * 2\n number_of_columns_to_render = @job.ending_column - @job.starting_column\n\n number_of_jobs_that_we_want_to_create = number_of_real_process\n if((number_of_columns_to_render/number_of_real_process) < 1) \n number_of_jobs_that_we_want_to_create = number_of_columns_to_render\n end\n\n @subjobs = generate_subjobs(number_of_jobs_that_we_want_to_create) \n end",
"def test_table\n return <<HERE;\n 2 3 5 7 11\n 3 9 15 21 33\n 5 15 25 35 55\n 7 21 35 49 77\n 11 33 55 77 121\nHERE\nend",
"def tables\n [\n ]\n end",
"def add_join_table( id_left, table_left, id_right, table_right, name = nil, &block )\n name ||= [ table_left, table_right ].sort.join( '_' )\n add_table name do\n foreign_key id_left, table_left\n foreign_key id_right, table_right\n primary_key [ id_left, id_right ]\n unique [ id_right, id_left ]\n instance_eval &block if block\n end\n end",
"def 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 copy \n t = @tab.clone ;\n for i in 0..3\n t[i] = t[i].clone\n end\n Table.new(t) ;\n end",
"def splitView(splitView, resizeSubviewsWithOldSize:oldSize)\n\t\tfirstSubview = splitView.subviews.objectAtUntestedIndex(0)\n\t\tsecondSubview = splitView.subviews.objectAtUntestedIndex(1)\n\t\tdividerThickness = splitView.dividerThickness\n\t\tframe = splitView.frame\n\t\t\n\t\tfirstSubviewFrame = firstSubview.frame\t\t\n\t\texistingFirstSubviewFrame = firstSubview.frame\n\t\t\n\t\tfirstSubviewFrame.size.height = frame.size.height\n\t\t\n\t\tminimumSearchPaneWidth = 375\n\t\tmaximumSearchPaneWidth = ((splitView.frame.size.width * 3) / 5).floor\n\t\t\n\t\tif existingFirstSubviewFrame.size.width.floor <= minimumSearchPaneWidth\n\t\t\tif existingFirstSubviewFrame.size.width > ((oldSize.width / 5) * 2).floor\n\t\t\t\t\t# If the width of the search pane has gone down to the minimum size,\n\t\t\t\t\t# then open up to an ideal width, 2 fifths of the frame seems about right\n\t\t\t\t\tfirstSubviewFrame.size.width = ((frame.size.width / 5) * 2).floor\n\t\t\telse\n\t\t\t\t\tfirstSubviewFrame.size.width = minimumSearchPaneWidth\n\t\t\tend\n\t\telse\n\t\t\t# Otherwise continue using the ratio between the subview to the full split view\n\t\t\tfirstSubviewFrame.size.width = (frame.size.width / (oldSize.width / firstSubviewFrame.size.width)).floor\n\t\tend\n\t\t\n\t\tif firstSubviewFrame.size.width <= minimumSearchPaneWidth\n\t\t\tfirstSubviewFrame.size.width = minimumSearchPaneWidth \n\t\telsif firstSubviewFrame.size.width >= maximumSearchPaneWidth\n\t\t\tfirstSubviewFrame.size.width = maximumSearchPaneWidth\n\t\tend\n\t\t\n\t\tfirstSubview.frame = firstSubviewFrame\n\t\t\n\t\tsecondSubviewFrame = secondSubview.frame\n\t\tsecondSubviewFrame.size.height = frame.size.height\n\t\tsecondSubviewFrame.origin.x = firstSubviewFrame.size.width + dividerThickness;\n\t\tsecondSubviewFrame.size.width = frame.size.width - firstSubviewFrame.size.width - dividerThickness;\n\t\tsecondSubview.frame = secondSubviewFrame\n\tend",
"def table_data\n @building_groups.reduce([]) do |table, bg|\n table << energy_row(bg)\n end\n end",
"def get_model_table(part)\n rows = @parser.find(part).find_children('tr').list_results\n table = []\n rows.each do |row|\n table.push(\n get_model_row(@parser.find(row).find_children('td,th').list_results)\n )\n end\n get_valid_model_table(table)\n end",
"def post_processing_tables(nodes)\n tables = nodes\n .css('table:not(.o-ld-columns-table)')\n .add_class('c-ld-table')\n tables.wrap('<div class=\"c-ld-table__wrap\"></div>') unless @options[:material]\n end",
"def table(b, rain_fall_type, _year, ji, compare)\n dataset = rain_fall_type.tr('_', ' ')\n dataset_compare = compare.tr('_', ' ')\n hash_data = if rain_fall_type == 'All'\n ji.map do |el|\n if el.to_s == 'Year'\n { title: 'Year', field: el, headerFilter: true }\n else\n { title: el.to_s.tr('_', ' '), field: el }\n end\n end\n else\n\n hash_data = if compare == 'None'\n [\n { title: 'Year', field: 'Year', headerFilter: true },\n { title: dataset, field: rain_fall_type }\n\n ]\n else\n [{ title: 'Year', field: 'Year', headerFilter: true },\n { title: dataset, field: rain_fall_type },\n { title: dataset_compare, field: compare }]\n end\n end\n\n data = { column: hash_data, data: b }\n data\n end",
"def parse_table; end",
"def chooseTable\n @metadata.chooseTable\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 create_table objects, columns, title, date_param = nil, nosort = false\n\t\tcurr_user = current_user\n\t\n\t\tid_to_names = [\"trip_id\",\"destination_id\",\"bus_id\"]\n\t\ttimes = [\"depart_time\",\"arrive_time\",\"return_time\"]\n\t\tdates = [\"date\",\"start\",\"expiry\",\"offset_date\",\"start_date\",\"end_date\",\"created_at\",\"updated_at\"]\n\t\tno_management = [\"permissions\", \"roles\"]\n\t\tmanagement_headers = [\"updated_by\",\"created_at\",\"updated_at\"]\n\t\t\n\t\thtml = \"\"\n\t\thtml << '<h1>'.html_safe\n\t\thtml << title\n\t\t\n\t\thtml << '</h1>'.html_safe\n\t\t\n\t\thtml << '<table class=\"admin_table\">'.html_safe\n\t\t\n\t\thtml << '<tr class=\"tr_header\">'.html_safe\n\t\tcolumns.each do |col|\n\t\t\t\n\t\t\tcol_title = col\n\t\t\t\n\t\t\tif col.include? '_id' then col_title = col.split('_id')[0] end\n\t\t\t\n\t\t\tif management_headers.include? col\n\t\t\t\tif curr_user.has_permission? :management\n\t\t\t\t\thtml << '<th>'.html_safe\n\t\t\t\t\tif !nosort \n\t\t\t\t\t\thtml << sort_table(col, col_title.humanize, date_param).html_safe\n\t\t\t\t\telse\n\t\t\t\t\t\thtml << col_title.humanize\n\t\t\t\t\tend\n\t\t\t\t\thtml << '</th>'.html_safe\n\t\t\t\tend\n\t\t\telse\n\t\t\t\thtml << '<th>'.html_safe\n\t\t\t\tif !nosort \n\t\t\t\t\thtml << sort_table(col, col_title.humanize, date_param).html_safe\n\t\t\t\telse\n\t\t\t\t\thtml << col_title.humanize\n\t\t\t\tend\n\t\t\t\thtml << '</th>'.html_safe\n\t\t\tend\n\t\t\t\n\t\tend\n\t\t\n\t\t# Show Column\n\t\thtml << '<th></th>'.html_safe\n\t\t\n\t\t# Edit Column\n\t\tif (curr_user.has_permission? :admin) || (!(no_management.include? objects[0].class.name.tableize) && (curr_user.has_permission? :management))\n\t\t\thtml << '<th></th>'.html_safe\n\t\tend\n\t\t\n\t\t# Destroy Column\n\t\tif curr_user.has_permission? :admin\n\t\t\thtml << '<th></th>'.html_safe\n\t\tend\n\t\t\n\t\thtml << '</tr>'.html_safe\n\t\t\n\t\ti = 0\n\t\tobjects.each do |obj|\n\t\t\tif i.even?\n\t\t\t\thtml << '<tr class=\"tr_alt_1\">'.html_safe\n\t\t\telse\n\t\t\t\thtml << '<tr class=\"tr_alt_2\">'.html_safe\n\t\t\tend\n\t\t\t\tcolumns.each do |col|\n\t\t\t\t\t\n\t\t\t\t\tif id_to_names.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\thtml << (link_to obj.send(col).id.to_s + \": \" + obj.send(col).name, obj.send(col)).html_safe\n\t\t\t\t\telsif col == \"user_id\" || col == \"updated_by\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\tif obj.send(col)\n\t\t\t\t\t\t\thtml << (link_to obj.send(col).userid, obj.send(col)).html_safe\n\t\t\t\t\t\tend\n\t\t\t\t\telsif col == \"id\"\n\t\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).to_s\n\t\t\t\t\telsif col == \"weekday\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << Date::DAYNAMES[obj.send(col)]\n\t\t\t\t\telsif times.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).strftime(\"%I:%M %p\")\n\t\t\t\t\telsif dates.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).strftime(\"%B %d, %Y\")\n\t\t\t\t\telsif col.include? \"_id\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\tif obj.send(col)\n\t\t\t\t\t\t\thtml << (link_to obj.send(col).id.to_s, obj.send(col)).html_safe\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).to_s\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# Show Column\n\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\thtml << (link_to \"Show\", obj).html_safe\n\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\t\n\t\t\t\t# Edit Column\n\t\t\t\tif (curr_user.has_permission? :admin) || (!(no_management.include? objects[0].class.name.tableize) && (curr_user.has_permission? :management))\n\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\thtml << (link_to \"Edit\", \"/\" + obj.class.name.tableize + \"/\" + obj.id.to_s + \"/edit\").html_safe\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# Destroy Column\n\t\t\t\tif curr_user.has_permission? :admin\n\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\thtml << (link_to \"Destroy\", obj, :confirm => 'Are you sure?', :method => :delete).html_safe\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\n\t\t\thtml << '</tr>'.html_safe\n\t\t\ti = i + 1\n\t\tend\n\t\t\n\t\thtml << '</table>'.html_safe\n\t\t\n\t\thtml.html_safe\n\tend",
"def employee_tables\n @record.employees.each do |employee|\n h3 employee.full_name\n info_table(employee)\n contacts_table(employee)\n end\n end",
"def make_table(options={})\n get_table(options).rows\n end",
"def table\r\n\t\tempty = Hash.new\r\n\t\tif @text.length < 2\r\n\t\t\treturn empty\r\n\t\tend\r\n\t\ttableHelper(@tree, \"\")\r\n\t\treturn @table\r\n\tend",
"def create_side_table\n RailsRedshiftReplicator.connection.exec \"CREATE TABLE #{temporary_table_name} (LIKE #{replication.target_table})\"\n end",
"def add_divider_row_to_table\n table << \" -\"\n size.times { table << '-----' }\n table << \"\\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 generate_table(name, data_set1, data_set2 , data_set3, data_set4 , assignment_names,data_set1_name , data_set2_name, data_set3_name, data_set4_name )\n table = \"#{name}\"\n\n table << \"<br/><table border='1' align='left'>\"\n\n table << \"<tr><td></td>\"\n assignment_names.each_with_index do |assignment,index|\n table << \"<td>(#{index+1})#{assignment}</td>\"\n end\n\n color = '#'+COLOR_1+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set1_name}</td>\"\n data_set1.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n color = '#'+COLOR_2+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set2_name}</td>\"\n data_set2.each do |value|\n table << \"<td>#{value}</td>\"\n end\n\n if(data_set3)\n color = '#'+COLOR_3+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set3_name}</td>\"\n data_set3.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n if(data_set4)\n color = '#'+COLOR_4+';'\n table << \"</tr><tr><td style='color:#{color}'>#{data_set4_name}</td>\"\n data_set4.each do |value|\n table << \"<td>#{value}</td>\"\n end\n end\n\n table << \"</tr></table>\"\n @table = table\n end",
"def shared_slice(hash_)\n offset_ = @offset\n select_set_ = {}\n hash_.each do |k_, v_|\n if (ainfo_ = @structure.axis(k_))\n aindex_ = ainfo_.axis_index\n unless select_set_.include?(aindex_)\n lindex_ = ainfo_.index(v_)\n if lindex_\n offset_ += ainfo_.step * lindex_\n select_set_[aindex_] = true\n end\n end\n end\n end\n Table.new(@structure.substructure_omitting(select_set_.keys),\n :acquire => @vals, :offset => offset_, :parent => self)\n end",
"def split_table_fields(select_statement, split_options = {})\n return select_statement if select_statement.class != String\n table_fields = []\n select_statement.split(\",\").each do |tf|\n # this will make:\n # m[0] => 'table_name'\n # m[1] => 'field_name'\n # m[2] => ' as as_field_name'\n # m[3] => 'count'\n if m = tf.strip.match(/^`?(\\w+|\\*)`?\\.`?(\\w+|\\*)`?($| as \\w+$)/)\n table_fields << [m[1], m[2], m[3]]\n elsif m = tf.strip.match(/^(\\w+|\\*)$/)\n # there was no table specified so default to current table\n table_fields << [self.table_name, m[1]]\n elsif m = tf.strip.match(/^(count)\\((\\w+|\\*)\\)($| as \\w+$)/) #count(*)\n # there was no table specified so default to current table\n table_fields << [self.table_name, m[2], m[3], m[1]]\n end\n end\n \n # delete those not for this table\n if split_options[:delete_other_model_selects]\n # delete every not for this table OR if we're in a has_and_belongs_to_many join, t0\n table_fields.delete_if {|tf| tf[0] != self.table_name && !(split_options[:is_join] && tf[0] == 't0')}\n end\n table_fields\n end",
"def join(secDataset,pair)\n #print \"\\n#{pair}\\n\"\n pair[0].downcase! unless @columns.include?(pair[0])\n pair[1].downcase! unless secDataset.columns.include?(pair[1])\n @data.each do |row|\n secDataset.each do |row2|\n #print \"\\nPorovnavam #{row[pair[0]]} s #{row2[pair[1]]}\\n\"\n if (row[pair[0]] == row2[pair[1]])\n row.merge!(row2)\n break\n end\n end\n #secDataset.find(pair[0])\n #TODO zoptimalizovat -> zlepsit slozitost z m*n!\n end\n sloupce = secDataset.columns\n sloupce.each do |sl|\n set_column(sl,nil)\n end\n\n end",
"def create_collection_table(rows:, columns:, col_id:, plate_on_end: nil, display_id: false)\n plate_on_end ||= rows == 12 && columns == 8 ? true : false\n text_color = 'black'\n border_color = '&#E9E9E9'\n bg_color = '&#b8b8b8'\n size = rows * columns\n slots = (1..size + rows + columns + 1).to_a\n tab = slots.each_slice(columns + 1).each_with_index.map do |row, row_idx|\n row.each_with_index.map do |col, col_idx|\n if row_idx == 0 && display_id\n if col_idx == 0\n { class: 'td-empty-slot',\n content: '<b>ID:</b>',\n style: {color: text_color, 'background-color' => border_color } }\n elsif col_idx == 1\n { class: 'td-empty-slot',\n content: \"<b>#{col_id}</b>\",\n style: {color: text_color, 'background-color' => border_color, border: '0px' } }\n else\n { class: 'td-empty-slot',\n content: '',\n style: {color: text_color, 'background-color' => border_color, border: '0px' } }\n end\n elsif row_idx == 0\n { class: 'td-empty-slot',\n content: \"<b>#{plate_on_end ? get_alpha(col_idx) : col_idx}</b>\",\n style: { color: text_color, 'background-color' => border_color } }\n elsif col_idx.zero?\n { class: 'td-empty-slot',\n content: \"<b>#{plate_on_end ? row_idx : get_alpha(row_idx)}</b>\",\n style: { color: text_color, 'background-color' => border_color } }\n else\n { class: 'td-empty-slot',\n content: '',\n style: { 'background-color' => bg_color } }\n end\n end\n end\n end",
"def start_table\r\n n = @char_set.length\r\n t_size = @size\r\n create_table(@char_set, '', n, t_size)\r\n end",
"def create_table\n dimension_length = (@numbers_to_multiply.length - 1)\n @multiplication_table = []\n new_table_row = [\" \"]\n\n for i in 0..dimension_length\n new_table_row << @numbers_to_multiply[i]\n end\n\n new_table_row\n @multiplication_table << new_table_row\n\n for x in 0..dimension_length \n new_table_row = []\n new_table_row << @numbers_to_multiply[x]\n # rowValues = \"#{@numbers_to_multiply[x]} |\"\n for y in 0..dimension_length\n nextEntry = @numbers_to_multiply[x] * @numbers_to_multiply[y]\n new_table_row << nextEntry\n end\n @multiplication_table << new_table_row\n end\n end",
"def data_tables\n @data_tables ||= @holdings_page.search('#rightcol')\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 ft\n\tFancifyTable.new([[1,2],[3,4]])\nend",
"def admin_round_table(year, round)\n # TODO move to controller\n nba_playoff_matchups =\n NbaPlayoffMatchup.includes(:nba_team1)\n .includes(:nba_team2)\n .includes(:winning_nba_team)\n .where(year: year, round: round)\n .order(:position)\n if (nba_playoff_matchups.empty?)\n return \"\"\n end\n\n tags = []\n tags << content_tag(:h4, \"Round \" + round.to_s)\n content_tag(:table, class: TABLE_CLASS) do\n tags << content_tag(:thead,\n content_tag(:tr,\n COL_NAMES.collect { |name| content_tag(:th, name)}.join.html_safe))\n tags << content_tag(:tbody) do\n nba_playoff_matchups.each do |nba_playoff_matchup|\n tags << nba_playoff_matchup_row(nba_playoff_matchup).html_safe\n end\n end #content_tag :tbody\n tags.join.html_safe \n end #content_tag :table\n end",
"def index\n @sub_data_tables = SubDataTable.all\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 init_table\n\t$table = Array.new($height) { Array.new($width, '.')}\nend",
"def create_join_table_gas(filter, all_savings)\n filter.each_with_index do |contract, index|\n JoinTableGasSimulationContract.create(gas_simulation: self, gas_contract: contract, savings: all_savings[index])\n end\n end",
"def build_tables\n @db.exec(%q[\n CREATE TABLE IF NOT EXISTS breeds(\n id serial NOT NULL PRIMARY KEY,\n breed varchar(30),\n price integer\n )])\n\n @db.exec(%q[\n CREATE TABLE IF NOT EXISTS puppies(\n id serial NOT NULL PRIMARY KEY,\n breed varchar(30),\n name varchar(30),\n age integer,\n created_at timestamp NOT NULL DEFAULT current_timestamp\n )])\n\n @db.exec(%q[\n CREATE TABLE IF NOT EXISTS requests(\n id serial NOT NULL PRIMARY KEY,\n breed text,\n status text,\n created_at timestamp NOT NULL DEFAULT current_timestamp\n )])\n end",
"def tables\n @tables ||= {}.tap do |tables|\n parsed_data['tables'].map do |table|\n parsed_table_rows = parse_choices(table['rows'])\n tables[table['id']] = Table.new(table['name'], table['parameters'], parsed_table_rows)\n end\n end\n end",
"def master_mix_table(inputs:, input_names:, composition:, mult:)\n header = [\n \"#{composition.polymerase.display_name} #{composition.polymerase.item}\",\n \"#{composition.dye.display_name} #{composition.dye.item}\",\n composition.water.display_name\n ]\n\n row = [\n composition.polymerase.add_in_table(mult),\n composition.dye.add_in_table(mult),\n composition.water.add_in_table(mult)\n ]\n\n input_names.each_with_index do |input_name, i|\n header << \"#{input_name} #{inputs[i]}\"\n row << composition.input(input_name).add_in_table(mult)\n end\n\n [header, row].transpose\n end",
"def table=(_arg0); end",
"def draw_table_second_title_columns(table_info, width_columns = [260, 260])\n table (table_info) do\n rows(0).background_color = 'F0F0F0'\n rows(0).border_width = 1\n columns(0).border_width = 1\n columns(0..1).font_style = :bold\n columns(0..1).size = 9\n self.column_widths = width_columns\n end\n end",
"def show\n @table1 = AnimalDeath.where(:destiny_id => requested_resource).select(show_table1('show', Destiny, AnimalDeath)).limit(10)\n @table2 = AnimalSale.where(:destiny_id => requested_resource).select(show_table1('show', Destiny, AnimalSale)).limit(10)\n super\n end",
"def monolith_table(groups, metadata)\n checkmark = \" <span style='color: limegreen'>✔</span>\"\n\n # TODO: The checkmark crap below needs to be abstracted.\n formatters = {\n 'New' => proc { |f, l| ['', '', l] },\n 'Updated' => proc { |f, l| ['', '', l + (metadata[f]['installed'].any? ? checkmark : '' ) ] },\n 'Renamed' => proc { |f, l| [\"#{metadata[f]['oldname']}\" + (metadata[f]['installed'].any? ? checkmark : '' ), \"→\", l ] }\n }\n\n table = HTML::Table.new do |t|\n t.align = 'center'\n end\n\n groups.each do |group_name, members|\n title = Table::Row.new do |r|\n r.content = ['', '', group_name]\n end\n title.class_ = 'title'\n table.push title\n\n formatter = formatters[group_name]\n\n members.each do |formula|\n content = Table::Row.new do |r|\n link = \"<a href=#{metadata[formula]['homepage']}>#{formula}</a>\"\n r.content = formatter.call(formula, link).push(\n h(metadata[formula]['desc'])\n )\n r.first.class_ = 'name'\n end\n table.push content\n end\n end\n\n table\nend",
"def 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 create_table(name, options=OPTS, &block)\n if options[:partition_of]\n create_partition_of_table_from_generator(name, CreatePartitionOfTableGenerator.new(&block), options)\n return\n end\n\n super\n end",
"def addTableEntries( symTab )\r\n\t\t@tablaSimbolos.clearItems\r\n\t\t@tablaSimbolos.rowHeaderMode = LAYOUT_FIX_WIDTH\r\n\t\t@tablaSimbolos.rowHeaderWidth = 0\r\n\t\t@tablaSimbolos.setTableSize(0, 5)\r\n\t\t@tablaSimbolos.font = @defaultFont\r\n\t\t@tablaSimbolos.tableStyle |= TABLE_COL_SIZABLE\r\n\t\t@tablaSimbolos.setColumnText(0, \"Nombre Variable\")\r\n\t\t@tablaSimbolos.setColumnText(1, \"Localidad\")\r\n\t\t@tablaSimbolos.setColumnText(2, \"No. de línea\")\r\n\t\t@tablaSimbolos.setColumnText(3, \"Valor\")\r\n\t\t@tablaSimbolos.setColumnText(4, \"Tipo\")\r\n\t\t@tablaSimbolos.columnHeader.setItemJustify(0, FXHeaderItem::CENTER_X)\r\n\t\t@tablaSimbolos.columnHeader.setItemJustify(1, FXHeaderItem::CENTER_X)\r\n\t\t@tablaSimbolos.columnHeader.setItemJustify(2, FXHeaderItem::CENTER_X)\r\n\t\t@tablaSimbolos.columnHeader.setItemJustify(3, FXHeaderItem::CENTER_X)\r\n\t\t@tablaSimbolos.columnHeader.setItemJustify(4, FXHeaderItem::CENTER_X)\r\n\t\t@tablaSimbolos.setColumnWidth( 0, 300)\r\n\t\t@tablaSimbolos.setColumnWidth( 1, 300)\r\n\t\t@tablaSimbolos.setColumnWidth( 2, 230)\r\n\t\t@tablaSimbolos.setColumnWidth( 3, 219)\r\n\t\t@tablaSimbolos.setColumnWidth( 4, 300)\r\n\t\t@NUM_FILAS = 0\r\n\t\tsymTab.each{ |llave, entrada|\r\n\t\t\t@tablaSimbolos.appendRows(1)\r\n\t\t\t@tablaSimbolos.setItemText(@NUM_FILAS, 0, symTab[llave].nombre)\r\n\t\t\t@tablaSimbolos.setItemText(@NUM_FILAS, 1, symTab[llave].direccionMem.to_s)\r\n\t\t\t@tablaSimbolos.setItemText(@NUM_FILAS, 2, symTab[llave].numsLinea)\r\n\t\t\t@tablaSimbolos.setItemText(@NUM_FILAS, 3, symTab[llave].valor.to_s)\r\n\t\t\t@tablaSimbolos.setItemText(@NUM_FILAS, 4, symTab[llave].tipo)\r\n\t\t\t@tablaSimbolos.setItemJustify(@NUM_FILAS, 0, FXTableItem::CENTER_X)\r\n\t\t\t@tablaSimbolos.setItemJustify(@NUM_FILAS, 1, FXTableItem::CENTER_X)\r\n\t\t\t@tablaSimbolos.setItemJustify(@NUM_FILAS, 2, FXTableItem::CENTER_X)\r\n\t\t\t@tablaSimbolos.setItemJustify(@NUM_FILAS, 3, FXTableItem::CENTER_X)\r\n\t\t\t@tablaSimbolos.setItemJustify(@NUM_FILAS, 4, FXTableItem::CENTER_X)\r\n\t\t\t@NUM_FILAS += 1\r\n\t\t}\r\n\tend",
"def bid_cells(bid, seed_on_left_or_right)\n options = {:align => seed_on_left_or_right, :style => \"border-bottom: 1px solid black; padding-#{seed_on_left_or_right}: 2mm;\"}\n seed = content_tag :td, (bid ? \"(#{bid.seed})\" : ' '), options\n team = content_tag :td, (bid ? h(bid.team.name) : ' '), options\n cells = [seed, team]\n cells.reverse! if 'right' == seed_on_left_or_right\n cells\n end",
"def cd_id_table\n view_name = cd_id_table_tn\n if @cd_id_table_tn_exists.nil?\n @cd_id_table_tn_exists=true\n if !$db.table_exists?(view_name)\n $db.run(\"CREATE VIEW #{view_name} AS SELECT DISTINCT(r.canonical_document_id) FROM records r INNER JOIN records_searches br ON r.id=br.record_id INNER JOIN searches b ON br.search_id=b.id WHERE b.systematic_review_id=#{self[:id]} AND b.valid=1\n\n UNION\n\n SELECT DISTINCT r.canonical_document_id FROM searches b INNER JOIN records_searches br ON b.id=br.search_id INNER JOIN records_references rr ON br.record_id=rr.record_id INNER JOIN bib_references r ON rr.reference_id=r.id WHERE b.systematic_review_id=#{self[:id]} and r.canonical_document_id IS NOT NULL and b.valid=1 GROUP BY r.canonical_document_id\")\n end\n end\n $db[view_name.to_sym]\n end",
"def buffer_preparation(op_count,op_in_cell_lysate,op_wash_amount, op_out_protein)\r\n op_table =[[\"Falcon tube ID\",\"Purification buffer volume\",\"Imidazole volume\"]]\r\n \r\n for i in 0..(op_count-1)\r\n #if !op_wash_amount[i]\r\n #op_wash_amount[i] = 5\r\n #end\r\n row = []\r\n row << op_in_cell_lysate[i]\r\n row << {content: \"15 mL\", check: true}\r\n row << {content: \"#{op_wash_amount[i]*3} µl\", check: true}\r\n op_table << row\r\n end\r\n \r\n show do\r\n title \"Prepare wash buffer\"\r\n check \"Grab Purification Buffer from 4°C refrigerator.\"\r\n check \"Grab a imidazole aliquot, in a box labeled <b>protein purification</b> in -20°C freezer (B1-165)\"\r\n #check \"Grab <b>#{op_count}</b> 50 mL Falcon tube and label with #{op_in_cell_lysate.to_sentence} on the tube wall.\"\r\n check \"Prepare wash buffer according to the table.\"\r\n check \"Mix the buffer by quick vortexing.\"\r\n table op_table\r\n end\r\n end",
"def table \n table = data.map do |slot|\n slot.position.to_s.ljust(12) + slot.license_plate.ljust(19) + slot.color + \"\\n\" if slot\n end.join('')\n end",
"def build_table(response)\n table = Terminal::Table.new do |t|\n t.title = \"Food trucks\"\n t.headings = ['Name', 'Location']\n t.rows = fill_table_items(response)\n t.style = { :border_top => true, :border_bottom => true}\n end\n return table\n\n end",
"def index\n @splitters = Splitter.all\n end",
"def parse_and_set_tables\n tables = @nokogiri_document.xpath(\".//table\")\n @tables_count = tables.count\n unless @tables_count > 12\n tables.each_with_index do | table , index |\n if index.odd?\n key = define_key_based_on_index(index)\n noko = Nokogiri::HTML(table.to_s)\n noko.xpath(\"/html/body/table\").each do | table |\n @tables[key] = table\n end\n noko = nil\n end\n end\n end\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 initialize_columns\n @columns = []\n valid_table = table.alias('valid_taxon_names')\n\n @columns.push({ header: 'ro', projected: rank_over(table, valid_table) })\n\n @columns.push({header: 'taxon_name_id', projected: table[:id].as('taxon_name_id') } )\n @columns.push({header: 'cached_valid_taxon_name_id', projected: table[:cached_valid_taxon_name_id].as('cached_valid_taxon_name_id') } )\n @columns.push({header: 'cached', projected: table[:cached].as('cached') } )\n @columns.push({header: 'cached_author_year', projected: table[:cached_author_year].as('cached_author_year') } )\n @columns.push({header: 'cached_is_valid', projected: table[:cached_is_valid].as('cached_is_valid') } )\n\n if fieldsets.include?('observations')\n @columns.push({header: 'otu_id', projected: otu_table[:id].as('otu_id') } )\n @columns.push({header: 'otu_name', projected: otu_table[:name].as('otu_name')} )\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 table_specific_items(objects)\n @tableheadings, @tablecolumncount = objects[0].table_headings\n @tablerow = tablerow_array(objects)\n @tablerowcount = @tablerow.count\n end",
"def tabla_pasos(contador,array_anterior)\n aux=0\n tabla = Terminal::Table.new do |a|\n a.title= \"ELEMENTOS A ORDENAR: #{array_anterior}\"\n a.headings = [{value:'DATO', alignment: :center},{value:'ESTRUCTURA', alignment: :center}]\n for i in 0..contador-1\n a.add_row([\n aux+=1,\n @pasoL[i]\n ])\nend\n end\n return tabla\n end",
"def tables\n return enum_for(:tables) unless block_given?\n\n yield nil, rows\n end",
"def prepare_table(element)\n name=element.attributes[\"name\"]\n oid=SNMPPass.oid2num(element.attributes[\"oid\"])\n\n # Read index and columns\n indexes=element.elements[\"row/linkage\"].elements.collect(\"index\") {|index| index.attributes[\"name\"]}\n columns=element.elements[\"row\"].elements.collect(\"column\") do\n |column|\n column_name=column.attributes[\"name\"]\n column_oid=column.attributes[\"oid\"]\n column_id=SNMPPass.oid2num(column_oid).last\n\n $DEBUG.puts \"TABLE: #{name} NAME: #{column_name} ID #{column_id}, OID: #{column_oid}\"\n\n #column_desc=column.elements[\"description\"].text.gsub(/^[[:blank:]\\n]*/,\"\").gsub(/[[:blank:]\\n]*$/,\"\")\n type=prepare_type(column.elements[\"syntax\"], column_name)\n [column_name,column_id,type]\n end\n\n @indexes[name]=indexes\n @columns[name]=columns\n\n table=DynamicTree.new(oid){|op, *roid| dynamic_tree_callback(name, op, *roid) }\n add_node(table)\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 get_table(options={})\n options = {:vertical_rulings => []}.merge(options)\n\n tables = if options[:vertical_rulings].empty?\n BasicExtractionAlgorithm.new.extract(self)\n else\n BasicExtractionAlgorithm.new(options[:vertical_rulings]).extract(self)\n end\n\n tables.first\n end",
"def tables(opts=OPTS, &block)\n tables_or_views('TABLE', opts, &block)\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.51351094",
"0.5121764",
"0.51185375",
"0.5114956",
"0.5113389",
"0.511185",
"0.5104276",
"0.5089847",
"0.5084871",
"0.5082211",
"0.5053777",
"0.5044182",
"0.5040706",
"0.50395894",
"0.5034069",
"0.5033889",
"0.50269276",
"0.5013865",
"0.5011015",
"0.5005809",
"0.50036895",
"0.49991584",
"0.49973336",
"0.49954522",
"0.49945602",
"0.4985041",
"0.49843925",
"0.49765354",
"0.49723762",
"0.4966375",
"0.49660668",
"0.49652115",
"0.49640042",
"0.49605513",
"0.49554706",
"0.49513167",
"0.49498358",
"0.49453655",
"0.4942769",
"0.494173",
"0.4941245",
"0.49388024",
"0.49230468",
"0.49169928",
"0.49167967",
"0.49120188",
"0.49021214",
"0.48946744",
"0.48817807",
"0.48801303",
"0.4879661",
"0.48763326",
"0.48736975",
"0.48703495",
"0.48656",
"0.48639977",
"0.48623148",
"0.4860729",
"0.48604068",
"0.4848047",
"0.4845082",
"0.48431846",
"0.4841021",
"0.48396492",
"0.48327857",
"0.48316455",
"0.48265684",
"0.4820232",
"0.48070836",
"0.4805687"
] | 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 << (1..@generated.length).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 << (1..@expected.length).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 = \" \" 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",
"def construct_table(table_values)\n table = String.new\n column_width = 8\n \n if table_values.empty? then return table end\n \n # Construct column headers first\n columns = table_values.values()[0].keys.sort\n table << \"\".center(column_width)\n columns.each do |column|\n table << \"|\" + column.to_s.center(column_width)\n end\n \n table_width = table.length\n table << \"\\n\"\n \n # Construct each row\n rows = table_values.keys.sort\n rows.each do |row|\n table << \"\".center(table_width, \"-\") + \"\\n\"\n table << row.to_s.center(column_width)\n \n row_values = table_values[row]\n columns.each do |column|\n multiple = row_values[column]\n table << \"|\" + multiple.to_s.center(column_width)\n end\n table << \"\\n\"\n end\n return table\nend",
"def to_html\n htmlString = %{<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">}\n htmlString += %{<tr>}\n LineCounter.columnNames.each { |name| htmlString += %{<th>#{name}</th>} }\n htmlString += %{</tr>}\n self.each do |result|\n htmlString += %{<tr>}\n result.to_a.each { |cell| htmlString += %{<td>#{cell}</td> } }\n htmlString += %{</tr>}\n end\n htmlString += %{</table>}\n htmlString += %{<p><em>Generated by } +\n %{<a href=\"http://countloc.rubyforge.org\">countloc</a> version #{VERSION} } +\n %{on #{Time.now.asctime}</em></p>}\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 table_to_s\n table = Terminal::Table.new do |t|\n symbols = @grammar.terminals.keys.to_a + [Grammar::END_SYM]\n t << [''] + symbols\n\n @grammar.non_terminals.each do |non_terminal|\n t.add_separator\n row = [non_terminal]\n symbols.each { |sym| row << @table[non_terminal][sym].to_s || ' '}\n t << row\n end\n\n end\n table.to_s\n end",
"def content\n number_to_skip = 0 # Keeps track of the # of columns to skip\n \n html = ''\n table.header.column_names.each do |column|\n number_to_skip -= 1 and next if number_to_skip > 0\n \n if cell = @cells[column]\n number_to_skip = (cell[:colspan] || 1) - 1\n else\n cell = Cell.new(column, nil)\n end\n \n html << cell.html\n end\n \n html\n end",
"def to_s\n empty = ''.freeze\n tr = 'tr'.freeze\n th = 'th'.freeze\n td = 'td'.freeze\n nl = \"\\n\".freeze\n tr_attr = @opts[:tr]\n th_attr = @opts[:th]\n td_attr = @opts[:td]\n col_th = @opts[:column_th]\n\n t = tag('table', empty, @opts[:table])\n s = t.open.dup\n s << nl\n\n if caption = @opts[:caption]\n s << tag(:caption, caption).to_s\n end\n\n if widths = @opts[:widths]\n s << \"<colgroup>\\n\"\n widths.each do |w|\n s << \"<col width=\\\"#{w.to_i}\\\" />\\n\"\n end\n s << \"</colgroup>\\n\"\n end\n\n if headers = @opts[:headers]\n s << \"<thead>\\n\"\n headers = headers.split(',') if headers.is_a?(String)\n trh = tag(tr, empty, handle_proc(tr_attr, headers))\n s << trh.open\n s << nl\n headers.each_with_index do |header, i|\n s << tag(th, header, handle_proc(th_attr, header)).to_s\n end\n s << trh.close\n s << \"</thead>\\n\"\n end\n\n s << \"<tbody>\\n\"\n @rows.each do |row|\n trh = tag(tr, empty, handle_proc(tr_attr, row))\n s << trh.open\n s << nl\n row.each_with_index do |col, i|\n s << tag((col_th && i == 0 ? th : td), col, handle_proc(td_attr, col, i, row)).to_s\n end\n s << trh.close\n end\n s << \"</tbody>\\n\"\n s << t.close\n end",
"def test_table_too\n return <<HERE;\n 2 3 5 7 11\n 2 4 6 10 14 22\n 3 6 9 15 21 33\n 5 10 15 25 35 55\n 7 14 21 35 49 77\n 11 22 33 55 77 121\nHERE\nend",
"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 add_divider_row_to_table\n table << \" -\"\n size.times { table << '-----' }\n table << \"\\n\"\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 make_row(column_elements)\n\t\"<tr><td>#{column_elements.join(\"</td><td>\")}</td></tr>\"\nend",
"def to_s\n return '' if cols < 1\n col_sizes = max_col_sizes\n str = heading_str(col_sizes)\n str << separator(col_sizes)\n str << body_str(col_sizes)\n str\n end",
"def to_empty\n table.dup.tap do |t|\n t.rows.each do |r, row|\n row.each do |c, cell|\n row.fill(c, Table::Cell::Empty.new(cell))\n end\n end\n end\n end",
"def to_s\n result = ''\n for r in 0..height\n lines = Array.new(cell_height) { '' }\n for c in 0..width\n # Differentiate the behaviour based on the visibility state of four cells at a time\n c1, c2, c3, c4 = self[r-1, c-1], self[r-1, c], self[r, c-1], self[r, c]\n v1, v2, v3, v4 = (c1 and c1.visible), (c2 and c2.visible), (c3 and c3.visible), (c4 and c4.visible)\n if v4\n lines[0] << '#' * cell_width\n (1...cell_height).each do | i | lines[i] << '#' end\n else\n lines[0] << if v1 or v2 or v3\n '#'\n else\n ' '\n end\n lines[0] << if v2\n '#' * (cell_width - 1)\n else\n ' ' * (cell_width - 1)\n end\n if v3\n (1...cell_height).each do | i | lines[i] << '#' end\n else\n (1...cell_height).each do | i | lines[i] << ' ' end\n end\n end\n if v4\n if c4.empty\n lines[1] << c4.number.to_s.ljust(cell_width-1)\n (2...cell_height).each do | i | lines[i] << ' ' * (cell_width-1) end \n else\n (1...cell_height).each do | i | lines[i] << '#' * (cell_width-1) end \n end\n else\n (1...cell_height).each do | i | lines[i] << ' ' * (cell_width-1) end\n end\n end\n result << lines.join(\"\\n\") << \"\\n\"\n end\n result\n end",
"def to_s\n str = \"\"\n count_row = 0\n count_col = 0\n str << \"-\"*25 << \"\\n\"\n rows.each do |row|\n row.each do |ele|\n str << ele.to_s << \" \"\n count_col += 1\n if count_col == 3\n str << \"| \"\n count_col = 0\n end\n end\n count_row += 1\n if count_row == 3\n str << \"\\n\" << \"-\"*25 << \"\\n\"\n count_row = 0\n else\n str << \"\\n\"\n end\n end\n str << \"-\"*25\n end",
"def show_body\n brows = []\n current_context[0][:body].map do |hash|\n hash.each do |_key , _val|\n _val = _val.scan(/.{100}/).join(\"\\n\") if _val.size > 150 # This line To fix table layout\n\n brows << [\"#{_key}\".green, \"#{_val}\".white]\n brows << :separator\n end\n end\n\n return brows\n end",
"def full_table_content\n _rations = squash_rations(format_rations)\n \n move_down(50)\n\n text \"Order for #{@sprint.started_at} to #{@sprint.finished_at}\"\n \n build_table(rations_headers + sort_by_id(_rations))\n\n move_down(10)\n\n text \"Full price for order is #{calculate_full_price(_rations)}\"\n end",
"def _tableish(html, row_selector, column_selectors) #:nodoc\n doc = Nokogiri::HTML(html)\n # Parse the table.\n rows = doc.search(row_selector)\n\n max_columns = _row_width(rows[0], column_selectors)\n max_rows = _column_height(rows)\n\n # Initialize a 2 dimensional array representing the size of the table in tableish format\n grid = Array.new(max_rows) { Array.new(max_columns, nil) }\n\n table_row_index = 0\n grid.each_with_index do |grid_row, grid_row_index|\n row = rows[table_row_index]\n\n cells = _select_cells(column_selectors, row)\n table_column_index = 0\n grid_row.size.times do |grid_column_index|\n next if grid[grid_row_index][grid_column_index] != nil\n\n cell = cells[table_column_index]\n if cell\n col_span, row_span = 1, 1\n row_span = cell['rowspan'].to_i - 1 if cell['rowspan']\n col_span = cell['colspan'].to_i - 1 if cell['colspan']\n\n # draw blank cells based on colspan and rowspan\n if cell['rowspan'] && cell['colspan']\n row_span.times do |row_offset|\n row_offset_index = grid_row_index + (row_offset + 1)\n col_span.times do |col_offset|\n col_offset_index = grid_column_index + (col_offset + 1)\n grid[row_offset_index][col_offset_index] = \"\" unless row_offset_index >= rows.size || col_offset_index >= max_columns\n end\n end\n end\n\n if cell['rowspan']\n row_span.times do |row_span_offset|\n row_offset_index = grid_row_index + (row_span_offset + 1)\n grid[row_offset_index][grid_column_index] = \"\" unless row_offset_index >= rows.size\n end\n end\n\n if cell['colspan']\n col_span.times do |col_span_offset|\n col_offset_index = grid_column_index + (col_span_offset + 1)\n grid[grid_row_index][col_offset_index] = \"\" unless col_offset_index >= max_columns\n end\n end\n\n # print cell value into grid and move to next table column, only if cell hasn't been touched yet\n if grid[grid_row_index][grid_column_index] == nil\n table_column_index += 1\n grid[grid_row_index][grid_column_index] = _cell_value(cell)\n end\n end\n end\n table_row_index += 1\n end\n\n _pad_grid_with_blanks(grid)\n\n grid\n end",
"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 table_header\n line = \"File|Total\".dup\n line << \"|Line\" if header_line_rate?\n line << \"|Branch\" if header_branch_rate?\n line << \"\\n\"\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 to_s\n str = prefix.dup\n str << header_to_s || ''\n str << columns_to_s || ''\n str << hr_to_s || ''\n\n sort_rows\n rows.each { |row|\n if (is_hr(row))\n str << hr_to_s\n else\n str << row_to_s(row) if row_visible(row)\n end\n }\n\n str << postfix\n\n return str\n end",
"def to_s\n @matrix.inject('') do |combined_rows, row|\n formatted_row =\n row.inject('') { |combined_cells, cell| \"#{combined_cells} #{cell}\" }\n \"#{combined_rows}\\n#{formatted_row}\"\n end\n end",
"def create_table_fragment(hash, options={})\n c_count = hash.size\n return \"\" if c_count == 0\n\n table_properties = options.delete(:table_properties)\n if table_properties\n table_style = table_properties.table_style\n column_widths = table_properties.column_widths\n column_styles = table_properties.column_styles\n else\n table_style = options.delete(:table_style)\n column_widths = options.delete(:column_widths)\n column_styles = options.delete(:column_styles)\n table_properties = TableProperties.new(table_style, column_widths, column_styles)\n end\n\n skip_header = options.delete(:skip_header)\n fragment = \"<w:tbl>#{table_properties}\"\n\n if column_widths\n fragment << \"<w:tblGrid>\"\n column_widths.each do |column_width|\n fragment << \"<w:gridCol w:w=\\\"#{column_width}\\\"/>\"\n end\n fragment << \"</w:tblGrid>\"\n end\n\n unless skip_header\n fragment << \"<w:tr>\"\n hash.keys.each do |header|\n encoded_header = Nokogiri::XML::Document.new.encode_special_chars(header.to_s)\n fragment << \"<w:tc><w:p><w:r><w:t>#{encoded_header}</w:t></w:r></w:p></w:tc>\"\n end\n fragment << \"</w:tr>\"\n end\n\n r_count = hash.values.inject(0) { |max, value| [max, value.is_a?(Array) ? value.length : (value.nil? ? 0 : 1)].max }\n 0.upto(r_count - 1).each do |i|\n fragment << \"<w:tr>\"\n hash.values.each_with_index do |v, j|\n table_cell = create_table_cell_fragment(v, i,\n :width => column_widths ? column_widths[j] : nil,\n :style => column_styles ? column_styles[j] : nil)\n fragment << table_cell.gsub(\"</w:p><w:p>\", '')\n end\n fragment << \"</w:tr>\"\n end\n\n fragment << \"</w:tbl>\"\n fragment\n end",
"def to_s\n header_output = build_header_output\n data_output = build_data_output\n\n string = ''\n string << Yummi.colorize(@title, @style[:title]) << $/ if @title\n string << Yummi.colorize(@description, @style[:description]) << $/ if @description\n table_data = header_output + data_output\n if @layout == :vertical\n # don't use array transpose because the data may differ in each line size\n table_data = rotate table_data\n end\n string << content(table_data)\n end",
"def 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\n \"| #{cells.join(' | ')} |\"\n end",
"def body_with_updated_annotations\n RewriteComments.call body do |line_number, line_to_whitespace, whitespace, comment|\n if !comment[VALUE_REGEX]\n [whitespace, comment]\n elsif line_to_whitespace.empty?\n result = results[line_number-1].map { |result| result.gsub \"\\n\", '\\n' }.join(', ')\n [whitespace, CommentFormatter.call(whitespace.size, VALUE_MARKER, result, options)]\n else\n result = results[line_number].map { |result| result.gsub \"\\n\", '\\n' }.join(', ')\n [whitespace, CommentFormatter.call(line_to_whitespace.size + whitespace.size, VALUE_MARKER, result, options)]\n end\n end\n end",
"def test_table\n return <<HERE;\n 2 3 5 7 11\n 3 9 15 21 33\n 5 15 25 35 55\n 7 21 35 49 77\n 11 33 55 77 121\nHERE\nend",
"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 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 build_report_body\n draw_table(data, :width => 600)\n end",
"def to_s(mode = :pretty, len_col = 3)\n return super if empty?\n if mode == :pretty\n clen = cols_len\n to_a.collect {|r| mapcar(r, clen) {|x, l| format(\"%#{l}s \",x.to_s)} << \"\\n\"}.join(\"\")\n else\n i = 0; s = \"\"; cs = column_size\n each do |e|\n i = (i + 1) % cs\n s += format(\"%#{len_col}s \", e.to_s)\n s += \"\\n\" if i == 0\n end\n s\n end\n end",
"def build_report_body\n draw_table(data, :width => 700)\n end",
"def render_tbody\n if @lines and @lines.size > 0\n return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join)))\n return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' }))\n end\n ''\n end",
"def render(row, header)\n hash = header.to_hash(row)\n\n result = \"\"\n fixed_layout.each do |map|\n # A nil value is considered an empty string\n value = hash[map.key].to_s\n result << format(\"%-#{map.size}.#{map.size}s\", value)\n end\n result\n end",
"def row_cells_to_text_columns(table_row)\n table_row.cells.map do |cell|\n # Join paragraphs into a String using a space delimiter.\n cell_paragraphs(cell).join(' ')\n end\n end",
"def table\r\n\t\tempty = Hash.new\r\n\t\tif @text.length < 2\r\n\t\t\treturn empty\r\n\t\tend\r\n\t\ttableHelper(@tree, \"\")\r\n\t\treturn @table\r\n\tend",
"def format_table!\n table.rows.each do |row|\n row.cells.each_with_index do |cell, i|\n set_cell_format_option!(cell, i)\n format_cell!(cell)\n end\n end\n\n true\n end",
"def print_table(columns, data, print_headings = true)\n\n # Fill base lengths\n columns.each do |col|\n col[:length] = (print_headings ? col[:title].length : 0)\n end\n\n # Compute maximum length of each field\n data.each do |datum|\n\n columns.each do |col|\n if (col[:func] != nil)\n str = col[:func].call(datum).to_s\n else\n str = datum[col[:key]].to_s\n end\n str = str.gsub(/\\e\\[[0-9;]*m/, '') # eliminate \"colors\"\n col[:length] = [ col[:length], str.length ].max\n end\n\n end\n\n # Create the format string\n table_format_row = '|'\n columns.each do |col|\n if (col[:type] == :int)\n table_format_row << sprintf(\" %%%dd |\", col[:length])\n else\n table_format_row << sprintf(\" %%-%ds |\", col[:length])\n end\n end\n table_format_row << \"\\n\"\n\n # Special line: title\n table_format_title = \"\\e[1m\\e[4m\" +\n table_format_row.gsub(/%-?([0-9]+)[a-z]/, '%-\\1s').gsub(/\\|/, ' ') + \"\\e[m\"\n\n # Create the horizontal line\n table_horizontal = '+'\n columns.each do |col|\n table_horizontal << '-' * (col[:length]+2) << '+'\n end\n\n # Print table\n if (print_headings)\n titles = []\n columns.each do |col|\n titles << col[:title]\n end\n #puts table_horizontal\n printf(table_format_title, *titles);\n else\n puts table_horizontal\n end\n\n data.each do |datum|\n cols_ary = []\n columns.each do |col|\n if (col[:func])\n cols_ary << col[:func].call(datum)\n else\n cols_ary << datum[col[:key]]\n end\n end\n printf(table_format_row, *cols_ary)\n #puts table_horizontal\n end\n puts table_horizontal\n\nend",
"def build_table(content)\n table content do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = %w(DDDDDD FFFFFF)\n self.column_widths = [40, 300, 60, 60, 70]\n self.cell_style = {\n border_width: 0,\n size: 10\n }\n end\n end",
"def table \n table = data.map do |slot|\n slot.position.to_s.ljust(12) + slot.license_plate.ljust(19) + slot.color + \"\\n\" if slot\n end.join('')\n end",
"def clean_table(table, number_of_colums)\n above_row = []\n #filter if they are not last column, and they are same as the item on the row above\n table.reduce([]) { |result, row|\n result << row.each_with_index.map do |item,i|\n if i == number_of_colums\n item \n else\n item == above_row[i] ? '' : item \n end\n end\n above_row = row\n result\n }\n end",
"def clean_table(table, number_of_colums)\n above_row = []\n #filter if they are not last column, and they are same as the item on the row above\n table.reduce([]) { |result, row|\n result << row.each_with_index.map do |item,i|\n if i == number_of_colums\n item \n else\n item == above_row[i] ? '' : item \n end\n end\n above_row = row\n result\n }\n end",
"def to_table\n headers = fields.map { |field| field.label.downcase }\n body = fields.map { |field| field.to_s.downcase }\n\n [headers, body]\n end",
"def to_s\n value.map { |ar| ar.map { |v| v.to_s.gsub(/\\t|\\n|\\r/,' ') }.join \"\\t\" }.join($/)\n end",
"def draw_summary_table\n header = [\"Date\", \"Issue Number\", \n \"Total Subscribers\", \"Change in Subscribers\"]\n\n body = report.table(:date,:number,:count,:delta)\n\n document.table([header]+body) do |t|\n t.header = true\n t.style(t.columns(1..-1)) { |c| c.align = :right }\n end\n end",
"def columns_to_s # :nodoc:\n nameline = ' ' * indent\n barline = nameline.dup\n last_col = nil\n last_idx = nil\n columns.each_with_index { |col,idx|\n if (last_col)\n # This produces clean to_s output without truncation\n # Preserves full string in cells for to_csv output\n padding = pad(' ', last_col, last_idx)\n nameline << padding\n remainder = padding.length - cellpad\n remainder = 0 if remainder < 0\n barline << (' ' * (cellpad + remainder))\n end\n\n nameline << col\n barline << ('-' * col.length)\n\n last_col = col\n last_idx = idx\n }\n\n return \"#{nameline}\\n#{barline}\"\n end",
"def to_s\n width = 3\n translations = {\n \"\\n\" => \"\\\\n\",\n \"\\t\" => \"\\\\t\",\n \" \" => \"\\\\s\"\n }\n\n str = \"Transition table:\\n\"\n\n str += \"\".ljust(width)\n @characters.each do |c|\n c = translations[c] if translations.has_key?(c)\n str += c.ljust(width)\n end\n\n str += \"\\n\"\n\n @transition_table.each.with_index do |row, index|\n str += index.to_s.ljust(width)\n @characters.each do |c|\n str += row[c].to_s.ljust(width)\n end\n str += \"\\n\"\n end\n\n str += \"\\nLambda table:\\n\"\n\n str += \"\".ljust(width)\n (0..@state_counter).each do |row|\n str += row.to_s.ljust(width)\n end\n\n str += \"\\n\"\n\n (0..@state_counter).each.with_index do |row, index|\n str += index.to_s.ljust(width)\n (0..@state_counter).each do |col|\n str += @lambda_table[row][col].to_s.ljust(width)\n end\n str += \"\\n\"\n end\n\n return str\n end",
"def table_row(row, alignment)\n\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\n end",
"def to_s\n\t\t@tab.map{|l|\n\t\t\tl.map{|b|\n\t\t\t\tb ? \"*\":\" \"\n\t\t\t}.join\n\n\t\t}.join(\"\\n\")\n\tend",
"def block_textile_table( text ) \n text.gsub!( TABLE_RE ) do |matches|\n\n tatts, fullrow = $~[1..2]\n tatts = pba( tatts, 'table' )\n tatts = shelve( tatts ) if tatts\n rows = []\n\n fullrow.each_line do |row|\n ratts, row = pba( $1, 'tr' ), $2 if row =~ /^(#{A}#{C}\\. )(.*)/m\n cells = []\n row.split( /(\\|)(?![^\\[\\|]*\\]\\])/ )[1..-2].each do |cell|\n next if cell == '|'\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 }</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 \"\\t<table#{ tatts }>\\n#{ rows.join( \"\\n\" ) }\\n\\t</table>\\n\\n\"\n end\n end",
"def columnate!(theWidth, thePad = ' ')\n\n # Setup the basic sizes.\n\n trLen = @theLines.length\n return self if trLen == 0\n thePad = '' if thePad.nil?\n pdWide = thePad.length\n trWide = self.width\n cols = 1\n\n # If there is just no room to break at all, return now.\n\n return self if 2*trWide + pdWide > theWidth\n\n # At least two columns will fit. See how many more will.\n\n 2.upto(theWidth) do |i|\n break if i*trWide + (i-1)*pdWide > theWidth\n cols = i\n end\n \n # Find the length of the basic columns. There may be some extra elements\n # beyond the allocation of the original. Pass them to the columns one by\n # one from left to right.\n\n baseLen = trLen.div(cols)\n theLens = Array.new(cols, baseLen)\n 0.upto(trLen-cols*baseLen-1) { |i| theLens[i] = theLens[i] + 1 }\n\n # Now create an array of lines for each column.\n\n colArrays = Array.new(cols, Array.new)\n colStart = 0\n 0.upto(cols-1) do |i|\n colArrays[i] = @theLines[colStart, theLens[i]]\n colStart += theLens[i]\n end\n\n # Readjust the current TR with the first column of lines.\n\n @theLines = colArrays[0]\n\n # Now for each of the other columns, join it to the existing TR using the\n # pad in between.\n\n 1.upto(cols-1) do |i|\n theCol = TextRect.new(colArrays[i])\n theCol.lPad!(thePad) if pdWide > 0\n self.join!(theCol)\n end\n\n return self\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? ? \" \" : 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",
"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 table_row(row, alignment)\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\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 build_table_body(doc, files)\n doc.tbody {\n files.each do |file|\n doc.tr {\n get_file_meta(file).values.each { |val| doc.td val }\n }\n end\n }\n end",
"def table_close(opts)\n output = \"\\\\begin{table}\\n\"\n output << \" \\\\centering\\n\"\n output << \" \\\\begin{tabular}{ #{\"l \" * @table[0].size }}\\n\"\n @table.each do |row|\n output << \" #{row.join(\" & \")} \\\\\\\\\\n\"\n end\n output << \" \\\\end{tabular}\\n\"\n output << \"\\\\end{table}\\n\"\n output\n end",
"def to_s\n\t\t\ts = edge_row + \"\\n\"\n\t\t\t@n_rows.times do |r|\n\t\t\t\ts << \"|\"\n\t\t\t\t@n_cols.times do |c|\n\t\t\t\t\tcorrect_row_index = @n_rows - r -1 \n\t\t\t\t\t#flip board updside down for representation\n\t\t\t\t\ts << \"#{represent_entry(correct_row_index,c)} |\"\n\t\t\t\tend\n\t\t\t\ts << \"\\n\"\n\t\t\tend\n\t\t\ts << edge_row + \"\\n\"\n\t\t\ts << \" \" + (0..@n_cols -1).to_a.join(' ') + \"\\n\"\n\t\t\treturn s\n\t\tend",
"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 to_s\n data.map { |ar| ar.map { |v| v.to_s.gsub(/\\t|\\n|\\r/,' ') }.join \"\\t\" }.join( $/ )\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 table(*columns, &block)\n\n rows = Array.new\n yield(rows)\n\n # determine maximum cell widths\n max_cell_widths = rows.inject(Array.new(columns.length, 0)) do |result, row|\n lengths = row.map { |column| column.to_s.length }\n result.each_with_index { |length, index| result[index] = ([length, lengths[index]].max rescue length) }\n end\n columns.each_with_index { |col, index| col[:actual_width] ||= max_cell_widths[index] }\n\n # determine actual column width\n column_widths = columns.map do |column|\n if column[:width] == :rest\n nil\n elsif column[:width]\n column[:width]\n elsif column[:min_width]\n [column[:min_width], column[:actual_width]].max\n elsif column[:max_width]\n [column[:max_width], column[:actual_width]].min\n else\n column[:actual_width]\n end\n end\n\n if column_widths.include?(nil)\n fill_column = columns[column_widths.index(nil)]\n width_left = options[:width] - ((columns.length - 1) * (style[:cell_separator] ? 3 : 1)) - column_widths.compact.inject(0) { |sum, col| sum + col}\n column_widths[column_widths.index(nil)] = width_left\n end\n\n line(:green) if @style[:top_line]\n\n # Print table header\n if table_has_header?(columns)\n column_titles = []\n columns.each_with_index do |column, index|\n width = column_widths[index]\n alignment = (column[:align] == :right ? '' : '-')\n column_titles.push(colorize(\"%#{alignment}#{width}s\" % column[:title].to_s[0...width], :bold))\n end\n\n puts column_titles.join(style[:cell_separator] ? \" #{characters[:vertical_line]} \" : ' ')\n line(:green)\n end\n\n # Print the rows\n rows.each do |row|\n row_values = []\n columns.each_with_index do |column, index|\n width = column_widths[index]\n case column[:type]\n when :ratio\n if width > 4\n if column[:treshold] && column[:treshold] < row[index].to_f\n bar = ''\n bar << characters[:block] * (width.to_f * column[:treshold]).round\n bar << colorize(characters[:block] * (width.to_f * (row[index].to_f - column[:treshold])).round, :red)\n row_values.push(bar)\n else\n # Create a bar by combining block characters\n row_values.push(characters[:block] * (width.to_f * row[index].to_f).round)\n end\n else\n # Too few characters for a ratio bar. Display nothing\n row_values.push('')\n end\n else\n alignment = (columns[index][:align] == :right ? '' : '-')\n cell_value = \"%#{alignment}#{width}s\" % row[index].to_s[0...width]\n cell_value = colorize(cell_value, :bold, :brown) if columns[index][:highlight]\n row_values.push(cell_value)\n end\n end\n puts row_values.join(style[:cell_separator] ? \" #{characters[:vertical_line]} \" : ' ')\n end\n end",
"def summary_table\n update_now_date_time\n calc_difference\n labels = [DueText.period, ' ', DueText.duration, DueText.measure]\n rows = summary_array\n puts tabulate(labels, rows, { 'indent' => 4, 'style' => 'fancy' })\n end",
"def to_s\n self.to_a.map{ |row| row.join(' ') }.join(\"\\n\")\n end",
"def inspect\n to_table.render :ascii\n end",
"def to_s\n \"\"\"\n <tr>\n <td>#{@name}</td>\n <td>#{@version}</t>\n <td>#{@release}</td>\n <td>#{@architecture}</td>\n <td>#{@description}</td>\n <tr>\n \"\"\"\n end",
"def accept_table header, body, aligns\n @res << \"\\n<table role=\\\"table\\\">\\n<thead>\\n<tr>\\n\"\n header.zip(aligns) do |text, align|\n @res << '<th'\n @res << ' align=\"' << align << '\"' if align\n @res << '>' << CGI.escapeHTML(text) << \"</th>\\n\"\n end\n @res << \"</tr>\\n</thead>\\n<tbody>\\n\"\n body.each do |row|\n @res << \"<tr>\\n\"\n row.zip(aligns) do |text, align|\n @res << '<td'\n @res << ' align=\"' << align << '\"' if align\n @res << '>' << CGI.escapeHTML(text) << \"</td>\\n\"\n end\n @res << \"</tr>\\n\"\n end\n @res << \"</tbody>\\n</table>\\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"
] | [
"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.5647963",
"0.56272036",
"0.5601708",
"0.5596944",
"0.5571213",
"0.5561446",
"0.55522037",
"0.5530964",
"0.55261236",
"0.5519401",
"0.5506744",
"0.54904395",
"0.5490271",
"0.5462047",
"0.5456329",
"0.54549956",
"0.5441483",
"0.543608",
"0.54201686",
"0.54092723",
"0.54065794",
"0.53981805",
"0.53961235",
"0.53942865",
"0.5393583",
"0.53914905",
"0.5387659",
"0.5381888",
"0.53806096",
"0.5377177",
"0.53659487",
"0.53516287",
"0.534764",
"0.53459924",
"0.53394055",
"0.5327853",
"0.53230417",
"0.53181505",
"0.5316413",
"0.5304418",
"0.53035957",
"0.53020126",
"0.52925915",
"0.52925915",
"0.52879363",
"0.52861744",
"0.5279481",
"0.5274085",
"0.5269971",
"0.5254623",
"0.52524316",
"0.5251058",
"0.5247084",
"0.524505",
"0.5243196",
"0.5238925",
"0.5238777",
"0.52325755",
"0.5229624",
"0.5222327",
"0.5220132",
"0.5216916",
"0.5209465",
"0.5206337",
"0.5204526",
"0.51977044",
"0.51935107",
"0.51890403",
"0.5172734",
"0.51660526"
] | 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 << (1..@generated.length).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 << (1..@expected.length).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 = \" \" 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? ? \" \" : 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",
"def show_body\n brows = []\n current_context[0][:body].map do |hash|\n hash.each do |_key , _val|\n _val = _val.scan(/.{100}/).join(\"\\n\") if _val.size > 150 # This line To fix table layout\n\n brows << [\"#{_key}\".green, \"#{_val}\".white]\n brows << :separator\n end\n end\n\n return brows\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 block_textile_table( text ) \n text.gsub!( TABLE_RE ) do |matches|\n\n tatts, fullrow = $~[1..2]\n tatts = pba( tatts, 'table' )\n tatts = shelve( tatts ) if tatts\n rows = []\n\n fullrow.each_line do |row|\n ratts, row = pba( $1, 'tr' ), $2 if row =~ /^(#{A}#{C}\\. )(.*)/m\n cells = []\n row.split( /(\\|)(?![^\\[\\|]*\\]\\])/ )[1..-2].each do |cell|\n next if cell == '|'\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 }</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 \"\\t<table#{ tatts }>\\n#{ rows.join( \"\\n\" ) }\\n\\t</table>\\n\\n\"\n end\n end",
"def to_s_corrected\n @cells.map { |row| row.join(' ') }.join(\"\\n\")\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 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 wrap(line, cols=80, tabsize=2)\n line = line.gsub(/\\t/, \" \" * tabsize) unless tabsize == nil\n line.gsub(/(.{1,#{cols}})( +|$\\r?\\n?)|(.{1,#{cols}})/, \"\\\\1\\\\3\\n\").split(/\\s*?\\n/)\n end",
"def content\n number_to_skip = 0 # Keeps track of the # of columns to skip\n \n html = ''\n table.header.column_names.each do |column|\n number_to_skip -= 1 and next if number_to_skip > 0\n \n if cell = @cells[column]\n number_to_skip = (cell[:colspan] || 1) - 1\n else\n cell = Cell.new(column, nil)\n end\n \n html << cell.html\n end\n \n html\n end",
"def columnate!(theWidth, thePad = ' ')\n\n # Setup the basic sizes.\n\n trLen = @theLines.length\n return self if trLen == 0\n thePad = '' if thePad.nil?\n pdWide = thePad.length\n trWide = self.width\n cols = 1\n\n # If there is just no room to break at all, return now.\n\n return self if 2*trWide + pdWide > theWidth\n\n # At least two columns will fit. See how many more will.\n\n 2.upto(theWidth) do |i|\n break if i*trWide + (i-1)*pdWide > theWidth\n cols = i\n end\n \n # Find the length of the basic columns. There may be some extra elements\n # beyond the allocation of the original. Pass them to the columns one by\n # one from left to right.\n\n baseLen = trLen.div(cols)\n theLens = Array.new(cols, baseLen)\n 0.upto(trLen-cols*baseLen-1) { |i| theLens[i] = theLens[i] + 1 }\n\n # Now create an array of lines for each column.\n\n colArrays = Array.new(cols, Array.new)\n colStart = 0\n 0.upto(cols-1) do |i|\n colArrays[i] = @theLines[colStart, theLens[i]]\n colStart += theLens[i]\n end\n\n # Readjust the current TR with the first column of lines.\n\n @theLines = colArrays[0]\n\n # Now for each of the other columns, join it to the existing TR using the\n # pad in between.\n\n 1.upto(cols-1) do |i|\n theCol = TextRect.new(colArrays[i])\n theCol.lPad!(thePad) if pdWide > 0\n self.join!(theCol)\n end\n\n return self\n\n end",
"def replace_td_elements_with_new_lines(column)\n column.xpath('br').each do |br_tag|\n br_tag.replace(Nokogiri::XML::Text.new(\"\\n\", column.document))\n end\n end",
"def fold( value )\n value.gsub( /(^[ \\t]+.*$)|(\\S.{0,#{options(:BestWidth) - 1}})(?:[ \\t]+|(\\n+(?=[ \\t]|\\Z))|$)/ ) do\n $1 || $2 + ( $3 || \"\\n\" )\n end\n\t\tend",
"def test_table_too\n return <<HERE;\n 2 3 5 7 11\n 2 4 6 10 14 22\n 3 6 9 15 21 33\n 5 10 15 25 35 55\n 7 14 21 35 49 77\n 11 22 33 55 77 121\nHERE\nend",
"def make_row(column_elements)\n\t\"<tr><td>#{column_elements.join(\"</td><td>\")}</td></tr>\"\nend",
"def row_cells_to_text_columns(table_row)\n table_row.cells.map do |cell|\n # Join paragraphs into a String using a space delimiter.\n cell_paragraphs(cell).join(' ')\n end\n end",
"def output\n # This results in a hash of two-element arrays. The key is the header and\n # the value is an array of the header and formatted header. We do the\n # latter so the structure parallels the structure for rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n result += hline(widths) if loc_row.nil?\n next if loc_row.nil?\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end",
"def to_s\n\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 handle_tab_width(body)\n if /\\t/ =~ body\n tab_width = @options.tab_width\n body.split(/\\n/).map do |line|\n 1 while line.gsub!(/\\t+/) do\n ' ' * (tab_width * $&.length - $`.length % tab_width)\n end && $~\n line\n end.join \"\\n\"\n else\n body\n end\n end",
"def tabulate2 content, options\n widths = calculate_column_widths(content, 99)\n str = \"| \"\n sep = \"+\"\n widths.each do |w|\n str << \"%-#{w}s | \"\n sep << (\"-\"*(w+2)) + \"+\"\n end\n data = []\n data << sep \n content.each_with_index {|line, ix| \n data << str % line \n data << sep if ix == 0\n }\n data << sep\n require 'tempfile'\n tmpfile = Tempfile.new('SQL.XXXXXX')\n filename = tmpfile.path\n #filename = Shellwords.escape(filename)\n #puts \"Writing to #{filename}\"\n tmpfile.write(data.join(\"\\n\"))\n tmpfile.close # need to flush, otherwise write is buffered\n return filename\nend",
"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 table \n table = data.map do |slot|\n slot.position.to_s.ljust(12) + slot.license_plate.ljust(19) + slot.color + \"\\n\" if slot\n end.join('')\n end",
"def parse\n @table = []\n rows = @doc.split(/\\r?\\n/)\n rows.each do |row|\n row_array = row.split(\"|\")\n row_array.each(&:strip!)\n @table.push(row_array)\n end\n @table.delete_at(1) if @header # strip header separator\n @table\n end",
"def transpile\n template.lines.map { |line| Line.new(line).to_text }.join\n end",
"def construct_table(table_values)\n table = String.new\n column_width = 8\n \n if table_values.empty? then return table end\n \n # Construct column headers first\n columns = table_values.values()[0].keys.sort\n table << \"\".center(column_width)\n columns.each do |column|\n table << \"|\" + column.to_s.center(column_width)\n end\n \n table_width = table.length\n table << \"\\n\"\n \n # Construct each row\n rows = table_values.keys.sort\n rows.each do |row|\n table << \"\".center(table_width, \"-\") + \"\\n\"\n table << row.to_s.center(column_width)\n \n row_values = table_values[row]\n columns.each do |column|\n multiple = row_values[column]\n table << \"|\" + multiple.to_s.center(column_width)\n end\n table << \"\\n\"\n end\n return table\nend",
"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 build_verbatim margin\n p :verbatim_begin => margin if @debug\n verbatim = RDoc::Markup::Verbatim.new\n\n min_indent = nil\n generate_leading_spaces = true\n line = ''.dup\n\n until @tokens.empty? do\n type, data, column, = get\n\n if type == :NEWLINE then\n line << data\n verbatim << line\n line = ''.dup\n generate_leading_spaces = true\n next\n end\n\n if column <= margin\n unget\n break\n end\n\n if generate_leading_spaces then\n indent = column - margin\n line << ' ' * indent\n min_indent = indent if min_indent.nil? || indent < min_indent\n generate_leading_spaces = false\n end\n\n case type\n when :HEADER then\n line << '=' * data\n _, _, peek_column, = peek_token\n peek_column ||= column + data\n indent = peek_column - column - data\n line << ' ' * indent\n when :RULE then\n width = 2 + data\n line << '-' * width\n _, _, peek_column, = peek_token\n peek_column ||= column + width\n indent = peek_column - column - width\n line << ' ' * indent\n when :BREAK, :TEXT then\n line << data\n else # *LIST_TOKENS\n list_marker = case type\n when :BULLET then data\n when :LABEL then \"[#{data}]\"\n when :NOTE then \"#{data}::\"\n else # :LALPHA, :NUMBER, :UALPHA\n \"#{data}.\"\n end\n line << list_marker\n peek_type, _, peek_column = peek_token\n unless peek_type == :NEWLINE then\n peek_column ||= column + list_marker.length\n indent = peek_column - column - list_marker.length\n line << ' ' * indent\n end\n end\n\n end\n\n verbatim << line << \"\\n\" unless line.empty?\n verbatim.parts.each { |p| p.slice!(0, min_indent) unless p == \"\\n\" } if min_indent > 0\n verbatim.normalize\n\n p :verbatim_end => margin if @debug\n\n verbatim\n end",
"def test_table\n return <<HERE;\n 2 3 5 7 11\n 3 9 15 21 33\n 5 15 25 35 55\n 7 21 35 49 77\n 11 33 55 77 121\nHERE\nend",
"def table_header\n line = \"File|Total\".dup\n line << \"|Line\" if header_line_rate?\n line << \"|Branch\" if header_branch_rate?\n line << \"\\n\"\n end",
"def to_s\n return '' if cols < 1\n col_sizes = max_col_sizes\n str = heading_str(col_sizes)\n str << separator(col_sizes)\n str << body_str(col_sizes)\n str\n end",
"def to_table\n headers = fields.map { |field| field.label.downcase }\n body = fields.map { |field| field.to_s.downcase }\n\n [headers, body]\n end",
"def body_with_updated_annotations\n RewriteComments.call body do |line_number, line_to_whitespace, whitespace, comment|\n if !comment[VALUE_REGEX]\n [whitespace, comment]\n elsif line_to_whitespace.empty?\n result = results[line_number-1].map { |result| result.gsub \"\\n\", '\\n' }.join(', ')\n [whitespace, CommentFormatter.call(whitespace.size, VALUE_MARKER, result, options)]\n else\n result = results[line_number].map { |result| result.gsub \"\\n\", '\\n' }.join(', ')\n [whitespace, CommentFormatter.call(line_to_whitespace.size + whitespace.size, VALUE_MARKER, result, options)]\n end\n end\n end",
"def clean_table(table, number_of_colums)\n above_row = []\n #filter if they are not last column, and they are same as the item on the row above\n table.reduce([]) { |result, row|\n result << row.each_with_index.map do |item,i|\n if i == number_of_colums\n item \n else\n item == above_row[i] ? '' : item \n end\n end\n above_row = row\n result\n }\n end",
"def clean_table(table, number_of_colums)\n above_row = []\n #filter if they are not last column, and they are same as the item on the row above\n table.reduce([]) { |result, row|\n result << row.each_with_index.map do |item,i|\n if i == number_of_colums\n item \n else\n item == above_row[i] ? '' : item \n end\n end\n above_row = row\n result\n }\n end",
"def to_html\n htmlString = %{<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">}\n htmlString += %{<tr>}\n LineCounter.columnNames.each { |name| htmlString += %{<th>#{name}</th>} }\n htmlString += %{</tr>}\n self.each do |result|\n htmlString += %{<tr>}\n result.to_a.each { |cell| htmlString += %{<td>#{cell}</td> } }\n htmlString += %{</tr>}\n end\n htmlString += %{</table>}\n htmlString += %{<p><em>Generated by } +\n %{<a href=\"http://countloc.rubyforge.org\">countloc</a> version #{VERSION} } +\n %{on #{Time.now.asctime}</em></p>}\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 get_valid_model_table(table)\n new_table = []\n unless table.empty?\n length_table = table.size\n (0..length_table - 1).each do |row_index|\n cells_added = 0\n original_row = [].concat(table[row_index])\n new_table[row_index] = [] if new_table.size <= row_index\n length_row = original_row.size\n (0..length_row - 1).each do |cell_index|\n cell = original_row[cell_index]\n new_cell_index = cell_index + cells_added\n new_row = new_table[row_index]\n until new_row[new_cell_index].nil?\n cells_added += 1\n new_cell_index = cell_index + cells_added\n end\n new_row[new_cell_index] = cell\n\n next unless cell.has_attribute?('rowspan')\n\n rowspan = cell.get_attribute('rowspan').to_i\n\n next unless rowspan > 1\n\n (1..rowspan - 1).each do |rowspan_index|\n new_row_index = row_index + rowspan_index\n new_table[new_row_index] = [] if new_table[new_row_index].nil?\n new_table[new_row_index][new_cell_index] = cell\n end\n end\n end\n end\n new_table\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 build_report_body\n draw_table(data, :width => 600)\n end",
"def tablify(string)\n output = \"<table>\\n\"\n r = 0\n array = string.split(/\\n/)\n array.each do |x|\n if !x.nil?\n output << \"\\t<tr>\\n\"\n x.gsub!(\" \",\"\\t\")\n row = x.split(/\\t/)\n row.each do |y|\n if r>0\n output << \"\\t\\t<td>#{y}</td>\\n\"\n else\n output << \"\\t\\t<th>#{y}</th>\\n\"\n end\n end\n output << \"\\t</tr>\\n\"\n r += 1\n end\n end\n output << \"</table>\\n\\n\"\n return output\nend",
"def build_report_body\n draw_table(data, :width => 700)\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 _tableish(html, row_selector, column_selectors) #:nodoc\n doc = Nokogiri::HTML(html)\n # Parse the table.\n rows = doc.search(row_selector)\n\n max_columns = _row_width(rows[0], column_selectors)\n max_rows = _column_height(rows)\n\n # Initialize a 2 dimensional array representing the size of the table in tableish format\n grid = Array.new(max_rows) { Array.new(max_columns, nil) }\n\n table_row_index = 0\n grid.each_with_index do |grid_row, grid_row_index|\n row = rows[table_row_index]\n\n cells = _select_cells(column_selectors, row)\n table_column_index = 0\n grid_row.size.times do |grid_column_index|\n next if grid[grid_row_index][grid_column_index] != nil\n\n cell = cells[table_column_index]\n if cell\n col_span, row_span = 1, 1\n row_span = cell['rowspan'].to_i - 1 if cell['rowspan']\n col_span = cell['colspan'].to_i - 1 if cell['colspan']\n\n # draw blank cells based on colspan and rowspan\n if cell['rowspan'] && cell['colspan']\n row_span.times do |row_offset|\n row_offset_index = grid_row_index + (row_offset + 1)\n col_span.times do |col_offset|\n col_offset_index = grid_column_index + (col_offset + 1)\n grid[row_offset_index][col_offset_index] = \"\" unless row_offset_index >= rows.size || col_offset_index >= max_columns\n end\n end\n end\n\n if cell['rowspan']\n row_span.times do |row_span_offset|\n row_offset_index = grid_row_index + (row_span_offset + 1)\n grid[row_offset_index][grid_column_index] = \"\" unless row_offset_index >= rows.size\n end\n end\n\n if cell['colspan']\n col_span.times do |col_span_offset|\n col_offset_index = grid_column_index + (col_span_offset + 1)\n grid[grid_row_index][col_offset_index] = \"\" unless col_offset_index >= max_columns\n end\n end\n\n # print cell value into grid and move to next table column, only if cell hasn't been touched yet\n if grid[grid_row_index][grid_column_index] == nil\n table_column_index += 1\n grid[grid_row_index][grid_column_index] = _cell_value(cell)\n end\n end\n end\n table_row_index += 1\n end\n\n _pad_grid_with_blanks(grid)\n\n grid\n end",
"def to_s\n result = ''\n for r in 0..height\n lines = Array.new(cell_height) { '' }\n for c in 0..width\n # Differentiate the behaviour based on the visibility state of four cells at a time\n c1, c2, c3, c4 = self[r-1, c-1], self[r-1, c], self[r, c-1], self[r, c]\n v1, v2, v3, v4 = (c1 and c1.visible), (c2 and c2.visible), (c3 and c3.visible), (c4 and c4.visible)\n if v4\n lines[0] << '#' * cell_width\n (1...cell_height).each do | i | lines[i] << '#' end\n else\n lines[0] << if v1 or v2 or v3\n '#'\n else\n ' '\n end\n lines[0] << if v2\n '#' * (cell_width - 1)\n else\n ' ' * (cell_width - 1)\n end\n if v3\n (1...cell_height).each do | i | lines[i] << '#' end\n else\n (1...cell_height).each do | i | lines[i] << ' ' end\n end\n end\n if v4\n if c4.empty\n lines[1] << c4.number.to_s.ljust(cell_width-1)\n (2...cell_height).each do | i | lines[i] << ' ' * (cell_width-1) end \n else\n (1...cell_height).each do | i | lines[i] << '#' * (cell_width-1) end \n end\n else\n (1...cell_height).each do | i | lines[i] << ' ' * (cell_width-1) end\n end\n end\n result << lines.join(\"\\n\") << \"\\n\"\n end\n result\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 full_table_content\n _rations = squash_rations(format_rations)\n \n move_down(50)\n\n text \"Order for #{@sprint.started_at} to #{@sprint.finished_at}\"\n \n build_table(rations_headers + sort_by_id(_rations))\n\n move_down(10)\n\n text \"Full price for order is #{calculate_full_price(_rations)}\"\n end",
"def tidy(data)\n indent = 0\n data.split(/\\n/).map do |line|\n line.gsub!(/^\\s*/, '')\n next if line.empty?\n indent -= 1 if line =~ /^\\s*\\}\\s*$/\n line = (' ' * (indent * 2)) + line\n indent += 1 if line =~ /\\{\\s*$/\n line\n end.compact.join(\"\\n\") + \"\\n\"\n end",
"def to_s\n str = \"\"\n count_row = 0\n count_col = 0\n str << \"-\"*25 << \"\\n\"\n rows.each do |row|\n row.each do |ele|\n str << ele.to_s << \" \"\n count_col += 1\n if count_col == 3\n str << \"| \"\n count_col = 0\n end\n end\n count_row += 1\n if count_row == 3\n str << \"\\n\" << \"-\"*25 << \"\\n\"\n count_row = 0\n else\n str << \"\\n\"\n end\n end\n str << \"-\"*25\n end",
"def table\r\n\t\tempty = Hash.new\r\n\t\tif @text.length < 2\r\n\t\t\treturn empty\r\n\t\tend\r\n\t\ttableHelper(@tree, \"\")\r\n\t\treturn @table\r\n\tend",
"def build_table(content)\n table content do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = %w(DDDDDD FFFFFF)\n self.column_widths = [40, 300, 60, 60, 70]\n self.cell_style = {\n border_width: 0,\n size: 10\n }\n end\n end",
"def render_tbody\n if @lines and @lines.size > 0\n return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join)))\n return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' }))\n end\n ''\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 generate_migration_body(tables)\n current_tables, new_tables = table_names(tables).partition do |table_name| \n @db_table_names.include?(table_name)\n end\n\n add_line \"change do\"\n create_new_tables(new_tables, tables)\n alter_tables(current_tables, tables)\n add_line \"end\"\n end",
"def table_to_s\n table = Terminal::Table.new do |t|\n symbols = @grammar.terminals.keys.to_a + [Grammar::END_SYM]\n t << [''] + symbols\n\n @grammar.non_terminals.each do |non_terminal|\n t.add_separator\n row = [non_terminal]\n symbols.each { |sym| row << @table[non_terminal][sym].to_s || ' '}\n t << row\n end\n\n end\n table.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 to_s\n data.map { |ar| ar.map { |v| v.to_s.gsub(/\\t|\\n|\\r/,' ') }.join \"\\t\" }.join( $/ )\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 table_trim(b, rain_fall_type, _year, ji, compare)\n dataset = rain_fall_type.tr('_', ' ')\n dataset_compare = compare.tr('_', ' ')\n if rain_fall_type == 'All'\n hash_data = ji.map do |el|\n if el.to_s == 'Year'\n { title: 'Year', field: el, headerFilter: true }\n else\n { title: el.to_s.tr('_', ' ').split.first, field: el }\n end\n end\n else\n\n if compare == 'None'\n hash_data = [\n { title: 'Year', field: 'Year', headerFilter: true },\n { title: dataset.to_s.tr('_', ' ').split.first, field: rain_fall_type }\n\n ]\n else\n hash_data = [{ title: 'Year', field: 'Year', headerFilter: true },\n { title: dataset.to_s.tr('_', ' ').split.first, field: rain_fall_type },\n { title: dataset_compare.to_s.tr('_', ' ').split.first, field: compare }]\n end\n end\n\n data = { column: hash_data, data: b }\n data\n end",
"def render(column_interval=0.01)\n STDERR.puts(\"Rendering with #{column_interval}\")\n ct = 0\n @buffer.each do |row|\n row.each_with_index do |val,i|\n @strip[i]=val\n end\n @strip.write!\n ct += 1\n sleep(column_interval)\n end\n\n STDERR.puts(\"Wrote #{ct} columns.\")\n end",
"def _node_parse_table_cell(node)\n # In a Swordfish::Node::Table object, the number of table cells must equal the\n # total number of rows times the total number of columns; that is, even if\n # two cells are merged together, there must be a Swordfish::Node::TableCell for\n # each one. Merges are defined using the \"merge_up\" and \"merge_left\" properties.\n\n cell = Swordfish::Node::TableCell.new\n extra_cells = []\n\n # Get the inner content of the cell\n node.xpath(\"./w:p\").each do |paragraph|\n cell.append _node_parse_paragraph(paragraph)\n end\n \n # Determine whether this cell spans multiple rows. In Office OpenXML,\n # a table cell is defined in every row, even if the cell is vertically-merged. The representation\n # of the merged cell within each row is given a vMerge property, with the topmost one also\n # having a vMerge value of \"restart\", and the others having no vMerge value.\n if node.xpath(\"./w:tcPr/w:vMerge\").length > 0 && node.xpath(\"./w:tcPr/w:vMerge\")[0]['w:val'].nil?\n cell.merge_up = true\n end\n\n # Determine whether this cell spans multiple columns. Unlike with vertical merges,\n # a horizontally-merged Office OpenXML cell is only defined once, but is given a gridSpan\n # property defining the number of columns it spans. Since Swordfish requires a cell for each\n # column, loop to generate the additional cells, and set their merge_left values appropriately.\n if node.xpath(\"./w:tcPr/w:gridSpan\").length > 0\n node.xpath(\"./w:tcPr/w:gridSpan\")[0]['w:val'].to_i.-(1).times do\n c = Swordfish::Node::TableCell.new\n c.merge_left = true\n extra_cells << c\n end\n end\n\n # Return the generated cell or cells\n if extra_cells.empty?\n return cell\n else\n return [cell] + extra_cells\n end\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 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 to_s\n\t\t@tab.map{|l|\n\t\t\tl.map{|b|\n\t\t\t\tb ? \"*\":\" \"\n\t\t\t}.join\n\n\t\t}.join(\"\\n\")\n\tend",
"def diagonalize\n text_lines = @text_lines ; @text_lines = [ ]\n sltn_lines = @sltn_lines ; @sltn_lines = [ ]\n text_lines.each_with_index do |line, i|\n line.split('').each_with_index do |char, j|\n (@text_lines[i+j] ||= '') << char\n (@sltn_lines[i+j] ||= '') << sltn_lines[i][j]\n end\n end\n end",
"def to_empty\n table.dup.tap do |t|\n t.rows.each do |r, row|\n row.each do |c, cell|\n row.fill(c, Table::Cell::Empty.new(cell))\n end\n end\n end\n end",
"def tabify(item)\n item = item.split(\"\\n\") if item.kind_of? String\n item.map { |i| \" \" + i }.join(\"\\n\")\n end",
"def initialize_table\n @total_rows.times do |row|\n row_array = Array.new(@total_columns, \"\")\n @reconstructed_table.push(row_array)\n end\n end",
"def create_table_fragment(hash, options={})\n c_count = hash.size\n return \"\" if c_count == 0\n\n table_properties = options.delete(:table_properties)\n if table_properties\n table_style = table_properties.table_style\n column_widths = table_properties.column_widths\n column_styles = table_properties.column_styles\n else\n table_style = options.delete(:table_style)\n column_widths = options.delete(:column_widths)\n column_styles = options.delete(:column_styles)\n table_properties = TableProperties.new(table_style, column_widths, column_styles)\n end\n\n skip_header = options.delete(:skip_header)\n fragment = \"<w:tbl>#{table_properties}\"\n\n if column_widths\n fragment << \"<w:tblGrid>\"\n column_widths.each do |column_width|\n fragment << \"<w:gridCol w:w=\\\"#{column_width}\\\"/>\"\n end\n fragment << \"</w:tblGrid>\"\n end\n\n unless skip_header\n fragment << \"<w:tr>\"\n hash.keys.each do |header|\n encoded_header = Nokogiri::XML::Document.new.encode_special_chars(header.to_s)\n fragment << \"<w:tc><w:p><w:r><w:t>#{encoded_header}</w:t></w:r></w:p></w:tc>\"\n end\n fragment << \"</w:tr>\"\n end\n\n r_count = hash.values.inject(0) { |max, value| [max, value.is_a?(Array) ? value.length : (value.nil? ? 0 : 1)].max }\n 0.upto(r_count - 1).each do |i|\n fragment << \"<w:tr>\"\n hash.values.each_with_index do |v, j|\n table_cell = create_table_cell_fragment(v, i,\n :width => column_widths ? column_widths[j] : nil,\n :style => column_styles ? column_styles[j] : nil)\n fragment << table_cell.gsub(\"</w:p><w:p>\", '')\n end\n fragment << \"</w:tr>\"\n end\n\n fragment << \"</w:tbl>\"\n fragment\n end",
"def normalize\n @height = @text_lines.size\n @width = 0\n @sltn_lines = [ ]\n @text_lines.each do |line|\n len = line.length\n @width = len if (len > @width)\n @sltn_lines << '+' * len\n end\n (0...@text_lines.size).each do |i|\n no_pad_chars = @width - @text_lines[i].length\n 1.upto(no_pad_chars) do\n @text_lines[i] << '+'\n @sltn_lines[i] << '+'\n end\n end\n end",
"def draw_table_five_columns(table_info, width_columns = [100, 100, 100, 70, 130])\n table (table_info) do\n columns(0..4).border_width = 1\n columns(0..4).size = 9\n self.column_widths = width_columns\n end\n end",
"def to_s\n \"| #{cells.join(' | ')} |\"\n end",
"def to_s\n value.map { |ar| ar.map { |v| v.to_s.gsub(/\\t|\\n|\\r/,' ') }.join \"\\t\" }.join($/)\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.5320066",
"0.53123915",
"0.53113323",
"0.53061813",
"0.527191",
"0.5256733",
"0.5239399",
"0.5223068",
"0.5189844",
"0.5184551",
"0.51740944",
"0.51716155",
"0.51552254",
"0.5111236",
"0.5106839",
"0.5104583",
"0.51024055",
"0.5095324",
"0.5089024",
"0.5080962",
"0.5075819",
"0.50740284",
"0.50739926",
"0.507346",
"0.5066289",
"0.5059055",
"0.50563216",
"0.50551754",
"0.50500494",
"0.5049571",
"0.5049465",
"0.5049465",
"0.5047693",
"0.50451416",
"0.50435096",
"0.50312215",
"0.50229716",
"0.50163233",
"0.50094664",
"0.50059706",
"0.49933377",
"0.49885014",
"0.49702373",
"0.49529088",
"0.4946678",
"0.49436373",
"0.49348634",
"0.49171975",
"0.49148163",
"0.49114323",
"0.49020177",
"0.4897596",
"0.4891375",
"0.48788062",
"0.4874974",
"0.48705548",
"0.48671985",
"0.48606798",
"0.485684",
"0.484567",
"0.48421735",
"0.48412725",
"0.48364004",
"0.4832248",
"0.48279288",
"0.48224145",
"0.48091447",
"0.48052326",
"0.48000988",
"0.47955096"
] | 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 old_row(chunk)
old_class = {
'-' => 'del',
'+' => '',
'=' => 'unchanged',
'!' => 'del'
}[chunk.action]
[old_class.empty?, chunk.old_element.map { |el| %(<td class="#{old_class}">#{el}</td>) }]
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def new_row(chunk)\n new_class = {\n '-' => '',\n '+' => 'ins',\n '=' => 'unchanged',\n '!' => 'ins'\n }[chunk.action]\n [new_class.empty?, chunk.new_element.map { |el| %(<td class=\"#{new_class}\">#{el}</td>) }]\n end",
"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 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 = \" \"\n value = \" \"\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",
"def build_group_html_rows(group, col_count, label = nil, group_text = nil)\n in_a_widget = self.rpt_options[:in_a_widget] || false\n\n html_rows = []\n\n content =\n if group == :_total_\n _(\"All Rows\")\n else\n group_label = group_text || group\n group_label = _(\"<Empty>\") if group_label.blank?\n \"#{label}#{group_label}\"\n end\n\n if (self.group == 'c') && extras && extras[:grouping] && extras[:grouping][group]\n display_count = _(\"Count: %{number}\") % {:number => extras[:grouping][group][:count]}\n end\n content << \" | #{display_count}\" unless display_count.blank?\n html_rows << \"<tr><td class='group' colspan='#{col_count}'>#{CGI.escapeHTML(content)}</td></tr>\"\n\n if extras && extras[:grouping] && extras[:grouping][group] # See if group key exists\n MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation\n if extras[:grouping][group].key?(calc.first) # Only add a row if there are calcs of this type for this group value\n grp_output = \"\"\n grp_output << \"<tr>\"\n grp_output << \"<td#{in_a_widget ? \"\" : \" class='group'\"} style='text-align:right'>#{_(calc.last)}:</td>\"\n col_order.each_with_index do |c, c_idx| # Go through the columns\n next if c_idx == 0 # Skip first column\n grp_output << \"<td#{in_a_widget ? \"\" : \" class='group'\"} style='text-align:right'>\"\n grp_output << CGI.escapeHTML(\n format(\n c.split(\"__\").first, extras[:grouping][group][calc.first][c],\n :format => self.col_formats[c_idx] ? self.col_formats[c_idx] : :_default_\n )\n ) if extras[:grouping][group].key?(calc.first)\n grp_output << \"</td>\"\n end\n grp_output << \"</tr>\"\n html_rows << grp_output\n end\n end\n end\n html_rows << \"<tr><td class='group_spacer' colspan='#{col_count}'> </td></tr>\" unless group == :_total_\n html_rows\n end",
"def _node_parse_table_cell(node)\n # In a Swordfish::Node::Table object, the number of table cells must equal the\n # total number of rows times the total number of columns; that is, even if\n # two cells are merged together, there must be a Swordfish::Node::TableCell for\n # each one. Merges are defined using the \"merge_up\" and \"merge_left\" properties.\n\n cell = Swordfish::Node::TableCell.new\n extra_cells = []\n\n # Get the inner content of the cell\n node.xpath(\"./w:p\").each do |paragraph|\n cell.append _node_parse_paragraph(paragraph)\n end\n \n # Determine whether this cell spans multiple rows. In Office OpenXML,\n # a table cell is defined in every row, even if the cell is vertically-merged. The representation\n # of the merged cell within each row is given a vMerge property, with the topmost one also\n # having a vMerge value of \"restart\", and the others having no vMerge value.\n if node.xpath(\"./w:tcPr/w:vMerge\").length > 0 && node.xpath(\"./w:tcPr/w:vMerge\")[0]['w:val'].nil?\n cell.merge_up = true\n end\n\n # Determine whether this cell spans multiple columns. Unlike with vertical merges,\n # a horizontally-merged Office OpenXML cell is only defined once, but is given a gridSpan\n # property defining the number of columns it spans. Since Swordfish requires a cell for each\n # column, loop to generate the additional cells, and set their merge_left values appropriately.\n if node.xpath(\"./w:tcPr/w:gridSpan\").length > 0\n node.xpath(\"./w:tcPr/w:gridSpan\")[0]['w:val'].to_i.-(1).times do\n c = Swordfish::Node::TableCell.new\n c.merge_left = true\n extra_cells << c\n end\n end\n\n # Return the generated cell or cells\n if extra_cells.empty?\n return cell\n else\n return [cell] + extra_cells\n end\n end",
"def get_model_row(row)\n new_row = [].concat(row)\n size = row.size\n (0..size - 1).each do |i|\n cell = row[i]\n\n next unless cell.has_attribute?('colspan')\n\n colspan = cell.get_attribute('colspan').to_i\n\n next unless colspan > 1\n\n (1..colspan - 1).each do |j|\n new_row.insert(i + j, cell)\n end\n end\n new_row\n end",
"def in_rows(renderer, *rows, cols: nil, offset: nil)\n rows += yield(renderer) if block_given?\n\n inner_self = self\n\n renderer.call do\n rows.flatten.compact.map do |row|\n div :row do\n html_class = inner_self.col_offset_class(offset) +\n inner_self.col_class(cols)\n\n div(html_class) { row }\n end\n end\n end\n end",
"def id_and_class(options = {}) # change to {}\n\t\tids = [\"id='td_#{self.cell_id(options[:number])}' class='#{self.class_name} #{options[:outer_span]}\"]\n\t\tids << \" \" << options[:target] if options[:target]\n\t\t(ids << \"'\").join\n\t\t# end\n\tend",
"def _node_parse_table_row(node)\n row = Swordfish::Node::TableRow.new\n node.xpath('./w:tc').each do |cell|\n row.append _node_parse_table_cell(cell)\n end\n row\n end",
"def generate_row(row)\n '<tr>' + '<td>' + \"#{(row.map {|x| generate_item(x)}).join('</td><td>')}\" + '</td></tr>' + \"\\n\" \n end",
"def _tableish(html, row_selector, column_selectors) #:nodoc\n doc = Nokogiri::HTML(html)\n # Parse the table.\n rows = doc.search(row_selector)\n\n max_columns = _row_width(rows[0], column_selectors)\n max_rows = _column_height(rows)\n\n # Initialize a 2 dimensional array representing the size of the table in tableish format\n grid = Array.new(max_rows) { Array.new(max_columns, nil) }\n\n table_row_index = 0\n grid.each_with_index do |grid_row, grid_row_index|\n row = rows[table_row_index]\n\n cells = _select_cells(column_selectors, row)\n table_column_index = 0\n grid_row.size.times do |grid_column_index|\n next if grid[grid_row_index][grid_column_index] != nil\n\n cell = cells[table_column_index]\n if cell\n col_span, row_span = 1, 1\n row_span = cell['rowspan'].to_i - 1 if cell['rowspan']\n col_span = cell['colspan'].to_i - 1 if cell['colspan']\n\n # draw blank cells based on colspan and rowspan\n if cell['rowspan'] && cell['colspan']\n row_span.times do |row_offset|\n row_offset_index = grid_row_index + (row_offset + 1)\n col_span.times do |col_offset|\n col_offset_index = grid_column_index + (col_offset + 1)\n grid[row_offset_index][col_offset_index] = \"\" unless row_offset_index >= rows.size || col_offset_index >= max_columns\n end\n end\n end\n\n if cell['rowspan']\n row_span.times do |row_span_offset|\n row_offset_index = grid_row_index + (row_span_offset + 1)\n grid[row_offset_index][grid_column_index] = \"\" unless row_offset_index >= rows.size\n end\n end\n\n if cell['colspan']\n col_span.times do |col_span_offset|\n col_offset_index = grid_column_index + (col_span_offset + 1)\n grid[grid_row_index][col_offset_index] = \"\" unless col_offset_index >= max_columns\n end\n end\n\n # print cell value into grid and move to next table column, only if cell hasn't been touched yet\n if grid[grid_row_index][grid_column_index] == nil\n table_column_index += 1\n grid[grid_row_index][grid_column_index] = _cell_value(cell)\n end\n end\n end\n table_row_index += 1\n end\n\n _pad_grid_with_blanks(grid)\n\n grid\n end",
"def bug_row_helper(bug,opts={})\n opts[:class] ||= 'row'\n \n # this make inline editing work \n @bug = bug\n content = column_helper :class => 'bug col-name', :content => checkbox_helper(opts[:checkbox], {\n :element_id => 'bug_ids',\n :element_value => bug.id,\n :element_default => true,\n :element_link => link_to(h(bug.title),bug)\n })\n \n content << column_helper(:class =>'bug col-name', :content =>in_place_editor_field(@bug, :title,{}, {}))\n content << column_helper(:class =>'bug col-name', :content => @bug.user.login)\n content << column_helper(:class =>'bug col-quantity', :content=>link_to(@bug.comments.size,bug_comments_path(@bug)))\n content << column_helper(:class =>'bug col-quantity', :content =>@bug.human_readable_status)\n content << column_helper(:class => 'bug spacer', :content=>in_place_editor_field(@bug, :description,{}, {:rows=>3} ))\n content_tag('dl',content,:class => opts[:class])\nend",
"def to_renderable(go_down = true, template = read_template('_table_cell.xml.erb'))\n\n horizontal, vertical = calculate_sizing\n\n cells =\n (0..vertical-1).map do |i|\n (0..horizontal-1).map do |j|\n\n options = {}\n if i == 0 && j == 0\n options[:gridspan] = horizontal >= 2 ? horizontal : false\n options[:rowspan] = vertical >= 2 ? vertical : false\n options[:data] = @data\n\n elsif i == 0\n options[:h_merge] = 1\n options[:rowspan] = vertical >= 2 ? vertical : false\n options[:template] = template\n elsif j == 0\n options[:gridspan] = horizontal >= 2 ? horizontal : false\n options[:v_merge] = i\n options[:template] = template\n else\n options[:h_merge] = 1\n options[:v_merge] = i\n options[:template] = template\n end\n\n options[:template] = template\n\n RenderableCell.new(options.merge(@options))\n end\n end\n\n neighbor_rows = @right.flat_map { |n| n.to_renderable(false, template) }\n\n # join right neighbor rows with mine if we have neighbors\n cells = cells.zip(neighbor_rows).map { |myrow, nrow| myrow + nrow } unless neighbor_rows.empty?\n\n return cells if @bottom.empty? || !go_down\n\n bot_rows = @bottom[0].to_renderable(true, template)\n\n cells + bot_rows\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n '</strong></font>'\n \n end",
"def build_cell(cell)\n # implement in row class\n nil\n end",
"def row_for_single(match)\n row = content_tag :tr do\n cells = []\n \n cell = content_tag :td do \n formatted_date(match.date_played) \n end\n cells << cell\n\n cell = content_tag :td do\n match['pname']\n end\n cells << cell\n\n\n\n cell = content_tag :td do \n match.place \n end\n cells << cell\n\n cell = content_tag :td do \n match.surface \n end\n cells << cell\n\n cell = content_tag :td do\n match.environment\n end\n\n cells.join.html_safe\n end\n\n row.html_safe\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n if @strong_on\n \"</strong></font>\"\n else\n \"</font>\"\n end\n \n end",
"def after_cell_render_styling(column_name,cell_value,record)\n if @strong_on\n \"</strong></font>\"\n else\n \"</font>\"\n end\n \n end",
"def generate_line_start(runner, passed)\n \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}' style='#{passed == true ? \"background-color: #e3ffdb; color: #7ab86c;\" : \"background-color: #ffdddd; color: #770000;\"}'><td><strong>#{runner}</strong></td>\"\n end",
"def table_row(row, alignment)\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\n end",
"def table_row(row, alignment)\n\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\n end",
"def make_row(column_elements)\n\t\"<tr><td>#{column_elements.join(\"</td><td>\")}</td></tr>\"\nend",
"def format_rows\n [trait.format_row(self)]\n end",
"def make_header_row(column_elements)\n\t\"<tr style=\\\"background-color: #808080;\\\"><td style=\\\"#{CENTER};\\\"><span style=\\\"#{WHITE};\\\"><strong>\n\t\t#{column_elements.join(\"</strong></span></td><td style=\\\"#{CENTER};\\\"><span style=\\\"#{WHITE};\\\"><strong>\")}\n\t\t</strong></span></td></tr>\"\nend",
"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 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 tr_highlight_simple(model, new_model)\n h = \"highlight\" if model.id == new_model.try(:id)\n n = \" new\" if model.created_at.to_date == Date.today\n\n css_class = \"#{h} #{n}\".squeeze(' ').strip\n\n content_tag :tr, id: css_id(model), data: {id: model.id}, class: css_class do\n yield\n end\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 row_cells_to_text_columns(table_row)\n table_row.cells.map do |cell|\n # Join paragraphs into a String using a space delimiter.\n cell_paragraphs(cell).join(' ')\n end\n end",
"def weight_row_template\n wrap_with :table, class: \"_weight-row-template hidden\" do\n wrap_with :tr do\n card.left.format.weight_row 0, \"\"\n end\n end\n end",
"def render\n if invisible?\n ''\n else\n col_renders = nodes.reject(&:invisible?).map(&:render).join(\"\\n<!-- End Col -->\\n\")\n <<-HTML\n <div class=\"#{row_class}\">\n #{col_renders}\n </div>\n HTML\n end\n end",
"def table_row_by_children node\n newchildren = []\n node.children.each do |child|\n unless child.element?\n next\n end\n\n td = Nokogiri::XML::Node.new( 'td', $document )\n td.children = child.clone\n newchildren << td\n end\n tr = Nokogiri::XML::Node.new( 'tr', $document )\n tr.children = Nokogiri::XML::NodeSet.new( $document, newchildren )\n tr[:class] = node.name\n\n newnode = node.replace tr\n return newnode\nend",
"def highlight_cell(tbl, row, col, id, check: false)\n bg_color = '&#ade6dd' unless check\n\n tbl[row + 1][col + 1] = { content: id,\n check: check,\n class: 'td-full-slot',\n style: {'background-color'=> bg_color}}\n end",
"def tr_highlight(model, new_model)\n css_class = \"highlight\" if model.id == new_model.try(:id)\n content_tag :tr, id: css_id(model), class: css_class do\n yield\n end\n end",
"def rownode_to_row(rownode)\n rownode.xpath('td').map &:text\nend",
"def cell(op, index, table_type)\n snippet = \"\"\n if op.nil?\n snippet += \"<td class='opcode op-#{index} unused'></td>\"\n else\n snippet += \"<td class='opcode op-#{index} #{op['group'].to_s.tr('/', '-')}'>\"\n snippet += \" <div class='mnemonic'>\"\n snippet += \" #{op['mnemonic']} \"\n snippet += \" #{op['operand1']}\" if op['operand1']\n snippet += \" , #{op['operand2']}\" if op['operand2']\n snippet += \" </div>\"\n snippet += \" <div>\"\n snippet += \" <span class='length'>#{op['length']}</span>\"\n snippet += \" <span class='cycles'>#{op['cycles'].join(\"-\")}</span>\"\n snippet += \" </div>\"\n snippet += \" <div class='flags'>#{op['flags'].join(' ')}</div>\"\n snippet += \"</td>\"\n end\n snippet\nend",
"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 table_cell_headers(row_cells)\n list = []\n\n row_cells.each do |cell|\n list << if cell[:list_items].count == 1\n item = cell[:list_items][0]\n this_label(item[:code], item[:action_name], item[:label]) unless item[:label] == false\n else\n ''\n end\n end\n list\n end",
"def make_cells_for_row\n (drill.headers.size).times do |num|\n header_id = drill.headers.sort_by(&:position)[num].id\n self.exercise_items.create(:header_id => header_id)\n end\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 content\n @row.html\n end",
"def monolith_table(groups, metadata)\n checkmark = \" <span style='color: limegreen'>✔</span>\"\n\n # TODO: The checkmark crap below needs to be abstracted.\n formatters = {\n 'New' => proc { |f, l| ['', '', l] },\n 'Updated' => proc { |f, l| ['', '', l + (metadata[f]['installed'].any? ? checkmark : '' ) ] },\n 'Renamed' => proc { |f, l| [\"#{metadata[f]['oldname']}\" + (metadata[f]['installed'].any? ? checkmark : '' ), \"→\", l ] }\n }\n\n table = HTML::Table.new do |t|\n t.align = 'center'\n end\n\n groups.each do |group_name, members|\n title = Table::Row.new do |r|\n r.content = ['', '', group_name]\n end\n title.class_ = 'title'\n table.push title\n\n formatter = formatters[group_name]\n\n members.each do |formula|\n content = Table::Row.new do |r|\n link = \"<a href=#{metadata[formula]['homepage']}>#{formula}</a>\"\n r.content = formatter.call(formula, link).push(\n h(metadata[formula]['desc'])\n )\n r.first.class_ = 'name'\n end\n table.push content\n end\n end\n\n table\nend",
"def seq_cell_status(otu, gene) # :yields: HTML cell representation of this gene/OTU combination results \r\n # want 'done', 'data not done', 'add', with links to show seq \r\n\r\n if seqs = otu.sequences(:gene_ids => [gene.id]) \r\n \r\n if seqs.size == 0\r\n return content_tag(:td, 0)\r\n else\r\n return content_tag(:td, seqs.size)\r\n end\r\n\r\n else \r\n return content_tag(:td, link_to('add', {:controller => :seqs, :action => \"new_from_table\", :otu_id => otu_id, :gene_id => gene_id }), :class => \"no_decision\")\r\n end\r\n\r\n #rescue \r\n # return \"error: \" + otu_id.to_s + \" \" + gene_id.to_s + \" \" + @proj.id.to_s \r\n #end\r\n\r\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n \n \"</font>\"\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n \n \"</font>\"\n end",
"def generate_buyflow_table(suite)\n results = suite.testruns\n sum = 0\n failErrorSummary = ''\n color_status = ''\n results.entries.each do |row|\n color_status = \"#009900\" if row[\"result\"].upcase == \"PASS\"\n color_status = \"#FF9900\" if row[\"result\"].upcase == \"ERR\"\n color_status = \"#FF3300\" if row[\"result\"].upcase == \"FAIL\"\n failErrorSummary +=\"\"\"\n <tr>\n <td style='background-color: #{color_status}; color:#FFFFFF; border: 1px solid black;' align='center'><strong><font face='verdana' size='1'>#{row[\"result\"]}</font></strong></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"Brand\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"Campaign\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ExpectedOffercode\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ActualOffercode\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ConfirmationNum\"]}</font></td>\n </tr>\n \"\"\"\n end\n\n errorTable = ''\n unless failErrorSummary == ''\n errorTable = \"\"\"\n <br />\n <br />\n <table border: 1px solid black; bgcolor='#000000' width='100%' color='#FFFFFF' cellpadding='10' cellspacing='0'>\n <tr>\n <td align='center'>\n <b><font face='verdana' size='3' color='#FFFFFF'>\n Test Run results\n </font></b>\n </td>\n </tr>\n </table>\n <table style='border: 1px solid black; table-layout: fixed;' cellpadding='5px' cellspacing='0' bgcolor='#FFFFFF' width='100%'>\n <tr style='text-align: center; color:#ffffff;' bgcolor='#4E5E66'>\n <td style='border: 1px solid black;'>\n <strong>\n Status\n </strong>\n </td>\n <td width='20%' style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Test Name</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Brand</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Expected Offercode</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Actual Offercode</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Conf #</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Notes</font></strong>\n </td>\n </tr>\n #{failErrorSummary}\n </table>\n \"\"\"\n end\n return errorTable\n end",
"def to_data(force_level = :none)\n cells = [] \n merges = []\n col_widths = {}\n row_heights = {}\n\n css.reset(force_level)\n\n tb = doc.css('table').first \n\n # ignoring specified formats for anything other than table tr td/th\n tb_format = css.format_from_node(tb) \n\n row = 0\n doc.css('tr').each do |tr|\n tr_format = tb_format.merge(@css.format_from_node(tr))\n\n increment = true\n tr.css('td, th').each_with_index do |td, col|\n \n # TODO Do we really need rowheight and colwidth now that there\n # is css parsing?\n rowheight = td.attributes[\"rowheight\"]\n colwidth = td.attributes[\"colwidth\"]\n rowspan = td.attributes[\"rowspan\"]\n colspan = td.attributes[\"colspan\"]\n\n rowheight &&= rowheight.value.to_i\n colwidth &&= colwidth.value.to_i\n rowspan &&= rowspan.value.to_i\n colspan &&= colspan.value.to_i\n\n add_td_to_cells(row, col, td, tr_format, cells)\n if colspan\n (1..colspan-1).each {|t| \n add_td_to_cells(row, col+t, td, tr_format, cells)\n }\n end\n if rowspan\n (1..rowspan-2).each {|t| \n add_td_to_cells(row+t, col, td, tr_format, cells)\n }\n increment = false\n end\n if colspan || rowspan\n merges << [\n row, col, row + (rowspan || 2)-2, col + (colspan || 1)-1\n ]\n end\n end\n\n row += 1 if increment\n end\n\n puts cells.inspect\n { cells: cells, merges: { 0 => merges } }\n end",
"def convert_row(row_hash)\n result = ''\n row_hash.each_value do|col|\n result << '<td>'\n case col\n # Handle simple columns here, pass off more complex ones\n when String, Fixnum then result << col.to_s\n when NilClass then result << ''\n when Array then result << convert_array(col)\n else\n result << 'Unknown data type!!!'\n end\n result << '</td>'\n end\n result\n end",
"def error_messages_for_tr(clazz)\n if clazz.present? && clazz.errors.present? && clazz.errors.count > 0\n return \"<tr><td><div class='error'>Errors: #{clazz.errors.full_messages}</div></td></tr>\".html_safe\n end\n end",
"def row_cells\n rowdata = []\n print_layout.each do |section|\n rowdata += row_cell_items(section[:row_cells])\n end\n rowdata\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n\n \"</font>\"\n end",
"def render_tbody\n if @lines and @lines.size > 0\n return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join)))\n return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' }))\n end\n ''\n end",
"def mobile_outstanding_rsvp_sidebar_row(meeting, invitee, klass)\n\t res = ''\n\t row_id = \"outstanding_#{invitee.id}\"\n\t if invitee.is_a?(Member)\n\t res << content_tag('td', link_to(truncate(invitee.user_name, 18), member_profile_url(:id => invitee.user_name), :title => invitee.user_name, :alt => invitee.user_name))\n\t select = select_tag(\"status_for_#{invitee.id}\", options_for_select(['Approve', 'Decline'])) \n\t res << content_tag('td', select, :class => 'approve_decline')\n\t end\n\t content_tag('tr', res, :class => klass, :id => row_id )\n end",
"def all_input_tags_wrapper(record, rows)\n \"\\n<table class='#{record.class.scaffold_table_class :form}'><tbody>\\n#{rows.join}</tbody></table>\\n\"\n end",
"def process_row(row)\n row\n end",
"def process_row\n # overwrite this class\n end",
"def health_history_row f, *args\n content_tag :div, class:'row', style:'margin:0' do\n args.map{ |arg|\n content = \n if arg.is_a? String\n arg\n elsif arg.is_a? Symbol\n check_and_label_tags arg, arg.to_s.titleize\n elsif arg.is_a? Array\n check_and_label_tags *arg\n end\n content_tag :div, content, class:'span2'\n }.join(\"\\n\").html_safe\n end\n end",
"def comment_row_helper(comment,opts={})\n opts[:class] ||= 'row'\n \n # this make inline editing work \n @comment = comment\n \n content = checkbox_helper(opts[:checkbox], {\n :element_id => 'comment_ids',\n :element_value => comment.id,\n :element_default => true,\n :element_link => link_to(h(comment.detail.capitalize),bug_path(comment.bug))\n })\n \n content = column_helper(:class =>'comment col-reporter', :content => \"posted by #{@comment.user.login}\")\n content << column_helper( :class => 'comment col-description', :content => h(comment.detail.capitalize))\n content_tag('dl',content,:class => opts[:class])\nend",
"def group_rows(group, col_count, group_text = nil)\n mri = options.mri\n grp_output = \"\"\n if mri.extras[:grouping] && mri.extras[:grouping][group] # See if group key exists\n if mri.group == \"c\" # Show counts row\n if group == :_total_\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>Count for All Rows: #{mri.extras[:grouping][group][:count]}</td></tr>\"\n else\n g = group_text ? group_text : group\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>Count for #{g.blank? ? \"<blank>\" : g}: #{mri.extras[:grouping][group][:count]}</td></tr>\"\n end\n else\n if group == :_total_\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>All Rows</td></tr>\"\n else\n g = group_text ? group_text : group\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>#{g.blank? ? \"<blank>\" : g} </td></tr>\"\n end\n end\n MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation\n if mri.extras[:grouping][group].key?(calc.first) # Only add a row if there are calcs of this type for this group value\n grp_output << \"<tr>\"\n grp_output << \"<td class='group'>#{calc.last.pluralize}:</td>\"\n mri.col_order.each_with_index do |c, c_idx| # Go through the columns\n next if c_idx == 0 # Skip first column\n grp_output << \"<td class='group' style='text-align:right'>\"\n grp_output << CGI.escapeHTML(mri.format(c.split(\"__\").first,\n mri.extras[:grouping][group][calc.first][c],\n :format => mri.col_formats[c_idx] ? mri.col_formats[c_idx] : :_default_\n )\n ) if mri.extras[:grouping][group].key?(calc.first)\n grp_output << \"</td>\"\n end\n grp_output << \"</tr>\"\n end\n end\n end\n grp_output << \"<tr><td class='group' colspan='#{col_count}'> </td></tr>\" unless group == :_total_\n grp_output\n end",
"def build_row(row, i)\n row.map.with_index do |piece, j|\n color_options = colors_for(i,j)\n piece.to_s.colorize(color_options)\n end\n end",
"def build_table(content)\n table content do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = %w(DDDDDD FFFFFF)\n self.column_widths = [40, 300, 60, 60, 70]\n self.cell_style = {\n border_width: 0,\n size: 10\n }\n end\n end",
"def row_cell(tag_string, cell={}, row={})\n cell = self.tag('cell', tag_string, cell)\n self.tag('row', cell, row)\n end",
"def form_table_element(*args, &block)\n content, options = filter_tag_args(*args)\n options[:class] = (dom_class = options.delete(:class) ? \"fieldRow #{dom_class}\" : 'fieldRow')\n if block_given? && !content\n concat tag(\"td\", \n {:class => cycle('formBoxTwoColumnsLeftColumn', 'formBoxTwoColumnsRightColumn', :name => 'form_box_two_columns'),\n :style => \"vertical-align:top;\"}, true)\n concat content_tag(\"dl\", capture(&block), options)\n concat \"</td>\"\n else\n content_tag(\"td\", content_tag(\"dl\", content, options), \n {:class => cycle('formBoxTwoColumnsLeftColumn', 'formBoxTwoColumnsRightColumn', :name => 'form_box_two_columns')})\n end\n end",
"def bid_cells(bid, seed_on_left_or_right)\n options = {:align => seed_on_left_or_right, :style => \"border-bottom: 1px solid black; padding-#{seed_on_left_or_right}: 2mm;\"}\n seed = content_tag :td, (bid ? \"(#{bid.seed})\" : ' '), options\n team = content_tag :td, (bid ? h(bid.team.name) : ' '), options\n cells = [seed, team]\n cells.reverse! if 'right' == seed_on_left_or_right\n cells\n end",
"def handle_row(business, row)\n\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 build_table_helpers(resource)\n @module.module_eval <<-end_eval\n def #{resource.singular}_table(opts={}, &block)\n content = capture(&block)\n opts[:class] = ResourcefulViews.resourceful_classnames('#{resource.singular}_table', *(opts.delete(:class) || '').split)\n concat(content_tag(:table, content, opts))\n end\n def #{resource.singular}_row(*args, &block)\n opts = args.extract_options!\n opts[:class] = ResourcefulViews.resourceful_classnames('#{resource.singular}', *(opts.delete(:class) || '').split)\n opts[:id] = '#{resource.singular}_' + args.first.id.to_s unless args.empty?\n content = capture(&block)\n concat(content_tag(:tr, content, opts))\n end\n end_eval\n end",
"def time_rows\n rows = []\n (0..NUM_HALF_HOURS-1).each do |half_hour|\n cols = []\n row = content_tag :tr do\n cols << hour_cell(half_hour)\n cols << minute_cell(half_hour)\n (0..(num_days-1)).each do |day|\n cols << event_cells(half_hour,day)\n end\n cols.join.html_safe\n end\n rows << row\n end\n rows.join.html_safe\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n '</font>' if column_name != \"id\"\n \n end",
"def plan_header_cell(plan, index, plan_size)\n classes = []\n classes << 'plan_name' << 'thhead'\n classes << 'thead_first' if index == 0\n classes << 'thead_last' if (index + 1) == plan_size\n classes << 'selected' if plan.bought_by?(current_account)\n\n content_tag('td', :class => classes.join(' ')) do\n content_tag('h3', h(plan.name))\n end\n end",
"def form_row(label,field)\n \tcontent_tag(:tr, content_tag(:th, label) + content_tag(:td, field))\n \tend",
"def parse_row(row)\n cells = row.css('td')\n return nil if cells.nil?\n\n {\n \"volfdnr\" => extract_id(cells[0]),\n \"title\" => extract_text(cells[1]),\n \"presenter\" => extract_text(cells[3]),\n \"date\" => extract_text(cells[4]),\n \"type\" => extract_text(cells[5])\n }\nend",
"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 << (1..@generated.length).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 << (1..@expected.length).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"
] | [
"0.7510548",
"0.7364384",
"0.66827005",
"0.66615427",
"0.6320908",
"0.6252681",
"0.6111531",
"0.6109477",
"0.6099684",
"0.6079694",
"0.60587615",
"0.60540134",
"0.60315174",
"0.5992878",
"0.59632367",
"0.5950665",
"0.59503984",
"0.58869535",
"0.5861187",
"0.5830213",
"0.5727594",
"0.56854326",
"0.5679809",
"0.5667932",
"0.5664823",
"0.5658942",
"0.5637213",
"0.55830187",
"0.5582427",
"0.5570482",
"0.55702484",
"0.55508614",
"0.5549735",
"0.5547941",
"0.55463684",
"0.5526755",
"0.5517736",
"0.55107903",
"0.549584",
"0.5479578",
"0.5473442",
"0.5464365",
"0.54548264",
"0.543736",
"0.543736",
"0.54372543",
"0.5437223",
"0.5437063",
"0.5431314",
"0.54309493",
"0.54261124",
"0.5422882",
"0.5418061",
"0.5412763",
"0.5393207",
"0.5380824",
"0.53446203",
"0.5341976",
"0.53408307",
"0.53399456",
"0.5339463",
"0.5307976",
"0.53034276",
"0.52815247",
"0.52721345",
"0.52692425",
"0.52681637",
"0.5259285",
"0.52584314",
"0.5258229",
"0.52556956",
"0.52556956",
"0.52527136",
"0.5244215",
"0.5241516",
"0.52379626",
"0.5236968",
"0.5231273",
"0.52273667",
"0.52253556",
"0.522362",
"0.52196807",
"0.5219664",
"0.5219559",
"0.52170146",
"0.52148014",
"0.521245",
"0.5210411",
"0.5208056",
"0.52049315",
"0.5204612",
"0.5201176",
"0.520061",
"0.51959634",
"0.51891017",
"0.51879275",
"0.5185887",
"0.518238",
"0.5179676",
"0.5168312"
] | 0.68154114 | 2 |
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 = \" \"\n value = \" \"\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",
"def build_group_html_rows(group, col_count, label = nil, group_text = nil)\n in_a_widget = self.rpt_options[:in_a_widget] || false\n\n html_rows = []\n\n content =\n if group == :_total_\n _(\"All Rows\")\n else\n group_label = group_text || group\n group_label = _(\"<Empty>\") if group_label.blank?\n \"#{label}#{group_label}\"\n end\n\n if (self.group == 'c') && extras && extras[:grouping] && extras[:grouping][group]\n display_count = _(\"Count: %{number}\") % {:number => extras[:grouping][group][:count]}\n end\n content << \" | #{display_count}\" unless display_count.blank?\n html_rows << \"<tr><td class='group' colspan='#{col_count}'>#{CGI.escapeHTML(content)}</td></tr>\"\n\n if extras && extras[:grouping] && extras[:grouping][group] # See if group key exists\n MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation\n if extras[:grouping][group].key?(calc.first) # Only add a row if there are calcs of this type for this group value\n grp_output = \"\"\n grp_output << \"<tr>\"\n grp_output << \"<td#{in_a_widget ? \"\" : \" class='group'\"} style='text-align:right'>#{_(calc.last)}:</td>\"\n col_order.each_with_index do |c, c_idx| # Go through the columns\n next if c_idx == 0 # Skip first column\n grp_output << \"<td#{in_a_widget ? \"\" : \" class='group'\"} style='text-align:right'>\"\n grp_output << CGI.escapeHTML(\n format(\n c.split(\"__\").first, extras[:grouping][group][calc.first][c],\n :format => self.col_formats[c_idx] ? self.col_formats[c_idx] : :_default_\n )\n ) if extras[:grouping][group].key?(calc.first)\n grp_output << \"</td>\"\n end\n grp_output << \"</tr>\"\n html_rows << grp_output\n end\n end\n end\n html_rows << \"<tr><td class='group_spacer' colspan='#{col_count}'> </td></tr>\" unless group == :_total_\n html_rows\n end",
"def _node_parse_table_cell(node)\n # In a Swordfish::Node::Table object, the number of table cells must equal the\n # total number of rows times the total number of columns; that is, even if\n # two cells are merged together, there must be a Swordfish::Node::TableCell for\n # each one. Merges are defined using the \"merge_up\" and \"merge_left\" properties.\n\n cell = Swordfish::Node::TableCell.new\n extra_cells = []\n\n # Get the inner content of the cell\n node.xpath(\"./w:p\").each do |paragraph|\n cell.append _node_parse_paragraph(paragraph)\n end\n \n # Determine whether this cell spans multiple rows. In Office OpenXML,\n # a table cell is defined in every row, even if the cell is vertically-merged. The representation\n # of the merged cell within each row is given a vMerge property, with the topmost one also\n # having a vMerge value of \"restart\", and the others having no vMerge value.\n if node.xpath(\"./w:tcPr/w:vMerge\").length > 0 && node.xpath(\"./w:tcPr/w:vMerge\")[0]['w:val'].nil?\n cell.merge_up = true\n end\n\n # Determine whether this cell spans multiple columns. Unlike with vertical merges,\n # a horizontally-merged Office OpenXML cell is only defined once, but is given a gridSpan\n # property defining the number of columns it spans. Since Swordfish requires a cell for each\n # column, loop to generate the additional cells, and set their merge_left values appropriately.\n if node.xpath(\"./w:tcPr/w:gridSpan\").length > 0\n node.xpath(\"./w:tcPr/w:gridSpan\")[0]['w:val'].to_i.-(1).times do\n c = Swordfish::Node::TableCell.new\n c.merge_left = true\n extra_cells << c\n end\n end\n\n # Return the generated cell or cells\n if extra_cells.empty?\n return cell\n else\n return [cell] + extra_cells\n end\n end",
"def get_model_row(row)\n new_row = [].concat(row)\n size = row.size\n (0..size - 1).each do |i|\n cell = row[i]\n\n next unless cell.has_attribute?('colspan')\n\n colspan = cell.get_attribute('colspan').to_i\n\n next unless colspan > 1\n\n (1..colspan - 1).each do |j|\n new_row.insert(i + j, cell)\n end\n end\n new_row\n end",
"def id_and_class(options = {}) # change to {}\n\t\tids = [\"id='td_#{self.cell_id(options[:number])}' class='#{self.class_name} #{options[:outer_span]}\"]\n\t\tids << \" \" << options[:target] if options[:target]\n\t\t(ids << \"'\").join\n\t\t# end\n\tend",
"def in_rows(renderer, *rows, cols: nil, offset: nil)\n rows += yield(renderer) if block_given?\n\n inner_self = self\n\n renderer.call do\n rows.flatten.compact.map do |row|\n div :row do\n html_class = inner_self.col_offset_class(offset) +\n inner_self.col_class(cols)\n\n div(html_class) { row }\n end\n end\n end\n end",
"def _node_parse_table_row(node)\n row = Swordfish::Node::TableRow.new\n node.xpath('./w:tc').each do |cell|\n row.append _node_parse_table_cell(cell)\n end\n row\n end",
"def generate_row(row)\n '<tr>' + '<td>' + \"#{(row.map {|x| generate_item(x)}).join('</td><td>')}\" + '</td></tr>' + \"\\n\" \n end",
"def _tableish(html, row_selector, column_selectors) #:nodoc\n doc = Nokogiri::HTML(html)\n # Parse the table.\n rows = doc.search(row_selector)\n\n max_columns = _row_width(rows[0], column_selectors)\n max_rows = _column_height(rows)\n\n # Initialize a 2 dimensional array representing the size of the table in tableish format\n grid = Array.new(max_rows) { Array.new(max_columns, nil) }\n\n table_row_index = 0\n grid.each_with_index do |grid_row, grid_row_index|\n row = rows[table_row_index]\n\n cells = _select_cells(column_selectors, row)\n table_column_index = 0\n grid_row.size.times do |grid_column_index|\n next if grid[grid_row_index][grid_column_index] != nil\n\n cell = cells[table_column_index]\n if cell\n col_span, row_span = 1, 1\n row_span = cell['rowspan'].to_i - 1 if cell['rowspan']\n col_span = cell['colspan'].to_i - 1 if cell['colspan']\n\n # draw blank cells based on colspan and rowspan\n if cell['rowspan'] && cell['colspan']\n row_span.times do |row_offset|\n row_offset_index = grid_row_index + (row_offset + 1)\n col_span.times do |col_offset|\n col_offset_index = grid_column_index + (col_offset + 1)\n grid[row_offset_index][col_offset_index] = \"\" unless row_offset_index >= rows.size || col_offset_index >= max_columns\n end\n end\n end\n\n if cell['rowspan']\n row_span.times do |row_span_offset|\n row_offset_index = grid_row_index + (row_span_offset + 1)\n grid[row_offset_index][grid_column_index] = \"\" unless row_offset_index >= rows.size\n end\n end\n\n if cell['colspan']\n col_span.times do |col_span_offset|\n col_offset_index = grid_column_index + (col_span_offset + 1)\n grid[grid_row_index][col_offset_index] = \"\" unless col_offset_index >= max_columns\n end\n end\n\n # print cell value into grid and move to next table column, only if cell hasn't been touched yet\n if grid[grid_row_index][grid_column_index] == nil\n table_column_index += 1\n grid[grid_row_index][grid_column_index] = _cell_value(cell)\n end\n end\n end\n table_row_index += 1\n end\n\n _pad_grid_with_blanks(grid)\n\n grid\n end",
"def bug_row_helper(bug,opts={})\n opts[:class] ||= 'row'\n \n # this make inline editing work \n @bug = bug\n content = column_helper :class => 'bug col-name', :content => checkbox_helper(opts[:checkbox], {\n :element_id => 'bug_ids',\n :element_value => bug.id,\n :element_default => true,\n :element_link => link_to(h(bug.title),bug)\n })\n \n content << column_helper(:class =>'bug col-name', :content =>in_place_editor_field(@bug, :title,{}, {}))\n content << column_helper(:class =>'bug col-name', :content => @bug.user.login)\n content << column_helper(:class =>'bug col-quantity', :content=>link_to(@bug.comments.size,bug_comments_path(@bug)))\n content << column_helper(:class =>'bug col-quantity', :content =>@bug.human_readable_status)\n content << column_helper(:class => 'bug spacer', :content=>in_place_editor_field(@bug, :description,{}, {:rows=>3} ))\n content_tag('dl',content,:class => opts[:class])\nend",
"def to_renderable(go_down = true, template = read_template('_table_cell.xml.erb'))\n\n horizontal, vertical = calculate_sizing\n\n cells =\n (0..vertical-1).map do |i|\n (0..horizontal-1).map do |j|\n\n options = {}\n if i == 0 && j == 0\n options[:gridspan] = horizontal >= 2 ? horizontal : false\n options[:rowspan] = vertical >= 2 ? vertical : false\n options[:data] = @data\n\n elsif i == 0\n options[:h_merge] = 1\n options[:rowspan] = vertical >= 2 ? vertical : false\n options[:template] = template\n elsif j == 0\n options[:gridspan] = horizontal >= 2 ? horizontal : false\n options[:v_merge] = i\n options[:template] = template\n else\n options[:h_merge] = 1\n options[:v_merge] = i\n options[:template] = template\n end\n\n options[:template] = template\n\n RenderableCell.new(options.merge(@options))\n end\n end\n\n neighbor_rows = @right.flat_map { |n| n.to_renderable(false, template) }\n\n # join right neighbor rows with mine if we have neighbors\n cells = cells.zip(neighbor_rows).map { |myrow, nrow| myrow + nrow } unless neighbor_rows.empty?\n\n return cells if @bottom.empty? || !go_down\n\n bot_rows = @bottom[0].to_renderable(true, template)\n\n cells + bot_rows\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n '</strong></font>'\n \n end",
"def build_cell(cell)\n # implement in row class\n nil\n end",
"def row_for_single(match)\n row = content_tag :tr do\n cells = []\n \n cell = content_tag :td do \n formatted_date(match.date_played) \n end\n cells << cell\n\n cell = content_tag :td do\n match['pname']\n end\n cells << cell\n\n\n\n cell = content_tag :td do \n match.place \n end\n cells << cell\n\n cell = content_tag :td do \n match.surface \n end\n cells << cell\n\n cell = content_tag :td do\n match.environment\n end\n\n cells.join.html_safe\n end\n\n row.html_safe\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n if @strong_on\n \"</strong></font>\"\n else\n \"</font>\"\n end\n \n end",
"def after_cell_render_styling(column_name,cell_value,record)\n if @strong_on\n \"</strong></font>\"\n else\n \"</font>\"\n end\n \n end",
"def generate_line_start(runner, passed)\n \"<tr class='#{ i % 2 == 0 ? 'a' : 'b'}' style='#{passed == true ? \"background-color: #e3ffdb; color: #7ab86c;\" : \"background-color: #ffdddd; color: #770000;\"}'><td><strong>#{runner}</strong></td>\"\n end",
"def table_row(row, alignment)\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\n end",
"def table_row(row, alignment)\n\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\n end",
"def make_row(column_elements)\n\t\"<tr><td>#{column_elements.join(\"</td><td>\")}</td></tr>\"\nend",
"def format_rows\n [trait.format_row(self)]\n end",
"def make_header_row(column_elements)\n\t\"<tr style=\\\"background-color: #808080;\\\"><td style=\\\"#{CENTER};\\\"><span style=\\\"#{WHITE};\\\"><strong>\n\t\t#{column_elements.join(\"</strong></span></td><td style=\\\"#{CENTER};\\\"><span style=\\\"#{WHITE};\\\"><strong>\")}\n\t\t</strong></span></td></tr>\"\nend",
"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 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 tr_highlight_simple(model, new_model)\n h = \"highlight\" if model.id == new_model.try(:id)\n n = \" new\" if model.created_at.to_date == Date.today\n\n css_class = \"#{h} #{n}\".squeeze(' ').strip\n\n content_tag :tr, id: css_id(model), data: {id: model.id}, class: css_class do\n yield\n end\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 row_cells_to_text_columns(table_row)\n table_row.cells.map do |cell|\n # Join paragraphs into a String using a space delimiter.\n cell_paragraphs(cell).join(' ')\n end\n end",
"def weight_row_template\n wrap_with :table, class: \"_weight-row-template hidden\" do\n wrap_with :tr do\n card.left.format.weight_row 0, \"\"\n end\n end\n end",
"def render\n if invisible?\n ''\n else\n col_renders = nodes.reject(&:invisible?).map(&:render).join(\"\\n<!-- End Col -->\\n\")\n <<-HTML\n <div class=\"#{row_class}\">\n #{col_renders}\n </div>\n HTML\n end\n end",
"def table_row_by_children node\n newchildren = []\n node.children.each do |child|\n unless child.element?\n next\n end\n\n td = Nokogiri::XML::Node.new( 'td', $document )\n td.children = child.clone\n newchildren << td\n end\n tr = Nokogiri::XML::Node.new( 'tr', $document )\n tr.children = Nokogiri::XML::NodeSet.new( $document, newchildren )\n tr[:class] = node.name\n\n newnode = node.replace tr\n return newnode\nend",
"def highlight_cell(tbl, row, col, id, check: false)\n bg_color = '&#ade6dd' unless check\n\n tbl[row + 1][col + 1] = { content: id,\n check: check,\n class: 'td-full-slot',\n style: {'background-color'=> bg_color}}\n end",
"def tr_highlight(model, new_model)\n css_class = \"highlight\" if model.id == new_model.try(:id)\n content_tag :tr, id: css_id(model), class: css_class do\n yield\n end\n end",
"def rownode_to_row(rownode)\n rownode.xpath('td').map &:text\nend",
"def cell(op, index, table_type)\n snippet = \"\"\n if op.nil?\n snippet += \"<td class='opcode op-#{index} unused'></td>\"\n else\n snippet += \"<td class='opcode op-#{index} #{op['group'].to_s.tr('/', '-')}'>\"\n snippet += \" <div class='mnemonic'>\"\n snippet += \" #{op['mnemonic']} \"\n snippet += \" #{op['operand1']}\" if op['operand1']\n snippet += \" , #{op['operand2']}\" if op['operand2']\n snippet += \" </div>\"\n snippet += \" <div>\"\n snippet += \" <span class='length'>#{op['length']}</span>\"\n snippet += \" <span class='cycles'>#{op['cycles'].join(\"-\")}</span>\"\n snippet += \" </div>\"\n snippet += \" <div class='flags'>#{op['flags'].join(' ')}</div>\"\n snippet += \"</td>\"\n end\n snippet\nend",
"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 table_cell_headers(row_cells)\n list = []\n\n row_cells.each do |cell|\n list << if cell[:list_items].count == 1\n item = cell[:list_items][0]\n this_label(item[:code], item[:action_name], item[:label]) unless item[:label] == false\n else\n ''\n end\n end\n list\n end",
"def make_cells_for_row\n (drill.headers.size).times do |num|\n header_id = drill.headers.sort_by(&:position)[num].id\n self.exercise_items.create(:header_id => header_id)\n end\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 monolith_table(groups, metadata)\n checkmark = \" <span style='color: limegreen'>✔</span>\"\n\n # TODO: The checkmark crap below needs to be abstracted.\n formatters = {\n 'New' => proc { |f, l| ['', '', l] },\n 'Updated' => proc { |f, l| ['', '', l + (metadata[f]['installed'].any? ? checkmark : '' ) ] },\n 'Renamed' => proc { |f, l| [\"#{metadata[f]['oldname']}\" + (metadata[f]['installed'].any? ? checkmark : '' ), \"→\", l ] }\n }\n\n table = HTML::Table.new do |t|\n t.align = 'center'\n end\n\n groups.each do |group_name, members|\n title = Table::Row.new do |r|\n r.content = ['', '', group_name]\n end\n title.class_ = 'title'\n table.push title\n\n formatter = formatters[group_name]\n\n members.each do |formula|\n content = Table::Row.new do |r|\n link = \"<a href=#{metadata[formula]['homepage']}>#{formula}</a>\"\n r.content = formatter.call(formula, link).push(\n h(metadata[formula]['desc'])\n )\n r.first.class_ = 'name'\n end\n table.push content\n end\n end\n\n table\nend",
"def content\n @row.html\n end",
"def seq_cell_status(otu, gene) # :yields: HTML cell representation of this gene/OTU combination results \r\n # want 'done', 'data not done', 'add', with links to show seq \r\n\r\n if seqs = otu.sequences(:gene_ids => [gene.id]) \r\n \r\n if seqs.size == 0\r\n return content_tag(:td, 0)\r\n else\r\n return content_tag(:td, seqs.size)\r\n end\r\n\r\n else \r\n return content_tag(:td, link_to('add', {:controller => :seqs, :action => \"new_from_table\", :otu_id => otu_id, :gene_id => gene_id }), :class => \"no_decision\")\r\n end\r\n\r\n #rescue \r\n # return \"error: \" + otu_id.to_s + \" \" + gene_id.to_s + \" \" + @proj.id.to_s \r\n #end\r\n\r\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n \n \"</font>\"\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n \n \"</font>\"\n end",
"def generate_buyflow_table(suite)\n results = suite.testruns\n sum = 0\n failErrorSummary = ''\n color_status = ''\n results.entries.each do |row|\n color_status = \"#009900\" if row[\"result\"].upcase == \"PASS\"\n color_status = \"#FF9900\" if row[\"result\"].upcase == \"ERR\"\n color_status = \"#FF3300\" if row[\"result\"].upcase == \"FAIL\"\n failErrorSummary +=\"\"\"\n <tr>\n <td style='background-color: #{color_status}; color:#FFFFFF; border: 1px solid black;' align='center'><strong><font face='verdana' size='1'>#{row[\"result\"]}</font></strong></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"Brand\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"Campaign\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ExpectedOffercode\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ActualOffercode\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ConfirmationNum\"]}</font></td>\n </tr>\n \"\"\"\n end\n\n errorTable = ''\n unless failErrorSummary == ''\n errorTable = \"\"\"\n <br />\n <br />\n <table border: 1px solid black; bgcolor='#000000' width='100%' color='#FFFFFF' cellpadding='10' cellspacing='0'>\n <tr>\n <td align='center'>\n <b><font face='verdana' size='3' color='#FFFFFF'>\n Test Run results\n </font></b>\n </td>\n </tr>\n </table>\n <table style='border: 1px solid black; table-layout: fixed;' cellpadding='5px' cellspacing='0' bgcolor='#FFFFFF' width='100%'>\n <tr style='text-align: center; color:#ffffff;' bgcolor='#4E5E66'>\n <td style='border: 1px solid black;'>\n <strong>\n Status\n </strong>\n </td>\n <td width='20%' style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Test Name</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Brand</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Expected Offercode</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Actual Offercode</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Conf #</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Notes</font></strong>\n </td>\n </tr>\n #{failErrorSummary}\n </table>\n \"\"\"\n end\n return errorTable\n end",
"def to_data(force_level = :none)\n cells = [] \n merges = []\n col_widths = {}\n row_heights = {}\n\n css.reset(force_level)\n\n tb = doc.css('table').first \n\n # ignoring specified formats for anything other than table tr td/th\n tb_format = css.format_from_node(tb) \n\n row = 0\n doc.css('tr').each do |tr|\n tr_format = tb_format.merge(@css.format_from_node(tr))\n\n increment = true\n tr.css('td, th').each_with_index do |td, col|\n \n # TODO Do we really need rowheight and colwidth now that there\n # is css parsing?\n rowheight = td.attributes[\"rowheight\"]\n colwidth = td.attributes[\"colwidth\"]\n rowspan = td.attributes[\"rowspan\"]\n colspan = td.attributes[\"colspan\"]\n\n rowheight &&= rowheight.value.to_i\n colwidth &&= colwidth.value.to_i\n rowspan &&= rowspan.value.to_i\n colspan &&= colspan.value.to_i\n\n add_td_to_cells(row, col, td, tr_format, cells)\n if colspan\n (1..colspan-1).each {|t| \n add_td_to_cells(row, col+t, td, tr_format, cells)\n }\n end\n if rowspan\n (1..rowspan-2).each {|t| \n add_td_to_cells(row+t, col, td, tr_format, cells)\n }\n increment = false\n end\n if colspan || rowspan\n merges << [\n row, col, row + (rowspan || 2)-2, col + (colspan || 1)-1\n ]\n end\n end\n\n row += 1 if increment\n end\n\n puts cells.inspect\n { cells: cells, merges: { 0 => merges } }\n end",
"def convert_row(row_hash)\n result = ''\n row_hash.each_value do|col|\n result << '<td>'\n case col\n # Handle simple columns here, pass off more complex ones\n when String, Fixnum then result << col.to_s\n when NilClass then result << ''\n when Array then result << convert_array(col)\n else\n result << 'Unknown data type!!!'\n end\n result << '</td>'\n end\n result\n end",
"def error_messages_for_tr(clazz)\n if clazz.present? && clazz.errors.present? && clazz.errors.count > 0\n return \"<tr><td><div class='error'>Errors: #{clazz.errors.full_messages}</div></td></tr>\".html_safe\n end\n end",
"def row_cells\n rowdata = []\n print_layout.each do |section|\n rowdata += row_cell_items(section[:row_cells])\n end\n rowdata\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n\n \"</font>\"\n end",
"def render_tbody\n if @lines and @lines.size > 0\n return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join)))\n return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' }))\n end\n ''\n end",
"def mobile_outstanding_rsvp_sidebar_row(meeting, invitee, klass)\n\t res = ''\n\t row_id = \"outstanding_#{invitee.id}\"\n\t if invitee.is_a?(Member)\n\t res << content_tag('td', link_to(truncate(invitee.user_name, 18), member_profile_url(:id => invitee.user_name), :title => invitee.user_name, :alt => invitee.user_name))\n\t select = select_tag(\"status_for_#{invitee.id}\", options_for_select(['Approve', 'Decline'])) \n\t res << content_tag('td', select, :class => 'approve_decline')\n\t end\n\t content_tag('tr', res, :class => klass, :id => row_id )\n end",
"def all_input_tags_wrapper(record, rows)\n \"\\n<table class='#{record.class.scaffold_table_class :form}'><tbody>\\n#{rows.join}</tbody></table>\\n\"\n end",
"def process_row(row)\n row\n end",
"def process_row\n # overwrite this class\n end",
"def health_history_row f, *args\n content_tag :div, class:'row', style:'margin:0' do\n args.map{ |arg|\n content = \n if arg.is_a? String\n arg\n elsif arg.is_a? Symbol\n check_and_label_tags arg, arg.to_s.titleize\n elsif arg.is_a? Array\n check_and_label_tags *arg\n end\n content_tag :div, content, class:'span2'\n }.join(\"\\n\").html_safe\n end\n end",
"def comment_row_helper(comment,opts={})\n opts[:class] ||= 'row'\n \n # this make inline editing work \n @comment = comment\n \n content = checkbox_helper(opts[:checkbox], {\n :element_id => 'comment_ids',\n :element_value => comment.id,\n :element_default => true,\n :element_link => link_to(h(comment.detail.capitalize),bug_path(comment.bug))\n })\n \n content = column_helper(:class =>'comment col-reporter', :content => \"posted by #{@comment.user.login}\")\n content << column_helper( :class => 'comment col-description', :content => h(comment.detail.capitalize))\n content_tag('dl',content,:class => opts[:class])\nend",
"def build_row(row, i)\n row.map.with_index do |piece, j|\n color_options = colors_for(i,j)\n piece.to_s.colorize(color_options)\n end\n end",
"def group_rows(group, col_count, group_text = nil)\n mri = options.mri\n grp_output = \"\"\n if mri.extras[:grouping] && mri.extras[:grouping][group] # See if group key exists\n if mri.group == \"c\" # Show counts row\n if group == :_total_\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>Count for All Rows: #{mri.extras[:grouping][group][:count]}</td></tr>\"\n else\n g = group_text ? group_text : group\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>Count for #{g.blank? ? \"<blank>\" : g}: #{mri.extras[:grouping][group][:count]}</td></tr>\"\n end\n else\n if group == :_total_\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>All Rows</td></tr>\"\n else\n g = group_text ? group_text : group\n grp_output << \"<tr><td class='group' colspan='#{col_count}'>#{g.blank? ? \"<blank>\" : g} </td></tr>\"\n end\n end\n MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation\n if mri.extras[:grouping][group].key?(calc.first) # Only add a row if there are calcs of this type for this group value\n grp_output << \"<tr>\"\n grp_output << \"<td class='group'>#{calc.last.pluralize}:</td>\"\n mri.col_order.each_with_index do |c, c_idx| # Go through the columns\n next if c_idx == 0 # Skip first column\n grp_output << \"<td class='group' style='text-align:right'>\"\n grp_output << CGI.escapeHTML(mri.format(c.split(\"__\").first,\n mri.extras[:grouping][group][calc.first][c],\n :format => mri.col_formats[c_idx] ? mri.col_formats[c_idx] : :_default_\n )\n ) if mri.extras[:grouping][group].key?(calc.first)\n grp_output << \"</td>\"\n end\n grp_output << \"</tr>\"\n end\n end\n end\n grp_output << \"<tr><td class='group' colspan='#{col_count}'> </td></tr>\" unless group == :_total_\n grp_output\n end",
"def build_table(content)\n table content do\n row(0).font_style = :bold\n self.header = true\n self.row_colors = %w(DDDDDD FFFFFF)\n self.column_widths = [40, 300, 60, 60, 70]\n self.cell_style = {\n border_width: 0,\n size: 10\n }\n end\n end",
"def row_cell(tag_string, cell={}, row={})\n cell = self.tag('cell', tag_string, cell)\n self.tag('row', cell, row)\n end",
"def form_table_element(*args, &block)\n content, options = filter_tag_args(*args)\n options[:class] = (dom_class = options.delete(:class) ? \"fieldRow #{dom_class}\" : 'fieldRow')\n if block_given? && !content\n concat tag(\"td\", \n {:class => cycle('formBoxTwoColumnsLeftColumn', 'formBoxTwoColumnsRightColumn', :name => 'form_box_two_columns'),\n :style => \"vertical-align:top;\"}, true)\n concat content_tag(\"dl\", capture(&block), options)\n concat \"</td>\"\n else\n content_tag(\"td\", content_tag(\"dl\", content, options), \n {:class => cycle('formBoxTwoColumnsLeftColumn', 'formBoxTwoColumnsRightColumn', :name => 'form_box_two_columns')})\n end\n end",
"def bid_cells(bid, seed_on_left_or_right)\n options = {:align => seed_on_left_or_right, :style => \"border-bottom: 1px solid black; padding-#{seed_on_left_or_right}: 2mm;\"}\n seed = content_tag :td, (bid ? \"(#{bid.seed})\" : ' '), options\n team = content_tag :td, (bid ? h(bid.team.name) : ' '), options\n cells = [seed, team]\n cells.reverse! if 'right' == seed_on_left_or_right\n cells\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 handle_row(business, row)\n\n end",
"def build_table_helpers(resource)\n @module.module_eval <<-end_eval\n def #{resource.singular}_table(opts={}, &block)\n content = capture(&block)\n opts[:class] = ResourcefulViews.resourceful_classnames('#{resource.singular}_table', *(opts.delete(:class) || '').split)\n concat(content_tag(:table, content, opts))\n end\n def #{resource.singular}_row(*args, &block)\n opts = args.extract_options!\n opts[:class] = ResourcefulViews.resourceful_classnames('#{resource.singular}', *(opts.delete(:class) || '').split)\n opts[:id] = '#{resource.singular}_' + args.first.id.to_s unless args.empty?\n content = capture(&block)\n concat(content_tag(:tr, content, opts))\n end\n end_eval\n end",
"def time_rows\n rows = []\n (0..NUM_HALF_HOURS-1).each do |half_hour|\n cols = []\n row = content_tag :tr do\n cols << hour_cell(half_hour)\n cols << minute_cell(half_hour)\n (0..(num_days-1)).each do |day|\n cols << event_cells(half_hour,day)\n end\n cols.join.html_safe\n end\n rows << row\n end\n rows.join.html_safe\n end",
"def after_cell_render_styling(column_name,cell_value,record)\n '</font>' if column_name != \"id\"\n \n end",
"def plan_header_cell(plan, index, plan_size)\n classes = []\n classes << 'plan_name' << 'thhead'\n classes << 'thead_first' if index == 0\n classes << 'thead_last' if (index + 1) == plan_size\n classes << 'selected' if plan.bought_by?(current_account)\n\n content_tag('td', :class => classes.join(' ')) do\n content_tag('h3', h(plan.name))\n end\n end",
"def form_row(label,field)\n \tcontent_tag(:tr, content_tag(:th, label) + content_tag(:td, field))\n \tend",
"def parse_row(row)\n cells = row.css('td')\n return nil if cells.nil?\n\n {\n \"volfdnr\" => extract_id(cells[0]),\n \"title\" => extract_text(cells[1]),\n \"presenter\" => extract_text(cells[3]),\n \"date\" => extract_text(cells[4]),\n \"type\" => extract_text(cells[5])\n }\nend",
"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 << (1..@generated.length).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 << (1..@expected.length).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"
] | [
"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.55680346",
"0.5549841",
"0.5548508",
"0.5545985",
"0.5545485",
"0.55261105",
"0.5517562",
"0.551026",
"0.54950774",
"0.54785305",
"0.54728913",
"0.54624474",
"0.5453716",
"0.54369503",
"0.54369503",
"0.54364914",
"0.54364425",
"0.5436336",
"0.5430587",
"0.54283553",
"0.5425383",
"0.5422317",
"0.54177016",
"0.54121685",
"0.53926",
"0.5380745",
"0.5343799",
"0.5341029",
"0.533986",
"0.53391004",
"0.5338692",
"0.530764",
"0.5304281",
"0.52801794",
"0.5271627",
"0.5268707",
"0.5268135",
"0.5259399",
"0.52587056",
"0.5258459",
"0.5255067",
"0.5255067",
"0.5254198",
"0.5243745",
"0.5241512",
"0.5237284",
"0.52345437",
"0.52306557",
"0.5224586",
"0.52243346",
"0.5221976",
"0.52196395",
"0.52195084",
"0.5218818",
"0.5216288",
"0.5213095",
"0.521273",
"0.52104026",
"0.520494",
"0.52044654",
"0.5202864",
"0.5200906",
"0.5200738",
"0.519675",
"0.5187685",
"0.5187186",
"0.5185355",
"0.51808083",
"0.51798177",
"0.51676345"
] | 0.75109816 | 0 |
Calculate the differences between two arrays (rows) an enclose these differences in strong html tags. Also, html escape the raw table data before enclosing. | def diff_arrays(generated, expected)
gen_result = []
exp_result = []
Diff::LCS.sdiff(generated, expected) do |chunk|
case chunk.action
when '-'
gen_result << %(<strong>#{CGI.escape_html chunk.old_element}</strong>)
when '+'
exp_result << %(<strong>#{CGI.escape_html chunk.new_element}</strong>)
when '='
gen_result << (CGI.escape_html chunk.old_element)
exp_result << (CGI.escape_html chunk.new_element)
when '!'
gen_result << %(<strong>#{CGI.escape_html chunk.old_element}</strong>)
exp_result << %(<strong>#{CGI.escape_html chunk.new_element}</strong>)
end
end
[gen_result, exp_result]
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 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 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 to_html \n PrettyDiff::HtmlGenerator.generate_diff(chunks)\n end",
"def to_html\n diff(@old, @new, @fields).reduce({}) do |diffed_output, (key, val)|\n if val.class == Hash\n diffed_output[key] = val.reduce({}) do |d_o, (k, v)|\n d_o[k] = v.to_s :html\n d_o\n end\n else\n diffed_output[key] = val.to_s :html\n end\n diffed_output\n end\n end",
"def diff(table, wait_time = Capybara.default_max_wait_time, ignore_case: false)\n to_table = self.to_table\n\n if ignore_case == true\n table = Cucumber::MultilineArgument::DataTable.from(downcase_array(table.raw))\n to_table = downcase_array(to_table)\n end\n\n table.diff!(to_table) || true\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 = \" \" 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 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 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 fix_html(ary)\n text = \"\"\n\n ary.each do |s|\n temp = s.gsub('<', '<').gsub('>', '>')\n temp = temp.gsub('&b', '<b>').gsub('&/b', '</b>')\n temp = temp.gsub('&i', '<i>').gsub('&/i', '</i>')\n\n text += \" #{temp}<br />\\n\"\n end\n\n return text\nend",
"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 plain_diff(first_weapon_stat, second_weapon_stat)\n diff_value = first_weapon_stat - second_weapon_stat\n\n if diff_value < 0\n html = \"<span class='upper'>#{second_weapon_stat} ▲</span>\"\n elsif diff_value > 0\n html = \"<span class='down'>#{second_weapon_stat} ▼</span>\"\n else\n html = \"#{first_weapon_stat}\"\n end\n\n return html.html_safe\n end",
"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 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 << (1..@generated.length).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 << (1..@expected.length).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 generate_diff wA, wB\n\n # puts \"---------------------------------> generating diff for #{wA} and #{wB}\"\n # sort by magnitude of id\n # returns w1 has earlier id than w2\n wA < wB ? w1id = wA : w1id = wB\n wA < wB ? w2id = wB : w2id = wA\n\n # get refs to whole works\n w1 = Work.find(w1id)\n w2 = Work.find(w2id)\n\n # check they belong to same project\n errors.add(:project, \"projects don't match\") unless w1.project_id == w2.project_id\n\n project = Project.find(w2.project_id) # same as w1\n\n\n # ----------- make diffs ------------ #\n\n # set values to diff from neighbord\n w1_md = w1.file_content_md.force_encoding(\"UTF-8\") if !w1.file_content_md.nil?\n w1_html = w1.file_content_html.force_encoding(\"UTF-8\") if !w1.file_content_html.nil?\n w1_text = w1.file_content_text.force_encoding(\"UTF-8\") if !w1.file_content_text.nil?\n\n # **note** self.file_content_md is coming from ReverseMarkdown now, instead of PandocRuby\n diff_md_val = Diffy::Diff.new(w1_md ,w2.file_content_md).to_s\n diff_html_val = Diffy::Diff.new(w1_md ,w2.file_content_md).to_s(:html)\n diff_text_val = Diffy::Diff.new(w1_text ,w2.file_content_text).to_s\n\n ### ALWAYS DIFF INTO :HTML FORMAT SO WE CAN DISPLAY IT NEATLY.\n ### ALWAYS DIFF !EMPTY RIGHT/LEFT\n diff_left_val = Diffy::SplitDiff.new(w1_md ,w2.file_content_md, :format => :html, :allow_empty_diff => false).left if !w1_md.nil?\n diff_right_val = Diffy::SplitDiff.new(w1_md ,w2.file_content_md, :format => :html, :allow_empty_diff => false).right if !w1_md.nil?\n\n # _text diffs for pdfs and plain text docs\n diff_left_text_val = Diffy::SplitDiff.new(w1_text ,w2.file_content_text, :format => :html, :allow_empty_diff => false).left if !w1_text.nil?\n diff_right_text_val = Diffy::SplitDiff.new(w1_text ,w2.file_content_text, :format => :html, :allow_empty_diff => false).right if !w1_text.nil?\n\n # ** .scrub! ensures we don't get any fucked up character encoding errors from mysql2\n # if !diff_md_val.nil? ensures we're dealing with a diffable doc (ie not a picture)\n diff_md_val.force_encoding(\"UTF-8\").scrub! if !diff_md_val.nil? #.encode!('UTF-8', :invalid => :replace, :undef => :replace, :replace => '')!diff_md_val.nil?\n diff_html_val.force_encoding(\"UTF-8\").scrub! if !diff_html_val.nil?\n diff_text_val.force_encoding(\"UTF-8\").scrub! if !diff_text_val.nil?\n\n diff_left_val.force_encoding(\"UTF-8\").scrub! if !diff_left_val.nil?\n diff_right_val.force_encoding(\"UTF-8\").scrub! if !diff_right_val.nil?\n\n # diff_left_text_val.force_encoding(\"UTF-8\").scrub! if !diff_left_val.nil?\n # diff_right_text_val.force_encoding(\"UTF-8\").scrub! if !diff_right_val.nil?\n # diff_left_val.force_encoding(\"UTF-8\").scrub! if !diff_left_val.nil?\n # diff_right_val.force_encoding(\"UTF-8\").scrub! if !diff_right_val.nil?\n diff_left_text_val.force_encoding(\"UTF-8\").scrub! if !diff_left_text_val.nil?\n diff_right_text_val.force_encoding(\"UTF-8\").scrub! if !diff_right_text_val.nil?\n\n # ----------- update or create diff ------------ #\n\n # update_or_create for, well, updating or creating\n diff = Diff.where(project_id: project.id, work1: w1id, work2: w2id).first_or_create\n diff.update!(\n diff_md: diff_md_val,\n diff_html: diff_html_val,\n diff_text: diff_text_val,\n left: diff_left_val,\n right: diff_right_val,\n left_text: diff_left_text_val,\n right_text: diff_right_text_val\n )\n\n end",
"def merge_table_with_results(input_table, json_results)\n final_results = []\n # Strip extra stuff from the results to get the original line\n clean_results = json_results.collect do |row|\n row.collect do |cell|\n clean_cell(cell)\n end\n end\n # Perform a context-diff\n input_table.sdiff(clean_results).each do |diff|\n # If this row was in the input table, but not in the results,\n # output it as an ignored row\n if diff.action == '-'\n # Ignore all cells in the row\n final_results << input_table[diff.old_position].collect do |cell|\n \"ignore:#{cell}\"\n end\n # In all other cases, output the row from json_results\n else # '=', '+', '!'\n final_results << json_results[diff.new_position]\n end\n end\n return final_results\n end",
"def to_html aInline = false\n protect(self, VERBATIM_TAGS, true) do |text|\n html = protect(text, PROTECTED_TAGS, false) {|s| s.thru_redcloth aInline }\n\n # collapse redundant <pre> elements -- a side effect of RedCloth\n while html.gsub! %r{<pre>\\s*(<(code|pre)[^>]*>.*?</\\2>)\\s*</pre>}m, '\\1'\n end\n\n # ensure tables have a border: this *greatly* improves\n # readability in text-mode web browsers like Lynx and w3m\n html.gsub! %r/<table/, '\\& border=\"1\"'\n\n html.thru_coderay\n end\n end",
"def to_html\n htmlString = %{<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">}\n htmlString += %{<tr>}\n LineCounter.columnNames.each { |name| htmlString += %{<th>#{name}</th>} }\n htmlString += %{</tr>}\n self.each do |result|\n htmlString += %{<tr>}\n result.to_a.each { |cell| htmlString += %{<td>#{cell}</td> } }\n htmlString += %{</tr>}\n end\n htmlString += %{</table>}\n htmlString += %{<p><em>Generated by } +\n %{<a href=\"http://countloc.rubyforge.org\">countloc</a> version #{VERSION} } +\n %{on #{Time.now.asctime}</em></p>}\n end",
"def diff_and_markup(s1, s2, ignore_limit=1)\n diffs=Diff::LCS.sdiff(s1, s2).map {|lcs_change| handle_lcs_change( lcs_change ) }\n changes_to_chunks( diffs, ignore_limit )\n end",
"def create_confluence_table_html(data)\n\t\txm = Builder::XmlMarkup.new(:indent => 2)\n\t\txm.table {\n\t\t xm.tr { data[0].keys.each { |key| xm.th(key)}}\n\t\t data.each { |row| xm.tr { row.values.each { |value| xm.td(value)}}}\n\t\t}\n\n\t\treturn \"#{xm}\"\t\t\n\tend",
"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 diffyable\n # add appropriate diff column data for diff.right and diff.left and update other attrs to the Diffy way®\n\n w1id = self.work1\n w2id = self.work2\n w1work = Work.find(w1id)\n w2work = Work.find(w2id)\n w1md = w1work.file_content_md\n w2md = w2work.file_content_md\n w1txt = w1work.file_content_text\n w2txt = w2work.file_content_text\n\n html = Diffy::Diff.new(w1md, w2md).to_s(:html)\n md = Diffy::Diff.new(w1md, w2md).to_s\n text = Diffy::Diff.new(w1txt, w2txt).to_s\n \n lucy = Diffy::SplitDiff.new(w1md, w2md, :format => :html).left\n recha = Diffy::SplitDiff.new(w1md, w2md, :format => :html).right\n\n html.force_encoding(\"UTF-8\").scrub!\n md.force_encoding(\"UTF-8\").scrub!\n text.force_encoding(\"UTF-8\").scrub!\n\n lucy.force_encoding(\"UTF-8\").scrub!\n recha.force_encoding(\"UTF-8\").scrub!\n\n self.update_attributes(left: lucy, right: recha, diff_md: md, diff_html: html, diff_text: text)\n self.save\n end",
"def original_line_text(line)\n \n #if line.print_change == true\n rev_line_class = 'rev_row' \n #else\n # rev_line_class = 'rev_row_strike'\n #end\n \n last_clause_change = Change.where(:specline_id => line.specline_id).last\n if line[:id] == last_clause_change[:id] \n \"<table width='100%' class='rev_table'><tr id='#{line.id.to_s}' class='#{rev_line_class}'><td class='rev_row_padding'>#{line_content(line)}</td><td class='rev_line_menu_mob'>#{rev_mob_menu(line)}</td><td class='rev_line_menu'>#{reinstate_original_line(line)}#{change_info(line)}</td></tr><tr class='rev_mob_menu_popup'><td class='mob_rev_menu' colspan=3 >#{reinstate_original_line(line)}#{change_info(line)}</td></tr></table>\".html_safe \n else\n \"<table width='100%' class='rev_table'><tr id='#{line.id.to_s}' class='#{rev_line_class}'><td class='rev_row_padding'>#{line_content(line)}</td><td class='rev_line_menu_mob'>#{rev_mob_menu(line)}</td><td class='rev_line_menu'>#{change_info(line)}</td></tr><tr class='rev_mob_menu_popup'><td class='mob_rev_menu' colspan=3 >#{change_info(line)}</td></tr></table>\".html_safe \n end \n end",
"def to_html\n require \"iruby\"\n if size > 7\n # pass 8 rows so maxrows is applied\n IRuby::HTML.table(first(4).to_a + last(4).to_a, maxrows: 7)\n else\n IRuby::HTML.table(to_a)\n end\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 to_s_corrected\n @cells.map { |row| row.join(' ') }.join(\"\\n\")\n end",
"def render_tbody\n if @lines and @lines.size > 0\n return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join)))\n return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' }))\n end\n ''\n end",
"def table_row(row, alignment)\n\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\n end",
"def rates(table_rows)\n table_rows.map do |e|\n e.css('.content').map(&:text).map(&:strip).map do |txt|\n txt.split(\"\\n\").map(&:strip)\n end\n end\n end",
"def table_row(row, alignment)\n result = ''\n i = 0\n\n row.each_with_index do |e, k|\n next if alignment[k] == Constants::SEPARATOR\n\n text = inline_code(e, true)\n\n if /\\\\newline/ === text\n text = \"\\\\specialcell[t]{#{text}}\"\n text.gsub!(/\\\\newline/, '\\\\\\\\\\\\\\\\')\n end\n\n result << text\n result << ' & ' if k < row.size - 1\n i += 1\n end\n\n @io << \"#{result} \\\\\\\\\" << nl\n end",
"def display_diff(version1, version2)\n version1_text = render_wiki_content(:content => version1)\n version2_text = render_wiki_content(:content => version2)\n diff(version1_text, version2_text)\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 diff\n return if diffs.empty?\n\n minimized_hunk.diff(:unified) + NEWLINE\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 diffed(old, new)\n differ = Differ.diff_by_line(new, old)\n differ.to_s[/\\{[^}]+\\}/][1...-1].gsub(/\\s{2,}/, '')\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 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 adjust_lt_gt(maths)\n maths.gsub(/</, '\\lt').gsub(/>/, '\\gt')\n end",
"def magazine_diff(first_weapon_stat, second_weapon_stat)\n diff_value = first_weapon_stat - second_weapon_stat\n\n if diff_value < 0\n html = \"<span class='upper'>#{second_weapon_stat} ▲</span>\"\n elsif diff_value > 0\n html = \"<span class='down'>#{second_weapon_stat} ▼</span>\"\n else\n html = \"#{first_weapon_stat}\"\n end\n\n return html.html_safe\n end",
"def all_input_tags_wrapper(record, rows)\n \"\\n<table class='#{record.class.scaffold_table_class :form}'><tbody>\\n#{rows.join}</tbody></table>\\n\"\n end",
"def difference(rt1, rt2)\n return template_tags(rt1) - template_tags(rt2)\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 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 accept_table header, body, aligns\n @res << \"\\n<table role=\\\"table\\\">\\n<thead>\\n<tr>\\n\"\n header.zip(aligns) do |text, align|\n @res << '<th'\n @res << ' align=\"' << align << '\"' if align\n @res << '>' << CGI.escapeHTML(text) << \"</th>\\n\"\n end\n @res << \"</tr>\\n</thead>\\n<tbody>\\n\"\n body.each do |row|\n @res << \"<tr>\\n\"\n row.zip(aligns) do |text, align|\n @res << '<td'\n @res << ' align=\"' << align << '\"' if align\n @res << '>' << CGI.escapeHTML(text) << \"</td>\\n\"\n end\n @res << \"</tr>\\n\"\n end\n @res << \"</tbody>\\n</table>\\n\"\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 replace_offensive_html\n html_tables.each do |tablename|\n if self.respond_to? tablename\n html_replacements.each_pair do |replacable,replacement|\n self.send(\"#{tablename}=\",(self.send tablename).gsub(replacable,replacement))\n end\n end\n end\n self\n end",
"def print_table\n\t\t@start_map.each {|k,v|\n\t\t\tr = @end_map[k]\n\t\t\tdiff = r-v\n\t\t\tputs \"#{k} => #{v} | #{r} diff #{diff}\"\n\t\t}\n end",
"def latex_table(data, top_headings, left_headings)\n matrix = [[''] + top_headings] +\n left_headings.zip(data).map { |heading, line| [heading] + line }\n latex_matrix matrix\nend",
"def _reduce_13(val, _values, result)\n content = val[1]\n result = inline \"<em>#{content}</em>\", content\n\n result\nend",
"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 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 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? ? \" \" : 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",
"def display_results_html\n\t\t output =\"<!DOCTYPE html><html xmlns=\\\"http://www.w3.org/1999/xhtml\\\"><head><title></title></head><body>\"\n\t\t output.concat(\"<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>\")\n @filehash.each{ |key, value| output.concat(\"<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>\")}\n output.concat(\"</tbody></table></body></html>\")\n puts output\n end",
"def mergerows(row1,row2)\n\t\tif row2 >= @text.length\n\t\t\treturn\n\t\tend\n\t\tcol = @text[row1].length\n\t\t@text[row1] = @text[row1].dup\n\t\t@text[row1] += @text[row2]\n\t\t@text.delete_at(row2)\n\tend",
"def to_html\n map { |x| x.output(\"\") }.join\n end",
"def format descriptions\n formatted = format_rows descriptions\n\n aligned = formatted.transpose.map do |column|\n width = column.map { |entry| entry.length }.max\n\n column.map { |entry| entry.rjust width }\n end\n\n aligned.transpose.map do |row|\n row.join ' '\n end\n end",
"def compute_diff\n original_content_file = Tempfile.new(rand(1024).to_s)\n original_content_file.open\n original_content_file.write(content)\n original_content_file.flush\n diff = `diff #{original_content_file.path} #{tempfile.path}`\n diff.gsub!(/> (.*\\n)/m, '\\1'.green)\n diff.gsub!(/< (.*\\n)/m, '\\1'.red)\n ensure\n original_content_file.close\n original_content_file.unlink\n diff\n end",
"def generate_buyflow_table(suite)\n results = suite.testruns\n sum = 0\n failErrorSummary = ''\n color_status = ''\n results.entries.each do |row|\n color_status = \"#009900\" if row[\"result\"].upcase == \"PASS\"\n color_status = \"#FF9900\" if row[\"result\"].upcase == \"ERR\"\n color_status = \"#FF3300\" if row[\"result\"].upcase == \"FAIL\"\n failErrorSummary +=\"\"\"\n <tr>\n <td style='background-color: #{color_status}; color:#FFFFFF; border: 1px solid black;' align='center'><strong><font face='verdana' size='1'>#{row[\"result\"]}</font></strong></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"Brand\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"Campaign\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ExpectedOffercode\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ActualOffercode\"]}</font></td>\n <td style='border: 1px solid black;' align='center'><font face='verdana' size='1'>#{row[\"ConfirmationNum\"]}</font></td>\n </tr>\n \"\"\"\n end\n\n errorTable = ''\n unless failErrorSummary == ''\n errorTable = \"\"\"\n <br />\n <br />\n <table border: 1px solid black; bgcolor='#000000' width='100%' color='#FFFFFF' cellpadding='10' cellspacing='0'>\n <tr>\n <td align='center'>\n <b><font face='verdana' size='3' color='#FFFFFF'>\n Test Run results\n </font></b>\n </td>\n </tr>\n </table>\n <table style='border: 1px solid black; table-layout: fixed;' cellpadding='5px' cellspacing='0' bgcolor='#FFFFFF' width='100%'>\n <tr style='text-align: center; color:#ffffff;' bgcolor='#4E5E66'>\n <td style='border: 1px solid black;'>\n <strong>\n Status\n </strong>\n </td>\n <td width='20%' style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Test Name</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Brand</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Expected Offercode</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Actual Offercode</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Conf #</font></strong>\n </td>\n <td style='border: 1px solid black;'>\n <strong><font size='1' face='verdana'>Notes</font></strong>\n </td>\n </tr>\n #{failErrorSummary}\n </table>\n \"\"\"\n end\n return errorTable\n end",
"def summary_table\n update_now_date_time\n calc_difference\n labels = [DueText.period, ' ', DueText.duration, DueText.measure]\n rows = summary_array\n puts tabulate(labels, rows, { 'indent' => 4, 'style' => 'fancy' })\n end",
"def generate_result_and_time_columns(examples, failures, array_file_content)\n \"<td><img src='images/accept.png' align='absmiddle'/> #{examples}  <img src='images/exclamation.png' align='absmiddle'/> #{failures}</td><td>#{array_file_content.select{|l| l =~ /^Finished in/}[0].split(/Finished in /)[1].split(/\\.$/)[0]}</td></tr>\"\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 test_to_html\n df = Rover::DataFrame.new({\"a\" => [1, 2, 3], \"b\" => [\"one\", \"two\", \"three\"]})\n assert_match \"<table>\", df.to_html\n end",
"def colorized_diff(&block); 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 run_diff(a, b)\n\t\t\ta = \"\" if a == nil\n\t\t\tb = \"\" if b == nil\n\t\t\n\t\t\t@a = a\n\t\t\t@b = b\n\t\t\n\t\t\t# run the initial word-based diff\n\t\t\t@worddiff = WordDiff.new(a, b)\n\t\t\n\t\t\tawords = @worddiff.a_words\n\t\t\tbwords = @worddiff.b_words\n\t\t\twdiff = @worddiff.differences\n\t\t\n\t\t\t#\n\t\t\t# now run through all the words in the longest\n\t\t\t# of the sentences, and for words that differ\n\t\t\t# run a character based diff and calculate the differing\n\t\t\t# characters actual position within the sentences\n\t\t\t#\n\t\t\tmax = awords.length\n\t\t\tmax = bwords.length if bwords.length > awords.length\n\t\t\n\t\t\tstr = \"\"\n\t\t\n\t\t\tfor i in 0..max-1\n\t\t\n\t\t\t\tif wdiff.include?(i)\n\t\t\t\t\tdiff_by_char(awords[i], bwords[i]).each do |chardiff|\n\t\t\t\t\t\t@differences.push(chardiff + str.length)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\n\t\t\t\tstr << \" #{bwords[i]}\"\n\t\t\tend\n\n\t\t\t# return void\t\t\n\t\t\treturn\n\t\tend",
"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 multTable(x1,x2,y1,y2)\n\tif !x1.is_a? Integer or !y1.is_a? Integer or !x2.is_a? Integer or !y2.is_a? Integer\n\t\treturn \"Invalid input type\"\n\tend\n\tif x1 > x2 or y1 > y2\n\t\treturn \"x1 and y1 must both be less than x2 and y2 respectively\"\n\tend\n\tlenArr=[]\n\tstrtStr = \" \"*(y2.to_s.length) + \" \"\n\tfinStr = y2.to_s + \" \"\n\tfor x in x1..x2\n\t\tx_s = x.to_s\n\t\tprod = x*y2\n\t\tprod_s = prod.to_s\n\t\tlenArr << prod_s.length\n\t\tstrtStr+=x_s+\" \"*(lenArr[-1] - x_s.length) + \" \"\n\t\tif x == x2\n\t\t\tfinStr+= prod_s\n\t\telse\n\t\t\tfinStr+= prod_s +\" \"\n\t\tend\t\n\tend\n\tputs strtStr\n\tfor y in y1..(y2 -1)\n\t\tstr =y.to_s+\" \"*(y2.to_s.length-y.to_s.length)+\" \"\n\t\tfor x in x1..x2\n\t\t\tprod = x*y\n\t\t\tprod_s = prod.to_s\n\t\t\tstr+=prod_s+\" \"*(lenArr[x-x1] - prod_s.length) + \" \"\n\t\tend\n\t\tputs str\n\tend\n\tputs finStr\nend",
"def emit_differences(species, confused_with)\n <<-difference\n #{confused_with}: '''\n to do description\n '''\n \n difference\n end",
"def evaluateDiffResult()\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 merge(stmt2)\n # print each statement to a file\n [ [ @rows, \"/tmp/merge.1\" ],\n [ stmt2.rows, \"/tmp/merge.2\" ] ].each do | cur_rows, cur_file |\n f = File.open(cur_file, \"w\")\n cur_rows.each do |row| \n if !row[0].nil?\n f.puts(row[0].text) \n end\n end\n f.close\n end\n \n # run an sdiff on it\n @diffs = []\n IO.popen(\"sdiff -w1 /tmp/merge.1 /tmp/merge.2\") do |f|\n f.each { |line| @diffs.push(line.chomp) }\n end\n system(\"rm /tmp/merge.1 /tmp/merge.2\")\n \n # paralellize the arrays, by inserting blank rows\n @diffs.each_with_index do |cur_diff,idx|\n if cur_diff == \"<\"\n new_row = [@rows[idx][0]]\n while new_row.length < stmt2.rows[idx].length\n new_row.push(Cell.new)\n end\n stmt2.rows.insert(idx,new_row)\n elsif cur_diff == \">\"\n new_row = [stmt2.rows[idx][0]]\n while new_row.length < @rows[idx].length\n new_row.push(Cell.new)\n end\n @rows.insert(idx,new_row)\n else\n end\n end\n \n # merge them together\n @rows.size.times do |i|\n @rows[i].concat(stmt2.rows[i])\n end\n end",
"def tabulate(labels, data, indent = 0,style=\"simple\" )\n raise \"Invalid table style!\" unless $template.keys.include? style\n raise 'Label and data do not have equal columns!' unless labels.size == data.transpose.size\n\n data = data.inject([]){|rs, r| rs += r.to_rows }\n data = data.unshift(labels).transpose\n padding = $template[style][:padding] \n data = data.collect {|c| \n c.collect {|e| ' ' * padding + e.to_s + ' ' * padding } \n }\n widths = data.collect {|c| c.collect {|a| a.width}.max } \n newdata = []\n data.each_with_index {|c,i|\n newdata << c.collect { |e| e + ' '*(widths[i] - e.width) }\n }\n data = newdata\n data = data.transpose\n data = [ $template[style][:hlframe] + data[0].join($template[style][:fs]) + $template[style][:hrframe] ] + \\\n data[1..-1].collect {|l| $template[style][:lframe] + l.join($template[style][:fs]) + $template[style][:rframe] }\n lines = []\n if !$template[style][:tframe].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:tframe] *n }.join($template[style][:cross]) + $template[style][:cross]\n end\n lines << data[0]\n if !$template[style][:hs].to_s.empty? and !$template[style][:lframe].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:hs] *n }.join($template[style][:cross]) + $template[style][:cross]\n elsif !$template[style][:hs].to_s.empty?\n lines << widths.collect{|n| $template[style][:hs] *n }.join($template[style][:cross])\n end\n data[1..-2].each{ |line|\n lines << line\n if !$template[style][:rs].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:rs] *n }.join($template[style][:cross]) + $template[style][:cross]\n end\n }\n lines << data[-1]\n if !$template[style][:bframe].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:bframe] *n }.join($template[style][:cross]) + $template[style][:cross]\n end\n lines.collect {|l| ' '*indent + l}.join(\"\\n\")\nend",
"def changelog_entry_display(shaped_changes)\n shaped_changes.map do |entry|\n field = t(\"activerecord.attributes.patient.#{entry[0]}\")\n field = content_tag('strong') { \"#{field}:\" }.freeze\n orig = entry[1][:original]\n separator = '->'.freeze\n mod = entry[1][:modified]\n\n safe_join([field, orig, separator, mod], ' ').freeze\n end\n end",
"def inline_formatting(str)\n str.rstrip!\n str = @re_help.rewrite_emphasis(str) do |marker, s|\n \"#{Tags[marker][:open]}#{s}#{Tags[marker][:close]}\"\n end\n str = @re_help.rewrite_images(str) do |link|\n \"<img src=\\\"#{link}\\\" />\"\n end\n str = @re_help.rewrite_links(str) do |link, text|\n text ||= link\n link = link.sub(/^file:(.*)::(.*?)$/) do\n\n # We don't support search links right now. Get rid of it.\n\n \"file:#{$1}\"\n end\n link = link.sub(/^file:/i, \"\") # will default to HTTP\n link = link.sub(/\\.org$/i, \".html\")\n \"<a href=\\\"#{link}\\\">#{text}</a>\"\n end\n if (@output_type == :table_row) then\n str.gsub!(/^\\|\\s*/, \"<td>\")\n str.gsub!(/\\s*\\|$/, \"</td>\")\n str.gsub!(/\\s*\\|\\s*/, \"</td><td>\")\n end\n if (@output_type == :table_header) then\n str.gsub!(/^\\|\\s*/, \"<th>\")\n str.gsub!(/\\s*\\|$/, \"</th>\")\n str.gsub!(/\\s*\\|\\s*/, \"</th><th>\")\n end\n str\n end",
"def sanitize_cells(rows)\n rows.map do |cells|\n cells.map do |cell|\n \n if cell.is_a? Float\n cell = cell ? cell.to_i.to_s : \"\"\n else\n cell = cell ? cell.to_s : \"\"\n end\n cell ? cell.strip : \"\"\n end\n end\n end",
"def altered_clause_text(clause_title, selected_revision, current_project) \n \n last_clause_change = Change.where('project_id = ? AND clause_id = ? AND clause_add_delete =?', current_project.id, clause_title.id, 2).last\n if selected_revision.id == last_clause_change[:revision_id]\n \"<table width='100%' class='rev_table'><tr id='#{clause_title.id.to_s}'class='clause_title_2'><td class='rev_clause_code'>#{clause_title.clauseref.subsection.section.ref.to_s}#{clause_title.clauseref.subsection.ref.to_s}.#{clause_title.clauseref.clausetype_id.to_s}#{clause_title.clauseref.clause.to_s}#{clause_title.clauseref.subclause.to_s}</td><td class ='rev_clause_title'> #{clause_title.clausetitle.text.to_s}</td><td class='rev_line_menu_mob'>#{rev_mob_menu(clause_title)}</td><td class='rev_line_menu'>#{reinstate_original_clause(clause_title)}#{change_info_clause(clause_title)}</td></tr><tr class='rev_mob_menu_popup'><td class='mob_rev_menu' colspan=3 >#{reinstate_original_clause(clause_title)}#{change_info_clause(clause_title)}</td></tr></table>\".html_safe \n else\n \"<table width='100%' class='rev_table'><tr id='#{clause_title.id.to_s}'class='clause_title_2'><td class='rev_clause_code'>#{clause_title.clauseref.subsection.section.ref.to_s}#{clause_title.clauseref.subsection.ref.to_s}.#{clause_title.clauseref.clausetype_id.to_s}#{clause_title.clauseref.clause.to_s}#{clause_title.clauseref.subclause.to_s}</td><td class ='rev_clause_title'> #{clause_title.clausetitle.text.to_s}</td><td class='rev_line_menu_mob'>#{rev_mob_menu(clause_title)}</td><td class='rev_line_menu'>#{change_info_clause(clause_title)}</td></tr><tr class='rev_mob_menu_popup'><td class='mob_rev_menu' colspan=3 >#{change_info_clause(clause_title)}</td></tr></table>\".html_safe \n end\n end",
"def TeX2htm(text,state=:normal,fname=\"\",sec=\"\")\n sp=proc{|s| $trads[$key.succ!]=s; \"\\\\#{$key} \"}\n mathdisplay=proc{|s|\n sp[TeX2htm(s,:math).h(\"I\").h(\"td\").h(\"tr\").h(\"table\").h(\"center\")]}\n text=text.gsub(/([^\\\\]|^)%.*/){m=$~;m[1]} # suppress tex comments\n unless state==:math\n text.gsub!(/\\\\$/,\"\\\\ \")\n vb=/\\|'\\\\\\|'\\|/ # a | in verbatim\n vb2=/\\|\\s*\\{\\s*\\\\tt\\s*\\\\\\|\\s*\\}\\s*\\|/ # another way for | in verbatim\n vbb=/(?:#{vb2}|#{vb})/o\n text.gsub!(/([^\\\\]|^|\\\\\\\\)\\|((?:[^|]|#{vbb})*)\\|/om){ m=$~\n if m[2]=~/\\n/\n m[1]+sp[m[2].gsub(vbb,\"|\").lines.map{|l| v=l.split(\"#\");\n\tv[0].gsub!(/&/,\"#\");v[0].gsub!(/</,\"<\");\n\tif v[1] then v[1]=TeX2htm(v[1]); v.join(\"#\")\n\telse v[0]\n\tend}.join.h(\"pre\")]\n else m[1]+sp[m[2].gsub(vbb,\"|\").gsub(/&/,\"#\").gsub(/</,\"<\").clean.h(\"code\")]\n end\n }\n text.gsub!(/\\$\\$(.*?)\\$\\$/m){m=$~; mathdisplay[m[1]]}\n text.gsub!(/\\\\\\[(.*?)\\\\\\]/m){m=$~; mathdisplay[m[1]]}\n text.gsub!(/([^\\\\]|^)\\$(.*?)\\$/m){m=$~\n m[1]+sp[TeX2htm(m[2],:math).h(\"I\")]}\n text.gsub!(/([^\\\\]|^)\\*([^*]*)([^\\\\])\\*/){m=$~;\n m[1]+sp[(m[2]+m[3]).h(\"strong\")]}\n end\n text.gsub!(/\\\\\\\\/){\"\\\\cr\"}\n text.gsub!(/([^\\\\])<([^>]*)>/m){m=$~;m[1]+sp[TeX2htm(m[2]).h(\"var\")]}\n text.gsub!(/([^\\\\]|^)'((?:[^']|\\\\')*)([^\\\\])'/m){m=$~;\n m[1]+sp[(m[2]+m[3]).clean.h(\"code\")]}\n text.gsub!(/([^\\\\]|^)\\\\([*{}|': <>;,#~-])/){m=$~;m[1]+sp[OneChar[m[2]]]}\n text.gsub!(/([^\\\\]|^)\\\\([*{}|': <>;,#~-])/){m=$~;m[1]+sp[OneChar[m[2]]]}\n unless state==:math\n text.gsub!(/^\\s*$/,\"\\\\par\")\n text.gsub!(/^\\s*\\\\vspace\\{[^}]*\\}\\s*$/,\"\\\\par\")\n text.gsub!(/^([^:\\n]*)([^\\\\]):(.*?)(?=\\\\par)/m){m=$~\n sp[\"<DL><DT>#{TeX2htm(m[1]+m[2])}:<DD>\"]+\"#{m[3]}\"+sp[\"</DL>\"]}\n text.gsub!(/\\\\cr/){sp[\"<BR>\"]}\n # characters that can appear in a cross reference\n text.gsub!(/([^\\\\]|^)\"([\\w\\s.$-]*)\"/m){m=$~;\n m[1]+sp[\"<a href=\\\"#{name2fn m[2]}\\\">#{m[2]}</a>\"]}\n text.gsub!(/\\\\\"/){sp['\"']}\n text.gsub!(/\\\\cite(?:\\[([^\\]\\[]*)\\])?\\s*\\{\\s*((?:\\w|,)+)\\s*\\}/m) { m=$~\n r=\"<A href=\\\"biblio.htm##{m[2].split(\",\")[0]}\\\">#{m[2].h(\"cite\")}</a>\"\n r<< \", \"+m[1] if m[1]\n sp[r] }\n text.gsub!(/\\\\accent\\s*([0-9]*)\\s*([a-zA-Z])/m){m=$~\n a=Accents[m[1]+m[2]]\n if a then a\n else $err.print \"** unhandled accent #{fname}:#{sec} #{m[0]}\\n\"\n end}\n text.gsub!(/\\\\psubsection\\s*\\{(.*?)\\}/m){m=$~; m[1].h(\"h3\")}\n text.gsub!(/\\\\psection\\s*\\{(.*?)\\}/m){m=$~;m[1].h(\"h1\").style(\"color:#ff0000\")}\n text.gsub!(/\\\\index\\s*\\{(.*?)\\}/m){m=$~\n $indexcount+=1 # emit an anchor and remember the index keys for later\n r=m[1].gsub(/\\\\([a-zA-Z]+) /){m=$~; $trads[m[1]] || \"\\\\#{m[1]} \"}\n $index[r]=$index[r].push([\"#{fname}#I#{$indexcount}\",\"#{sec.chapnum}.#{sec.secnum}\"])\n \"<A name = \\\"I#{$indexcount}\\\"></a>\\n\"\n }\n text.gsub!(/\\\\begin\\{([^}]*)\\}(.*?)\\\\end\\{\\1\\}/m){m=$~\n case m[1]\n when \"displaymath\",\"equation\" then mathdisplay[m[2]]\n when \"center\" then m[2].h(\"center\")\n when \"itemize\",\"enumerate\" then m[2]\n else \"{beg-\"+m[1]+\"}\".h(\"s\")+m[2]+\"{end-\"+m[1]+\"}\".h(\"s\")\n end}\n text.gsub!(/~/,\" \")\n end\n# nestedbraces=// # can define but not recognized inside another regexp\n# text.gsub!(/\\\\(\\s)/){m=$~;m[1]}\n text.gsub!(/\\{\\s*\\\\(?:sl|it)([^}]*)\\}/m){m=$~;\n sp[TeX2htm(m[1],state).h(\"I\")]}\n text.gsub!(/\\{\\s*\\\\cal([^}]*\\{[^}]*\\}[^}]*)\\}/m){sp[$~[1].style(\"font-family: cursive\")]}\n text.gsub!(/\\{\\s*\\\\cal([^}]*)\\}/m){sp[$~[1].style(\"font-family: cursive\")]}\n text.gsub!(/\\{\\s*\\\\tt([^}]*\\{[^}]*\\}[^}]*)\\}/m){m=$~;sp[m[1].h(\"code\")]}\n text.gsub!(/\\{\\s*\\\\tt([^}]*)\\}/m){m=$~;sp[m[1].h(\"code\")]}\n text.gsub!(/\\{\\s*\\\\bf([^}]*\\{[^}]*\\}[^}]*)\\}/m){m=$~;sp[m[1].h(\"strong\")]}\n text.gsub!(/\\{\\s*\\\\bf([^}]*)\\}/m){m=$~;sp[m[1].h(\"strong\")]}\n text.gsub!(/\\{\\s*\\\\em([^}]*\\{[^}]*\\}[^}]*)\\}/m){m=$~;sp[m[1].h(\"em\")]}\n text.gsub!(/\\{\\s*\\\\em([^}]*)\\}/m){m=$~;sp[m[1].h(\"em\")]}\n if state==:math\n text.gsub!(/</){sp[\"<\"]}\n text.gsub!(/>/){sp[\">\"]}\n texarg=/([^{\\\\]|\\{(?:(?:[^{}]|\\{[^{}]*\\})*)\\}|\\\\[a-zA-Z]+)/\n text.gsub!(/\\^\\\\prime/om){sp[\"'\"]}\n text.gsub!(/\\^\\{\\\\prime\\\\prime\\}/om){sp[\"''\"]}\n text.gsub!(/\\\\not\\s*\\\\equiv/om){sp[\"≢\"]}\n text.gsub!(/\\\\(?:text|mbox|hbox)\\{([^{}]*)\\}/){m=$~;\n sp[TeX2htm(m[1]).h(\"/i\")]}\n text.gsub!(/\\^\\s*#{texarg}/om){m=$~;sp[TeX2htm(m[1],:math).h(\"sup\")]}\n text.gsub!(/_\\s*#{texarg}/om){m=$~;sp[TeX2htm(m[1],:math).h(\"sub\")]}\n text.gsub!(/\\\\underline\\s*#{texarg}/om){m=$~;sp[TeX2htm(m[1],:math).h(\"u\")]}\n text.gsub!(/\\\\overline\\s*#{texarg}/om){m=$~;\n sp['<span style=\"text-decoration: overline\">'+\n TeX2htm(m[1],:math)+\"<\\/span>\"]}\n text.gsub!(/\\{\\s*\\\\rm([^}]*)\\}/m){m=$~;sp[m[1].h(\"I\")]}\n text.gsub!(/\\{\\s*\\\\mathcal([^}]*)\\}/m){m=$~;sp[m[1].h(\"u\")]}\n text.gsub!(/\\\\frac#{texarg}#{texarg}/om){m=$~;\n n=TeX2htm(m[1],'math'); d=TeX2htm(m[2],'math')\n n=\"(#{n})\" if n.length>1\n d=\"(#{d})\" if n.length>1\n \"#{n}/#{d}\"}\n text.gsub!(/\\\\not\\s*\\\\in/){sp[\"∉\"]}\n text.gsub!(/\\\\not\\s*=/){sp[\"≠\"]}\n text.gsub!(/\\\\([a-zA-Z]+)/){m=$~;\n if MathMacs[m[1]] then sp[MathMacs[m[1]]] else m[0] end}\n text.gsub!(/\\\\pmod\\s*#{texarg}/){m=$~;sp[\"(</i>mod<i> #{TeX2htm(m[1],:math)})\"]}\n text.gsub!(/\\\\begin\\{([^}]*)\\}(.*?)\\\\end\\{\\1\\}/m){m=$~\n case m[1]\n when \"array\",\"pmatrix\" then \n if m[1]==\"array\" then r=m[2].sub(/\\{[cl]*\\}/,\"\") else r=m[2] end\n r=r.split(\"\\\\cr\").map{|l| l.split(\"&\").map{|i| \n i.h(\"I\").h(\"td\")}.join(\"\").h(\"tr\")}.join.h('table style=\"display:inline-table;\"').h(\"td\").h(\"/td\")\n if m[1]==\"pmatrix\" then \"(\"+r+\")\" else r end\n else \"{beg-\"+m[1]+\"}\".h(\"s\")+m[2]+\"{end-\"+m[1]+\"}\".h(\"s\")\n end\n }\n end\n text.gsub!(/\\\\(?:text|mbox|hbox)\\{([^{}]*)\\}/){m=$~;\n sp[TeX2htm(m[1]).h(\"/i\")]}\n text.gsub!(/\\\\([a-zA-Z]+)/){m=$~;AlwaysMacs[m[1]] || m[0]}\n text.gsub!(/\\{([^{}]*)\\}/){m=$~; m[1]}\n text.gsub!(/\\\\([a-zA-Z]+) /){m=$~; $trads[m[1]] || \"\\\\#{m[1]} \"}\n text.gsub!(/\\\\([a-zA-Z]+) /){m=$~; $trads[m[1]] || \"\\\\#{m[1]} \"}\n text.gsub!(/\\\\([a-zA-Z]+)/){m=$~; $trads[m[1]] || \"\\\\#{m[1]}\"}\n text.scan(/\\\\([a-zA-Z]+)/){|m| $err.print \"!!!!! #{m.inspect} state=#{state}\\n\"}\n text\nend",
"def unified_diff(text_old, text_new, label=\"--- old\\n+++ new\\n\", context=3)\n msg = \"\\\\ No newline at end of string\"\n lines_old = _text2lines(text_old, msg)\n lines_new = _text2lines(text_new, msg)\n #\n buf = \"#{label}\"\n len = 0\n prevhunk = hunk = nil\n diffs = Diff::LCS.diff(lines_old, lines_new)\n diffs.each do |diff|\n hunk = Diff::LCS::Hunk.new(lines_old, lines_new, diff, context, len)\n if hunk.overlaps?(prevhunk)\n hunk.unshift(prevhunk)\n else\n buf << prevhunk.diff(:unified) << \"\\n\"\n end if prevhunk\n len = hunk.file_length_difference\n prevhunk = hunk\n end\n buf << prevhunk.diff(:unified) << \"\\n\" if prevhunk\n return buf\n end",
"def to_html\n \"<p>#{inline_html(escape_xml(@lines.join(\"\\n\")))}</p>\"\n end",
"def render_issue_relations(issue, relations)\n manage_relations = User.current.allowed_to?(:manage_issue_relations, issue.project)\n s = ''.html_safe\n relations.each do |relation|\n other_issue = relation.other_issue(issue)\n css = \"issue hascontextmenu #{other_issue.css_classes}\"\n buttons =\n if manage_relations\n link_to(\n l(:label_relation_delete),\n relation_path(relation),\n :remote => true,\n :method => :delete,\n :data => {:confirm => l(:text_are_you_sure)},\n :title => l(:label_relation_delete),\n :class => 'icon-only icon-link-break'\n )\n else\n \"\".html_safe\n end\n buttons << link_to_context_menu\n s <<\n content_tag(\n 'tr',\n content_tag('td',\n check_box_tag(\n \"ids[]\", other_issue.id,\n false, :id => nil),\n :class => 'checkbox') +\n content_tag('td',\n relation.to_s(@issue) {|other|\n link_to_issue(\n other,\n :project => Setting.cross_project_issue_relations?)\n }.html_safe,\n :class => 'subject',\n :style => 'width: 50%') +\n content_tag('td', other_issue.status, :class => 'status') +\n content_tag('td', format_date(other_issue.start_date), :class => 'start_date') +\n content_tag('td', format_date(other_issue.due_date), :class => 'due_date') +\n content_tag('td', link_to_user(other_issue.assigned_to), :class => 'assigned_to') +\n content_tag('td',\n (if other_issue.disabled_core_fields.include?('done_ratio')\n ''\n else\n progress_bar(other_issue.done_ratio)\n end),\n :class=> 'done_ratio') +\n content_tag('td', buttons, :class => 'buttons'),\n :id => \"relation-#{relation.id}\",\n :class => css)\n end\n content_tag('table', s, :class => 'list issues odd-even')\n end",
"def run_diff(a, b)\n\t\t\ta = \"\" if a == nil\n\t\t\tb = \"\" if b == nil\n\t\n\t\t\t@a_words = a.split(\" \")\n\t\t\t@b_words = b.split(\" \")\n\t\n\t\t\tmax = @a_words.length\n\t\t\tmax = @b_words.length if @b_words.length > @a_words.length\n\t\n\t\t\tfor i in 0..max-1\n\t\t\t\t@differences.push(i) if @a_words[i] != @b_words[i]\n\t\t\tend\n\t\t\t\n\t\t\t# return void\n\t\t\treturn\n\t\tend",
"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 format_rows descriptions\n formatted = descriptions.map do |description|\n @column_descriptions.map do |field, _, format,|\n format % description[field]\n end\n end\n\n [@headers].concat formatted\n end",
"def make_row(column_elements)\n\t\"<tr><td>#{column_elements.join(\"</td><td>\")}</td></tr>\"\nend",
"def table_close(opts)\n output = \"\\\\begin{table}\\n\"\n output << \" \\\\centering\\n\"\n output << \" \\\\begin{tabular}{ #{\"l \" * @table[0].size }}\\n\"\n @table.each do |row|\n output << \" #{row.join(\" & \")} \\\\\\\\\\n\"\n end\n output << \" \\\\end{tabular}\\n\"\n output << \"\\\\end{table}\\n\"\n output\n end",
"def to_html threshold=30\n name = @name || 'nil'\n html = '<table>' + '<tr><th> </th><th>' + name.to_s + '</th></tr>'\n @index.each_with_index do |index, num|\n html += '<tr><td>' + index.to_s + '</td>' + '<td>' + self[index].to_s + '</td></tr>'\n \n if num > threshold\n html += '<tr><td>...</td><td>...</td></tr>'\n break\n end\n end\n html += '</table>'\n\n html\n end",
"def to_html threshold=30\n name = @name || 'nil'\n html = '<table>' + '<tr><th> </th><th>' + name.to_s + '</th></tr>'\n @index.each_with_index do |index, num|\n html += '<tr><td>' + index.to_s + '</td>' + '<td>' + self[index].to_s + '</td></tr>'\n \n if num > threshold\n html += '<tr><td>...</td><td>...</td></tr>'\n break\n end\n end\n html += '</table>'\n\n html\n end",
"def compare_data(table)\n data1 = query(@db1, \"SELECT * FROM #{table}\", \"hash\")\n data2 = query(@db2, \"SELECT * FROM #{table}\", \"hash\")\n \n changes = false\n data1.each do |row|\n if ! data2.include?(row)\n to_insert(@db2_output, table, row)\n changes = true\n end\n end \n @db2_output << \"\\n\" if changes\n \n changes = false\n data2.each do |row|\n if ! data1.include?(row)\n to_insert(@db1_output, table, row)\n changes = true\n end\n end\n @db1_output << \"\\n\" if changes\n end",
"def tableize_order_payment(hash, options = {class: 'table table-bordered'})\n if hash.present? && hash.kind_of?(Hash)\n content_tag(:table, class: options[:class]) do\n title = options.delete(:title)\n\n content = content_tag(:tbody) do\n hash.map do |k, v|\n content_tag(:tr) do\n content_tag((options[:th] ? :th : :td), k) +\n content_tag(:td) do\n if v.kind_of?(Hash)\n tableize_order_payment(v, options.merge(th: (options.key?(:sub_th) ? options[:sub_th] : options[:th])))\n elsif v.kind_of?(Array)\n '[' + v.join(', ') + ']'\n else\n v\n end\n end\n end\n end.join.html_safe\n end\n\n title.blank? ? content : (content_tag(:thead) { content_tag(:tr) { content_tag(:th, title, colspan: 2) } } + content)\n end\n else\n hash.to_s.html_safe\n end\n end",
"def better_format(text, html_options = {}, options = {})\n wrapper_tag = options.fetch(:wrapper_tag, :p)\n\n text = sanitize(text) if options.fetch(:sanitize, true)\n paragraphs = split_paragraphs(text)\n\n if paragraphs.empty?\n content_tag(wrapper_tag, nil, html_options)\n else\n paragraphs.map { |paragraph|\n # paragraph = \"<br />\" if paragraph.empty? || paragraph =~ /\\A\\s+\\z/ \n paragraph.gsub!(/(?:^\\s)|\\G\\s/m, \" \") if !(paragraph[0..4]==\"<pre>\" && paragraph[-6..-1]==\"</pre>\")\n content_tag(wrapper_tag, paragraph, html_options, options[:sanitize])\n }.join(\"\\n\\n\").html_safe\n end\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 format_table!\n table.rows.each do |row|\n row.cells.each_with_index do |cell, i|\n set_cell_format_option!(cell, i)\n format_cell!(cell)\n end\n end\n\n true\n end",
"def truncated_diff_lines\n prev_lines = []\n\n highlighted_diff_lines.each do |line|\n if line.meta?\n prev_lines.clear\n else\n prev_lines << line\n\n break if for_line?(line)\n\n prev_lines.shift if prev_lines.length >= NUMBER_OF_TRUNCATED_DIFF_LINES\n end\n end\n\n prev_lines\n end",
"def sanitize_cells(rows)\n rows.map do |cells|\n cells.map do |cell|\n cell ? cell.strip : \"\"\n end\n end\n end",
"def bid_cells(bid, seed_on_left_or_right)\n options = {:align => seed_on_left_or_right, :style => \"border-bottom: 1px solid black; padding-#{seed_on_left_or_right}: 2mm;\"}\n seed = content_tag :td, (bid ? \"(#{bid.seed})\" : ' '), options\n team = content_tag :td, (bid ? h(bid.team.name) : ' '), options\n cells = [seed, team]\n cells.reverse! if 'right' == seed_on_left_or_right\n cells\n end",
"def export_diff_two_table(case_name, current, expect, error_list)\n pathname = get_path_name(case_name, @report_directory)\n \n book = Spreadsheet::Workbook.new\n sheet1 = book.create_worksheet :name=> case_name\n \n sheet1.row(0).push \"Current Test Table\"\n sheet1.row(0).default_format = @titile_format\n \n curr_row_idx = sheet1.last_row_index + 1 \n export_two_table_to_excel(curr_row_idx, sheet1, current)\n\n idx = sheet1.last_row_index + 1\n sheet1.row(idx).push \"Expect Table\"\n sheet1.row(idx).default_format = @titile_format\n \n expect_row_idx = sheet1.last_row_index + 1 \n export_two_table_to_excel(expect_row_idx, sheet1, expect)\n \n if !error_list.nil?\n handle_error_list(curr_row_idx, expect_row_idx, sheet1, error_list[0])\n handle_error_list(curr_row_idx + current[0].length + 1, expect_row_idx + expect[0].length + 1, sheet1, error_list[1])\n end\n book.write(pathname)\n end",
"def html(cell_value)\n apply_format(cell_value, format, option).to_s\n end",
"def merge_cells(refs)\n xml = String.new(%Q{<mergeCells r=\"#{refs.length}\">})\n\n refs.each do |ref|\n xml << %Q{<mergeCell ref=\"#{ref}\"/>}\n end\n\n xml << '</mergeCells>'\n @xml_merge_cells = xml\n end",
"def block_textile_table( text ) \n text.gsub!( TABLE_RE ) do |matches|\n\n tatts, fullrow = $~[1..2]\n tatts = pba( tatts, 'table' )\n tatts = shelve( tatts ) if tatts\n rows = []\n\n fullrow.each_line do |row|\n ratts, row = pba( $1, 'tr' ), $2 if row =~ /^(#{A}#{C}\\. )(.*)/m\n cells = []\n row.split( /(\\|)(?![^\\[\\|]*\\]\\])/ )[1..-2].each do |cell|\n next if cell == '|'\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 }</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 \"\\t<table#{ tatts }>\\n#{ rows.join( \"\\n\" ) }\\n\\t</table>\\n\\n\"\n end\n end"
] | [
"0.6884463",
"0.6313503",
"0.6285979",
"0.61260605",
"0.6093102",
"0.57066536",
"0.5673564",
"0.5631533",
"0.5617306",
"0.557994",
"0.5558415",
"0.5512505",
"0.5511733",
"0.54913265",
"0.5454809",
"0.54534966",
"0.5448401",
"0.54331577",
"0.537509",
"0.53118265",
"0.53113043",
"0.5294953",
"0.52816194",
"0.5211795",
"0.5209609",
"0.52092284",
"0.51846135",
"0.5183543",
"0.5183511",
"0.51821697",
"0.51723844",
"0.5164443",
"0.5152615",
"0.5142868",
"0.5122578",
"0.5118337",
"0.5110731",
"0.5108053",
"0.51070374",
"0.5097279",
"0.50957656",
"0.50720453",
"0.50487345",
"0.5035429",
"0.50220394",
"0.50025904",
"0.49942747",
"0.49828056",
"0.4978932",
"0.49670044",
"0.49643973",
"0.49507186",
"0.49442872",
"0.49408352",
"0.49379924",
"0.49359185",
"0.49236843",
"0.4911545",
"0.4906619",
"0.49038494",
"0.48928615",
"0.4883297",
"0.48816428",
"0.48810202",
"0.48723507",
"0.48645312",
"0.48638985",
"0.486165",
"0.48592234",
"0.48543",
"0.48462448",
"0.48412234",
"0.48314014",
"0.48307887",
"0.482245",
"0.4820589",
"0.4815536",
"0.4807836",
"0.47979605",
"0.47919577",
"0.47901717",
"0.47882771",
"0.47845554",
"0.47777206",
"0.47674978",
"0.47672546",
"0.47494888",
"0.47494888",
"0.47481883",
"0.47463813",
"0.4742262",
"0.47374496",
"0.47347793",
"0.47347245",
"0.4732272",
"0.47316927",
"0.47309083",
"0.47282606",
"0.4716218",
"0.47135082"
] | 0.61839837 | 3 |
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",
"def expected_headers_unmet\n unmet = []\n expected = test_case.expected_headers\n expected.each_pair do |k,v|\n got = response.headers[k]\n unmet << \"[headers] #{v} expected for #{k}, got #{got}\" unless (got == v)\n end\n unmet.empty? ? nil : unmet.join(\"\\n\")\n end",
"def find_indices(keys)\n %i[row col].collect do |which|\n index = @headers[which].find_key_idx(keys[which])\n raise Report::ReportError, \"no matching #{which} header key for '#{keys[which]}'\" unless index\n index\n end\n end",
"def check_uniqueness_of_header(header_array)\n uniqueness = Array.new\n duplicates = Array.new\n\n header_array.each do |header|\n if uniqueness.include? header\n duplicates << header\n else\n uniqueness << header\n end\n end\n\n return duplicates.uniq\n\n end",
"def test\n return true if expected_header == actual_header\n\n message = \"expected #{expected_header.inspect}, got #{actual_header.inspect}\"\n raise(UnexpectedHeader, message)\n end",
"def column_headers\n use_column_headers ? columns.map(&:heading) : true\n end",
"def input_headers(values=false)\r\n if self.sample_type.downcase == SAMPLE_CONFIG[\"Review\"][\"title\"].downcase\r\n last_work_Sample = sample.last_work_sample(self)\r\n input_headers = last_work_sample.input_headers\r\n if values\r\n if last_work_sample.position == 0\r\n input_headers = self.line.input_headers.map{|i| [i.label, i.value] }\r\n else\r\n input_headers = input_headers.map{|i| [i,\"result from previous sample\"] }\r\n end\r\n end\r\n input_headers = last_work_sample.input_headers\r\n input_headers = input_headers.map{|i| [i,\"result from previous sample\"] } if values\r\n else\r\n prev_sample = Sample.previous_sample(self)\r\n if prev_sample.nil?\r\n input_headers = values ? self.line.input_headers.map{|i| [i.label, i.value] } : self.line.input_headers.map(&:label)\r\n elsif prev_sample.instruction.instruction_type == \"raw_html\"\r\n # TODO:: Make this work once CFML is started\r\n input_headers = prev_sample.instruction.raw_html.scan(/result\\[(\\S*)\\]/).flatten\r\n input_headers = input_headers.map{|i| [i,\"result from previous sample\"] } if values\r\n else\r\n input_headers = prev_sample.instruction.form_fields.map(&:label)\r\n input_headers = input_headers.map{|i| [i,\"result from previous sample\"] } if values\r\n end\r\n end\r\n input_headers\r\n\r\n end",
"def transaction_summary_table_sub_headers\n _array = Array.new(0)\n transaction_summary_table_sub_header.each do |_th|\n Log.debug \"QALog: ============sub column name is - \" + _th.text() + \"============\"\n _array.push(_th.text())\n end\n return _array\n end",
"def get_cells_headers_ids(header, index)\n ids = []\n header.each do |row|\n if row[index].has_attribute?('scope') &&\n row[index].get_attribute('scope') == 'col'\n ids.push(row[index].get_attribute('id'))\n end\n end\n ids\n end",
"def table_has_header?(columns)\n columns.any? { |column| !column[:title].nil? }\n end",
"def column_header_names\r\n column_headers.collect {|header| header.name }\r\n end",
"def summary_table_headers(args={})\n\t\t'''\n\t\t\t<thead>\n\t <tr>\n\t <th>Created At</th>\n\t <th>Payable To Organization Id</th>\n\t <th>Payable From Organization Id</th>\n\t <th>Payable From Patient Id</th>\n\t <th>Total</th>\n\t <th>Paid</th>\n\t <th>Pending</th>\n\t <th>Options</th>\n\t </tr>\n\t </thead>\n\t\t'''\n\tend",
"def 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 test_fail_on_pk_overlap_with_header\n end",
"def accept_table header, body, aligns\n @res << \"\\n<table role=\\\"table\\\">\\n<thead>\\n<tr>\\n\"\n header.zip(aligns) do |text, align|\n @res << '<th'\n @res << ' align=\"' << align << '\"' if align\n @res << '>' << CGI.escapeHTML(text) << \"</th>\\n\"\n end\n @res << \"</tr>\\n</thead>\\n<tbody>\\n\"\n body.each do |row|\n @res << \"<tr>\\n\"\n row.zip(aligns) do |text, align|\n @res << '<td'\n @res << ' align=\"' << align << '\"' if align\n @res << '>' << CGI.escapeHTML(text) << \"</td>\\n\"\n end\n @res << \"</tr>\\n\"\n end\n @res << \"</tbody>\\n</table>\\n\"\n end",
"def insert_headers headers = []\n @headers = Hash[headers.map.with_index { |e, i| [e, i] }]\n define_row(@headers)\n\n @has_headers = false\n end",
"def header_row_index\n index(header)\n end",
"def table_header\n print '<table class=\"colors sortable\">', \"\\n\"\n print '<col width=\"15%\"><col width=\"20%\"><col width=\"15%\"><col width=\"50%\">'\n\n print '<tr>'\n print '<th class=\"sorttable_nosort\">Swatch</th>', \"\\n\"\n print '<th class=\"clickable\">Color name</th>', \"\\n\"\n print '<th id=\"hex\" class=\"hidden\">' # fake column for colors\n\n print '<th class=\"sorttable_nosort clickable\">', \"\\n\"\n print \"<span title='Sort by triplet' onclick='sortcol(\\\"hex\\\")'>Hex Triplet</span>\", \"\\n\"\n print \"<img id=\\\"arrow\\\" src='css/images/arrow-both.png'/>\", \"\\n\"\n %w[R G B].each do |letter|\n print \"<span title='Sort by #{letter} value' onclick='sortcol(\\\"#{letter}\\\")'>#{letter}</span>\", \"\\n\"\n end\n print '</th>', \"\\n\"\n\n print '<th class=\"sorttable_nosort\"><span class=\"latex\">L<sup>a</sup>T<sub>e</sub>X</span></th>', \"\\n\"\n print '<th id=\"R\" class=\"hidden\"></th>'\n print '<th id=\"G\" class=\"hidden\"></th>'\n print '<th id=\"B\" class=\"hidden\"></th>'\n print '</tr>'\nend",
"def sub_admins_table_headers\n expand(subadmins_icon)\n wait_until_ajax_finished(sub_admins_div)\n sub_admins_table.headers_text\n end",
"def create_column_headers_index_hash\n collect_column_headers\n @column_hash = Hash[(0...@column_headers.size).zip(@column_headers)] # ==> {0=>102231711, 1=>103244134, 2=>103285344, 3=>103293593}\nend",
"def compare_table current_table, expect_table\n @compareTable.compare_table(current_table, expect_table)\n end",
"def survey_headers(survey_ids)\n # s_headers = cache_fetch(\"survey_headers_#{survey_ids.join('-')}\", :expires_in => 15.minutes) do\n ss = Survey.find(survey_ids)\n ss.inject(Dictionary.new) { |hash, s| hash[s.id] = s.cell_variables; hash }.order_by\n # end\n end",
"def get_headers\n headers = []\n @data.each do |druid, column_hash|\n headers << column_hash.keys\n end\n headers_out = headers.flatten.uniq\n end",
"def build_header(keys_template)\n header = ''\n names = []\n keys = deep_copy(keys_template)\n\n keys.each { |key|\n begin\n if @config.header_mappings.any? { |k| k.include? key }\n\n header_label = key\n\n @config.header_mappings.each { |k, v|\n if header_label.include? k\n header_label.gsub!(k, v)\n end\n\n }\n names << header_label\n\n elsif @config.header_overrides.split(',').include?(key)\n names << key\n elsif key.include?('coordinates')\n names << key\n elsif key.split('.')[-1].is_i?\n names << key\n else\n #We want to grab the last element and add it to the array.\n name = key.split(\".\")[-1]\n\n if !names.include?(name)\n names << name\n else\n if key.split(\".\")[-2].is_i?\n name = key.split(\".\")[-3..-1].join(\".\")\n else\n name = key.split(\".\")[-2..-1].join(\".\")\n end\n\n if !names.include?(name)\n names << name\n else\n name = key.split(\".\")[-3..-1].join(\".\")\n if !names.include?(name)\n names << name\n else\n #p \"No action taken. #{name} not added to name array. (build_header)\"\n end\n end\n end\n end\n rescue Exception => e\n AppLogger.log.error(\"ERROR in build_header method with #{key}: #{e.message}\")\n end\n }\n\n header = CSV.generate do |csv|\n csv << names\n end\n\n header\n end",
"def test_column_names_equals_of_class_table_schema_difference\n namesABC = %w(columnA columnB columnC)\n [\n [[] , [] , true ],\n [%w(id) , %w(id) , true ],\n [namesABC, %w(columnA columnB columnC), true ],\n [namesABC, %w(columnA columnB columnD), false],\n [namesABC, %w(columnI columnB columnC), false],\n ].each do |column_names1, column_names2, expected|\n table_schema1 = make_table_schema_mock(column_names1)\n table_schema2 = make_table_schema_mock(column_names2)\n ts_diff = TableSchemaDifference.new(table_schema1, table_schema2)\n assert_equal(expected, ts_diff.column_names_equals?, \"TableSchemaDifference#column_names_equals?\")\n end\n end",
"def generate_header_row\n (@header.map {|x| generate_header_item(x)}).join\n end",
"def index_headers\n index_fields.map { |field| field.label }\n end",
"def create_row_headers_index_hash\n collect_row_headers\n @row_hash = Hash[(0...@row_headers.size).zip(@row_headers)] # ==> {0=>0, 1=>734638, 2=>734639, 3=>734640, 4=>734641, 5=>734642, 6=>734643, 7=>734644, 8=>734645, 9=>734646}\nend",
"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 dwc_occurrence_table_header_tag\n content_tag(:tr, CollectionObject::DwcExtensions::DWC_OCCURRENCE_MAP.keys.collect{|k| content_tag(:th, k)}.join.html_safe, class: [:error])\n end",
"def valid_headers?(row)\n (required_csv_headers - row.keys).empty?\n end",
"def transaction_summary_table_main_headers\n transaction_summary_table.headers_text\n end",
"def merge(other)\n headers = dup\n other.each do |field, value|\n headers[downcased(field)] = value\n end\n headers\n end",
"def headers_with_selection selected_sort, except: [], headers: nil\n headers ||= self.headers\n all_headers = []\n if selected_sort.keys.length > 0\n all_headers = headers.each do |header|\n if header[:field] == selected_sort['field']\n header[:sorted_by] = selected_sort['direction']\n else\n header[:sorted_by] = nil\n end.deep_dup\n end\n else\n all_headers = headers.deep_dup\n end\n return all_headers.select{ |header| !except.include?(header[:field]) }\n end",
"def check_correspondence(header)\n\t\terr = \"\"\n\t\tif(header.length > @map.length)\n\t\t\traise \"inconsistent between header and mapping\"\n\t\tend\n\t\t\n\t\tidx = 0\n\t\t@map.each_key do |key|\n\t\t\tif(idx == header.length-1) \n\t\t\t\tbreak\n\t\t\telsif(header[idx].eql?(key))\n\t\t\t\tidx+=1\n\t\t\tend\n\t\tend\n\t\tif(idx < header.length - 1)\n\t\t\traise \"inconsistent between header and mapping_\"\n\t\tend\n\t\t\n\t#\tputs header\n\t#\tputs @map\n\t#\tputs \"IDX=\"+idx.to_s\t\n\tend",
"def headers\n @headers ||= next_row\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 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 << (1..@generated.length).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 << (1..@expected.length).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 header\n temp = \"\"\n result = \"SpecId\\tLabel\\tCharge\\t\"\n \n nokogiriDoc(@target).xpath(\"//#{@xmlns}search_hit\").each do |hit|\n temp = hit.xpath(\".//#{@xmlns}search_score\")\n break\n end\n \n temp.each do |score|\n result += score.xpath(\"./@name\").to_s + \"\\t\"\n end\n \n result += \"Peptide\\t\" + \"Proteins\"\n end",
"def typus_table_header(model, fields)\n returning(String.new) do |html|\n headers = []\n fields.each do |key, value|\n order_by = model.reflect_on_association(key.to_sym).primary_key_name rescue key\n sort_order = (params[:sort_order] == 'asc') ? 'desc' : 'asc'\n if (model.model_fields.map(&:first).collect { |i| i.to_s }.include?(key) || model.reflect_on_all_associations(:belongs_to).map(&:name).include?(key.to_sym)) && params[:action] == 'index'\n headers << \"<th>#{link_to \"<div class=\\\"#{sort_order}\\\">#{t(key.humanize)}</div>\", { :params => params.merge(:order_by => order_by, :sort_order => sort_order) }}</th>\"\n else\n headers << \"<th>#{t(key.humanize)}</th>\"\n end\n end\n headers << \"<th> </th>\"\n html << <<-HTML\n<tr>\n#{headers.join(\"\\n\")}\n</tr>\n HTML\n end\n end",
"def column_headers(data)\n data.find { |line| line.split(' ').first.downcase == HEADER_INDICATOR }.split(' ')\n end",
"def headers\n # units and source have to go last, so if we push in a new header, these go\n # at end\n @headers+['units','source']\n end",
"def machine_hash(headers,rows)\n # This is just to give a nice data structure (a hash of )\n rows.each_with_index.map do |row, index|\n # todo - rearrange the hash so it is sorted - do we need the row index?\n Hash[headers.each_with_index.map { |header, pos| \n [header, row[pos] ]}\n ].merge('row' => index+2)\n end\n end",
"def show_headers\n hrows = []\n current_context[0][:headers].map do |hash|\n hash.each do |_key , _val|\n _val = _val.scan(/.{100}/).join(\"\\n\") if _val.size > 150 # This line To fix table layout\n\n hrows << [\"#{_key}\".green , \"#{_val}\".white]\n hrows << :separator\n end\n end\n\n return hrows\n end",
"def compare_arrays(*arrays)\n arrays.\n arrays.each do |tab,*tabs|\n puts \"tabs = #{tabs}\"\n\n end\n end",
"def generate_header(array)\n header_array = array.dup\n header_array.unshift('')\n end",
"def tabular_input_cleanse_header\n ignored_columns = tabular_input.header.cleanse!\n logger.warn('Stripped out invalid columns from custom header', ignored_columns) unless ignored_columns.empty?\n\n self.tabular_input_header = tabular_input.header.columns\n end",
"def set_converted_headers\n header_conversion_chart = @import_rows_to_class.const_get(:RECORD_HEADERS).invert\n @converted_headers = importable_columns.map { |col| header_conversion_chart[col] }\n end",
"def calculate_header\n headers = []\n height = 0\n @current_groups.each do |field, current_value|\n identifier_field = @sections[:groups][field.to_sym][:settings][:identifier_field] || nil\n value = (!@record.class.reflect_on_association(field).nil? and !identifier_field.nil?) ? @record.send(field.to_sym).send(identifier_field) : @record.send(field)\n\n if value != current_value\n reset_groups_values field\n\n headers << field.to_sym\n height += @sections[:groups][field.to_sym][:settings][:height] + @sections[:groups][field.to_sym][:settings][:posY]\n\n @current_groups[field] = value\n end\n end unless @current_groups.empty?\n\n [headers, height]\n end",
"def generate_header_row\n generate_row(@header)\n end",
"def generate_header_row\n generate_row(@header)\n end",
"def header\n self.mult_table.header_line.to_s + \"\\n\"\n end",
"def grid_head_data_headers(cols: nil, **opt, &block)\n start_column = positive(opt.delete(:'aria-colindex')) || 1\n (cols || grid_row_columns).map.with_index(start_column) do |col, idx|\n grid_head_cell(col, **opt, 'aria-colindex': idx, &block)\n end\n end",
"def test_csv_table_match(subject)\n # Compare the fields\n if !subject.empty?\n subject_fields = subject[0].keys\n master_fields = @golden_master.headers\n\n if subject_fields.count != master_fields.count\n throw_no_match \"Expected #{master_fields.count} field(s), got #{subject_fields.count}\"\n end\n\n master_fields.each_with_index do |column, index|\n if column != subject_fields[index]\n throw_no_match \"Expected field \\\"#{column}\\\", got field \\\"#{subject_fields[index]}\\\"\"\n end\n end\n end\n\n # Compare the number of records\n subject_record_count = subject.count\n master_record_count = @golden_master.inject(0){|count| count += 1}\n if subject_record_count != master_record_count\n throw_no_match \"Expected #{master_record_count} record(s), got #{subject_record_count}\"\n end\n\n # Compare the values of the golden master with the subject\n current_row = 0\n @golden_master.each do |row|\n row.each do |field, master_string|\n subject_value = subject[current_row][field]\n if !match_values?(master_string, subject_value)\n throw_no_match \"Field \\\"#{field}\\\", Record #{current_row + 1}: Expected value #{master_string.nil? ? '<NULL>' : \"\\\"#{master_string}\\\"\"}, got #{subject_value.nil? ? '<NULL>' : \"\\\"#{subject_value}\\\"\"}\"\n end\n end\n current_row += 1\n end\n end",
"def generate_header_row\n '<tr>' + '<th>' + \"#{(@header.map {|x| generate_header_item(x)}).join('</th><th>')}\" + '</th></tr>' + \"\\n\"\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 master_mix_table(inputs:, input_names:, composition:, mult:)\n header = [\n \"#{composition.polymerase.display_name} #{composition.polymerase.item}\",\n \"#{composition.dye.display_name} #{composition.dye.item}\",\n composition.water.display_name\n ]\n\n row = [\n composition.polymerase.add_in_table(mult),\n composition.dye.add_in_table(mult),\n composition.water.add_in_table(mult)\n ]\n\n input_names.each_with_index do |input_name, i|\n header << \"#{input_name} #{inputs[i]}\"\n row << composition.input(input_name).add_in_table(mult)\n end\n\n [header, row].transpose\n end",
"def table_header\n line = \"File|Total\".dup\n line << \"|Line\" if header_line_rate?\n line << \"|Branch\" if header_branch_rate?\n line << \"\\n\"\n end",
"def filtered_schema_headers(filter)\n repeater_keys = @schema_hash.select {|k,v| v == \"R\"}.keys\n filter_keys = @schema_hash.select {|k,v| v == filter}.keys\n\n return repeater_keys + filter_keys\n end",
"def union_compatible?(other)\n header == other.header\n end",
"def check_header_and_footer()\n locators = Locator.where(brand: 'all', step: 'vanityuci')\n header_check(locators)\n footer_check(locators)\n return true\n end",
"def partner_signups_report_headers\n partner_signups_report_table.headers_text\n end",
"def thead(*args)\n content_tag :thead, content_tag(:tr, args.map { |arg| content_tag :th, arg.to_s.humanize }.join.html_safe)\n end",
"def thead(*args)\n content_tag :thead, content_tag(:tr, args.map { |arg| content_tag :th, arg.to_s.humanize }.join.html_safe)\n end",
"def write_headers\n @sheet.row(0).replace [header]\n @sheet.row(3).replace name_header_row(@player.longs.first.ticker_name, @player.shorts.first.ticker_name, @player.calls.first.ticker_name)\n @sheet.row(4).replace data_header_row(long_short_headers, long_short_headers, call_put_headers)\n\n @sheet.row(17).replace name_header_row(@player.futures.first.ticker_name, 'Total P&L', @player.puts.first.ticker_name)\n @sheet.row(18).replace data_header_row(long_short_headers, overall_headers, call_put_headers)\n end",
"def headers\n @attributes + @includes.values.flatten\n end",
"def headers\n rows.first\n end",
"def write_header csv = nil\n csv << indices\n end",
"def test_compare_many\n result = @comparer.compare @first_doc, @second_doc\n\n #assert_equal result >= 0, true\n #assert_equal result <= 1, true\n\n results = Array.new(@documents.length) { Array.new(@documents.length, 0) }\n\n @dest = SheetDestination.new $test_results_dir + \"/loaded(#{@doc_count})_compare-documents(#{@compare_count}).ods\"\n\n @documents.length.times { |i|\n @documents.length.times { |j|\n puts \"comapre #{i} with #{j}\" if j % 10 == 0\n\n results[i][j] = @comparer.compare @documents[i], @documents[j]\n\n @dest.write results[i][j], i, j\n\n break if j + 1 >= @compare_count\n }\n\n break if i + 1 >= @compare_count\n }\n\n @dest.save\n dest = SheetDestination.new $test_results_dir + '/tdm.ods'\n dest.write_tdm @documents\n\n end",
"def column_headings\n {\n :line_count => \"Lines\",\n :loc_count => \"LOC\",\n :file_count => \"Classes\",\n :method_count => \"Methods\",\n :average_methods => \"M/C\",\n :method_length => \"LOC/M\",\n :class_length => \"LOC/C\"\n }\n end",
"def check_taxon_headers\n headers = @csvfile.headers()\n if headers.nil?\n @validation_results[:issues] << {:issue_description => 'Unable to read headers from CSV'}\n return\n end\n # Require at least one taxon header\n found_taxon_headers = (@config.taxonomy_columns.values) & headers\n if found_taxon_headers.empty?\n # No taxon headers found\n @validation_results[:issues] << {\n :issue_description => 'Missing taxon headers',\n :suggested_solution => \"Make sure CSV file has headers for taxa '#{@config.taxonomy_columns.values.join(',')}'.\"\n }\n else\n # Found at least one taxon header in the CSV file that is described by the template\n # Need to reverse the hash so that we can look up an internal group name (e.g. 'htg')\n # based on the value that appears in the CSV file (e.g. 'Higher Taxonomic Group')\n # Also, only store mappings for values that were found in the CSV, since our template\n # may reference extra fields\n\n @taxon_header_map = @config.taxonomy_columns.reject{|k,v| !found_taxon_headers.include? v }.invert\n @validation_results[:info] << {:info => 'Taxon headers are valid'}\n end\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.5240619",
"0.5217368",
"0.520975",
"0.52019626",
"0.51702154",
"0.5167721",
"0.5157594",
"0.51545405",
"0.51322865",
"0.512744",
"0.51264",
"0.51063323",
"0.5096239",
"0.50836056",
"0.5082097",
"0.5079105",
"0.5078018",
"0.50767136",
"0.50737005",
"0.50729495",
"0.50617474",
"0.5050905",
"0.5043746",
"0.50349295",
"0.5034004",
"0.50238824",
"0.5021842",
"0.4999918",
"0.4985112",
"0.49747095",
"0.49735403",
"0.49682903",
"0.49590966",
"0.4945896",
"0.4942631",
"0.4941966",
"0.49247956",
"0.4923923",
"0.49207562",
"0.49181852",
"0.49178508",
"0.4909176",
"0.49017236",
"0.48919663",
"0.48895574",
"0.4883133",
"0.48586366",
"0.48578167",
"0.48541343",
"0.48541343",
"0.48518044",
"0.4843996",
"0.48418412",
"0.4841611",
"0.48392883",
"0.4833666",
"0.48236603",
"0.48140645",
"0.4813311",
"0.4811604",
"0.48091516",
"0.4808188",
"0.4808188",
"0.48056993",
"0.48056254",
"0.47991496",
"0.47984082",
"0.4797079",
"0.47954813",
"0.47954446"
] | 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",
"def schedule_timeout (workitem, timeout_attname=:timeout)\n\n determine_timeout(workitem, timeout_attname)\n to_reschedule(get_scheduler)\n end",
"def set_timeout timeout\r\n command 'setTimeout', timeout\r\n end",
"def set_timeout timeout\r\n command 'setTimeout', timeout\r\n end",
"def timeout seconds=nil\n if block_given?\n before = @telnet_options[:timeout]\n self.timeout = seconds\n begin\n yield\n ensure\n self.timeout = before\n end\n else\n if seconds\n warn \"Warning: Use EM::P::SimpleTelnet#timeout= to set the timeout.\"\n end\n @telnet_options[:timeout]\n end\n end",
"def timeout=(_arg0); end",
"def timeout_wrap(&block)\n ::Timeout.timeout(timeout, &block)\n rescue ::Timeout::Error\n failure(:RPC_FAILED, \"The server took longer than #{timeout} seconds to respond\")\n end",
"def do_schedule_timeout (timeout)\n\n return unless timeout\n return if timeout.strip == ''\n\n h.timeout_schedule_id = @context.storage.put_schedule(\n 'at',\n h.fei,\n timeout,\n 'action' => 'cancel',\n 'fei' => h.fei,\n 'flavour' => 'timeout')\n end",
"def psubscribe_with_timeout(timeout, *channels, &block); end",
"def setTimeout(seconds = 0, *args, id: nextTimerID__, &block)\n return unless block\n setTimeout__ id, Time.now.to_f + seconds, args, &block\n end",
"def timeout=(timeout)\n @timeout = timeout.to_f/1000 * 60\n end",
"def merge_timeout(seconds = T.unsafe(nil)); end",
"def timeout(args = {}, &block)\n return Knjappserver::Threadding_timeout.new({\n :kas => self,\n :block => block,\n :args => []\n }.merge(args)).start\n end",
"def create_timed_delete(timeout, port_entry)\n mtimer = EM.add_timer(timeout.to_i) do\n time_left = port_entry.lifetime_left\n if time_left > 0\n #puts \"object has #{time_left} seconds left, #{Time.now}\"\n create_timed_delete(time_left, port_entry)\n else\n #puts \"timed delete writer #{Time.now}\"\n @portentries.delete(@portentries.key(port_entry))\n end\n end\n port_entry.timer = mtimer\n end",
"def create_timeout_timer_whilst_in_state(timer_id, timeout_in)\n raise ArgumentError, 'Block required' unless block_given?\n\n timers[timer_id] << EventMachine::Timer.new(timeout_in) do\n yield\n end\n connection.unsafe_once_state_changed { clear_timers timer_id }\n end",
"def timeout(seconds, options = {}, &block)\n timeout = timeout_start(seconds, options)\n parse(&block)\n timeout_stop(timeout)\n end",
"def timeout=(value)\n @timeout = value\n end",
"def initialize(timeout, options)\n @timeout = timeout\n @options = options\n end",
"def psubscribe_with_timeout(timeout, *channels, &block)\n _subscription(:psubscribe_with_timeout, timeout, channels, block)\n end",
"def timeout( seconds=nil )\n\t\tif seconds\n\t\t\treturn self.clone( :timeout => seconds )\n\t\telse\n\t\t\treturn @options[:timeout]\n\t\tend\n\tend",
"def subscribe_with_timeout(duration, size = 1, &block)\n Timeout::timeout(duration) do\n subscribe(nil, size, &block)\n join\n end\n rescue Timeout::Error\n quit\n end",
"def timer_timed_out\n self.log(\"Globaler Timer ist abgelaufen\")\n JavaScript::Runtime.call_slot(Global.timer_path, Global.timer_slot)\n end",
"def triggerTimeout _args\n \"triggerTimeout _args;\" \n end",
"def initialize interval, timeout\n @interval = interval\n @cancelled = false\n\n @timeout = EM.add_periodic_timer timeout, method(:timeout_fired)\n\n schedule\n end",
"def add_oneshot delay, timer_proc\n return nil unless timer_proc\n\n timer = Timer.new :timers => self, :delay => delay, :periodical => false, :timer_proc => timer_proc\n add timer\n timer\n end",
"def consider_timeout\n\n do_schedule_timeout(attribute(:timeout))\n end",
"def with_max_timeout(max_timeout)\n @max_timeout = max_timeout\n self\n end",
"def initialize(timeout = DEFAULT_TIMEOUT)\n timeout = timeout.to_int if timeout.respond_to?(:to_int)\n \n raise ArgumentError.new(\"Timeout must be > 0\") unless timeout > 0\n \n @timeout = timeout\n \n # we can use this for look-ups in O(1), instead of only find-min in O(1)\n @store = {}\n end",
"def untilTimeout()\n return Timer.timeRemaining(@name)\n end",
"def timer(callback = nil, &blk)\n Timer.new(@loop, callback || blk)\n end",
"def timeout= seconds\n @telnet_options[:timeout] = seconds\n set_comm_inactivity_timeout( seconds )\n end",
"def on_timer_timeout\n #puts \"#on_timer_minute #{@timer_minute} #{@timer_minute_limit}\"\n @timer_minute += 1\n if @timer_minute > @timer_minute_limit\n change_wallpaper\n\n # Restart timer\n reset_timer_minute\n end\n end",
"def onTimeout(interval, &block)\n \n raise ArgumentError unless interval.kind_of? Numeric\n \n ref = {:interval => interval.to_i, :block => block}\n \n with_mutex do \n if @queue.empty?\n @queue << ref\n else \n @queue.each.with_index do |v, i|\n if v[:interval] >= interval\n v[:interval] -= interval\n @queue.insert(i, ref) \n break\n else\n ref[:interval] -= v[:interval] \n if @queue.last == v\n @queue << ref\n break\n end\n end\n end\n end \n @update.push ref \n end\n \n ref\n end",
"def default_timeout_class=(_arg0); end",
"def timeout_increment\n ->(_try_count) { base_timeout }\n end",
"def worker_timeout(timeout); end",
"def timeout_start(seconds, options = {})\n options, timeout_options = Kernel.filter_options options, emit: nil\n if event = options[:emit]\n _, model_event = resolve_event(event)\n end\n model.timeout_start(seconds, timeout_options.merge(emit: model_event))\n end",
"def onTimedOut(args)\n args = Hash.symbolicate(args)\n if args[:time] && args[:slot] && args[:path]\n\n if Global.timer\n Global.timer.invalidate\n Global.timer = nil\n Global.timer_path = nil\n Global.timer_slot = nil\n end\n\n Global.timer_slot = args[:slot]\n Global.timer_path = args[:path]\n time = args[:time].to_i / 1000\n\n self.log(\"Globaler Timer wurde mit #{time} Sekunden gestartet\")\n\n Dispatch::Queue.main.async do\n Global.timer = NSTimer.scheduledTimerWithTimeInterval(time, target:self, selector:'timer_timed_out', userInfo:nil, repeats: false)\n end\n end\n end",
"def initialize( timeout: Arborist::Monitor::Webservice.default_timeout )\n\t\t\tself.timeout = timeout\n\t\tend",
"def start_timer\n Thread.new do\n loop {\n sleep @session_ttl\n reap_expired_sessions\n } \n end \n end",
"def lock_timeout(duration:)\n add option: \"-lock-timeout=#{duration}\"\n end",
"def timeout(*args, &block)\n Timeout::timeout(*args, &block)\n rescue Timeout::Error\n :timeout\n end",
"def max_timeout=(timeout)\n self.device.max_timeout = timeout\n end",
"def verify!(timeout)\n now = Time.now.to_i\n if (now - @last_verification) > timeout\n reconnect! unless active?\n @last_verification = now\n end\n end",
"def script_timeout=(seconds); end",
"def timeout_seconds\n return 1200\n end",
"def call(timeout)\n @time_out_at = read_clock + timeout\n\n yield\n end",
"def on_timeout\n trigger\n reset\n end",
"def timeout!; end",
"def timeout(value)\n fresh.tap do |criteria|\n criteria.timeout_value = value\n end\n end",
"def timeout_at; end",
"def test_timeout\n session=enter_the_room(\"test_timeout\")[\"session\"]\n response=get_event(session, {:check_response => false})\n assert last_response.ok?\n assert response[\"result\"] == 'timeout'\n end",
"def connect_timeout=(_arg0); end",
"def request_timeout(type, options); end",
"def with_timeout(duration, exception = TimeoutError, message = \"execution expired\", &block)\n\t\t\tFiber.scheduler.with_timeout(duration, exception, message, &block)\n\t\tend",
"def timeout_raw=(timeout)\n @serial_timer.timeout = timeout\n end",
"def with_timeout( timeout, &block )\n expire = Time.now + timeout.to_f\n sleepy = @sleep_in_ms / 1000.to_f()\n # this looks inelegant compared to while Time.now < expire, but does not oversleep\n loop do\n return true if block.call\n log :debug, \"Timeout for #{@key}\" and return false if Time.now + sleepy > expire\n sleep(sleepy)\n # might like a different strategy, but general goal is not use 100% cpu while contending for a lock.\n end\n end",
"def register_timer( name )\n Timer.new( @metrics.timer( name ) )\n end",
"def add_countdown(name, seconds, notify_frequency = nil)\n @timers[name] = Timer.new(name, Timer::COUNTDOWN, seconds, notify_frequency) {|timer| @game_object.notify :timer_tick, timer }\n end",
"def on_timeout\n trigger\n @active = false\n end",
"def timeout=(timeout)\n @stop_time = timeout.nil? ? nil : current_time + timeout\n end",
"def set_Timeout(value)\n set_input(\"Timeout\", value)\n end",
"def set_Timeout(value)\n set_input(\"Timeout\", value)\n end",
"def set_Timeout(value)\n set_input(\"Timeout\", value)\n end",
"def set_Timeout(value)\n set_input(\"Timeout\", value)\n end",
"def set_Timeout(value)\n set_input(\"Timeout\", value)\n end",
"def set_Timeout(value)\n set_input(\"Timeout\", value)\n end",
"def add_oneshot_at exact_time, timer_proc\n return nil unless timer_proc\n\n timer = Timer.new :timers => self, :exact_time => exact_time, :periodical => false, :timer_proc => timer_proc\n add timer\n timer\n end",
"def timeout(arg = nil)\n set_or_return(\n :timeout,\n arg,\n kind_of: Integer\n )\n end",
"def create_exit_when_idle_timer\n timeout_in_seconds = option(:exit_when_idle).to_i * 60\n return unless timeout_in_seconds > 0\n begin\n kill_exit_when_idle_timer # make sure only 1 timer thread is running at a time\n @exit_when_idle_timer = Thread.new do\n sleep timeout_in_seconds\n stop_signal = (Signal.list.keys & ['QUIT', 'INT']).first\n Process.kill(stop_signal, Process.pid)\n end\n rescue ::Exception => ex\n @logger.error { \"Unable to schedule timer to exit when idle in #{timeout_in_seconds} seconds: #{ex.message}\\n #{ex.backtrace.join(\"\\n \")}\" }\n end\n end",
"def timeout=(new_timeout)\n if new_timeout && new_timeout.to_f < 0\n raise ArgumentError, \"Timeout must be a positive number\"\n end\n @timeout = new_timeout.to_f\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.5345537",
"0.5324366",
"0.5324366",
"0.53109515",
"0.52911174",
"0.52886176",
"0.5280888",
"0.5280737",
"0.52678",
"0.5254147",
"0.5231222",
"0.5217886",
"0.5207467",
"0.5195109",
"0.51907307",
"0.51873004",
"0.5164927",
"0.51639235",
"0.515252",
"0.5150342",
"0.51491815",
"0.5148793",
"0.51423633",
"0.51377153",
"0.51315665",
"0.51128787",
"0.5112729",
"0.5109271",
"0.51091015",
"0.5101222",
"0.5098216",
"0.5095076",
"0.509239",
"0.5092334",
"0.50922734",
"0.5091344",
"0.509023",
"0.50885457",
"0.5080936",
"0.5080835",
"0.50560766",
"0.50522316",
"0.50371826",
"0.5033265",
"0.5032982",
"0.4995584",
"0.49887833",
"0.49881774",
"0.49829656",
"0.49730125",
"0.49696848",
"0.4968881",
"0.49637207",
"0.49571574",
"0.49568865",
"0.4955625",
"0.49294573",
"0.4924735",
"0.49201238",
"0.4918223",
"0.49103856",
"0.4910196",
"0.4910196",
"0.4910196",
"0.4910196",
"0.4910196",
"0.49086598",
"0.4901535",
"0.48982245",
"0.48896337"
] | 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",
"def simple_graph(vertices, klass = MiniGraphdb::Node)\n nodes = Hash.new { |hsh, k| hsh[k] = klass.new(val: k) }\n\n vertices.each do |a_node, other_node|\n nodes[a_node].r_edge nodes[other_node]\n end\n\n def nodes.print_graph\n values.each do |node|\n edges = node.edges.byweight.map(&:val).join(\", \")\n puts \"#{node.val} => #{edges}\"\n end\n end\n\n nodes\n end",
"def to_h\n inject(Hash.new { |h,k| h[k]=[] }) do |h, edge|\n h[edge.out_vertex] << edge.in_vertex\n h\n end\n end",
"def hash\n size.hash ^ rank.hash\n end",
"def test_06\n @dg = DiGraph.new([5,9],[0,3],[3,8],[8,9],[9,0])\n @paths = Hash.new\n @paths[5] = [9]\n @paths[0] = [3]\n @paths[3] = [8]\n @paths[8] = [9]\n @paths[9] = [0]\n @nodes = @paths.keys\n received_dg = @dg.strongly_connected_component_including_node(0);\n filled_dg = DiGraph.new(*fill(0));\n if (not filled_dg.equal?(received_dg))\n puts \"test_06 failed...\"\n puts \"DiGraph => #{@dg.to_s}\"\n puts \"node => 0\"\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 hash # Hack for Ruby 1.8.6\n @node.id.hash ^ self.class.hash\n end",
"def cell_array_visited\n cell_array = []\n @cells_visited.map { |ms_cell| cell_array << ms_cell.cell }\n cell_array\n end",
"def test_05\n @dg = DiGraph.new([0,7],[1,9],[1,4],[7,4],[7,0],[7,9],[3,7],[9,4],[9,7],[9,9],[4,1],[4,4],[4,7])\n @paths = Hash.new\n @paths[0] = [7]\n @paths[1] = [9,4]\n @paths[7] = [4,0,9]\n @paths[3] = [7]\n @paths[9] = [4,7,9]\n @paths[4] = [1,4,7]\n @nodes = @paths.keys\n received_dg = @dg.strongly_connected_component_including_node(0);\n filled_dg = DiGraph.new(*fill(0));\n if (not filled_dg.equal?(received_dg))\n puts \"test_05 failed...\"\n puts \"DiGraph => #{@dg.to_s}\"\n puts \"node => 0\"\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 adjacent_vertices 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 << @Vertices[@Hash[@Edges[i].points[1]]]\n\t\t\tend\n\t\t\tif @Edges[i].points[1] == v.label\n\t\t\t\ttemp_array << @Vertices[@Hash[@Edges[i].points[0]]]\n\t\t\tend\n\t\tend\n\n\t\treturn temp_array\n\n\tend",
"def edges\n edges = 0\n @graph.each_value do |v|\n edges += v.size\n end\n edges\n end",
"def connected_component\n sa = []\n queue = []\n visited = []\n\n queue.push self.id\n visited.push self.id\n\n while not queue.empty?\n answer_id = queue.shift\n\n answer = Answer.find(answer_id)\n sa << answer_id\n\n for similar_answer in answer.similar_answers do\n unless visited.include?(similar_answer)\n queue.push similar_answer\n visited.push similar_answer\n end\n\n end\n end\n sa\n end",
"def dfs(graph)\n visited = Hash.new\n\n graph.each do |vertex, _|\n visited[vertex] = Hash.new\n visited[vertex][:state] = \"not visited\"\n end\n\n # This is to enable passing by reference in the dfs_visit method, otherwise\n # simply having a variable for integer will get passed by value and does not\n # behave/increment as expected.\n order = Hash.new\n order[:time] = 0\n\n graph.each do |vertex, _|\n dfs_visit(graph, vertex, visited, order) unless visited[vertex][:state] == \"done\"\n end\n\n visited\nend",
"def random_graph(node_count, edge_ratio)\n @nodes = Hash.new()\n @edges = Hash.new()\n @adjacency = Hash.new(0)\n (1..node_count).each {|i| @nodes[i] = Graph::Node.new(i, \"Node \"+i.to_s, \"myurl\")} #make random nodes\n for i in (1..node_count)\n for j in (1..node_count) #edges in both directions, chance of 1 each way\n if(i!=j and rand() < edge_ratio) #make random edges\n rel_type = (rand()*10).ceil #get a random set of attributes (rel_type) for that edge\n @edges[j*node_count+i] = Graph::Edge.new(j*node_count+i, @nodes[i], @nodes[j], rel_type)\n @adjacency[[i,j]] += 1 #count the edge\n end\n end\n end\n end",
"def problem_107\n if false\n net = [ \"-,16,12,21,-,-,-\", \"16,-,-,17,20,-,-\", \"12,-,-,28,-,31,-\",\n \"21,17,28,-,18,19,23\", \"-,20,-,18,-,-,11\", \"-,-,31,19,-,-,27\",\n \"-,-,-,23,11,27,-\" ]\n net.map! {|line| line.split(/,/).map {|i| i == '-' ? nil : i.to_i}}\n else\n net = []\n open(\"network.txt\").each do |line|\n net << line.chomp.split(/,/).map {|i| i == '-' ? nil : i.to_i}\n end\n end\n\n # Reformat into an array of nodes, with the their connections\n nodes = Hash.new {|h,k| h[k] = Hash.new }\n net.each_with_index do |row,i| # Each nodes is connected to...\n row.each_index do |col| # For each possible connection....\n # Add the node we are connected to and the cost\n nodes[i][col] = row[col] if row[col]\n end\n end\n\n initial = nodes.reduce(0) do |a,row|\n row[1].reduce(a) {|aa,p| aa + p[1] }\n end / 2\n # add to the 'borg' that is node0\n node0,node0_links = nodes.shift\n ans = []\n node0_contains = Hash.new\n node0_contains[node0] = true\n\n # What we do select the lowest link, the 'merge' it into node0, repeat\n while nodes.length > 0\n n,v = node0_links.min {|a,b| a[1] <=> b[1]}\n ans << [n,v] # Save the link for the answer\n node0_contains[n] = true # add to the 'borg' that is node0\n nodes[n].each_pair do |k,a| # Now merge in new poin, update vertexs\n next if node0_contains[k]\n node0_links[k] = [a, node0_links[k] || 1_000_000].min\n end\n nodes.delete(n) # Remove from free nodes\n node0_links.delete(n) # Remove from vertexes to resolve\n end\n\n now = ans.reduce(0) {|a,v| a + v[1]}\n puts \"initial = #{initial}\"\n puts \"now = #{now}\"\n initial - now\nend",
"def all_edges\n\t\t@e.uniq\n\tend",
"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 plexus_comparability_explore(edge, k, classification, space='')\n ret = plexus_comparability_explore_inner(edge, k, classification, :forward, space)\n plexus_comparability_explore_inner(edge.reverse, k, classification, :backward, space) && ret\n end",
"def possible_edges\n @possible_edges ||= @node_list.to_a.combination(2).to_a\n end",
"def graph_to_genome(colored_edges)\n <<-DOC\n GraphToGenome(GenomeGraph)\n P ← an empty set of chromosomes\n for each cycle Nodes in GenomeGraph\n Chromosome ← CycleToChromosome(Nodes)\n add Chromosome to P\n return P\n\n\n Sample Input:\n (2, 4), (3, 6), (5, 1), (7, 9), (10, 12), (11, 8)\n Sample Output:\n (+1 -2 -3)(-4 +5 -6) \n DOC\n\n # We have to detect cycle first and then form chromosme\n # The cycle ends when a second digit in the edge is less than the first digit\n\n p = []\n list = []\n lowest = -1\n colored_edges.each do |edge|\n if lowest == -1\n list = edge\n lowest = edge.min \n elsif (edge.min < lowest)\n list << edge[0]\n list.unshift(edge[1])\n p << list\n list = []\n lowest = -1\n else\n list << edge[0]\n list << edge[1]\n end\n end\n # p << list unless list.empty?\n if list.length >= 1\n last_elem = list.pop \n list.unshift(last_elem)\n p << list\n end\n\n genome = []\n p.each do |chrome|\n # puts chrome.join(\" \")\n # puts \"\"\n # puts cycle_to_chromosome(chrome).join(\" \") \n genome << cycle_to_chromosome(chrome)\n end\n return genome\n end",
"def construct_adj_list(edges)\n map = Hash.new\n edges.each do |edge|\n from = edge[0]\n to = edge[1]\n if map[to].nil?\n map[to] = []\n end\n if map[from].nil?\n map[from] = []\n end\n map[from].push(to)\n end\n map\nend",
"def nodes\n @graph.keys.length\n end",
"def hash\n @matrix\n end",
"def all_edges\n @edges.values.inject { |arr1, arr2| arr1 + arr2 } || []\n end",
"def explore(start)\n visited = Hash.new(false)\n visited[start] = true \n start.out_edges.each do |edge|\n explore(edge.dest) if !visited[edge.dest]\n end\n return visited\n end",
"def in_degree\n @in_edges.length\n end",
"def install_order(arr)\n vertices = {}\n max = 0 \n arr.each do |tuple|\n vertices[tuple[0]] = Vertex.new(tuple[0]) unless verticles[tuple[0]]\n vertices[tuple[1]] = Vertex.new(tuple[1]) unless verticles[tuple[1]]\n # create an edge for each pair \n\n Edge.new(vertices[tuple[1]], vertices[tuple[0]])\n\n max = tuple.max if tuple.max > max \n end \n\n independent = []\n (1..max).each do |i| \n independent << i unless vertices[i]\n end \n\n independent + topological_sort(vertices.values).map { |v| v.value }\nend",
"def numbered_pairs_to_adjacency_matrix(pairs, directed=false)\n nodes = entities(pairs).sort\n n = nodes[-1] + 1\n matrix = Array.new(n) { Array.new(n) { 0 } }\n pairs.each do |a, b| \n matrix[a][b] = 1\n matrix[b][a] = 1 if !directed\n end\n return matrix\nend",
"def numbered_pairs_to_adjacency_matrix(pairs, directed=false)\n nodes = entities(pairs).sort\n n = nodes[-1] + 1\n matrix = Array.new(n) { Array.new(n) { 0 } }\n pairs.each do |a, b| \n matrix[a][b] = 1\n matrix[b][a] = 1 if !directed\n end\n return matrix\nend",
"def colored_edges(p)\n <<-DOC\n ColoredEdges(P)\n Edges ← an empty set\n for each chromosome Chromosome in P\n Nodes ← ChromosomeToCycle(Chromosome)\n for j ← 1 to |Chromosome|\n add the edge (Nodes2j, Nodes2j +1) to Edges\n return Edges \n The following algorithm constructs ColoredEdges(P) for a genome P. \n In this pseudocode, we will assume that an n-element array (a1, . . . , an) has an invisible (n + 1)-th element \n that is equal to its first element, i.e., an+1 = a1.\n DOC\n\n # puts p\n edges = []\n p.each do |chrome|\n # puts chrome.join(\" \")\n nodes = chromosome_to_cyle(chrome)\n # In this pseudocode, we will assume that an n-element array (a1, . . . , an) has an invisible (n + 1)-th element \n # that is equal to its first element, i.e., an+1 = a1. \n # So lets add the first element at the end\n nodes.push(nodes.first)\n # puts nodes.join(\" \")\n (1..(chrome.length)).each do |j|\n val_2j = 2*j - 1 \n val_2j_1 = (2*j + 1) -1 \n edges << [nodes[val_2j], nodes[val_2j_1]]\n end\n # puts edges.each {|i| puts i.join(\",\")}\n end\n return edges\n end",
"def depth_first_search\n visited = {}\n timestamp = {}\n tree_edges = {}\n back_edges = {}\n cross_edges = {}\n forward_edges = {}\n count = 0\n\n # begin workaround removing depencency to order of Hash#each\n if @index.empty? then\n preference_of_nodes = nil\n else\n preference_of_nodes = {}.merge(@index)\n i = preference_of_nodes.values.max\n @graph.each_key do |node0|\n preference_of_nodes[node0] ||= (i += 1)\n end\n end\n # end workaround removing depencency to order of Hash#each\n\n dfs_visit = Proc.new { |from|\n visited[from] = true\n timestamp[from] = [count += 1]\n ary = @graph[from].keys\n # begin workaround removing depencency to order of Hash#each\n if preference_of_nodes then\n ary = ary.sort_by { |node0| preference_of_nodes[node0] }\n end\n # end workaround removing depencency to order of Hash#each\n ary.each do |to|\n if visited[to]\n if timestamp[to].size > 1\n if timestamp[from].first < timestamp[to].first\n \t# forward edge (black)\n \tp \"#{from} -> #{to} : forward edge\" if $DEBUG\n \tforward_edges[from] = to\n else\n \t# cross edge (black)\n \tp \"#{from} -> #{to} : cross edge\" if $DEBUG\n \tcross_edges[from] = to\n end\n else\n # back edge (gray)\n p \"#{from} -> #{to} : back edge\" if $DEBUG\n back_edges[from] = to\n end\n else\n # tree edge (white)\n p \"#{from} -> #{to} : tree edge\" if $DEBUG\n tree_edges[to] = from\n dfs_visit.call(to)\n end\n end\n timestamp[from].push(count += 1)\n }\n\n ary = @graph.keys\n # begin workaround removing depencency to order of Hash#each\n if preference_of_nodes then\n ary = ary.sort_by { |node0| preference_of_nodes[node0] }\n end\n # end workaround removing depencency to order of Hash#each\n ary.each do |node|\n unless visited[node]\n dfs_visit.call(node)\n end\n end\n return timestamp, tree_edges, back_edges, cross_edges, forward_edges\n end",
"def predicates\n @graphs.inject([]) {|memo, g| memo += g.predicates}\n end",
"def graph_states\n self.graph.states\n end",
"def get_adjacency_matrix\n max_index = find_max_index\n adjacency_matrix = [nil] * max_index\n adjacency_matrix.map! { [0] * max_index }\n @edges.each do |edg|\n from_index = edg.node_from.value\n to_index = edg.node_to.value\n adjacency_matrix[from_index][to_index] = edg.value\n end\n adjacency_matrix\n end",
"def has_edges\n return false unless @vertices.length > 0\n\n @vertices.each do |vertex|\n vertex.neighbours.each do |neighbour|\n if (neighbour == true)\n return true\n end\n end\n end\n\n return false\n end",
"def find_order_bfs\n queue = []\n @num_courses.times { |v| queue.push(v) if @in_degrees[v].zero? } # 入度为0的全都放入\n\n visited = []\n until queue.empty?\n node_key = queue.shift\n\n visited.unshift(node_key) # 注意顺序\n\n @nodes[node_key]&.each do |neighbor|\n @in_degrees[neighbor] -= 1\n queue.push(neighbor) if @in_degrees[neighbor].zero?\n end\n end\n\n visited.size == @num_courses ? visited : []\n end",
"def randomVertices(g)\n\t# Select a vertex (1) from the graph\n\t# Select a random neighbor from vertex (1) to contract with\n\tv1 = g.keys.sample\n\tv2 = g[v1].sample\n\n\t[v1, v2]\nend",
"def generate_graph_hash(n)\n edges_weights = {}\n # go through all vertices and generate random edges/ weights\n 0.upto(n - 1) do |u|\n # create an edge from this node to the next\n # generate weight for the new edge\n weight = rand(n)\n # create an edge to next vertex...easy way to ensure connectivity\n v = u + 1\n edge = [u, v]\n edges_weights[edge] = weight\n # create an alternative edge...randomly\n if (rand(n) % 2) == 0 && u < (n - 1)\n alt_weight = Random.new.rand(weight+1..n)\n alt_v = Random.new.rand(v+1..n)\n alt_edge = [u, alt_v]\n edges_weights[alt_edge] = alt_weight\n end\n end\n edges_weights\n end",
"def edges\r\n @types[ Sketchup::Edge ].keys\r\n end",
"def hash\n ([self.class] + self.class.comparison_attrs.map{|x| send(x)}).hash\n end",
"def neighbors(vertex)\n @graph[vertex] || []\n end",
"def strongly_connected_components\n\t\t@explored_nodes = Array.new(size, false)\n\t\t@finishing_time_arr = Array.new(size)\n\t\t@scc = Array.new\n\t\t@dfs_queue = Array.new\n\t\t@finishing_time_queue = Array.new\n\t\t@finishing_time = 0\n\t\tcalculate_finishing_time\n\t\t@leaders = scc_call_order\n\t\tcalculate_scc\n\t\tputs \"#{@scc.map(&:count).sort.reverse.take(5)}\"\n\tend",
"def find_degrees_edges\n raise RuntimeError, \"Call filter_graph_by_users before find_degrees\" unless File.exist? @graph_filename\n \n # Open graph file and read in undirected edges\n puts \"Reading in edges from graph & calculating in/outdegree...\"\n edges = {}\n degrees = {}\n File.open(@c.graph,\"r\").each do |l|\n parts = l.split(' ',3)\n id1,id2 = parts[0].to_i, parts[1].to_i\n degrees[id2] ||= [0,0]\n degrees[id1] ||= [0,0]\n degrees[id2][0] += 1\n degrees[id1][1] += 1\n #id1,id2 = id2,id1 if id2 < id1\n edges[id1] ||= Set.new\n edges[id1].add id2\n end\n \n # Write in-degree count to file\n puts \"Writing in/out-degree to file...\"\n File.open(@c.degrees+\"~\", \"w\") do |f|\n degrees.each do |k,v|\n f.puts \"#{k} #{v[0]} #{v[1]}\"\n end\n end\n File.rename(@c.degrees+\"~\", @c.degrees)\n \n # Count in-degrees & loop through edges and count and write to file\n puts \"Writing directed edges to file...\"\n File.open(@people_edge_filename+\"~\", \"w\") do |f|\n edges.each do |k,v|\n v.each do |k2|\n f.puts \"#{k} #{k2}\"\n # degrees[k] ||= 0\n # degrees[k2] ||= 0\n # degrees[k] += 1\n # degrees[k2] += 1\n end\n end\n end\n File.rename(@people_edge_filename+\"~\", @people_edge_filename)\n \n end",
"def traverse_graph\n for i in 0..@number_of_vertices-1 do\n if @adjacent_list[i].length > 0 && @adjacent_list[i].length > @indegree[i]\n break\n end\n end\n\n return true if (i == @number_of_vertices)\n\n dfs_traversal(i);\n\n for i in 0..@number_of_vertices-1\n if (@visited[i] == false && @adjacent_list[i].length > 0)\n return false\n end\n end\n end",
"def test_has_edges\n graph = Graph.new\n vertex_a = Vertex.new('a')\n vertex_b = Vertex.new('b')\n vertex_c = Vertex.new('c')\n graph.add_vertex(vertex_a).add_vertex(vertex_b).add_vertex(vertex_c)\n graph.add_edge('b','c')\n\n assert(graph.has_edges() == true)\n end",
"def to_hash\n build\n\n return @probabilities\n end",
"def get_values_for_verification\n \t@intermediate_nodes = self.get_intermediate_nodes\n @array = []\n\n @intermediate_nodes.each do |node|\n @array << node.sha.to_s\n if node.is_right_child\n @array << \"rchild\"\n else\n @array << \"lchild\"\n end\n end\n\n \t@array << Node.get_root_node.sha.to_s\n @array << \"root\"\n\n \treturn @array\n #return @intermediate_nodes\n end",
"def build_sketch_graph\n\t@temp_hop_record = Hash.new\n\t@processed_list = Hash.new\n\t$node_list.each do |n|\n\t\t#Nodes in sketched graph: queries, user_inputs\n\t\t#if n.getInstr.getFromUserInput or (n.isQuery? and n.isWriteQuery?) or (n.getInstr.instance_of?AttrAssign_instr and n.getInstr.getFuncname.index('!') == nil)\n\t\tif n.isQuery? #or n.getInstr.getFromUserInputor isTableAttrAssign(n) \n\t\t\tn.Tnode = TreeNode.new(n)\n\t\t\t$sketch_node_list.push(n.Tnode)\t\n\t\t\t@temp_hop_record[n] = Array.new\n\t\t\t@processed_list[n] = Array.new\n\t\t\t@temp_hop_record[n].push(n)\n\t\tend \n\tend\n\tfor i in 0...$node_list.length\n\t\tadded_edge = false\n\t\tno_changes = true\n\t\t$node_list.each do |n|\n\t\t\tif n.Tnode != nil\n\t\t\t\t@temp_hop_record[n].push(nil)\n\t\t\t\ttemp_node = @temp_hop_record[n].shift\n\t\t\t\tstep = 0\n\t\t\t\twhile temp_node != nil and step < 10000 do\n\t\t\t\t\tstep += 1\n\t\t\t\t\tno_changes = false\n\t\t\t\t\ttemp_node.getDataflowEdges.each do |e|\n\t\t\t\t\t\tif e.getToNode.Tnode != nil and e.getToNode != n\n\t\t\t\t\t\t\tif n.Tnode.hasChildren(e.getToNode.Tnode) == false and (n.getIndex < e.getToNode.getIndex)\n\t\t\t\t\t\t\t\tn.Tnode.addChildren(e.getToNode.Tnode, i)\n\t\t\t\t\t\t\t\t#puts \"\\tAdd edge: #{n.getIndex}:#{n.getInstr.toString} -> #{e.getToNode.getIndex}:#{e.getToNode.getInstr.toString}\"\n\t\t\t\t\t\t\t\tadded_edge = true\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif e.getToNode != n \n\t\t\t\t\t\t\t\tif @processed_list[n].include?e\n\t\t\t\t\t\t\t\telsif e.getToNode.getIndex < e.getFromNode.getIndex #returnv\n\t\t\t\t\t\t\t\t\te.getToNode.getDataflowEdges.each do |e1|\n\t\t\t\t\t\t\t\t\t\tif e1.getToNode.getIndex > temp_node.getIndex\n\t\t\t\t\t\t\t\t\t\t\t@temp_hop_record[n].push(e1.getToNode)\n\t\t\t\t\t\t\t\t\t\t\t@processed_list[n].push(e1)\n\t\t\t\t\t\t\t\t\t\tend \n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t@temp_hop_record[n].push(e.getToNode)\n\t\t\t\t\t\t\t\t\t@processed_list[n].push(e)\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\ttemp_node = @temp_hop_record[n].shift\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tif added_edge\n\t\t\t#puts \"iteration #{i} ||\"\n\t\tend\n\t\tif no_changes\n\t\t\tbreak\n\t\tend\n\tend\n=begin\n\tgraph_write($graph_file, \"digraph sketch {\\n\")\n\t$node_list.each do |n|\n\t\tif n.Tnode != nil\n\t\t\tif n.isQuery?\n\t\t\t\tcolor = \"blue\"\n\t\t\telsif n.getInstr.instance_of?AttrAssign_instr\n\t\t\t\tcolor = \"darkorange\"\n\t\t\telse\n\t\t\t\tcolor = \"crimson\"\n\t\t\tend\n\t\t\tgraph_write($graph_file, \"\\tn#{n.getIndex} [label=<<i>#{n.getIndex}__#{n.getInstr.toString2}</i>> color=#{color}]; \\n\")\n\t\t\tn.Tnode.children.each do |c|\n\t\t\t\tgraph_write($graph_file, \"\\tn#{n.getIndex} -> n#{c.node.node.getIndex} [label=\\\"#{c.dist}\\\"]\\n\")\n\t\t\tend\n\t\tend\n\tend\n\tgraph_write($graph_file, \"}\")\n=end\nend",
"def edges\n i = 0\n @hypernyms.each do |key, values|\n i += values.length\n end\n i\n end",
"def edges\n edges = []\n vertices.each do |x|\n if x.neighbors\n neighbors = x.neighbors\n neighbors.each do |id|\n n = find_vert(id)\n edges << [x.id, n.id]\n end\n end\n end\n edges\n end",
"def prim(array, vertex_num)\n mstSet = []\n vertex_key = []\n vertex_last = vertex_num\n min_cost = 9999999999999\n (0..vertex_last - 1).each do |i|\n vertex_key[i] = min_cost\n mstSet[i] = false\n end\n vertex_key[0] = 0\n (0..vertex_last - 1).each do |x|\n u = find_min_edge(mstSet, vertex_key)\n mstSet[u] = true\n update_key(array, u, vertex_key, mstSet)\n end\n sum = 0\n (0..vertex_key.length-1).each do |i|\n sum += vertex_key[i]\n end\n return sum\nend",
"def get_all_edges(course)\n edges = []\n edges.push({node.id_to_s => course.id_to_s})\n queue = Queue.new\n queue << node\n\n until queue.empty?\n n = queue.pop\n n.nodes.each do |sub_node|\n node_id = n.id_to_s\n subnode_id = sub_node.id_to_s\n edges.push({subnode_id => node_id})\n\n if sub_node.operation != NodeOperation::NODE\n queue << sub_node\n end\n end\n end\n edges\n end",
"def compare_edges_diff_types(rev, subm, num_rev_edg, num_sub_edg)\n # puts(\"*****Inside compareEdgesDiffTypes :: numRevEdg :: #{num_rev_edg} numSubEdg:: #{num_sub_edg}\") \n best_SV_VS_match = Array.new(num_rev_edg){Array.new}\n cum_edge_match = 0.0\n count = 0\n max = 0.0\n flag = 0\n wnet = WordnetBasedSimilarity.new \n for i in (0..num_rev_edg - 1)\n if(!rev[i].nil? and rev[i].in_vertex.node_id != -1 and rev[i].out_vertex.node_id != -1)\n #skipping edges with frequent words for vertices\n if(wnet.is_frequent_word(rev[i].in_vertex.name) and wnet.is_frequent_word(rev[i].out_vertex.name))\n next\n end\n #identifying best match for edges\n for j in (0..num_sub_edg - 1) \n if(!subm[j].nil? and subm[j].in_vertex.node_id != -1 and subm[j].out_vertex.node_id != -1)\n #checking if the subm token is a frequent word\n if(wnet.is_frequent_word(subm[j].in_vertex.name) and wnet.is_frequent_word(subm[j].out_vertex.name))\n next\n end \n #for S-V with S-V or V-O with V-O\n if(rev[i].in_vertex.type == subm[j].in_vertex.type and rev[i].out_vertex.type == subm[j].out_vertex.type)\n #taking each match separately because one or more of the terms may be a frequent word, for which no @vertex_match exists!\n sum = 0.0\n cou = 0\n if(!@vertex_match[rev[i].in_vertex.node_id][subm[j].out_vertex.node_id].nil?)\n sum = sum + @vertex_match[rev[i].in_vertex.node_id][subm[j].out_vertex.node_id]\n cou +=1\n end\n if(!@vertex_match[rev[i].out_vertex.node_id][subm[j].in_vertex.node_id].nil?)\n sum = sum + @vertex_match[rev[i].out_vertex.node_id][subm[j].in_vertex.node_id]\n cou +=1\n end \n if(cou > 0)\n best_SV_VS_match[i][j] = sum.to_f/cou.to_f\n else\n best_SV_VS_match[i][j] = 0.0\n end\n #-- Vertex and SRL\n best_SV_VS_match[i][j] = best_SV_VS_match[i][j]/ compare_labels(rev[i], subm[j])\n flag = 1\n if(best_SV_VS_match[i][j] > max)\n max = best_SV_VS_match[i][j]\n end\n #for S-V with V-O or V-O with S-V\n elsif(rev[i].in_vertex.type == subm[j].out_vertex.type and rev[i].out_vertex.type == subm[j].in_vertex.type)\n #taking each match separately because one or more of the terms may be a frequent word, for which no @vertex_match exists!\n sum = 0.0\n cou = 0\n if(!@vertex_match[rev[i].in_vertex.node_id][subm[j].in_vertex.node_id].nil?)\n sum = sum + @vertex_match[rev[i].in_vertex.node_id][subm[j].in_vertex.node_id]\n cou +=1\n end\n if(!@vertex_match[rev[i].out_vertex.node_id][subm[j].out_vertex.node_id].nil?)\n sum = sum + @vertex_match[rev[i].out_vertex.node_id][subm[j].out_vertex.node_id]\n cou +=1\n end \n if(cou > 0)\n best_SV_VS_match[i][j] = sum.to_f/cou.to_f\n else\n best_SV_VS_match[i][j] =0.0\n end\n flag = 1\n if(best_SV_VS_match[i][j] > max)\n max = best_SV_VS_match[i][j]\n end\n end\n end #end of the if condition\n end #end of the for loop for submission edges\n \n if(flag != 0) #if the review edge had any submission edges with which it was matched, since not all S-V edges might have corresponding V-O edges to match with\n # puts(\"**** Best match for:: #{rev[i].in_vertex.name} - #{rev[i].out_vertex.name} -- #{max}\")\n cum_edge_match = cum_edge_match + max\n count+=1\n max = 0.0 #re-initialize\n flag = 0\n end\n end #end of if condition\n end #end of for loop for review edges\n \n avg_match = 0.0\n if(count > 0)\n avg_match = cum_edge_match.to_f/ count.to_f\n end\n return avg_match\nend",
"def visited_board\n Array.new(@size) { Array.new(@size, false) }\n end",
"def tight? graph, rank\n end",
"def build_weight_array(nodes)\n weight_array = []\n gcd = nodes.map {|n| n.weight }.inject(0) {|r,w| r.gcd(w) }\n nodes.each {|n|\n (n.weight / gcd).times {\n weight_array << n\n }\n }\n weight_array\n end",
"def adjEdges(u)\n\t\tl = Array.new\n\t\t@edgeSet.each do |e|\n\t\t\tif e.s == u\n\t\t\t\tl << e\n\t\t\tend\n\t\tend\n\t\tl\n\tend",
"def make_branch connected_nodes_number, avalable_nodes\n nodes = []\n\n num = rand(1..connected_nodes_number)\n\n num = 0 unless num\n\n num.times do\n node = gen_uniq_rand_hash(4, avalable_nodes)\n nodes << node\n\n # increiment the count of each avalable node so we can enforce a limit the\n # number of connections TO each node\n avalable_nodes[node] += 1\n end\n\n nodes\nend",
"def complile_relationships\n relationships = []\n @classifications.each do |classification|\n relationship = Relationship.new(@query, classification)\n relationships << relationship unless relationship.score.zero?\n end\n relationships.sort\n end",
"def in_degree(vertex)\n\tend",
"def listEdges(matrix)\n edges = {}\n hitList = {}\n\n matrix.each_with_index do |line, i|\n aI = @alphaHash[i]\n line.each_with_index do |node, j|\n dist = matrix[i][j]\n aJ = @alphaHash[j]\n if dist != -1\n edge = (i < j ? \"#{aI}#{aJ}\" : \"#{aJ}#{aI}\")\n edges[aI] = {} if edges[aI].nil?\n edges[aJ] = {} if edges[aJ].nil?\n edges[aI][aJ] = dist\n edges[aJ][aI] = dist\n hitList[edge] = dist\n end\n end\n end\n\n hitList = Hash[hitList.sort_by {|k,v| v*-1}]\n [edges,hitList]\nend",
"def number_of_connected(graph)\n visited = Hash.new(false)\n res = 0\n graph.vertices.keys.each do |v|\n unless visited[v]\n dfu(graph, v, visited)\n res += 1\n end\n end\n res\n end",
"def build_assignment_graph(layer)\n\t\th = @via_positions.length\n\t\tfail if (h == 0) || h.odd?\n\t\tfail if @start_node.pads.min < 0 || @start_node.pads.max >= @layer_count\n\t\tfail if @end_node.pads.min < 0 || @end_node.pads.max >= @layer_count\n\t\tvia_count = h / 2\n\t\tputs via_count\n\t\tlayers = 0..(@layer_count - 1) \n\t\tcolums = 0..(via_count * 2) # F O F O F for via_count == 2 \n\t\t#vp = @via_positions.dup # x,y pairs\n\t\t#vp.unshift(@start_node.y)\n\t\t#vp.unshift(@start_node.x)\n\t\tvp = [@start_node.x, @start_node.y] + @via_positions\n\t\tm = Array.new(@layer_count){Array.new(via_count * 2 + 1)}\n\t\tfor i in colums # from T back to S\n\t\t\tif i.even?\n\t\t\t\ty = vp.pop\n\t\t\t\tx = vp.pop\n\t\t\tend\n\t\t\tfor j in layers\n\t\t\t\tl = Array.new\n\t\t\t\tif i.even? # forward\n\t\t\t\t\tk = i + 1\n\t\t\t\t\twhile k > 0\n\t\t\t\t\t\tk -= 2\n\t\t\t\t\t\tif k == -1 # link forward node to T node\n\t\t\t\t\t\t\tl << @end_node if @end_node.pads.include?(j)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (h = m[j][k])\n\t\t\t\t\t\t\t\tl << h # link to up/down node \n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = F_node.new(x, y, j, l)\n\t\t\t\t\t\tl.each{|el|\n\t\t\t\t\t\t#unless @segment_list.index{|m| m.x1 == && m.y1 == el.y1 & m.x2 == el.x2 && m.y2 == el.y2}\n\t\t\t\t\t\t\t@segment_list << Segment.new(x, y, el.x, el.y)\n\t\t\t\t\t\t}\n\t\t\t\t\tend\n\t\t\t\telse #up/down\n\t\t\t\t\tfor k in layers do\n\t\t\t\t\t\tif (k != j) && (h = m[k][i - 1])\n\t\t\t\t\t\t\tl << h\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = V_node.new(x, y, j, l)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t#puts @segment_list.length\n\t\t@segment_list.uniq!{|el| [el.x1, el.y1, el.x2, el.y2]}\n\t\tputs @segment_list.length\n\t\t@all_intersecting_segments = Array.new\n\t\t@segment_list.each{|el|\n\t\t\t@all_intersecting_segments += el.intersecting_segments\n\t\t}\n\t\t@all_intersecting_segments.uniq!\n\n\t\tfor j in layers\n\t\t\tif (h = m[j][-1]) && @start_node.pads.include?(j)\n\t\t\t\t@start_node.next << h\n\t\t\tend\n\t\tend\n\tend",
"def hash\n\t\t[@a, @b, self.class::D].hash\n\tend",
"def vertex_edges(vertex_id)\n vertex_edges = []\n all_edges = edges\n all_edges.each { |e| vertex_edges << [vertex_id, e[1]] if e[0] == vertex_id }\n vertex_edges\n end",
"def node_to_array(node)\n # Is this too clever?\n # { \"01\" => \"bar\", \"00\" => \"foo\", \"02\" => \"baz\" } # node_to_hash\n # [ [\"01\", \"bar\"], [\"00\", \"foo\"], [\"02\", \"baz\"] ] # to_a\n # [ [\"00\", \"foo\"], [\"01\", \"bar\"], [\"02\", \"baz\"] ] # sort\n # [ \"foo\", \"bar\", \"baz\" ] # map\n node_to_hash(node).to_a.sort.map(&:last)\n end",
"def hash\n code = 17\n code = 37*code + @x.hash\n code = 37*code + @y.hash\n # Add lines like this for each significant instance variable\n code # Return the resulting code\n end",
"def vertices\n (@structure.keys | @structure.values).flatten.uniq\n end",
"def check\n raise \"Non unique node entries\" unless nodes.uniq == nodes\n raise \"Non unique edge entries\" unless edges.uniq == edges\n @edges.each do |e|\n raise \"self loop\" if e.n1 == e.n2\n raise \"wrong order\" unless e.n1 < e.n2\n raise \"edge not found in n1 incident list\" unless @incident_map[e.n1].find_index(e) \n raise \"edge not found in n2 incident list\" unless @incident_map[e.n2].find_index(e)\n end\n return true\n end",
"def check_eligibility(graph,visited,group_no,final_matchings, case_value)\n for j in 0..graph[0].size\n if(graph[group_no][j] == case_value && visited[j] == false)\n visited[j] = true\n if(final_matchings[j] ==-1 || check_eligibility(graph,visited,final_matchings[j] ,final_matchings, case_value) )\n final_matchings[j] = group_no\n return true\n end\n end\n end\n return false\n end",
"def cc\n preorder, postorder, visited, cc, ccs = [], [], [], [], []\n @count = 0\n id = {}\n adj_lists.each do |v|\n if !visited.include?(v.name)\n dfs_visit(v.name, adj_lists, id, visited, preorder, postorder)\n @count += 1\n puts \"***Back in cc method***\\n\"\n end\n end\n\n puts \"id = #{id}\\n\\n\"\n\n (0..id.values.last).each do |i|\n id.each do |vertex, component|\n cc << vertex if i == component\n end\n ccs << cc.sort if cc != []\n cc = []\n end\n print \"ccs: #{ccs}\\n\\n\"\n ccs\n end",
"def graph\n @graph ||= Codependency::Graph.new\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.51590437",
"0.5144509",
"0.5142079",
"0.51396304",
"0.5127002",
"0.5126637",
"0.5117689",
"0.51176023",
"0.5117122",
"0.50947",
"0.5091778",
"0.50851107",
"0.508342",
"0.5082349",
"0.50770324",
"0.50729996",
"0.50602186",
"0.5046347",
"0.5043247",
"0.50427556",
"0.50339687",
"0.50284773",
"0.5022853",
"0.50207806",
"0.5019196",
"0.5004999",
"0.5004999",
"0.5001409",
"0.50004613",
"0.49915335",
"0.49786472",
"0.4970059",
"0.4967645",
"0.49648952",
"0.49587142",
"0.49562377",
"0.49551192",
"0.49549416",
"0.49532497",
"0.4949704",
"0.4948574",
"0.49419263",
"0.49381346",
"0.49338195",
"0.49333808",
"0.4931587",
"0.49208933",
"0.49076343",
"0.49065158",
"0.49031156",
"0.4900022",
"0.488434",
"0.4884271",
"0.48767275",
"0.4870922",
"0.4870639",
"0.4867851",
"0.48666745",
"0.48642784",
"0.4858879",
"0.48502055",
"0.48453894",
"0.48422214",
"0.48360658",
"0.48327568",
"0.48258045",
"0.48228067",
"0.48216116",
"0.4819012",
"0.48149836"
] | 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",
"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 |idx|\n rel[idx, 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",
"def eulerian_path(graph)\n # We can just use the eulerian cycle problem by just choosing the \n # first node which has greater outdegree than indegree\n\n node = graph.keys[0]\n in_degrees = {}\n graph.values.flatten.each do |val|\n in_degrees[val] = 0 unless in_degrees.has_key?(val)\n in_degrees[val] += 1\n end\n # puts in_degrees.to_s\n graph.each do |k,v|\n if in_degrees.has_key?(k) and v.length > in_degrees[k]\n node = k\n break\n end\n unless in_degrees.has_key?(k)\n node = k\n break\n end\n end\n stack = [node]\n cycle = []\n while (not stack.empty?)\n node = stack[-1]\n if graph.has_key?(node)\n new_node = graph[node][0]\n # puts \"New node:\" + new_node\n stack << new_node\n if graph[node].length > 1\n graph[node].delete(new_node)\n else\n graph.delete(node)\n end\n else\n cycle.unshift(stack.pop)\n # puts stack.join(\" \")\n end\n end\n\n return cycle \n end",
"def gen_graph(connected: true, directed: false)\n graph = Graph.new(directed: directed)\n\n ('A'..'G').each { |char| graph.add_vertex(Vertex.new(id: char)) }\n\n all_possible_edges = graph.vertices().permutation(2)\n\n all_possible_edges.to_a.shuffle.each do |pair|\n\n break if graph.connected? and connected\n\n graph.add_edge(from: pair[0], to: pair[1])\n\n # adding both directions for undirected edge\n unless graph.directed?\n graph.add_edge(from: pair[1], to: pair[0])\n end\n\n\n # # Graph is guaranteed to be connected if out-degree of each vertext is at least 2\n # # To make graph less connected, introduce a probability for adding\n # # extra edges for vertices which already have an out-degree of 2\n # if graph.degree(pair[0]) < 2 or (graph.degree(pair[0]) >= 2 and rand() < 0.10)\n #\n # graph.add_edge(from: pair[0], to: pair[1])\n #\n # # adding both directions for undirected edge\n # unless graph.directed?\n # graph.add_edge(from: pair[1], to: pair[0])\n # end\n #\n # end\n end\n ap graph.adj_list\n\n graph\nend",
"def subgraph_from_depth(graph, from, depth)\n\n ret = graph.class.new\n\n return ret if depth < 0\n\n return ret if ! graph.vertex?(from)\n\n if depth == 0\n ret.add_vertex! from\n return ret\n end\n\n # e.g.,\n # graph = GRATR::DirectedPseudoGraph[0,1, 1,2, 1,2, 1,3, 2,4, 2,5,\n # 2,5, 3,6, 3,7, 5,8, 6,8, 6,9]\n # 0\n # |\n # 1\n # // \\\n # 2 3\n # / \\\\ / \\\n # 4 5 6 7\n # \\ /\\\n # 8 9\n #\n # from = 1\n # depth = 2\n\n 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\n edges = buildEdgeList graph, from, depth\n\n graph.edges.each { |e| ret.add_edge!(e) if edges.include?([e.source, e.target]) }\n\n #\n # 1\n # // \\\n # 2 3\n # / \\\\ / \\\n # 4 5 6 7\n #\n ret\nend",
"def complete_graph(n)\n set = (Integer === n) ? 1..n : n\n RGL::ImplicitGraph.new do |g|\n g.vertex_iterator { |b| set.each(&b) }\n g.adjacent_iterator do |x, b|\n set.each { |y| b.call(y) unless x == y }\n end\n end\nend",
"def t\n adj_t = Array.new(vertices.length) { [] }\n adj.each_with_index do |adj_j, j|\n adj_j.each do |v|\n adj_t[vertices.index(v)] << vertices[j]\n end\n end\n dup.tap { |g| g.adj = adj_t }\n end",
"def feedback_arc_graph(graph)\n edges_to_graph(feedback_arc_set(graph))\n end",
"def directors\n directors = []\n self.children.each { |m|\n m.directors.slice(0,1).each { |d| directors.push(d) }\n }\n directors.uniq\n end",
"def to_a\n [@left_edge, @bottom_edge, @right_edge, @top_edge]\n end",
"def graph\n if @graph.nodes.empty?\n build_nodes!\n establish_edges!\n end\n\n @graph\n end",
"def graph\n if @graph.nodes.empty?\n build_nodes!\n establish_edges!\n end\n\n @graph\n end",
"def orden_nodos(g,d)\r\n return Cola.new(g.grafo[d])\r\n end",
"def edges\n @structure.reduce([]) do |acc, node|\n acc + node[1].map { |dest| [node[0], dest] }\n end\n end",
"def adj pt\n return [[pt[0]-1,pt[1]], [pt[0]+1,pt[1]], [pt[0],pt[1]-1], [pt[0],pt[1]+1]]\nend",
"def subgraph(list = nil)\n if list\n\t@label.clear\n\tlist.each do |node|\n\t @label[node] = true\n\tend\n end\n sub_graph = Pathway.new([], @undirected)\n @graph.each do |from, hash|\n\tnext unless @label[from]\n\thash.each do |to, relation|\n\t next unless @label[to]\n\t sub_graph.append(Relation.new(from, to, relation))\n\tend\n end\n return sub_graph\n end",
"def adj(u)\n\t\tl = Array.new\n\t\t@edgeSet.each do |e|\n\t\t\tif e.s == u\n\t\t\t\tl << e.d\n\t\t\tend\n\t\tend\n\t\tl\n\tend",
"def degrees\n Enumerator.new(@structure.length) do |y|\n nodes.each do |node|\n y << [node, degree(node)]\n end\n end\n end",
"def subgraph\n paths.subgraph\n end",
"def topological_ordering(graph)\n <<-DOC\n TOPOLOGICALORDERING(Graph)\n List ← empty list\n Candidates ← set of all nodes in Graph with no incoming edges\n while Candidates is non-empty\n select an arbitrary node a from Candidates\n add a to the end of List and remove it from Candidates\n for each outgoing edge from a to another node b\n remove edge (a, b) from Graph\n if b has no other incoming edges \n add b to Candidates\n if Graph has edges that have not been removed\n return \"the input graph is not a DAG\"\n else return List \n DOC\n\n list = []\n keys = graph.keys\n values = graph.values.flatten.uniq\n candidates = keys - values\n loop do\n break if candidates.empty?\n a = candidates[0]\n list << a\n candidates.delete(a)\n loop do\n break unless graph[a]\n b = graph[a][0]\n graph[a].delete(b)\n graph.delete(a) if graph[a].empty?\n candidates << b unless graph.values.flatten.include?(b)\n end\n end\n\n unless graph.empty?\n return \"Graph is not a DAG\" \n end\n\n return list\n end",
"def build\n GraphUtilities.alternation(@left.build, @right.build)\n end",
"def make_graph(all_dependencies)\n graph = RGL::DirectedAdjacencyGraph.new\n all_dependencies.each do |source, targets|\n if targets.empty?\n graph.add_vertex(source)\n else\n targets.each { |target| graph.add_edge(source, target) }\n end\n end\n graph\n end",
"def graphviz(oGraph, c0, c1, c2, c3, c4)\n return if @src_id.nil? || @dst_id.nil?\n return if @count > 1 # TODO: eliminate dupulicate trans\n\n guard = @block.condition_success unless @block.nil?\n guard = \"unknown\" if guard.nil?\n\n if @title.nil?\n title = ''\n else\n title = \"#{@title}\"\n end\n @label = @type + '(' + title + ')\\n' + guard + '\\n' + @block.id\n\n if (@src_id =~ /^V_/) && (@dst_id =~ /^V_/)\n # V to V form\n src_id = @src_id + '_inbound'\n dst_id = @dst_id + '_inbound'\n\n elsif (@src_id =~ /^V_/) && (@dst_id =~ /^C_/)\n src_id = @src_id + '_inbound'\n dst_id = @dst_id\n\n c2.add_node(dst_id) if $graphviz_with_rank\n elsif (@src_id =~ /^C_/) && (@dst_id =~ /^V_/)\n src_id = @src_id\n dst_id = @dst_id + '_outbound'\n c2.add_node(src_id) if $graphviz_with_rank\n c4.add_node(dst_id) if $graphviz_with_rank\n elsif (@src_id =~ /^C_/) && (@dst_id =~ /^C_/)\n # redirect\n src_id = @src_id\n dst_id = @dst_id\n c2.add_node(src_id) if $graphviz_with_rank\n c3.add_node(dst_id) if $graphviz_with_rank\n else\n src_id = @src_id\n dst_id = @dst_id\n end\n\n # draw\n e = oGraph.add_edge(src_id, dst_id, label: @label)\n end",
"def create_dot_graph\r\n\r\n \t# Create the base object, then add edges/nodes later etc\r\n \tmy_graph = Graph.new\r\n \tmy_graph.name= \"State_Model\"\r\n \tmy_graph.node_style= :ellipse\r\n \tmy_graph.type = :digraph\r\n\r\n \t# For each entry in the Adjacency matrix extract the relationships and add the graph edges.\r\n \tself.adjacency_matrix.each_key do |table_key|\r\n \t\ttransition_list=self.adjacency_matrix[table_key]\r\n \t\ttransition_list.each do |transition|\r\n \t\t # is the action guarded?\r\n \t\t if self.guarded_actions !=nil\r\n \t\t guarded=self.guarded_actions.include? transition.action\r\n \t\t\tend # end if \r\n \t\t\t# add the edge...\r\n \t\t\tmy_graph.add_edge(transition.start_state, transition.end_state, \" #{transition.action} \", guarded)\r\n \t\tend # end add transitions\r\n \tend # end add nodes\r\n\r\n \treturn my_graph\r\n end",
"def subgraph_from_to(graph, from, to)\n\n graph = subgraph_from(graph, from)\n\n to = [to] unless to.is_a?(Array)\n\n def buildEdgeList graph, to\n ret = Set.new\n to.each do |child|\n parents = graph.adjacent(child, {:direction => :in})\n ret.merge(parents.map { |parent| [parent, child] })\n ret.merge(buildEdgeList(graph, parents))\n end\n ret\n end\n\n edges = buildEdgeList graph, to\n ret = graph.class.new\n graph.edges.each { |e| ret.add_edge!(e) if edges.include?([e.source, e.target]) }\n ret\nend",
"def spanning_tree\n raise ArgumentError unless connected?\n result = (self.class.to_s == \"ArrayGraph\") ?\n ArrayGraph.new(vertices) :\n LinkedGraph.new(vertices)\n dfs(0) { |v,w| result.add_edge(v,w) if 0 <= v }\n result\n end",
"def vertices\n self.connections.map {|c| c.end}\n end",
"def directions\n STRAIGHT + DIAGONAL\n end",
"def to_graph(graph = RDF::Graph.new)\n properties.each do |property|\n property.to_graph(graph)\n end\n graph\n end",
"def inversed; end",
"def degrees_of_separation(start_node, destination_node)\n start_node_id = start_node[\"self\"].split('/').last.to_i\n destination_node_id = destination_node[\"self\"].split('/').last.to_i\n @neo.execute_script(\"g.v(start_node_id).\n as('x').\n in.loop('x'){it.loops <= 4 &\n it.object.id != destination_node_id}.\n simplePath.\n filter{it.id == destination_node_id}.\n paths{it.name}\", {:start_node_id => start_node_id,\n :destination_node_id => destination_node_id })\nend",
"def directed?\n @undirected ? false : true\n end",
"def test_to_s\n graph = DirectedGraph.new\n vertex_a = Vertex.new('a')\n vertex_b = Vertex.new('b')\n vertex_c = Vertex.new('c')\n graph.add_vertex(vertex_a).add_vertex(vertex_b).add_vertex(vertex_c)\n graph.add_edge('a','b').add_edge('c','b')\n\n assert(graph.to_s == 'a=>b,b=>,c=>b')\n end",
"def isolates\n edges.inject(Set.new(vertices)) { |iso, e| iso -= [e.source, e.target] }\n end",
"def ungraphed\n clone(:graph=>nil, :graph_aliases=>nil) # SEQUEL5: Remove :graph_aliases\n end",
"def orden_nodos(g,d)\r\n return Pila.new(g.grafo[d])\r\n end",
"def graph_states\n self.graph.states\n end",
"def draw_graph(graph)\n type = graph.directed? ? :digraph : :graph\n g = GraphViz.new(:G, :type => type)\n graph.vertices().each do |v|\n g.add_node(v.id)\n end\n\n added_edges = Set.new\n\n graph.edges_by_vertices().each do |x, edges|\n from = g.get_node(x.id)\n edges.each do |y|\n to = g.get_node(y.id)\n\n if graph.directed?\n # draw each individual 'directed' edge\n g.add_edge(from, to)\n else\n # draw only one edge to represent 'undirected' edge\n g.add_edge(from, to) unless added_edges.include?([to, from])\n added_edges.add([from, to])\n end\n\n\n end\n end\n\n\n filename = \"graph.png\"\n g.output( :png => filename )\n system(\"open #{filename}\")\nend",
"def make_implicit(vertices, edges)\n RGL::ImplicitGraph.new do |g|\n edges.default = []\n g.vertex_iterator { |b| vertices.each(&b) }\n g.adjacent_iterator do |x, b|\n vertices.each {|y| b.call(y) if edges[x].include? y}\n end\n end\nend",
"def to_gv\n # General graph options\n str = \"digraph #{@name} {\\n\"\n str += \"\\t// General graph options\\n\"\n str += \"\\trankdir = LR;\\n\"\n str += \"\\tsize = \\\"10.5,7.5\\\";\\n\"\n str += \"\\tnode [ style = filled, fillcolor = white, fontsize = 8.0 ]\\n\"\n str += \"\\tedge [ arrowhead = vee, arrowsize = 0.5, fontsize = 8.0 ]\\n\"\n str += \"\\n\"\n\n str += \"\\t// Places\\n\"\n str += \"\\tnode [ shape = circle ];\\n\"\n @places.each_value {|id| str += @objects[id].to_gv }\n str += \"\\n\"\n\n str += \"\\t// Transitions\\n\"\n str += \"\\tnode [ shape = box, fillcolor = grey90 ];\\n\"\n @transitions.each_value {|id| str += @objects[id].to_gv }\n str += \"\\n\"\n\n str += \"\\t// Arcs\\n\"\n @arcs.each_value {|id| str += @objects[id].to_gv }\n str += \"}\\n\" # Graph closure\n\n return str\n end",
"def to_dot\n require 'graphviz_r'\n gvr = GraphvizR.new('mind_map')\n gvr.graph[:bgcolor => 'transparent']\n edges = cull()\n\n edges.flatten.uniq.each do |post|\n def post.dot_id; \"post_#{ id }\"; end\n gvr[post.dot_id][ style_node(post) ]\n end\n\n edges.each{ |from, to| gvr[from.dot_id] - gvr[to.dot_id] }\n return gvr.to_dot # that ^ declares a GraphViz edge!\n end",
"def ordenEach ()\n ordenado = []\n each do\n |node|\n if ordenado.empty?\n ordenado.push(node)\n else\n indice = 0\n while indice < ordenado.length\n if node <= ordenado[indice]\n ordenado.insert(indice, node)\n break\n elsif indice == ordenado.length-1\n ordenado.insert(indice+1, node)\n break\n end\n indice+=1\n end\n end\n end\n return ordenado\n end",
"def all_degrees_of_separation(entity)\n if entity.is_a?(Sociographer::Entity)\n # @@neo = Neography::Rest.new\n self_node = self.get_node\n entity_node = entity.get_node\n if self_node && entity_node\n paths = []\n self_node.all_simple_paths_to(entity_node).incoming(:friends).depth(5).nodes.each do |path|\n # path << node.object_type.safe_constantize.find(node[\"object_id\"])\n in_between = path.map{|n| begin {entity_type: n.object_type, entity_id: n[:object_id]} rescue Exception end }\n path = {length: path.size-1, users: in_between}\n paths << path\n # puts \"#{(path.size - 1)} degrees: \" + path.map{|n| begin n.object_type.safe_constantize.find(n[:object_id]).name rescue Exception end }.join(\" => friends =>\") \n end\n return paths\n else\n false\n end\n else\n false\n end\n end",
"def detect_cycle_in_graph(edges)\nend",
"def topological_sort(vertices)\n arr = []\n next_v = []\n \n vertices.each do |v|\n if v.in_edges.empty?\n next_v.push(v) \n end \n end\n while next_v.length > 0\n current = next_v.shift\n arr.push(current)\n \n while current.out_edges.length > 0\n edge = current.out_edges.pop\n if edge.to_vertex.in_edges.length == 1\n next_v.push(edge.to_vertex) \n end \n edge.destroy!\n end\n end\n \n arr.length == vertices.length ? arr : []\n end",
"def ur_to_ul\n a = 0\n x = 0\n edge3 = []\n\n # compute the index a < (12 choose 3) and the edge permutation\n (UR..BR).each do |j|\n if edge_permutation[j] <= UL\n a += n_choose_k(j, x + 1)\n edge3 << edge_permutation[j]\n x += 1\n end\n end\n\n # compute the index b < 3! for the permutation in edge3\n b = 0\n 2.downto(1).each do |j|\n k = 0\n while edge3[j] != j\n edge3 = rotateLeft(edge3, 0, j)\n k += 1\n end\n b = (j + 1) * b + k\n end\n\n (6 * a + b) & 0xffff\n end",
"def make_logicalPart_unique(graph, edge, vertices, recursive = false)\n\n edges = edge.is_a?(Array) ? edge : [edge]\n\n edges_with_same_target = graph.edges.select { |e| e.target == edges[0].target }\n return if edges_with_same_target.size <= edges.size\n\n vertex_org = edges[0].target\n vertex_new = create_unique_symbol(vertex_org, Set.new(graph.vertices + vertices.keys))\n vertices[vertex_new] = vertices[vertex_org].dup\n make_target_unique(graph, edges, vertex_new)\n\n return unless recursive\n\n graph.adjacent(vertex_new, {:direction => :out, :type => :vertices}).uniq.each do |target|\n e = graph.edges.select { |e| e.source == vertex_new and e.target == target }\n make_logicalPart_unique(graph, e, vertices, recursive)\n end\n\nend",
"def dfa2dot(dfa)\n str = \"digraph {\\n\"\n str += \"size=\\\"2,2\\\"\\nratio=1.0\\n\"\n str += \"node [shape=circle]\\n\"\n str += \"preinit [shape=plaintext, label=\\\"\\\"]\\n\"\n (dfa.states - dfa.final_states).each do |state|\n str += state + \"\\n\"\n end\n str += \"node [shape=doublecircle]\\n\"\n dfa.final_states.each do |state|\n str += state + \"\\n\"\n end\n str += \"preinit -> #{dfa.initial_state}\\n\"\n dfa.states.each do |s1|\n dfa.states.each do |s2|\n res = dfa.transitions.find_all { |tr| tr[0] == s1 and tr[1] == s2 }\n unless res.empty?\n label = res.map { |tr| tr[2] }.join(',')\n str += s1 + \"->\" + s2 + \"[label=\\\"#{label}\\\"]\\n\"\n end\n end\n end\n \n str + \"}\"\n end",
"def get_graph\n @graph = Graph.new\n @tparses.each do |p|\n if p[:args]\n p[:args].each do |type, arg|\n @graph.add_edge(p[:idx], arg, 1) if arg >= 0\n end\n end\n end\n\n g = GraphViz.new(:G, :type => :digraph)\n g.node[:shape] = \"box\"\n g.node[:fontsize] = 11\n g.edge[:fontsize] = 9\n\n n = []\n @tparses.each do |p|\n n[p[:idx]] = g.add_nodes(p[:idx].to_s, :label => \"#{p[:word]}/#{p[:pos]}/#{p[:cat]}\")\n end\n\n @tparses.each do |p|\n if p[:args]\n p[:args].each do |type, arg|\n if arg >= 0 then g.add_edges(n[p[:idx]], n[arg], :label => type) end\n end\n end\n end\n\n g.get_node(@root.to_s).set {|_n| _n.color = \"blue\"} if @root >= 0\n g.get_node(@focus.to_s).set {|_n| _n.color = \"red\"} if @focus >= 0\n\n @graph_rendering = g.output(:svg => String)\n end",
"def relations\n Relations::RelationTraverser.new(@internal_node)\n end",
"def get_graph_rendering(parse)\n return '' if parse.nil? || parse[:root].nil?\n\n tokens = parse[:tokens]\n root = parse[:root]\n focus = parse[:focus]\n\n g = GraphViz.new(:G, :type => :digraph)\n g.node[:shape] = \"box\"\n g.node[:fontsize] = 10\n g.edge[:fontsize] = 9\n\n n = []\n tokens.each do |p|\n n[p[:idx]] = g.add_nodes(p[:idx].to_s, :label => \"#{p[:lex]}/#{p[:pos]}/#{p[:cat]}\")\n end\n\n tokens.each do |p|\n if p[:args]\n p[:args].each do |type, arg|\n if arg >= 0 then g.add_edges(n[p[:idx]], n[arg], :label => type) end\n end\n end\n end\n\n g.get_node(root.to_s).set {|_n| _n.color = \"blue\"} if root >= 0\n g.get_node(focus.to_s).set {|_n| _n.color = \"red\"} if focus >= 0\n g.output(:svg => String)\n end",
"def get_vertices\n getVertices.to_route(:graph => self, :element_type => :vertex)\n end",
"def get_vertices\n getVertices.to_route(:graph => self, :element_type => :vertex)\n end",
"def graph\n Graph.new(project_path_trie, tsort)\n end",
"def to_dot(include_starred_states = false)\n all_states = transitions.values.map(&:to_a).flatten.uniq.reject { |t| t == \"*\" }\n\n \"\".tap do |s|\n s << \"digraph #{self.class.name.inspect} {\\n\"\n transitions.each do |signal, signal_transitions|\n signal_transitions.each do |from, to|\n next if !include_starred_states && (from == \"*\" || to == \"*\")\n\n from = from == \"*\" ? all_states : [from]\n to = to == \"*\" ? all_states : [to]\n from.product(to).each { |f, t| s << \" #{f} -> #{t} [ label=\\\"#{signal}\\\" ]\\n\" }\n end\n end\n s << \"}\\n\"\n end\n end",
"def edge_vertices( edge )\r\n if edge_reversed?( edge )\r\n edge.vertices.reverse\r\n else\r\n edge.vertices\r\n end\r\n end",
"def orientations\n return @orientations\n end",
"def add_undirected_edge(id1,id2)\n @g[id1] ||= Set.new\n @g[id2] ||= Set.new\n @g[id1] << id2\n @g[id2] << id1\n end",
"def topsort\n graph = RGL::DirectedAdjacencyGraph.new\n # init vertices\n items = @normal_sources\n items.each {|item| graph.add_vertex(item) }\n # init edges\n items.each do |item|\n item.dependencies.each do |dependency|\n # If we can find items that provide the required dependency...\n # (dependency could be a wildcard as well, hence items)\n dependency_cache[dependency] ||= provides_tree.glob(dependency)\n # ... we draw an edge from every required item to the dependant item\n dependency_cache[dependency].each do |required_item|\n graph.add_edge(required_item, item)\n end\n end\n end\n\n begin\n graph.topsorted_vertices\n rescue RGL::TopsortedGraphHasCycles => e\n output_cycles(graph)\n raise e # fail fast\n end\n end",
"def in_degree\n @in_edges.length\n end",
"def generate_graph\n end",
"def to_s\n edges.collect {|e| e.to_s}.sort.join\n end",
"def in_out_edges\n in_edges + out_edges\n end",
"def communicationgraph_old(filter=@filter, &block) # :nodoc:\n us = users(filter)\n if block\n g = DotGraph.new(us, :directed => true, &block)\n else\n g = DotGraph.new(us, :directed => true) { |n| n.name }\n end\n pages(filter).each do |p| \n p.revisions(filter).inject do |a,b|\n g.link(b.user,a.user)\n b\n end\n end\n g\n end",
"def to_ntriples\n to_n3\n end",
"def make_directed(vertices, directed_edges)\n g = RGL::DirectedAdjacencyGraph.new\n \n vertices.each { |v| g.add_vertex(v) }\n \n directed_edges.each do |source, targets|\n targets.each { |target| g.add_edge(source, target) }\n end\n \n g\nend",
"def shortest_degrees_of_separation(entity)\n @@neo = Neography::Rest.new\n self_node = self.get_node\n entity_node = entity.get_node\n if self_node && entity_node\n paths = []\n self_node.shortest_path_to(entity_node).incoming(:friends).depth(5).nodes.each do |path|\n # path << node.object_type.safe_constantize.find(node[\"object_id\"])\n in_between = path.map{|n| begin n.object_type.safe_constantize.find(n[:object_id]).id rescue Exception end }\n path = {length: path.size-1, users: in_between}\n paths << path\n # puts \"#{(path.size - 1)} degrees: \" + path.map{|n| begin n.object_type.safe_constantize.find(n[:object_id]).name rescue Exception end }.join(\" => friends =>\") \n end\n paths\n end\n end",
"def to_ntriples\n self.to_n3\n end",
"def traverse room, direction\n case direction.to_sym\n when :right\n return @graph[room.coords[:y]][room.coords[:x] + 1] unless room.is_right?\n when :left\n return @graph[room.coords[:y]][room.coords[:x] - 1] unless room.is_left?\n when :up\n return @graph[room.coords[:y] - 1][room.coords[:x]] unless room.is_top?\n when :down\n return @graph[room.coords[:y] + 1][room.coords[:x]] unless room.is_bottom?\n end\n\n return false\n end",
"def edges\n @pathway.relations.collect do |rel|\n [ rel.node[0], rel.node[1], rel.relation ]\n end\n end",
"def directions\n DIRECTIONS\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.50110096",
"0.5004714",
"0.5000932",
"0.4978039",
"0.4967964",
"0.49415103",
"0.4936515",
"0.49300727",
"0.4929381",
"0.49279127",
"0.49279127",
"0.49274206",
"0.49000365",
"0.4893518",
"0.48898387",
"0.48878282",
"0.48777106",
"0.48745105",
"0.48702458",
"0.48555624",
"0.48554394",
"0.48514253",
"0.48278728",
"0.4796624",
"0.4793079",
"0.47870004",
"0.47799006",
"0.4779113",
"0.47691616",
"0.4758528",
"0.47492102",
"0.47457805",
"0.47394964",
"0.47337443",
"0.47303045",
"0.4725598",
"0.47136262",
"0.4706741",
"0.47034326",
"0.470145",
"0.4700457",
"0.46956635",
"0.46873522",
"0.4678434",
"0.46779987",
"0.46537316",
"0.4651245",
"0.46299008",
"0.4629514",
"0.4618018",
"0.46157637",
"0.46157637",
"0.46147844",
"0.4614352",
"0.46093282",
"0.46085468",
"0.4608083",
"0.46072975",
"0.45996714",
"0.4599557",
"0.4594047",
"0.45920753",
"0.45881668",
"0.45833993",
"0.4581841",
"0.45715216",
"0.45680627",
"0.4566039",
"0.45648023",
"0.45644566"
] | 0.64383256 | 1 |
Taken from Figure 5.10, on pg. 130 of Martin Golumbic's, _Algorithmic_Graph_ _Theory_and_Perfect_Graphs. | def plexus_comparability_explore(edge, k, classification, space='')
ret = plexus_comparability_explore_inner(edge, k, classification, :forward, space)
plexus_comparability_explore_inner(edge.reverse, k, classification, :backward, space) && ret
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"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 test_05\n @dg = DiGraph.new([0,7],[1,9],[1,4],[7,4],[7,0],[7,9],[3,7],[9,4],[9,7],[9,9],[4,1],[4,4],[4,7])\n @paths = Hash.new\n @paths[0] = [7]\n @paths[1] = [9,4]\n @paths[7] = [4,0,9]\n @paths[3] = [7]\n @paths[9] = [4,7,9]\n @paths[4] = [1,4,7]\n @nodes = @paths.keys\n received_dg = @dg.strongly_connected_component_including_node(0);\n filled_dg = DiGraph.new(*fill(0));\n if (not filled_dg.equal?(received_dg))\n puts \"test_05 failed...\"\n puts \"DiGraph => #{@dg.to_s}\"\n puts \"node => 0\"\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 topological_sort(vertices) # array => # layers of unordered sets (could implement these as subarrays)\n # Kahn's alg. #Coffman-Graham gives deterministic sorting\n #look for vertices w/o @in_edges; add to list\n #look for vertices w/o @in_edges (exclude @in_edges in list)\n #repeat until all vertices in the list\n\n #w/o queue\n list = []\n\n until list.length == vertices.length\n changed = false\n vertices.each do |vertex|\n if !list.include?(vertex) && ( vertex.in_edges.length == 0 ||\n vertex.in_edges.all?{|edge| list.include?(edge.from_vertex)} )\n list.push(vertex)\n changed = true\n end\n end\n\n return [] if !changed\n end\n\n list\n\n # #w/ queue (could also implement by enqueueing out-edges' to-vertices\n # for each node added to list, replacing queue.each w/ until queue.empty?)\n # list = []\n # queue = []\n #\n # full = vertices.length\n #\n # until list.length == full\n # changed = false\n # vertices.each do |vertex|\n # if vertex.in_edges.length == 0 && !list.include?(vertex)\n # queue.push(vertex)\n # end\n # end\n #\n # queue.each do |vertex|\n # vertex.out_edges.each {|edge| edge.destroy!} #causes spec's test to malfunction\n # list.push(queue.shift)\n # changed = true\n # end\n #\n # return [] if !changed\n # end\nend",
"def generate_graph\n end",
"def test_06\n @dg = DiGraph.new([5,9],[0,3],[3,8],[8,9],[9,0])\n @paths = Hash.new\n @paths[5] = [9]\n @paths[0] = [3]\n @paths[3] = [8]\n @paths[8] = [9]\n @paths[9] = [0]\n @nodes = @paths.keys\n received_dg = @dg.strongly_connected_component_including_node(0);\n filled_dg = DiGraph.new(*fill(0));\n if (not filled_dg.equal?(received_dg))\n puts \"test_06 failed...\"\n puts \"DiGraph => #{@dg.to_s}\"\n puts \"node => 0\"\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 problem_107\n if false\n net = [ \"-,16,12,21,-,-,-\", \"16,-,-,17,20,-,-\", \"12,-,-,28,-,31,-\",\n \"21,17,28,-,18,19,23\", \"-,20,-,18,-,-,11\", \"-,-,31,19,-,-,27\",\n \"-,-,-,23,11,27,-\" ]\n net.map! {|line| line.split(/,/).map {|i| i == '-' ? nil : i.to_i}}\n else\n net = []\n open(\"network.txt\").each do |line|\n net << line.chomp.split(/,/).map {|i| i == '-' ? nil : i.to_i}\n end\n end\n\n # Reformat into an array of nodes, with the their connections\n nodes = Hash.new {|h,k| h[k] = Hash.new }\n net.each_with_index do |row,i| # Each nodes is connected to...\n row.each_index do |col| # For each possible connection....\n # Add the node we are connected to and the cost\n nodes[i][col] = row[col] if row[col]\n end\n end\n\n initial = nodes.reduce(0) do |a,row|\n row[1].reduce(a) {|aa,p| aa + p[1] }\n end / 2\n # add to the 'borg' that is node0\n node0,node0_links = nodes.shift\n ans = []\n node0_contains = Hash.new\n node0_contains[node0] = true\n\n # What we do select the lowest link, the 'merge' it into node0, repeat\n while nodes.length > 0\n n,v = node0_links.min {|a,b| a[1] <=> b[1]}\n ans << [n,v] # Save the link for the answer\n node0_contains[n] = true # add to the 'borg' that is node0\n nodes[n].each_pair do |k,a| # Now merge in new poin, update vertexs\n next if node0_contains[k]\n node0_links[k] = [a, node0_links[k] || 1_000_000].min\n end\n nodes.delete(n) # Remove from free nodes\n node0_links.delete(n) # Remove from vertexes to resolve\n end\n\n now = ans.reduce(0) {|a,v| a + v[1]}\n puts \"initial = #{initial}\"\n puts \"now = #{now}\"\n initial - now\nend",
"def topological_sort(vertices)\n\n # # Determine the in-degree of each node.\n # in_degrees = []\n #\n # vertices.each do |vertex|\n # in_degrees.push(vertex.in_edges.length)\n # end\n #\n # # Collect nodes with zero in-degree in a queue.\n # queue = []\n # in_degrees.each_with_index do |degree, idx|\n # queue.push(vertices[idx]) if degree == 0\n # end\n #\n # deletelist = []\n # # While the queue is not empty:\n # while(queue.length != 0)\n # # Pop node u from queue,\n # u = queue.shift()\n # # remove u from the graph,\n # vertices.delete(u)\n # # We maintain a list that records in which order the nodes are removed.\n # deletelist.push(u)\n # u.out_edges.each {|edge| edge.destroy!}\n #\n # # check if there is a new node with in-degree zero (among the neighbors of u)\n # in_degrees = []\n # vertices.each do |vertex|\n # in_degrees.push(vertex.in_edges.length)\n # end\n # # If yes, put that node into the queue.\n # in_degrees.each_with_index do |degree, idx|\n # queue.push(vertices[idx]) if (degree == 0) && (queue.include?(vertices[idx]) == false)\n # end\n # end\n #\n # # If the queue is empty:\n # # if we removed all nodes from the graph, return the list\n # return deletelist if vertices == []\n #\n # # else we return an empty list that indicates that an order is not possible due to a cycle\n # return []\n\n #I tried but I don't understand what the spec is saying\n in_edge_counts = {}\n queue = []\n\n vertices.each do |v|\n in_edge_counts[v] = v.in_edges.count\n queue << v if v.in_edges.empty?\n end\n\n sorted_vertices = []\n\n until queue.empty?\n vertex = queue.shift\n sorted_vertices << vertex\n\n vertex.out_edges.each do |e|\n to_vertex = e.to_vertex\n\n in_edge_counts[to_vertex] -= 1\n queue << to_vertex if in_edge_counts[to_vertex] == 0\n end\n end\n\n sorted_vertices\n\n # The time complexity of this implementation is O(2v + 2e)\n\nend",
"def detect_cycle_in_graph(edges)\nend",
"def hard(input)\n graph = Graph.from(input)\n components = []\n vertices = Set.new(graph.vertices)\n until vertices.empty?\n start = vertices.first\n component = graph_walk(graph, start)\n components << component\n vertices = vertices.difference(component)\n end\n components.length\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 topological_sort(vertices)\n # visited = Set.new\n # # visited = Array.new(vertices.length, false)\n # cycle = [false]\n # result = []\n #\n # vertices.each do |vertex|\n # unless visited.include?(vertex)\n # visit(vertex, visited, result, cycle)\n # end\n # end\n #\n # if cycle == [true]\n # return []\n # else\n # return result\n # end\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n queue = []\n result = []\n vertices.each do |vert|\n queue << vert if vert.in_edges.empty?\n end\n # byebug\n count = 0\n until queue.empty?\n vertex = queue.pop\n result << vertex\n to_destroy = []\n for i in (0..(vertex.out_edges.length - 1))\n edge = vertex.out_edges[i]\n if edge.to_vertex.in_edges.length == 1\n queue.push(edge.to_vertex)\n end\n to_destroy << edge\n i += 1\n end\n to_destroy.each do |edge|\n edge.destroy!\n end\n count += 1\n end\n result\nend",
"def topological_sort(vertices)\n result = []\n queue = []\n visited_nodes = 0\n remaining_vert = vertices.dup\n while result.length < vertices.length\n # print 'hey'\n # print remaining_vert.map{|vert| vert.in_edges.length}\n # print remaining_vert.map{|vert| vert.value}\n remaining_vert.each do |vert|\n if vert.in_edges.length == 0\n queue.push(vert)\n new_vert = []\n remaining_vert.each do |vert2|\n new_vert.push(vert2) unless vert2 == vert\n end\n remaining_vert = new_vert\n end\n end\n # print 'hi'\n # print queue.map{|queue| queue.out_edges.length}\n return [] if remaining_vert.length>0 && queue.length == 0\n next_vert = queue.shift()\n next_vert.out_edges.each do |edge|\n edge.destroy!\n end\n result.push(next_vert)\n # print result.map{|queue| queue.out_edges.length}\n visited_nodes+=1\n end\n result\nend",
"def complete_graph(n)\n set = (Integer === n) ? 1..n : n\n RGL::ImplicitGraph.new do |g|\n g.vertex_iterator { |b| set.each(&b) }\n g.adjacent_iterator do |x, b|\n set.each { |y| b.call(y) unless x == y }\n end\n end\nend",
"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 topological_sort(vertices)\n # Khan's algorithm\n sorted_arr = []\n queue = Queue.new\n # in_edges = {}\n vertices.each do |vertex|\n if vertex.in_edges.empty?\n queue.enq(vertex)\n end\n end\n\n # vertices.each do |vertex|\n # in_edge_cost = vertex.in_edges.reduce(0) { |sum, edge| sum += edge.cost }\n # in_edges[vertex] = in_edge_cost\n # queue << vertex if in_edge_cost == 0\n # end\n\n until queue.empty?\n u = queue.deq\n sorted_arr << u\n while u.out_edges.length != 0\n current_edge = u.out_edges[0]\n queue.enq(current_edge.to_vertex) if current_edge.to_vertex.in_edges == [current_edge]\n current_edge.destroy!\n end\n u.out_edges = []\n end\n\n # until queue.empty?\n # current = queue.shift\n #\n # current.out_edges.each do |edge|\n # to_vertex = edge.to_vertex\n # in_edges[to_vertex] -= edge.cost\n # queue << to_vertex if in_edges[to_vertex] == 0\n # end\n #\n # sorted arr << current\n # end\n\n if sorted_arr.length != vertices.length\n return []\n # vertices.length == order.length ? order : []\n end\n\n sorted_arr\n\n # Tarjan's algorithm (without cyce catching)\n # order = []\n # explored = Set.new\n #\n # vertices.each do |vertex|\n # dfs!(order, explored, vertex) unless explored.include?(vertex) #depth-first search\n # end\n #\n # order\n\nend",
"def topological_sort(vertices)\n order = []\n explored = Set.new \n\n vertices.each do |vertex|\n dfs!(order, explored, vertex) unless explored.include?(vertex)\n end \n\n order \n\nend",
"def test_create_graph\r\n \tnode1 = Node.new(1, 'C', [2, 3])\r\n \tnode2 = Node.new(2, 'A', [3, 4, 6])\r\n \tnode3 = Node.new(3, 'K', [5])\r\n \tnode4 = Node.new(4, 'T', nil)\r\n \tnode5 = Node.new(5, 'E', nil)\r\n \tnode6 = Node.new(6, 'B', nil)\r\n \tsmall_graph = [node1, node2, node3, node4, node5, node6]\r\n \treader = GraphReader.new('small_graph.txt')\r\n \treader.create_graph()\r\n \treader.graph.shift\r\n \tassert_equal reader.graph.map(&:letter), small_graph.map(&:letter)\r\n end",
"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 complete_weighted_bigraph(n)\n g = GraphMatching::Graph::WeightedBigraph.new\n max_u = (n.to_f / 2).ceil\n min_v = max_u + 1\n weight = 1\n 1.upto(max_u) do |i|\n min_v.upto(n) do |j|\n g.add_edge(i, j)\n g.set_w([i, j], weight)\n weight += 1\n end\n end\n g\nend",
"def test_to_s\n graph = DirectedGraph.new\n vertex_a = Vertex.new('a')\n vertex_b = Vertex.new('b')\n vertex_c = Vertex.new('c')\n graph.add_vertex(vertex_a).add_vertex(vertex_b).add_vertex(vertex_c)\n graph.add_edge('a','b').add_edge('c','b')\n\n assert(graph.to_s == 'a=>b,b=>,c=>b')\n end",
"def topological_sort(vertices)\n in_edges = {}\n result = []\n queue = vertices.select do |vertex|\n in_edges[vertex] = vertex.in_edges.length\n vertex.in_edges.empty?\n end\n\n until queue.empty?\n vertex = queue.pop\n result.push(vertex)\n vertex.out_edges.map(&:to_vertex).each do |vertex|\n in_edges[vertex] -= 1\n queue.unshift(vertex) if in_edges[vertex] == 0\n end\n end\n in_edges.all?{|vertex,count| count == 0} ? result : []\n\nend",
"def topological_sort(vertices)\n count = {}\n sorted = []\n free_queue = []\n\n vertices.each do |vertex|\n count[vertex.value] = vertex.in_edges.length\n if vertex.in_edges.empty?\n free_queue.unshift(vertex)\n end\n end\n\n until free_queue.empty?\n # debugger\n current = free_queue.pop\n # p free_queue.map{|e|e.value}\n sorted << current\n # p current.out_edges.length\n verts = []\n current.out_edges.each do |edge|\n count[edge.to_vertex.value] -= 1\n # vert = edge.to_vertex\n # verts << vert\n end\n\n\n vertices.each do |vertex|\n free_queue.unshift(vertex) if count[vertex.value] == 0 && sorted.index(vertex).nil?\n end\n\n end\n sorted = sorted.uniq\n return [] if sorted.length != vertices.length\n sorted\nend",
"def gen_graph(connected: true, directed: false)\n graph = Graph.new(directed: directed)\n\n ('A'..'G').each { |char| graph.add_vertex(Vertex.new(id: char)) }\n\n all_possible_edges = graph.vertices().permutation(2)\n\n all_possible_edges.to_a.shuffle.each do |pair|\n\n break if graph.connected? and connected\n\n graph.add_edge(from: pair[0], to: pair[1])\n\n # adding both directions for undirected edge\n unless graph.directed?\n graph.add_edge(from: pair[1], to: pair[0])\n end\n\n\n # # Graph is guaranteed to be connected if out-degree of each vertext is at least 2\n # # To make graph less connected, introduce a probability for adding\n # # extra edges for vertices which already have an out-degree of 2\n # if graph.degree(pair[0]) < 2 or (graph.degree(pair[0]) >= 2 and rand() < 0.10)\n #\n # graph.add_edge(from: pair[0], to: pair[1])\n #\n # # adding both directions for undirected edge\n # unless graph.directed?\n # graph.add_edge(from: pair[1], to: pair[0])\n # end\n #\n # end\n end\n ap graph.adj_list\n\n graph\nend",
"def test_create_graph\n val = create_graph(1234, 5)\n locations_count = val[0].count\n prospectors_count = val[1].count\n assert_equal 7, locations_count\n assert_equal 5, prospectors_count\n end",
"def findMaximum(weights)\n\t\n\tputs \"Weights\" if DEBUG_OUTPUT\n\tprintMatrix(weights) if DEBUG_OUTPUT\n\t# l(x) == l[x]\n\t\t\n\teq = EqualityGraph.new(weights)\n\teq.generateLabelFunctions()\n\t\n\t#Generate equality graph\n\t\n\teq.generateEqualityGraph()\n\t\n\t#Pick an abitrary matching in the equality subgraph\n\t\n\teq_match = MatchGraph.new(eq.x_vertices, eq.y_vertices)\n\t\n\teq.initialMatch(eq_match)\t\n\t\n\tputs \"Equality Match\\n#{eq_match.to_s}\" if DEBUG_OUTPUT\n\t\n\t#puts \"Is Equality Match perfect? #{eq_match.isPerfectMatch}\" if DEBUG_OUTPUT\n\t\t\t\n\tuntil(eq_match.isPerfectMatch)\n\t\t#Pick a free vertex in X\n\t\tfreeX = eq_match.get_free_x_vertex\n\t\t\n\t\teq_match.alt_tree_x_nodes.push(freeX)\n\t\t\t\n\t\tputs \"\\nMAJOR STEP Picked a free X: #{freeX}\" if DEBUG_OUTPUT\n\t\t\n\t\ts_vertices = [ freeX ]\n\t\tt_vertices = Array.new\n\t\t\n\t\t#Though sets s and t should be enough, will keep track of the alternating paths \n\t\t#originating at freeX\n\t\t\n\t\t\n\t\ts_neighbors = eq.get_neighbors_of_x_vertices(s_vertices).to_set\n\t\t\n\t\ts_neighbors_not_in_t = s_neighbors.to_a\n\t\t\n\t\tuntil(false)\n\t\t\tputs \"S = #{s_vertices.to_a} N(S) = #{s_neighbors.to_a} T= #{t_vertices.to_a}\" if DEBUG_OUTPUT\n\t\t\t\t\n\t\t\tif s_neighbors.size == t_vertices.size\n\t\t\t\tputs \"\\nSTEP No more s_neighbors to process, growing eq\" if DEBUG_OUTPUT\n\t\t\t\told_size = s_neighbors.size\n\t\t\t\t\n\t\t\t\teq.growEqualityGraph(s_vertices, t_vertices, s_neighbors, s_neighbors_not_in_t)\n\t\t\t\t\n\t\t\t\traise \"s neighbors did not increase\" if s_neighbors.size <= old_size\t\t\t\t\t\t\n\t\t\telse\n\t\t\t\tputs \"\\nSTEP Picking a new Y not yet in T from S neighbors\" if DEBUG_OUTPUT\n\t\t\t\t#pick y\n\t\t\t\ty = s_neighbors_not_in_t.pop #(s_neighbors - t_vertices).find { true } \n\t\t\t\tif eq_match.is_y_vertex_free(y)\n\t\t\t\t\t#Reset S and T\n\t\t\t\t\traise \"T and S are out of wack\" if s_vertices.size != t_vertices.size + 1\t\t\t\t\t\n\t\t\t\t\teq_match = growMatch(y, eq_match, eq, freeX)\n\t\t\t\t\tputs \"Grew match Equality Graph was #{eq}\" if DEBUG_OUTPUT\n\t\t\t\t\tbreak\n\t\t\t\telse\n\t\t\t\t\tputs \"y[#{y}] is matched\" if DEBUG_OUTPUT\n\t\t\t\t\tnew_s_node = growTree(s_vertices, t_vertices, y, eq, eq_match)\n\t\t\t\t\t\n\t\t\t\t\tnew_s_neighbors = eq.get_neighbors_of_x_vertices( [new_s_node] )# - t_vertices\n\t\t\t\t\ts_neighbors.merge( new_s_neighbors )\n\t\t\t\t\t#new_s_neighbors could intesect with t\n\t\t\t\t\ts_neighbors_not_in_t = (s_neighbors - t_vertices).to_a\n\t\t\t\tend\n\t\t\tend \n\t\tend\n\tend\n\t\n\tputs \"Sum is #{eq_match.sumEdgeWeights(weights)}\" if DEBUG_OUTPUT\n\t\n\treturn eq_match.sumEdgeWeights(weights)\nend",
"def topological_sort(vertices)\n queue = []\n result = []\n count = {}\n vertices.each do |vertex|\n count[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n until queue.empty?\n vertex = queue.shift\n result << vertex\n vertex.out_edges.each do |edge|\n to = edge.to_vertex\n count[to] -= 1\n queue << to if count[to] == 0\n end\n end\n if count.values.reduce(:+).zero?\n result\n else\n []\n end\nend",
"def test_graph_edges\n test_g = Graph.new\n test_g.add_edge(\"a\", \"b\")\n puts \"assert adding edge to a graph adds its nodes too\"\n assert (test_g.contains(\"a\"))\n\n puts \"assert that edges are directed, ie not symmetric relation\"\n assert test_g.has_edge(\"a\",\"b\")\n assert !(test_g.has_edge(\"b\",\"a\"))\n end",
"def topological_sort(vertices)\n in_edge_count = {}\n list = []\n queue = []\n vertices.each do |vertex|\n in_edge_count[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n until queue.empty?\n u = queue.shift\n list << u\n u.out_edges.each do |vertex|\n to_vertex = vertex.to_vertex\n in_edge_count[to_vertex] -= 1\n queue << to_vertex if in_edge_count[to_vertex] == 0\n end\n end\n list\nend",
"def growEqualityGraph(s_vertices, t_vertices, s_neighbors, s_neighbors_not_in_t) #weights, s_vertices, t_vertices, s_neighbors_not_in_t, s_neighbors)\n\t\t\n\t\t#update labels\n\t\t\n\t\t\n\t\tlabelUpdateVal = nil\n\t\t\n\t\t#We want to grow T in order to up the chance we can have a match\n\t\t\n\t\tunconnected_y_vertices = @y_vertices - t_vertices\n\t\t\n\t\tputs \"Update labels, matching some thing in S #{s_vertices.to_a} and not T #{unconnected_y_vertices.to_a}\" if DEBUG_OUTPUT\n\t\t\t\t\t\t\t\n\t\ts_vertices.each do |xIdx|\n\t\t\tunconnected_y_vertices.each do |y|\n\t\t\t\t\t\n\t\t\t\tyIdx = yIdx(y)\n\t\t#\t\t\t\t\t\t\n\t\t\t\tnext if @weights[xIdx][yIdx] == nil\n\t\t\t\t#puts \"looking at #{x} #{xIdx} #{y} #{yIdx} ..label vals #{labelX[xIdx]} + #{labelY[yIdx]} - weights[xIdx][yIdx]\" if DEBUG_OUTPUT\n\t\t\t\tcandidate = @labelX[xIdx] + @labelY[yIdx] - @weights[xIdx][yIdx]\n\t\t\t\tlabelUpdateVal = candidate if labelUpdateVal == nil || candidate < labelUpdateVal\n\t\t\tend\n\t\tend\n\t\t\t\n\t\t#Todo probably the cells matching candidate and exactly\n\t\t#the ones that are the new lines in the equality subgraph\n\t\t\n\t\tputs \"Label Updating Value #{labelUpdateVal}\" if DEBUG_OUTPUT\n\t\t\t\n\t\t\t#Now adjust the label values accordingly\n\t\t#\t\t\t\t#This adjustment will keep the equality graph the same but add an edge\n\t\ts_vertices.each do |xIdx|\n\t\t\t@labelX[xIdx] -= labelUpdateVal\n\t\tend\n\t\t\t\n\t\tt_vertices.each do |y|\t\t\n\t\t\t@labelY[yIdx(y)] += labelUpdateVal\n\t\tend\n\t\t\t\t\t\n\t\t#@edges = Set.new\n\t\t#puts \"Arg: #{@edges.to_a}\" if DEBUG_OUTPUT\n\t\t\n\t\t#New eq graph has same edges if x is part of s && y is part of t or\n\t\t#if x,y not part s,t respectively\n\t\t#so we just have to blow away stuff in s, but not t and t but not s\n\t\t\n\t\tclearEdges\t\t\n#\t\tnot_s_vertices = x_vertices - s_vertices\n#\t\t\n#\t\t@edges.reject! { |e| s_vertices.member?(e[0]) != t_vertices.member?(e[1]) }\n#\t\t\n\t\ts_vertices.each do |x|\n\t\t\tunconnected_y_vertices.each do |y|\n\t\t\t\t#puts \"genEqGraph x=[#{x}] y=[#{y}] weight=#{weights[xIdx][yIdx]} labelX=#{labelX[xIdx]} labelY=#{labelY[yIdx]}\" if DEBUG_OUTPUT\n\t\t\t\tif isEdge(x, y) == true\n\t\t\t\t\tputs \"Adding #{y} to s_neighbors #{s_neighbors.to_a}\" if DEBUG_OUTPUT\n\t\t\t\t\ts_neighbors.add(y)\n\t\t\t\t\ts_neighbors_not_in_t.push(y)\t\t\t\t\t\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tputs \"LabelX #{@labelX}\" if DEBUG_OUTPUT\n\t\tputs \"LabelY #{@labelY}\" if DEBUG_OUTPUT\t\t\n\t\tputs \"New Equality graph\\n#{to_s}\" if DEBUG_OUTPUT\t\t\t\n\t\t\t\t\t\n\tend",
"def test_to_s\n graph = Graph.new\n vertex_a = Vertex.new('a')\n vertex_b = Vertex.new('b')\n vertex_c = Vertex.new('c')\n graph.add_vertex(vertex_a).add_vertex(vertex_b).add_vertex(vertex_c)\n graph.add_edge('a','b').add_edge('c','b')\n\n assert(graph.to_s == 'a=>b,b=>a,b=>c,c=>b')\n end",
"def solve\n graph = Graph.create(words, WordNode)\n graph.connect_nodes(:one_char_diff)\n\n end_node = graph.nodes_hash[end_word]\n start_node = graph.nodes_hash[start_word]\n start_node.cost = 0\n\n heap = Containers::Heap.new { |a, b| (a.cost <=> b.cost) == -1 }\n graph.nodes_hash.each do |k, v|\n heap.push v\n end\n\n puts heap.size\n # puts \"is empty?#{heap.empty?}\"\n until heap.empty? do\n current_node = heap.pop\n puts current_node.value, current_node.cost\n # puts current_node == end_node\n # puts current_node.value, end_node.value\n return graph.path(end_node) if current_node == end_node\n\n current_node.connected_nodes.each do |node|\n\n # puts node.visited\n unless node.visited\n cost = current_node.cost + 1\n if cost < node.cost\n node.cost = cost\n node.parent = current_node\n # puts \"changed parent\"\n # puts node.parent\n end\n end\n end\n\n current_node.visited = true\n end\n end",
"def topological_sort(vertices)\n #Kahn's Algorithm\n #queue keeps the nodes that have not been sorted yet\n #whatever is popped off the stack goes to sorted and is done\n queue = []\n sorted = []\n\n #loop through vertices\n vertices.each do |vertex|\n #find vertices with no dependencies and push to queue\n queue << vertex if vertex.in_edges.empty?\n end\n\n #pop off from queue and check the out edges of each\n #after pop, delete the vertex all its out edges\n #push that vertex into the sorted array\n #look at each of the destination nodes and push them onto queue if no in edges\n #do this until the queue is empty\n until queue.empty?\n curr_node = queue.shift\n\n sorted << curr_node\n to_vertices = []\n\n #grabs all the vertices connected to the out edges of the curr_node\n curr_node.out_edges.reverse.each do |out_edge|\n # until curr_node.out_edges.empty?\n\n\n # p out_edge.to_vertex.value\n to_vertices << out_edge.to_vertex\n\n #destroy the edge after using it up\n #destroy not working like how I thought it would, maybe save destroy for after\n\n # out_edge.destroy!\n out_edge.destroy!\n end\n\n #need to check if these vertices are connected to anything after\n #curr_node's out edge deletion\n to_vertices.each do |vertex|\n queue << vertex if vertex.in_edges.empty?\n end\n\n #check all vertices connected by curr_node's out_edges\n #if those\n end\n\n if sorted.length == vertices.length\n return sorted\n else\n return []\n end\n\n \n # easy_read = []\n # sorted.each do |vertex|\n # easy_read << vertex.value\n # end\n # p easy_read\n\n\n\n #Tarjan's Algorithm\nend",
"def alg; end",
"def test_in_edges_on_examples\n assert_equal(@small_dfa.ith_edges(4), @small_dfa.in_edges(0,true))\n assert_equal(@small_dfa.ith_edges(0,5), @small_dfa.in_edges(1,true))\n assert_equal(@small_dfa.ith_edges(1,3), @small_dfa.in_edges(2,true))\n assert_equal(@small_dfa.ith_edges(2), @small_dfa.in_edges(3,true))\n\n assert_equal(@small_nfa.ith_edges(5), @small_nfa.in_edges(0,true))\n assert_equal(@small_nfa.ith_edges(0,1,6), @small_nfa.in_edges(1,true))\n assert_equal(@small_nfa.ith_edges(2), @small_nfa.in_edges(2,true))\n assert_equal(@small_nfa.ith_edges(3,4), @small_nfa.in_edges(3,true))\n end",
"def test_complex_cyclic_graph_acyclic_and_cyclic\n g = Graph.new\n a = Node.new('a')\n b = Node.new('b')\n c = Node.new('c')\n d = Node.new('d')\n e = Node.new('e')\n f = Node.new('f')\n g.add_node(a)\n g.add_node(b)\n g.add_node(c)\n g.add_node(d)\n g.add_node(e)\n g.add_node(f)\n a.add_edge(Edge.new(a, b))\n a.add_edge(Edge.new(a, c))\n b.add_edge(Edge.new(b, c))\n b.add_edge(Edge.new(b, d))\n c.add_edge(Edge.new(c, d))\n c.add_edge(Edge.new(c, e))\n e.add_edge(Edge.new(e, d))\n d.add_edge(Edge.new(d, f))\n f.add_edge(Edge.new(f, e))\n assert_equal false, g.acyclic?\n assert_equal true, g.cyclic?\n end",
"def build_assignment_graph(layer)\n\t\th = @via_positions.length\n\t\tfail if (h == 0) || h.odd?\n\t\tfail if @start_node.pads.min < 0 || @start_node.pads.max >= @layer_count\n\t\tfail if @end_node.pads.min < 0 || @end_node.pads.max >= @layer_count\n\t\tvia_count = h / 2\n\t\tputs via_count\n\t\tlayers = 0..(@layer_count - 1) \n\t\tcolums = 0..(via_count * 2) # F O F O F for via_count == 2 \n\t\t#vp = @via_positions.dup # x,y pairs\n\t\t#vp.unshift(@start_node.y)\n\t\t#vp.unshift(@start_node.x)\n\t\tvp = [@start_node.x, @start_node.y] + @via_positions\n\t\tm = Array.new(@layer_count){Array.new(via_count * 2 + 1)}\n\t\tfor i in colums # from T back to S\n\t\t\tif i.even?\n\t\t\t\ty = vp.pop\n\t\t\t\tx = vp.pop\n\t\t\tend\n\t\t\tfor j in layers\n\t\t\t\tl = Array.new\n\t\t\t\tif i.even? # forward\n\t\t\t\t\tk = i + 1\n\t\t\t\t\twhile k > 0\n\t\t\t\t\t\tk -= 2\n\t\t\t\t\t\tif k == -1 # link forward node to T node\n\t\t\t\t\t\t\tl << @end_node if @end_node.pads.include?(j)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (h = m[j][k])\n\t\t\t\t\t\t\t\tl << h # link to up/down node \n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = F_node.new(x, y, j, l)\n\t\t\t\t\t\tl.each{|el|\n\t\t\t\t\t\t#unless @segment_list.index{|m| m.x1 == && m.y1 == el.y1 & m.x2 == el.x2 && m.y2 == el.y2}\n\t\t\t\t\t\t\t@segment_list << Segment.new(x, y, el.x, el.y)\n\t\t\t\t\t\t}\n\t\t\t\t\tend\n\t\t\t\telse #up/down\n\t\t\t\t\tfor k in layers do\n\t\t\t\t\t\tif (k != j) && (h = m[k][i - 1])\n\t\t\t\t\t\t\tl << h\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = V_node.new(x, y, j, l)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t#puts @segment_list.length\n\t\t@segment_list.uniq!{|el| [el.x1, el.y1, el.x2, el.y2]}\n\t\tputs @segment_list.length\n\t\t@all_intersecting_segments = Array.new\n\t\t@segment_list.each{|el|\n\t\t\t@all_intersecting_segments += el.intersecting_segments\n\t\t}\n\t\t@all_intersecting_segments.uniq!\n\n\t\tfor j in layers\n\t\t\tif (h = m[j][-1]) && @start_node.pads.include?(j)\n\t\t\t\t@start_node.next << h\n\t\t\tend\n\t\tend\n\tend",
"def create_full_graph(spec_edges)\n create_sub_graph(spec_edges, $game_map.width+$game_map.height)\n end",
"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 tight? graph, rank\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 test\n puts 'Building Graph for tests...'\n # Simple graph\n #\n # First\n # / \\\n # second third\n # / | | \\\n # fourth fifth goal sixth\n #\n # Construct graph\n first = GraphNode.new 'First'\n second = GraphNode.new 'Second'\n third = GraphNode.new 'Third'\n fourth = GraphNode.new 'Fourth'\n fifth = GraphNode.new 'Fifth'\n sixth = GraphNode.new 'Sixth'\n goal = GraphNode.new 'Goal'\n\n first.connect second\n first.connect third\n\n second.connect first\n second.connect fourth\n second.connect fifth\n\n third.connect first\n third.connect goal\n third.connect sixth\n\n fourth.connect second\n fifth.connect second\n\n goal.connect third\n sixth.connect third\n\n # Perform tests\n puts \"Testing from root node 'First'\"\n puts(bfs(first) { |node| puts ' ' + node })\n\n puts \"Testing from second node 'Second'\"\n puts(bfs(second) { |node| puts ' ' + node })\nend",
"def test_complex_acyclic_graph_acyclic_and_cyclic\n g = Graph.new\n a = Node.new('a')\n b = Node.new('b')\n c = Node.new('c')\n d = Node.new('d')\n e = Node.new('e')\n g.add_node(a)\n g.add_node(b)\n g.add_node(c)\n g.add_node(d)\n g.add_node(e)\n a.add_edge(Edge.new(a, b))\n a.add_edge(Edge.new(a, c))\n b.add_edge(Edge.new(b, c))\n b.add_edge(Edge.new(b, d))\n c.add_edge(Edge.new(c, d))\n c.add_edge(Edge.new(c, e))\n e.add_edge(Edge.new(e, d))\n assert_equal true, g.acyclic?\n assert_equal false, g.cyclic?\n end",
"def topological_sort(vertices)\n edge_count = {}\n sorted = []\n queue = []\n vertices.each do |vertex|\n edge_count[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n until queue.empty?\n current = queue.shift\n sorted << current\n current.out_edges.each do |edge|\n destination = edge.to_vertex\n edge_count[destination] -= 1\n queue << destination if edge_count[destination] == 0\n end\n\n end\n sorted\nend",
"def topological_sort(vertices)\n vertex_queue = []\n sorted_queue = []\n\n vertex_count = {}\n\n #vertex queue has vertex which do not have any in_edges\n vertices.each do |vertex|\n vertex_count[vertex] = vertex.in_edges.count\n vertex_queue << vertex if vertex.in_edges.empty?\n end\n\n # while !vertex_queue.empty?\n until vetex_queue.empty?\n new_vertex = vertex_queue.shift\n sorted_queue << new_vertex\n\n new_vertex.out_edges.each do |out|\n to_vertex = out.to_vertex\n\n vertex_count[to_vertex] -= 1\n vertex_queue << to_vertex if vertex_count[to_vertex] == 0\n end\n end\n sorted_queue\nend",
"def test_graph_to_s_incomplete\n sut_graph = Graph.new\n sut_graph.name=\"test_graph\" \n #sut_graph.type=:digraph\n sut_graph.node_style=:ellipse\n \n sut_graph.add_edge(\"TEST1\" , \"TEST2\" , \"take_me_to_test_2\")\n assert_raises RuntimeError do\n returned_obj = sut_graph.to_s\n end # end assert\n end",
"def test_out_edges_on_examples\n assert_equal(@small_dfa.ith_edges(0), @small_dfa.out_edges(0,true))\n assert_equal(@small_dfa.ith_edges(1,2,5), @small_dfa.out_edges(1,true))\n assert_equal(@small_dfa.ith_edges(4), @small_dfa.out_edges(2,true))\n assert_equal(@small_dfa.ith_edges(3), @small_dfa.out_edges(3,true))\n\n assert_equal(@small_nfa.ith_edges(0), @small_nfa.out_edges(0,true))\n assert_equal(@small_nfa.ith_edges(1,2,3), @small_nfa.out_edges(1,true))\n assert_equal(@small_nfa.ith_edges(4,6), @small_nfa.out_edges(2,true))\n assert_equal(@small_nfa.ith_edges(5), @small_nfa.out_edges(3,true))\n end",
"def fewest_edges(start, finish)\n queue = [start]\n path, dequeue = [], []\n visited, distance, previous = {}, {}, {}\n infinity = (2**(0.size * 8 - 2) - 1) # max Fixnum integer value\n adj_lists.each do |v|\n visited[v.name] = false\n distance[v.name] = infinity\n previous[v.name] = nil\n end\n distance[start] = 0\n cyclic = start == finish # if start/end with same vertex\n visited[start] = true if !cyclic\n loops = 0\n\n while !queue.empty?\n loops += 1\n current = queue.shift # queue is FIFO\n dequeue << current # array of dequeued vertices\n puts \"\\ncurrent = #{current}, queue = #{queue}\"\n\n if current == finish\n break if !cyclic\n break if loops > 1 # if cyclic\n end\n\n adj_vertices(current, adj_lists).each do |adj_vertex|\n if !visited[adj_vertex]\n visited[adj_vertex] = true\n queue << adj_vertex\n distance[adj_vertex] = distance[current] + 1\n previous[adj_vertex] = current\n puts \"adjacent vertex = #{adj_vertex}, queue = #{queue}\"\n # print \"visited = #{visited}\\n\"\n # print \"distance = #{distance}\\n\"\n end\n end\n end\n print_graph\n print \"Dequeued vertices: #{dequeue}\\n\"\n path = [finish]\n vname = finish\n while previous[vname]\n path << previous[vname]\n vname = previous[vname]\n previous[start] = nil if cyclic\n end\n path = path.reverse\n puts \"\\nShortest distance from #{start} to #{finish}: #{distance[finish]} edges.\"\n print \"Path: #{path}\\n\\n\"\n\n distance[finish]\n end",
"def bellman_ford(graph, s)\n paths = Hash.new\n\n # initialization\n graph.each do |vertex, _|\n paths[vertex] = Hash.new\n paths[vertex][:distance] = Float::INFINITY\n paths[vertex][:parent] = nil\n end\n\n paths[s][:distance] = 0\n\n # Even though there are three nested loops, it only takes (V - 1)(E) time\n (1...graph.length).each do # iterating (V - 1) times\n graph.each do |vertex, _|\n graph[vertex].each do |neighbor|\n # technique of relaxation - for an edge (u, v), compare v.distance > (u.distance + weight(u, v))\n if paths[neighbor[0]][:distance] > (paths[vertex][:distance] + neighbor[1])\n paths[neighbor[0]][:distance] = paths[vertex][:distance] + neighbor[1]\n paths[neighbor[0]][:parent] = vertex\n end\n end\n end\n end\n\n graph.each do |vertex, _|\n graph[vertex].each do |neighbor|\n if paths[neighbor[0]][:distance] > (paths[vertex][:distance] + neighbor[1])\n return false\n end\n end\n end\n\n paths\n\nend",
"def test_edges_on_examples\n assert_equal(6,@small_dfa.edges.size)\n assert_equal(7,@small_nfa.edges.size)\n end",
"def test_ith_edges_on_examples\n assert_equal(@small_dfa.edges, @small_dfa.ith_edges(0,1,2,3,4,5))\n assert_equal([@small_dfa.ith_edge(1)], @small_dfa.ith_edges(1))\n assert_equal([@small_dfa.ith_edge(1), @small_dfa.ith_edge(4)], @small_dfa.ith_edges(1,4))\n assert_equal(@small_nfa.edges, @small_nfa.ith_edges(0,1,2,3,4,5,6))\n assert_equal([@small_nfa.ith_edge(1)], @small_nfa.ith_edges(1))\n assert_equal([@small_nfa.ith_edge(1), @small_nfa.ith_edge(4)], @small_nfa.ith_edges(1,4))\n end",
"def test_make_graph\n\t\ttest_main = Main.new(3, 4, 6)\n\t\ttest_graph = Graph.new(10)\n\t\ttest_graph = test_main.make_graph(test_graph)\n\t\tassert_equal test_graph.get_loc(\"Matzburg\").paths.length, 4\n\tend",
"def graphit\n ticks = %w(▁ ▂ ▃ ▄ ▅ ▆ ▇)\n distance = @data.max.to_f / ticks.size\n puts @data.map { |x| compute(x, distance) <= 0 ? ticks[0] : ticks[compute(x, distance)] }.join('')\n end",
"def gamma_decomposition\n k = 0; comparability=true; classification={}\n edges.map {|edge| [edge.source,edge.target]}.each do |e|\n if classification[e].nil?\n k += 1\n classification[e] = k; classification[e.reverse] = -k\n comparability &&= plexus_comparability_explore(e, k, classification)\n end\n end; [classification, comparability]\n end",
"def topological_sort(vertices)\n order = []\n explored = Set.new\n\n vertices.each do |vertex|\n dfs!(order, explored, vertex) unless explored.include?(vertex)\n end\n\n order\nend",
"def equal_by_tree?(graph_obj1, graph_obj2)\n check_pre((graph_obj?(graph_obj1) and graph_obj?(graph_obj2)))\n if (not equal_by_dim?(graph_obj1, graph_obj2)) then false\n elsif graph_obj1.union1d? and graph_obj2.union1d? then equal_by_tree?(graph_obj1.left, graph_obj2.left) and \n equal_by_tree?(graph_obj1.right, graph_obj2.right)\n# elsif (range1d?(graph_obj1) and range1d?(graph_obj2)) or\n# (point1d?(graph_obj1) and point1d?(graph_obj2)) then (graph_obj1 == graph_obj2)\n elsif graph_obj1.union2d? and graph_obj2.union2d? then equal_by_tree?(graph_obj1.left, graph_obj2.left) and \n equal_by_tree?(graph_obj1.right, graph_obj2.right)\n elsif (graph_obj1.range2d? and graph_obj2.range2d?) or \n (graph_obj1.point2d? and graph_obj2.point2d?) or\n (range1d?(graph_obj1) and range1d?(graph_obj2)) or\n (point1d?(graph_obj1) and point1d?(graph_obj2)) then true\n \n# (graph_obj1.x_range == graph_obj2.x_range) and\n# (graph_obj1.y_range == graph_obj2.y_range)\n# elsif (graph_obj1.point2d? and graph_obj2.point2d?) then (graph_obj1.x == graph_obj2.x) and (graph_obj1.y == graph_obj2.y)\n else false\n end\nend",
"def test_has_edges\n graph = Graph.new\n vertex_a = Vertex.new('a')\n vertex_b = Vertex.new('b')\n vertex_c = Vertex.new('c')\n graph.add_vertex(vertex_a).add_vertex(vertex_b).add_vertex(vertex_c)\n graph.add_edge('b','c')\n\n assert(graph.has_edges() == true)\n end",
"def test_has_edges_vertices_only\n vertex_a = Vertex.new('a')\n vertex_b = Vertex.new('b')\n vertex_c = Vertex.new('c')\n graph = Graph.new\n graph.add_vertex(vertex_a).add_vertex(vertex_b).add_vertex(vertex_c)\n\n assert(graph.has_edges() == false)\n end",
"def topological_sort(vertices) # Kahn's Algorithm. Queue is breadth first search\n sorted = []\n top_queue = []\n in_edge_count = Hash.new(0)\n vertices.each do |vertex|\n in_edge_count[vertex] = vertex.in_edges.length\n top_queue.unshift(vertex) if vertex.in_edges.empty?\n end\n until top_queue.empty?\n # debugger\n current = top_queue.pop\n sorted << current\n current.out_edges.each do |edge|\n top_queue.unshift(edge.to_vertex) if in_edge_count[edge.to_vertex] <= 1\n in_edge_count[edge.to_vertex] -= 1\n end\n # current.destroy!\n\n end\n if sorted.length == vertices.length\n return sorted\n else\n return []\n end\nend",
"def run(g)\n\tedges = g.edges\n\tvertics = g.vertics\n\tlast_finished = nil\n\tvisited = []\n\tvertics.each do |u|\n\t\tif !visited.include? u\n\t\t\tdfs(u, edges, visited)\n\t\t\tlast_finished = u\n\t\tend\n\tend\n\tvisited = []\n\tdfs(last_finished, edges, visited)\n\tif vertics.size == visited.size\n\tp \"mother vertex: #{last_finished}\"\n\tend\nend",
"def topological_sort(vertices)\n in_edge_counts = {}\n sorted = []\n queue = []\n\n vertices.each do |vertex|\n in_edge_counts[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n\n until queue.empty?\n current = queue.shift\n sorted << current\n\n current.out_edges.each do |edge|\n in_edge_counts[edge.to_vertex] -= 1\n queue << edge.to_vertex if in_edge_counts[edge.to_vertex] == 0\n end\n\n end\n\n sorted.length == 2 ? [] : sorted\nend",
"def topological_sort(vertices)\n #Khan's\n sorted = []\n top = []\n has_in_edges = {}\n\n # O(|v|) time\n #take vertex if it has no in-edges\n vertices.each do |vertex|\n has_in_edges[vertex] = vertex.in_edges.length\n if vertex.in_edges.empty?\n top.push(vertex)\n end\n end\n\n # O(|e| set) time\n until top.empty?\n current = top.shift\n sorted.push(current)\n current.out_edges.each do |edge|\n to_vertex = edge.to_vertex\n has_in_edges[to_vertex] -= 1\n if has_in_edges[to_vertex] == 0\n top.push(to_vertex)\n end\n end\n\n end\n\n return sorted if sorted.length == vertices.length\n []\nend",
"def topological_sort(vertices)\n in_edge_store = {}\n queue = []\n\n vertices.each do |vertex|\n in_edge_store[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n\n ordered_vertices = []\n until queue.empty?\n current_vertex = queue.shift\n ordered_vertices << current_vertex\n current_vertex.out_edges.each do |edge|\n next_vertex = edge.to_vertex\n in_edge_store[next_vertex] -= 1\n queue << next_vertex if in_edge_store[next_vertex] == 0\n end\n end\n\n ordered_vertices\nend",
"def topological_sort(vertices)\n order = []\n explored = Set.new\n temp = Set.new\n cycle = false\n\n vertices.each do |vertex|\n cycle = dfs!(order, explored, vertex) unless explored.include?(vertex)\n return [] if cycle\n end\n\n order\nend",
"def dfs(graph)\n visited = Hash.new\n\n graph.each do |vertex, _|\n visited[vertex] = Hash.new\n visited[vertex][:state] = \"not visited\"\n end\n\n # This is to enable passing by reference in the dfs_visit method, otherwise\n # simply having a variable for integer will get passed by value and does not\n # behave/increment as expected.\n order = Hash.new\n order[:time] = 0\n\n graph.each do |vertex, _|\n dfs_visit(graph, vertex, visited, order) unless visited[vertex][:state] == \"done\"\n end\n\n visited\nend",
"def graphs(n)\n {\n 'cpu' =>\n \"groupByNode(collectd.#{name(n)}.cpu.*.cpu.*.value, 5, 'sumSeries')\",\n\n 'memory' =>\n \"groupByNode(collectd.#{name(n)}.memory.memory.*.value,4,'sumSeries')\",\n\n 'interface_if_octets_rx' =>\n \"groupByNode(collectd.#{name(n)}.interface.if_octets.*.rx,4,'sumSeries')\",\n\n 'interface_if_octets_tx' =>\n \"groupByNode(collectd.#{name(n)}.interface.if_octets.*.tx,4,'sumSeries')\",\n\n 'qmail_filecount_files' =>\n \"groupByNode(collectd.#{name(n)}.filecount.*.files.value,3,'sumSeries')\",\n\n 'qmail_filecount_files_stacked' =>\n \"groupByNode(collectd.*.filecount.*.files.value,1,'sumSeries')\",\n\n 'qmail_filecount_files_derivative' =>\n \"groupByNode(collectd.#{name(n)}.filecount.*.files.value,3,'derivative')\",\n\n 'qmail_filecount_files_derivative_stacked' =>\n \"groupByNode(collectd.*.filecount.*.files.value,1,'derivative')\",\n\n 'qmail_filecount_files_integral' =>\n \"groupByNode(collectd.#{name(n)}.filecount.*.files.value,3,'integral')\",\n\n 'qmail_filecount_files_integral_stacked' =>\n \"groupByNode(collectd.*.filecount.*.files.value,1,'integral')\",\n\n 'qmail_filecount_size' =>\n \"groupByNode(collectd.#{name(n)}.filecount.*.bytes.value,3,'sumSeries')\",\n\n 'qmail_filecount_size_stacked' =>\n \"groupByNode(collectd.*.filecount.*.bytes.value,1,'sumSeries')\",\n }\n end",
"def topological_sort(vertices)\n sorted = []\n queue = []\n in_edge_counts = {}\n\n vertices.each do |vertex|\n in_edge_counts[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n\n until queue.empty?\n current = queue.shift\n sorted << current\n\n current.out_edges.each do |edge|\n destination = edge.to_vertex\n in_edge_counts[destination] -= 1\n queue << destination if in_edge_counts[destination] == 0\n end\n end\n sorted\nend",
"def create_knight_tour_graph(board_size)\n new_graph = Graph.new()\n board_size.times do |x|\n board_size.times do |y|\n new_graph.add_vertex([x,y])\n end\n end\n knight_legal_moves(new_graph)\n new_graph\nend",
"def test_add_edge_with_cycles\n @graph.add_edge('a', 'b');\n @graph.add_edge('b', 'c');\n @graph.add_edge('c', 'a');\n\n # 0 and 2 are indexes of vertex a and vertex c respectively\n assert(@graph.vertices[0].neighbours[2] == true && @graph.vertices[2].neighbours[0] == true)\n end",
"def test_has_edges_when_empty\n graph = Graph.new\n\n assert(graph.has_edges() == false)\n end",
"def possible_bipartition_VERBOSE(dislikes)\n puts \"\\nADJ LIST = #{dislikes}\"\n # when can we stop? when we visited all the dogs\n # what about friendly dogs? they're exempt\n \n friendlies = dislikes.select do |enemyList|\n enemyList == []\n end\n \n needToVisitThisMany = dislikes.length - friendlies.length\n puts \"NEED TO VISIT THIS MANY: #{needToVisitThisMany}\"\n \n dislikes.length.times do |i|\n puts \"\\nNEW STARTER NODE = #{i}\"\n # start a new scenario with i as the starterNode\n queue = [i]\n visited = {}\n # visited will have key of index# for each dog, and value of T/F for easy flipping back and forth\n \n visited[i] = true\n \n until queue.empty?\n currDog = queue.pop()\n newColor = !visited[currDog]\n puts \"looking at currDog = #{currDog}\"\n \n dislikes[currDog].each do |enemy|\n puts \"\\tenemy = #{enemy}\"\n if visited[enemy].nil?\n visited[enemy] = newColor \n queue << enemy\n elsif visited[enemy] != newColor\n return false\n end\n end\n \n newColor = !newColor if queue.empty?\n end\n \n puts \"visited = #{visited}, ARE WE DONE? #{visited.keys.count} == #{needToVisitThisMany}\"\n return true if visited.keys.count == needToVisitThisMany\n end\n \n return true\nend",
"def topological_sort(vertices)\n num_edges = {}\n queue = []\n\n vertices.each do |vertex|\n num_edges[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n\n sorted = []\n\n while queue.length > 0\n vertex = queue.shift\n sorted.push(vertex)\n\n vertex.out_edges.each do |edge|\n to_vertex = edge.to_vertex\n\n num_edges[to_vertex] -= 1\n if num_edges[to_vertex] == 0\n queue.push(to_vertex)\n end\n end\n end\n\n if sorted.length == vertices.length\n sorted\n else\n []\n end\nend",
"def topological_sort(vertices)\n queue = Queue.new\n sorted_arr = []\n in_edges_count = {}\n\n vertices.each do |vertex|\n queue << vertex if vertex.in_edges.empty?\n in_edges_count[vertex] = vertex.in_edges.length\n end\n\n until queue.empty?\n test_vertex = queue.shift\n\n sorted_arr << test_vertex\n test_vertex.out_edges.each do |edge|\n destination_vertex = edge.to_vertex\n in_edges_count[destination_vertex] -= 1\n queue << destination_vertex if in_edges_count[destination_vertex].zero?\n end\n end\n\n return [] if sorted_arr.length < vertices.length\n sorted_arr\nend",
"def topological_sort(vertices)\n queue = []\n order = []\n in_edge_count = {}\n\n vertices.each do |vertex|\n in_edge_count[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n\n until queue.empty?\n current = queeue.shift\n order << current\n\n current.out_edges.each do |edge|\n to_vert = edge.to_vertex\n in_edge_count[to_vert] -= 1\n queue << to_vert if in_edge_count[to_vert] == 0\n end\n\n end\n\n order.length == vertices.length ? order : []\nend",
"def bfs(g,s)\r\n q = []\r\n dists = Hash.new(Float::INFINITY)\r\n curr = s\r\n dists[curr] = 0\r\n \r\n #q += g[curr].each_index.select {|v| v != s && !dists.include?(v) && g[curr][v] == 1 }.map {|v| [curr,v] }\r\n g[curr].each.with_index {|e,v| q.push [curr,v] if v != s && e == 1 && !dists.include?(v)}\r\n while q.size > 0\r\n \tprev,curr = q.shift\r\n dists[curr] = [6 + dists[prev],dists[curr]].min\r\n #q += g[curr].each_index.select {|v| v != s && !dists.include?(v) && g[curr][v] == 1 }.map {|v| [curr,v] }\r\n g[curr].each.with_index {|e,v| q.push [curr,v] if v != s && e == 1 && !dists.include?(v)}\r\n #prev,curr = q.shift\r\n end\r\n \r\n return dists\r\nend",
"def install_order(arr)\n vertices = {}\n max = 0 \n arr.each do |tuple|\n vertices[tuple[0]] = Vertex.new(tuple[0]) unless verticles[tuple[0]]\n vertices[tuple[1]] = Vertex.new(tuple[1]) unless verticles[tuple[1]]\n # create an edge for each pair \n\n Edge.new(vertices[tuple[1]], vertices[tuple[0]])\n\n max = tuple.max if tuple.max > max \n end \n\n independent = []\n (1..max).each do |i| \n independent << i unless vertices[i]\n end \n\n independent + topological_sort(vertices.values).map { |v| v.value }\nend",
"def topological_sort(vertices)\n out_queue = []\n sorted = []\n sorted_hash = {}\n\n until sorted.length == vertices.length \n out_queue = vertices.select do |v| \n v.in_edges.empty? && !sorted_hash.include?(v.value)\n end\n # Break if Cyclic/Disconnected Graph\n return [] if out_queue.empty?\n\n until out_queue.empty?\n vertice = out_queue.shift\n sorted << vertice\n sorted_hash[vertice.value] = true\n vertice.out_edges[0].destroy! until vertice.out_edges.empty?\n end\n end\n\n sorted\nend",
"def topological_sort(vertices)\n sorted = []\n top = new Queue() \n graph.vertices.each do |vertex|\n if vertex.in_edges.empty? \n top.enqueue(vertex)\n end \n end \nd\n until top.empty? \n current = top.pop \n sorted << current \n current.out_edges.each do |edge|\n if edge.destination.in_edges.empty? \n top.enqueue(edges)\n end \n end \n graph.delete_edge(edge)\n graph.delete_vertex(current); \n end \n\n \n\nend",
"def test_specific_info\n \n # Start a new graph with no vertices\n graph = Graph.new()\n \n # Add 2 vertices to the graph\n origin = { \"code\" => \"NYC\" ,\n \"name\" => \"New York\" ,\n \"country\" => \"US\" ,\n \"continent\" => \"North America\" ,\n \"timezone\" => -5 ,\n \"coordinates\" => { \"N\" => 41, \"W\" => 74 } ,\n \"population\" => 22200000 ,\n \"region\" => 3 }\n \n destination = { \"code\" => \"WAS\" ,\n \"name\" => \"Washington\" ,\n \"country\" => \"US\" ,\n \"continent\" => \"North America\" ,\n \"timezone\" => -5 ,\n \"coordinates\" => {\"N\" => 39, \"W\" => 77} ,\n \"population\" => 8250000 ,\n \"region\" => 3 } \n graph.add_node(origin)\n graph.add_node(destination)\n \n assert_equal(graph.get_specific_info(\"CHI\"), \"City doesn't exist in the graph.\")\n \n # Get information on Washington and check that correct information is\n # contained in the return value\n info = graph.get_specific_info(\"WAS\")\n \n assert_equal( info.include?(\"WAS\"), true )\n assert_equal( info.include?(\"Washington\"), true )\n assert_equal( info.include?(\"US\"), true )\n assert_equal( info.include?(\"North America\"), true )\n assert_equal( info.include?(\"N 39, W 77\"), true )\n assert_equal( info.include?(\"Population: 8250000\"), true )\n assert_equal( info.include?(\"Region: 3\"), true )\n assert_equal( info.include?(\"Direct Connections: WAS\"), false )\n \n # Add an edge and check if that information is reflected in the return value\n graph.add_edge(\"NYC\",\"WAS\" ,570)\n info = graph.get_specific_info(\"NYC\")\n \n assert_equal( info.include?(\"Direct Connections: WAS - 570\"), true)\n\n end",
"def topological_sort(vertices)\n queue = vertices.select { |node| node.in_edges.length == 0 }\n ordered_list = []\n\n degree = {}\n vertices.each { |node| degree[node.value] = node.in_edges.length }\n\n until queue.empty?\n curr_node = queue.pop\n ordered_list << curr_node\n\n curr_node.out_edges .map { |edge| edge.to_vertex }\n .each { |child| degree[child.value] -= 1 }\n\n queue = vertices.select do |node|\n degree[node.value] == 0 && !queue.include?(node) && !ordered_list.include?(node)\n end + queue\n end\n\n return degree.all? { |_, v| v == 0 } ? ordered_list : []\nend",
"def topological_sort(vertices)\n queue = []\n result = []\n\n vertices.each do |vertex|\n if vertex.in_edges.empty?\n queue.push(vertex)\n end\n end\n\n until queue.empty?\n vertex = queue.shift\n result << vertex\n\n vertex.out_edges.dup.each do |edge|\n if edge.to_vertex.in_edges.length == 1\n queue.push(edge.to_vertex) \n end\n edge.destroy!\n end\n end\n \n if vertices.length == result.length\n return result\n else\n return []\n end\nend",
"def topological_sort(vertices)\n next_vertex = Queue.new\n result = []\n vertices.each do |vertex|\n next_vertex.push(vertex) if vertex.in_edges.length < 1\n end\n\n while !next_vertex.empty?\n vertex = next_vertex.pop\n vertex.out_edges.each do |edge|\n new_vertex = edge.to_vertex\n next_vertex.push(new_vertex) if new_vertex.in_edges.length <= 1\n end\n vertex.out_edges.each{|edge| edge.destroy!}\n result.push(vertex)\n end\n result\nend",
"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 depth_first_search\n visited = {}\n timestamp = {}\n tree_edges = {}\n back_edges = {}\n cross_edges = {}\n forward_edges = {}\n count = 0\n\n # begin workaround removing depencency to order of Hash#each\n if @index.empty? then\n preference_of_nodes = nil\n else\n preference_of_nodes = {}.merge(@index)\n i = preference_of_nodes.values.max\n @graph.each_key do |node0|\n preference_of_nodes[node0] ||= (i += 1)\n end\n end\n # end workaround removing depencency to order of Hash#each\n\n dfs_visit = Proc.new { |from|\n visited[from] = true\n timestamp[from] = [count += 1]\n ary = @graph[from].keys\n # begin workaround removing depencency to order of Hash#each\n if preference_of_nodes then\n ary = ary.sort_by { |node0| preference_of_nodes[node0] }\n end\n # end workaround removing depencency to order of Hash#each\n ary.each do |to|\n if visited[to]\n if timestamp[to].size > 1\n if timestamp[from].first < timestamp[to].first\n \t# forward edge (black)\n \tp \"#{from} -> #{to} : forward edge\" if $DEBUG\n \tforward_edges[from] = to\n else\n \t# cross edge (black)\n \tp \"#{from} -> #{to} : cross edge\" if $DEBUG\n \tcross_edges[from] = to\n end\n else\n # back edge (gray)\n p \"#{from} -> #{to} : back edge\" if $DEBUG\n back_edges[from] = to\n end\n else\n # tree edge (white)\n p \"#{from} -> #{to} : tree edge\" if $DEBUG\n tree_edges[to] = from\n dfs_visit.call(to)\n end\n end\n timestamp[from].push(count += 1)\n }\n\n ary = @graph.keys\n # begin workaround removing depencency to order of Hash#each\n if preference_of_nodes then\n ary = ary.sort_by { |node0| preference_of_nodes[node0] }\n end\n # end workaround removing depencency to order of Hash#each\n ary.each do |node|\n unless visited[node]\n dfs_visit.call(node)\n end\n end\n return timestamp, tree_edges, back_edges, cross_edges, forward_edges\n end",
"def simple_graph(vertices, klass = MiniGraphdb::Node)\n nodes = Hash.new { |hsh, k| hsh[k] = klass.new(val: k) }\n\n vertices.each do |a_node, other_node|\n nodes[a_node].r_edge nodes[other_node]\n end\n\n def nodes.print_graph\n values.each do |node|\n edges = node.edges.byweight.map(&:val).join(\", \")\n puts \"#{node.val} => #{edges}\"\n end\n end\n\n nodes\n end",
"def strongly_connected_components\n\t\t@explored_nodes = Array.new(size, false)\n\t\t@finishing_time_arr = Array.new(size)\n\t\t@scc = Array.new\n\t\t@dfs_queue = Array.new\n\t\t@finishing_time_queue = Array.new\n\t\t@finishing_time = 0\n\t\tcalculate_finishing_time\n\t\t@leaders = scc_call_order\n\t\tcalculate_scc\n\t\tputs \"#{@scc.map(&:count).sort.reverse.take(5)}\"\n\tend",
"def test_has_edge_no_edge\n assert(@graph.has_edge('b', 'd') == false)\n end",
"def topological_sort(vertices)\n in_edge_count = {}\n queue = []\n visited = {}\n vertices.each do |vertex|\n in_edge_count[vertex] = vertex.in_edges.count\n queue << vertex if vertex.in_edges.empty?\n end\n sorted = []\n\n until queue.empty?\n vertex = queue.pop\n sorted << vertex\n\n vertex.out_edges.each do |edge|\n to_vertex = edge.to_vertex\n in_edge_count[to_vertex] -= 1\n queue << to_vertex if in_edge_count[to_vertex] == 0\n end\n end\n sorted.length == vertices.length ? sorted : []\nend",
"def topological_sort(vertices)\n order = []\n explored = Set.new\n temp = Set.new\n cycle = false\n vertices.each do |vertex|\n cycle = dfs!(order,explored,vertex,temp,cycle) unless explored.include?(vertex)\n return [] if cycle\n end\n order\nend",
"def test_to_s_only_vertices\n graph = Graph.new\n vertex_a = Vertex.new('a')\n vertex_b = Vertex.new('b')\n vertex_c = Vertex.new('c')\n graph.add_vertex(vertex_a).add_vertex(vertex_b).add_vertex(vertex_c)\n\n assert(graph.to_s == 'a=>,b=>,c=>')\n end",
"def test_graph_to_s\n sut_graph = Graph.new\n sut_graph.name=\"test_graph\" \n sut_graph.type=:digraph\n sut_graph.node_style=:ellipse\n #sut_graph.add_node \"TEST1\"\n #sut_graph.add_node \"TEST2\"\n sut_graph.add_edge(\"TEST1\" , \"TEST2\" , \"take_me_to_test_2\")\n \n \n returned_obj = sut_graph.to_s\n assert( returned_obj.instance_of?(String) , \"Check to_s returns String, returns: #{returned_obj.class}\" )\n assert(returned_obj.scan(/test_graph/).length==1 , \"Check once occurence of graph name in dot to_s.\")\n assert(returned_obj.scan(/digraph test_graph/).length==1 , \"Check graph type and name in dot to_s.\") \n assert(returned_obj.scan(/shape = ellipse/).length==1 , \"Check graph node style in dot to_s.\") \n #assert(returned_obj.scan(/TEST1\\;/).length==1 , \"Check that Node definition is included: TEST1;\")\n #assert(returned_obj.scan(/TEST2\\;/).length==1 , \"Check that Node definition is included: TEST2}\")\n assert(returned_obj.scan(/label = \\\"take_me_to_test_2\"/).length==1 , \"Check that arc label is included\")\n \n end",
"def printResult(edges)\n sum = 0\n graph = []\n edges.each do |k,v|\n edges[k].each do |key,value|\n sum += value\n graph << \"#{k}#{key}\"\n edges[key].delete(k)\n end\n end\n p sum\n p graph\n end",
"def k_topological_sort(vertices)\n topological_order = []\n\n degrees = {}\n #count the number of in edges for each vertex O(|V|)\n vertices.each { |vertex| degrees[vertex] = vertex.in_edges.length }\n\n #Select those with no in edges\n queue = degrees.select { |vertex, length| length == 0 }.keys\n\n until queue.empty?\n topological_order.push(queue.pop)\n\n #for each out edge, decrement the to vertexes incoming\n #edge count by one\n vertex.out_edges.each do |edge|\n degrees[edge.to_vertex] -= 1\n\n #If there are no more in edges, add it to the queue!\n if degrees[edge.to_vertex] == 0\n queue.unshift(edge.to_vertex)\n end\n end\n end\n #When there is a cycle, the queue will be empty before each node will\n #have been checked; therefore the results array will equal\n #the vertex array iff there is a topological ordering.\n if topological_order.length == vertices.length\n topological_order\n else\n []\n end\n end",
"def test_delete_if\n graph = Rgraphum::Graph.new\n (0..9).each do |i|\n graph.vertices << { label: \"v#{i}\" }\n end\n (0..9).each do |i|\n graph.edges << {\n source: graph.vertices[i],\n target: graph.vertices[(i+1) % 10],\n weight: i,\n }\n end\n\n # v0 -> v1 -> v2 -> v3 -> v4 -> v5 -> v6 -> v7 -> v8 -> v9\n # ^ |\n # +-----------------------------------------------------+\n assert_equal 10, graph.vertices.size\n assert_equal 10, graph.edges.size\n graph.vertices do |vertex|\n assert_equal 2, vertex.edges.size\n end\n\n graph.edges.delete_if { |edge| edge.weight.odd? }\n # graph.edges.reject! { |edge| edge.weight.odd? }\n\n # v0 -> v1 v2 -> v3 v4 -> v5 v6 -> v7 v8 -> v9\n assert_equal 10, graph.vertices.size\n assert_equal 5, graph.edges.size, \"edges.size was 10 but deleted 5 edges\"\n\n assert_equal 0, graph.edges[0].weight\n assert_equal 2, graph.edges[1].weight\n assert_equal 4, graph.edges[2].weight\n assert_equal 6, graph.edges[3].weight\n assert_equal 8, graph.edges[4].weight\n\n graph.vertices do |vertex|\n assert_equal 1, vertex.edges.size\n end\n end",
"def n_paths(graph, from)\n counter = { from => 1 }\n graph.topsort.each do |v|\n next if v == from\n in_edges = graph.edges.select { |e| e.target == v && graph.adjacent(v, :direction => :in).include?(e.source) }\n counter[v] = in_edges.map { |e| counter[e.source] }.inject(:+)\n end\n counter\nend",
"def topological_sort(vertices)\n queue = []\n sorted = []\n # keep track of vertex in_edges count so that\n # it doesnt get prematurely pushed into queue\n count = {}\n\n # find started vertexes\n vertices.each do |vertex|\n queue.push(vertex) if vertex.in_edges.empty?\n count[vertex] = vertex.in_edges.count\n end\n\n until queue.empty?\n vertex = queue.shift\n sorted << vertex\n vertex.out_edges.each do |edge|\n vert = edge.to_vertex\n count[vert] -= 1\n queue.push(vert) if count[vert] == 0\n end\n end\n\n sorted.count == vertices.count ? sorted : []\nend",
"def print_graph()\n puts \"Adjacency Matrix\"\n @adjacent_list.each_with_index {|value, index| puts \"#{index} #{value} \\n\" }\n\n puts \"Indegree Matrix\"\n @indegree.each_with_index {|value, index| puts \"#{index} #{value} \\n\" }\n end",
"def best_swap graph\n swap.gain = MIN\n A.each do |a|\n B.each do |b|\n d = a.d + b.d - 2*c(a,b)\n if d > swap.gain\n swap.gain = d\n swap = a,b\n end\n end\n end\n return swap\nend",
"def topological_sort(vertices)\n list = []\n sorted = []\n count_set = {}\n\n vertices.each do |vertex|\n count_set[vertex] = vertex.in_edges.count\n list << vertex if vertex.in_edges.empty?\n end\n\n until list.empty?\n vertex = list.shift\n sorted << vertex\n\n vertex.out_edges.each do |edge|\n to = edge.to_vertex\n count_set[to] -= 1\n list << to if count_set[to] == 0\n end\n end\n\n if sorted.length == vertices.length\n sorted\n else\n []\n end\nend",
"def incomplete_graph(n, completeness)\n g = GraphMatching::Graph::WeightedGraph.new\n 0.upto(n - 1) do |i| g.add_vertex(i) end\n max_weight = ((1..n - 1).reduce(:+).to_f * completeness).to_i + 1\n 0.upto(n - 2) do |i|\n (i + 1).upto(n - 1) do |j|\n next unless rand < completeness\n g.add_edge(i, j)\n w = rand(max_weight)\n g.set_w([i, j], w)\n end\n end\n g\nend",
"def topological_sort(graph)\n queue = []\n graph.each do |vertex|\n queue << vertex if vertex.in_edges.empty?\n end\n sorted_result = []\n until queue.empty?\n curr_vertex = queue.shift\n curr_vertex.out_edges.reverse_each do |edge|\n edge.destroy!\n end\n sorted_result << curr_vertex\n graph.delete(curr_vertex)\n graph.each do |vertex|\n queue << vertex if vertex.in_edges.empty? && !queue.include?(vertex)\n end\n end\n graph.length.zero? ? sorted_result : []\nend",
"def topological_sort(vertices)\n res = []\n queue = []\n vertices.each do |vertex|\n queue << vertex if vertex.in_edges.empty?\n end\n until queue.empty?\n vertex = queue.shift\n res << vertex\n out_edges = vertex.out_edges.dup\n out_edges.each do |edge|\n queue << edge.to_vertex if edge.to_vertex.in_edges.length == 1\n edge.destroy!\n end\n end\n res\nend"
] | [
"0.64346105",
"0.6398724",
"0.6208612",
"0.6197937",
"0.61747503",
"0.6088391",
"0.6077693",
"0.6058904",
"0.6004932",
"0.59683543",
"0.5968108",
"0.596783",
"0.5966691",
"0.59432596",
"0.586969",
"0.5836332",
"0.5834974",
"0.58266145",
"0.58245474",
"0.58133066",
"0.58031946",
"0.5788417",
"0.57837903",
"0.57781607",
"0.5774184",
"0.5765328",
"0.575655",
"0.57562566",
"0.57338226",
"0.57326204",
"0.57261604",
"0.57208",
"0.5708564",
"0.5705054",
"0.570236",
"0.57021517",
"0.569908",
"0.5689141",
"0.56873494",
"0.56856304",
"0.5681855",
"0.5672701",
"0.5655175",
"0.56541663",
"0.5648524",
"0.5627508",
"0.56237084",
"0.56186",
"0.5614943",
"0.5611695",
"0.5602107",
"0.5601402",
"0.55998784",
"0.5592523",
"0.55901265",
"0.5590031",
"0.55868137",
"0.5575586",
"0.5574368",
"0.556591",
"0.5562339",
"0.5555063",
"0.55523044",
"0.55493826",
"0.5528164",
"0.5526187",
"0.5525871",
"0.5521027",
"0.5515898",
"0.55105954",
"0.5508024",
"0.5507048",
"0.5505008",
"0.5497932",
"0.5488559",
"0.5488283",
"0.54848975",
"0.54818213",
"0.5471668",
"0.5454648",
"0.54543144",
"0.54520905",
"0.5448017",
"0.5444533",
"0.5443695",
"0.54426986",
"0.5442533",
"0.54409003",
"0.543983",
"0.5431937",
"0.5430923",
"0.54298115",
"0.5429669",
"0.54271287",
"0.5422726",
"0.54182756",
"0.5411005",
"0.5409069",
"0.5405454",
"0.53951055",
"0.5391217"
] | 0.0 | -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",
"def authorSearch(name)\n matches = @books_in_stock.select {|isbn,book| book.author == name}\n matches.values\n end",
"def show_search\n @book = BookFinder.search_google_books_by_identifier(params[:identifier]) # Instantiate book instance from Google Books search (by Google identifier)\n end",
"def search_books(name = nil, author = nil, price_start = nil, price_end = nil, page_size = nil, page_no = nil)\n query_string = <<QUERY_STRING\n {\n books(name: \\\"#{name}\\\", author: \\\"#{author}\\\"#{', priceStart: ' + price_start.to_s if price_start}#{', priceEed: ' + price_end.to_s if price_end}#{', pageSize: ' + page_size.to_s if page_size}#{', pageNo: ' + page_no.to_s if page_no}) {\n id\n name\n author\n price\n }\n }\nQUERY_STRING\nputs query_string.inspect\n # books(name: \\\"\\\", author: \\\"\\\", priceStart: , priceEnd: 33)\n# byebug\n result_hash = GplTestSchema.execute(query_string)\n puts result_hash.inspect\nend",
"def return_user_books(input)\n @books = GoogleBooks::API.search(@input, :count => 5)\n @books.each do |book|\n if !(book.title.nil? || book.authors.nil? || book.publisher.nil?)\n puts book.title, book.authors, book.publisher, \"\\n\"\n end\n end\n\n def save_book_title\n puts \"If you would like to save a book to your reading list, please type the title of the book you'd like to save.\" .blue\n get_user_book_input(@input)\n book_input = @input\n if book_to_save = @books.find{|book| book.title == book_input }\n GoogleLib::Google_library.all << book_input\n else\n puts \"Please enter a valid title\"\n save_book_title\n end\n end\n end",
"def api_search_by_author(input)\n url = \"https://www.googleapis.com/books/v1/volumes?q=#{input}+inauthor&key=#{API_KEY}\"\n response = RestClient.get(url)\n parsed_response = JSON.parse(response)\n parsed_response\n end",
"def test_search_parse\n br = @b.instance.get(@isbn10)\n assert br.is_a?(BookRenter::BookResult)\n assert br.error.nil?\n end",
"def to_hash\n hash = {\n \"id\" => id,\n \"isbn\" => isbn,\n \"edition_group_id\" => edition_group_id,\n \"author\" => author,\n \"edition\" => edition,\n \"publisher\" => publisher,\n \"cover\" => cover,\n \"image\" => full_image_uri }\n end",
"def book_info_goodreads_library\n client = Goodreads::Client.new(Goodreads.configuration)\n results = client.book_by_title(params[:q])\n rescue\n []\n end",
"def initialize(title, author, isbn)\n @title = title\n @author = author\n @isbn = isbn\nend",
"def isbn(isbn, bookname = \"\")\n isbn1 = isbn.to_s.gsub(/ISBN/i, \"\")\n isbn2 = isbn1.gsub(/-/, \"\")\n\n if bookname == \"\"\n buf = \"\"\n else\n buf = \"#{h(bookname)}\"\n end\n\n aid = @options['amazon.aid'] ? \"/#{@options['amazon.aid']}\" : \"\"\n\n s = \"\"\n s << buf\n s << \"【 \"\n s << make_anchor( \"http://www.amazon.co.jp/exec/obidos/ASIN/#{isbn2}#{aid}/ref=nosim/\", 'amazon' ) + ' / '\n s << make_anchor( \"http://www.bk1.co.jp/search/search.asp?srch=2&kywd=&ti=&au=&pb=&isbn=#{isbn1}&idx=1\", 'bk1' ) + ' / '\n s << make_anchor( \"http://www.netdirect.co.jp/search/ISSSchDetail.asp?ISBN=#{isbn2}\", '旭屋' ) + ' / '\n s << make_anchor( \"http://www.jbook.co.jp/product.asp?isbn=#{isbn2}\", 'Jbook' ) + ' / '\n s << make_anchor( \"http://bookweb.kinokuniya.co.jp/guest/cgi-bin/wshosea.cgi?W-ISBN=#{isbn2}\", '紀伊國屋' ) + ' / '\n s << make_anchor( \"http://www.esbooks.co.jp/bks.svl?CID=BKS504&access_method=isbn_cd&input_data=#{isbn1}\", 'eS!' ) + ' / '\n s << make_anchor( \"http://bsearch.rakuten.co.jp/Btitles?KEY=#{isbn1}\", '楽天' )\n s << \" 】\"\nend",
"def isbn\n return nil unless @marc_record.fields('020')\n isbns = @marc_record.fields('020').map do |field|\n StdNum::ISBN.normalize(field['a'])\n end\n isbns.compact\n end",
"def find_book_by_title(title)\n for book in @books\n if book[:title] == title\n return book\n end\n end\n end",
"def initialize(title, author, isbn)\n @title = title\n @author = author\n @isbn = isbn\n end",
"def create\n # @book = Book.new(book_params)\n\n # respond_to do |format|\n # if @book.save\n # format.html { redirect_to @book, notice: 'Book was successfully created.' }\n # format.json { render action: 'show', status: :created, location: @book }\n # else\n # format.html { render action: 'new' }\n # format.json { render json: @book.errors, status: :unprocessable_entity }\n # end\n # end\n\n\n\n @isbn = params[:book][:ISBN]\n search_term = params[:search] || \"#{@isbn}\"\n @res = Amazon::Ecs.item_lookup(search_term, { :search_index => 'Books', :id_type => \"ISBN\", :response_group => \"ItemAttributes\"})\n @imgs = Amazon::Ecs.item_lookup(search_term, { :search_index => 'Books', :id_type => \"ISBN\", :response_group => 'Images',\n :search_index => 'Books',\n :sort => 'relevancerank' })\n puts @imgs.items.first.get_element('MediumImage').get('URL')\n # need to save author, title, publisher of first returned item\n @new_book = @res.items.first\n @book = Book.new\n @book.title = @res.items.first.get_element('ItemAttributes').get('Title')\n @book.author = @res.items.first.get_element('ItemAttributes').get('Author')\n @book.publisher = @res.items.first.get_element('ItemAttributes').get('Publisher')\n @book.url = @imgs.items.first.get_element('MediumImage').get('URL')\n @book.save\n\n\n end",
"def new\n\n @user = User.find(current_user.id)\n @book = Book.new\n @book.user_id = @user.id\n\n @book = Book.new(:title => params[:rtitle],:author => params[:rauthor], :isbn => params[:risbn])\n # @book = Book.find_by_user_id(@user.id)\n\n isbn = @book.isbn\n user_id = @user.id\n books = Book.find_by_isbn_and_user_id(isbn,user_id)\n if books.nil?\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book }\n end\n else\n redirect_to \"/books/search\"\n flash[:alert] = \"the book '#{@book.title}' already exist - please search for another book!!!\"\n end\n end",
"def initialize(isbn, price) \n self.isbn = isbn \n self.price = price \n end",
"def test_get_book_by_isbn\n data = post_book('isbn' => '9780132990448')\n assert_equal('9780132990448', data[0]['data']['isbn'].to_s)\n end",
"def list_books_w_matching_title(title)\n books = @mybooks.get_books_by_title(title)\n\tbooks.each {|book| puts \"#{book[:key]} | #{book[:author]}, #{book[:title]}\"}\nend",
"def initialize(isbn)\n self.isbn = isbn\n end",
"def isbn(isbn)\n if @isbn.nil?\n @isbn = []\n end\n @isbn << isbn\n end",
"def info_by_title(title)\n for book in @array_of_books\n return book if :title == title\n end\n end",
"def searchisbn\n end",
"def get_book(book_isbn)\n plsql.books.first :book_isbn => book_isbn\n end",
"def rate_books( books )\n ratings_by_isbn = {}\n books.each_slice( 500 ) do |batch|\n begin\n isbns = batch.collect { |book| book.ean }\n url = \"http://www.goodreads.com/book/review_counts.json?isbns=#{isbns.join(',')}&key=#{CONFIG['GOODREADS_KEY']}\"\n data = JSON.parse( open( url ).read )\n data['books'].each do |rating|\n ratings_by_isbn[ rating['isbn13'] ] = rating\n end\n rescue Exception\n puts \"Ooops! #{$!}\"\n end\n end\n books.each do |book|\n if rating = ratings_by_isbn[ book.ean ]\n book.add_rating( rating )\n end\n end\n end",
"def initialize(title,author,isbn)\n @title = title\n @author = author\n @isbn = isbn.to_i\n# @borrow = false\n end",
"def find_books(books, library, stream)\n @library_branch_location = library\n stream << \"data: status: Finding which books are available...\\n\\n\"\n book_available = false\n\n books.each do |book|\n # get related isbns and limit collection to a maximum of 20 ISBNs\n related_isbns = get_related_isbns(book[:isbn])[0...20]\n\n libraries_available = []\n # search through ISBNs, 5 at a time (due to limits on chipublib search),\n # break at first results found\n (0...related_isbns.length).step(5) do |count|\n isbn_search_range = related_isbns[count...count+5]\n isbn_search_string = isbn_search_range.join('+or+')\n\n fetch_result = fetch(\"#{LIBRARY_SEARCH_URL}?&isbn=#{isbn_search_string}&location=#{@library_branch_location}&format=Book&advancedSearch=submitted\")\n\n # unzip\n body = Zlib::GzipReader.new(StringIO.new(fetch_result[:response].body)).read\n\n if fetch_result[:page_type] == \"search\"\n if body.index(LIBRARY_NO_RESULTS_STRING) == nil\n # assemble a collection of results\n page = Nokogiri::HTML(body)\n libraries_available = parse_search_results(page)\n else\n # no results for this book's ISBN(s)\n # puts LIBRARY_NO_RESULTS_STRING\n end\n else # detail, one result for this book's ISBN(s)\n libraries_available = parse_detail(body)\n end\n\n # if it's available at our library, don't bother going through any other ISBNs for this book,\n # just tell me it's available so the next book can be processed\n if libraries_available.include? LIBRARY_MY_STRING; break end\n\n # don't make too many requests too fast :)\n sleep 1/60\n end\n\n # show where the book is available\n html = \"<li><a href='#{book[:url]}' title='#{book[:title]}'>#{book[:title]}</a> is available\"\n if libraries_available.include? LIBRARY_MY_STRING\n book_available = true\n stream << \"data: #{html}\\n\\n\"\n elsif libraries_available.length > 0 && @library_branch_location == ''\n book_available = true\n html += \" at \"\n libraries_available.uniq.each do |library|\n html += \"<span class='library'>#{library}</span>\"\n if (libraries_available.last != library); html += \", \" end\n end\n html += \"</li>\"\n stream << \"data: #{html}\\n\\n\"\n else\n # show those unavailable\n end\n\n end\n\n stream << \"data: status: None of your books are available.\\n\\n\" unless book_available == true\nend",
"def to_hash\n @to_hash ||= RISBN::NokogiriUtils.hash_from_node(xml_nodes)[:entry]\n end",
"def returnBooksByGenre(userGenre)\n @books.each do \n |book|\n #book[0] holds just the key of all the book in the hash\n #book[1] holds availablility and the book itself\n #For every book, check if available\n book[1][0].select do\n |key, value|\n if(value.genre == userGenre)\n p value\n end\n end #end inner do\n end #end outer do\n end",
"def isbn\n generate_barcode('barcode.isbn')\n end",
"def initialize(books)\n # initialize is a ruby function\n @books = books # we have our array of books hashes\n end",
"def to_h\n hash = {}\n if doi.present?\n hash['doi'] = doi\n hash['doi_uri'] = doi_uri\n end\n if isbn.present?\n hash['isbn'] = isbn\n hash['isbn_uri'] = isbn_uri\n end\n if issn.present?\n hash['issn'] = issn\n hash['issn_uri'] = issn_uri\n end\n if pmid.present?\n hash['pmid'] = pmid\n hash['pmid_uri'] = pmid_uri\n end\n hash\n end",
"def find_book_by_title(book_title)\n books = @books\n for book in books\n if (book[:title] == book_title)\n return book\n end\n end\n return nil\n end",
"def print_lore_book(id, hash)\n hash['elements'].each do |book|\n puts book['label']+\": \"+book['description']if book['id'] == id\n end\nend",
"def fill_student_hash\n students = create_student_hash\n add_links_to_hash(students) \n populate_hash(students)\n #html_hash = scrape_and_store_each_profile(doc)\n #populate_hash_with_profile(students, html_hash, :tagline, '.textwidget h3') #tagline\n #populate_hash_with_bio(students, html_hash) #bio\n #populate_hash_with_social(students, html_hash, :github, 2) #github\n #populate_hash_with_social(students, html_hash, :twitter, 0) #twitter\n #populate_hash_with_social(students, html_hash, :linkedin, 1) # linkedin\nend",
"def search_a1books(query,type)\n #@@logger.info(\"Search a1books..\")\n #@@logger.info(query)\n mtype= type[:search_type]\n\n #@@logger.info(mtype)\n\n prices=[]\n if mtype != 'books' then\n #@@logger.info ('----------------Ignoring search on a1books---------------------------------------------')\n price_info = {:price=> -999, :author=> 'fake',:name=>'fake', :img => 'fake', :url => 'fake', :source=>'Rediff', :weight => -999}\n prices.push(price_info)\n return prices\n end\n url =\"http://www.a1books.co.in/searchresult.do?searchType=books&keyword=#{query[:search_term]}&fromSearchBox=Y&partnersite=a1india&imageField=Go\"\n page = self.fetch_page(url)\n\n begin\n price_text = page.search(\"span.salePrice\").map { |e| \"#{e.text.tr('A-Za-z,','')}\" }\n name_text = page.search(\"table.section a.label\").map{ |e| \"#{e.text}\" }\n author_text = page.search(\"table.section td[@width='100%']\").map{ |e| \"#{e.text}\" }\n url_text = page.search(\"table.section a.label[@href]\").map{|e| e['href'] }\n discount_text =\"\" \n shipping_text =\"\"\n \n \n (0...price_text.length).each do |i|\n author = author_text[i]\n name = name_text[i].strip\n search_index = author.index(name) \n if search_index != nil then \n author = author[search_index+name.length..author.length]\n end\n if (name_text[i] == nil && author != nil) then\n weight,cost = find_weight(author, \"#{query[:search_term]}\" )\n elsif (name_text[i] !=nil && author == nil) then\n weight,cost = find_weight(name_text[i], \"#{query[:search_term]}\" )\n else\n weight,cost = find_weight(name_text[i]+\" \"+author, \"#{query[:search_term]}\" )\n end \n if (weight > 0) then\n price_info = {:price => price_text[i],:author=>proper_case(author), :name=>proper_case(name_text[i]), :img=>\"\",:url=>\"http://a1books.co.in\"+url_text[i], :source=>'A1Books', :weight=>weight, :discount=>discount_text, :shipping => shipping_text} \n prices.push(price_info)\n end\n end\n rescue => ex\n #Just ignore this error\n #@@logger.info (\"#{ex.class} : #{ex.message}\")\n end\n prices\n end",
"def initialize(hash) # only called when creating books from api\n @chapters = {} # must be an empty hash on instantiation to contain all chapters of the book\n hash.each do |k,v|\n self.send(\"#{k}=\", v)\n end\n end",
"def fetch_books(term)\n response = RestClient.get(\"https://www.googleapis.com/books/v1/volumes?q=#{term}\")\n\n JSON.parse(response.body)\n end",
"def isbn(request)\n request.referent.isbn && request.referent.isbn.gsub('-', '')\n end",
"def use_google(hash)\n @google_hash = hash\n @google_hash\n end",
"def set_isbn\n @isbn = Isbn.new(number: book_copy_params[\"isbn\"])\n if @isbn.valid? \n @book = @isbn.search_or_create_book_by_isbn\n if !@book.save\n render json: @book.errors, status: :unprocessable_entity \n end\n else \n render json: @isbn.errors, status: :unprocessable_entity \n end\n end",
"def author_hash; end",
"def isbn\n\t\tread_attribute(:isbn).length == 13 ? read_attribute(:isbn).insert(3,'-') : read_attribute(:isbn)\n\tend",
"def get_related_isbns(isbn)\n response = open(\"http://www.librarything.com/api/thingISBN/\" + isbn)\n if response.nil?; return [isbn] end\n\n page = Nokogiri::XML(response)\n related_isbns = []\n page.css('isbn').each { |related_isbn| related_isbns.push(related_isbn.text) }\n\n related_isbns\nend",
"def fetch_books(term)\n response = RestClient.get(\"https://www.googleapis.com/books/v1/volumes?q=#{term}\")\n\n JSON.parse(response.body)\nend",
"def isbn(base: 10)\n case base\n when 10 then generate_base10_isbn\n when 13 then generate_base13_isbn\n else raise ArgumentError, 'base must be 10 or 13'\n end\n end",
"def parse_item(item) \n @book = JSON(item.body)[\"data\"].first \t\n \n # @book = Hashie::Mash.new book_data\n @book_id = @book['book_id']\n @title = @book['title']\n @authors = @book['author_data'] || []\n @publisher = @book['publisher_name']\n @published_date = extract_date @book['edition_info'] if @book['edition_info'].present?\n @description = @book['summary']\n @isbn = @book['isbn13']\n @isbn10 = @book['isbn10']\n @dewey = @book['dewey_decimal']\n @page_count = extract_page_count @book['physical_description_text'] if @book['physical_description_text'].present?\n @notes = @book['notes']\n @edition_info = @book['edition_info']\n @physical_description = @book['physical_description_text']\n @subject_ids = @book['subject_ids'] || []\n @language = @book['language']\n end",
"def add(num)\n #item = '9781133049791'\n item = num.fetch(\"isbn\")\n if !Book.pluck(:isbn).include?(item)\n @res = Amazon::Ecs.item_search(item, { :search_index => 'All', :response_group => 'Medium' })\n @res.items.each do |book|\n @db = Book.create\n @db.isbn = item\n @db.author = book.get('ItemAttributes/Author')\n @db.name = book.get('ItemAttributes/Title')\n @db.edition = book.get('ItemAttributes/Edition').to_i\n @db.retail_price = ((book.get('ItemAttributes/ListPrice/Amount').to_f/100)*3.65).to_i\n @db.description = book.get('EditorialReviews/EditorialReview/Content')\n @db.photo = book.get('LargeImage/URL')\n @db.save\n end\n end\n @thisBook = Book.find(:all, :conditions => {:isbn => item})\n redirect_to @thisBook\n end",
"def hash\n @data[:asin].to_s.hash\n end",
"def get_document_details(doc)\n tmp_hash = {}\n tmp_hash[\"id\"] = doc[\"bibid\"]\n tmp_hash[\"location\"] = doc[\"location\"].present? ? doc[\"location\"] : \"\"\n tmp_hash[\"title\"] = doc[\"fulltitle_display\"].present? ? doc[\"fulltitle_display\"] : \"\"\n if doc[\"format\"].present?\n if doc[\"format\"][1].present? and doc[\"format\"][1] == \"Microform\"\n the_format = doc[\"format\"][1]\n else\n the_format = doc[\"format\"][0]\n end\n else\n the_format = \"\"\n end\n # oclc_id and isbn are used to get the images from googlebooks\n oclc_id = doc[\"oclc_id_display\"].present? ? doc[\"oclc_id_display\"][0] : \"\"\n isbn = doc[\"isbn_display\"].present? ? doc[\"isbn_display\"][0].split(\" \")[0] : \"\"\n tmp_hash[\"format\"] = the_format\n tmp_hash[\"pub_date\"] = doc[\"pub_date_display\"].present? ? doc[\"pub_date_display\"] : \"\"\n tmp_hash[\"publisher\"] = doc[\"publisher_display\"].present? ? doc[\"publisher_display\"] : \"\"\n tmp_hash[\"author\"] = doc[\"author_display\"].present? ? doc[\"author_display\"] : \"\"\n tmp_hash[\"availability\"] = doc[\"availability_json\"].present? ? doc[\"availability_json\"] : \"\"\n tmp_hash[\"locations\"] = doc[\"availability_json\"].present? ? process_locations(doc[\"availability_json\"]) : []\n tmp_hash[\"citation\"] = doc[\"cite_preescaped_display\"].present? ? doc[\"cite_preescaped_display\"] : \"\"\n tmp_hash[\"callnumber\"] = doc[\"callnum_display\"].present? ? doc[\"callnum_display\"] : \"\"\n # the difference between these next two: \"internal_class_label\" gets used in the data attribute\n # of some elements, while the \"display_class_label\" gets displayed in the UI and has the added\n # font awesomne html\n classification = doc[\"classification_display\"].present? ? doc[\"classification_display\"] : \"\"\n tmp_hash[\"internal_class_label\"] = build_class_label(classification)\n tmp_hash[\"display_class_label\"] = tmp_hash[\"internal_class_label\"].gsub(' : ','<i class=\"fa fa-caret-right class-caret\"></i>').html_safe\n # tmp_hash[\"img_url\"] = get_googlebooks_image(oclc_isbn[0], oclc_isbn[1], the_format)\n tmp_hash[\"img_url\"] = get_googlebooks_image(oclc_id, isbn, the_format)\n\n return tmp_hash\n end",
"def isbn=(newIsbn)\n\t\t@isbn = newIsbn\n\tend",
"def return_item_from_bay(user_input_raw, input_hash)\n user_input_sym = user_input_raw.to_sym\n if input_hash.key?(user_input_sym)\n then return input_hash[user_input_sym]\n else\n print 'No such bay found'\n end\n end",
"def book\n fetch('harry_potter.books')\n end",
"def get_search\n puts \"Search Title or Author. Enter 4 or more letters.\".blue\n puts \">\".blue.bold\n @@found_title_match = []; @@found_author_match = [];\n all_title_array = []; all_author_array=[]\n\n r = gets[0..20].chomp\n if r.length < 4\n puts \"Search string must contain at least four characters\".blue\n get_search\n else\n puts \"Searching... #{r}\".red\n @@book_class.each do | book |\n regx_result = /#{r}/i =~ book.title.chomp\n if regx_result != nil\n @@found_title_match << book\n end\n end\n\n @@book_class.each do | book |\n regx_result_author = /#{r}/i =~ book.author.chomp\n if regx_result_author != nil\n @@found_author_match << book\n end\n end\n end\n # puts \"group by value\".cyan\n # ref http://ruby-doc.org/core-2.2.1/Enumerable.html#method-i-group_by\n all_title_array= @@found_title_match.group_by{|book| book.title}\n all_author_array = @@found_author_match.group_by{|book| book.author}\n\n # puts \"first\".cyan\n # ref: http://ruby-doc.org/core-2.2.0/Array.html#method-i-first\n all_title_array.merge!(all_author_array)\n all_title_array.each{|k,v|p v.first.to_s.chomp}\n # all_author_array.each{|k,v|p v.first.to_s.chomp} :keep\n end",
"def create_book( bookinfo_hash )\r\n name = bookinfo_hash[:name]\r\n author = bookinfo_hash[:author]\r\n\r\n puts \"#{name}, written by #{author}\"\r\nend",
"def select_using_hash(chapter,probs,year,semester,student_id)\n # year = 2014, etc.; semester = \"s\" or \"f\"\n chapter = chapter.to_s\n year = year.to_i\n semester = semester.to_s\n student_id = student_id.to_s\n # figure out an integer for the semester, counting from spring 2014 = 0\n s = (year-2014)*2;\n if semester==\"f\" then s=s+1 end\n x = student_id+\",\"+chapter+\",\"+probs.join(\":\")\n hash = md5_hash_hex(x); # 32 hex digits\n hex4 = hash.to_s[-4..-1]\n k = hex4.to_i(16) # convert hex string to fixnum\n k = k+s; # if a student is repeating the course, cycle through the problems, don't assign same one\n n = probs.length;\n return k%n;\nend",
"def fetch_book_info\n url = \"#{BASE_URL}/#{book_id}\"\n resp = RestClient::Request.execute(url: url, method: \"GET\")\n resp_obj = JSON.parse(resp)\n\n {\n id: book_id,\n title: resp_obj[\"volumeInfo\"][\"title\"],\n author: resp_obj[\"volumeInfo\"][\"authors\"][0],\n image: resp_obj[\"volumeInfo\"][\"imageLinks\"] ? resp_obj[\"volumeInfo\"][\"imageLinks\"][\"thumbnail\"] : DEFAULT_IMAGE\n }\n end",
"def searchReviews(isbn = '', title = '', author = '')\n url = \"https://api.nytimes.com/svc/books/v3/reviews.json\"\n params = {\n author: author,\n title: title,\n isbn: isbn\n }\n self.request(url, params)\n end",
"def composers_hash\n search_by_itemprop_hash 'musicBy'\n end",
"def index\n @book = Book.find_by_asin(params[:id]) || AmazonCatalog.asinLookup(params[:id])\n end",
"def book_params\n # params.fetch(:book, {})\n params.require(:book).permit(:isbn, :title, :author, :language, :published, :edition, :image, :subject, :summary, :is_special_collection_item, :search)\n end",
"def odsa_books\n inst_books\n end",
"def bulk_isbn_query(isbns)\n string = \"srw.bn any \\\"#{isbns.first}\\\"\"\n isbns[1..-1].each do |num|\n string << \" or srw.bn any \\\"#{num}\\\"\"\n end\n string\nend",
"def object_book_params\n params.fetch(:object_book, {})\n end",
"def find(address)\n # Geocode the given address.\n geocode address\n\n ward = Data.new(data)\n ward.to_hash\n end",
"def get_herb_list\n # Herb http://www.wowdb.com/search.aspx?browse=5.-2\n if @@herbs.length == 0\n herbs = search_list(\"5.-2\")\n herbs.each do |h|\n if not h[:skill].nil? and h[:skill] > 0\n @@herbs[h[:name]] = h[:id]\n end\n end \n end\n return @@herbs\n end",
"def busca_libro(isbn)\n\t\tfor libro in @libros\n\t\t\tif libro.isbn == isbn\n\t\t\t\treturn libro\n\t\t\tend\n\t\tend\n\t\treturn nil\n\tend",
"def product_to_bay(ref_hash, item_string)\n key = ref_hash.key(item_string)\n return key\nend",
"def hash_data(item)\n { item: item, barcode: item.sample.properties.fetch('Barcode ID') }\n end",
"def initialize(title, author, isbn, available)\n @title = title\n @author = author\n @isbn = isbn\n @available = available\n end",
"def initialize(isbn, price)\n raise ArgumentError if isbn.empty? || price <= 0\n @isbn = isbn #sets the attribute isbn as the argument isbn\n @price = price #sets the attribute price as the argument price\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.51762664",
"0.5171246",
"0.51631474",
"0.51590365",
"0.51141703",
"0.5110755",
"0.50971717",
"0.5096188",
"0.50875974",
"0.50836205",
"0.5078331",
"0.5067868",
"0.5048881",
"0.50449526",
"0.50404495",
"0.50368583",
"0.5013926",
"0.50107384",
"0.49815768",
"0.49811852",
"0.49410328",
"0.49309206",
"0.49198255",
"0.49190482",
"0.49134287",
"0.49084035",
"0.49070352",
"0.4906943",
"0.49062118",
"0.48983842",
"0.4887574",
"0.4871866",
"0.48511985",
"0.48491514",
"0.48245493",
"0.48109585",
"0.47966802",
"0.47862384",
"0.4784117",
"0.47560194",
"0.4754638",
"0.47498196",
"0.47414383",
"0.4736179",
"0.47324866",
"0.47243798",
"0.47151837",
"0.4715122",
"0.47133476",
"0.47125003",
"0.47115928",
"0.47104388",
"0.4708129",
"0.46987355",
"0.46840855",
"0.46827242",
"0.4677234",
"0.46736923",
"0.46565717",
"0.46531025",
"0.4648894",
"0.46240708",
"0.46134204",
"0.46071234",
"0.46061757",
"0.46058288",
"0.4603189",
"0.46011743",
"0.46004787",
"0.45905462"
] | 0.7637749 | 0 |
Called by the event loop when a remote TCP connection attempt completes successfully. | def connection_completed
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def connection_completed\n log_debug '[client-cnxn] Established server connection, sending request'\n send_request unless error?\n rescue\n fail(:RPC_ERROR, 'Connection error: %s' % $!.message) unless failed?\n end",
"def connection_successful\n @authenticating = false\n opened!\n\n exec_callback_yielding_self(:connect)\n end",
"def connection_completed\n @connection_completed = true\n begin_handshake\n rescue Exception\n log.fatal { \"Error in #connection_completed\" }\n p $!; puts *$@\n end",
"def connection_completed\n connect @conn_headers # call EM supplied CONNECT method\n @log.debug(\"#{self} connection_completed done\")\n end",
"def connection_successful\n @connection_deferrable.succeed\n end",
"def server_connection_success\n LOGGER.info \"Successful connection to #{@remote.join(':')}\"\n @connected = true\n @server_side.send_data(@buffer_out)\n @buffer_out = ''\n end",
"def connection_completed\n @connection_state = :connected\n @connection_state_callback.call if @connection_state_callback\n end",
"def connection_completed\n @connected = true\n Skates.logger.debug {\n \"CONNECTED\"\n } # Very low level Logging\n end",
"def on_connection_success &block\n @connection_success_callback = block\n end",
"def connection_completed\n @connected = true\n send_request @args\n end",
"def connection_completed\n puts \"The connection for #{@my_address} has been successfully completed.\"\n end",
"def connection_status_done; end",
"def connection_completed\n # We aren't completely connected yet if the connection is encrypted.\n connected! unless @network.secure?\n end",
"def connect\r\n begin\r\n TCPSocket.new(@server, @port) #used for checking the connection\r\n puts \"Connection successful!\"\r\n run()\r\n rescue => exception\r\n puts \"Failed to connect to : #{@server}:#{@port}\"\r\n puts \"Closing...\"\r\n sleep(2)\r\n end\r\n \r\n end",
"def connection_completed\n start_tls\n end",
"def connection_completed\n start_tls\n end",
"def complete_connect_nonblock\n ensure_state :connecting\n\n begin\n remote_sockaddr = ::Socket.sockaddr_in(@remote_port, @remote_addr)\n\n # Note: `exception: false` for Socket#connect_nonblock is only supported in Ruby 2.3+\n # TODO: use `exception: false` when we drop support for Ruby 2.2\n @socket.connect_nonblock(remote_sockaddr)\n rescue Errno::ECONNREFUSED\n close\n raise Socketry::ConnectionRefusedError, \"connection to #{@remote_addr}:#{@remote_port} refused\"\n rescue Errno::EHOSTDOWN\n close\n raise Socketry::HostDownError, \"cannot connect to #{@remote_addr}: host is down\"\n rescue Errno::EINPROGRESS, Errno::EALREADY\n return :wait_writable\n rescue Errno::EISCONN\n # Sometimes raised when we've connected successfully\n end\n\n change_state :connected\n self\n end",
"def connection_completed\n\tend",
"def connection_completed\n# @keepalive = EM::PeriodicTimer.new(60) { send_data ' ' }\n start\n end",
"def on_tcp_connection_failure(&block)\n define_callback :tcp_connection_failure, &block\n end",
"def on_handshake_succeeded( fd, endpoint )\n\t\t\tself.log.debug \"Client socket on FD %d handshake succeeded\" % [ fd ]\n\t\tend",
"def connect\n succeed # Triggers all callbacks for class\n end",
"def connection_completed()\n super()\n puts \"#{self} connection_completed done!\"\n end",
"def connection_completed()\n super()\n puts \"#{self} connection_completed done!\"\n end",
"def connection_completed()\n super()\n puts \"#{self} connection_completed done!\"\n end",
"def ssl_handshake_completed\n connected!\n end",
"def try_connect\n return if established?\n \n @socket = TCPSocket.new(*destination.split(':'))\n rescue Errno::ECONNREFUSED\n # No one listening? Well.. too bad.\n @socket = nil\n end",
"def connection_completed\n JR::JobLogger.log('Begin distributor handshake')\n data = {node_info: {name: @node.config[:name], server: @node.server} }\n data = Marshal.dump(data)\n send_data(data)\n end",
"def start\n Socket.accept_loop(@tcpserver) do |connection|\n SLogger.debug(\"[server] accepted a new connection (#{connection})\")\n\n self.session.connection = connection\n self.handle_connection(connection)\n end\n rescue IOError\n Thread.exit\n end",
"def disconnection_successful\n exec_callback_yielding_self(:disconnect)\n close_connection\n closed!\n end",
"def ssl_handshake_completed\n log_system_debug(\"TLS connection established to \" << remote_desc) if $oversip_debug\n\n # @connected in TlsClient means \"TLS connection\" rather than\n # just \"TCP connection\".\n @connected = true\n @timer_tls_handshake.cancel if @timer_tls_handshake\n\n # Run OverSIP::SipEvents.on_server_tls_handshake.\n ::Fiber.new do\n if @callback_on_server_tls_handshake\n log_system_debug \"running OverSIP::SipEvents.on_server_tls_handshake()...\" if $oversip_debug\n begin\n ::OverSIP::SipEvents.on_server_tls_handshake self, @server_pems\n rescue ::Exception => e\n log_system_error \"error calling OverSIP::SipEvents.on_server_tls_handshake():\"\n log_system_error e\n close_connection\n end\n\n # If the user or peer has closed the connection in the on_server_tls_handshake() callback\n # then notify pending transactions.\n if @local_closed or error?\n log_system_debug \"connection closed, aborting\" if $oversip_debug\n @pending_client_transactions.each do |client_transaction|\n client_transaction.tls_validation_failed\n end\n @pending_client_transactions.clear\n @pending_messages.clear\n @state = :ignore\n end\n end\n\n @pending_client_transactions.clear\n @pending_messages.each do |msg|\n send_data msg\n end\n @pending_messages.clear\n end.resume\n end",
"def connection_ended\n end",
"def connection_ended\n end",
"def tls_successful_handshake\n logdebug \"Succesful handshake!\"\n end",
"def client_connected\n @dest_host = @proxy_host\n @dest_port = @proxy_port\n connect_to_dest\n end",
"def connect\n return if @connected && (@socket && !@socket.closed?)\n on_connect\n @connected = true\n end",
"def socket_connected\n post_init\n end",
"def connection_action\n @sslsocket.connect_nonblock\n end",
"def complete_handshake\n if @state == :handshake\n log.debug { 'Handshake completed' }\n @state = :connected\n @started = Time.now\n @node.push_notification(:connection, info.merge(type: :connected))\n @node.addrs << addr\n end\n send_data P::Addr.pkt(@node.addr) if @node.config[:announce]\n end",
"def attempt_connection\n @connection_future = Concurrent::Future.new do\n connection_method.call\n end\n connection_future.execute\n end",
"def wait_connection; end",
"def wait_connection; end",
"def on_connect_event(ctx)\n logger.debug(\"Client connect from #{ctx[:server][:remote_ip]}:#{ctx[:server][:remote_port]}\")\n end",
"def connect\n #trap(\"INT\") {EM.stop}\n\n EventMachine.run do\n @connection = MQTT::ClientConnection.connect(@remote_host, @remote_port)\n\n # Stuff happens here\n yield(self)\n\n # Disconnect once all the other deferred callbacks\n @connection.callback do\n disconnect\n end\n\n puts \"Finished initing run\"\n end\n end",
"def connection_action\n @sslsocket.accept_nonblock\n end",
"def on_connection_established(&block)\n @on_connection_established_block = block\n end",
"def connect\n loop do\n return if @stopped.value\n interval = @backoff.next_interval\n if interval > 0\n @logger.warn { \"Will retry connection after #{'%.3f' % interval} seconds\" } \n sleep(interval)\n end\n begin\n cxn = open_connection(build_headers)\n if cxn.status != 200\n body = cxn.read_all # grab the whole response body in case it has error details\n cxn.close\n @on[:error].call({status_code: cxn.status, body: body})\n next\n elsif cxn.headers[\"content-type\"] && cxn.headers[\"content-type\"].start_with?(\"text/event-stream\")\n return cxn # we're good to proceed\n end\n @logger.error { \"Event source returned unexpected content type '#{cxn.headers[\"content-type\"]}'\" }\n rescue Errno::EBADF\n raise\n rescue StandardError => e\n @logger.error { \"Unexpected error from event source: #{e.inspect}\" }\n @logger.debug { \"Exception trace: #{e.backtrace}\" }\n cxn.close if !cxn.nil?\n end\n # if unsuccessful, continue the loop to connect again\n end\n end",
"def connect!\n Timeout::timeout(5) do\n self.remote = TCPSocket.new(host, port)\n end\n rescue Timeout::Error => e\n raise ConnectionTimeoutError\n rescue\n raise CannotConnectError\n end",
"def connect\n self.send({\n msg: :connect,\n version: @version,\n support: @support\n })\n\n #handle incoming response form the server\n self.onmessage = lambda do |event|\n\n res = JSON.parse(event.data)\n\n if res.has_key? 'session'\n #connection is successful - update session and record version\n @session = res['session'].to_s\n @@last_suc_version = @version\n\n else #there was a failed connection\n @version = res['version']\n #retry the send request with the version specified by the server\n self.send({\n msg: :connect\n version: @version,\n support: @support\n })\n end\n\n end\n end",
"def on_session_ended\n @connection = nil\n\n # Automatically reconnect to the server if allowed\n if @reconnect\n reconnect_from(Exception) do\n connect\n trigger(:reconnected)\n end\n end\n end",
"def wait_connection_attempt_result(timeout: nil)\n connection_future.wait(timeout)\n connection_future.complete?\n end",
"def _connect\n return if @ssl_connected\n\n Error.translate do\n @plaintext_connected ||= super\n return if !@plaintext_connected\n\n # Mark the connection as not connected due to the pending SSL handshake.\n @connected = false\n\n @socket.connect_nonblock\n @ssl_connected = @connected = true\n end\n rescue IO::WaitReadable, IO::WaitWritable, Errno::EINPROGRESS\n rescue Error => e\n close e\n end",
"def connection_completed\n ## start sending KEEP_ALIVE_MESSAGE\n puts 'sending keep_alive sending ...'\n EM::PeriodicTimer.new(KEEP_ALIVE_INTERVAL) { send_data KEEP_ALIVE_MESSAGE }\n end",
"def initiate_connection\n Retriable.retriable on: [Errno::ECONNREFUSED, Errno::EHOSTUNREACH] do\n TCPSocket.new(ip, port).close\n end\n end",
"def establish_connection\n @connecting_to_socket = true\n start_time = Time.now\n while(@timeout.nil? || Time.now - start_time < @timeout )\n begin\n b = self\n srv = EventMachine::connect_unix_domain(self.socket, EventMachine::Connection, true) do |c|\n logger.info(\"Connected to #{b.socket}\")\n end\n @connected_to_socket = true\n @connecting_to_socket = false\n return\n rescue RuntimeError => e\n @connecting_to_socket = false\n sleep 5\n end\n end\n logger.warn(\"Backend #{socket} did not spin up in the required #{@timeout} seconds.\")\n @dead = true\n end",
"def connected\n log :connect, \"+++ #{@ip}:#{@port} (#{@proto}) connected\\n\"\n end",
"def connect(&block)\n @socket ||= TCPSocket.new(@host, @port)\n update_thread(&block)\n rescue StandardError => e\n puts e\n end",
"def begin_handshake\n if incoming? && !@node.accept_connections?\n return close_connection unless @node.config[:connect].include?([@host, @port.to_s])\n end\n log.info { \"Established #{@direction} connection\" }\n @node.connections << self\n @state = :handshake\n send_version\n rescue Exception\n log.fatal { \"Error in #begin_handshake\" }\n p $!; puts *$@\n end",
"def connection_completed\n\t\tsend_data \"#{$username}:#{$password}\"\n\tend",
"def disconnection_successful\n @disconnection_deferrable.succeed\n\n self.close_connection\n end",
"def connect\n disconnect if connected?\n @socket = TCPSocket.new(@host, @port)\n @socket.setsockopt(::Socket::SOL_SOCKET, ::Socket::SO_KEEPALIVE, true)\n read_line # \"BOB 00.00.0D\"\n read_line # \"OK\"\n self\n end",
"def on_connect_event(ctx)\n carterdte_logger.info(\"Connection from #{ctx[:server][:remote_ip]}\")\n end",
"def connect\n retry_count = 0\n begin\n @socket = TCPSocket.new(@current_server[:host], @current_server[:port])\n rescue => ex\n warn \"Faild to connect: #{ex.class} (server: #{@current_server})\"\n warn ex.message\n retry_count += 1\n if retry_count > 3\n set_current_server\n warn \"Connecting another server: #{@current_server}\"\n retry_count = 0\n end\n sleep 1\n retry\n end\n @socket.autoclose = true\n nil\n end",
"def finish\n begin\n @socket.close\n rescue\n end\n on_disconnected\n end",
"def attempt_connection\n @connection_future = Concurrent::Future.new do\n Roby::DRoby::Logfile::Client.new(host, port)\n end\n connection_future.execute\n end",
"def loop_forever\n running = true\n\n while wait_for_connection\n @logger.info(\"New client connected\")\n command, *arguments = next_message.split\n @logger.debug \"#{command} received\"\n response = case command\n when /^track$/i then track(arguments.first)\n when /^list$/i then list\n when /^release$/i then release(arguments.first)\n end\n\n write(response) unless response.nil?\n end\n rescue => e\n @logger.error(\"An error occurred when waiting for new connections!\\n\\t#{e.inspect}\\n\\t#{e.backtrace.join(\"\\n\\t\")}\")\n end",
"def connected(socket, remote_state)\n Distributed.debug { \"#{self}: connected\" }\n register_link(socket)\n local_server.state_update remote_state\n @send_queue = Queue.new\n\t @send_thread = Thread.new(&method(:communication_loop))\n end",
"def connected?; connection_state == :connected end",
"def run\n loop do\n # Wait for a client to connect and then create a thread for it\n Thread.new(@server.accept) do |client_socket|\n logger.info \"Accepted client: #{client_socket.peeraddr.join(':')}\"\n server_socket = TCPSocket.new(@server_host, @server_port)\n begin\n process_packets(client_socket, server_socket)\n rescue Exception => exp\n logger.error exp.to_s\n end\n logger.info \"Disconnected: #{client_socket.peeraddr.join(':')}\"\n server_socket.close\n client_socket.close\n end\n end\n end",
"def _post_connect()\n return unless (@connect_headers[:\"accept-version\"] && @connect_headers[:host]) # 1.0\n if @connection_frame.command == Stomp::CMD_ERROR\n @connection_frame.headers = _decodeHeaders(@connection_frame.headers)\n return\n end\n # We are CONNECTed\n cfh = @connection_frame.headers.symbolize_keys\n @protocol = cfh[:version]\n if @protocol\n # Should not happen, but check anyway\n raise Stomp::Error::UnsupportedProtocolError unless Stomp::SUPPORTED.index(@protocol)\n else # CONNECTed to a 1.0 server that does not return *any* 1.1 type headers\n @protocol = Stomp::SPL_10 # reset\n return\n end\n # Heartbeats\n return unless @connect_headers[:\"heart-beat\"]\n _init_heartbeats()\n end",
"def retry_connection(opts)\n log_msg = \"[SSH] opening connection to #{self}\"\n log_msg += \" via #{ssh_gateway_username}@#{ssh_gateway}:#{ssh_gateway_port}\" if ssh_gateway\n logger.debug(log_msg)\n yield\n rescue *RESCUE_EXCEPTIONS_ON_ESTABLISH => e\n if (opts[:retries] -= 1) > 0\n message = if opts[:message]\n logger.debug(\"[SSH] connection failed (#{e.inspect})\")\n opts[:message]\n else\n \"[SSH] connection failed, retrying in #{opts[:delay]} seconds \" \\\n \"(#{e.inspect})\"\n end\n logger.info(message)\n sleep(opts[:delay])\n retry\n else\n logger.warn(\"[SSH] connection failed, terminating (#{e.inspect})\")\n raise SshFailed, \"SSH session could not be established\"\n end\n end",
"def waited_on_connect?\n @waited_on_connect\n end",
"def ensure_connected! \n if @ssh_options[:timeout]\n total_timeout = @ssh_options[:timeout] * 2\n else\n total_timeout = 30\n end\n # puts \"Total timeout: #{total_timeout}\"\n @connections=[]\n hosts_to_connect = @hosts.inject(0) {|sum,h| sum += (h.connect_failed ? 0:1)}\n # puts \"#{hosts_to_connect} to connect\"\n @hosts.each do |host|\n if @connection_cache[host.name] || host.connected\n @connection_mutex.synchronize { @connections << {:connection=>@connection_cache[host.name], :host=>host} }\n host.connected=true\n elsif !host.connect_failed\n Thread.new {\n begin\n #puts \"Connecting #{host.name}\" \n c = Net::SSH.start(host.name, @user_name, @ssh_options)\n @connection_cache[host.name] = c\n @connection_mutex.synchronize { @connections << {:connection=>c, :host=>host} }\n host.connected=true\n #puts \"Connected #{host.name}\" \n rescue Exception => e\n host.connect_failed = true\n host.connected=false\n error \"Unable to connect to #{host.name}\\n#{e.message}\"\n @connection_mutex.synchronize {@connections << {:connection=>nil, :host=>host} }\n host.exception=e\n end \n }\n end\n end\n s = Time.now\n loop do\n l=0\n @connection_mutex.synchronize { l = @connections.length }\n break if l == hosts_to_connect\n sleep(0.1)\n if Time.now - s > total_timeout\n puts \"Warning -- total connection time expired\"\n puts \"Failed to connect:\"\n hosts.each do |h|\n unless h.connected\n puts \" #{h.name}\" \n h.connect_failed=true\n # TODO: Need to handle this situations much better. Attempt to kill thread and/or mark connection in cache as unreachable\n end\n end\n break\n end\n end \n end",
"def handle_tcp_failure(connection, settings)\n\n logger.info(\"Connection to AMQP lost. Finding new host..\")\n\n if @amqp_hosts.size == 1\n logger.info(\"Only a single host.. reconnecting\")\n connection.reconnect(false, 10)\n return\n end\n\n current_host = settings[:host]\n new_host = get_new_amqp_host(@amqp_hosts)\n\n while new_host == current_host\n new_host = get_new_amqp_host(@amqp_hosts)\n end\n\n settings[:host] = new_host\n\n logger.info (\"Reconnecting to AMPQ host: #{new_host}\")\n\n connection.reconnect_to(settings)\n end",
"def ready(packet)\n @connected = true\n\n send_nick()\n end",
"def init\n # Open a socket for the server to connect on.\n @sock = TCPSocket.new(@address , @server.port)\n @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)\n @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, false)\n unless RUBY_PLATFORM =~ /win32/\n @sock.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK)\n end\n c = Connection.new(@server, @sock)\n if c.init\n log.info \"(#{c.object_id}) Connection made.\"\n publish(c)\n true\n else\n false\n end\n rescue Exception\n log.error \"Connector#init\"\n log.error $!\n false\n end",
"def tcp_ssh_alive(hostname,port=22)\n tcp_socket = TCPSocket.new(hostname, port)\n readable = IO.select([tcp_socket], nil, nil, 5)\n if readable\n Chef::Log.debug(\"sshd accepting connections on #{hostname}, banner is #{tcp_socket.gets}\")\n true\n else\n false\n end\n \n rescue Errno::ETIMEDOUT\n false\n rescue Errno::EPERM\n false\n rescue Errno::ECONNREFUSED\n sleep 2\n false\n rescue Errno::EHOSTUNREACH, Errno::ENETUNREACH\n sleep 2\n false\n ensure\n tcp_socket && tcp_socket.close\n end",
"def on_connect(socket)\n Utils.logger.info(\"[Client Connected: #{socket.inspect}]\")\n end",
"def ssl_handshake_completed\n return unless @tls_options[:verify_peer]\n @client_cert = get_peer_cert\n close_connection if @client_cert && !valid_client?(@client_cert)\n end",
"def on_open(event)\n logger.debug 'Socket opened'\n @connected = true\n end",
"def on_connection_error &block\n @connection_error_callback = block\n end",
"def on_connect_accept( avatar, address, hostid )\n\t\t\tself.log.debug \"unhandled on_connect_accept: connection accepted from '%s' (%s)\" %\n\t\t\t\t[ address, hostid ]\n\t\tend",
"def on_stream_reconnect(timeout, retries)\n puts \"reconnecting in: #{timeout} seconds\\n\"\n end",
"def server_loop(server)\n loop do\n Thread.start(server.accept) do |client|\n _unused, remote_port, _unused, remote_ip = client.peeraddr\n @server.logging \"--> OPEN connection from #{remote_ip}:#{remote_port}\"\n client.puts @entrypoint_routine.call\n client.close\n @server.logging \"<-- CLOSE connection from #{remote_ip}:#{remote_port}\"\n end\n end\n end",
"def do_success( channel )\n assert_state :init\n @log.debug \"initializing sftp subsystem\" if @log.debug?\n\n packet = @buffers.writer\n packet.write_long @version\n send_data FXP_INIT, packet\n\n @state = :version\n end",
"def connect\n @socket = TCPSocket.open @host, @port\n @connected = !@socket.closed?\n end",
"def connect\n socket.connect(@host, @port)\n @connected = true\n rescue SocketError => e\n warn e\n end",
"def accept_connection(tcp)\n counter = counter ? counter + 1 : 1\n\n sock = BasicSocket.for_fd(tcp.sysaccept)\n sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_NOSIGPIPE, true) if Socket.const_defined? :SO_NOSIGPIPE\n sock\n rescue RuntimeError => e\n counter == 1 ? retry : raise(e)\n end",
"def after_successful_connection(&block)\n Thread.new do\n sleep_interval = @retry_initial_interval\n # in case of a pipeline's shutdown_requested?, the method #close shutdown also this thread\n # so no need to explicitly handle it here and return an AbortedBatchException.\n until successful_connection? || @stopping.true?\n @logger.debug(\"Waiting for connectivity to Elasticsearch cluster, retrying in #{sleep_interval}s\")\n sleep_interval = sleep_for_interval(sleep_interval)\n end\n block.call if successful_connection?\n end\n end",
"def connectionStart(conn)\n\n port, host = conn.peeraddr[1,2]\n client = \"#{host}:#{port}\"\n #puts \"#{client} is connected\"\n $counter=$counter + 1\n $maxConnections = $maxConnections + 1\n puts $counter.to_s+\" clients connected\"\n $logger.info \"#{client} has connected\"\n $logger.info $counter.to_s+\" clients connected\"\nend",
"def connection_established(pid, conn)\n @connections[pid.uuid] ||= conn\n __send__(conn.connected_callback, pid)\n @connections[pid.uuid].remote_pid || pid # looks like hack, but it is not.\n end",
"def attempt_reconnect\n @disconnect_cb.call(@last_err) if @disconnect_cb\n\n # Clear sticky error\n @last_err = nil\n\n # Do reconnect\n srv = nil\n begin\n srv = select_next_server\n\n # Establish TCP connection with new server\n @io = create_socket\n @io.connect\n @stats[:reconnects] += 1\n\n # Set hostname to use for TLS hostname verification\n @hostname = srv[:hostname]\n\n # Established TCP connection successfully so can start connect\n process_connect_init\n\n # Reset reconnection attempts if connection is valid\n srv[:reconnect_attempts] = 0\n srv[:auth_required] ||= true if @server_info[:auth_required]\n\n # Add back to rotation since successfully connected\n server_pool << srv\n rescue NoServersError => e\n raise e\n rescue => e\n # In case there was an error from the server check\n # to see whether need to take it out from rotation\n srv[:auth_required] ||= true if @server_info[:auth_required]\n server_pool << srv if can_reuse_server?(srv)\n\n @last_err = e\n\n # Trigger async error handler\n @err_cb.call(e) if @err_cb\n\n # Continue retrying until there are no options left in the server pool\n retry\n end\n\n # Clear pending flush calls and reset state before restarting loops\n @flush_queue.clear\n @pings_outstanding = 0\n @pongs_received = 0\n\n # Replay all subscriptions\n @subs.each_pair do |sid, sub|\n @io.write(\"SUB #{sub.subject} #{sub.queue} #{sid}#{CR_LF}\")\n end\n\n # Flush anything which was left pending, in case of errors during flush\n # then we should raise error then retry the reconnect logic\n cmds = []\n cmds << @pending_queue.pop until @pending_queue.empty?\n @io.write(cmds.join) unless cmds.empty?\n @status = CONNECTED\n @pending_size = 0\n\n # Reset parser state here to avoid unknown protocol errors\n # on reconnect...\n @parser.reset!\n\n # Now connected to NATS, and we can restart parser loop, flusher\n # and ping interval\n start_threads!\n\n # Dispatch the reconnected callback while holding lock\n # which we should have already\n @reconnect_cb.call if @reconnect_cb\n end",
"def on_connected( fd, endpoint )\n\t\t\tself.log.debug \"Client socket on FD %d connected\" % [ fd ]\n\t\tend",
"def check\n tcp_socket_request\n mark_message \"Ping check to #{host}:#{port} successful\"\n rescue => e\n mark_message \"Error: '#{e}'\"\n mark_failure\n end",
"def connected\n\t\tdo_send('CN1')\t# Connection command - initiate comms\n\t\n\t\t@polling_timer = schedule.every('60s') do\n\t\t\tlogger.debug \"Polling JVC\"\n\t\t\tdo_send('CN1')\t# Connection command\n\t\tend\n\tend",
"def wait_connect(trycnt=10)\n trycnt.times do\n case sts = status\n when 0x00; return\n when 0x23; raise \"SSID not configured\"\n when 0x24; raise \"Encryption key invalid\"\n when 0x27; raise \"SSID was found, but join failed\"\n # else; Object.puts \"status = 0x#{sts.to_s(16)}\"\n end\n end\n raise \"Cannot connect to target\"\n end",
"def run\r\n Settings::DEFAULT_TRIGGERS.each_key{|k| load_trigger(k, true)}\r\n Settings::TRIGGERS.each_key{|k| load_trigger(k)}\r\n @socket = TCPSocket.open(self.server, self.port)\r\n\r\n $log.info(\"Initiating handshake with server...\")\r\n say \"USER #{nick} 0 * #{nick}\"\r\n say \"NICK #{nick}\"\r\n\r\n until @socket.eof? do\r\n msg = @socket.gets\r\n msg = (msg.split(\" \")[1] == \"PRIVMSG\" ? PrivateMessage.new(msg) : Message.new(msg))\r\n\r\n if msg.type == \"PRIVMSG\"\r\n cache_message(msg)\r\n fire_triggers(msg)\r\n end\r\n\r\n #keep alive\r\n if msg.parts[0] == \"PING\"\r\n say \"PONG :pingis\"\r\n else\r\n case msg.parts[1]\r\n when \"001\"\r\n $log.info(\"Processing connection to server...\")\r\n when \"376\"\r\n $log.info(\"Connected to server, joining channel...\")\r\n join_chan(self.chan)\r\n when \"366\"\r\n @in_chan = true\r\n $log.info(\"Successfully joined ##{self.chan}\")\r\n else\r\n end\r\n end\r\n #output to terminal window whatever the server is giving our socket\r\n $log.info(\"#{msg.stringify}\")\r\n end\r\n end",
"def connection_completed\n if REQUEST_PROTOCOL == 'https'\n start_tls\n end\n\n #Resets connection state\n flush_connection_state\n\n #Constructing request hash\n request_options = {}\n request_options[:request_method] = REQUEST_METHOD\n request_options[:request_protocol] = REQUEST_PROTOCOL\n request_options[:host] = HOST\n request_options[:url_path] = @options[:path]\n request_options[:query_params] = @options[:query_params]\n request_options[:request_body] = @options[:request_body]\n request_options[:oauth] = @options[:oauth]\n\n request = TwitterStreaming::HTTPRequest.new(request_options)\n\n request_string = request.to_string\n\n #Sending raw request data over socket\n send_data request_string\n end",
"def on_connection_interruption(&block)\n self.redefine_callback(:after_connection_interruption, &block)\n end",
"def on_open(event)\n logger.debug 'Socket opened'\n @connected = true\n dispatch('command' => 'session_started')\n end"
] | [
"0.7353997",
"0.72152746",
"0.7053522",
"0.6949944",
"0.6949624",
"0.6855503",
"0.67274",
"0.671445",
"0.65525144",
"0.64445853",
"0.64123917",
"0.64009845",
"0.63158876",
"0.6298302",
"0.62887657",
"0.62887657",
"0.62276804",
"0.6226778",
"0.62242013",
"0.61590016",
"0.61296135",
"0.6110253",
"0.6106285",
"0.6106285",
"0.6106285",
"0.6056375",
"0.6039916",
"0.5989934",
"0.59836614",
"0.5974042",
"0.5945244",
"0.58763856",
"0.58763856",
"0.5873021",
"0.58650345",
"0.58619976",
"0.58608717",
"0.5844963",
"0.5799658",
"0.5797321",
"0.5785606",
"0.5785606",
"0.5768755",
"0.57623583",
"0.57476145",
"0.57373977",
"0.5729792",
"0.572875",
"0.57264215",
"0.5720418",
"0.57010716",
"0.5690675",
"0.56703013",
"0.56644183",
"0.56349015",
"0.56109834",
"0.560658",
"0.5603571",
"0.5564734",
"0.5560117",
"0.55449045",
"0.55322266",
"0.5515417",
"0.5512069",
"0.5508038",
"0.5495139",
"0.5493915",
"0.5483127",
"0.5482762",
"0.5473872",
"0.5460363",
"0.5458115",
"0.54562217",
"0.5439168",
"0.5438168",
"0.54320866",
"0.5418247",
"0.5417121",
"0.54134095",
"0.5404163",
"0.540263",
"0.53972775",
"0.5390664",
"0.5381467",
"0.5369684",
"0.5368493",
"0.53582287",
"0.53547466",
"0.53534496",
"0.534857",
"0.53481805",
"0.534688",
"0.5338301",
"0.53339815",
"0.53301495",
"0.5326447",
"0.5321749",
"0.53217196",
"0.53168416",
"0.53158176"
] | 0.64256036 | 10 |
Called by the event loop whenever data has been received by the network connection. It's called with a single parameter, a String containing the network protocol data, which may of course be binary. You will generally overwrite this method to perform your own processing of the incoming data. | def receive_data(data)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def receive_binary_data data\n # no-op\n end",
"def receive_data(data)\n self.received_data += data\n process_data if data.end_with?(\"\\n\")\n end",
"def receive data\n data.each_char do |char|\n @buffer.concat char\n if @in_header\n prepare_to_parse_message if @buffer.end_with?(\"\\r\\n\\r\\n\")\n else\n parse_message_from_buffer if @buffer.bytesize == @content_length\n end\n end\n end",
"def receiving(data); end",
"def receiving(data); end",
"def receive_data(data)\n split_data = data.split(\"\\n\")\n @received = @received + split_data\n @@log.warn \"#{self} receive_data ...\"\n @@log.debug \"#{self} \\n<<<#{data}>>>\"\n end",
"def receive_data(data)\n handle(data)\n end",
"def receive_data(data)\n data = UTF8Cleaner.clean(data)\n begin\n Skates.logger.debug {\n \"RECEIVED : #{data}\"\n }\n @parser.push(data) \n rescue\n Skates.logger.error {\n \"#{$!}\\n#{$!.backtrace.join(\"\\n\")}\"\n }\n end\n end",
"def receive(data); end",
"def receive_data(data)\n Babylon.logger.debug(\"RECEIVED : #{data}\")\n @parser.push(data)\n end",
"def receive_data(data)\n data.chomp!\n port, ip = Socket.unpack_sockaddr_in(self.get_peername)\n\n @@logger.debug(\"R [#{ip}:#{port}] #{data}\")\n self.handle_command(data)\n end",
"def receive_data(data)\n # puts \"From #{(@player || @connector).inspect} #{ip_address}:\"\n # puts \"> \" + data.inspect\n \n benchmark do\n if @player\n @player.handle_input(data.strip)\n else\n @connector.handle_input(data.strip)\n end\n end\n rescue Exception => e\n raise e #if AEON_ENV == :test\n end",
"def receive_data(data)\n logdebug \"receive_data:\", :data => data\n end",
"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",
"def receive_data data\n if @telnet_options[:telnet_mode]\n c = @input_rest + data\n se_pos = c.rindex(/#{IAC}#{SE}/no) || 0\n sb_pos = c.rindex(/#{IAC}#{SB}/no) || 0\n if se_pos < sb_pos\n buf = preprocess_telnet(c[0 ... sb_pos])\n @input_rest = c[sb_pos .. -1]\n\n elsif pt_pos = c.rindex(\n /#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\\z/no) ||\n c.rindex(/\\r\\z/no)\n\n buf = preprocess_telnet(c[0 ... pt_pos])\n @input_rest = c[pt_pos .. -1]\n\n else\n buf = preprocess_telnet(c)\n @input_rest.clear\n end\n else\n # Not Telnetmode.\n #\n # We cannot use #preprocess_telnet on this data, because that\n # method makes some Telnetmode-specific assumptions.\n buf = @input_rest + data\n @input_rest.clear\n unless @telnet_options[:bin_mode]\n if pt_pos = buf.rindex(/\\r\\z/no)\n buf = buf[0 ... pt_pos]\n @input_rest = buf[pt_pos .. -1]\n end\n buf.gsub!(/#{EOL}/no, \"\\n\")\n end\n end\n\n # in case only telnet sequences were received\n return if buf.empty?\n\n # append output from server to input buffer and log it\n @input_buffer << buf\n log_output buf, true\n\n # cancel the timer for wait_time value because we received more data\n if @wait_time_timer\n @wait_time_timer.cancel\n @wait_time_timer = nil\n end\n\n # we only need to do something if there's a connection state callback\n return unless @connection_state_callback\n\n # we ensure there's no timer running to check the input buffer\n if @check_input_buffer_timer\n @check_input_buffer_timer.cancel\n @check_input_buffer_timer = nil\n end\n\n if @input_buffer.size >= 100_000\n ##\n # if the input buffer is really big\n #\n\n # We postpone checking the input buffer by one second because the regular\n # expression matches can get quite slow.\n #\n # So as long as data is received (continuously), the input buffer is not\n # checked. It's only checked one second after the whole output has been\n # received.\n @check_input_buffer_timer = EventMachine::Timer.new(1) do\n @check_input_buffer_timer = nil\n check_input_buffer\n end\n else\n ##\n # as long as the input buffer is small\n #\n\n # check the input buffer now\n check_input_buffer\n end\n end",
"def receive_data data\n #log.debug { \"Receiving data (#{data.size} bytes)\" }\n @lock.synchronize { @parser.parse(data) }\n rescue\n log.warn { \"Error handling data: #{data.hth}\" }\n p $!; puts *$@\n end",
"def receive_data( data )\n emit( 'data_received', data )\n # TODO: Handle when a line contains \\n and when data are trunkated (buff).\n data.split(\"\\n\").map { |line|\n receive_line( line.strip )\n }\n end",
"def receive_end_of_binary_data\n # no-op\n end",
"def receive_data(data)\n\n if data.match 'SOURCE'\n p data\n send_data(\"HTTP 200 OK\\r\\n\\r\\n\")\n else\n # require 'pry'; binding.pry\n p data.size\n @channel.push(data.bytes)\n end\n end",
"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 receive_data(data)\n (@buffer ||= BufferedTokenizer.new(delimiter = \"__1_EE\")).extract(data).each do |line|\n #strip newline at beginning of line\n if line.match(/^\\W{1}./)\n line = line[1..line.length-1]\n end\n if line.valid?\n log_entry(line)\n send_data \"0\"\n else\n port, ip = Socket.unpack_sockaddr_in(get_peername)\n host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]\n ActiveRecord::Base.logger.error \"Dropped log entry from #{host} - checksum invalid\"\n send_data \"99\"\n end\n end\n end",
"def receive_data(data)\n @buffer.extract(data).each do |line|\n port, host = Socket.unpack_sockaddr_in(self.get_peername)\n # Trim trailing newlines \n @receiver.receive(host, port, line.chomp)\n end\n end",
"def receive_data &block\n self.on_data_received = block\n end",
"def receive_data(data)\n self.data_received_from_upstream << data\n @parser << data unless is_ssl\n self.client.send_data(data)\n end",
"def receive_data(data)\n @data_last_received_at = Time.now\n\n @parser.parse_data(data)\n end",
"def as_received\n raw_data\n end",
"def receive_data(data)\n port, host = Socket.unpack_sockaddr_in(self.get_peername)\n # Trim trailing newlines \n @receiver.receive(host, port, data.chomp)\n end",
"def process_data\n begin\n data = ::ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(received_data))\n packet = ::Syncano::Packets::Base.instantize_packet(data)\n\n if packet.notification?\n notification = ::Syncano::Resources::Notifications::Base.instantize_notification(client, packet)\n\n callbacks_queue.each do |callback_name|\n callbacks[callback_name].call(notification)\n end\n elsif packet.call_response?\n queue_response(packet)\n elsif packet.auth?\n queue_response(packet)\n end\n\n self.received_data = ''\n rescue Exception => e\n p 'EXCEPTION!'\n p e.inspect\n end\n end",
"def receive_data(data)\n #@logger.trace { \">>> #{data.inspect}\" }\n @buffer.receive(data) do |message_type_char, raw_message|\n @message = MosesPG::Message.create(message_type_char, raw_message)\n @logger.trace { \">>> #{@message}\" }\n @message.events.each { |event| send(event) }\n end\n self\n end",
"def receive_data data\n data.lines.each { |line| receive_line line }\n end",
"def receive_data(data)\n @in << data\n send(@state)\n rescue => e\n handle_error(e)\n end",
"def receive_data(data)\n\t\t$logger.warn(\"receive_data() not implemented\")\n\tend",
"def receive_data(data)\n log_debug '[server] receive_data: %s' % data\n @buffer << data\n handle_client if @buffer.flushed?\n end",
"def receive(data)\n @buffer.concat(data)\n while s = @buffer.scan(/.*?\\n/)\n forward(s.strip)\n end\n nil\n end",
"def receive_data(data)\n Blather.logger.debug \"\\n#{'-'*30}\\n\"\n Blather.logger.debug \"STREAM IN: #{data}\"\n @parser << data\n\n rescue ParseError => e\n @error = e\n send \"<stream:error><xml-not-well-formed xmlns='#{StreamError::STREAM_ERR_NS}'/></stream:error>\"\n stop\n end",
"def receive_data(data)\n Blather.logger.debug \"\\n#{'-'*30}\\n\"\n Blather.logger.debug \"STREAM IN: #{data}\"\n @parser << data\n\n rescue ParseError => e\n @error = e\n send_data \"<stream:error><xml-not-well-formed xmlns='#{StreamError::STREAM_ERR_NS}'/></stream:error>\"\n stop\n rescue => e\n Blather.logger.debug e\n Blather.logger.debug e.backtrace.join(\"\\n\")\n end",
"def receive_data(data)\n case @state\n when :protocol_proposal\n deferrable = @in_flight\n @state = :idle\n @in_flight = nil\n if data == 'ok'\n send_next_request\n deferrable.succeed\n else\n close_connection\n deferrable.fail(\"server response: #{data.inspect}\")\n end\n\n when :request\n @recv_buf << data\n response_size = @recv_buf.unpack('N').first\n if response_size && @recv_buf.bytesize >= response_size + 4\n response = @recv_buf[4, response_size]\n deferrable = @in_flight\n @state = :idle\n @in_flight = @recv_buf = nil\n send_next_request\n deferrable.succeed(response)\n end\n\n else\n raise \"Received data in unexpected state: #{@state.inspect}\"\n end\n end",
"def receive_data(data)\n # p \"|<-- #{data}\"\n @parser << data\n end",
"def receive_stream_data(data)\n begin\n @buffer.extract(data).each do |line|\n parse_stream_line(line)\n end\n @stream = ''\n rescue => e\n receive_error(\"#{e.class}: \" + [e.message, e.backtrace].flatten.join(\"\\n\\t\"))\n close_connection\n return\n end\n end",
"def receive_data data\n (@buf ||= '') << data\n\n while @buf.slice!(/(.*?)\\r?\\n/)\n receive_line($1)\n end\n end",
"def receive_data data\n #puts \"receive data #{data.dump} |(#{data.length})\"\n if data.length == 0\n close\n end\n @response_data += data\n remaining_unhandled_data = handle_data @response_data\n @response_data = remaining_unhandled_data\n end",
"def receive_data data\n (@buffer||='') << data\n\n while index = @buffer.index(Cdelimiter)\n begin\n line = @buffer.slice!(0,index+2)\n process_cmd line\n rescue ParserError\n @buffer[0...0] = line\n break\n end\n end\n end",
"def on_data(socket, data)\n buffer = @packet_buffers[socket]\n\n if buffer\n buffer.buffer_data data\n\n while packet = buffer.next_packet\n on_msg(socket, Marshal.load(packet))\n end\n end\n end",
"def receive_data(data)\n forwarder = Forwarder.new(host, data.strip, ports)\n send_data(forwarder.start)\n close_connection_after_writing\n end",
"def receive_data data\n if @state == :state_playing\n @bust_prompt = true\n $last_sent = '\\n'\n end\n\n data = \"\\n\" if data == nil\n data.gsub!(/\\r\\n|\\n\\r|\\r|\\n/,\"\\n\")\n data = \"\\n\" if data.empty?\n\n # separates telnet sequence from main data stream. Returns the telnet sequences in their own string in the queue.\n a = @network_parser.resume data\n\n a.each do |d|\n data.gsub!(/\\n/, \"\")\n if d.length == 0\n a.delete d\n end\n end \n \n a << \"\" if a.empty?\n\n a.each do |d|\n @input_queue.push d\n end\n \n ## Ok, check we need to shift a command off the top.\n while !@input_queue.empty?\n comm = @input_queue.shift\n \n return if comm == nil \n\n # next if comm.length == 0\n if comm.length != 0 && comm[0].ord == IAC\n # let's see if it matches one we know of.\n do_mxp = DO_MXP \n dont_mxp = DONT_MXP\n do_mccp = DO_MCCP\n dont_mccp = DONT_MCCP \n\n if do_mccp == comm\n log :debug, \"telnet do mccp sequence detected.\"\n# mccp_initialize(self)\n end\n if do_mxp == comm\n mxp_initialize(self)\n log :debug, \"telnet do mxp sequence detected.\"\n end \n log :debug, \"telnet sequence detected.\"\n next ### it's a telnet sequence\n end\n case @state\n when :state_new_connection\n if @nanny.alive?\n if (@nanny.resume comm.downcase) == true\n text_to_socket \"Closing connection.\" + ENDL\n close_connection\n return\n end\n end\n when :state_playing\n \n handle_cmd_input comm\n else\n log :error, \"Socket in bad state.\"\n end\n end\n end",
"def receive_data(data)\n while not (data.nil? or data.empty?)\n data.force_encoding 'BINARY' if data.respond_to?(:force_encoding)\n unless @payload_bytes_to_read\n nul = data.index ?\\0\n if nul\n @buffer << data.slice!(0, nul)\n data.slice!(0,1) # Remove the NUL\n metadata = @buffer.join('')\n @buffer = []\n begin\n receive_metadata(metadata)\n rescue Exception => e\n log_exception(e, 'Invalid metadata', metadata)\n close_connection\n return\n end\n else\n @buffer << data\n data = nil\n end\n end\n if @payload_bytes_to_read\n if data.size >= @payload_bytes_to_read\n @buffer << data.slice!(0, @payload_bytes_to_read)\n payload = @buffer.join('')\n @buffer, @payload_bytes_to_read = [], nil\n begin\n receive_payload(payload)\n rescue Exception => e\n log_exception(e, 'Invalid payload')\n close_connection\n return\n end\n else\n @buffer << data\n @payload_bytes_to_read -= data.size\n data = nil\n end\n end\n end\n end",
"def receive_data data\n @buf.extract(data).each do |packet|\n begin\n request = JSON::parse(packet)\n log.debug { request }\n case request['method']\n when \"relay_tx\"\n return handle_relay_tx(request, *request['params'])\n when \"monitor\"\n respond(request, handle_monitor(request, *request['params']))\n else\n if respond_to?(\"handle_#{request['method']}\")\n respond(request, send(\"handle_#{request['method']}\", *request['params']))\n else\n respond(request, { error: \"unknown command: #{request['method']}. send 'help' for help.\" })\n end\n end\n rescue\n respond(request, { error: $!.message })\n end\n end\n rescue Exception\n p $!; puts *$@\n end",
"def receive_data data\n puts \"%% Parser got: #{data}\" if $options[:debug]\n @parser << data\n end",
"def fetch(length)\n # This callback should be set just once, yielding with the parsed message\n @driver.on(:message) { |msg| yield(msg.data.pack('C*')) } if @driver.listeners(:message).length.zero?\n\n data = @sock.read_nonblock(length) # Read from the socket\n @driver.parse(data) # Parse the incoming data, run the callback from above\n end",
"def receive_data(data)\n log_debug { '[server] receive_data: %s' % data }\n\n @request_buffer << data\n @request_data = @request_buffer.data\n @stats.request_size = @request_buffer.size\n\n handle_client if @request_buffer.flushed?\n end",
"def receive_data(data)\n @buffer << data\n end",
"def handle_message(data)\n if @encoding == :etf\n handle_etf_message(data)\n else\n handle_json_message(data)\n end\n end",
"def receive_data(data)\n @server_parser.parse(data) do |packet|\n debug \"server --> #{packet.inspect}\"\n state.update packet\n\n if packet.kind == :disconnect\n log \"server disconnect: #{packet.message}\"\n EM.stop\n end\n\n handle packet\n\n if current_action\n current_action.update(packet)\n send_pending_action_packets\n end\n end\n rescue => e\n STDERR.puts e.inspect\n EM.stop\n raise\n end",
"def receive_data data\n @buf.extract(data).each do |line|\n @lines_received += 1\n @bytes_received += line.bytesize\n\n receive_line line.chomp\n end\n end",
"def receive_data(data)\n @last_data_received_at = Time.now\n @parser << data\n end",
"def receive_data(data)\n puts \"-- From #{@player || @connector} #{ip_address}:\"\n puts \"-- \" + data.inspect.yellow\n \n benchmark do\n if @player\n @player.handle_input(data)\n else\n @connector.handle_input(data)\n end\n end\n # rescue => e\n # # We want errors to be raised when Aeon is in test mode.\n # Aeon.mode == :test ? raise(e) : Aeon.logger.error(e)\n end",
"def receive_data data\n return unless (data and data.length > 0)\n\n # Do this stuff in lieu of a constructor.\n @lt2_mode ||= :lines\n @lt2_delimiter ||= \"\\n\"\n @lt2_linebuffer ||= []\n\n remaining_data = data\n\n while remaining_data.length > 0\n if @lt2_mode == :lines\n delimiter_string = case @lt2_delimiter\n when Regexp\n remaining_data.slice(@lt2_delimiter)\n else\n @lt2_delimiter\n end\n ix = remaining_data.index(delimiter_string) if delimiter_string\n if ix\n @lt2_linebuffer << remaining_data[0...ix]\n ln = @lt2_linebuffer.join\n @lt2_linebuffer.clear\n if @lt2_delimiter == \"\\n\"\n ln.chomp!\n end\n receive_line ln\n remaining_data = remaining_data[(ix+delimiter_string.length)..-1]\n else\n @lt2_linebuffer << remaining_data\n remaining_data = \"\"\n end\n elsif @lt2_mode == :text\n if @lt2_textsize\n needed = @lt2_textsize - @lt2_textpos\n will_take = if remaining_data.length > needed\n needed\n else\n remaining_data.length\n end\n\n @lt2_textbuffer << remaining_data[0...will_take]\n tail = remaining_data[will_take..-1]\n\n @lt2_textpos += will_take\n if @lt2_textpos >= @lt2_textsize\n # Reset line mode (the default behavior) BEFORE calling the\n # receive_binary_data. This makes it possible for user code\n # to call set_text_mode, enabling chains of text blocks\n # (which can possibly be of different sizes).\n set_line_mode\n receive_binary_data @lt2_textbuffer.join\n receive_end_of_binary_data\n end\n\n remaining_data = tail\n else\n receive_binary_data remaining_data\n remaining_data = \"\"\n end\n end\n end\n end",
"def receive_data(data)\n @client.send_command(SendDataCommand.new(@connection_id, data))\n end",
"def receive_data data\n begin\n # log 'receive_data', data\n @buf << data\n\n while frame = Frame.parse(@buf)\n log 'receive', frame\n process_frame frame\n end\n rescue Exception => e\n logger.exception(\"[amqp] Failed processing frame, closing connection\", e, :trace) unless ENV['IGNORE_AMQP_FAILURES']\n failed\n end\n end",
"def on_data(payload)\n # Do stuff with the payload\n Troph::Log.info \"received nomination message: #{payload}\"\n end",
"def receive_data data\n\t\tputs \"............>>>#{data.length}\"\n\tend",
"def received\n end",
"def receive_data(data)\n @idle = false\n trace data\n process if @request.parse(data)\n rescue InvalidRequest => e\n log_error(\"Invalid request\", e)\n post_process Response::BAD_REQUEST\n end",
"def receive_data(data)\n data.split(\"\\n\").each do |d|\n @test_controller.notify({source: \"statsd-router\", text: d})\n end\n end",
"def receive(data)\n puts data\n end",
"def receive(data)\n puts data\n end",
"def receive_data(data)\n # a large json-rpc message may be split over multiple packets\n # (invocations of receive_data)\n # and multiple messages may be concatinated into one packet\n @data += data\n while extracted = JSONParser.extract_json_from(@data)\n msg, @data = *extracted\n @rjr_node.send(:handle_message, msg, self) # XXX private method\n end\n end",
"def on_message_data_receiving_event(ctx) end",
"def receive_data(data)\n (@buffer ||= '') << data\n while index = @buffer.index(DELIM)\n begin\n line = @buffer.slice!(0, index+2)\n process_cmd line\n rescue ParserError\n @buffer[0...0] = line\n break\n end\n end\n end",
"def receive_data(data)\n @buffer += data\n\n until @buffer.empty?\n\n eol = @buffer.index(CRLF)\n \n # Include IMAP literals on the same line.\n # The format for a literal is \"{8}\\r\\n........\"\n # so the size would be at the end of what we thought was the line.\n # We then skip over that much, and try looking for the next newline.\n # (The newline after a literal is the end of the actual line,\n # there's no termination marker for literals).\n while eol && @buffer[0, eol][/\\{(\\d+)\\}\\z/]\n eol = @buffer.index(CRLF, eol + CRLF.size + $1.to_i)\n end\n\n # The current line is not yet complete, wait for more data.\n return unless eol\n\n line = @buffer.slice!(0, eol + CRLF.size)\n\n receive_response parse(line)\n end\n end",
"def onData(data,_chan,_event)\n id = @config[:radix][:id]\n me = \"#{id}/#{__method__}\" \n @log.info(\"[#{me}]\")\n begin\n dec = dechan(data,_chan,_event)\n @log.debug(\"[#{me}] data size: #{dec.to_s.size}\")\n rescue Exception => ex\n @log.debug(\"[#{me}] data error: #{ex.inspect}\") \n end\n # TODO: send to the local queue and to dashing\n end",
"def do_recv()\n data = super()\n message = Hurricane::Message.new()\n message.type = data.data[0].name\n message.destination = data.data[1]\n message.tag = data.data[2]\n message.data = data.data[3]\n message\n end",
"def receive_data(chunk)\n @chunk_buffer << chunk\n while frame = next_frame\n self.receive_frame(AMQ::Client::StringAdapter::Frame.decode(frame))\n end\n end",
"def receive_data(data)\n buffer.concat(data)\n end",
"def receive_data\n if @socket\n # udp receive\n @socket.recvfrom(1024)\n else\n # tcp receive\n sleep 0.1\n if $received_data\n $received_data.shift\n else\n fail 'no data'\n end\n end\n end",
"def receive\n parse(recv)\n end",
"def receive_data(data)\n data.chomp!\n @@count = @@count + 1\n puts(\"Count : #{@@count} - Data : #{data}\")\n end",
"def receive_data data\n command preprocess_data(data), @command_groups, true\n end",
"def process_data\n unless @state.include?(:rcpt)\n send_data \"503 Operation sequence error\\r\\n\"\n else\n succeeded = proc {\n send_data \"354 Send it\\r\\n\"\n @state << :data\n @databuffer = []\n }\n failed = proc {\n send_data \"550 Operation failed\\r\\n\"\n }\n\n d = receive_data_command\n\n if d.respond_to?(:callback)\n d.callback(&succeeded)\n d.errback(&failed)\n else\n (d ? succeeded : failed).call\n end\n end\n end",
"def receive_data(chunk)\n @chunk_buffer << chunk\n while frame = get_next_frame\n receive_frame(AMQ::Client::Framing::String::Frame.decode(frame))\n end\n end",
"def receive_data(data)\n @buffer.extract(data).each do |line|\n payload = { :uuid => @uuid, \n :message => line,\n :host => @host,\n :user => @user }\n @global_history_fanout.publish(payload.to_json)\n end\n end",
"def receive_data data, recursive = false\n # if recursive is true we already invoked the receive data callbacks!\n unless recursive\n receive_data_callbacks.each do |callback|\n EM.next_tick do\n callback.call data.dup\n end\n end\n end\n @linebuffer ||= []\n @lf_offset ||= 0\n\n parse_crlf data\n\n receive_update @outputbuffer.string unless recursive\n end",
"def proxy_receive_data data\n @proxystatus = :headers if !@proxystatus\n \n if @proxystatus == :headers\n # First gather the headers\n @proxybuffer += data\n if @proxybuffer =~ /\\r\\n\\r\\n/\n\n # Detected end of headers\n header_data = @proxybuffer[0...($~.begin(0))]\n @proxybuffer = @proxybuffer[($~.end(0))..-1]\n\n # Try the webrick parser\n headers = {}\n header_lines = header_data.split(/[\\r\\n]+/)\n status = header_lines[0]\n header_lines[1..-1].each do |line|\n h = line.split(/:\\s*/, 2)\n headers[h[0]] = h[1]\n end\n \n # The rest of the incoming connection \n @proxystatus = :stream\n end\n end\n \n if @proxystatus == :stream\n send_data header_lines[0] + \"\\r\\n\"\n send_data \"Content-Type: \" + headers['Content-Type'] + \"\\r\\n\"\n send_data \"Content-Length: \" + headers['Content-Length'] + \"\\r\\n\"\n send_data \"\\r\\n\"\n send_data @proxybuffer\n\n # Any further data is piped through \n EM::enable_proxy proxy_conn, self, 1024*10\n end\n end",
"def receive_data(data)\n\t@buffer.clear if (@buffer.size + data.size) > 1000\n\t@buffer += data\n\n\tif @buffer.unpack('C4Nn2N4C16C192NC*').include?($DHCP_MAGIC)\n\t process_message(@buffer.dup)\n\t @buffer.clear\n\tend\n end",
"def receive_data(monitoring_datagram)\n monitoring_datagram.chomp!\n source_port, source_ip = Socket.unpack_sockaddr_in(get_peername)\n unless monitoring_datagram.start_with?(DATAGRAM_PREFIX)\n ::OnesnooperServer::Log.warn \"[#{self.class.name}] Discarding datagram from \" \\\n \"#{source_ip}:#{source_port} (not #{DATAGRAM_PREFIX})\"\n return\n end\n\n ::OnesnooperServer::Log.debug \"[#{self.class.name}] Received #{monitoring_datagram.inspect} \" \\\n \"from #{source_ip}:#{source_port}\"\n ::OnesnooperServer::RequestHandler.parse(\n monitoring_datagram,\n source_ip,\n source_port,\n @store_instances\n ).run(callback)\n end",
"def do_data( channel, data )\n if @parsed_data\n @parsed_data[:content].append data\n return if @parsed_data[:length] > @parsed_data[:content].length\n\n type = @parsed_data[:type]\n content = @parsed_data[:content]\n @parsed_data = nil\n else\n reader = @buffers.reader( data )\n length = reader.read_long-1\n type = reader.read_byte\n content = reader.remainder_as_buffer\n\n if length > content.length\n @parsed_data = { :length => length,\n :type => type,\n :content => content }\n return\n end\n end\n\n if type == FXP_VERSION\n do_version content\n else\n assert_state :open\n @dispatcher.dispatch channel, type, content\n end\n end",
"def receive_internal_data data\n @tokenizer.extract(data) do |b_data|\n data_obj = load_data(b_data)\n receive_data(data_obj) if data_obj\n end\n end",
"def on_data(&block)\n connection = CodeBlockConnection::OnData.new(self,block)\n add_connection(connection)\n connection\n end",
"def on_message_data_event(ctx); end",
"def read_incoming_data\n begin\n line = @socket.gets\n rescue StandardError => boom\n @dead_socket = true\n report \"+++ERROR in read_incoming_data -> @socket.gets: #{boom.inspect}\"\n end\n\n # If we somehow got no data here, the socket is closed. Run away!!!\n if !line\n @dead_socket = true\n return\n end\n\n line.chomp!\n\n report \"+++INCOMING: #{line}\" if @loud\n\n # Only synchronize long enough to push our incoming string onto the\n # input buffer\n @input_buffer_mutex.synchronize do\n @input_buffer.push(line)\n end\n end",
"def on_raw_data(&block)\n connection = CodeBlockConnection::OnRawData.new(self,block)\n add_connection(connection)\n connection\n end",
"def receive_data data\n @connection_attempts = 0\n @buffer.extract(data).each do |packet|\n response = JSON.parse(packet)\n log.debug { d = response['result'].inspect\n \"response: #{response['method']} #{d[0...50]}#{d.size > 50 ? '...' : ''}\" }\n if cb = @requests[response['id']]\n cb.call(response['result'])\n else\n callback(:response, response['method'], response['result'])\n callback(response['method'].to_sym, response['result'])\n end\n end\n end",
"def on_data_received= proc\n @on_data_received = proc\n drain\n end",
"def recv\n data = String.new\n data << @socket.gets until data.match(/\\r\\n$/)\n Parser.parse(data)\n end",
"def receive_data(data)\n msg = nil\n begin\n msg = Resolv::DNS::Message.decode data\n rescue\n else\n req = @requests[msg.id]\n if req\n @requests.delete(msg.id)\n req.receive_answer(msg)\n end\n end\n end",
"def on_message_data_event(ctx) end",
"def on_message(event)\n data = if @inflate\n packed = event.data.pack('c*')\n @inflate << packed\n return unless packed.end_with?(ZLIB_SUFFIX)\n\n @inflate.inflate('')\n else\n event.data\n end\n\n LOGGER.debug { \"[IN] #{data[0].ord == 131 ? data.inspect : data}\" }\n emit(:message, data)\n end",
"def handle(data)\n\t\t\t\tprocess_line(data)\n\t\t\tend",
"def on_message data\n\t\t# broadcast sends an asynchronous message to all sibling instances, but not to self.\n\t\tdata = ERB::Util.html_escape data\n\t\tbroadcast :_print_out, data\n\t\tresponse << \"You said: #{data}\"\n\t\tresponse << (request.ssl? ? \"FYI: Yes, This is an SSL connection...\" : \"FYI: Nope, this isn't an SSL connection (clear text).\") if data.match /ssl\\?/i\nend",
"def receive_data(data)\n data.each_char do |char|\n if char == @end_seq[ @end_i ]\n if @end_i == @end_seq.size-1\n @minerd.send_detach\n EM.stop\n return\n end\n\n @end_i += 1\n\n if @end_i == 1\n @private_buffer += char\n\n else\n @buffer += char\n end\n\n elsif char == @end_seq.first\n @private_buffer += char\n\n else\n @end_i = 0\n\n unless @private_buffer.empty?\n @buffer += @private_buffer\n @private_buffer.clear\n end\n\n @buffer += char\n end\n end\n\n @minerd.send_write(@buffer)\n @buffer.clear\n end"
] | [
"0.7287591",
"0.6997978",
"0.6995834",
"0.69918716",
"0.69918716",
"0.6922707",
"0.6887814",
"0.6799326",
"0.67842966",
"0.676754",
"0.6760229",
"0.67588294",
"0.6680338",
"0.66706926",
"0.66583735",
"0.6651172",
"0.66433084",
"0.6616395",
"0.66030884",
"0.6594346",
"0.6572307",
"0.6561833",
"0.65565425",
"0.654761",
"0.6538961",
"0.65335184",
"0.6522138",
"0.6513115",
"0.650585",
"0.650457",
"0.65013397",
"0.6474945",
"0.64704645",
"0.64565796",
"0.6446544",
"0.64384836",
"0.64379287",
"0.64360434",
"0.6408987",
"0.6403909",
"0.639604",
"0.63479674",
"0.63331515",
"0.6331211",
"0.63306355",
"0.63260317",
"0.6316366",
"0.6315478",
"0.6307429",
"0.6284972",
"0.6284401",
"0.6283689",
"0.628142",
"0.62674224",
"0.6257674",
"0.625432",
"0.6250404",
"0.6248502",
"0.6246074",
"0.6229833",
"0.6213843",
"0.6213451",
"0.61864555",
"0.6181361",
"0.61755633",
"0.61755633",
"0.61637855",
"0.6157297",
"0.61359614",
"0.6119689",
"0.6099447",
"0.60981894",
"0.6079355",
"0.6074073",
"0.607213",
"0.6068916",
"0.60668737",
"0.6050214",
"0.6048864",
"0.6027902",
"0.6020641",
"0.6015497",
"0.60056925",
"0.59832346",
"0.5982416",
"0.5963045",
"0.5957704",
"0.592739",
"0.5924151",
"0.59187376",
"0.59121233",
"0.5891185",
"0.5887905",
"0.58774436",
"0.5873585",
"0.58650047",
"0.5853033",
"0.5849907",
"0.5832452",
"0.58287126"
] | 0.69325876 | 5 |
Send the data to the remote end of the connection asynchronously. | def send_data(data)
@impl.send_data data
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def send_data(*args)\n EM.next_tick do\n @socket.send_data(*args)\n end\n end",
"def send(data)\r\n @connected.callback { send_data data }\r\n end",
"def send(data)\r\n @connected.callback { send_data data }\r\n end",
"def send_data(*args)\n EM.next_tick do\n @socket.send_data(*args)\n end\n end",
"def _send_data(data)\n send_data(data + \"\\r\\n\")\n end",
"def send_and_get_data data\n send_data data\n get_data_with_timeout data.size\n end",
"def send data\n data = [data.bytesize, *data.bytes].pack 'NC*'\n\n @socket.send data, 0\n end",
"def send(data)\n @conn.send serialize data\n end",
"def send_eof\n msg = @buffers.writer\n msg.write_byte CHANNEL_EOF\n msg.write_long @remote_id\n @connection.send_message msg\n self\n end",
"def send(data)\n @socket.send(data, SEND_FLAGS)\n end",
"def send_data(data)\n logdebug \"send_data:\", :data => data\n attempt_write(data)\n end",
"def send_msg(data)\n @send_lock.synchronize{\n TCP.em.schedule { send_data(data) }\n }\n end",
"def send_data(data)\n \n return nil if @connection.nil? or data.nil? or data.empty? \n \n begin\n @connection.send(data, 0)\n puts \"#{self.class} send to #{@tcp_ip}:#{@tcp_port} this: #{data.to_hex}\" if $debug\n rescue\n @connection = nil\n return nil\n end\n \n end",
"def send_data(data)\n super(data)\n puts \"#{self} send_data done: #{data.inspect}\"\n end",
"def send_data(data)\n super(data)\n puts \"#{self} send_data done: #{data.inspect}\"\n end",
"def send_raw(data)\n raise ::Pwnlib::Errors::EndOfTubeError if @conn.nil?\n\n data.gsub!(context.newline, \"\\r\\n\") if @convert_newlines\n begin\n @conn.write(data)\n rescue RubySerial::Error\n close\n raise ::Pwnlib::Errors::EndOfTubeError\n end\n end",
"def send_to peer\n peer.semaphore.synchronize do \n data = { id: service_id, data: self.data }.to_json\n buffer = Buffer::Writer.new data\n buffer.segments.each { |segment| peer.send_data segment }\n peer.last_used_at = Time.now\n sleep 0.3\n end\n end",
"def receive_data(data)\n @client.send_command(SendDataCommand.new(@connection_id, data))\n end",
"def apush\n socket = EM::Synchrony::TCPSocket.new('localhost', 22195)\n socket.write(to_bytes)\n socket.close\n end",
"def call\n\t\t\t\tAsync do\n\t\t\t\t\tendpoint.connect do |socket|\n\t\t\t\t\t\tstream = Async::IO::Stream.new(socket)\n\t\t\t\t\t\t\n\t\t\t\t\t\t@command.call(stream)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend",
"def send(data)\n @client.send(data)\n end",
"def send_data( data )\n raise \"channel not open\" unless @state == :open\n @channel.send_data data\n end",
"def send_data( data )\n\t\tjson = data.to_json\n\t\tbytes = json.bytesize\n\t\tputs \"SEND %3i bytes to %s: %s\" % [bytes,name,json] if $DEBUG\n\t\tunless @socket.closed?\n\t\t\t@socket.write [bytes].pack('n')\n\t\t\tunless @socket.closed?\n\t\t\t\t@socket.write(json) == bytes\n\t\t\tend\n\t\tend\n\tend",
"def flush\n @sendbuf_lock.synchronize {\n while @sendbuf.size > 0\n send_data(@sendbuf[0..@block_size-1])\n @sendbuf = @sendbuf[@block_size..-1].to_s\n end\n }\n end",
"def write(data)\n result = @socket.write(data)\n\n @socket.flush\n return result\n end",
"def send_raw(data)\n socket.send_raw data\n end",
"def send_data data\n super \"#{data}\\n\"\n Events.dispatch(:raw_out, Message.new(self, data, true))\n\n @lines_sent += 1\n @bytes_sent += data.bytesize + 1\n\n $log.debug(\"IRCConnection.send_data #{@name}\") { data }\n end",
"def write(data)\n ret = io.write data\n @receivers.each do |r|\n Fiber.new { r.call data }.resume\n end\n ret\n end",
"def sync_send\n sync_write.putc(\"!\")\n sync_write.flush\n end",
"def send_pending_data\n needs_looping = true\n while needs_looping\n needs_looping = false\n pending_data.delete_if do |socket, chunks|\n if chunks.empty?\n # nothing left to send for this socket\n next\n end\n\n buffer = chunks.shift\n while !chunks.empty? && (buffer.size + chunks[0].size < DATA_CHUNK_SIZE)\n buffer.concat(chunks.shift)\n end\n Server.debug \"sending #{buffer.size} bytes to #{socket}\"\n\n begin\n written = socket.write_nonblock(buffer)\n rescue Interrupt\n raise\n rescue Errno::EAGAIN\n Server.debug \"cannot send: send buffer full\"\n chunks.unshift(buffer)\n next\n rescue Exception => e\n Server.warn \"disconnecting from #{socket}: #{e.message}\"\n e.backtrace.each do |line|\n Server.warn \" #{line}\"\n end\n socket.close\n next(true)\n end\n\n remaining = buffer.size - written\n if remaining == 0\n Server.debug \"wrote complete chunk of #{written} bytes to #{socket}\"\n # Loop if we wrote the complete chunk and there\n # is still stuff to write for this socket\n needs_looping = !chunks.empty?\n else\n Server.debug \"wrote partial chunk #{written} bytes instead of #{buffer.size} bytes to #{socket}\"\n chunks.unshift(buffer[written, remaining])\n end\n false\n end\n end\n end",
"def send_raw(data)\n # puts \"Sending data\"\n # puts_data(data)\n write(data)\n end",
"def flush\n @socket&.flush\n end",
"def send_data(data)\n @lock.synchronize do\n\n @send_buffer += data\n limited_by_polling = (@last_send + @http_polling >= Time.now)\n limited_by_requests = (@pending_requests + 1 > @http_requests)\n\n # Can we send?\n if !limited_by_polling and !limited_by_requests\n data = @send_buffer\n @send_buffer = ''\n\n Thread.new do\n Thread.current.abort_on_exception = true\n post_data(data)\n end\n\n elsif !limited_by_requests\n Thread.new do\n Thread.current.abort_on_exception = true\n # Defer until @http_polling has expired\n wait = @last_send + @http_polling - Time.now\n sleep(wait) if wait > 0\n # Ignore locking, it's already threaded ;-)\n send_data('')\n end\n end\n\n end\n end",
"def write(data)\n rescue_writable do\n socket.write_nonblock(data)\n end\n end",
"def send_data( data )\n @connection.register_data_request( self, data )\n end",
"def run\n while true; async.handle_message @socket.read; end\n end",
"def write(data)\n begin\n @socket.sync = false\n if data.nil?\n write_timeout([0, 0, @seq].pack(\"CvC\"), @opts[:write_timeout])\n @seq = (@seq + 1) % 256\n else\n data = StringIO.new data if data.is_a? String\n while d = data.read(MAX_PACKET_LENGTH)\n write_timeout([d.length%256, d.length/256, @seq].pack(\"CvC\")+d, @opts[:write_timeout])\n @seq = (@seq + 1) % 256\n end\n end\n @socket.sync = true\n @socket.flush\n rescue Errno::EPIPE\n @socket.close rescue nil\n raise ClientError::ServerGoneError, 'MySQL server has gone away'\n rescue Errno::ETIMEDOUT\n raise ClientError, \"write timeout\"\n end\n end",
"def send( text )\n checkConnection()\n @conn.write( text + EOL )\n end",
"def send( text )\n checkConnection()\n @conn.write( text + EOL )\n end",
"def send! data\n send_output_io! data if @output_io || host\n send_log_io! data if log_io\n self\n end",
"def write(data)\n reset_timer\n\n loop do\n result = socket.write_nonblock(data, :exception => false)\n return result unless result == :wait_writable\n\n IO.select(nil, [socket], nil, time_left)\n log_time\n end\n end",
"def send_msg(data, connection)\n # TODO\n end",
"def write(data)\n reset_timer\n\n begin\n return socket.write_nonblock(data)\n rescue IO::WaitWritable\n IO.select(nil, [socket], nil, time_left)\n log_time\n retry\n end\n rescue EOFError\n :eof\n end",
"def send_event( data )\n\t\tuntil data.empty?\n\t\t\tbytes = self.socket.sendmsg_nonblock( data, 0, exception: false )\n\n\t\t\tif bytes == :wait_writable\n\t\t\t\tIO.select( nil, [self.socket], nil )\n\t\t\telse\n\t\t\t\tself.log.debug \"Sent: %p\" % [ data[0, bytes] ]\n\t\t\t\tdata[ 0, bytes ] = ''\n\t\t\tend\n\t\tend\n\tend",
"def send str\n\n @send_buffer.push [Time.now.to_i + @send_buffer_delay, str] if @send_buffer_delay > 0\n\n begin\n if @send_buffer_delay > 0\n Protocol.write @client, (@send_buffer.shift)[1], :debug => 5 if Time.now.to_i >= (@send_buffer.first)[0]\n else\n Protocol.write @client, str, :debug => 5\n end\n false\n rescue Exception=>e\n puts \"!D connection terminated: #{e}\" if Config.debug\n true\n end\n end",
"def send_data_packet( data )\n # overhead is ( byte.length + id.length + strlen.length ) = 9\n data, data_to_return = split_data_for_packet( data.to_s, 9 )\n @window_size -= data.length\n\n msg = @buffers.writer\n msg.write_byte CHANNEL_DATA\n msg.write_long @remote_id\n msg.write_string data\n @connection.send_message msg\n\n data_to_return\n end",
"def send_msg(data, connection)\n connection.send_msg(data)\n end",
"def send_data(data)\n super(data)\n @@log.warn \"#{self} send_data done: #{data.inspect}\"\n end",
"def blocking_write( data )\r\n raise RuntimeError, \"CONN_UDP: blocking_write: Not connected!\" unless connected?\r\n begin\r\n @sock.send(data, 0)\r\n rescue\r\n destroy_connection\r\n raise RuntimeError, \"CONN_UDP: blocking_write: Couldn't write to socket! (#{$!})\"\r\n end\r\n end",
"def send_data(data, type = :text)\n pid = Thread.new do\n do_send(data, type)\n end\n end",
"def send_async(method, *arguments); end",
"def send_msg(data, connection)\n # TODO\n end",
"def server_connection_success\n LOGGER.info \"Successful connection to #{@remote.join(':')}\"\n @connected = true\n @server_side.send_data(@buffer_out)\n @buffer_out = ''\n end",
"def send_data_to_server(data)\n if @use_http_tunnel\n send_data_with_http_tunnel(data)\n else\n status = Timeout::timeout(6) {\n @socket_srv.puts( data )\n }\n end\n rescue Timeout::Error\n @log.error \"Timeout error on send_data_to_server\"\n @cup_gui.log_sometext \"ERRORE: timeout connessione col server durante l'invio di dati \"\n rescue\n @log.error \"Error on send_data_to_server #{data}. Detail: #{$!}\"\n @cup_gui.log_sometext \"Errore connessione server (#{$!})\\n\"\n @socket_srv = nil\n end",
"def write(data)\n timeout = false\n loop do\n result = @socket.write_nonblock(data, :exception => false)\n return result unless result == :wait_writable\n\n raise TimeoutError, \"Write timed out after #{@write_timeout} seconds\" if timeout\n\n timeout = true unless @socket.to_io.wait_writable(@write_timeout)\n end\n end",
"def blocking_write( data )\n raise RuntimeError, \"RAWIP: blocking_write: Not connected!\" unless connected?\n begin\n @ssock.send(data, 0, @addr)\n rescue\n destroy_connection\n raise RuntimeError, \"RAWIP: blocking_write: Couldn't write to socket! (#{$!})\"\n end\n end",
"def send(data)\n debug [:send, data]\n send_data(\"\\x00#{data}\\xff\")\n end",
"def send(data)\n debug [:send, data]\n send_data(\"\\x00#{data}\\xff\")\n end",
"def do_data( data )\n @log.debug \"[#{@id}] got #{data.length} bytes\" if @log.debug?\n\n @data << data\n @progress_callback[@data] if @progress_callback\n\n if @length < 0 || @data.length < @length\n if @length < 0\n length = @chunk_size\n else\n length = @length - @data.length\n length = length > @chunk_size ? @chunk_size : length\n end\n\n @log.debug \"[#{@id}] requesting #{length} more bytes\" if @log.debug?\n @driver.read @id, @handle, @offset + @data.length, length\n @session.register( @id, self )\n else\n @callback[ OK, @data ]\n end\n end",
"def send_data(raw_data)\n encoded_message = encode(raw_data)\n Rails.logger.debug { \"#{Time.zone.now.getutc.inspect}: Sending to #{@socket.url}: #{encoded_message.inspect}\" }\n # Send the message to the WebSocket connection _immediately_\n # by scheduling it for the next execution of the EventMachine reactor run.\n # Otherwise, the message might be queued causing delays for users.\n EventMachine.next_tick do\n @socket.send(encoded_message)\n end\n end",
"def send_chunk(data)\n response.write('%x' % data.size + \"\\r\\n\")\n response.write(data + \"\\r\\n\")\n end",
"def send_with_reply( type, data=nil )\n send_packet type, data\n read_packet\n end",
"def receive_data(data)\n log \"<< #{data.size}\"\n @write_to_channel << data\n end",
"def receive_data(data)\n @write_to_channel << data\n end",
"def sends_data(data)\n script.sends_channel_data(self, data)\n end",
"def send(cmd)\n return false unless connected?\n while read_nonblock do end # flush previous response data\n @client.send(cmd, 0)\n @client.recv(256).strip\n end",
"def flush\n return @transport.flush unless @write\n\n out = [@wbuf.length].pack('N')\n out << @wbuf\n @transport.write(out)\n @transport.flush\n @wbuf = ''\n end",
"def flush\n return @transport.flush unless @write\n\n out = [@wbuf.length].pack('N')\n out << @wbuf\n @transport.write(out)\n @transport.flush\n @wbuf = ''\n end",
"def send_data(io, data)\n loop do\n n = io.syswrite(data)\n return if n == data.bytesize\n data = data[n..-1]\n end\n end",
"def flush\n @socket.flush if @socket\n end",
"def receive_data(data)\n data.each_char do |char|\n if char == @end_seq[ @end_i ]\n if @end_i == @end_seq.size-1\n @minerd.send_detach\n EM.stop\n return\n end\n\n @end_i += 1\n\n if @end_i == 1\n @private_buffer += char\n\n else\n @buffer += char\n end\n\n elsif char == @end_seq.first\n @private_buffer += char\n\n else\n @end_i = 0\n\n unless @private_buffer.empty?\n @buffer += @private_buffer\n @private_buffer.clear\n end\n\n @buffer += char\n end\n end\n\n @minerd.send_write(@buffer)\n @buffer.clear\n end",
"def flush\n self.channel.flush\n end",
"def flush\n self.channel.flush\n end",
"def flush\n if !@write\n return @transport.flush\n end\n\n out = [@wbuf.length].pack('N')\n out << @wbuf\n @transport.write(out)\n @transport.flush\n @wbuf = ''\n end",
"def write(s)\n @port.write(s)\n sleep(@wait_after_send / 1000.0) if @wait_after_send\n end",
"def write_to_socket bytes\n socket.write_nonblock bytes\n rescue IO::WaitWritable\n :wait_writable\n end",
"def send!\n @_sended = true\n self\n end",
"def send_data( type, data )\n data = data.to_s\n\n msg = @buffers.writer\n msg.write_long data.length + 1\n msg.write_byte type\n msg.write data\n\n @channel.send_data msg\n end",
"def receive_data(data)\n forwarder = Forwarder.new(host, data.strip, ports)\n send_data(forwarder.start)\n close_connection_after_writing\n end",
"def send_data(pipe, data)\n pipe.write(data, \"\\n#{MSG_ENDI}\\n\")\nend",
"def send( data )\n # Final text data header:\n header = 0b10000001\n\n # Payload size to use (data will always be unmasked):\n size = \"#{data}\".size\n\n # Standard payload:\n if size < 126 then\n @connection.write [ header, size, \"#{data}\" ].pack \"C2A#{size}\"\n\n # 16-bit extended payload:\n elsif size <= 65535 then\n bytes = [ size ].pack( \"S\" ).unpack( \"C2\" ).reverse.map( &:to_i )\n @connection.write [ header, 126, *bytes, \"#{data}\" ]\n .pack \"C4A#{size}\"\n\n # 64-bit extended payload:\n else\n bytes = [ size ].pack( \"S\" ).unpack( \"C8\" ).reverse.map( &:to_i )\n @connection.write [ header, 127, *bytes, \"#{data}\" ]\n .pack \"C10A#{size}\"\n end\n end",
"def connection_completed\n @connected = true\n send_request @args\n end",
"def write(*args)\n raise Errors::ConnectionFailure, \"Socket connection was closed by remote host\" unless alive?\n handle_socket_errors { super }\n end",
"def receive_data(data)\n\n if data.match 'SOURCE'\n p data\n send_data(\"HTTP 200 OK\\r\\n\\r\\n\")\n else\n # require 'pry'; binding.pry\n p data.size\n @channel.push(data.bytes)\n end\n end",
"def send(message)\n\t\t\t@conn.send(message)\n\t\tend",
"def write_remote(buf) \n\t\t\tdlog(\"PassiveX:#{self} Queuing #{buf.length} to remote side\", 'core', LEV_3)\n\n\t\t\t@remote_queue += buf\n\n\t\t\tflush_output\n\t\tend",
"def send_data(data, options = T.unsafe(nil)); end",
"def remote_command(command)\n socket = TCPSocket.new(@host, @port)\n socket.puts command\n\n data = \"\"\n until (line = socket.readline) =~ /END/\n data << line\n end\n\n socket.close\n data\n end",
"def send\n @sent_at = Time.now\n sender.publish(data, meta)\n self\n end",
"def write(data)\n @mutex.synchronize { @buffer = @buffer.dup.concat(data) }\n pump_buffer\n Reactor.selector.wakeup unless monitor.interests == :r\n end",
"def _send_message data\n response << data\n end",
"def connection_completed\n# @keepalive = EM::PeriodicTimer.new(60) { send_data ' ' }\n start\n end",
"def send_event( data )\n\n\t\tuntil data.empty?\n\t\t\tbytes = self.socket.send( data, 0, self.multicast_address, self.port )\n\n\t\t\tself.log.debug \"Sent: %p\" % [ data[0, bytes] ]\n\t\t\tdata[ 0, bytes ] = ''\n\t\tend\n\tend",
"def send!\n return if @buffer.empty?\n recursive_send(@buffer)\n @buffer.clear\n end",
"def deliver(data)\n @queue.enq data\n end",
"def realtime_sender() \n loop {\n @sender_plugin.send_data(@data.pop)\n }\n end",
"def send_data(value)\r\n msg = \"#{value.chop}\\r\\n\"\r\n @socket.print(msg)\r\n end",
"def puts data\n\t\t@write_semaphore.synchronize do\n\t\t\t@write_data = data\n\t\t\t@write_cv.signal\n\t\tend\n\tend",
"def send_all(event, data)\n\t\tEM.next_tick {\n\t\t\t@sockets.each do |s|\n\t\t\t\ts.send(event, data) \n\t\t\tend\n\t\t}\n\tend",
"def send_to_port(message, port)\n s = EventMachine::Synchrony::TCPSocket.new('127.0.0.1', port)\n s.write message\n data = ''\n recv = s.read(1)\n while recv\n data += recv\n recv = s.read(1)\n end\n s.close\n data\nend"
] | [
"0.66698295",
"0.6628655",
"0.6628655",
"0.6627564",
"0.6500473",
"0.6366982",
"0.63434035",
"0.62043387",
"0.6151476",
"0.6076242",
"0.6041061",
"0.6027718",
"0.6026118",
"0.60195225",
"0.60195225",
"0.59812474",
"0.5958997",
"0.59378445",
"0.5886627",
"0.5858122",
"0.5856723",
"0.5852171",
"0.58340293",
"0.58057404",
"0.5794879",
"0.57866085",
"0.5783688",
"0.5778347",
"0.57643664",
"0.5763379",
"0.57566625",
"0.5697826",
"0.569574",
"0.5688016",
"0.5682418",
"0.56797135",
"0.56584513",
"0.56338435",
"0.56338435",
"0.5630941",
"0.5630551",
"0.56093156",
"0.56090426",
"0.56004184",
"0.559382",
"0.5577449",
"0.55678385",
"0.55664444",
"0.55611557",
"0.55492043",
"0.55488825",
"0.5533495",
"0.55330867",
"0.55165935",
"0.55162996",
"0.5497307",
"0.54957634",
"0.54957634",
"0.5484649",
"0.5479375",
"0.5475138",
"0.5469589",
"0.54600066",
"0.5457064",
"0.54564196",
"0.5453516",
"0.5451061",
"0.5451061",
"0.5448092",
"0.54317486",
"0.5429699",
"0.54281574",
"0.54281574",
"0.54180574",
"0.5404411",
"0.5403395",
"0.5384546",
"0.5366877",
"0.536527",
"0.5361646",
"0.5357081",
"0.5341622",
"0.533805",
"0.53291345",
"0.5328793",
"0.5327708",
"0.5315457",
"0.53130025",
"0.531132",
"0.5308386",
"0.53076494",
"0.5305281",
"0.5302185",
"0.5296427",
"0.52944714",
"0.5279953",
"0.52797157",
"0.5274877",
"0.5274314",
"0.527218"
] | 0.5897386 | 18 |
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\t@aes.key = key\n \t\t\t\t@aes.iv = iv\n \t\t\t\t@aes.encrypt\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",
"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 encrypt!(cipher, iv, options={}) # rubocop:disable Naming/MethodParameterName\n opt = { salt: '' }.merge!(options)\n\n set_crypto cipher, opt[:intmode]\n compute_iv_for_encrypting iv, opt[:salt]\n\n authenticate_if_needed iv\n encrypted_msg = encrypt_body(iv, opt)\n encrypted_msg << generate_auth_tag(opt) if authenticated?\n self[:content].read(iv + encrypted_msg)\n\n # Remove plain payloads\n self[:body] = PacketGen::Types::String.new\n\n remove_enciphered_packets\n self.calc_length\n self\n end",
"def do_aes(key_binary_p, iv_binary_p, input_binary_p, output_binary_p,\n response_length_p, status_p, decrypt: false)\n key = Binary.from_pointer(key_binary_p).to_s\n iv = Binary.from_pointer(iv_binary_p).to_s\n input = Binary.from_pointer(input_binary_p).to_s\n\n write_binary_string_and_set_status(output_binary_p, status_p) do\n output = Hooks.aes(key, iv, input, decrypt: decrypt)\n response_length_p.write_int(output.bytesize)\n\n output\n end\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 blocks(options = {}, &block)\n block_objects(options.merge(object: :blocks), block)\n end",
"def initialize(input = nil, &block)\n raise Vedeu::Error::RequiresBlock unless block_given?\n\n @input = input\n @output = block\n end",
"def initialize( options = {}, &block )\n @mutex = Mutex.new\n\n setup!(options)\n block.call(self) if block\n end",
"def construct( &block )\n self.instance_eval(&block)\n @options\n end",
"def write_buffer(io = ::StringIO.new, encrypter: nil)\n io.binmode if io.respond_to?(:binmode)\n zos = new(io, stream: true, encrypter: encrypter)\n yield zos\n zos.close_buffer\n end",
"def enable(options = {}, &block)\n @enabled = true unless @enabled\n if block_given?\n begin\n yield(self)\n ensure\n close\n end\n end\n self\n end",
"def initialize(options = {})\n @password = options.fetch(:password, nil)\n @salt = options.fetch(:salt, nil)\n\n yield self if block_given?\n end",
"def initialize(options = {})\n # Use any options given, but fall back to the defaults set on the module\n ChefAPI::Configurable.keys.each do |key|\n value = if options[key].nil?\n ChefAPI.instance_variable_get(:\"@#{key}\")\n else\n options[key]\n end\n\n instance_variable_set(:\"@#{key}\", value)\n end\n\n yield self if block_given?\n end",
"def render_block(block, options = {})\n render partial: partial_name_for(block, options), object: block, as: :block\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 enable(_options = {})\r\n unless @enabled\r\n initialize_input\r\n @enabled = true\r\n end\r\n if block_given?\r\n begin\r\n yield(self)\r\n ensure\r\n close\r\n end\r\n else\r\n self\r\n end\r\n end",
"def perform(input, method)\n aes = OpenSSL::Cipher.new('AES-128-CBC')\n aes.public_send(method)\n aes.iv = @iv\n aes.key = @key\n aes.padding = 16 #PKCS7 padding\n aes.update(input) + aes.final\n end",
"def initialize(options={}, &block)\n super(options)\n\n block.call(self) # Allow for population of data with a block during initialization.\n end",
"def initialize(context, offset = T.unsafe(nil), decrypter = T.unsafe(nil)); end",
"def encryptor(io, password, &b)\n Encrypt.open(io, password, mtime, &b)\n end",
"def initialize\n self.cipher = AesCipher.new\n end",
"def spawn_tee(escape = nil, reader: nil, writer: nil, &block)\n # Lots of contours to make #last_pipe and\n # #next_pipe work correctly.\n reader ||= last_pipe\n writer ||= next_pipe\n\n if block_given?\n on_subnet do\n name = next_pipe\n path = Channel.of_type(name).create(name, config)\n spawn_command(\"tee #{path}\", readers: [reader], writers: [writer])\n block.call\n end\n elsif escape\n spawn_command(\"tee #{Channel.of_type(escape).io_name_for(escape, config)}\", readers: [reader], writers: [writer])\n else\n fail 'No block or escape given'\n end\n end",
"def encryptor(io, password, &b)\n Encrypt.open(io, &b)\n end",
"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 decrypt(*args, &block)\n crypt :decrypt, *args, &block\n end",
"def file(options={}, &block)\n if !@sftp.is_a?(ZTK::SSH)\n # Massage for Net::SSH\n flags = (options[:flags] || 'w')\n mode = (options[:mode] || nil)\n\n target = options[:target]\n chown = options[:chown]\n chmod = options[:chmod]\n\n @sftp.file.open(target, flags, mode) do |file|\n yield(file)\n end\n\n chown.nil? or self.exec(%(chown -v #{chown} #{target}))\n chmod.nil? or self.exec(%(chmod -v #{chmod} #{target}))\n else\n # Pass-through for ZTK:SSH\n @sftp.file(options, &block)\n end\n end",
"def initialize(&block)\n load_defaults!\n\n @best ||= false\n @fast ||= false\n\n instance_eval(&block) if block_given?\n\n @cmd = \"#{ utility(:lzma) }#{ options }\"\n @ext = '.lzma'\n end",
"def create(**opts, &block)\n @blob.create(**opts) do |io|\n @compress.writer(io, **@opts) do |cio|\n @format.encoder(cio, **@opts, &block)\n end\n end\n end",
"def configure(&block)\n raise ArgumentError, \"Block is required.\" unless block_given?\n yield @options\n end",
"def initialize(&block)\n @required_options = []\n instance_exec &block\n end",
"def open_with_block(opt, block)\n Tempfile.create(TEMPORARY_FILE_PREFIX, **opt) do |temporary_file|\n temporary_file.write(contents)\n temporary_file.seek(0)\n\n block.call(temporary_file)\n end\n end",
"def initialize(options = {})\n ::ActiveSupport.run_load_hooks(:crypt_keeper_mysql_aes_log, self)\n @key = digest_passphrase(options[:key], options[:salt])\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 generate_block_context(context:, block_param_node:)\n binds = ArgumentsBinder.new(generator: generator).bind(types: method_types, arguments: block_param_node.parameter)\n\n Contexts::BlockContext.new(parent: context, registry: registry, receiver: context.receiver, binds: binds)\n end",
"def initialize(name, options, block)\n @name = name\n @options = options\n @block = block\n async.run\n end",
"def encrypt(*args, &block)\n crypt :encrypt, *args, &block\n end",
"def open_for_delivery(options = {}, &block)\n options = {:certificate => self.configuration[:certificate],\n :passphrase => self.configuration[:passphrase],\n :host => self.configuration[:host],\n :port => self.configuration[:port]}.merge(options)\n open(options, &block)\n end",
"def get_cipher\n OpenSSL::Cipher::Cipher.new('AES-256-CBC')\n end",
"def initialize(options={}, &block)\n set_defaults\n apply_options(options, &block)\n end",
"def initialize(options = {})\n key = options.fetch(:key)\n salt = options.fetch(:salt)\n\n @encryptor = ::ActiveSupport::MessageEncryptor.new \\\n ::ActiveSupport::KeyGenerator.new(key).generate_key(salt, 32)\n end",
"def without_encryption(&block)\n with_encryption_context encryptor: ActiveRecord::Encryption::NullEncryptor.new, &block\n end",
"def initialize(options = {})\n init_options(options)\n\n yield self if block_given?\n end",
"def chain(&block)\n commands = Commands.new(mode: :chain)\n commands.instance_eval(&block)\n self.!(commands)\n end",
"def initialize(options, &block)\n @templates = options.fetch(:templates)\n @seed = \"#{Process.pid}#{options.fetch(:seed, generate_seed).to_i}\"\n\n @env = (ENV_TEMPLATE % @seed).freeze\n @databases = @templates.inject({}) do|h, t|\n h[t] = \"#{Configuration.test_databases[t]['database']}_#{@seed}\".freeze\n h\n end.freeze\n\n execute(&block) unless block.nil?\n end",
"def with_options(options, &block)\n raise ArgumentError.new(\"No block supplied to GrammaticalContext:with_options\") unless block_given?\n yield merge(options)\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 initialize(ios,options={})\n @ios = ios\n header = options.fetch(:header, true)\n # Compress is only used at this point for setting the flag in the header\n @compress = options.fetch(:compress, false)\n\n # Use primary cipher by default, but allow a secondary cipher to be selected for encryption\n @cipher = SymmetricEncryption.cipher(options[:version])\n raise \"Cipher with version:#{options[:version]} not found in any of the configured SymmetricEncryption ciphers\" unless @cipher\n\n @stream_cipher = @cipher.send(:openssl_cipher, :encrypt)\n\n write_header if header\n end",
"def initialize(blocks, options = {})\n @blocks = blocks\n @list = []\n @thread_index = 0\n end",
"def initialize(&block)\n @block = block\n end",
"def initialize(&block)\n @block = block\n end",
"def initialize(&block)\n @block = block\n end",
"def build_block_container(*args, &block)\n options = args.extract_options!\n\n anonymous = false\n if args.first\n name = args.shift\n else\n name = self.anonymous_block_name\n anonymous = true\n end\n\n block_container = Blocks::Container.new\n block_container.name = name.to_sym\n block_container.options = options\n block_container.block = block\n block_container.anonymous = anonymous\n block_container\n end",
"def mode(*modes, &block)\n fail_if_wrong_modes modes\n fail 'Block required' unless block_given?\n self.current_modes = modes\n instance_eval(&block)\n reset_modes\n end",
"def initialize(file_name, stream = T.unsafe(nil), encrypter = T.unsafe(nil)); end",
"def initialize(options = {})\n parse_options options\n yield self if block_given?\n end",
"def initialize(options = {})\n opts = { file: nil, temp: nil, line: 1, blocking: true }.merge(options)\n if !opts_is_valid?opts\n fail ArgumentError, 'define file OR temp'\n elsif opts[:file]\n edit_file(opts)\n elsif opts[:temp]\n edit_temp(opts)\n end\n end",
"def initialize(name, aes_size, sha_size, alg)\n @name = name\n @aes_size = aes_size\n @sha_size = sha_size\n @cipher_name = \"aes-#{aes_size}-cbc\"\n @alg = alg\n @digest = OpenSSL::Digest.new(\"sha#{@sha_size}\")\n end",
"def initialize(options = {}, &callback)\n raise ArgumentError, \"Missing required :pipe_name\" unless @pipe_name = options[:pipe_name]\n @callback = callback\n @pipe_eventable = nil\n end",
"def process_options(&block)\n self.option_processors ||= []\n option_processors << block\n self\n end",
"def exec(command, options = {}, &block) #:yields: stdin\n exec4(command, options) do |pid, stdin, stdout, stderr|\n block.call(stdin) if block_given?\n stdin.close_write\n pid, status = Process.waitpid2(pid)\n raise Error, stderr.read.chomp if status.exitstatus.nonzero?\n stdout\n end\n end",
"def initialize(options = {})\n options.each do |key, value|\n send(:\"#{key}=\", value)\n end\n yield self if block_given?\n end",
"def run!(options = {})\n container = new(options) do |g|\n blocks.each do |block|\n block.call(g)\n end\n end\n container\n end",
"def initialize(options = {}, &block)\n @options = options = {\n cookbook_path: RSpec.configuration.cookbook_path || calling_cookbook_path(caller),\n role_path: RSpec.configuration.role_path || default_role_path,\n log_level: RSpec.configuration.log_level,\n path: RSpec.configuration.path,\n platform: RSpec.configuration.platform,\n version: RSpec.configuration.version,\n }.merge(options)\n\n Chef::Log.level = options[:log_level]\n\n Chef::Config.reset!\n Chef::Config.formatters.clear\n Chef::Config.add_formatter('chefspec')\n Chef::Config[:cache_type] = 'Memory'\n Chef::Config[:client_key] = nil\n Chef::Config[:cookbook_path] = Array(options[:cookbook_path])\n Chef::Config[:role_path] = Array(options[:role_path])\n Chef::Config[:force_logger] = true\n Chef::Config[:solo] = true\n\n yield node if block_given?\n end",
"def initialize(options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value)\n end\n yield(self) if block_given?\n\n end",
"def initialize(options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value)\n end\n yield(self) if block_given?\n end",
"def initialize(options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value)\n end\n yield(self) if block_given?\n end",
"def initialize(file, options={})\n @file = file\n\n @mode = options[:mode]\n @applique = options[:applique]\n end",
"def initialize(*args)\n if self.class == BlockCommand\n raise TypeError, 'BlockCommand.new should not be called directly'\n end\n super\n end",
"def file(options={}, &block)\n ssh.file(options, &block)\n end",
"def stack_from_block(options = {}, &block)\n s = Cfer::Core::Stack.new(options)\n templatize_errors('block') do\n s.build_from_block(&block)\n end\n s\n end",
"def initialize name, options = {}\n @name, @enter, @cycle, @leave = name, *options.values_at(:enter, :cycle, :leave)\n instance_eval &block if block_given?\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.4578289",
"0.45645332",
"0.45627892",
"0.4555043",
"0.45497406",
"0.4536364",
"0.45334023",
"0.45295525",
"0.45282677",
"0.4521764",
"0.45139644",
"0.45117074",
"0.4503399",
"0.44917807",
"0.44885004",
"0.44862568",
"0.44846588",
"0.44820186",
"0.44812477",
"0.44722956",
"0.44647133",
"0.44538704",
"0.44534108",
"0.44534084",
"0.44468406",
"0.44207156",
"0.4419799",
"0.44182083",
"0.44162312",
"0.44141212",
"0.44131738",
"0.44014087",
"0.43823886",
"0.43745",
"0.4355403",
"0.4344329",
"0.43419147",
"0.43394315",
"0.43359864",
"0.43323448",
"0.4324774",
"0.43211192",
"0.43198076",
"0.43097362",
"0.4297244",
"0.42951825",
"0.4292063",
"0.429188",
"0.42876822",
"0.42876822",
"0.42808762",
"0.4280518",
"0.42800245",
"0.42799392",
"0.42617297",
"0.42604744",
"0.42557406",
"0.42521495",
"0.42512563",
"0.42498475",
"0.42329386",
"0.42297292",
"0.4223686",
"0.4219934",
"0.4219934",
"0.42198804",
"0.42120358",
"0.42098066",
"0.42091107",
"0.42076185"
] | 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\t@aes.key = key\n \t\t\t\t@aes.iv = iv\n \t\t\t\t@aes.encrypt\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",
"def aes_encrypt(plain_string)\n cipher = OpenSSL::Cipher::Cipher.new(ssl_cipher)\n cipher.encrypt\n\n key = cipher.random_key\n\n cipher.key = key\n cipher.pkcs5_keyivgen(key)\n encrypted_data = cipher.update(plain_string) + cipher.final\n\n {:key => key, :data => encrypted_data}\n end",
"def aes_encrypt(plain_string)\n cipher = OpenSSL::Cipher.new(ssl_cipher)\n cipher.encrypt\n\n key = cipher.random_key\n\n cipher.key = key\n cipher.pkcs5_keyivgen(key)\n encrypted_data = cipher.update(plain_string) + cipher.final\n\n {:key => key, :data => encrypted_data}\n end",
"def encryptor_obj\n @e_obj ||= LocalCipher.new(GlobalConstant::SecretEncryptor.cache_data_sha_key)\n end",
"def encryptor_obj\n @e_obj ||= LocalCipher.new(GlobalConstant::SecretEncryptor.cache_data_sha_key)\n end",
"def with_reusable_cipher\n cipher = get_or_init_reusable_cipher\n\n result = yield(cipher)\n\n cleanup_reusable_cipher\n\n return result\n rescue => e\n # when an error is encountered, we cannot trust the state of the cipher object.\n @logger.debug(\"shared cipher: removing because an exception was raised in #{Thread.current}\", :exception => e.message)\n destroy_reusable_cipher\n raise\n end",
"def new\n\t\t@block = Block.new\n\tend",
"def encryptCBC(plaintext, key, iv, padding: false)\r\n\t\t## split the text into chunks of block size\r\n\t\tblock_size = 16\r\n\t\tblocks = plaintext.chars.each_slice(block_size).to_a.map{|v| v.join.to_s}\r\n\r\n\r\n\t\tciphertext = String.new\r\n\t\tvector = iv\r\n\t\tblocks.each do |block|\r\n\t\t\txor = block^vector\r\n\t\t\tvector = encryptECB(xor, key, padding: false)\r\n\t\t\tciphertext += vector\r\n\t\tend\r\n\r\n\t\tciphertext\r\n\tend",
"def encrypt_aes_cbc(key, iv)\n key_str = str(key)\n iv_str = str(iv)\n msg = self.pad(16).value\n\n _encrypt_aes_cbc(msg, key_str, iv_str)\n end",
"def aes_encrypt(data, key, iv, cipher_type)\n aes = OpenSSL::Cipher::Cipher.new(cipher_type)\n aes.encrypt\n aes.key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(key, \"randomString\", 1024, aes.key_len)\n aes.iv = iv if iv != nil\n aes.update(data.to_s) + aes.final \n end",
"def encrypt(block)\n return_value = encrypt! block\n \n self.calls_left -= 1\n if calls_left < 0\n return_value = nil\n destroy\n else\n save!\n end\n return_value\n end",
"def initialize(key)\n @cipher = Internals::AES::BlockCipher.new(key)\n\n # L is defined as follows (quoted from the PMAC paper):\n #\n # Equation 1:\n #\n # a · x =\n # a<<1 if firstbit(a)=0\n # (a<<1) ⊕ 0¹²⁰10000111 if firstbit(a)=1\n #\n # Equation 2:\n #\n # a · x⁻¹ =\n # a>>1 if lastbit(a)=0\n # (a>>1) ⊕ 10¹²⁰1000011 if lastbit(a)=1\n #\n # Let L(0) ← L. For i ∈ [1..µ], compute L(i) ← L(i − 1) · x by\n # Equation (1) using a shift and a conditional xor.\n #\n # Compute L(−1) ← L · x⁻¹ by Equation (2), using a shift and a\n # conditional xor.\n #\n # Save the values L(−1), L(0), L(1), L(2), ..., L(µ) in a table.\n # (Alternatively, [ed: as we have done in this codebase] defer computing\n # some or all of these L(i) values until the value is actually needed.)\n @l = []\n tmp = Internals::Block.new\n tmp.encrypt(@cipher)\n\n PRECOMPUTED_BLOCKS.times.each do\n block = Internals::Block.new(tmp.data.dup)\n block.data.freeze\n block.freeze\n\n @l << block\n tmp.dbl\n end\n\n @l.freeze\n\n # Compute L(−1) ← L · x⁻¹:\n #\n # a>>1 if lastbit(a)=0\n # (a>>1) ⊕ 10¹²⁰1000011 if lastbit(a)=1\n #\n @l_inv = Internals::Block.new(@l[0].data.dup)\n last_bit = @l_inv[Internals::Block::SIZE - 1] & 0x01\n\n (Internals::Block::SIZE - 1).downto(1) do |i|\n carry = Internals::Util.ct_select(@l_inv[i - 1] & 1, 0x80, 0)\n @l_inv[i] = (@l_inv[i] >> 1) | carry\n end\n\n @l_inv[0] >>= 1\n @l_inv[0] ^= Internals::Util.ct_select(last_bit, 0x80, 0)\n @l_inv[Internals::Block::SIZE - 1] ^= Internals::Util.ct_select(last_bit, Internals::Block::R >> 1, 0)\n @l_inv.freeze\n @l_inv.data.freeze\n end",
"def cryptor\n key = Rails.application.secrets.secret_key_base.bytes[0..31].pack( \"c\" * 32 )\n ActiveSupport::MessageEncryptor.new(key)\n end",
"def encrypt(*args, &block)\n crypt :encrypt, *args, &block\n end",
"def encrypt_ecb_nofinal(msg, key)\n cipher = OpenSSL::Cipher.new('AES-128-ECB')\n cipher.encrypt\n cipher.key = key\n return cipher.update(msg)\nend",
"def aes_decrypt(key, crypt_string)\n cipher = OpenSSL::Cipher.new(ssl_cipher)\n\n cipher.decrypt\n cipher.key = key\n cipher.pkcs5_keyivgen(key)\n cipher.update(crypt_string) + cipher.final\n end",
"def perform(input, method)\n aes = OpenSSL::Cipher.new('AES-128-CBC')\n aes.public_send(method)\n aes.iv = @iv\n aes.key = @key\n aes.padding = 16 #PKCS7 padding\n aes.update(input) + aes.final\n end",
"def encrypt_block(block, key) \n\t# key[0] = p, key[1] = g, key[2] = e2\n\tk = rand(key[0] - 1)\n\tc1 = ModMath.pow(key[1], k, key[0])\n\t# c2 = ((e2^k % p) * (m % p)) % p\n\tc2 = (ModMath.pow(key[2], k, key[0]) * ModMath.pow(block, 1, key[0])) % key[0]\n\treturn c1, c2\nend",
"def crypt( decrypt_or_encrypt, data, pwhash, iv )\n c = OpenSSL::Cipher.new CIPHER\n c.send decrypt_or_encrypt.to_sym\n c.key = pwhash\n c.iv = iv\n c.update( data ) << c.final\n end",
"def encryption_oracle(input)\n #Hardcoded, secret string\n append = 'Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg'\n append << 'aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq'\n append << 'dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg'\n append << 'YnkK'\n append = append.unpack('m')\n\n str = input + append.join\n\n cipher = OpenSSL::Cipher.new('AES-128-ECB') \n cipher.encrypt \n cipher.key = 'O' * Blocksize;\n \n enc = cipher.update(str) + cipher.final\n #Hex encoded return\n return enc.unpack('H*').join\nend",
"def decrypt(*args, &block)\n crypt :decrypt, *args, &block\n end",
"def new_block_el(*args); end",
"def initialize(name, aes_size, sha_size, alg)\n @name = name\n @aes_size = aes_size\n @sha_size = sha_size\n @cipher_name = \"aes-#{aes_size}-cbc\"\n @alg = alg\n @digest = OpenSSL::Digest.new(\"sha#{@sha_size}\")\n end",
"def encrypt(plaintext, passwd, options = {})\n cipher = new_cipher(:encrypt, passwd, options)\n cipher.iv = iv = cipher.random_iv\n ciphertext = cipher.update(plaintext)\n ciphertext << cipher.final\n Base64.encode64(combine_iv_and_ciphertext(iv, ciphertext))\n end",
"def aes_decrypt(key, crypt_string)\n cipher = OpenSSL::Cipher::Cipher.new(ssl_cipher)\n\n cipher.decrypt\n cipher.key = key\n cipher.pkcs5_keyivgen(key)\n decrypted_data = cipher.update(crypt_string) + cipher.final\n end",
"def block(name, &block)\n klass = SuperbTextConstructor.block(name, &block)\n @blocks << klass\n klass\n end",
"def encrypt_aes_ecb(key)\n key_str = str(key)\n msg = self.pad(16).value\n\n _encrypt_aes_ecb(msg, key_str)\n end",
"def _setup(action)\n @cipher ||= OpenSSL::Cipher.new(@options[:cipher]) \n # Toggles encryption mode\n @cipher.send(action)\n @cipher.padding = @options[:padding]\n @cipher.key = @key.unpack('a2'*32).map{|x| x.hex}.pack('c'*32)\n end",
"def decrypt_aes_cbc(key, iv, padding: false)\n key_str = str(key)\n iv_str = str(iv)\n data = self.pad(16).value\n\n _decrypt_aes_cbc(data, key_str, iv_str)\n end",
"def crypt(decrypt_or_encrypt, data, key, iv)\n c = OpenSSL::Cipher.new(CIPHER)\n c.send(decrypt_or_encrypt.to_sym)\n c.key = key\n c.iv = iv\n c.update(data) << c.final\n end",
"def encrypt(text, iv)\n if @cipher\n cipher = OpenSSL::Cipher::Cipher.new(\"aes-#{@cipher}-cbc\")\n cipher.encrypt\n cipher.key = @secret[0..@cipher_block_size]\n if iv != \"\"\n cipher.iv = iv\n end\n cipher_text = cipher.update(text)\n cipher_text << cipher.final\n return Base64.encode64(cipher_text) #output in base64\n else\n return text\n end\n end",
"def cipher; end",
"def open(nonce, ciphertext)\n raise(LengthError, 'Nonce length') if nonce.bytesize != NONCE_BYTES\n\n ct_padded = prepend_zeroes(BOX_ZERO_BYTES, ciphertext)\n buffer = zero_string(ct_padded.bytesize)\n\n success = Sodium.crypto_secretbox_xsalsa20poly1305_open(buffer, ct_padded, ct_padded.bytesize, nonce, @key)\n raise(CryptoError, \"Decryption failed (#{success})\") unless success.zero?\n\n remove_zeroes(ZERO_BYTES, buffer)\n end",
"def build_encrypter\n @encrypter = Crypt::AutoEncrypter.new(\n @options[:auto_encryption_options].merge(client: self)\n )\n end",
"def block_class() Block; end",
"def decipher(key, user_iv, text)\n ssl_decipher = OpenSSL::Cipher.new('AES-256-CBC')\n ssl_decipher.decrypt\n ssl_decipher.key = key\n ssl_decipher.iv = user_iv\n ssl_decipher.update(text) + ssl_decipher.final\n end",
"def create_block_object(&block)\n block\nend",
"def decrypt(cipher_text, key, opts={})\n ::AES::AES.new(key, opts).decrypt(cipher_text)\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 decode_aes(str)\n unpacked_data = Base64.decode64(str).unpack(ENCODING_FORMAT)\n # Splat the data array apart\n # nonce, auth_tag, encrypted_data = unpacked_data\n CipherParams.new(*unpacked_data)\n end",
"def encrypt(plaintext)\n @cipher.encrypt(@secret_key, plaintext)\n end",
"def decode_aes(str)\n unpacked_data = str.unpack1(\"m\").unpack(ENCODING_FORMAT)\n # Splat the data array apart\n # nonce, auth_tag, encrypted_data = unpacked_data\n CipherParams.new(*unpacked_data)\n end",
"def create_block\n block = nil\n f = nil\n tf = Tempfile.new path\n tf.close\n begin\n f = File.open tf.path, 'w'\n f.allocate Block.size\n f.close\n block = Block.new\n block.device = self\n block.save!\n File.rename tf.path, block.file_path\n rescue\n f.close if f && !f.closed?\n block.destroy if block\n tf.unlink if File.exist? tf.path\n raise\n end\n # TODO(pwnall): code\n end",
"def encrypt(object)\n old_version = '0.0.1'\n result = ''\n if cipher.respond_to?(:iv=) and @iv == nil\n iv = OpenSSL::Random.random_bytes(cipher.iv_len)\n cipher.iv = iv\n result << old_version << iv\n end\n\n if cipher.respond_to?(:public_encrypt)\n result << cipher.public_encrypt(object)\n else\n cipher_setup :encrypt\n result << cipher.update(object) << cipher.final\n cipher.reset\n end\n return result\n end",
"def encrypt data, key, iv, cipher_type\n aes = OpenSSL::Cipher::Cipher.new cipher_type\n aes.encrypt\n aes.key = key\n aes.iv = iv if iv != nil\n aes.update(data) + aes.final \n end",
"def encrypt(plain_text, password = nil, salt = nil)\n password = password.nil? ? Hoodie.crypto.password : password\n salt = salt.nil? ? Hoodie.crypto.salt : salt\n\n cipher = new_cipher(:encrypt, password, salt)\n cipher.iv = iv = cipher.random_iv\n ciphertext = cipher.update(plain_text)\n ciphertext << cipher.final\n Base64.encode64(combine_iv_ciphertext(iv, ciphertext))\n end",
"def vigenere_cipher(string, key_sequence, alphabet)\r\n\r\nend",
"def vigenere_cipher(string, key_sequence, alphabet)\n #\n # your code goes here\n #\nend",
"def decrypt encrypted_data, key, iv, cipher_type\n aes = OpenSSL::Cipher::Cipher.new cipher_type\n aes.decrypt\n aes.key = key\n aes.iv = iv if iv != nil\n aes.update(encrypted_data) + aes.final \n end",
"def encrypt_message(message)\n aes = OpenSSL::Cipher.new(@cipher).encrypt\n aes.key = @encryption_key\n iv = aes.random_iv\n aes.iv = iv\n iv + (aes.update(message) << aes.final)\n end",
"def pkcs_7(block, blocksize)\n padding_amount =\n if block.length < blocksize\n blocksize - block.length\n elsif block.length % blocksize == 0\n 0\n else\n n = block.length % blocksize\n\n blocksize - n\n end\n\n (block.bytes + ([padding_amount] * padding_amount)).pack(\"C*\")\n end",
"def encrypt(data, key, iv, cipher_type)\n aes = OpenSSL::Cipher::Cipher.new(cipher_type)\n aes.encrypt\n aes.key = key\n aes.iv = iv if iv != nil\n aes.update(data) + aes.final\n end",
"def cipher_block_size()\n case @cipher\n when \"256\"\n return 32\n when \"192\"\n return 24\n else\n return 16\n end\n end",
"def encrypt()\n cipher_type = \"aes-128-ecb\"\n data = password;\n key = master_password;\n \n self.encrypted_password = aes_encrypt(data,key,nil,cipher_type).to_s\n end",
"def generate_key_iv(mode, pass=nil, salt=nil, hash=nil)\r\n\r\n salt = salt.nil? ? get_default_salt(mode) : salt\r\n key_iv_str = OpenSSL::PKCS5.pbkdf2_hmac(pass, salt, 2000, (@cipher.key_len + @cipher.iv_len), hash)\r\n key = key_iv_str[0, @cipher.key_len]\r\n iv = key_iv_str[@cipher.key_len, @cipher.iv_len]\r\n cipher_key_iv = { key: key, iv: iv }\r\n\r\n cipher_key_iv\r\n end",
"def ciphertext_only(ciphertext)\n for i in 0...@alphabet.length\n c = Caesar.new(i, @alphabet)\n print c.decrypt(ciphertext) + \"\\n\"\n end \n end",
"def _decode_aes256 cipher, iv, data\n aes = OpenSSL::Cipher::Cipher.new \"aes-256-#{cipher}\"\n aes.decrypt\n aes.key = @encryption_key\n aes.iv = iv\n aes.update(data) + aes.final\n end",
"def initialize(&block)\n @block = block\n end",
"def initialize(&block)\n @block = block\n end",
"def decrypt_byte(iv, block, known)\n c = BLOCK_SIZE.times.map { rand(0..255) }\n p = known.length + 1\n\n # During encryption we:\n # 1. XOR (block, iv)\n # 2. Encrypt the value above ending with an \"encrypted value\"\n #\n # During decryption we do:\n # 1. decrypted_value = aes_cbc_decrypt(encrypted_value, KEY)\n # 2. XOR(decrypted_value, iv)\n # 3. We now have our plaintext\n #\n # So let's deconstruct what \"c[byte_pos] = x ^ p ^ iv[byte_pos]\" means.\n #\n # 1. We know \"x\" is part of our \"zeroing IV\", meaning:\n # * XOR(decrypted_value[pos], x) == 0\n # 2. p is the amount of zeroing bytes we already know\n # 3. iv[byte_pos] is our IV\n #\n # By doing c[byte_pos] = x ^ p ^ iv[byte_pos]\n #\n # We know that doing XOR(XOR(decrypted_block, iv), iv) will return decrypted_block\n # Following with XOR(decrypted_block[pos], x) will return 0 since x is equal the block\n # byte.\n # Followed by XOR(0, p) will return p, setting the byte to the padding value we want\n\n known.each_with_index do |x, i|\n byte_pos = BLOCK_SIZE - i - 1\n c[byte_pos] = x ^ p ^ iv[byte_pos]\n end\n\n i = 0\n\n loop do\n c[BLOCK_SIZE - p] = i\n break if check_credentials(c, block)\n raise \"Couldn't guess byte\" if i > 256\n i += 1\n end\n\n # So here we know c[BLOCK_SIZE - p] = i generated a value that\n # when XORed creates a valid padding for that specific byte.\n # Now we need to find the value for the \"zeroing IV\".\n #\n # We know that \"iv[BLOCK_SIZE - p] ^ i\" generates a number for a valid padding\n # when XORing it with our decrypted_value\n # and \"p\" represents that number for the current iteration. So XORing\n # \"iv[BLOCK_SIZE - p] ^ i\" with \"p\" will generate a number that when XORed\n # with the decrypted block will zero it.\n\n iv[BLOCK_SIZE - p] ^ i ^ p\nend",
"def decode_block( chars_block, alphabet=Saltpack::Armor::B62ALPHABET, shift=false )\n\t bytes_size = Saltpack::Armor.max_bytes_size( alphabet.length, chars_block.length )\n\t expected_block_size = Saltpack::Armor.character_block_size( alphabet.length, bytes_size )\n\n\t\tself.log.debug \"For %p with an alphabet of %d chars: bytes_size=%d; expected_block_size=%d\" %\n\t\t\t[ chars_block, alphabet.length, bytes_size, expected_block_size ]\n\n\t\traise ArgumentError, \"illegal block size %d, expected %d\" %\n\t\t\t[ chars_block.length, expected_block_size ] unless\n\t\t\t\tchars_block.length == expected_block_size\n\n\t extra = Saltpack::Armor.extra_bits( alphabet.length, chars_block.length, bytes_size )\n\n\t # Convert the chars to an integer.\n\t bytes_int = Saltpack::Armor.get_char_index( alphabet, chars_block[0] )\n\t\tchars_block[ 1.. ].chars.each do |char|\n\t bytes_int *= alphabet.length\n\t bytes_int += Saltpack::Armor.get_char_index( alphabet, char )\n\t\tend\n\n\t # Shift right by the extra bits.\n\t bytes_int >>= extra if shift\n\n\t\treturn [ bytes_int.to_s(16) ].pack( 'H*' )\n\tend",
"def initialize(&block)\n @block = block\n end",
"def cipher_type\n self.class.cipher_type(algorithm: algorithm, key_length: key_length, mode: mode)\n end",
"def add_cipher(version, cipher, key_length, status)\n unless @supported_versions.include? version\n raise ArgumentError, \"Must be a supported SSL Version\"\n end\n unless OpenSSL::SSL::SSLContext.new(version).ciphers.flatten.include?(cipher) || @deprecated_weak_ciphers.include?(cipher)\n raise ArgumentError, \"Must be a valid SSL Cipher for #{version}!\"\n end\n unless key_length.kind_of? Integer\n raise ArgumentError, \"Must supply a valid key length\"\n end\n unless [:accepted, :rejected].include? status\n raise ArgumentError, \"Status must be either :accepted or :rejected\"\n end\n\n strong_cipher_ctx = OpenSSL::SSL::SSLContext.new(version)\n # OpenSSL Directive For Strong Ciphers\n # See: https://web.archive.org/web/20121125052802/http://www.rapid7.com/vulndb/lookup/ssl-weak-ciphers\n strong_cipher_ctx.ciphers = \"ALL:!aNULL:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM\"\n\n if strong_cipher_ctx.ciphers.flatten.include? cipher\n weak = false\n else\n weak = true\n end\n\n cipher_details = {:version => version, :cipher => cipher, :key_length => key_length, :weak => weak, :status => status}\n @ciphers << cipher_details\n end",
"def initialize(width, height, &block)\n raise ArgumentError, \"give me a block, pretty please\" unless block_given?\n \n @width, @height = Integer(width), Integer(height)\n @canvas = SmartImage::Canvas.new @width, @height\n \n yield self\n @canvas.destroy\n @canvas = DeadCanvas.new\n end",
"def encryption_oracle(buffer)\n prefix_padding = rand(5..10).times.map { rand(0..255) }\n suffix_padding = rand(5..10).times.map { rand(0..255) }\n padded_buffer = pkcs7_pad(prefix_padding + buffer + suffix_padding, 16)\n key = 16.times.map { rand(0..255) }\n\n if rand(2).zero?\n puts 'Encrypting with ECB...'\n aes_ecb_encrypt(padded_buffer, key)\n else\n puts 'Encrypting with CBC...'\n iv = 16.times.map { rand(0..255) }\n aes_cbc_encrypt(padded_buffer, key, iv)\n end\nend",
"def encryption_oracle(message)\n rand_key = SecureRandom.random_bytes(16)\n rand_iv = SecureRandom.random_bytes(16)\n front_bytes = SecureRandom.random_bytes(rand(5..10))\n end_bytes = SecureRandom.random_bytes(rand(5..10))\n\n padded_message = front_bytes + message + end_bytes\n\n (rand(1..2) == 1) ? encrypt_ecb(message, rand_key) : encrypt_cbc(message, rand_key, rand_iv)\nend",
"def symmetric_key(name, cipher_class, cipher_name, key_abi_type, hooks = {})\n object_wrapper name, Tem::Keys::Symmetric, [key_abi_type, :key],\n :read => lambda { |k| Tem::Keys::Symmetric.new k },\n :to => lambda { |k| k.ssl_key },\n :new => lambda { |klass|\n k = cipher_class.new cipher_name\n \n unless k.respond_to? :key\n # Some ciphers don't give back the key that they receive.\n # We need to synthesize that.\n class <<k\n def key=(new_key)\n super\n @_key = new_key\n end\n def key\n @_key\n end\n end\n end\n k\n }\n end",
"def generate_block_context(context:, block_param_node:)\n binds = ArgumentsBinder.new(generator: generator).bind(types: method_types, arguments: block_param_node.parameter)\n\n Contexts::BlockContext.new(parent: context, registry: registry, receiver: context.receiver, binds: binds)\n end",
"def encrypt(plaintext)\n box.encrypt(plaintext)\n end",
"def aes_ecb_encrypt(data, key, params: {})\n key_arr = key.unpack(\"C*\")\n\n data = pad_data(data, 16)\n encrypted_data = data.unpack(\"C*\").each_slice(16).map do |slice|\n state = array_to_matrix(slice)\n encrypted_state = aes_encrypt_block(state, key_arr)\n matrix_to_array(encrypted_state).pack(\"C*\")\n end\n\n # return base64 encoded data\n [encrypted_data.join].pack(\"m\")\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.51365846",
"0.51341",
"0.5109646",
"0.5109646",
"0.50613356",
"0.5058148",
"0.50431466",
"0.5016904",
"0.500889",
"0.49875155",
"0.4983952",
"0.49529693",
"0.49315372",
"0.49041525",
"0.4886956",
"0.48579794",
"0.4849706",
"0.48385996",
"0.48302573",
"0.4804948",
"0.47747692",
"0.47627136",
"0.47523335",
"0.47519967",
"0.47405535",
"0.47185314",
"0.47144",
"0.46901196",
"0.46834293",
"0.46796012",
"0.46785203",
"0.46769327",
"0.46536022",
"0.46513864",
"0.46456584",
"0.46182892",
"0.46136743",
"0.46041524",
"0.45994264",
"0.459856",
"0.4591648",
"0.45803392",
"0.45748383",
"0.45699817",
"0.45697626",
"0.45600513",
"0.4537896",
"0.45344228",
"0.45176178",
"0.4516711",
"0.45011228",
"0.44973484",
"0.44864693",
"0.4486024",
"0.44784266",
"0.44762108",
"0.4471396",
"0.4471396",
"0.44637552",
"0.44602597",
"0.4457528",
"0.44511664",
"0.4441166",
"0.44358444",
"0.44323277",
"0.44322062",
"0.4422322",
"0.44150263",
"0.44144323",
"0.44135588"
] | 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(!@fh.eof? && !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 && !@f.eof?\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",
"def blocks_parse(input)\n return nil\nend",
"def reader_proc(&block)\n #defined by default_for_proc_type in initialize!\n end",
"def set_block\n @request = JSON.parse(request.body.read, {:symbolize_names => true})\n @block = Block.find_by(prev_block: @request[:prev_block])\n end",
"def set_block &b\n @block = b\n end",
"def read_body(&block)\n while byte = @body.read(1)\n yield byte\n end\n end",
"def data(&block)\n if not @data.nil?\n return @data\n end\n \n self.prepare! # seeks to block position\n \n if not block.nil?\n loop do\n size = @io.getbyte\n break if size <= 0\n block.call(@io.read(size))\n end\n else\n data = \"\"\n self.data do |chunk|\n data << chunk\n end\n @data = data\n \n return @data\n end\n end",
"def input(input, &block)\n if input.instance_of? String\n if block\n @infiles << {\n enable_cache: input\n block: block\n }\n else\n @infiles << File.expand_path(input)\n end\n elsif input.instance_of? Array\n input.each do |file|\n if block\n @infiles << {\n file: File.expand_path(file),\n block: block\n }\n else\n @infiles << File.expand_path(file)\n end\n end\n else\n fail TypeError, \"Input #{f.inspect} is not a string nor an array!\"\n end\n self\n end",
"def consume_simple_block(input = T.unsafe(nil)); end",
"def read_stream(chunksize_hint, &block)\r\n StringIO.open(@text, \"rb\") do |ios|\r\n while bytes = ios.read(chunksize_hint)\r\n block.call(bytes)\r\n end\r\n end\r\n end",
"def read_stream(chunksize_hint, &block)\r\n IO.popen(@command, \"r\") do |ios|\r\n while bytes = ios.read(chunksize_hint)\r\n block.call(bytes)\r\n end\r\n end\r\n end",
"def read_stream_block\n StreamBlock.parse(read_payload)\n end",
"def each_input_line\n with_input_io{|io| io.each_line(&Proc.new)}\n end",
"def stream\n $stdin.each do |line|\n record = recordize(line.chomp)\n next unless record\n process(*record) do |output_record|\n emit output_record\n end\n end\n end",
"def normal=(block)\n raise ArgumentError, \"normal expects a block, not a #{block.class}\" unless block.is_a?(Proc)\n @normal = block\n end",
"def transfer_block(source, destination, block_opening = nil)\n if block_opening.nil?\n File.open(source) do |f|\n f.each do |line|\n destination.puts line\n end\n end\n else\n File.open(source) do |f|\n block_opened = false\n f.each do |line|\n if !block_opened && line.start_with?(block_opening)\n destination.puts line\n block_opened = true\n elsif block_opened && !line.start_with?('}')\n destination.puts line\n elsif block_opened && line.start_with?('}')\n destination.puts line\n break\n end\n end\n end\n end\nend",
"def read_block_header # :nodoc:\n unless header = rio.read(BLOCK_HEADER_SIZE)\n return\n end\n\n type, index, payload_size = header.unpack('CxvV')\n if !type || !index || !payload_size\n return\n end\n\n next_block_pos = rio.tell + payload_size\n if file_size < next_block_pos\n return\n end\n\n if !BLOCK_TYPES.include?(type)\n file = if rio.respond_to?(:path) then \" in file #{rio.path}\"\n end\n Pocolog.warn \"invalid block type '#{type}' found#{file} at position #{rio.tell}, expected one of #{BLOCK_TYPES.join(\", \")}. The file is probably corrupted. The rest of the file will be ignored.\"\n return\n end\n\n @block_info.io = @rio\n @block_info.pos = @next_block_pos\n @block_info.type = type\n @block_info.index = index\n @block_info.payload_size = payload_size\n @next_block_pos = next_block_pos\n true\n end",
"def initialize(file=nil, line=1, options={}, &block)\n raise ArgumentError, \"file or block required\" if file.nil? && block.nil?\n @file = file\n @line = line || 1\n @options = options || {}\n @reader = block || lambda { |t| File.read(file) }\n end",
"def read_file filename\n \n # The first block location is stored in the hash table.\n hash_a = Hashing::hash_for :hash_a, filename\n hash_b = Hashing::hash_for :hash_b, filename\n hash_entry = @hash_table.find do |h|\n [h.hash_a, h.hash_b] == [hash_a, hash_b]\n end\n unless hash_entry\n return nil\n end\n block_entry = @block_table[hash_entry.block_index]\n unless block_entry.file?\n return nil \n end\n @io.seek @user_header.archive_header_offset + block_entry.block_offset\n file_data = @io.read block_entry.archived_size\n \n # Blocks can be encrypted. Decryption isn't currently implemented as none \n # of the blocks in a StarCraft 2 replay are encrypted.\n if block_entry.encrypted?\n return nil\n end\n \n # Files can consist of one or many blocks. In either case, each block \n # (or *sector*) is read and individually decompressed if needed, then \n # stitched together for the final result.\n if block_entry.single_unit?\n if block_entry.compressed?\n if file_data.bytes.next == 16\n file_data = Bzip2.uncompress file_data[1, file_data.length]\n end\n end\n return file_data \n end\n sector_size = 512 << @archive_header.sector_size_shift\n sectors = block_entry.size / sector_size + 1\n if block_entry.has_checksums\n sectors += 1\n end\n positions = file_data[0, 4 * (sectors + 1)].unpack \"V#{sectors + 1}\"\n sectors = []\n positions.each_with_index do |pos, i|\n break if i + 1 == positions.length\n sector = file_data[pos, positions[i + 1] - pos]\n if block_entry.compressed?\n if block_entry.size > block_entry.archived_size\n if sector.bytes.next == 16\n sector = Bzip2.uncompress sector\n end\n end\n end\n sectors << sector\n end\n sectors.join ''\n end",
"def with_input_file\n current_root.with_input_file(storage_key, tmp_dir: tmpdir_for_with_input_file) do |file|\n yield file\n end\n end",
"def each_line\n while line = self.gets do\n yield line\n end\n end",
"def stream *args, &block\n get(*args) { stream { |io| instance_exec io, &block } }\n end",
"def read(block_name, dest_buffer = nil)\n dest_buffer ||= alloc_buffer\n if block_name >= @mem_file.size\n raise ArgumentError,\"No such block name #{block_name} exists (size=#{@mem_file.size})\"\n end\n\n src = @mem_file[block_name]\n ByteArray.copy(src,0,@block_size,dest_buffer,0)\n dest_buffer\n end",
"def process(io=$stdin)\n io = open(io)\n result = load(io)\n \n if use_close || file\n close(io)\n end\n \n result\n end",
"def initialize(input = nil, &block)\n raise Vedeu::Error::RequiresBlock unless block_given?\n\n @input = input\n @output = block\n end",
"def input_iterator\n return arguments.each unless arguments.empty?\n return File.foreach(options[:input]) if options[:input]\n\n $stdin.each_line\n end",
"def each(&block)\n File.open(@filename).each do |line|\n yield(line.chomp)\n end\n end",
"def each(&block)\n\t\t\t\treturn to_enum unless block_given?\n\t\t\t\t\n\t\t\t\twhile chunk = gets\n\t\t\t\t\tyield chunk\n\t\t\t\tend\n\t\t\tend",
"def process_lines(input_file)\n for line in input_file\n process_line(line)\n end\n end_of_file\n end",
"def execute_block(block)\n case\n when block.is_a?(Symbol)\n send(block)\n when block.respond_to?(:call) && (block.arity == 1 || block.arity == -1)\n block.call(self)\n else\n block\n end \n end",
"def stream!\n @scratch.open(\"original\") { |file| yield file }\n end",
"def read(&block)\n Dir.mktmpdir(File.join(\"Amylase-#{UUID.new.generate}\"), Dir.tmpdir) do |tmpdir|\n tmp_filename = File.join(tmpdir, @data_source.name)\n\n File.open(tmp_filename, 'wb') do |file|\n @s3_obj.read do |chunk|\n file.write(chunk)\n end\n end\n\n File.open(tmp_filename) do |file|\n file.each_line do |line|\n yield line\n end\n end\n end\n end",
"def parse_with_block(&block)\n\n # if there is a valid column_mapping, then we need to change the mapped_header\n mapped_header = @headers\n if (@column_mapping.mapping)\n mapped_header = Array.new\n @column_mapping.mapping.each_with_index do |map, index|\n mapped_header[map] = @headers[index] if (map.is_a? Numeric)\n end\n end\n\n while (!((chunk = read_chunk).nil?))\n if (mapped_header.size == 0)\n block.call(@reader.getLineNumber(), @reader.getRowNumber(), format(chunk))\n else\n block.call(@reader.getLineNumber(), @reader.getRowNumber(), format(chunk),\n mapped_header)\n end\n end\n \n end",
"def start_new_block\n if (@block_buffer)\n add_block(@block_buffer)\n @block_buffer = nil\n end\n end",
"def output(format)\n block = nil\n ignore_line = false\n\n # We can this multiples times\n @input.rewind if @input.eof?\n\n Enumerator.new do |y|\n # Comments are discarded (lines beginnig with %)\n @input.readlines.reject { |l| l.start_with?('%') }.each do |line|\n # right space are discarded (line terminators, tabs and spaces)\n line.rstrip!\n\n if block.nil?\n # Searching for a new block...\n block = BLOCKS.find { |b| b[1][:begin_re].match line }\n\n # The begin of a block!\n unless block.nil?\n block = block[0]\n\n # We can ignore the actual line?\n ignore_line = BLOCKS[block][:ignore_match_line]\n\n # Send the begin mark for this format\n y.yield format::BLOCKS[block][:begin]\n end\n elsif BLOCKS[block][:end_re].match line\n # We find the end of a block!\n # Send the end mark for this format\n y.yield format::BLOCKS[block][:end]\n\n # We can ignore the actual line?\n if BLOCKS[block][:ignore_match_line]\n block = nil\n next\n end\n end\n\n # More on line!\n y.yield process_line(line, block, format) unless ignore_line\n ignore_line = false if ignore_line\n end\n\n # There are a close block pending?\n y.yield format::BLOCKS[block][:end] unless block.nil?\n end\n end",
"def storbinary(cmd, file, blocksize, rest_offset = nil, &block) # :yield: data\n if rest_offset\n file.seek(rest_offset, IO::SEEK_SET)\n end\n synchronize do\n voidcmd(\"TYPE I\")\n conn = transfercmd(cmd, rest_offset)\n loop do\n buf = file.read(blocksize)\n break if buf == nil\n conn.write(buf)\n yield(buf) if block\n end\n conn.close # closes the SSL\n conn.io.close # closes the TCP below it\n voidresp\n end\n end",
"def storlines(cmd, file, &block) # :yield: line\n synchronize do\n voidcmd(\"TYPE A\")\n conn = transfercmd(cmd)\n loop do\n buf = file.gets\n break if buf == nil\n if buf[-2, 2] != CRLF\n buf = buf.chomp + CRLF\n end\n conn.write(buf)\n yield(buf) if block\n end\n conn.close # closes the SSL\n conn.io.close # closes the TCP below it\n voidresp\n end\n end",
"def parse_block(*_arg0); end",
"def read_io(io, &block)\n read_memory(io.read, &block)\n end",
"def update\n @block = @site.blocks.find(params[:id])\n\n respond_to do |format|\n params[:block].delete :user_id\n if @block.update_attributes(params[:block])\n flash[:notice] = 'Block was successfully updated.'\n format.html { redirect_to([@site, @block]) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @block.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def capture_with_inputs(stream, *args)\n begin\n # override STDOUT\n stream = stream.to_s\n eval \"$#{stream} = StringIO.new\"\n # override STDIN\n $stdin = StringIO.new\n $stdin.puts(args.shift) until args.empty?\n $stdin.rewind\n yield\n result = eval(\"$#{stream}\").string\n ensure\n eval(\"$#{stream} = #{stream.upcase}\")\n $stdin = STDIN\n end\n result\n end",
"def get_input_stream(entry, &a_proc); end",
"def process_file_handle f\n begin\n line = f.readline\n rescue EOFError\n line = nil\n end\n while line\n process_line(line)\n begin\n # FIXME -- this call to File#readline blocks and doesn't let\n # stuff like SIGINT (generated from Ctrl-C on a keyboard,\n # say) take affect.\n line = f.readline\n rescue EOFError\n line = nil\n end\n end\n end",
"def read(file)\n begin\n if file.class == String\n f = File::open(file)\n else\n f = file\n end\n f.each_line do |line|\n input(line.strip)\n end\n ensure\n f.close\n end\n end",
"def run_locally(stdin_text = nil, &block)\n raise ArgumentError.new('block required') unless block_given?\n\n cmd = block.call\n # cmd = \"echo '#{stdin_text}' | #{cmd}\" if stdin_text\n\n raise \"Unable to run_locally - fork method not useable\" unless Process.respond_to? :fork\n\n # preload stdin if there is input to avoid a race condition\n if stdin_text\n stdin_pipe, child_stdin = IO.pipe if stdin_text\n count = child_stdin.write(stdin_text.to_s)\n child_stdin.close\n end\n\n child_stdout, stdout_pipe = IO.pipe\n child_stderr, stderr_pipe = IO.pipe\n unless (pid = Process.fork)\n if stdin_text\n STDIN.reopen(stdin_pipe)\n else\n STDIN.close\n end\n STDOUT.reopen(stdout_pipe)\n STDERR.reopen(stderr_pipe)\n begin\n Process.exec ENV, cmd\n rescue SystemCallError => e\n STDERR.write(\"Unable to execute command '#{cmd}'\\n #{e}\")\n ensure\n exit\n end\n end\n\n Process.wait\n\n stdout = ''\n stderr = ''\n loop do\n reads, writes, obands = IO.select([child_stdout, child_stderr], [], [], 1)\n break if reads.nil?\n stdout += child_stdout.read_nonblock(1024) if reads.include? child_stdout\n stderr += child_stderr.read_nonblock(1024) if reads.include? child_stderr\n end\n stdout = nil if stdout.empty?\n stderr = nil if stderr.empty?\n\n [stdout, stderr, cmd]\n end",
"def initialize(file, line_number, &block)\n @file = file\n @line_number = line_number.to_i\n @block = block\n end",
"def process_next_block\n data = read_data\n return if data.nil?\n\n @numbers = parse_numbers(data)\n process_next_block if @numbers.empty?\n end",
"def process_block(line_buffer, test_number)\n if (@custom_processor && @custom_processor.class.method_defined?(:process_testcase))\n @custom_processor.process_testcase line_buffer\n else\n line_buffer\n end\n end",
"def each\n File.open(to_path, 'rb') do |file|\n while chunk = file.read(16384)\n yield chunk\n end\n end\n end",
"def test_read_file_many_blocks\r\n hash_calc = Minitest::Mock.new('test_hash_calculator')\r\n block_checker = Minitest::Mock.new('test_block_checker')\r\n account_tracker = Minitest::Mock.new('account_tracker')\r\n def block_checker.read_next_line; \"1|2|3|4|5|6\"; end\r\n def block_checker.parse(string, char); [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]; end\r\n output = \"Line 0: Too many '|' in the block '1|2|3|4|5|6'\"\r\n assert_equal output, @g.read_file(hash_calc, block_checker, account_tracker)\r\n end",
"def start(&block)\n while line = next_line\n cmd, *args = parse(line)\n cmd && !cmd.empty? ?\n # If the command is not empty - invoke the handler\n block.call(cmd, args) :\n # Empty command ends the processing loop\n break\n end\n end",
"def read_block\n [\n gets.strip.to_i,\n gets.strip.split(' ').map {|v| v.to_i},\n gets.strip.split(' ').map {|v| v.to_i}\n ]\nend",
"def on_file(&block)\n @on_file = block\n end",
"def inputs(*a, &block)\n if block\n capture(block){super}\n else\n capture{super}\n end\n end",
"def _extract_block(block)\n src_file_path = block.source_location[0]\n block_start_line_number = block.source_location[1]\n\n src_file_content = File.open(src_file_path).read\n lines_after_block_start = src_file_content.split(\"\\n\")[block_start_line_number..-1]\n\n # block already starts with one \"do\"\n do_counter = 1\n # assuming that \"do themize\" and corresponding \"end\" placed on separate lines\n block_end_index = 1\n lines_after_block_start.each_with_index do |line, i|\n # http://stackoverflow.com/a/11899069/6376451\n do_counter += line.scan(/<%.*?do.*?%>/).size\n do_counter -= line.scan(/<%.*?end.*?%>/).size\n if line =~ /\\s*<%\\s*end\\s*%>/ && do_counter == 0\n block_end_index = i\n break\n end\n end\n return nil if block_end_index == 0\n\n lines_after_block_start[0..block_end_index-1].join(\"\\n\")\n end",
"def map_lines\n while (inline = input.gets)\n output.puts yield(inline)\n end\n end",
"def run_block_proc\n yield\nend",
"def get_input_stream(entry, &a_proc)\n get_entry(entry).get_input_stream(&a_proc)\n end",
"def read_chunk\n #puts(\"Reading #{BLOCK_SIZE} bytes from offset #{self.head}\")\n \n # Read a block relative to the head pointer offset\n self.last_chunk = File.read(buffer_file.path, BLOCK_SIZE, self.head)\n self.head += BLOCK_SIZE\n \n # If we've read to the end, loop around to the start\n if self.head >= File.size(buffer_file)\n self.head = 0\n end \n end",
"def each\n return enum_for unless block_given?\n\n while (chunk = read)\n yield chunk\n end\n end",
"def set_block\n @block = Block.find(params[:id])\n\n\n end",
"def with_input_io\n case input\n when IO, StringIO\n yield input\n when String\n File.open(input, 'r'){|io| yield io}\n else\n raise \"Unable to convert #{input} to an IO object\"\n end\n end",
"def open\n if !@path.nil?\n @stream = File.open(file, @mode)\n end\n\n results = nil\n\n begin\n results = yield @stream if block_given?\n ensure\n if !@path.nil?\n @stream.close\n @stream = nil\n end\n end\n\n results\n end",
"def streamed_api_command(command, stdin = nil, *args, &block)\n command, args = prepare_command_args(command, args)\n i, o, t = Open3.popen2(command, *args)\n i.puts(stdin) unless stdin.blank? # If we have any input, send it to the child\n i.close # Afterwards we can close child's stdin\n if block_given?\n o.each_line do |line|\n yield line\n end\n o.close\n raise \"#{command} failed\" unless t.value.success?\n else\n return o, t # The caller has to close o and wait for t\n end\n end",
"def read_new_data(pathname, &block)\n reader = RubyFileReader::Reader.new(pathname)\n reader.read_new_data(&block)\n end",
"def process(input = nil)\n if input.nil?\n input = STDIN\n end\n\n input.each_line do |line|\n detect_filename_in line\n parse line if @filename\n end\n\n if input.is_a? IO\n puts result_as(Suspiciouss::Result::PlainText)\n else\n result_as(Suspiciouss::Result::Markdown)\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.51355225",
"0.5086606",
"0.5059761",
"0.5013563",
"0.5013002",
"0.5001322",
"0.49964568",
"0.49944764",
"0.4986663",
"0.49798727",
"0.4979174",
"0.49753696",
"0.49554467",
"0.49305028",
"0.49277368",
"0.49230537",
"0.49142167",
"0.49008864",
"0.4900513",
"0.48917723",
"0.48849007",
"0.48799497",
"0.48730433",
"0.48691186",
"0.48656636",
"0.4849262",
"0.48483852",
"0.48480844",
"0.4847346",
"0.48277092",
"0.48092407",
"0.48071018",
"0.4783341",
"0.47815853",
"0.47740757",
"0.47717324",
"0.4760049",
"0.4748487",
"0.47197536",
"0.47178572",
"0.47178572",
"0.47178572",
"0.47178572",
"0.47178572",
"0.4712571",
"0.4709819",
"0.47005525",
"0.46970192",
"0.4692144",
"0.468078",
"0.4674033",
"0.46651506",
"0.46650892",
"0.4655292",
"0.46522266",
"0.46491766",
"0.4643491",
"0.46385998",
"0.46360368",
"0.46322608",
"0.46274033",
"0.46260443",
"0.4620058",
"0.460772",
"0.4607391",
"0.4606364",
"0.46042705",
"0.46028867",
"0.46024767",
"0.45966524"
] | 0.73888326 | 0 |
Opens an output stream of the given _file_ and the specified _block_. If _file_ is not given +STDOUT+ will be used instead. The specified _block_ will be passed the newly opened output stream. Once the _block_ has returned the output stream will be flushed and closed. | def process_output(file=nil)
output = if file
File.new(file.to_s,'w')
else
STDOUT
end
yield output if block_given?
output.flush
output.close
return nil
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def open_output_file(&block)\r\n outfile = options[:outfile]\r\n if outfile\r\n File.open(outfile, 'w') { |f| block.call(f) }\r\n else\r\n block.call(STDOUT)\r\n end\r\n end",
"def output(file, &block)\n @outfile = File.expand_path(file)\n @block = block\n self\n end",
"def write(block)\n @filemgr.write(block, @contents)\n end",
"def open_with_block(opt, block)\n Tempfile.create(TEMPORARY_FILE_PREFIX, **opt) do |temporary_file|\n temporary_file.write(contents)\n temporary_file.seek(0)\n\n block.call(temporary_file)\n end\n end",
"def dump_to_file(filename, &block)\n old_stdout = $stdout\n File.open(filename, 'w') do |fo|\n $stdout = fo\n yield\n end\n $stdout = old_stdout\n end",
"def write_to_file_if_needs_block(argv)\n unless argv.empty? \n $stdout = File.open(argv[0], \"w\")\n end\n\n yield\n\n unless argv.empty? \n $stdout.flush\n $stdout.close\n $stdout = STDOUT\n end\nend",
"def write_to(file_name, &block)\n file = File.new(file_name, \"w\")\n file.write \"---\\n\"\n yield(file) if block_given?\n file.write \"---\"\n file.close\nend",
"def write(&block)\n @write_block = block\n end",
"def log_and_stream(output)\n write_file output, @filename if @filename\n @block.call(output)\n end",
"def open_write(hold_open=false,&block)\n hold_open||=@write_handle # if already open, keep open\n @write_handle=File.open(filename,\"wb\") unless @write_handle\n yield @write_handle if block\n ensure\n close_write unless hold_open\n end",
"def output(data, stream_name = :stdout, &block)\n # Pass the output to the block\n if block.arity == 2\n args = [nil, nil]\n if stream_name == :stdout\n args[0] = data\n else\n args[1] = data\n end\n block.call(*args)\n else\n yield data if stream_name == :stdout\n end\n end",
"def capture_output(stream = STDOUT, &_block)\n old_stdout = stream.clone\n pipe_r, pipe_w = IO.pipe\n pipe_r.sync = true\n output = \"\"\n reader = Thread.new do\n begin\n loop do\n output << pipe_r.readpartial(1024)\n end\n rescue EOFError\n end\n end\n stream.reopen(pipe_w)\n yield\n ensure\n stream.reopen(old_stdout)\n pipe_w.close\n reader.join\n pipe_r.close\n return output\n end",
"def open(opt = {}, &block)\n return open_with_block(opt, block) if block\n\n open_without_block(opt)\n end",
"def write_to_file\n File.open(config.block_list_path, 'a') do |f|\n block_count = old_newest_block ? (block_list.size - old_newest_block.height - 1) : block_list.size\n block_list = self.block_list.sort{|(k1, v1), (k2, v2)| v1.height <=> v2.height}\n block_list = block_list[(old_newest_block.height + 1)..-1] if old_newest_block\n block_list.each_with_index do |(k, b), index|\n f.write(b.to_payload)\n f.flush\n print \"\\r#{(((index + 1).to_f / block_count) * 100).to_i}% done write parsed block to #{config.block_list_path}.\"\n end\n f.write(newest_block.to_payload)\n puts\n end\n end",
"def <<(block)\n blocks << block\n end",
"def write\n\t\tfile = File.new(@lock_file, \"w\")\n\t\tyield(file)\n\t\tfile.close\n\tend",
"def open_file(file, mode='w', &block)\n open_up_file root, file, mode, &block\n end",
"def render_block(block, options = {})\n render partial: partial_name_for(block, options), object: block, as: :block\n end",
"def writeBlock(pieceIndex, offset, block)\n regions = @pieceMapper.findBlock(pieceIndex, offset, block.length)\n indexInBlock = 0\n regions.each do |region|\n # Get the IO for the file with path 'path'. If we are being used in a reactor, this is the IO facade. If we\n # are not then this is a real IO.\n io = @ioManager.get(region.path)\n if ! io\n # No IO for this file. \n raise \"This process doesn't have write permission for the file #{region.path}\" if File.exists?(region.path) && ! File.writable?(region.path)\n\n # Ensure parent directories exist.\n dir = File.dirname region.path\n FileUtils.mkdir_p dir if ! File.directory?(dir)\n\n begin\n io = @ioManager.open(region.path)\n rescue\n @logger.error \"Opening file #{region.path} failed: #{$!}\"\n raise \"Opening file #{region.path} failed\"\n end\n end\n\n io.seek region.offset, IO::SEEK_SET\n begin\n io.write(block[indexInBlock, region.length])\n indexInBlock += region.length\n rescue\n # Error when writing...\n @logger.error \"Writing block to file #{region.path} failed: #{$!}\"\n piece = nil\n break\n end\n\n break if indexInBlock >= block.length\n end\n end",
"def capture_stdout(&block)\n\traise ArgumentError, \"No block given\" if !block_given?\n\told_stdout = $stdout\n\t$stdout = sio = StringIO.new\n\tyield\n\t$stdout = old_stdout\n\tsio.rewind\n\tputs sio.read\n\tsio.rewind\n\tsio.read\nend",
"def set_block &b\n @block = b\n end",
"def create_block\n block = nil\n f = nil\n tf = Tempfile.new path\n tf.close\n begin\n f = File.open tf.path, 'w'\n f.allocate Block.size\n f.close\n block = Block.new\n block.device = self\n block.save!\n File.rename tf.path, block.file_path\n rescue\n f.close if f && !f.closed?\n block.destroy if block\n tf.unlink if File.exist? tf.path\n raise\n end\n # TODO(pwnall): code\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 create\n @userblock = Userblock.new(params[:userblock])\n\n respond_to do |format|\n if @userblock.save\n flash[:notice] = 'Userblock was successfully created.'\n format.html { redirect_to(:controller => 'users', :action => 'show', :login => 'current_user.login') }\n format.xml { render :xml => @userblock, :status => :created, :location => @userblock }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @userblock.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def flush_block\n bf_compr = @compressor.compress(@buffer)\n writeloc(@file, bf_compr, @location)\n @block_ary[@cur_block] = @@block.new(@cur_block, @location, bf_compr.size)\n\n @buffer = '' \n @buflocation = 0\n @cur_block += 1 \n @location += bf_compr.size\n end",
"def block\n (@blocks ||= Array.new) << Block.new\n @in_block = @blocks.last\n yield\n @in_block = nil\n end",
"def custom_out(&block)\n raise StandardError, 'custom_out requires a block argument' unless block_given?\n\n @blocks << block\n end",
"def create\n @block = Block.new(params[:block])\n\n respond_to do |format|\n if @block.save\n flash[:notice] = 'Block was successfully created.'\n format.html { redirect_to(@block) }\n format.xml { render :xml => @block, :status => :created, :location => @block }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @block.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @block = @site.blocks.build(params[:block])\n @block.user_id = current_user.id\n\n respond_to do |format|\n if @block.save\n flash[:notice] = 'Block was successfully created.'\n format.html { redirect_to(one_table_blocks_path(@one_table)) }\n format.xml { render :xml => @block, :status => :created, :location => @block }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @block.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def output\n b = block.output\n self<< b\n b\n end",
"def logBlock(message, level, component, block)\n @logger.block(\n message, level: Logging::Writer::LEVEL_TO_TYPE[level],\n component: component\n ) do\n block.apply\n end\n end",
"def capture_stdout(&block)\n out = StringIO.new\n old_stdout = $stdout\n $stdout = out\n\n block.call\n\n $stdout = old_stdout\n out.string\n 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 write_file(p, file)\n File.open(browse_file(p, file), 'w') { |fh| fh.print yield }\n end",
"def open(path, &block)\n @io = File.open(path, 'r+') # TODO: r+ will create the file if it doesn't exist =( Do a exists? check before this and simply return nil? Or raise error? I hate errorrrs\n sleep(0.1) until !@io.eof?\n\n @io.readbyte # Sync\n\n if block_given?\n yield(self)\n\n close\n end\n\n self\n end",
"def transfer_block(source, destination, block_opening = nil)\n if block_opening.nil?\n File.open(source) do |f|\n f.each do |line|\n destination.puts line\n end\n end\n else\n File.open(source) do |f|\n block_opened = false\n f.each do |line|\n if !block_opened && line.start_with?(block_opening)\n destination.puts line\n block_opened = true\n elsif block_opened && !line.start_with?('}')\n destination.puts line\n elsif block_opened && line.start_with?('}')\n destination.puts line\n break\n end\n end\n end\n end\nend",
"def create\n @block = Block.new(params[:block])\n\n respond_to do |format|\n if @block.save\n flash[:notice] = 'Block was successfully created.'\n format.html { redirect_to(@block) }\n format.xml { render :xml => @block, :status => :created, :location => @block }\n format.json { render :json => @block, :status => :created, :location => @block }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @block.errors, :status => :unprocessable_entity }\n format.json { render :json => @block.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def capture_output(&block)\n stdout = STDOUT.clone\n\n read_io, write_io = IO.pipe\n read_io.sync = true\n\n output = \"\"\n reader = Thread.new do\n begin\n loop do\n output << read_io.readpartial(1024)\n end\n rescue EOFError\n end\n end\n\n STDOUT.reopen(write_io)\n block.call\nensure\n STDOUT.reopen(stdout)\n write_io.close\n reader.join\n\n return output\nend",
"def create\n\t\t@block = Block.new(block_params)\n\n\t\trespond_to do |format|\n\t\t\tif @block.save\n\t\t\t\tformat.html { redirect_to @block, notice: 'El bloque fue creado correctamente.' }\n\t\t\t\tformat.json { render :show, status: :created, location: @block }\n\t\t\telse\n\t\t\t\tformat.html { render :new }\n\t\t\t\tformat.json { render json: @block.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def execute_block(&block)\n @currently_executing_block = true\n output \"tell session id #{name}_tty\"\n self.instance_eval(&block)\n output \"end tell\"\n @currently_executing_block = false\n end",
"def stream keep_open=false, &block\n scheduler = env[ASYNC_CALLBACK] ? EventMachine : Gin::Stream\n body Gin::Stream.new(scheduler, keep_open){ |out| yield(out) }\n end",
"def log_and_stream(output)\n write_file output, runlog_filename if runlog_filename\n return @block.call(output) unless @block.nil?\n \"\"\n end",
"def create\n @block = Block.new(block_params)\n\n respond_to do |format|\n if @block.save\n format.html { render @block, notice: \"#{@block.id}\" }\n format.json { render action: 'show', status: :created, location: @block }\n else\n format.html { render action: 'new' }\n format.json { render json: @block.errors, status: :unprocessable_entity }\n end\n end\n end",
"def open_without_block(opt)\n file = Tempfile.new(TEMPORARY_FILE_PREFIX, Dir.tmpdir, **opt)\n file.write(contents)\n file.seek(0)\n file\n rescue StandardError\n file&.close!\n raise\n end",
"def create\n\t\t@block = Block.new(block_params)\n\n\t\tif @block.save\n\t\t\tredirect_to blocks_path\n\t\telse\n\t\t\trender 'new'\n\t\tend\n\n\tend",
"def spec_helper_silence_stream( stream, &block )\n begin\n old_stream = stream.dup\n stream.reopen( File::NULL )\n stream.sync = true\n\n yield\n\n ensure\n stream.reopen( old_stream )\n old_stream.close\n\n end\nend",
"def write( &block )\n compile!( :write!, &block )\n end",
"def output\n # if file name not present, just output to stdout.\n return $stdout.write(yield) if option[:ofile].nil?\n\n # times of calling output\n @serial ||= 0\n # Write to file, we should disable colorize\n enabled = Util.colorize_enabled?\n Util.disable_color! if enabled\n File.binwrite(file_of(option[:ofile], @serial), yield)\n Util.enable_color! if enabled\n @serial += 1\n end",
"def render_block(name, context, blocks = {}, use_blocks = true)\n # ob_start();\n display_block(name, context, blocks, use_blocks)\n # return ob_get_clean();\n end",
"def capture(stream=STDOUT, &block)\n old_stdout = stream.clone\n pipe_r, pipe_w = IO.pipe\n pipe_r.sync = true\n output = \"\"\n reader = Thread.new do\n begin\n loop do\n output << pipe_r.readpartial(1024)\n end\n rescue EOFError\n end\n end\n stream.reopen(pipe_w)\n yield\n ensure\n stream.reopen(old_stdout)\n pipe_w.close\n reader.join\n pipe_r.close\n return output\n end",
"def open(path, &block)\n File.open(File.join(self.path, path), \"r\", &block)\n end",
"def stream(&block)\n attributes[:streams] << API::Stream.build(&block)\n end",
"def open\n if !@path.nil?\n @stream = File.open(file, @mode)\n end\n\n results = nil\n\n begin\n results = yield @stream if block_given?\n ensure\n if !@path.nil?\n @stream.close\n @stream = nil\n end\n end\n\n results\n end",
"def lock_file(file, &_block)\n if ::File.exist?(file)\n ::File.open(file, 'r+') do |f|\n begin\n f.flock ::File::LOCK_EX\n yield if block_given?\n ensure\n f.flock ::File::LOCK_UN\n end\n end\n else\n yield if block_given?\n end\n end",
"def append_to_block(line)\n @block_buffer = (@block_buffer || '') + line\n end",
"def lock(&block)\n result = nil\n File.open(path + 'f.lock', 'w') do |fd|\n if fd.flock(File::LOCK_EX)\n begin\n result = block.call\n ensure\n fd.flock(File::LOCK_UN)\n end\n end\n end\n result\n end",
"def html_block_show(block)\n title, content = send(block.class.to_s.underscore, block)\n html_blocklike_show(title, content)\n end",
"def write_nonblock\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 create\n @block = Block.new(block_params)\n\n respond_to do |format|\n if @block.save\n format.html { redirect_to @block, notice: 'Block was successfully created.' }\n format.json { render action: 'show', status: :created, location: @block }\n else\n format.html { render action: 'new' }\n format.json { render json: @block.errors, status: :unprocessable_entity }\n end\n end\n end",
"def suppress_output(&block)\n $stdout = File.new(\"/dev/null\", \"w\")\n $stderr = File.new(\"/dev/null\", \"w\")\n result = block.call\n $stdout = STDOUT\n $stderr = STDERR\n result\n end",
"def create\n @block = Block.new(block_params)\n\n respond_to do |format|\n if @block.save\n format.html { redirect_back(fallback_location: root_path) }\n format.json { render :show, status: :created, location: @block }\n else\n format.html { render :show }\n format.json { render json: @block.errors, status: :unprocessable_entity }\n end\n end\n end",
"def stream\n @stream ||=\n ::File.open(file, \"w+\")\n end",
"def execute_block(block)\n case\n when block.is_a?(Symbol)\n send(block)\n when block.respond_to?(:call) && (block.arity == 1 || block.arity == -1)\n block.call(self)\n else\n block\n end \n end",
"def create\n @block = Block.new(block_params)\n\n respond_to do |format|\n if @block.save\n format.html { redirect_to @block, notice: 'Block was successfully created.' }\n format.json { render :show, status: :created, location: @block }\n else\n format.html { render :new }\n format.json { render json: @block.errors, status: :unprocessable_entity }\n end\n end\n end",
"def capture_output &block\n old_stdout = $stdout\n test_stdout = StringIO.new\n $stdout = test_stdout\n block.call\n test_stdout.string\nensure\n $stdout = old_stdout\nend",
"def block(user)\n post \"blocks/create/#{user}\"\n end",
"def toggle_block(options={}, &block)\n visible = options.has_key?(:visible) ? options[:visible] : true\n escapable = options.has_key?(:escapable) ? options[:escapable] : false\n out = \"<span class='toggle_block'>\"\n if options[:handle]\n out << \"<span class='toggle_block_content'>#{capture(visible, &block)}</span>\"\n out << \"<span class='toggled_block_content' style='display: none;'>#{capture(!visible, &block)}</span>\"\n out << handle_element(options[:handle])\n else\n if options[:toggle_handle]\n out << \"<span class='toggle_block_content'>#{capture(visible, &block)}#{handle_element(options[:toggle_handle])}</span>\"\n else\n out << \"<span class='toggle_block_content toggle_block_handle'>#{capture(visible, &block)}</span>\"\n end\n if options[:toggled_handle]\n out << \"<span class='toggled_block_content' style='display: none;'>#{capture(!visible, &block)}#{handle_element(options[:toggled_handle])}</span>\"\n else\n out << \"<span class='toggled_block_content toggle_block_handle' style='display: none;'>#{capture(!visible, &block)}</span>\"\n end\n end\n out << \"</span>\"\n raw out\n end",
"def print_result(&block)\n result_from_block = block.call()\n puts result_from_block\nend",
"def read(block)\n @filemgr.read(block, @contents)\n end",
"def write_to_output filename, content = nil # :yields: file\n self.create_output_file(filename) do |output_path|\n File.open(output_path, 'w') do |f|\n if content\n f.write(content)\n else\n yield f\n end\n end\n end\n end",
"def open( *args, &block ) # :yield: file\n File.open( expand_tilde, *args, &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 block_print\r\n\tputs \"Before the block!\"\r\n\tyield(10)\r\n\tputs \"After the block!\"\r\nend",
"def print_block_result\n block_result = yield\n puts block_result\nend",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def set_block\n @block = Block.find(params[:id])\n end",
"def format(&block)\n @format = block if block\n @format\n end",
"def write_image(&block)\n @image = GD2::Image.new(@width, @height)\n self.instance_eval(&block)\n @image.export(self.full_path)\n end",
"def redirect\n orig_defout = $defout\n $stdout = StringIO.new\n yield\n $stdout.string\n ensure\n $stdout = orig_defout\n end",
"def create\n @block = Block.new(params[:block])\n\n respond_to do |format|\n if @block.save\n format.html { redirect_to @block, :notice => 'Block was successfully created.' }\n format.json { render :json => @block, :status => :created, :location => @block }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @block.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def write_output_file(filename, &block)\n file = dir(File.join(\"output\", filename))\n File.open(file, 'w') do |f|\n yield f\n end\n @touchedfiles << undir(file)\n end",
"def <<(block)\n # parent assignment pending refactor\n #block.parent = self\n @blocks << block\n end",
"def call_block(block,stdout,stderr,exitstatus)\n # blocks that take no arguments have arity -1. Or 0. Ugh.\n if block.arity > 0\n case block.arity\n when 1 \n block.call(stdout)\n when 2\n block.call(stdout,stderr)\n else\n # Let it fail for lambdas\n block.call(stdout,stderr,exitstatus)\n end\n else\n block.call\n end\n end",
"def render(&block) #:nodoc:\r\n instance_eval(&block)\r\n @output_buffer\r\n end",
"def update\n @block = @site.blocks.find(params[:id])\n\n respond_to do |format|\n params[:block].delete :user_id\n if @block.update_attributes(params[:block])\n flash[:notice] = 'Block was successfully updated.'\n format.html { redirect_to([@site, @block]) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @block.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def dev_null(&block)\n begin\n orig_stdout = $stdout.dup # does a dup2() internally\n $stdout.reopen('/dev/null', 'w')\n yield\n ensure\n $stdout.reopen(orig_stdout)\n end\nend",
"def record_block\n @block = true\n end",
"def write(block_name, src_buffer)\n if block_name == @mem_file.size\n @mem_file << alloc_buffer\n end\n dest = @mem_file[block_name]\n ByteArray.copy(src_buffer,0,@block_size,dest,0)\n end",
"def close( &block )\n compile!( :close!, &block )\n end",
"def open(*a, &block)\n @device.open(*a) unless enabled?\n @enabled = true\n if block_given?\n begin\n yield(self)\n ensure\n close\n end\n else\n at_exit do\n close\n end\n self\n end\n end",
"def send_file(file_path, &block)\n if block.given?\n @j_del.sendFile(file_path, ARWrappedHandler.new(block))\n else\n @j_del.sendFile(file_path)\n end\n self\n end",
"def open(&block)\n repo.blob_pipe(sha, &block)\n end",
"def capture_output( &block )\n output_queue = Queue.new\n\n # Save original write implementation\n orig_stdout_write = STDOUT.method( :write )\n orig_stderr_write = STDERR.method( :write )\n\n #\n # Hijack #write method and push input string to queue.\n #\n\n STDOUT.define_singleton_method :write do |string|\n orig_stdout_write.call( string ).tap do\n output_queue << [ :stdout, string ]\n end\n end\n\n STDERR.define_singleton_method :write do |string|\n orig_stderr_write.call( string ).tap do\n output_queue << [ :stderr, string ]\n end\n end\n\n # Separate thread to push strings to block in background.\n capture_thread = Thread.new {\n loop do\n block.call( *output_queue.pop )\n end\n }\n\n # Wait for Ctrl+c\n loop do\n break if _pry_.input.getch == ?\\C-c\n end\n ensure\n capture_thread.kill\n\n # Restore original write implementation.\n STDOUT.define_singleton_method :write, orig_stdout_write\n STDERR.define_singleton_method :write, orig_stderr_write\n end",
"def capture_stdout(&block)\n\t\t original_stdout = $stdout\n\t\t $stdout = fake = StringIO.new\n\t\t begin\n\t\t yield\n\t\t ensure\n\t\t $stdout = original_stdout\n\t\t end\n\t\t fake.string\n\t\tend",
"def write(io_or_filename, &block)\n raise ArgumentError, \"missing block\" unless block_given?\n\n if io_or_filename.respond_to?(:write)\n write_to_io(io_or_filename, &block)\n else\n File.open(io_or_filename, 'w') do |file|\n write_to_io(file, &block)\n end\n end\n end",
"def beginprint(file_path)\n super(file_path)\n return unless block_given?\n\n yield\n endprint\n end"
] | [
"0.7268191",
"0.65893984",
"0.60492516",
"0.5772207",
"0.57595426",
"0.5591552",
"0.54906857",
"0.5461353",
"0.54451644",
"0.5399881",
"0.5226066",
"0.5196414",
"0.51919144",
"0.5190104",
"0.51548654",
"0.5147926",
"0.5137622",
"0.49896684",
"0.4972093",
"0.4962156",
"0.49604946",
"0.4914383",
"0.49044287",
"0.48878455",
"0.48725536",
"0.48574135",
"0.48478273",
"0.48373267",
"0.48351428",
"0.48219016",
"0.48217827",
"0.48119438",
"0.48030496",
"0.4791185",
"0.4787573",
"0.47838408",
"0.47824064",
"0.47514758",
"0.47487348",
"0.4743109",
"0.47416842",
"0.47372955",
"0.47136843",
"0.46978393",
"0.4691045",
"0.46822867",
"0.46804014",
"0.46771953",
"0.46731246",
"0.46714583",
"0.46594304",
"0.46575466",
"0.46569943",
"0.4655261",
"0.46498287",
"0.46393514",
"0.46384633",
"0.46339238",
"0.4632739",
"0.46259367",
"0.4612273",
"0.46101183",
"0.46080768",
"0.4594101",
"0.45909002",
"0.45871162",
"0.45768613",
"0.45761555",
"0.45757368",
"0.4571404",
"0.4565111",
"0.45644608",
"0.45640248",
"0.45572674",
"0.45448375",
"0.45421734",
"0.45421734",
"0.45421734",
"0.45421734",
"0.45421734",
"0.45405826",
"0.45334753",
"0.4516145",
"0.45106268",
"0.4510414",
"0.450866",
"0.44977608",
"0.4488495",
"0.4484107",
"0.44809",
"0.44740474",
"0.446772",
"0.44623253",
"0.4460025",
"0.44589257",
"0.44561422",
"0.44539934",
"0.4444656",
"0.44417113",
"0.44381094"
] | 0.5548416 | 6 |
Only allow a list of trusted parameters through. | def score_params
params.require(:score).permit(:user_id, :time, :difficulty)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def allowed_params\n ALLOWED_PARAMS\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def parameters_list_params\n params.require(:parameters_list).permit(:name, :description, :is_user_specific)\n end",
"def param_whitelist\n [:role, :title]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def allow_params_authentication!; end",
"def whitelisted_args\n args.select &:allowed\n end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def filtered_parameters; end",
"def sanitize_params_for user, params, allowed_params\n params.each do |key, val|\n #if allowed_params.include?(key)\n #sanitize!(user, params, key) if key =~ /_attributes|_ids$/\n #else\n #params.delete(key)\n #end\n params.delete(key) unless allowed_params.include?(key.to_sym)\n end\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def expected_permitted_parameter_names; end",
"def sanitize_parameters!(sanitizer, params)\n # replace :readwrite with :onlyif\n if params.has_key?(:readwrite)\n warn \":readwrite is deprecated. Replacing with :onlyif\"\n params[:onlyif] = params.delete(:readwrite)\n end\n\n # add default parameters\n bindata_default_parameters.each do |k,v|\n params[k] = v unless params.has_key?(k)\n end\n\n # ensure mandatory parameters exist\n bindata_mandatory_parameters.each do |prm|\n if not params.has_key?(prm)\n raise ArgumentError, \"parameter ':#{prm}' must be specified \" +\n \"in #{self}\"\n end\n end\n\n # ensure mutual exclusion\n bindata_mutually_exclusive_parameters.each do |param1, param2|\n if params.has_key?(param1) and params.has_key?(param2)\n raise ArgumentError, \"params #{param1} and #{param2} \" +\n \"are mutually exclusive\"\n end\n end\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def check_params; true; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def allowed?(*_)\n true\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def allowed_params(parameters)\n parameters.select do |name, values|\n values.location != \"path\"\n end\n end",
"def secure_params\n return @secure_params if @secure_params\n\n defn = implementation_class.definition\n field_list = [:master_id] + defn.field_list_array\n\n res = params.require(controller_name.singularize.to_sym).permit(field_list)\n res[implementation_class.external_id_attribute.to_sym] = nil if implementation_class.allow_to_generate_ids?\n @secure_params = res\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permit( params, whitelist, name = nil )\n raise 'Parametrization not yet configured' unless @configured\n whitelist ||= []\n px = params.respond_to?( :permit ) ? params : ActionController::Parameters.new( params )\n px = dig(px, name)\n px.permit( *whitelist )\n end",
"def valid_params?; end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def url_allowlist=(_arg0); end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def list_params\n params.permit(:list_name)\n end",
"def valid_params_request?; end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def param_list(param_type, name, type, required, description = nil, allowed_values = [], hash = {})\n hash.merge!({allowable_values: {value_type: \"LIST\", values: allowed_values}})\n param(param_type, name, type, required, description, hash)\n end",
"def safelists; end",
"def authorize_own_lists\n authorize_lists current_user.lists\n end",
"def listed_params\n params.permit(:listed, :list_id, :listable_id, :listable_type, :campsite_id)\n end",
"def lists_params\n params.require(:list).permit(:name)\n\n end",
"def list_params\n params.require(:list).permit(:name, :user_id)\n end",
"def list_params\n params.require(:list).permit(:name, :description, :type, :privacy, :allow_edit, :rating, :votes_count, :user_id)\n end",
"def check_params\n true\n end",
"def authorize_own_or_shared_lists\n authorize_lists current_user.all_lists\n end",
"def user_pref_list_params\n\t\tparams.require(:user).permit(:preference_list)\n\tend",
"def may_contain!(*keys)\n self.allow_only_permitted = true\n self.permitted_keys = [*permitted_keys, *keys].uniq\n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def whitelist; end",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.permit(:name)\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :list, :references)\n end",
"def cancan_parameter_sanitizer\n resource = controller_name.singularize.to_sym\n method = \"#{resource}_params\"\n params[resource] &&= send(method) if respond_to?(method, true)\n end",
"def list_params\n params.require(:list).permit(:name).merge(user_id: current_user.id)\n end",
"def whitelist_place_params\n params.require(:place).permit(:place_name, :unlock, :auth, :is_deep_checked, :parent_ADM4, :parent_ADM3, :parent_ADM2, :parent_ADM1, :parent_country, feature_code: [], same_as: [], related_authority: [], altlabel: [], note: []) # Note - arrays need to go at the end or an error occurs!\n end",
"def list_params\n params.fetch(:list, {}).permit(:user_id, :name, :active)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def secure_params(require_param, permit_keys)\n params.require(require_param).permit(*permit_keys)\n end",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def permitted_params\n []\n end",
"def price_list_params\n params.fetch(:price_list, {}).permit(:name, :valid_from, :valid_to, :active,\n :all_warehouses, :all_users, :all_contact_groups,\n warehouse_ids: [], price_lists_user_ids: [], contact_group_ids: [])\n end",
"def params(list)\n @declared_params = list\n end",
"def admin_review_params\n params.fetch(:review, {}).permit(whitelisted_params)\n end",
"def saved_list_params\n params.require(:saved_list).permit(:user_id)\n end",
"def allow(ids); end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def filter_params(param_set, **kwargs)\r\n begin\r\n key = kwargs[:key]\r\n params.require(key).permit(*param_set)\r\n rescue Exception\r\n params.permit(*param_set)\r\n end\r\n end",
"def valid_parameters\n sort_symbols(@interface.allowed_parameters)\n end",
"def validate_paramified_params\n self.class.paramify_methods.each do |method|\n params = send(method)\n transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid?\n end\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def secure_params\n return @secure_params if @secure_params\n\n @implementation_class = implementation_class\n resname = @implementation_class.name.ns_underscore.gsub('__', '_').singularize.to_sym\n @secure_params = params.require(resname).permit(*permitted_params)\n end",
"def refine_permitted_params(param_list)\n res = param_list.dup\n\n ms_keys = res.select { |a| columns_hash[a.to_s]&.array }\n ms_keys.each do |k|\n res.delete(k)\n res << { k => [] }\n end\n\n res\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :description, recipient_id_array: [])\n end",
"def safelist; end",
"def sponsor_params\n params.require(:sponsor).permit(WHITE_LIST)\n end",
"def valid_for_params_auth?; end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def shopping_list_params\n params.require(:shopping_list).permit!\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def permitters\n @_parametrizr_permitters || {}\n end",
"def allow_params(action, keys: nil, except: nil, &blk)\n keys &&= Array.wrap(keys)\n keys ||= User.field_names\n except &&= Array.wrap(except)\n except ||= %i[id email]\n devise_parameter_sanitizer.permit(action, keys: keys, except: except, &blk)\n end",
"def list_params\n if current_user && current_user.role == 'admin'\n params.require(:list).permit(:name, :url, :description, :user_id,\n ideas_attributes: [:id, :list_id, :body, :due_date, :completion_status, :_destroy])\n else\n params.require(:list).permit(:name, :description,\n ideas_attributes: [:body, :due_date, :completion_status]) \n end\n end",
"def whitelist(params)\n send_request_of_type(GlobalConstant::PrivateOpsApi.private_ops_api_type, 'post', '/token-sale/whitelist', params)\n end",
"def valid_access_params\n params.require(:valid_access).permit(:wish_list_id, :user_id)\n end",
"def url_allowlist; end",
"def ensure_redirected_params_are_safe!(passed_params)\n unless passed_params.is_a?(ActionController::Parameters) && passed_params.permitted?\n error_message = if passed_params.is_a?(ActionController::Parameters)\n unsafe_parameters = passed_params.send(:unpermitted_keys, params)\n \"[Rails::Prg] Error - Must use permitted strong parameters. Unsafe: #{unsafe_parameters.join(', ')}\"\n else\n \"[Rails::Prg] Error - Must pass strong parameters.\"\n end\n raise error_message\n end\n end",
"def data_collection_params\n allow = [:name,:description,:institution,:collection_name,:country_id,:province_id,:city_id]\n params.require(:data_collection).permit(allow)\n end",
"def quote_params\n params.permit!\n end"
] | [
"0.69497335",
"0.6812623",
"0.6803639",
"0.6795365",
"0.67448795",
"0.67399913",
"0.6526815",
"0.6518771",
"0.64931697",
"0.6430388",
"0.6430388",
"0.6430388",
"0.63983387",
"0.6356042",
"0.63535863",
"0.63464934",
"0.63444513",
"0.6337208",
"0.6326454",
"0.6326454",
"0.6326454",
"0.63140553",
"0.6299814",
"0.62642586",
"0.626006",
"0.62578833",
"0.6236823",
"0.6227561",
"0.6221758",
"0.62200165",
"0.620879",
"0.61983657",
"0.6195055",
"0.6172993",
"0.6156856",
"0.61558664",
"0.61521494",
"0.6135789",
"0.6121145",
"0.61118174",
"0.60736513",
"0.6071645",
"0.60632104",
"0.60549796",
"0.6043906",
"0.6034662",
"0.60207325",
"0.6018568",
"0.6016575",
"0.60103434",
"0.60084206",
"0.600763",
"0.6007443",
"0.6003619",
"0.6003619",
"0.5995791",
"0.5993301",
"0.5993231",
"0.5984926",
"0.597122",
"0.5968121",
"0.5965808",
"0.59640145",
"0.59632224",
"0.59602356",
"0.59332967",
"0.5927556",
"0.5922805",
"0.5909745",
"0.5905083",
"0.5904304",
"0.5893434",
"0.58888215",
"0.58823985",
"0.58823985",
"0.58823985",
"0.5873434",
"0.58619875",
"0.58533794",
"0.5845531",
"0.58426666",
"0.58360124",
"0.583218",
"0.5828041",
"0.5827927",
"0.5816121",
"0.5814705",
"0.5812719",
"0.581121",
"0.5803423",
"0.5803423",
"0.57995003",
"0.5794207",
"0.5784923",
"0.5781365",
"0.5776385",
"0.5774859",
"0.57671493",
"0.5766998",
"0.57618684",
"0.5758038"
] | 0.0 | -1 |
input: string of items separated by spaces (example: "carrots apples cereal pizza") steps: call the method food_list set default quantity (quantity = 0) creat a hash, where key is item and value is quantity print the list to the console [can you use one of your other methods here?] use print method for this step output: [what data type goes here, array or hash?] hash, a list in the form of strings | def food_list
list = Hash.new
list ["carrots"] = 0
list ["apples"] = 0
list ["pizza"] = 0
list ["cereal"] = 0
list
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_list(user_list)\n# input: string of items separated by spaces (example: \"carrots apples cereal pizza\")\n# puts \"\"\n# steps:\n # [fill in any steps here]\n list_array = user_list.split(\",\")\n # set default quantity\n quanity = 1\n # print the list to the console [can you use one of your other methods here?]\n p list_array.collect { |item| [item, quanity] }\n $list_hash = Hash[list_array.collect { |item| [item, quanity] } ]\n# output: [what data type goes here, array or hash?] Print result in hash\n p $list_hash\n $list_hash\nend",
"def create_grocery_list(shopping_items)\n # steps:\n # create an empty hash\n grocery_list = {}\n # add items\n # convert input into separate items\n shopping_items = shopping_items.split\n # add items to hash and set default quantity\n shopping_items.each do |item_name|\n grocery_list[item_name.to_sym] = 1\n end\n # print the list to the console [can you use one of your other methods here?]\n print_grocery_list(grocery_list)\n# output: explicit return the hash\n grocery_list\nend",
"def create_list_items(input_string)\n \n hsh = {}\n \n # create an array containing each item \n array_input = input_string.split(' ')\n \n # create a hash from the array (iterate), containing the information of key/value pairs \n array_input.each do |item|\n # set default quantity as value\n hsh[item] = 0\n end \n \n # print the list to the console (we will use the last method)\n print_list(hsh)\n \n # output: hash data structure of key/value pairs\n return hsh\nend",
"def createlist(str)\r\n# steps:\r\n# break the string into an array\r\n items = str.split\r\n item_list = {}\r\n\r\n\t# iterate through array and build hash\r\n items.each do |item|\r\n\r\n\t\t# iterate through array and build hash\r\n\t\t# set default quantity to 1\r\n \titem_list[item] = 1\r\n end\r\n # print the list to the console [the last method that print a list and make it look pretty]\r\n print_list(item_list)\r\n\r\n # output: the hash\r\n return item_list\r\nend",
"def create_list(input)\n grocery_list = {}\n # convert items in string to hash keys:\n input_array = input.split\n # convert string into array using\n # iterate through array assign each string item to a hash key with default value of x\n # set default quantity\n # iteration loop\n # grocery_list[\"key_name1\"] => 3\n input_array.each do |i|\n grocery_list[i] = 3\n end\n # print the list to the console [can you use one of your other methods here?]\n # call the method for printing a list *below*\n # output: [what data type goes here, array or hash?]\n # make output return hash\n # grocery_list, call the hash so that the last evaluated item is the hash.. and then that is returned\n grocery_list\nend",
"def grocery_list(grocery_items)\n # input: string of items separated by spaces (example: \"carrots apples cereal pizza\") \n # steps: \n # Create a new empty data structure (Hash) \n grocery = {}\n # Convert the string parameter into an array of words.\n item = grocery_items.split(\" \")\n # Iterate through the array and get the element.\n item.each do |product|\n # Store the element as a key in the hash.\n # set default quantity an integer with value 3. This is the default value of the keys in the hash.\n grocery[product] = 3\n display_list(grocery)\n end\n # print the list to the console [can you use one of your other methods here?]\n # output: Hash \n grocery\nend",
"def create_list(string)\n puts \"What is the default item quantity?\"\n default_quantity = gets.chomp.to_s\n list_array = string.split(' ')\n list_hash = {}\n list_array.each do |item|\n list_hash[item] = default_quantity\n end\n\n print_list(list_hash)\n\n list_hash\nend",
"def add_item(list, item, quantity=1)\r\n# input: item name and optional quantity\r\n# steps: \r\n # Use shopping list as input\r\n # Use the item to be added as 2nd input\r\n # Use the item quantity as a 3rd input (look up whether optional input is possible)\r\n # Add the item and quantity to the shopping list\r\n list[item] = quantity\r\n# output: shopping list with the added item and quantity\r\n printlist(list)\r\nend",
"def create_list(items_string)\r\n\tdefault_quantity = 1\r\n\r\n\tgrocery_list = Hash.new{|hash, key| hash[key] = default_quantity}\r\n\titems_array = items_string.split(\" \")\r\n\t\r\n\titems_array.each do |item| \r\n\t\tgrocery_list[item.to_sym]\r\n\tend\r\n\tprint_list(grocery_list)\r\n\tgrocery_list\r\nend",
"def initial_list(string_of_items)\n grocery_list = {}\n quantity = 1\n items_array = string_of_items.split(\" \")\n items_array.each do |item|\n grocery_list.store(item, quantity)\n end\n grocery_list\nend",
"def create_list(str, default_quantity=1)\n list = {}\n item_array = str.split\n item_array.each do |item|\n list[item] = default_quantity\n end\n print_list(list)\n return list\nend",
"def shopping_list(string)\n\tgrocery_list = {}\n# steps: \n \t# separate string into array\n\tarray = string.split(' ')\n\t# loop through array to create hash with items in array as key and set default quantity to \"\"\n\tarray.map {|item| grocery_list[item] = \"\"}\n\t# print the list to the console [can you use one of your other methods here?]\n\t# output: [what data type goes here, array or hash?]\n\tputs grocery_list\n\treturn grocery_list\nend",
"def create_list(input_string)\n grocery_list = {}\n items = input_string.split(' ')\n items.each do |item|\n add_item_to_list(grocery_list, item, 1)\n end\n\n print_list(grocery_list)\n\n add_item_to_list(grocery_list, \"milk\", 1)\n update_item_from_list(grocery_list, \"Lemonade\", 2)\n update_item_from_list(grocery_list, \"Tomatoes\", 3)\n update_item_from_list(grocery_list, \"Onions\", 10)\n update_item_from_list(grocery_list, \"iceCream\", 20)\n\n print_list(grocery_list)\n\n remove_item_from_list(grocery_list, \"IceCream\")\n\n print_list(grocery_list)\n\nend",
"def create_list(title, list_arr)\n # grocery_list will be a string from user\n # assign an empty hash (will eventually be the list)\n final_list = {}\n # use split method to get list items\n list_arr = list_arr.split\n # Iterate through the elements of the array and insert to hash\n # set default quantity\n list_arr.each { |item| final_list[item]=1}\n # print the list to the console [can you use one of your other methods here?]\n puts print_list(title,final_list)\n final_list\nend",
"def create_list\n\tgrocery_list = {}\n\tprint \"Please enter the items you need to buy seperated by spaces(example: 'carrots apples cereal'): \"\n\tarr_food = gets.chomp.split\n\tarr_food.each do |item|\n\t\tgrocery_list[item] = 1\n\tend\n\tprint_list(grocery_list)\nend",
"def create_list(list_str)\n food_list = {}\n list_array=list_str.split(\" \")\n default_qty = 1\n list_array.each do |food|\n food_list[food.to_sym] = default_qty\n end\n food_list\nend",
"def print_list(my_list)\r\n# input: \r\n \r\n# steps:\r\n# print to screen: iterate through hash item - quantity\r\n puts '------'\r\n puts \"Grocery list:\"\r\n my_list.each do |item, qty|\r\n puts \"#{item} - #{qty}\"\r\n end\r\n puts '-------'\r\n# output: each k,v pair printed surrounded by dashes\r\nend",
"def create_list(string_of_items, default_quantity)\n grocery_array = string_of_items.split(' ')\n grocery_hash = {}\n grocery_array.each { |item| grocery_hash[item] = default_quantity }\n grocery_hash\nend",
"def generate_list(string_of_items)\n grocery_list={}\n default_value=1\n items=string_of_items.split(' ')\n items.each do |item|\n #Transfer items into hash\n grocery_list[item]=default_value\n end\n return grocery_list\n print(grocery_list)\nend",
"def hash_start(food, quantity=1)\n\tgrocery_list = {}\n\n\tfood.split.each { |item| grocery_list[item] = quantity }\n\t\t\n\tgrocery_list\nend",
"def create_list(items_string, quantity = 0)\n list = {}\n items = items_string.split(\" \")\n items.each do |item|\n list[item] = quantity\n end\n list\nend",
"def create_list(list, grocery_hash={})\n\tlist_array = list.split(\" \")\n\tquantity = 0\n\tlist_array.each do |item|\n\t\tgrocery_hash[item]=quantity\n\tend\n\tprint_list(grocery_hash)\n\treturn grocery_hash\nend",
"def print_list(list)\r\n# input: completed list\r\n# steps:\r\n # iterate over list and print formatted list\r\n puts \"Your Grocery List\"\r\n list.each do |item, quantity|\r\n puts \"#{item}, qty: #{quantity}\"\r\n end\r\n # format: each item with its own line\r\n # \"item - quantity\"\r\n# output: implicit return of list\r\nend",
"def create_list(list_name,list_of_items)\n # create empty array\n list_name = []\n # for each item in string, use add item method to add item to grocery list (set default quantity to 1)\n shopping_items = list_of_items.split(' ')\n shopping_items.each do |thing_to_add|\n add_item_to_list(list_name,thing_to_add,1)\n end\n # print the list to the console\n print_list(list_name)\nend",
"def create_list(items)\n\titem_list = {}\n\titem_array = items.split(\" \")\n\tdefault_quantity = 1\n\titem_array.each do |item|\n\t\titem_list[item] = default_quantity\n\tend\n\tpretty_list(item_list) \nend",
"def add_item(list, item, quantity = 1)\r\n# input: list, item name, and optional quantity\r\n# steps: \r\n # check for optional quantity. if not present, set to default (1)\r\n list[item] = quantity\r\n # update list with input\r\n puts \"#{item.upcase} has been added to your grocery list!\"\r\n p list\r\n# output: complete list, updated\r\nend",
"def shopping_list(items)\n\t# separate the items into an array\n\titems = items.split\n\tputs \"Here are the items you entered.\"\n\tputs items\t\n\t# create the list to add items into.\n\t$list = Hash.new\n\t# enter quantity of each item.\n\titems.each_index do |x|\n\t\tputs \"Enter quantity with no spaces for #{items[x]}.\"\n\t\tquantity = gets.chomp\n\t\t# assign each quantity to the item and add to list\n\t\t$list[:\"#{items[x]}\"] = quantity\n\tend\n\tputs \"Here is your shopping list.\"\n\tputs $list\nend",
"def list_of_items(userinput)\n itemlist = []\n final_list = {}\n itemlist = userinput.split(' ')\n p itemlist\n quantity = 1\n itemlist.each do |value|\n final_list[value] = 1\n end\n puts final_list\n final_list\nend",
"def add_item(list, add_item, add_quantity=1)\n# steps:\n # Add item as key and quantity as value to final_list hash(item and quantity will be user inputs)\n list[add_item] = add_quantity\n # Return updated hash\n list\nend",
"def add_item(my_list, item, quantity)\r\n #input: a string seperated by an integer \r\n #steps: use a method that adds an item and quantity to the hash.\r\n my_list.store(item, quantity)\r\n # use a hash or store method hash.merge!(key => value) \r\n #output = hash with the updated item/quantity. \r\n my_list\r\n \r\nend",
"def create_list(food_string)\n grocery_list = {}\n new_food_array = food_string.split(\" \")\n new_food_array.each do |food|\n grocery_list[food] = 0\n end\n # p grocery_list\n print_list(grocery_list)\n return grocery_list\nend",
"def make_list (list, quantity = $default_quantity)\r\n list_arr = list.split\r\n list_arr.each do |list_item|\r\n $grocery_list[list_item] = quantity\r\n end\r\nend",
"def create_a_list(string_of_items)\n qty = 1\n grocery_hash = Hash.new\n string_of_items.split(\" \").each do |x|\n grocery_hash[x] = qty\n end\n grocery_hash\nend",
"def create_list(items, quantity=1)\r\n item_array = items.split(' ')\r\n item_hash = {}\r\n item_array.each do |items|\r\n item_hash[items] = quantity\r\n end \r\n p item_hash # p will both print and return # puts will print but will not return. It will return nil.\r\nend",
"def add_item(list_name, item, quantity=1)\r\n# input: list, item name, and optional quantity\r\n# steps: add item and its quantity to the hash\r\n list_name.store(item, quantity)\r\n# output: hash with new item\r\n p list_name\r\nend",
"def list_create(items)\n hash_items = Hash.new\n default_quantity = 1\n\n # adding a slick way to initialize hash in one line, but not as readable\n # return items.split(' ').product([1]).to_h\n\n items.split(' ').each do |x|\n hash_items[x] = default_quantity\n end\n\n return hash_items\nend",
"def create_list(items)\r\n\r\n\tshopping_list ={}\r\n\r\n\titems.split(\" \").each do |item|\r\n\t\tshopping_list[item] = 1\r\n\tend\r\n\r\n\t# will put a method call\r\n\tprint_list(shopping_list)\r\n\treturn shopping_list\r\n\r\nend",
"def create_list(list)\n grocery_list = Hash.new\n default_quantity = 1 \n list.split(\" \").each {|x| grocery_list[x] = default_quantity }\n p grocery_list\nend",
"def create_list(string_of_items)\n grocery_list = {}\n grocery_items = string_of_items.split\n grocery_items.each do |item, quantity|\n grocery_list[item] = 1\n end \n return grocery_list\nend",
"def add_item(list, name, quantity = 1) \r\n# input: item name and optional quantity\r\n# steps: \r\n# create add method with name and optional quantity arguments\r\n# add name and quantity to hash\r\n list[name] = quantity\r\n# output: print \"your item has been added to the hash\"\r\n return list\r\nend",
"def create_list(list)\n quantity = 1\n items = list.split(' ')\n grocery_list = { }\n\n items.each do |item|\n grocery_list[item] = quantity\n end\n grocery_list\nend",
"def print_list(list)\n# input:list\n# steps: iterate through the list\n list.each do |item, number|\n puts \"we have #{number} #{item}\"\n end\n puts \"in our grocery list\"\nend",
"def create_list(grocery_items)\n grocery_list = {}\n grocery_items = grocery_items.split(\" \")\n grocery_items.each do |item| \n grocery_list.store(item, 1)\n end\n puts \"This is your grocery list:\"\n print_list(grocery_list)\n return grocery_list\nend",
"def grocery_list(items)\n\t#items string into an array\n\t#create hash named LIST \n\t#LIST << items[0]\n\t#LIST[:carrots] = 2\n\n\titem_array = items.split(\" \")\n\tfood_list = {}\n\t\n\n\titem_array.each do |fooditem|\n\t\tfood_list[fooditem] = 2\n\tend\n\n\tfood_list\n\t# p food_list\n\nend",
"def add_item(list, item_name, optional_quantity)\n\nlist[item_name] = optional_quantity\n\n# input: list, item name, and optional quantity\n# steps:\n # Add new hash key based on item name\n # Tell method there may or may not be a argument passed in for quantity\n # assign quantity to 'optional-quantity' argument in method definition\n # Access method that contains initialized hash def add_item(create_list, item_name, quantity = 3)\n# output:\n # updated grocery list\nend",
"def create_list(items, qty=1)\n items = items.split(\" \")\n list = Hash.new\n\n items.each do |item|\n if list.has_key?(item)\n list[item] += qty\n elsif\n list[item] = qty\n end\n end\n\n return list.each {|k,v| puts \"#{k}: #{v}\"}\nend",
"def create_list(items)\n grocery_list = {}\n item_array = items.split(\" \")\n item_array.each do |item|\n grocery_list[item] = 1\n end\n print_list(grocery_list)\n grocery_list\nend",
"def printlist(list)\r\n# input: shopping list\r\n# steps:\r\nlist.each {|item, quantity| puts \"Please buy #{quantity} #{item}\"}\r\n # Print each item on the shopping list in a readable fashion\r\nend",
"def grocery_list(items)\n #method for create list\n array = items.split(\" \")\n #separate by spaces TEST\n #p grocery_array\n #test print\n hash = {}\n #empty hash\n array.each {|item| hash[item] = 1}\n #ends hash\n hash\n #test hash\nend",
"def create_list(string)\n list = string.split(' ')\n qty = 1\n grocery_list = {}\n list.each { |item| grocery_list[item] = qty }\n grocery_list\nend",
"def create_list(string_of_items)\n string_ary = string_of_items.split(\" \")\n string_hash = {}\n string_ary.each { |item| string_hash[item] = 1 }\n print_grocery_list(string_hash)\n return string_hash\nend",
"def list_maker(items, *quantities)\r\n list_hash = {}\r\n list_array = items.split(' ')\r\n for i in 0..(list_array.length - 1)\r\n list_hash[list_array[i]] = quantities[i]\r\n end\r\n list_hash.map do |item, quantity|\r\n if quantity == nil \r\n list_hash[item] = 1 \r\n end\r\n end\r\n list_hash\r\nend",
"def add_item(grocery,item_name,quantity)\n # input: list, item name, and optional quantity\n # steps: insert item_name as a key and quantity as a value to the hash \n grocery[item_name] = quantity\n # output:display the latest list\n display_list(grocery)\nend",
"def update_quanity(list, item, quantity)\r\n# input: list, item and quantity to be updated to\r\n# steps:\r\n # check if item exists\r\n # update quantity\r\n list[item] = quantity\r\n # print success \"your cart has been updated!\"\r\n puts \"The quantity for #{item.upcase} has been updated in your grocery list!\"\r\n p list\r\n# output: updated list with new quantity\r\nend",
"def create_list(items_str)\r\n items_hash={}\r\n items_array=items_str.split(\" \")\r\n items_array.each do |it|\r\n items_hash[it]=1\r\n end\r\n print_list(items_hash)\r\nend",
"def make_list(item_string = \"\")\r\n grocery_list = {}\r\n=begin\r\n items_array = item_string.split(\" \")\r\n #puts items_array\r\n\r\n items_array.each do |shopping_item|\r\n grocery_list[shopping_item] = 1\r\n end\r\n=end\r\n grocery_list = Hash[item_string.split(\" \").map {|item| [item, 1]}] \r\n #I think this is less readable, but i wanted to find another way to do it\r\n #puts grocery_list\r\n return grocery_list \r\nend",
"def create_list(items)\r\n\tgrocery_list = {}\r\n\tlist_of_items = items.split(' ')\r\n\r\n\tlist_of_items.each { |item| grocery_list[item] = 1}\r\n\tgrocery_list.each {|item, quantity| puts item, quantity}\r\nend",
"def list_creation(items_string)\r\n\tshopping_list = {}\r\n\tintit_list = items_string.split(' ')\r\n\tintit_list.each do|item|\r\n\t\tshopping_list[item] = 1\r\n\tend\r\n\tshopping_list\r\nend",
"def create_list(string)\n item_array = string.split(\" \")\n shopping_list = {}\n item_array.each do |item|\n shopping_list[item] = 1\n end\n list_print(shopping_list)\n shopping_list\nend",
"def creation_list (user_input)\r\n grocery_list = {}\r\n user_input_array = user_input.split(' ')\r\n user_input_array.each do |list_item|\r\n grocery_list[list_item] = 1\r\n end\r\n grocery_list\r\nend",
"def create_list(items)\n\tlist = {}\n\titems = items.split(' ')\n\tquantity = 0\n\tlist = Hash.new\n\n\titems.each do |item| \n\t\tlist[item] = quantity\n\tend\n\tlist\nend",
"def grocery_list(items)\n list = {}\n items.split.each do |item, quantity|\n list[item] = 0\n end\n p list\nend",
"def create_list\n item_array = []\n puts \"Enter items, type done when finished\"\n item = gets.chomp\n while item != \"done\"\n \titem_array << item\n \titem = gets.chomp\n end\n grocery_list = {}\n item_array.each { |item| grocery_list[item.to_sym] = 1 }\n puts grocery_list\n grocery_list\nend",
"def create_hash(items, default_qty = 0)\n groceries = {}\n items.split.each { |food| groceries[food] = default_qty }\n groceries \nend",
"def create_list(items)\n grocery_list = Hash.new(0) #other method is only local in grocery_list\n food_array = items.split(\" \")\n food_array.each{|food| grocery_list[food] = 1}\n grocery_list\nend",
"def create_list(item)\n list = {}\n new_item = item.split(\" \")\n \n new_item.each do |food|\n list[food] = 0\n end\n return list\nend",
"def create_list(item, quantity = 1)\n\tlist = {}\n\tsplit_item = item.split(\" \")\n\tsplit_item.each do |item_name|\n\t\tlist[item_name] = quantity\n\tend\n\treturn list\nend",
"def print(list)\n# steps: \n\t# make a new string\n\tstring = \"This is the shopping list: \\n\"\n\t# iterate through the list\n\tlist.each do |item, quantity|\n\t\t# add the items and quantities to the string and end with a newline\n\t\tstring = string + \"#{item}: #{quantity} \\n\"\n\tend\n# output: the string\n\tputs string\nend",
"def update_item(list, item, quantity)\r\n add_item(list, item, quantity)\r\n# input: Shopping list, item to be updated, new quantity\r\n# steps:\r\n # Use shopping list as input\r\n # Use item to be updated as input\r\n # Use new quantity to be updated as input\r\n # Update the quantity of the item on the list\r\n # list[item] = quantity\r\n# output: shopping list with updated quantity\r\n # printlist(list)\r\nend",
"def new_list(item_String, quantity = 1)\n $list = []\n array_strings = item_String.split\n array_strings.each do |element|\n \tlist_item = {\n \t\tquantity: quantity,\n \t\titem: element\n \t}\n \t $list.push(list_item) \n \tend\nend",
"def create_list(items_string)\n list = {}\n items_array = items_string.split(\",\")\n\n items_array.each do |item|\n list[item] = 1\n end\n print_pretty_list(list)\nend",
"def shopping_list(user_input)\r\n grocery_list = {}\r\n list = user_input.split(\" \")\r\n list.each do |item|\r\n grocery_list[item] = 1\r\n end\r\n p grocery_list\r\nend",
"def create_list(groceries)\n shopping_list = {}\n grocery_array = groceries.split(\" \")\n grocery_array.each do | item |\n add_item(item, 1, shopping_list)\n end\n print_list(shopping_list)\nend",
"def create_list(list)\n grocery_list = {}\n list.split(\" \").each do |item|\n grocery_list[item] = 1\n end\n p grocery_list #will later add the last method to this line\nend",
"def create_list(list)\n grocery_list = {}\n list.split(\" \").each do |item|\n grocery_list[item] = 1\n end\n p grocery_list #will later add the last method to this line\nend",
"def create_a_list(name, quantity)\n #list = name.split(\", \")\n list_items = {}\n #list.each do |name|\n list_items[name] = quantity\n #end\n p list_items\n return list_items\nend",
"def input (list, item, quantity)\n\tlist[item] = quantity\nend",
"def print_list(title,list)\n# steps:\n # print title of list (will ask user for this input)\n puts \"**********************\"\n puts \" #{title.upcase}:\"\n puts \"**********************\"\n # print headers of item and quantity\n puts \" # ITEM\"\n puts \"----------------------\"\n # print each item and it's quantity, bulleted if possible\n list.each {|item,quantity| puts \" #{quantity} #{item}\"}\n puts \"**********************\"\n # print today's date\n date = Time.new\n puts \" Made on: #{date.month}/#{date.day}/#{date.year}\"\nend",
"def print_list(food_list)\n food_list.each do |item_name, quantity|\n puts \"You have the following item #{item_name}, qty: #{quantity}.\"\n end\nend",
"def create_list_of(string_of_items)\n\tary_of_items = string_of_items.split(' ')\n\titem_list = {}\n\tary_of_items.each {|x| item_list[x] = 1}\n\tprint_list(item_list)\nend",
"def create_list(items)\n grocery_list = {}\n list_items = items.split\n list_items.each do |item|\n grocery_list[item] = 1\n end\n p print_list(grocery_list)\n end",
"def print_grocery_list(grocery_list)\n # steps: print \"Grocery List\"\n puts \"Grocery List:\"\n # for each item, print \"item name: quantity\"\n grocery_list.each do |item_name, quantity|\n puts \"#{item_name.to_s}: #{quantity}\"\n # output:\n end\nend",
"def print_list(list)\r\n # steps:\r\n # use each method to print the following: \"You have #{quantity} #{item_name}\"\r\n list.each do |name, quantity|\r\n puts \"You have #{quantity} of #{name}!\"\r\n end\r\n # output: -no output-\r\nend",
"def new_grocery_list(items)\n items_array = items.split\n grocery_hash = {}\n \n items_array.each do |item|\n grocery_hash[item] = 1\n end\n \n print_list(grocery_hash)\n \n \nend",
"def create_list(items)\r\n items_array = items.split(' ')\r\n grocery_hash = {}\r\n items_array.each do |item|\r\n add_item(grocery_hash, item)\r\n #grocery_hash[item] = 1\r\n end\r\n grocery_hash\r\nend",
"def create_list(items)\n items = items.split(' ')\n grocery_list = {}\n items.each do |item|\n grocery_list[item] = 1\n end\n p grocery_list\n grocery_list\nend",
"def add_to_grocery_list(grocery_list, item_name, quantity=1)\n # steps: add item to hash and set quantity\n grocery_list[item_name.to_sym] = quantity\n # output: explicit return updated hash\n grocery_list\nend",
"def create_list(groceries)\n default_qty = 1\n grocery_list = {}\n groceries.split(\" \").each {|grocery| grocery_list[grocery] = default_qty}\n #pretty_print(grocery_list)\n grocery_list\nend",
"def lets_go_shopping\r\n\r\n current_list = new_grocery_list\r\n add_new_item(current_list)\r\n remove_an_item(current_list)\r\n update_item_quantity(current_list)\r\n \r\n current_list.each do |key, value|\r\n puts \"Food: #{key}\"\r\n puts \"Qty: #{value}\" \r\n end\r\nend",
"def create_list(items)\n\n# Make an empty hash for grocery_list:\np grocery_list = {} \n\n \n# Takes the string of items that user puts in the create_list method, and turns it into an array:\np items = items.split\n\n# Iterate through each item in the array. This step turns the array into a hash buy asking if it has an item from the array as a key. If the item appears more than once in the array, it will count it as one key and give it a value of +1.\n items.each do | item |\n if grocery_list.has_key?(item)\n grocery_list[item] += 1\n else\n grocery_list[item] = 1\n end \n\n end\n grocery_list \nend",
"def add_item(list, food_item, quantity_of_food = 1)\n list[food_item] = quantity_of_food\n list\nend",
"def grocery_list(items)\n hash = Hash.new\n default = 1\n items.split(' ').each { |item|\n hash[item] = default }\n hash\nend",
"def create_list(item_string)\r\n items = item_string.split\r\n grocery_list = {}\r\n items.each do |item|\r\n grocery_list[item] = 1\r\n end\r\n grocery_list\r\nend",
"def create_list(items=\"\")\n grocery_list = Hash.new()\n list = items.split(\" \")\n list.each {|item| grocery_list[item] = 1 }\n grocery_list\nend",
"def createlist(items)\n new_items = items.split(\" \")\n list = Hash.new\n new_items.each {|item| list[item] = 1}\n prettylist(list)\n # use print_list method\nend",
"def new_grocery_list\r\n puts \"Enter items: \"\r\n initial_items = gets.chomp\r\n items = initial_items.split(\", \")\r\n\r\n my_grocery_list = {}\r\n \r\n items.each do |item|\r\n my_grocery_list[item] = 1\r\n end\r\n \r\n my_grocery_list\r\nend",
"def create_grocery_list(list, item_list)\n items = item_list.split\n items.each do |item|\n list.store(item, 1)\n end\n return list\n print_list(grocery_list)\nend",
"def make_grocery_list(items)\n grocery_list = {}\n grocery_item = items.split\n grocery_item.each do |i|\n grocery_list[i] = 1\n end\n print_list(grocery_list)\nend",
"def create_list(string, value=1)\n string.split(\" \").each do |item|\n $grocery_list[item] = value\n end\n # puts \"Initial list created:\"\n $grocery_list\nend",
"def make_list(grocery_string)\n groceries = Hash.new(1)\n grocery_array = grocery_string.split(\" \")\n grocery_array.each do |item|\n groceries[item] = 1\n end\n #print with whatever method we choose later on\n print_list(groceries)\n return groceries\nend",
"def create_list(items)\n item_list = items.split(' ')\n grocery_list = {} \n item_list.each do |item|\n grocery_list[item] = 1\n end\n grocery_list \nend"
] | [
"0.8018821",
"0.7789958",
"0.7782452",
"0.7751206",
"0.76809716",
"0.7590905",
"0.7558388",
"0.7521826",
"0.74911404",
"0.7400093",
"0.7395199",
"0.73887795",
"0.73873955",
"0.7338917",
"0.7330641",
"0.7198168",
"0.7170075",
"0.71476734",
"0.7140248",
"0.7133668",
"0.7127238",
"0.7125704",
"0.712443",
"0.7107354",
"0.7107228",
"0.71006894",
"0.7092889",
"0.7082923",
"0.70663905",
"0.70400393",
"0.70294166",
"0.70100224",
"0.700111",
"0.69826937",
"0.6953161",
"0.69432485",
"0.693371",
"0.69039917",
"0.68980485",
"0.68975866",
"0.68893504",
"0.68631554",
"0.6854089",
"0.6834974",
"0.68231964",
"0.68210596",
"0.6810588",
"0.681051",
"0.6788725",
"0.6752115",
"0.6745509",
"0.6739433",
"0.6731352",
"0.6731239",
"0.67306113",
"0.671902",
"0.67185193",
"0.6718151",
"0.6709744",
"0.66907257",
"0.6676156",
"0.6659995",
"0.66594404",
"0.66558397",
"0.665532",
"0.6643549",
"0.66387564",
"0.6638315",
"0.6636968",
"0.66233534",
"0.66191745",
"0.66163766",
"0.661608",
"0.66101265",
"0.66101265",
"0.6605449",
"0.65972",
"0.65968424",
"0.6594482",
"0.6587195",
"0.6581513",
"0.6573751",
"0.65723974",
"0.655932",
"0.65559584",
"0.6550419",
"0.6540049",
"0.65334773",
"0.65298337",
"0.65187025",
"0.65052503",
"0.6483106",
"0.64814955",
"0.6467672",
"0.64565974",
"0.6455872",
"0.64449763",
"0.6444498",
"0.6419091",
"0.64119565",
"0.6411953"
] | 0.0 | -1 |
Method to add an item to a list input: item name and optional quantity steps: create add_item method, add items to list output: new item with quantiy | def add_item(list, item, quant)
list[item] = quant
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def add_item(list, item_name, quantity = 1)\n\tlist[item_name] = quantity\n\tlist\nend",
"def add_item(list, item_name, quantity = 1)\n\tlist[item_name] = quantity\n\tlist\nend",
"def add_item(list, item_name, quantity = 1)\n\tlist[item_name] = quantity\n\tlist\nend",
"def add_item(list, item_name, quantity)\n\tlist[item_name] = quantity\n\tlist\nend",
"def add_item(list, item_name, quantity)\n\tlist[item_name] = quantity\n\tlist\nend",
"def add_item(list, item, quantity=1)\r\n# input: item name and optional quantity\r\n# steps: \r\n # Use shopping list as input\r\n # Use the item to be added as 2nd input\r\n # Use the item quantity as a 3rd input (look up whether optional input is possible)\r\n # Add the item and quantity to the shopping list\r\n list[item] = quantity\r\n# output: shopping list with the added item and quantity\r\n printlist(list)\r\nend",
"def add_item(list, name, quantity = 1) \r\n# input: item name and optional quantity\r\n# steps: \r\n# create add method with name and optional quantity arguments\r\n# add name and quantity to hash\r\n list[name] = quantity\r\n# output: print \"your item has been added to the hash\"\r\n return list\r\nend",
"def add_item(list, item, quantity = 1)\r\n# input: list, item name, and optional quantity\r\n# steps: \r\n # check for optional quantity. if not present, set to default (1)\r\n list[item] = quantity\r\n # update list with input\r\n puts \"#{item.upcase} has been added to your grocery list!\"\r\n p list\r\n# output: complete list, updated\r\nend",
"def add(list, item_name, quantity)\n\tlist[item_name] = quantity\n\tlist\nend",
"def add_item(list, add_item, add_quantity=1)\n# steps:\n # Add item as key and quantity as value to final_list hash(item and quantity will be user inputs)\n list[add_item] = add_quantity\n # Return updated hash\n list\nend",
"def add_item(item, quantity, list)\n\tlist[item] = quantity\n\titem\nend",
"def add_item(list_name, item, quantity=1)\r\n# input: list, item name, and optional quantity\r\n# steps: add item and its quantity to the hash\r\n list_name.store(item, quantity)\r\n# output: hash with new item\r\n p list_name\r\nend",
"def add_to_list(list,item,quantity)\n\tupdate_item(list,item,quantity)\nend",
"def add_item(list, item, quantity=0)\n\tlist[item] = quantity\n\tlist\nend",
"def additem(list, item, number = 1)\n# input: hash, item name and optional quantity\n# steps: push an item into the hash\n list.store(item, number)\nend",
"def add_items(list, item_name, quantity=0)\r\n\tlist[item_name] = quantity\r\n\tlist\r\nend",
"def add_new_items(list, item_name, quantity=1)\n list[item_name] = quantity\n list\nend",
"def add_item(list, item, quantity)\n\n\tlist[item] = quantity\n\tlist\n\nend",
"def update_quantity(item, list, quantity)\n add_item(item, list, quantity)\nend",
"def add_item(list, item_name, quantity=1)\n list[item_name] = quantity\nend",
"def add_item(new_list, item_name, quantity=1)\r\n \r\n new_list[item_name] = quantity\r\n \r\nend",
"def add_item (list, item, quantity = 1)\n\tlist[item] = quantity\n\treturn list\nend",
"def add_list(item_name, item_list, quantity = 1)\n item_list[item_name] = quantity\nend",
"def add_item(item, quant=0)\n\t$grocery_list.store(item, quant)\n\tp \"You added #{item} to your list.\"\nend",
"def add_item(item_list, item, qty)\r\n item_list[item] = qty\r\n item_list\r\nend",
"def add_item(item, quantity, list)\n\t# steps: \n\t# if the item is already in the list\n\tif list[item.to_sym] \n\t\t# add to the quantity\n\t\t#list[item.to_sym] = list[item.to_sym] + quantity\n\t\tlist[item.to_sym] += quantity\n\t# otherwise\n\telse\n\t\t# make a new key with the input quantity\n\t\tlist[item.to_sym] = quantity\n\tend\n\t# output:\n\t\t# updated list\n\tlist\nend",
"def add_item(current_list, item_added, quantity)\n current_list[item_added] = quantity\n current_list\nend",
"def add_item_to_list(list_name,item_to_add,quantity_to_add = 1)\n#create a hash element with the item name and the quantity, if specified\n#if no quantity is specified, default value = 1\n new_item = { \n item_name: item_to_add,\n quantity: quantity_to_add\n }\n# insert the hash into array \n list_name.push(new_item)\n new_item\nend",
"def add_item(list,item_name, qty)\n list[item_name] = qty\nend",
"def update_list(item_name, item_list, quantity)\n add_list(item_name, item_list, quantity)\nend",
"def add_item(list, item_name, quantity = 1)\r\n list[item_name] = quantity\r\nend",
"def add_item(item_name, price, quantity = 1)\n @transactions << Transaction.new(item_name, price, quantity)\n quantity.times{self.items << item_name}\n self.total += price*quantity\n end",
"def update(list, item, qty)\n add_item(list, item, qty)\nend",
"def add_item(list, item, quantity)\n\tlist[item] = quantity\n\tp list\nend",
"def update_quantity_of_item(list,item,quantity)\r\n add_item_to_list(list,item,quantity)\r\n list\r\nend",
"def add_item(list, item, quantity=0)\n list[item] = quantity\n list\nend",
"def add_item(item, price, *quantity)\n q = quantity.join(\"\").to_i\n if q > 1\n q.times do\n @items.push(item)\n end\n else\n @items.push(item)\n end\n if q > 1\n price_with_quantity = q * price\n @last = price_with_quantity\n @total += price_with_quantity\n else\n @last = price\n @total += price\n end\n\n end",
"def add_item(list, item_name_string, quantity=1)\r\n\titem_key = item_name_string.to_sym\r\n\tlist[item_key] = quantity\r\n\treturn list\r\nend",
"def add_item(list, item_name, quantity)\n list[item_name.to_sym] = quantity\n list \nend",
"def add_item(item,quantity,list)\n\tlist[item] = quantity\nend",
"def add_item(name, price, quantity = 1)\n self.total += price * quantity\n quantity.times {self.items << name}\n record_trans(name, price, quantity)\n end",
"def add_item(title, price, quantity=1) \n self.total += price * quantity\n quantity.times do\n items << title \n end\n self.last_transaction = price * quantity\n\n end",
"def add_item(item,amount=1,the_lists)\r\n\t# steps: accept 2 arguments. Item name and Quantity (with default)\r\n\tif the_lists[item] != nil\r\n\t puts \"Item is already on the List !\"\r\n\t puts \"Added amount to the quantity\"\r\n\t the_lists[item] += amount\r\n\telse\r\n the_lists[item] = amount\r\n\tend\r\n\r\n\tprint_list(the_lists)\r\nend",
"def add_item(list, new_item, quantity=1)\n list[new_item] = quantity \nend",
"def add(input_list, item, quantity)\n input_list[item] = quantity\nend",
"def list_add(hash_items, item_name, quantity = 1)\n hash_items [item_name] = quantity\n return hash_items\nend",
"def add_item(list, new_item, qty=1)\n list[new_item] = qty\nend",
"def add_item(list, item, quantity)\n list[item] = quantity\n list\nend",
"def add_item(list, item_name, optional_quantity)\n\nlist[item_name] = optional_quantity\n\n# input: list, item name, and optional quantity\n# steps:\n # Add new hash key based on item name\n # Tell method there may or may not be a argument passed in for quantity\n # assign quantity to 'optional-quantity' argument in method definition\n # Access method that contains initialized hash def add_item(create_list, item_name, quantity = 3)\n# output:\n # updated grocery list\nend",
"def add_item(string, float, integer = 1)\n # adds item price to total\n @total += float * integer\n # accepts an optional quantity of the item\n quantity = integer\n # loops to add item multiple times to the list \n quantity.times {@items << string}\n # holds the amount of the last transaction\n self.last_transaction = float * quantity\n end",
"def add_item(list, item, quantity = 1)\n list[item] = quantity\n list\nend",
"def add_item(item_name, grocery_list, quantity=1)\n grocery_list[item_name] = quantity\n grocery_list\n end",
"def add_item(title, p, q=1) # accepts a title and a price AND inc. the total. Optional quantity set to 1 since u will always have at least one item.\n @total += (p*q) # @ total is price times quantity, and increments (does not forget previous total as u add new items)\n q.times do # want to add the item as many times to the list as its quantity so keep doing this the # of times its quantity is\n @items << title\n end\n @last_transaction = p # the last transaction = the price of the last item added\n end",
"def add_item(title, amount, quantity=1)\n self.total += amount * quantity\n quantity.times do\n items << title\n end\n self.last_transaction = amount * quantity\n end",
"def add_item(grocery_list, item_name, quantity=1)\n\tgrocery_list[item_name] = quantity\n\treturn grocery_list\nend",
"def add_item(list, item, qty)\n list[item] = qty\n list\nend",
"def add_item(list, item, qty=nil, print=true)\n\t# input: \n\t# existing list, \n\t# item name (string), \n\t# quantity qty (int or string or nil(default)), \n\t# print? (t(default)/f)\n\t# output: updated list (array)\n\t\n\t# format list item \n\tif qty\n\t\tqty = qty.to_s\n\tend\n\titem = [item.strip.capitalize, qty]\n\t# append to list\n\tlist = list.push(item)\n\t# print list if print=true\n\tif print\n\t\tputs \"\\n\\nList updated: added item '#{item}'\\n\"\n\t\tprint_list(list)\n\tend\n\treturn list\nend",
"def add_item(shopping_list, item, quantity=1)\r\n\r\n\tshopping_list[item] = quantity\r\n#\treturn shopping_list\r\nend",
"def update_item(list, item, quantity)\r\n add_item(list, item, quantity)\r\n# input: Shopping list, item to be updated, new quantity\r\n# steps:\r\n # Use shopping list as input\r\n # Use item to be updated as input\r\n # Use new quantity to be updated as input\r\n # Update the quantity of the item on the list\r\n # list[item] = quantity\r\n# output: shopping list with updated quantity\r\n # printlist(list)\r\nend",
"def add_item(existing_list, new_item, item_integer)\n\t# input: item name and optional quantity\n\t# steps: pass in item name as key and assign value\n\texisting_list[new_item] = item_integer\n\t# output: hash\n\tp existing_list\nend",
"def add_item(list, item, quantity)\n #list = item.push\n list[item] = quantity.to_i\n list\nend",
"def add_item(item, list, quantity)\n list[item] = quantity\nend",
"def add_item(list, item, quantity)\n list[item] = quantity\n return list\nend",
"def add_item\n\t puts \"What is the name of the item you'd like to add?\"\n\t\t@item_name = gets.chomp\n\t\tputs \"And how many?\"\n\t\t@quantity = gets.chomp.to_i\n\t\tif @quantity <= 0\n\t\t puts \"Please enter a number higher than 0.\"\n\t\t puts \"(Also, must be '1' not 'one'.)\"\n\t\telse\n\t\t @grocery_list[@item_name] = @quantity\n\t\tend\n\t\tget_item\n\tend",
"def add_item(item, amount, quantity = 1)\n\n if quantity > 1\n self.total += (amount * quantity)\n quantity.times do \n @items << item\n end\n else\n self.total += amount\n @items << item\n end\n @last_amount = amount * quantity\n end",
"def add_item(title, price, quantity = 1)\n @title = title\n @price = price\n quantity.times {@items << title}\n @last_transaction = @price * quantity\n @total = @total + (@price * quantity)\n @total\n end",
"def add_item(list, item, qty = 1)\n list[item] = qty\n return list\nend",
"def add_item(grocery_list, item_name, qty = 1)\n\tgrocery_list[item_name] = qty\n\treturn grocery_list\nend",
"def add_item(item, price, quantity=1)\n @total += (price * quantity)\n @items.fill(item, @items.size, quantity)\n @last_transaction = {item => (price * quantity)}\n @last_qty = quantity\n end",
"def add_item(item, quantity = 1)\n order_item = self.order_items.find_by item: item, price: item.price\n if order_item.is_a? OrderItem\n order_item.add quantity\n else\n self.order_items.create item: item, price: item.price, quantity: quantity\n end\n recalculate!\n end",
"def updating_item(list,item,quantity)\r\n\r\n adding_item(list,item, quantity)\r\n\r\nend",
"def add_item(title, price, quantity=1)\n #and increases the total\n self.total += price * quantity\n #times.do for all the items\n quantity.times do\n @items << title\n end\n #doesn't forget about the previous total\n self.last_transaction = price * quantity\n end",
"def add_item(title, price, quantity=1)\n self.total += price * quantity\n #quantity amount of times it'll add the title to the items array\n quantity.times {items << title}\n self.last_transaction = price * quantity\n end",
"def add(list, item, quantity)\r\n\tlist[item] = quantity\r\n\tlist\r\nend",
"def add_item(list, item, qty = 1)\n list[item] = qty\n\n list\nend",
"def list_add(list, item_name, quantity=1)\n list[item_name] = quantity\n p list\nend",
"def add_item(list,item,quantity=1)\r\n list[item] = quantity\r\n list\r\nend",
"def update_quantity(list, item, quantity)\n\tadd_to_list(list, item, quantity)\nend",
"def add_item(list,name,quantity=1)\n list[name]=quantity\n return list\nend",
"def add_item!(list, item, qty=1)\r\n list[item] = qty\r\n list\r\nend",
"def add_item(name, quantity, list)\n list[name] = quantity\n p list\n return list\nend",
"def add_item(list, item, quantity=1)\n list[item] = quantity\nend",
"def add_to_list(list, item, quantity)\n #method to add items\n list[item] = quantity\nend",
"def add_item(list, item, qty=1)\n list[item] = qty\n p \"#{item} : #{list[item]}\"\nend",
"def add_item(list, item, quantity=1)\r\n\tlist[item] = quantity\r\n#\tp list\r\nend",
"def add_item (title, price, quantity = 1)\n i = 0\n while i < quantity\n @items << title\n i += 1\n end\n my_price = price * quantity\n @transactions << my_price\n @total += (price * quantity)\n end",
"def add_item(grocery_list, item_name, qty = 1)\r\n\tgrocery_list[item_name] = qty\r\n\treturn grocery_list\r\nend",
"def add_item(list, item, quantity)\n list[item] = quantity\nend",
"def add_item(list, item, quantity)\n list[item] = quantity\nend",
"def add_item_to_list(grocery_list, grocery_item, quantity = 1)\n grocery_list.store(grocery_item,quantity)\n puts \"I've added #{grocery_item} to the list. Please pick up #{quantity} of these.\"\nend",
"def add_item(title, price, quantity = 1)\n @total += price*quantity\n @instance_items << [title, price, quantity]\nend",
"def add_item(list, item, quantity=1)\n list[item] = quantity\n p list\nend",
"def add_to_list(list, item, quantity = 1)\n\tlist[item] = quantity\nend",
"def add_item(my_list, item, quantity)\r\n #input: a string seperated by an integer \r\n #steps: use a method that adds an item and quantity to the hash.\r\n my_list.store(item, quantity)\r\n # use a hash or store method hash.merge!(key => value) \r\n #output = hash with the updated item/quantity. \r\n my_list\r\n \r\nend",
"def add_item(list,item,quantity=1)\n list[item] = quantity\nend",
"def add_item(list,item,quantity=1)\n list[item] = quantity\nend",
"def add_item(item)\n\t\t#takes in item and adds to list\n\t\t@list << item\n\tend",
"def add_item(new_item)\n item = Item.new(new_item)\n items.push(item)\n end",
"def add_item(shopping_list, item, quantity)\r\n\tshopping_list[item] = quantity\r\n\tshopping_list\r\nend",
"def add_item(item, price, quantity = 1)\n @total += price * quantity\n @transactions << price * quantity\n i = quantity\n until i == 0 do\n @items << item\n i -= 1\n end\n end",
"def add_item(item)\r\n @list << item \r\n end"
] | [
"0.8221033",
"0.8221033",
"0.8220495",
"0.8195609",
"0.8195609",
"0.8170519",
"0.8040089",
"0.80394185",
"0.80090946",
"0.79906535",
"0.79727846",
"0.79109496",
"0.788369",
"0.78822744",
"0.7871026",
"0.7856891",
"0.77859944",
"0.7764603",
"0.7728242",
"0.77267337",
"0.76904684",
"0.7683866",
"0.76817566",
"0.7676126",
"0.7654491",
"0.76424277",
"0.76384294",
"0.7618222",
"0.7615606",
"0.7611933",
"0.75773853",
"0.7564358",
"0.7561034",
"0.75398105",
"0.7538053",
"0.7535464",
"0.75327593",
"0.75223166",
"0.75220644",
"0.75131124",
"0.7504036",
"0.75039685",
"0.75030494",
"0.75023115",
"0.74936503",
"0.7480351",
"0.74697393",
"0.7446993",
"0.74433154",
"0.74325097",
"0.74315315",
"0.74275285",
"0.7425084",
"0.7420967",
"0.7419541",
"0.7411594",
"0.7411052",
"0.7405698",
"0.74031025",
"0.74026495",
"0.7398698",
"0.73891485",
"0.7380544",
"0.7371968",
"0.7369992",
"0.7366787",
"0.7365102",
"0.73609954",
"0.7352529",
"0.7350997",
"0.7348752",
"0.7347429",
"0.73459816",
"0.7339557",
"0.7337206",
"0.73357326",
"0.73355615",
"0.73353124",
"0.7335212",
"0.7333082",
"0.7330128",
"0.7318624",
"0.73165256",
"0.7311085",
"0.7299271",
"0.7297823",
"0.72830635",
"0.7281916",
"0.7281916",
"0.7269728",
"0.72659457",
"0.7259203",
"0.72588384",
"0.7258508",
"0.7256497",
"0.7256497",
"0.72505915",
"0.7249665",
"0.72484267",
"0.72439",
"0.72364855"
] | 0.0 | -1 |
p add_item("item", 1) Method to remove an item from the list input: item to delete steps: using hash delete method to remove an item output: new list without the items that were removed | def delete_item(list, item)
del_list = list.delete(item)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def remove_item(my_list, item)\r\n# input: an item (something already in the list)\r\n# steps:\r\n my_list.delete(item)\r\n \r\n my_list\r\n# declare hash\r\n# delete method for item\r\n# output: hash with removed item\r\nend",
"def remove_item(new_list, item)\n \n new_list.delete(item)\n \n new_list\nend",
"def remove_item(list, rm_item)\n# steps:\n # use delete method with key (item) as argument\n list.delete(rm_item)\n # return list\n list\nend",
"def remove_item(list, item)\r\n# input: item to be removed, list\r\n# steps: \r\n # check if item exists\r\n # remove item\r\n list.delete(item)\r\n # print success message of item removed\r\n puts \"#{item.upcase} has been removed to your grocery list!\"\r\n p list\r\n# output: updated list\r\nend",
"def remove_item(item_list, item)\r\n item_list.delete(item)\r\n item_list\r\nend",
"def remove_item(list, item)\r\n# input: shopping list and item to be removed\r\n# steps: \r\n # Use shopping list as input\r\n # Use item to be removed as input\r\n # Remove the item from the list if it exists on the list\r\n list.delete(item)\r\n# output: shopping list with item removed\r\n printlist(list)\r\nend",
"def remove_item(input_hash, item)\n# input: list, item name, and optional quantity\n# steps: use input item to delete key\n input_hash.delete(item)\n# output: hash data structure of key/value pairs\nreturn input_hash\nend",
"def remove_item(list, item)\n\tlist.delete(item)\n\tlist\nend",
"def remove_item(item, list)\n\t# steps: delete the item if it exists\n\tlist.delete_if {|list_item| list_item == item.to_sym}\n\t# output: updated list\n\tlist\nend",
"def remove_item(list, item)\r\n list.delete(item)\r\n list\r\nend",
"def remove_item(list,item)\r\n\r\n list.delete(item)\r\n list\r\nend",
"def remove_item(list, item_removed)\n list.delete(item_removed)\nend",
"def remove_item(list,item)\n\tlist.delete(item)\n\tp list\nend",
"def remove_item (list, item)\n list.delete(item)\nend",
"def remove_item(new_list, item_name)\r\n new_list.delete(item_name)\r\nend",
"def remove_item(list, item)\n list.delete(item)\n list\nend",
"def remove_item(list, item)\n list.delete(item)\n list\nend",
"def remove_item(list, item)\n list.delete(item)\n list\nend",
"def remove_item(list, item)\n list.delete(item)\n list\nend",
"def remove_item(list, item)\r\n\tlist.delete(item)\r\n\treturn list\r\nend",
"def remove_item (item, list)\n list.delete(item)\n return list\nend",
"def remove_item(list, item)\n list.delete(item)\n list\nend",
"def remove_item(list, item)\n list.delete(item)\n list\nend",
"def remove_item(list, item)\n list.delete(item)\n list\nend",
"def remove_item(item, list)\n list.delete(item)\n return list\nend",
"def remove_item(list, item)\n list.delete(item)\n return list\nend",
"def remove_item(list,item)\n\tlist.delete(item)\nend",
"def delete_item(list, item)\n\tlist.delete(item)\n\tlist\nend",
"def remove_item(list, item)\n list.delete(item)\n return list\nend",
"def remove_item(item, list)\n list.delete(item)\nend",
"def remove_item (item,list)\nlist.delete(item)\nlist\nend",
"def remove_item(list, item)\n\tlist.delete(item)\nend",
"def remove_item(list, item_name)\r\n list.delete(item_name)\r\n list\r\nend",
"def remove_item (list, item)\n list.delete(item)\nend",
"def remove_item(list, item)\n list.delete(item)\n p list\nend",
"def remove_item(list, item)\n list.delete(item)\n p list\nend",
"def remove_item(list, item)\n list.delete(item)\n p list\nend",
"def delitem(list, item)\n# input: list and key\n list.delete(item)\n# steps: delete a given key item\nend",
"def remove_item(list_name, item)\r\n# input: list, item name\r\n# steps: delete item name and value from hash\r\n list_name.delete(item)\r\n# output: updated hash with item removed\r\np list_name\r\nend",
"def remove(input_list, item)\n input_list.delete(item)\nend",
"def delete_item(list, item)\n\tlist.delete(item)\n\treturn list\nend",
"def delete_item(item)\n\t\t#takes in an item and returns a new list\n\t\t@list.delete(item)\n\t\treturn @list\n\tend",
"def remove_item(list,item)\n list.delete(item)\n p list\nend",
"def remove_item(list, item_name)\n list.delete(item_name)\n list\nend",
"def remove_item(list, item)\n list.delete(item)\nend",
"def remove_item(list, item)\n list.delete(item)\nend",
"def remove_item(item, list)\r\n list.delete(item)\r\n p list\r\n list\r\nend",
"def remove_item(list, item)\n list.delete(item)\nend",
"def remove_item(list, item)\n list.delete(item)\nend",
"def remove(list, item)\n\tlist.delete(item)\n\tlist\nend",
"def remove_item(list, item)\r\n list.delete(item)\r\n p list\r\nend",
"def remove_item!(list, item)\r\n list.delete(item)\r\n list\r\nend",
"def remove_item(list, item_remove)\n list.delete(item_remove)\nend",
"def del_item(list, item_to_del)\n list.delete(item_to_del)\nend",
"def remove (list, item)\n\tlist.delete(item)\nend",
"def delete_item(list,item)\n list.delete(item)\n return list\nend",
"def delete_item(list, item)\n list.delete(item)\n list\nend",
"def delete_item(list, item)\n list.delete(item)\n list\nend",
"def remove(list, food_item)\n\tlist.delete(food_item)\n\tlist\nend",
"def remove_item(list, item_name)\n\tlist.delete(item_name)\n\tlist\nend",
"def remove_item(list, item_name)\n\tlist.delete(item_name)\n\tlist\nend",
"def remove_item(list, item_name)\n\tlist.delete(item_name)\n\tlist\nend",
"def delete_item(list,item)\n list.delete(item)\n list\nend",
"def delete_item(list,item)\n list.delete(item)\n list\nend",
"def remove_item(hash_list, item)\n hash_list.delete(item)\n p hash_list\nend",
"def remove(list,item)\r\n\tlist.delete(item)\r\n\tlist\r\nend",
"def remove(list, item)\r\n list.delete(item)\r\n list\r\nend",
"def remove_item(olist, item)\n olist.delete(item) \n olist\nend",
"def delete_item(list_item)\n @list.delete(list_item)\n @list\n end",
"def remove_item(list_items, item_name)\n list_items.delete(item_name)\nend",
"def remove_item(list, item_name)\n list.delete(item_name)\nend",
"def remove(list, item)\n\tlist.delete(item)\nend",
"def delete_item(list, item)\n del_list = list.delete(item)\nend",
"def remove_an_item(list, item)\n #method to remove item\n list.delete(item)\nend",
"def remove_item_from_list(list,item)\r\n list.delete(item)\r\n print_list(list)\r\nend",
"def delete_item(list,item)\n\tlist.delete(item)\nend",
"def remove_item(shopping_list, item)\r\n\r\n\tshopping_list.delete(item)\r\n\r\nend",
"def delete_item(current_list, item)\n current_list.delete(item)\n current_list\nend",
"def remove_item(list, item_name)\n\tlist.delete(item_name)\n\tp list\nend",
"def delete_item(list,item)\n list.delete(item)\nend",
"def delete_item(list,item)\n list.delete(item)\nend",
"def delete_item(list, item)\n list.delete(item)\nend",
"def remove_from_list(list, item)\n\tlist.delete(item)\nend",
"def delete_item(item)\r\n @list.delete(item)\r\n end",
"def remove_item\n\n end",
"def remove_from_list(list, item)\n list.delete(item)\n p list\nend",
"def remove_item(list, food)\n list.delete(food)\nend",
"def list_remove(hash_items, item_name)\n hash_items.delete(item_name)\n return hash_items\nend",
"def remove_item(shopping_list, item)\n shopping_list.delete(item)\nend",
"def remove_item(item_to_remove)\n $list_hash.delete_if{|current_item, quantity|item_to_remove==current_item} #goes through entire item in delete if hash if item in hash delete from hash\nend",
"def remove_item(item,the_lists)\r\n\t\t# steps: search the hash for the key that match the item name\r\n the_lists.delete_if{|item_name,item_quantity| item_name == item}\r\n\t\t#then delete the element\r\n\r\n\t\tprint_list(the_lists)\r\nend",
"def remove(final_list, item)\r\n final_list.delete(item)\r\n end",
"def remove(list, item_name)\r\n\tlist.delete(item_name)\r\n\tp list\r\nend",
"def remove_item(list, item_name)\r\n # list.delete_if { |item, amount| item == item_name }\r\n list.delete(item_name)\r\nend",
"def remove_from_list(item,list)\n list.delete(item)\nend",
"def list_remover(list,item) #takes 2 arguments, 1 list and name of an item\n\tlist.delete(item)\t\n\t\nend",
"def remove_item(list, name)\r\n# create remove method with name arguments\r\n# check if item is in the hash\r\n if list[name] != nil\r\n# remove item if present\r\n list.delete(name)\r\n end\r\n# output: print \"your item has been deleted from the hash\"\r\n return list\r\nend",
"def remove_item(list, item_name)\n # steps:\n # check IF item is included in list\n # delete the item\n # ELSE, print a message to the user\n list.include?(item_name) ? list.delete(item_name) : puts(\"No #{item_name} on the list.\")\n \n # output: return updated hash or the original hash\n list\nend",
"def remove_items(shopping_list, item)\n shopping_list.delete(item)\nend",
"def remove_item(item, list)\n\tlist.delete_if do |i|\n\t\ti == item \n\tend\nend"
] | [
"0.848525",
"0.8275207",
"0.82061034",
"0.81854343",
"0.81593275",
"0.81582993",
"0.81442285",
"0.8132168",
"0.81233776",
"0.80977386",
"0.80896837",
"0.8056447",
"0.8051242",
"0.8040771",
"0.80405915",
"0.80348045",
"0.80348045",
"0.80348045",
"0.80348045",
"0.8031067",
"0.8022672",
"0.80179566",
"0.800337",
"0.800337",
"0.799541",
"0.7995014",
"0.79807276",
"0.79791176",
"0.797799",
"0.79724216",
"0.79706335",
"0.79525036",
"0.7950509",
"0.7947362",
"0.794668",
"0.794668",
"0.7946207",
"0.79392076",
"0.79388547",
"0.79296976",
"0.79255366",
"0.7921571",
"0.7921524",
"0.792151",
"0.7918959",
"0.7918959",
"0.791863",
"0.79129136",
"0.7909308",
"0.7908364",
"0.7901585",
"0.78975415",
"0.789102",
"0.78894925",
"0.78840685",
"0.7862208",
"0.7847293",
"0.7847293",
"0.7835126",
"0.7829678",
"0.7829678",
"0.7829678",
"0.78274214",
"0.78274214",
"0.78133446",
"0.7806336",
"0.779923",
"0.779742",
"0.7775043",
"0.7771306",
"0.7768701",
"0.7766075",
"0.7766036",
"0.7764699",
"0.77577615",
"0.77561414",
"0.775346",
"0.7738582",
"0.7732343",
"0.7725411",
"0.7725411",
"0.77032536",
"0.7691472",
"0.7676656",
"0.7670045",
"0.765972",
"0.7651148",
"0.7640846",
"0.76390207",
"0.7624758",
"0.7614764",
"0.7606026",
"0.75870275",
"0.75769424",
"0.7575083",
"0.75746286",
"0.7553315",
"0.75503105",
"0.755023",
"0.7543167"
] | 0.7823024 | 64 |
Method to update the quantity of an item input: take new value for specified key steps: Input a value and assign that to the specified key output: item with new quantity | def update_quantity(list, item, quant)
list[item] = quant
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_item_quantity(hash_of_items, item, quantity)\n hash_of_items[item] = quantity\n hash_of_items\nend",
"def update_quantity (item, quantity)\n item_hash[item] = quantity\nend",
"def update_quantity(list, upd_item, new_quantity)\n# steps:\n # reassign key (item) a new value (quantity)\n list[upd_item] = new_quantity\n # return list\n list\nend",
"def update_quantity(input_hash, item, qty)\n# steps: use input item as key and input quantity as value\n# output: hash \n input_hash[item] = qty\n \nreturn input_hash\nend",
"def update_quantity(hash, item, quantity)\n hash[item] = quantity\nend",
"def update_qty(item_list, item, qty)\r\n item_list[item] = qty\r\n item_list\r\nend",
"def update_item_quantity(hash, item, quantity)\n hash[item] = quantity\n hash\nend",
"def update_quantity(item, quantity, hash)\n hash[item] = quantity\n return hash\nend",
"def update_quantity_of_items(list, item, quantity)\n list[item] = quantity\nend",
"def update_quantity(hash, item, quantity)\n\thash[item] = quantity\n\treturn hash\nend",
"def update_quantity(list, item, qty)\n list[item] = qty\n list\nend",
"def update_quantity(groceries_list, item, new_quantity)\n\t# Change value for inputted key to the desired quantity\n\tgroceries_list [item] = new_quantity\n\tgroceries_list\nend",
"def update_quantity(list, item_name, qty)\n list[item_name] = qty\nend",
"def quantity_update(hash, grocery, quantity)#ask user for item key they wish to change\n\thash[grocery] = grocery #locating matching key\n\thash[grocery] = quantity #updating value of that key\nend",
"def update_quantity(item, list, quantity)\n add_item(item, list, quantity)\nend",
"def update_quantity(hash, item_name, quantity)\r\n hash[item_name] = quantity\r\n hash\r\nend",
"def item_quantity(list, item_to_update, quantity)\n list[item_to_update] = quantity \nend",
"def update_item_quantity(list, item, quantity)\n list[item] = quantity\n list\nend",
"def update_quantity(list_name, item, value)\r\n# input: list, item name, new quantity\r\n# steps: find item in the hash and change quantity to new quantity\r\n list_name[item] = value\r\n# output: updated hash with new value for item key\r\n p list_name\r\nend",
"def update_quantity(hash, item, quantity)\n hash[item] = quantity\n return hash\nend",
"def update_item(hash, item, qty)\n hash[ item ] = qty\nend",
"def update_quantity(list, item, quantity)\n list[item] = quantity\nend",
"def update_quantity(hash, item, quantity)\n\n if hash.has_key?(item)\n hash[item] = quantity\n end\n return hash\n\nend",
"def update_quantity(list, item, quantity)\n list[item] = quantity\n list\nend",
"def update_quantity(list, item, quantity)\n list[item] = quantity\n list\nend",
"def update_quantity(list, item, quantity)\n list[item] = quantity.to_i\n list\nend",
"def update_quantity(shopping_list, item, quantity)\n shopping_list[item] = quantity\nend",
"def update_quantity (list, item, quantity)\n list[item] = quantity\nend",
"def update_quantity (list, item, quantity)\n list[item] = quantity\nend",
"def update_quantity(list, item, quantity)\n list[item] = quantity\nend",
"def update_quantity(list, item, quantity)\n\tlist[item] = quantity\n\tlist\nend",
"def update_quantity(list, item_name, quantity)\r\n list[item_name] = quantity\r\nend",
"def updated_quantity(list, item_name, quantity)\r\n\tlist[item_name] = quantity\r\n\tlist\r\nend",
"def update_quantity(list, item, quantity)\n #method to update quantity\n #can also add items\n list[item] = quantity\nend",
"def update_quantity(new_list, item_name, quantity)\r\n \r\n new_list[item_name] = quantity\r\nend",
"def update_quantity(list, item, updated_quantity)\n list[item] = updated_quantity\n list\nend",
"def update_quantity(list, item_name, new_quantity)\n list[item_name] = new_quantity\nend",
"def update_quantity(list, item_name, new_quantity)\n list[item_name] = new_quantity\nend",
"def update_quantity(list, item, quant)\n list[item] = quant\nend",
"def change_quantity(list, item, qty)\n list[item] = qty\n list\nend",
"def update(hash, item, qty)\n hash[item] = qty\nend",
"def update(hash, item, qty)\n hash[item] = qty\nend",
"def update_item(list,item,quantity)\n list[item] = quantity\nend",
"def update_item(list,item,quantity)\n list[item] = quantity\nend",
"def update_quantity(item, list, quantity)\n list[item] = quantity\n return list\nend",
"def update_quantity(list, key, quantity)\n list[\"#{key}\"] = quantity\n list\nend",
"def change_quantity(list, item, new_qty)\n list[item] = new_qty\nend",
"def update_quantity(list,item,item_count)\n\tlist[item] = item_count\nend",
"def input (list, item, quantity)\n\tlist[item] = quantity\nend",
"def update_amount(hash, item, new_quantity)\n\thash[item.to_sym] = new_quantity\n\thash\nend",
"def update_quantity(list, item_name, quantity)\n\tlist[item_name] = quantity.to_i\n\tlist\nend",
"def update_quantity(grocery,item_name,new_quantity)\n # input:list, item name, and new_quantity\n # steps: change old value of item_name with the new_quantity\n grocery[item_name] = new_quantity\n # output: display the latest list\n display_list(grocery)\nend",
"def update_quantity(list, item, quantity)\nlist[item] = quantity\nlist\nend",
"def update_quantity(list, item_name, quantity)\n\tlist[item_name] = quantity\n\tlist\nend",
"def update_quantity(list, item_name, quantity)\n\tlist[item_name] = quantity\n\tlist\nend",
"def update_qty(shopping_list, item, quantity)\r\n\r\n\tadd_item(shopping_list, item, quantity)\r\n\r\nend",
"def update_qty(list_hash, item, qty)\r\n \tlist_hash[item] = qty\r\n \tlist_hash\r\nend",
"def add_or_update_item_qty(shopping_list, item, quantity)\n shopping_list[item] = quantity\nend",
"def update_item (list,item,quantity)\n\tlist[item] = quantity\nend",
"def update_item_quantity(current_list)\r\n puts \"Enter item to update: \"\r\n item_to_update = gets.chomp\r\n \r\n puts \"Enter a new quantity: \"\r\n new_item_qty = gets.chomp\r\n new_item_qty = new_item_qty.to_i\r\n \r\n if current_list.has_key?(item_to_update)\r\n current_list[item_to_update] = new_item_qty\r\n end\r\n \r\n current_list\r\nend",
"def update_qty(list_items, item_name, new_qty)\n raise ArguementError.new(\"This item does not exist\") unless list_items.include?(item_name)\n list_items[item_name] = item_qty\nend",
"def update_qty(list, item_to_update, new_qty)\n # if list.has_key? item_to_update\n # list[item_to_update] = new_qty\n # end\n list[item_to_update] = new_qty if list.has_key? item_to_update\n list\nend",
"def update_quantity(list, key_name, quantity=1)\r\n\tlist[key_name] = quantity\r\n\treturn list\r\nend",
"def update (item, quantity)\n @groceries[item]=quantity\n end",
"def update (list, item, quantity)\n\tlist[item] = quantity\nend",
"def update(list, item, quantity)\n\tlist[item] = quantity\nend",
"def update_item(list, item, new_quantity)\n\tlist[item] = new_quantity\n\tlist\nend",
"def update_quantity(list, item, quantity)\r\n\tlist[item] = quantity\r\n\treturn list\r\nend",
"def update_quantity (item,list, quantity)\n list[item] = quantity\nlist\nend",
"def update(item,quantity,list)\n\tlist[item] = quantity\nend",
"def update_quantity(grocery_list, item_to_update, qty)\n grocery_list[item_to_update] = qty\n grocery_list\nend",
"def update_item(list, item, quantity)\r\n add_item(list, item, quantity)\r\n# input: Shopping list, item to be updated, new quantity\r\n# steps:\r\n # Use shopping list as input\r\n # Use item to be updated as input\r\n # Use new quantity to be updated as input\r\n # Update the quantity of the item on the list\r\n # list[item] = quantity\r\n# output: shopping list with updated quantity\r\n # printlist(list)\r\nend",
"def change_qty(list, item, qty)\n if list.has_key?(item) == false\n puts \"Item not found\"\n else\n qty.to_i\n list[item] = qty\n end\n list\nend",
"def update_quantity(list, item, quantity)\n\tlist[item] = quantity\n\tp list\nend",
"def update_item(item, list, quantity)\n if list.has_key?(item)\n list[item] = quantity\n return list\n else\n return list\n end\nend",
"def update(list, item, quantity)\n\tlist[item] = quantity\n\tlist\nend",
"def update_item(list_name, item_name, quantity)\r\n list_name[item_name] = quantity if list_name.has_key?(item_name)\r\nend",
"def update_quantity(hash, item, quantity)\r\n\tnew_hash = {item => quantity}\r\n\thash.merge!(new_hash)\r\n\thash\r\nend",
"def update_quantity(grocery_list, item, quantity)\n grocery_list[item] = quantity.to_i \n grocery_list\nend",
"def update(list, item, quantity)\n list[item] = quantity\n list\nend",
"def update_quantity(name, quantity, list)\n list[name] += quantity\nend",
"def update_quantity(grocery, item, update_quantity)\n if grocery.has_key?(item)\n grocery[item] = update_quantity\n end\n grocery\nend",
"def add(input_list, item, quantity)\n input_list[item] = quantity\nend",
"def update (list, item, qty)\n list[item] = qty\nend",
"def update_quantity(list, item, quantity)\n\tadd_to_list(list, item, quantity)\nend",
"def update_quantity(list, item, new_quantity)\n list.each do |key, value|\n if key == item\n list[key] = new_quantity\n end\n end\nend",
"def update_quan(list, item, quantity)\n list[item] = quantity\nend",
"def update_qty(list, item, qty)\n if list.has_key?(item)\n list[item] = qty\n end\n return list.each {|k,v| puts \"#{k}: #{v}\"}\nend",
"def update_quantity(list, item, new)\n if list.has_key?(item)\n list[item] = new\n #This is a different way that merges a new hash to update old hash\n # new_list = {key => new_quantity}\n # list.merge!(new_list) {|key, old_quantity, new_quantity| new_quantity}\n # p list\n end\nend",
"def update(list, item_name, quantity)\n\tlist[item_name] = quantity\nend",
"def update_quantity(list, item, quantity)\n list[item] = quantity\n p list\nend",
"def add_item(input_hash, item, qty = 0)\n# steps: use input item as key and input quantity as value \n input_hash[item] = qty\n# output: hash data structure of key/value pairs\n return input_hash\nend",
"def add_item(list, add_item, add_quantity=1)\n# steps:\n # Add item as key and quantity as value to final_list hash(item and quantity will be user inputs)\n list[add_item] = add_quantity\n # Return updated hash\n list\nend",
"def new_quantity(list, item, qty)\n list[item] += qty\n p list\nend",
"def update(list, item, quantity)\r\n if list.has_key?(item)\r\n list[item] = quantity\r\n else puts \"No item found\"\r\n end\r\n list \r\nend",
"def update_quantity(item, new_quantity, grocery_list)\n grocery_list[item] = new_quantity\nend",
"def update_item(list, item, quantity)\n\tlist[item] = quantity\n\treturn list\nend",
"def update_quantity(list, item_name, quantity)\n\tlist.each do |item, qty|\n\t\tif item === item_name\n\t\t\tlist[item] = quantity\n\t\tend\n\tend\nend",
"def update_quantity (quantity, item)\n $list.each do |list_item|\n if list_item[:item] == item\n list_item[:quantity] = quantity\n end\n end\nend",
"def update_quant(current_list, item, quantity)\n current_list[item] = quantity\n current_list\nend"
] | [
"0.8285092",
"0.8272936",
"0.82564175",
"0.82188153",
"0.8082456",
"0.80262333",
"0.8025164",
"0.79247564",
"0.79122823",
"0.7903981",
"0.78727496",
"0.78636533",
"0.7854685",
"0.78466725",
"0.7846255",
"0.7839987",
"0.78146607",
"0.78135145",
"0.78080344",
"0.7803778",
"0.7796097",
"0.7779031",
"0.77720165",
"0.7772001",
"0.7772001",
"0.77609116",
"0.7757333",
"0.77433556",
"0.77433556",
"0.77408713",
"0.7726027",
"0.77259",
"0.7723715",
"0.77041763",
"0.7703514",
"0.7695015",
"0.76923335",
"0.76923335",
"0.7691868",
"0.7690726",
"0.7687152",
"0.7687152",
"0.7672475",
"0.7672475",
"0.7660233",
"0.76560974",
"0.76549476",
"0.7646057",
"0.7635902",
"0.7624279",
"0.7620906",
"0.761554",
"0.76104045",
"0.7604981",
"0.7604981",
"0.7604536",
"0.7600856",
"0.7597793",
"0.7580479",
"0.7576269",
"0.756982",
"0.75595695",
"0.7547673",
"0.7541958",
"0.7527821",
"0.75211614",
"0.7521044",
"0.7520375",
"0.75183284",
"0.7518071",
"0.75144225",
"0.74944305",
"0.7486238",
"0.74833137",
"0.7476115",
"0.74721944",
"0.7468141",
"0.74675196",
"0.7452518",
"0.7441807",
"0.7440012",
"0.74285567",
"0.74170595",
"0.7416567",
"0.7413009",
"0.7405971",
"0.7401216",
"0.7399796",
"0.7394558",
"0.7393298",
"0.7391367",
"0.7387903",
"0.738781",
"0.7376537",
"0.736431",
"0.7362411",
"0.736154",
"0.7355205",
"0.7354864",
"0.7349411"
] | 0.77860636 | 21 |
Method to print a list and make it look pretty input: list of hash we want to print steps: print keys as strings with corresponding value output: keys as strings and their quantity | def print_list(list)
list.each do |item, quantity| puts "#{item}: #{quantity}"
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def pretty_list(hash)\r\n puts \"Grocery List:\"\r\n puts \" \"\r\n hash.each do |item_name, quantity|\r\n puts \"#{item_name}: #{quantity}\"\r\n end\r\nend",
"def print_list(my_list)\r\n# input: \r\n \r\n# steps:\r\n# print to screen: iterate through hash item - quantity\r\n puts '------'\r\n puts \"Grocery list:\"\r\n my_list.each do |item, qty|\r\n puts \"#{item} - #{qty}\"\r\n end\r\n puts '-------'\r\n# output: each k,v pair printed surrounded by dashes\r\nend",
"def prettyfie_list(hash)\r\n puts \"This is your current grocery list:\"\r\n puts \"\\n\"\r\n hash.each {|key, value| puts \"#{key} quantity = #{value}\" }\r\n puts \"\\n\"\r\nend",
"def pretty_print(list)\n list.each {|item, quantity| puts \"#{item} : #{quantity}\"}\nend",
"def print_list(hash)\n\tputs \"\" \n hash.each do |item, qty|\n puts \"#{item}: #{qty}\\n\"\n end\nend",
"def pretty_print_list(hash)\n\thash.each do |key, value|\n\t\tputs \"You need #{value}, #{key}\"\n\tend\nend",
"def print_list(list_name)\r\n# input: hash name\r\n# steps: add dashes and spacing\r\np \"List:\"\r\nlist_name.each do |key, value|\r\n p \"#{key}: #{value}\"\r\nend\r\n# output: pretty hash listed\r\nend",
"def print_list(list_hash)\r\n\tlist_hash.each {|key, value| puts \"#{key}; qty: #{value}\" }\r\nend",
"def pretty_in_print(list)\n puts \"---------------------------------------\"\n puts \"These are the items we are gonna buy\"\n list.each {|item, qty| puts \"#{qty} pieces of #{item}\" }\nend",
"def print_list(hash)\n hash.each do |item, quantity|\n puts \"#{item}: #{quantity}\"\n end\nend",
"def list_print(hash_items)\n printf(\"%20s%20s\\n\", '---------------','---------------')\n printf(\"%20s%20s\\n\", 'Item','Quantity')\n printf(\"%20s%20s\\n\", '---------------','---------------')\n\n hash_items.each do |x,y|\n printf(\"%20s%20s\\n\", x.upcase, y)\n end\n\nend",
"def print_list(hash)\n width= 50\n puts \"Shopping List\".center(width)\n puts \"\".rjust(50,\"-\")\n print \"Item\".ljust(width/2)\n print \"-\"\n puts \"Quantity\".rjust(width/2)\n puts \"\".rjust(50,\"-\")\n hash.each do |item, quantity|\n puts \"#{item.ljust(width/2)}-#{quantity.to_s.rjust(width/2)}\"\n end\nend",
"def print_list(hash)\n hash.each do |item, quantity|\n puts item + \" : \" + quantity.to_s\n end\n end",
"def print_list()\n $list_hash.each do |current_item, quantity|\n p \"#{current_item.strip}: #{quantity.to_i}\"\n end\nend",
"def print_list(hash)\r\n\thash.each do |item, quantity|\r\n\t\tputs \"#{item}, #{quantity}\"\r\n\tend\r\nend",
"def pretty_list(list)\n puts \"Grocery List:\"\n list.each do |key, value|\n puts \"#{value} #{key}(s)\"\n end\n \nend",
"def pretty_list(list)\n\tlist.each { |item_name, item_quantity|\n\t\tputs \"You will need to purchase #{item_quantity} of #{item_name}.\"\n\t}\nend",
"def print_list(item_list)\r\n\t# steps: iterate through each of hash element\r\n\t# print the header\r\n puts \"=========================\"\r\n\tputs \"== Grocery List So Far ==\"\r\n\tputs \"=========================\"\r\n\titem_list.each do |item,quantity|\r\n\t\t# display each element key and the value to make it look pretty\r\n\r\n\t\tputs item.ljust(20)+quantity.to_s\r\n\tend\r\nend",
"def pretty_list(list)\n list.each do |item,quantity|\n p \"#{item}! You have #{quantity}.\"\n end\nend",
"def pretty_list(list)\n list.each do |item,quantity|\n p \"#{item}! You have #{quantity}.\"\n end\nend",
"def pretty_up(list)\n puts \"\\nHere is your grocery list: \"\n list.each do |key, value|\n puts value.to_s + ' ' + key.to_s\n end\nend",
"def pretty_list(list)\n list.each {|item, quantity| puts \"You need #{quantity} #{item}\"}\nend",
"def pretty_list(list)\n list.each do |grocery_item, qty|\n puts \"#{grocery_item}, quantity: #{qty}\"\n end\nend",
"def print_list(list)\n puts \"Name \\t\\t Quantity\"\n list.each do |key, value|\n puts \"#{key} \\t\\t #{value}\"\n end\nend",
"def pretty(list)\n list.each {|item, quantity| p \"You need to buy #{quantity} of #{item}.\"}\nend",
"def pretty_list(list)\r\n\tlist.each { |item, quantity| puts \"Item: #{item.capitalize} - Amount: #{quantity}\" }\r\nend",
"def pretty_list(list)\n\tlist.each do |item, quantity|\n\t\tputs \"There are #{quantity} #{item} on the grocery list.\"\n\tend\nend",
"def print_list(hash)\n hash.each do |x,v|\n puts \"the item is #{x} and the quantity is #{v}.\"\n end\nend",
"def pretty_list(groceries_list)\n\t# Print a line of text to lead into the list\n\tputs \"Here is your updated grocery list:\"\n\t# for each key and value in the list, print a string \n\t# containing the key and value\n\tgroceries_list.each do |item, quantity|\n\t\tputs \"#{item}: #{quantity}\"\n\tend\nend",
"def print_list(input_hash)\n# steps: iterate through the hash and print keys/values\n puts \"Here are the items on your list\"\n input_hash.each do |item, qty|\n p \"For item #{item}, we have #{qty}\" \n end \n# output: nil\nend",
"def look_pretty(list)\n puts \"Here is your grocery list:\"\n list.each { |item, quantity| puts \"#{item}: #{quantity}\" }\nend",
"def pretty_list(grocery_list)\n grocery_list.each do |item, quantity|\n puts \"#{quantity} #{item}\"\n end\nend",
"def pretty_list(grocery_list)\n grocery_list.each do |item, quantity|\n puts \"#{quantity} #{item}\"\n end\nend",
"def print_list(list)\n puts \"List: #{list['name']}\"\n print_separator\n\n list[\"items\"].each do |item|\n puts \"\\tItem: \" + item['name'] + \"\\t\\t\\t\" +\n \"quantity: \" + item['quantity'].to_s\n end\n\n print_separator\nend",
"def print_list(list)\n\tlist.each do |iterator|\n\tputs \"#{iterator[:item].split.map(&:capitalize).join(' ')} - QTY #{iterator[:qty]}\"\n\tend\n\nend",
"def print_list\n $list.each {|list_item| puts \"#{list_item[:quantity]} #{list_item[:item]}\"}\nend",
"def print_list(hash)\n puts \"Grocery list:\"\n hash.each {|item, quantity| puts \"#{item} - #{quantity}\"}\nend",
"def print_list(list)\r\n# input: completed list\r\n# steps:\r\n # iterate over list and print formatted list\r\n puts \"Your Grocery List\"\r\n list.each do |item, quantity|\r\n puts \"#{item}, qty: #{quantity}\"\r\n end\r\n # format: each item with its own line\r\n # \"item - quantity\"\r\n# output: implicit return of list\r\nend",
"def grocery_printed_pretty(groceryhash)\n $groceryhash.map do |food_item, food_quantity|\n puts \"#{food_item.to_s} : #{food_quantity}\"\n end\nend",
"def prettify_list(list)\n\tlist.each do |item, quantity|\n\t\tp \"You have #{quantity} #{item}\"\n\tend\nend",
"def printable\n\t\t@entries.sort.map do |key, value|\n\t\t\t\"[#{key}] \\\"#{value}\\\"\"\n\t\tend.join(\"\\n\")\n\tend",
"def print_list(list_hash)\n list_hash.each do |key,value|\n puts \"The quantity of #{key} is: #{value}\"\n end\nend",
"def prettify(list)\r\n\r\n list.each do |item, quantity|\r\n puts \"There are #{quantity} #{item} in the list.\"\r\n end\r\n\r\nend",
"def printable\n asPrintable = \"\"\n doCount = 0 # way to keep track of the entries loop so a new line can be added to the end of the concat string\n @entries.sort.each do |keyWord, value|\n asPrintable += \"[#{keyWord}] \\\"#{value}\\\"\"\n if doCount < @entries.length - 1 # in order for test to pass, it cant have a extra line at the end\n asPrintable += \"\\n\" # only add one if not the last element of the hash\n end\n doCount += 1 # each loop adds one\n end\n asPrintable # return concat string\n end",
"def print(hash)\r\n\thash.each do |key, value|\r\n puts \"Item: #{key} Quantity: #{value}\"\r\nend\r\nend",
"def print_list(list)\n\tlist.each do |item,quantity|\n\t\tp \"#{quantity} #{item}\"\n\tend\nend",
"def print_pretty(list)\n list.each { |item, value| puts \"#{item} #{value}\" }\nend",
"def print_list\n @list.each { |item, qty| puts \"#{qty} #{item}\" }\n end",
"def print_list\n @list.each { |item, qty| puts \"#{qty} #{item}\" }\n end",
"def print_friendly_list(list)\n puts \n puts \"Shopping List:\"\n puts \"----------------\"\n list.each {|key, value| puts \"#{key} #{value}\" }\n puts \nend",
"def print_list(list)\n\tlist.each do |item, qty|\n\t\tputs \"#{item} = #{qty}\"\n\tend\nend",
"def print_list(input_list)\n input_list.each {|item,quantity|\n puts \"#{item} :#{quantity}\"\n }\nend",
"def print_pretty(new_list)\n puts \"Grocery List:\"\n new_list.each do |item, amount|\n \n puts \"#{item}: #{amount}\"\n end\nend",
"def pretty_list(list_name)\r\n list_name.each do |key, value|\r\n p \"#{key}: #{value}\"\r\n end\r\nend",
"def pretty_format\n pretty = \"\"\n sorted = @hash.sort_by { |name, arrays| name }\n\n sorted.each { |name, array|\n pretty.concat(name)\n pretty.concat(\": \")\n pretty.concat(\"#{@hash[name].join(\",\")}\\n\")\n\n }\n pretty\n\n ### FILL IN YOUR CODE HERE\n end",
"def print_hash(list)\nputs \"Current grocery list:\"\nputs \"---------------------\"\nlist.each do |item_name, item_quant|\n puts \" #{item_name}: #{item_quant}\"\nend\nend",
"def print_pretty (list)\n puts \"Grocery list\".upcase.center(50)\n puts \"-----------------\".center(50)\n list.each do |item,quantity|\n puts item.rjust(25) + \":\" + quantity.to_s.ljust(25) \n end\nend",
"def print_out(list)\n\tlist.each {|item, qty| puts \"#{item}; #{qty}\"}\nend",
"def print_pretty(grocery_list)\r\n\tgrocery_list.each do |item, quantity| \r\n\t\tputs \"you bought #{quantity} #{item}\"\r\n\tend\r\nend",
"def printhash(hash)\n puts \"-----------------------\"\n hash.each { |item, qty| \n puts \"#{item},\\n qty: #{qty}\"\n puts \"\"\n }\n puts \"-----------------------\"\nend",
"def print_list(list)\r\n list.each { |item, quantity| puts \"#{item}: #{quantity}\" }\r\nend",
"def print_list(list)\n list.each { |item, quantity| puts \"#{item}: #{quantity}\" }\nend",
"def print_list(complete_list)\n puts \"Here is a list of things of things you need to buy and the amount needed:\"\n complete_list.each {|key, value| puts \"#{value} #{key}\" }\nend",
"def print_list(list)\n\tlist.each do |item, quantity|\n\t\tputs \"#{item.capitalize}: #{quantity}\"\n\tend\nend",
"def printable\n \tprint_this = []\n \t@entries.each{ |k,v| print_this << \"[#{k}] \\\"#{v}\\\"\\n\" }\n \tprint_this.sort.join.chomp.chomp\n end",
"def print_list(list)\n p \"Shopping List:\"\n list.each do |k, v|\n p \"Item: #{k}, Qauntity: #{v}\"\n end\nend",
"def pretty_list(list)\n # new_list = \"\"\n # list.each { |item, quantity| new_list << \"You want #{quantity} #{item}\\n\" }\n # return new_list\n list.each { |item, quantity| puts \"You want #{quantity} #{item}\\n\" }\nend",
"def print_list(list)\n list_hash = list\n puts \"This is our grocery list: \"\n list_hash.each do |item_key, quant_value|\n puts \"#{item_key}: #{quant_value}\"\n end\nend",
"def print_list(list)\r\n\tlist.each {|item, quantity| puts \"#{item}: #{quantity}\"}\r\nend",
"def print_list(hash)\n count = 1\n hash.each do |key, value|\n p count.to_s + \") \" + key + \": \" + value.to_s\n count += 1\n end\nend",
"def look_pretty(grocery_hash)\n grocery_hash.each do |grocery, quantity|\n puts \"We need #{grocery}: #{quantity}\"\nend\n \nend",
"def print_list(list)\n list.each {|item,quantity| puts \"#{item}: #{quantity}\"}\nend",
"def print_list(list)\r\n puts \"-\"*20\r\n list.each do |item,quantity|\r\n puts \"Item:#{item} quantity:#{quantity}\"\r\n end\r\n puts \"-\"*20\r\n list\r\nend",
"def pretty_list(list)\n list.each{|food, quantity| puts \"Please get #{quantity} #{food}.\"}\n puts \"Thanks!\"\nend",
"def print_list(list)\n list.each_pair{ |item, quantity| puts \"#{item}: #{quantity}\" }\nend",
"def print_list(list)\n list.each_pair{ |item, quantity| puts \"#{item}: #{quantity}\" }\nend",
"def stringify(list) \n list.each do |item, qty|\n puts item + \" ==> \" + qty.to_s\n end\nend",
"def print_list(list)\n list.each do |item, quantity|\n p \"#{item}: #{quantity}\"\n end\nend",
"def format_list(list)\n puts \"Your grocery list:\"\n list.each do |key, value|\n puts \"#{key}: #{value}\"\n end\nend",
"def print_list(list)\n list.each do |item, quantity|\n puts \"#{item} x #{quantity}\"\n end\nend",
"def print_list(list)\n\tlist.each do |item, quantity|\n\t\tputs \"#{item}, amount: #{quantity}\"\n\tend\nend",
"def print_list(list)\n\tmax_index = list.length;\n\ti=1\n\twhile i<=max_index\n\tprint \"#{i}. #{hash_to_string(list[i-1])}\".center(get_winsize)\n\tprint \"\\n\"\n\ti +=1\n\tend\nend",
"def print_list(list)\n list.each do |name, quantity|\n puts \"#{name} : #{quantity}\"\n end\nend",
"def print_list(list)\n list.each do |item, quantity| puts \"#{item}: #{quantity}\"\n\n end\nend",
"def print_hash(hash_of_items)\n hash_of_items.each { |key, value| p \"#{key}: #{value}\" }\nend",
"def print_grocery_list(grocery_list) \n\t# create title and line break\n\tputs \"Current grocery list:\"\n\tputs \"----------\"\n\t# iterate through hash\n\tgrocery_list.each do |item, quantity|\n\t\t# print each item with its quantity\n\t\tputs \"#{item}: #{quantity}\"\n\tend\n\t# create line break for readability\n\tputs \"----------\"\nend",
"def pretty_list(list)\r\n\tputs \"Grocery List\".center(30)\r\n\tlist.each do |item, quantity|\r\n\t\tputs \"#{item} \".ljust(20) + \"#{quantity}\".rjust(10)\r\n\tend\r\nend",
"def pretty_list(grocery_list)\r\n puts \"Your Grocery List for next week!\"\r\n grocery_list.each do |item, num|\r\n puts \"#{item} qty #{num}\"\r\n end\r\n \r\nend",
"def print_list(fund_hash)\n fund_hash[:list].each do |item|\n puts \"Name: #{item[:name]}\"\n puts \"Description: #{item[:description]}\"\n puts \"Target: $#{item[:target]}\"\n puts \"Balance: $#{item[:balance]}\"\n puts \"Percentage: #{item[:percentage]}%\"\n puts \"Importance: #{item[:importance]}\"\n puts \"-------------------------\"\n end\n end",
"def print(list)\n# steps: \n\t# make a new string\n\tstring = \"This is the shopping list: \\n\"\n\t# iterate through the list\n\tlist.each do |item, quantity|\n\t\t# add the items and quantities to the string and end with a newline\n\t\tstring = string + \"#{item}: #{quantity} \\n\"\n\tend\n# output: the string\n\tputs string\nend",
"def print_list(list)\n\tlist.each do |item, quantity|\n\t\tputs \"We need #{quantity} #{item}\"\n\tend\nend",
"def print_list(grocery_hash={})\n\tputs \"*\" * 40\n\tputs \"Grocery List\"\n\tputs \"*\" * 40\n\tgrocery_hash.each do |food, quantity| puts \"#{food}:\".ljust(30) + \"#{quantity}\".rjust(10)\n\tend\n\tputs \"\"\nend",
"def print_list(hash)\n hash.each { |key, value| puts \"#{value}: #{key}\" }\nend",
"def print_list(list)\r\n list.each {|key,value| puts \"You need #{value} #{key}(s).\"}\r\nend",
"def print_item_list(item_list)\r\n item_list.each { |item, qty| puts \"- #{item} : #{qty}\" }\r\nend",
"def hash_printer(hash)\n puts \"Grocery List\"\n hash.each do |key, value|\n puts \"You need #{value} #{key}(s).\"\n end\nend",
"def print_list(list)\n list.each do |item, quant| \n puts \"Item: #{item}, Quantity: #{quant}\"\n end\nend",
"def pretty_print(result)\n result.each_with_index do |line, index|\n puts \"#{index+1}:\\t #{type_to_sym(line[:type])}\\t#{line[:value]}\"\n end\n end",
"def print_list(shopping_list)\n puts shopping_list.each {|item, quantity| puts \"#{item}: #{quantity}\"}\nend",
"def pretty_list(grocery_list)\n puts \"Shopping List\"\n grocery_list.each do |item, quantity|\n puts \"#{item}: #{quantity}\"\n end\n puts \"Happy Shopping!\"\nend"
] | [
"0.779294",
"0.77135444",
"0.7693041",
"0.7674169",
"0.75049746",
"0.7443091",
"0.74092066",
"0.7384402",
"0.7371843",
"0.7335432",
"0.73260117",
"0.7290909",
"0.7282052",
"0.7278292",
"0.7254332",
"0.7251003",
"0.7221183",
"0.7197294",
"0.7186273",
"0.7186273",
"0.7172586",
"0.7167873",
"0.715166",
"0.70856225",
"0.707662",
"0.70738256",
"0.7062106",
"0.70530725",
"0.7019557",
"0.70106125",
"0.7007751",
"0.69771445",
"0.69771445",
"0.6974289",
"0.6948572",
"0.69484895",
"0.69288194",
"0.6925108",
"0.6911502",
"0.68758017",
"0.68695277",
"0.6825406",
"0.68130594",
"0.6789132",
"0.6776547",
"0.6768189",
"0.6768034",
"0.6766228",
"0.6766228",
"0.6728382",
"0.6723267",
"0.6721305",
"0.6696178",
"0.6694621",
"0.6690725",
"0.6686475",
"0.66863537",
"0.66627264",
"0.66541666",
"0.66533583",
"0.66459304",
"0.662494",
"0.66102296",
"0.6606283",
"0.6600745",
"0.6597385",
"0.65965784",
"0.6596577",
"0.6586784",
"0.65771466",
"0.65734637",
"0.65716064",
"0.65670663",
"0.6563984",
"0.65476376",
"0.65476376",
"0.6544377",
"0.6533711",
"0.6512472",
"0.6508911",
"0.6507382",
"0.64992964",
"0.6497033",
"0.64919305",
"0.64844877",
"0.64843285",
"0.6458915",
"0.64561033",
"0.64481384",
"0.64476347",
"0.6433721",
"0.6424607",
"0.6422769",
"0.64055043",
"0.6381415",
"0.63772357",
"0.6366663",
"0.63591975",
"0.635838",
"0.6347661"
] | 0.67041886 | 52 |
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",
"def get_instance_reservations(filters = {})\n AWS.memoize do\n @ec2.regions['us-west-1'].reserved_instances.select do |ins|\n filters.reduce(true) do |memo, filter_kvp|\n memo && ins.send(filter_kvp[0]) == filter_kvp[1]\n end\n end\n end\n end",
"def db_instances(region)\n logger.info(\"fetching db instances of region #{region}\")\n rds_client = get_rds_client(region)\n next_token = nil\n rds_instances = []\n\n loop do\n options = { marker: next_token }\n resp = rds_client.describe_db_instances(options)\n rds_instances += resp.db_instances\n next_token = resp.marker\n break unless next_token\n end\n rds_instances\n end",
"def instances(type)\n @instances[type]\n end",
"def instances_action(action)\n opts = {}\n opts[:group] = @option.group if @option.group\n opts[:id] = @argv.instid if @argv.instid\n opts[:id] &&= [opts[:id]].flatten\n \n instances = Rudy::AWS::EC2::Instances.list_group(opts[:group], :running, opts[:id])\n raise \"No matching instances running\" if instances.nil?\n \n inst_names = instances.collect { |inst| inst.dns_public || inst.awsid }\n inst_ids = instances.collect { |inst| inst.awsid }\n \n instance_count = (instances.size == 1) ? '1 instance' : \"#{instances.size} instances\"\n \n print \"#{action.to_s.capitalize} #{instance_count} (#{inst_names.join(', ')}) \"\n print \"in #{opts[:group]}\" if opts[:group]\n li\n execute_check(:medium)\n \n execute_action(\"#{action.to_s.capitalize} Failed\") { \n Rudy::AWS::EC2::Instances.send(action, inst_ids)\n }\n status\n end",
"def get_instances\n instances = [ ]\n get_clouds.each do |cloud|\n instances += cloud.instances.index(:filter => [], :view => 'tiny')\n end\n instances\n end",
"def vms(range, groups)\n vms = []\n # load specific batch\n vm_pool = load_vm_pool\n return nil if vm_pool.count == 0\n\n @log.debug(\"Searching for vms based on range: #{range} and groups: #{groups}.\")\n vm_pool.each do |vm|\n unless vm['ID']\n @log.error('Skipping a record without an ID present.')\n next\n end\n\n # skip unsuitable virtual machines\n next unless want?(vm, range, groups)\n\n vms << vm['ID'].to_i\n end\n\n @log.debug(\"Selected vms: #{vms}.\")\n vms\n end",
"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 describe_container_instances(params={})\n if instances = params.delete('containerInstances')\n params.merge!(Fog::AWS.indexed_param('containerInstances.member', [*instances]))\n end\n\n request({\n 'Action' => 'DescribeContainerInstances',\n :parser => Fog::Parsers::AWS::ECS::DescribeContainerInstances.new\n }.merge(params))\n end",
"def describe_all_instances\n @os_aws.describe_all_instances\n end",
"def monitor_instances( options = {} )\n options = { :instance_id => [] }.merge(options)\n raise ArgumentError, \"No :instance_id provided\" if options[:instance_id].nil? || options[:instance_id].empty?\n params = pathlist(\"InstanceId\", options[:instance_id])\n return response_generator(:action => \"MonitorInstances\", :params => params)\n end",
"def ec2_instances\n instances = EC2::InstanceCollection.new(:config => config)\n instances.tagged('aws:autoscaling:groupName').tagged_values(name)\n end",
"def serversForCapRoles(roles)\n find_servers(:roles => roles).collect { |x| x.host }\nend",
"def run(name, tags, attributes, match_all)\n resources = api_client.tags.by_tag(resource_type: 'instances', tags: [tags], match_all: match_all)\n raise \"No Instances found for tag #{tags}\" if resources.empty?\n\n resources.first.links.each do |link|\n resource = api_client.resource(link['href'])\n # find the server_template of the instance\n st = resource.show.server_template\n # find the exact runnable bindings by name and which are operational on the instance\n runnable_bindings = st.show.runnable_bindings.index.select do |r|\n r.right_script.show.name == name && r.sequence == 'operational'\n end\n raise \"RightScript #{name} not found\" if runnable_bindings.empty?\n right_script = runnable_bindings.first.right_script\n if resource.show.state == 'operational'\n # run the found rightscript on the instance and pass the attributes as inputs.\n status = resource.run_executable(right_script_href: right_script.href, inputs: attributes)\n Chef::Log.info status\n end\n end\n end",
"def instances\n @instances ||= aws_client.instances(filters: instance_filters).map do |instance|\n OpenStruct.new(\n with_tags(instance, private_ip: instance.private_ip_address,\n public_ip: instance.public_ip_address,\n instance: instance.instance_id)\n )\n end\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::Notebooks::V1::ListInstancesResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def kitchen_instances(regexp, config)\n instances = Kitchen::Config.new(config).instances\n return instances if regexp.nil? || regexp == 'all'\n instances.get_all(Regexp.new(regexp))\n end",
"def aws_read_instances\n list = JSON.parse( IO.read( aws_instances_json ), :symbolize_names => true )\n list.each do |inst|\n inst[:roles] = ( inst[:roles] || [] ).map { |r| r.to_sym }\n end\n @aws_instances = list.sort { |p,n| p[:name] <=> n[:name] }\n end",
"def get_docker_instance_list(options)\n message = \"Information:\\tListing docker images\"\n command = \"docker ps\"\n output = execute_command(options,message,command)\n instances = output.split(/\\n/)\n return instances\nend",
"def search_cinstances(params)\n cinstances.with_account.by_state(params[:state]).search(params)\n end",
"def select(params = {})\n if params.has_key?(:path)\n path_regex = params[:path]\n path_regex = Regexp.new(path_regex.to_s) unless path_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && path_regex.match(agent.config_path) }\n notify(:msg => \"[#{@name}] Selecting all services for path #{path_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:type)\n type_regex = params[:type]\n type_regex = Regexp.new(type_regex.to_s) unless type_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && type_regex.match(agent.type) }\n notify(:msg => \"[#{@name}] Selecting all services of type #{type_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:core_type)\n core_type_regex = params[:core_type]\n core_type_regex = Regexp.new(core_type_regex.to_s) unless core_type_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && core_type_regex.match(agent.core_type) }\n notify(:msg => \"[#{@name}] Selecting all services of core type #{core_type_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:host) || params.has_key?(:hosts)\n host_names = arrayify(params[:host]) & arrayify(params[:hosts])\n selector = lambda {|agent| host_names.include?(agent.host) }\n notify(:msg => \"[#{@name}] Selecting all services for hosts #{host_names.inspect}\",\n :tags => [:galaxy, :trace])\n else\n notify(:msg => \"[#{@name}] Selecting all services\",\n :tags => [:galaxy, :trace])\n end\n command = ::Galaxy::Commands::ShowCommand.new([], @galaxy_options)\n command.report = GalaxyGatheringReport.new(@environment)\n agents = command.select_agents({})\n agents.each { |agent| agent.proxy = ::Galaxy::Transport.locate(agent.url) if agent.url }\n command.execute(agents)\n command.report.results.select {|result| selector.nil? || selector.call(result) }\n end",
"def existing_instances(filter=\"\")\r\n instances_raw = `ps xao pid,pgid,command | grep '#{process_name} #{name_grep_string} #{filter}' | grep -iv #{Process.pid} | awk '{print $1 \"\\t\" $2 \"\\t\" $3}'`\r\n instances_raw.split(\"\\n\").map do |row|\r\n pid, group, command = row.split(\"\\t\")\r\n ProcessInfo.new(pid.to_i, group.to_i, command)\r\n end\r\n end",
"def instances\n @instances ||= begin\n instances_channel = channel(\n Admin::V2::BigtableInstanceAdminClient::SERVICE_ADDRESS\n )\n Admin::V2::BigtableInstanceAdminClient.new(\n credentials: instances_channel,\n timeout: timeout,\n client_config: client_config,\n lib_name: \"gccl\",\n lib_version: Google::Cloud::Bigtable::VERSION\n )\n end\n end",
"def aws_instance_get(opts)\n AWS::EC2.new.instances[opts[:instance_id]]\n end",
"def instanceinfo(compute,name)\n\t\tresp = compute.describe_instances\t\n\t\tif (resp.status == 200)\n\t\t\t# check through the instances looking for one with a matching Name tag\n\t\t\tresp.body['reservationSet'].each { |x|\n\t\t\t\tx['instancesSet'].each { |y| \n\t\t\t\t\tif ( y['tagSet']['Name'] == name)\n\t\t\t\t\t\treturn y\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\traise \"ebsvol[aws]->instanceinfo: I couldn't list the instances\"\n\t\tend\n\t\tnil\n\tend",
"def extract_slave_instance_options(options)\n extract_instance_options('slave-', options)\n end",
"def list(mixins = nil)\n computes = ::Occi::Core::Resources.new\n\n Backends::Ec2::Helpers::AwsConnectHelper.rescue_aws_service(@logger) do\n rsrvts = @ec2_client.describe_instances.reservations\n rsrvts.each do |reservation|\n next unless reservation && reservation.instances\n reservation.instances.each { |instance| computes << parse_backend_obj(instance, reservation[:reservation_id]) }\n end if rsrvts\n end\n\n computes\n end",
"def find_roles *roles\n role_model.where(:name => roles.flatten)\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_running_instances(group)\n get_instances(group).select{ |instance| instance.ready? }\n end",
"def reserved_instances_offerings(options = {})\n action = 'DescribeReservedInstancesOfferings'\n params = {\n 'Action' => action\n }\n params.merge!(array_to_params(options[:reserved_instances_offering_ids], 'ReservedInstancesOfferingId')) if options[:reserved_instances_offering_ids]\n params['InstanceType'] = options[:instance_type] if options[:instance_type]\n params['AvailabilityZone'] = options[:availability_zone] if options[:availability_zone]\n params['ProductDescription'] = options[:product_description] if options[:product_description]\n\n response = send_query_request(params)\n parser = Awsum::Ec2::ReservedInstancesOfferingParser.new(self)\n parser.parse(response.body)\n end",
"def extract_master_instance_options(options)\n extract_instance_options('master-', options)\n end",
"def available_instances\n @available_instances ||= {}\n end",
"def instances_names_list\n return [] unless configured?\n\n aws_instances_ids = instances_list || []\n aws_instances_ids.map { |instance| instance[:node_name] }\n end",
"def get_all_instances(systems,code = @code)\n return [] unless code.is_a?(Array)\n return code.reduce([]) do |ar,sub|\n ar + get_all_instances(systems,sub)\n end + (code.select { |sub| is_instance?(sub,systems) }).to_a\n end",
"def all(options = {})\n request_model = @request_model_factory.all_builds_request_model(options)\n response = @network_client.perform_request(request_model)\n JSON.parse(response.body)['instances'].map do |hash|\n Fabricio::Model::Build.new(hash)\n end\n end",
"def get_pvm_instances\n pvm_instances = get(\"cloud-instances/#{guid}/pvm-instances\")[\"pvmInstances\"] || []\n\n pvm_instances.map do |pvm_instance|\n get_pvm_instance(pvm_instance[\"pvmInstanceID\"])\n end\n end",
"def instances_for_filter(filter_name, filter_value, state = \"running\")\n ec2.describe_instances(\n filters: [\n { name: filter_name, values: [filter_value] },\n { name: \"tag:environment\", values: [name] },\n { name: \"instance-state-name\", values: [state] }\n ])[:reservations]\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 watch_vm_instances(opts = {})\n @conn.watch_vminstances(opts)\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 selectors\n find_related_frbr_objects( :is_selected_by, :which_roles?) \n end",
"def instances\n @instances ||= []\n end",
"def query_users(options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.query_users(@cluster, policy)\n end",
"def instance\n node = 'AWS_EC2_INSTANCE'\n q = []\n\n # instance node\n q.push(_upsert({ node: node, id: @name }))\n\n # vpc node and relationship\n if @data.vpc_id\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_VPC',\n child_name: @data.vpc_id,\n relationship: 'MEMBER_OF_VPC'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # network_interfaces and relationship\n @data.network_interfaces.each do |ni|\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_NETWORK_INTERFACE',\n child_name: ni.network_interface_id,\n relationship: 'ATTACHED_TO_INSTANCE'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # security_groups and relationship\n @data.security_groups.each do |sg|\n opts = {\n child_node: 'AWS_SECURITY_GROUP',\n child_name: sg.group_id,\n parent_node: node,\n parent_name: @name,\n relationship: 'IN_SECURITY_GROUP'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # subnet and relationship\n if @data.subnet_id\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_SUBNET',\n # child_name: \"arn:aws:ec2:#{@region}:#{@account}:subnet/#{@data.subnet_id}\",\n child_name: @data.subnet_id,\n relationship: 'IN_SUBNET'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n if @data.iam_instance_profile\n opts = {\n node: 'AWS_EC2_IAM_PROFILE',\n id: @data.iam_instance_profile.arn\n }\n\n q.push(_merge(opts))\n\n opts = {\n from_node: node,\n from_name: @name,\n to_node: 'AWS_EC2_IAM_PROFILE',\n to_name: @data.iam_instance_profile.arn,\n relationship: 'HAS_IAM_PROFILE'\n }\n\n q.push(_link(opts))\n end\n\n if @data.metadata_options\n metadata_options = \"#{@name}-metadata-options\"\n\n opts = {\n node: 'AWS_EC2_INSTANCE_METADATA_OPTIONS',\n id: metadata_options\n }\n\n q.push(_merge(opts))\n\n opts = {\n from_node: node,\n from_name: @name,\n to_node: 'AWS_EC2_INSTANCE_METADATA_OPTIONS',\n to_name: metadata_options,\n relationship: 'HAS_METADATA_OPTIONS',\n relationship_attributes: @data.metadata_options.to_h\n }\n\n q.push(_link(opts))\n end\n\n q\n end",
"def query\n self.class.instances.each do |instance|\n if instance.name == name || instance.name.downcase == name\n return instance.properties\n end\n end\n nil\n end",
"def list\n attrcheck = { 'compartment' => @options[:compartment] }\n @validate.validate(@options, attrcheck)\n opts = {}\n opts[:availability_domain] = @options[:availability_domain] if @options[:availability_domain]\n opts[:display_name] = @options[:display_name] if @options[:display_name]\n BmcAuthenticate.new(@options)\n request = OracleBMC::Core::ComputeClient.new\n request = request.list_instances(@options[:compartment], opts)\n request.data\n end",
"def aws_find_instance( iprops )\n if iprops[:id]\n @aws_instances.find do |r|\n r[:id] == iprops[:id] && r[:region] == iprops[:region]\n end\n else\n [ :internet_name, :internet_ip, :name ].inject( nil ) do |found, key|\n found || @aws_instances.find { |r| r[key] == iprops[key] }\n end\n end\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 PoolParty::PoolPartyError.create(\"DslMethodCall\", \"You must call instances with either a number, a range or a hash (for a list of nodes)\")\n end\n end",
"def role_select\n @@Roles.list\n end",
"def aws_import_instances\n\n instances = []\n\n aws_regions.each do |region|\n ec2 = AWS::EC2.new.regions[ region ]\n\n found = ec2.instances.map do |inst|\n next unless [ :running, :pending ].include?( inst.status )\n aws_instance_to_props( region, inst )\n end\n\n instances += found.compact\n end\n\n @aws_instances = instances\n end",
"def get_instance_by_number(i=0, list = remote_instances_list) \n name = ((i.nil? || i.zero?) ? \"master\" : \"node#{i}\")\n list.select {|i| i.name == name }.first\n end",
"def active_instances\n Instance.running_for_laboratory(self)\n end",
"def instances\n @instances ||= init_instances.reject(&:terminated?)\n end",
"def vm_instances\n @conn.vminstances\n end",
"def index\n\n credentials = Aws::Credentials.new('AKIAJ2JD2EKKFVDSR37A', 'cnZUnzuyYPqUevEPb045VJUnW55VR+rUCQrplzd/')\n ec2 = Aws::EC2::Client.new(\n region: \"us-east-1\",\n credentials: credentials\n )\n #i = ec2.instances.create(:image_id => \"ami-e3106686\")\n resp = ec2.run_instances({\n dry_run: true,\n image_id: \"ami-e3106686\", # required\n min_count: 1, # required\n max_count: 1, # required\n instance_type: \"t1.micro\", # accepts t1.micro, m1.small, m1.medium, m1.large, m1.xlarge, m3.medium, m3.large, m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge, t2.micro, t2.small, t2.medium, t2.large, m2.xlarge, m2.2xlarge, m2.4xlarge, cr1.8xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge, hi1.4xlarge, hs1.8xlarge, c1.medium, c1.xlarge, c3.large, c3.xlarge, c3.2xlarge, c3.4xlarge, c3.8xlarge, c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, cc1.4xlarge, cc2.8xlarge, g2.2xlarge, cg1.4xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge, r3.8xlarge, d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge\n placement: {\n tenancy: \"default\", # accepts default, dedicated\n },\n\n block_device_mappings: [\n {\n virtual_name: \"String\",\n device_name: \"String\",\n ebs: {\n snapshot_id: \"String\",\n volume_size: 1,\n delete_on_termination: true,\n volume_type: \"standard\", # accepts standard, io1, gp2\n iops: 1,\n encrypted: true,\n },\n\n },\n ],\n monitoring: {\n enabled: true, # required\n },\n disable_api_termination: true,\n instance_initiated_shutdown_behavior: \"stop\", # accepts stop, terminate\n network_interfaces: [\n {\n delete_on_termination: true,\n private_ip_addresses: [\n {\n private_ip_address: \"172.31.2.177\", # required\n primary: true,\n },\n ],\n secondary_private_ip_address_count: 1,\n associate_public_ip_address: true,\n },\n ],\n ebs_optimized: true,\n })\n @ec2_instances = Ec2Instance.all\n end",
"def roles\n ::Syncano::QueryBuilder.new(self, ::Syncano::Resources::Role)\n end",
"def select(*args)\n call_query_method(:select, *args)\n end",
"def find_instances(tags)\n attempts = 0\n begin\n ec2.servers.select { |server| tags.reject { |k,v| server.tags[k] == tags[k] }.empty? }\n rescue Excon::Errors::ServiceUnavailable\n sleep 5\n attempts += 1\n return [] if attempts == 5\n retry\n end\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 chef_role(name, query = \"*:*\", options = {})\n # TODO: This can only get a node's top-level attributes. Make it get nested\n # ones.\n attr = options.delete(:attribute) || :ipaddress\n nodes = Chef::Search::Query.new.search(:node, query)[0].map {|n| n[attr] }\n role name, *nodes, options\n nodes\n end",
"def hosts(opts)\n ::ApplicationRecord.connection_pool.with_connection {\n # If we have the ID, there is no point in creating a complex query.\n if opts[:id] && !opts[:id].to_s.empty?\n return Array.wrap(Mdm::Host.find(opts[:id]))\n end\n\n wspace = Msf::Util::DBManager.process_opts_workspace(opts, framework)\n\n conditions = {}\n conditions[:state] = [Msf::HostState::Alive, Msf::HostState::Unknown] if opts[:non_dead]\n conditions[:address] = opts[:address] if opts[:address] && !opts[:address].empty?\n\n if opts[:search_term] && !opts[:search_term].empty?\n column_search_conditions = Msf::Util::DBManager.create_all_column_search_conditions(Mdm::Host, opts[:search_term])\n tag_conditions = Arel::Nodes::Regexp.new(Mdm::Tag.arel_table[:name], Arel::Nodes.build_quoted(\"(?mi)#{opts[:search_term]}\"))\n search_conditions = column_search_conditions.or(tag_conditions)\n wspace.hosts.where(conditions).where(search_conditions).includes(:tags).references(:tags).order(:address)\n else\n wspace.hosts.where(conditions).order(:address)\n end\n }\n end",
"def describe_instances\n return { reservations: [] } unless configured?\n\n @client.describe_instances.to_h\n end",
"def do_query(query_tags, options = {})\n query_tags = [query_tags] if query_tags.is_a?(String)\n Chef::Log.info \"Tagged query_tags: #{query_tags}\"\n match_all = options.fetch(:match_all, false)\n resources = api_client.tags.by_tag(resource_type: 'instances', tags: query_tags, match_all: match_all)\n Chef::Log.info \"Tagged resources: #{resources}\"\n\n tags_hash = {}\n if resources.first\n links = resources.first.links\n if links\n links.each do |link|\n Chef::Log.info \"Tagged Resource Cloud:#{link['href'].split('/')[0..3].join('/')}\"\n next unless api_client.get_instance.show.cloud.href == link['href'].split('/')[0..3].join('/')\n next unless api_client.resource(link['href']).state == 'operational'\n resource_tags = api_client.tags.by_resource(resource_hrefs: [link['href']]) # .first.tags\n tags_hash[link['href']] = {\n 'tags' => resource_tags.first.tags.map { |tag| tag['name'] },\n }\n end\n end\n end\n tags_set_array = []\n tags_hash.values.each do |value|\n tags_set_array << ::MachineTag::Set.new(value['tags'])\n end\n tags_set_array\n end",
"def select(*args, **options)\n call_query_method(:select, *args, **options)\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 instances_from_matches\n return single_class_results if one_class\n \n groups = results[:matches].group_by { |match|\n match[:attributes][\"class_crc\"]\n }\n groups.each do |crc, group|\n group.replace(\n instances_from_class(class_from_crc(crc), group)\n )\n end\n \n results[:matches].collect do |match|\n groups.detect { |crc, group|\n crc == match[:attributes][\"class_crc\"]\n }[1].compact.detect { |obj|\n obj.primary_key_for_sphinx == match[:attributes][\"sphinx_internal_id\"]\n }\n end\n end",
"def select_availability_zone(volumes, resource_pool_az)\n @az_provider.select(volumes, resource_pool_az)\n end",
"def select(*args)\n Criteria.new(:all, self).select(*args)\n end",
"def web_servers; machines_by_role('web'); 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.48158267",
"0.48138258",
"0.47898638",
"0.47835544",
"0.47757608",
"0.47713852",
"0.4759999",
"0.47447026",
"0.47283486",
"0.47213268",
"0.4709381",
"0.47083285",
"0.46975303",
"0.4654118",
"0.46326733",
"0.46099192",
"0.46043643",
"0.4590794",
"0.4576475",
"0.45603004",
"0.45543686",
"0.45515054",
"0.4547057",
"0.45422816",
"0.45338368",
"0.45335642",
"0.4525888",
"0.45254076",
"0.45213577",
"0.45006746",
"0.446855",
"0.44593617",
"0.4458779",
"0.44511876",
"0.44320533",
"0.4422172",
"0.44197598",
"0.44164446",
"0.4408486",
"0.4405874",
"0.4405874",
"0.43968105",
"0.43945456",
"0.43907425",
"0.43891007",
"0.4387214",
"0.4382709",
"0.43818912",
"0.43800944",
"0.43679014",
"0.43599477",
"0.43484876",
"0.43430865",
"0.4338885",
"0.43366432",
"0.43344873",
"0.43341997",
"0.43258438",
"0.4324227",
"0.43240932",
"0.43218035",
"0.43196845",
"0.43160468",
"0.43063828",
"0.42940167",
"0.42918256",
"0.42916512",
"0.4288688",
"0.42875138",
"0.42844665"
] | 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",
"def vms\n vms = object.vms.select do |vm|\n !current_user ||\n current_user.id == vm.user.id ||\n current_user.admin? ||\n (current_user.lead? && vm.project.users.include?(current_user)) ||\n (current_user.dev? && vm.project.users.include?(current_user) && vm.is_jenkins)\n end\n vms.map { |v| v.id }\n end",
"def people_with_the_role role\n mask = Person.mask_for_role(role)\n AdminDefinedRoleProject.where(role_mask: mask,project_id: self.id).collect{|r| r.person}\n end",
"def web_servers; machines_by_role('web'); end",
"def select(&block)\n new_instance_with_inherited_permitted_status(@parameters.select(&block))\n end",
"def extract_master_instance_options(options)\n extract_instance_options('master-', options)\n end",
"def shared\n role_values = Role.where(plan: self).where(Role.not_creator_condition).any? \n end",
"def roles\n return proposed_snapshot.roles if proposed? \n return active_snapshot.roles if active?\n []\n end",
"def roles\n Role.all.select do |role|\n role.movie == self\n end\n end",
"def get_instance_reservations(filters = {})\n AWS.memoize do\n @ec2.regions['us-west-1'].reserved_instances.select do |ins|\n filters.reduce(true) do |memo, filter_kvp|\n memo && ins.send(filter_kvp[0]) == filter_kvp[1]\n end\n end\n end\n end",
"def master_db; machine_by_role('master_db'); 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 select\n execute_only(:select)\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 filter_instances(instances, filters)\n filtered = instances\n # Include only instances that match all filters.\n filters.each do |filter|\n key, value = filter.first\n filtered = filtered.select { |i|\n found_tag = i.tags.find { |t|\n t.key == key.to_s\n }\n next if found_tag.nil?\n\n found_tag.value == value\n }\n end\n filtered\n end",
"def build_instances\n filter_instances.map.with_index do |(suite, platform), index|\n new_instance(suite, platform, index)\n end\n end",
"def app_servers\n return super unless CDO.chef_managed\n require 'aws-sdk'\n servers = Aws::EC2::Client.new.describe_instances(\n filters: [\n {name: 'tag:aws:cloudformation:stack-name', values: [CDO.stack_name]},\n {name: 'tag:aws:cloudformation:logical-id', values: ['Frontends']},\n {name: 'instance-state-name', values: ['running']}\n ]\n ).reservations.map(&:instances).flatten.map {|i| [\"fe-#{i.instance_id}\", i.private_dns_name]}.to_h\n servers.merge(super)\n end",
"def get_settings_by_role(role, settings, includeme=true, options={})\n options = {\n :search_string => role,\n :include_me => include_me,\n :order => [:role],\n :safe_deref => settings,\n :current_node => nil,\n :one_or_all => :one\n }.merge(options)\n opsit_search(options)\n end",
"def vms(range, groups)\n vms = []\n # load specific batch\n vm_pool = load_vm_pool\n return nil if vm_pool.count == 0\n\n @log.debug(\"Searching for vms based on range: #{range} and groups: #{groups}.\")\n vm_pool.each do |vm|\n unless vm['ID']\n @log.error('Skipping a record without an ID present.')\n next\n end\n\n # skip unsuitable virtual machines\n next unless want?(vm, range, groups)\n\n vms << vm['ID'].to_i\n end\n\n @log.debug(\"Selected vms: #{vms}.\")\n vms\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",
"def get_all_instances(systems,code = @code)\n return [] unless code.is_a?(Array)\n return code.reduce([]) do |ar,sub|\n ar + get_all_instances(systems,sub)\n end + (code.select { |sub| is_instance?(sub,systems) }).to_a\n end",
"def monitors_by_role(info, roles)\n roles = Array(roles).map(&:to_s)\n info.find_all { |_, monitor| roles.include?(monitor[:role].to_s) }\nend",
"def filter_select(match, metadata)\n # Break on container_name mismatch\n unless match.hosts.empty? || match.hosts.include?(metadata[:host])\n return false\n end\n # Break on host mismatch\n unless match.container_names.empty? || match.container_names.include?(metadata[:container])\n return false\n end\n # Break if list of namespaces is not empty and does not include actual namespace\n unless match.namespaces.empty? || match.namespaces.include?(metadata[:namespace])\n return false\n end\n\n match_labels(metadata[:labels], match.labels)\n end",
"def get_vms_selector(deployment_name, ids: [])\n {\n \"Deployment\" => {\n \"Name\" => deployment_name,\n \"Limit\" => \"100%\"\n },\n \"ID\" => { \"Values\" => ids }\n }\n end",
"def extract_slave_instance_options(options)\n extract_instance_options('slave-', options)\n end",
"def filtered_params\n %i[roles provider_type]\n end",
"def app_roles\n return @app_roles\n end",
"def select(*args)\n Criteria.new(:all, self).select(*args)\n end",
"def multiple_application_environment_options\n app_ids = params[:app_ids]\n app_ids = [app_ids].flatten\n unless app_ids.blank?\n options = \"\"\n App.where(:id => app_ids).order('apps.name asc').each do |app|\n apply_method = current_user.has_global_access? ? nil : \"app_environments_visible_to_user\"\n options += \"<optgroup class='app' label='#{app.name}'>\"\n options += options_from_model_association(app, :application_environments, :apply_method => apply_method)\n options += \"</optgroup>\"\n end\n render :text => options\n else\n render :nothing => true\n end\n end",
"def roles\n groups.find(:all, :conditions => {:context => Group::GroupType::ROLE})\n end",
"def select(params = {})\n if params.has_key?(:path)\n path_regex = params[:path]\n path_regex = Regexp.new(path_regex.to_s) unless path_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && path_regex.match(agent.config_path) }\n notify(:msg => \"[#{@name}] Selecting all services for path #{path_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:type)\n type_regex = params[:type]\n type_regex = Regexp.new(type_regex.to_s) unless type_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && type_regex.match(agent.type) }\n notify(:msg => \"[#{@name}] Selecting all services of type #{type_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:core_type)\n core_type_regex = params[:core_type]\n core_type_regex = Regexp.new(core_type_regex.to_s) unless core_type_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && core_type_regex.match(agent.core_type) }\n notify(:msg => \"[#{@name}] Selecting all services of core type #{core_type_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:host) || params.has_key?(:hosts)\n host_names = arrayify(params[:host]) & arrayify(params[:hosts])\n selector = lambda {|agent| host_names.include?(agent.host) }\n notify(:msg => \"[#{@name}] Selecting all services for hosts #{host_names.inspect}\",\n :tags => [:galaxy, :trace])\n else\n notify(:msg => \"[#{@name}] Selecting all services\",\n :tags => [:galaxy, :trace])\n end\n command = ::Galaxy::Commands::ShowCommand.new([], @galaxy_options)\n command.report = GalaxyGatheringReport.new(@environment)\n agents = command.select_agents({})\n agents.each { |agent| agent.proxy = ::Galaxy::Transport.locate(agent.url) if agent.url }\n command.execute(agents)\n command.report.results.select {|result| selector.nil? || selector.call(result) }\n end",
"def index\n client_application_id = current_user.client_application_id.to_s\n @roles = Role.where(client_application_id: client_application_id)\n end",
"def build_roles(role)\n results = @machines.reject { |m| [*m['role']].grep(role).empty? }\n rolesarray = []\n results.each do |machine|\n rolesarray.push(machine['name'])\n end\n rolesarray\n end",
"def select(cluster, tags = nil)\n\n end",
"def roles_for_vp_and_sysadmin\n\t\tvp_and_sysadmin_roles = []\n\t\tfor role in Role.all\n\t\t\tif role.name.eql?(\"System Admin\") || role.name.eql?(\"VP of Finance\") \n\t\t\t\tvp_and_sysadmin_roles << role\n\t\t\tend\n\t\tend\n\t\treturn vp_and_sysadmin_roles\n\tend",
"def kube_custom_search(context, term)\n cluster_id = node[cookbook_name]['cluster_id']\n ret_val = []\n filter = { 'name' => ['fqdn'], 'ip' => ['ipaddress'] }\n # puts \"search(#{context}, #{term}, filter_result: #{filter})\"\n search(context, term, filter_result: filter).each do |inst|\n raw = \"Raw search returns #{inst.inspect}\"\n # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n raise raw + \"\\n\" + err('no_master') if inst['name'].nil? && term == \"role:k8s_master_#{cluster_id}\"\n raise raw + \"\\n\" + err('no_minion') if inst['name'].nil? && term == \"role:k8s_minion_#{cluster_id}\"\n ret_val.push(name: inst['name'].downcase, ip: inst['ip'])\n end\n if ret_val.empty?\n abort(err('no_master')) if term == \"role:k8s_master_#{cluster_id}\"\n abort(err('no_minion')) if term == \"role:k8s_minion_#{cluster_id}\"\n end\n ret_val # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n end",
"def select(*args)\n @results = nil\n except(:select)\n @builder = builder.select(*args)\n self\n end",
"def where(*cond)\n return super if block_given?\n\n filters_per_role = self.cache_get(:filters_per_role) || init_filters([])\n\n Array.wrap(cond).each do |condition|\n filters = case condition\n when Hash\n hash_condition_to_filters(condition)\n when Sequel::SQL::BooleanExpression\n boolean_expression_to_filters(condition)\n else\n raise \"Unsupported condition type: #{condition.class}\"\n end\n\n append_filters(filters_per_role, filters)\n end\n\n dataset = self.from(RoleDataset.build(filters_per_role))\n dataset.cache_set(:filters_per_role, filters_per_role)\n dataset\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 existing_instances(filter=\"\")\r\n instances_raw = `ps xao pid,pgid,command | grep '#{process_name} #{name_grep_string} #{filter}' | grep -iv #{Process.pid} | awk '{print $1 \"\\t\" $2 \"\\t\" $3}'`\r\n instances_raw.split(\"\\n\").map do |row|\r\n pid, group, command = row.split(\"\\t\")\r\n ProcessInfo.new(pid.to_i, group.to_i, command)\r\n end\r\n end",
"def things_with_role(thing, role)\n require 'wavefront-sdk/search'\n wfs = Wavefront::Search.new(mk_creds, mk_opts)\n wfs.search(thing,\n conds_to_query([\"roles~#{role}\"]),\n limit: :all, sort_field: :id)\n end",
"def filtering_params(params)\n params.slice(:role, :query)\n end",
"def list_instances token: nil\n instances.list_instances parent: project_path, page_token: token\n end",
"def aws_read_instances\n list = JSON.parse( IO.read( aws_instances_json ), :symbolize_names => true )\n list.each do |inst|\n inst[:roles] = ( inst[:roles] || [] ).map { |r| r.to_sym }\n end\n @aws_instances = list.sort { |p,n| p[:name] <=> n[:name] }\n end",
"def eks_map(server_config_map)\n YAML.load(server_config_map.dig('data', 'mapRoles'))\n .select { |r| r.fetch('rolearn').include?('NodeInstanceRole') }\n end",
"def app_servers\n return super unless chef_managed\n require 'aws-sdk-ec2'\n servers = Aws::EC2::Client.new.describe_instances(\n filters: [\n {name: 'tag:aws:cloudformation:stack-name', values: [stack_name]},\n {name: 'tag:aws:cloudformation:logical-id', values: ['Frontends']},\n {name: 'instance-state-name', values: ['running']}\n ]\n ).reservations.map(&:instances).flatten.map {|i| [\"fe-#{i.instance_id}\", i.private_dns_name]}.to_h\n servers.merge(self[:app_servers])\n end",
"def active_instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving running instances\"\n fetch_instances ['ACTIVE']\n end",
"def roles_for_select\n Role.all.select {|role| can? :add_user, role }.sort.map {|r| [r.name.titleize, r.id] }\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 accessible_admin_sets_with_active_workflow\n accessible_admin_sets.select { |admin_set_id| Hyrax::PermissionTemplate.find_by(source_id: admin_set_id)&.active_workflow.present? }\n end",
"def build_selectors\n temp_release_docs.uniq(&:kubernetes_role_id).flat_map(&:build_selectors).uniq\n end",
"def role_selection\n \"#{name}\"\n end",
"def allows_vpc_and_non_vpc_instance_memberships\n data[:allows_vpc_and_non_vpc_instance_memberships]\n end",
"def roles(host)\n roles = [ \"network\" ]\n case host\n when /^node/\n roles << \"compute\"\n when /^login/\n roles << \"login\"\n when /^master/\n roles << \"master\"\n when /^nfs/\n roles << \"nfsserver\"\n end\n roles\nend",
"def acl_select\n select_opts = []\n self.full_acl.each do |userId|\n select_opts << [User.get(userId).username, userId]\n end\n select_opts\n end",
"def only(*args); add_hash_option(:only, args, :only_engines); end",
"def kitchen_instances(regexp, config)\n instances = Kitchen::Config.new(config).instances\n return instances if regexp.nil? || regexp == 'all'\n instances.get_all(Regexp.new(regexp))\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 selection(params)\n\n\t\t@driver = Jobs::ImageReconciliation::ImageDataset.joins(:visit)\n\t\t\t\t\t\t.joins(\"LEFT JOIN appointments ON appointments.id = visits.appointment_id\")\n\t\t\t\t\t\t.joins(\"LEFT JOIN vgroups ON vgroups.id = appointments.vgroup_id\")\n\t\t\t\t\t\t.joins(\"LEFT JOIN scan_procedures_vgroups ON vgroups.id = scan_procedures_vgroups.vgroup_id\")\n\t\t\t\t\t\t.where(\"scan_procedures_vgroups.scan_procedure_id in (#{params[:scan_procedure_white_list].join(\",\")})\")\n\t\t\t\t\t\t.where(\"scan_procedures_vgroups.scan_procedure_id not in (#{params[:scan_procedure_black_list].join(\",\")})\")\n\n\tend",
"def get_all_roles_nodes\n result = search(:node, \"chef_environment:#{node.chef_environment}\")\n if result.any? { |x| x['hostname'] == node['hostname'] }\n result.map! { |x| x['hostname'] == node['hostname'] ? node : x }\n else\n result.push(node)\n end\n return result.sort! { |a, b| a['hostname'] <=> b['hostname'] }\nend",
"def apply_instance_filters(ds)\n instance_filters.inject(ds){|ds1, i| ds1.where(*i[0], &i[1])}\n end",
"def filter_by attributes\n\n all.select { |item| matches? item, attributes }\n\n end",
"def chef_role(name, query = \"*:*\", options = {})\n # TODO: This can only get a node's top-level attributes. Make it get nested\n # ones.\n attr = options.delete(:attribute) || :ipaddress\n nodes = Chef::Search::Query.new.search(:node, query)[0].map {|n| n[attr] }\n role name, *nodes, options\n nodes\n end",
"def show\n @drivers = User.with_role :driver\n end",
"def build_matches rule_selectors: []\n exclude_default_roles = ENV.fetch(\n 'RISK_RULE_QUERY_EXCLUDE_DEFAULT_ROLES', RISK_RULE_QUERY_EXCLUDE_DEFAULT_ROLES\n ).to_s == 'true'\n\n role_attrs = exclude_default_roles ? \"{is_default: 'false'}\" : ''\n\n rule_selectors.collect.with_index do |selector, index|\n rule_selector = selector.map do |k,v|\n \"#{k}: '#{v}'\"\n end.join(', ')\n\n \"MATCH (ns:Namespace)<-[:SCOPE]-(ro#{index}:Role #{role_attrs})<-[:GRANT]-(:Rule {#{rule_selector}})\"\n end\n end",
"def admin_labs\n self.roles.where(name: \"admin\", resource_type: \"Lab\")\n end",
"def employees\n Employee.all.select{|employee| employee.role == self}\n \n end",
"def clean_instances(allowed_age, whitelist=nil)\n deleted = []\n undeleted = []\n @gate.instances.each do |instance|\n if is_opsworks_instance instance\n undeleted << instance.inspect\n else\n if expired(instance.launch_time,allowed_age) and instance.status != :terminated\n begin\n if whitelisted(instance.instance_id, whitelist)\n undeleted << instance.inspect\n else\n instance.api_termination_disabled=false\n instance.delete\n deleted << instance.inspect\n end\n rescue AWS::Errors::Base => e\n undeleted << instance.inspect\n end\n end\n end\n end\n return deleted, undeleted\n end",
"def vms\n vms = []\n if current_user.admin?\n vms = object.vms\n elsif current_user.lead?\n vms = object.vms.select { |vm| vm.project.users.include?(current_user) }\n elsif current_user.dev?\n vms = object.vms.select { |vm| vm.user.id == current_user.id || vm.is_jenkins }\n else\n vms = object.vms.select { |vm| vm.user.id == current_user.id }\n end\n vms.map { |v| v.id }\n end",
"def vms\n vms = []\n if current_user.admin?\n vms = object.vms\n elsif current_user.lead?\n vms = object.vms.select { |vm| vm.project.users.include?(current_user) }\n elsif current_user.dev?\n vms = object.vms.select { |vm| vm.user.id == current_user.id || vm.is_jenkins }\n else\n vms = object.vms.select { |vm| vm.user.id == current_user.id }\n end\n vms.map { |v| v.id }\n end",
"def get_classes_from_role(role, options)\n certname = options[:certname_for_facts]\n global_config = get_global_config\n global_config = find_facts(certname).merge(global_config)\n get_classes_per_scenario(global_config, role)\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.46213374",
"0.46175388",
"0.46151605",
"0.46143118",
"0.46098623",
"0.4595187",
"0.4589531",
"0.45685986",
"0.45392454",
"0.45348385",
"0.4523278",
"0.450376",
"0.45013824",
"0.44948715",
"0.44882703",
"0.44865787",
"0.44862813",
"0.44694725",
"0.4467281",
"0.44611973",
"0.44587588",
"0.44580254",
"0.4454489",
"0.44484782",
"0.44466525",
"0.4435137",
"0.44349343",
"0.44169623",
"0.44048837",
"0.44037142",
"0.44010282",
"0.4394002",
"0.4393998",
"0.43936154",
"0.43837926",
"0.43790486",
"0.43781427",
"0.43736458",
"0.43686908",
"0.436392",
"0.4363218",
"0.43544748",
"0.43540514",
"0.43484896",
"0.43474376",
"0.434598",
"0.43310332",
"0.43301862",
"0.4325457",
"0.43176952",
"0.4317546",
"0.43118876",
"0.43070725",
"0.43056747",
"0.42975563",
"0.42962152",
"0.42956257",
"0.42932558",
"0.4281362",
"0.42787585",
"0.42786124",
"0.42733017",
"0.427221",
"0.4270711",
"0.42609602",
"0.42579994",
"0.4249497",
"0.42483518",
"0.42483518",
"0.42408535"
] | 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",
"def create\n @instance = Instance.new(params[:instance])\n\n respond_to do |format|\n if @instance.save\n\n system(\"ssh root@#{CloudGui::Application.config.hypervisor_ip} \\\"exec /data/cloud/scripts/provision.sh #{params[:instance][:cpus]} #{params[:instance][:memory]} #{params[:instance][:baseimage]} 2>&1 | tee /data/cloud/logs/cloud_gui.log\\\"\")\n\n format.html { redirect_to @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 environment(name, options = {})\n @environments << Environment.new(name, options)\n end",
"def launch\n puts \"==> Creating EC2 instance...\"\n\n @instance = @aws_ec2.instances.create( @config.env.merge( { \"key_name\" => key_name, \"security_groups\" => [security_group_name] } ) )\n @instance.tag(\"environment\", {value: @config.environment})\n\n while @instance.status == :pending\n print \".\"\n sleep 2\n end\n\n # Sleep for 30 more seconds\n 15.times do\n print \".\"\n sleep 2\n end\n puts \".\" # new line\n\n puts \"==> Successfully created EC2 instance '#{@instance.id}'\"\n end",
"def set_instance\n if Instance.exists?(params[:id])\n @instance = Instance.find(params[:id])\n else\n render json: { error: 'No se ejecuto nada con ese id', codigo: 707 }\n end\n end",
"def add_chef_object(container_name, requestor, object_json)\n post(api_url(\"/#{container_name}\"), requestor, :payload => object_json)\n end",
"def create\n @app_instance = AppInstance.new(app_instance_params)\n\n respond_to do |format|\n if @app_instance.save\n format.html { redirect_to @app_instance, notice: 'App instance was successfully created.' }\n format.json { render action: 'show', status: :created, location: @app_instance }\n else\n format.html { render action: 'new' }\n format.json { render json: @app_instance.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create(name)\n url = prefix + \"create\" + \"&name=#{name}\"\n return response(url)\n end",
"def create\n ec2 = self.class.new_ec2(@resource.value(:user), @resource.value(:password))\n group = @resource.value(:name)\n begin\n ec2.describe_security_groups({:group_name => group})\n rescue Exception => e\n ec2.create_security_group({ \n :group_name => group,\n :group_description => @resource.value(:desc)\n })\n end\n # if instance in that security group exists, start it\n # otherwise just create a new instance \n ec2.run_instances(\n { :image_id => @resource.value(:image),\n # security groups\n :security_group => group,\n :instance_type => @resource.value(:type)\n })\n end",
"def create(name)\n url = prefix + \"create\" + \"&name=#{name}\"\n return response(url)\n end",
"def insert_entry(params)\n Entry.create(params)\n end",
"def create\n @instance = Instance.new(params[:instance])\n\n respond_to do |format|\n if @instance.save\n format.html { redirect_to(@instance, :notice => 'Instance was successfully created.') }\n format.xml { render :xml => @instance, :status => :created, :location => @instance }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @instance.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def run_instance options = {}\n instances = InstanceCollection.new(:config => config)\n instances.create(options.merge(:image => self))\n end",
"def create_instances(count)\n fail DTK::Error::Usage, \"Attribute 'admin_state' cannot be set to powered_off if node not created\" if admin_state_powered_off?\n aws_api_operation(:create).create_instances(count)\n end",
"def create\n megam_rest.post_appreq(to_hash)\n end",
"def create_instance(credentials, image_id, opts)\n new_vapp = nil\n vapp_opts = {} #assemble options to pass to Fog::Terremark::Real.instantiate_vapp_template\n terremark_hwp = hardware_profiles(credentials, {:name => 'default'}).first #sanity check values against default\n name = opts[:name]\n if not name\n name = \"inst#{Time.now.to_i}\"\n end\n if name.length > USER_NAME_MAX\n raise \"Parameter name must be #{USER_NAME_MAX} characters or less\"\n end\n unless ( (terremark_hwp.include?(:cpu, opts[:hwp_cpu].to_i)) &&\n (terremark_hwp.include?(:memory, opts[:hwp_memory].to_i)) ) then\n raise Deltacloud::Exceptions::ValidationFailure.new(\n StandardError.new(\"Error with cpu and/or memory values. you said cpu->#{opts[:hwp_cpu]} and mem->#{opts[:hwp_memory]}\")\n )\n end\n vapp_opts['cpus'] = opts[:hwp_cpu]\n vapp_opts['memory'] = opts[:hwp_memory]\n safely do\n terremark_client = new_client(credentials)\n#######\n#FIXME# what happens if there is an issue getting the new vapp id? (eg even though created succesfully)\n#######\n vapp_id = terremark_client.instantiate_vapp_template(name, image_id, vapp_opts).body['href'].split('/').last\n new_vapp = terremark_client.get_vapp(vapp_id)\n return convert_instance(new_vapp, terremark_client, credentials.user) #return an Instance object\n end\n end",
"def add(key, value, ttl = nil, req_options = nil)\n perform(:add, key, value, ttl_or_default(ttl), req_options)\n end",
"def add(name, key)\n issueKey_test(key)\n fetch({:method => :post, :body => name, :body_override => true, :parent => parent_name, :parent_key => key})\n end",
"def addCluster(args={})\n raise(ArgumentError, \"Arguments cannot be empty\") if args.empty?\n name = args[NAME] if args[NAME]\n raise(ArgumentError, \"Name of the cluster should be specified\") if name.empty?\n address = args[ADDRESS] if args[ADDRESS]\n raise(ArgumentError, \"Address of the cluster should be specified\") if address.empty?\n @crosssiteadmin.addCluster(name.to_java.to_s, address.to_java.to_s)\n end",
"def create\n @execution_environment = ExecutionEnvironment.new(execution_environment_params)\n\n respond_to do |format|\n if @execution_environment.save\n format.html { redirect_to @execution_environment, notice: 'Execution environment was successfully created.' }\n format.json { render :show, status: :created, location: @execution_environment }\n else\n format.html { render :new }\n format.json { render json: @execution_environment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def posts_add(post_or_values)\n params = prepare_param_post(post_or_values).to_params\n response = request(API_PATH_POSTS_ADD, params)\n parse_and_eval_execution_response(response.body)\n end",
"def create_instances request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n uri, body, query_string_params = transcode_create_instances_request request_pb\n response = @client_stub.make_post_request(\n uri: uri,\n body: body,\n params: query_string_params,\n options: options\n )\n result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, response if block_given?\n result\n end",
"def start_and_create_instances(num=1, user_data=nil)\n logger.info \"ENTERING DELAYED JOB\"\n begin\n new_instances = run_spot_instances(num, user_data)\n new_instances.each do |i|\n temp = Instance.create_from_aws_hash(i)\n temp.user_data = user_data\n temp.state = 'launched'\n temp.save\n end\n logger.info \"Started and saved #{num} #{ami_id} instances.\"\n EventLog.info \"Started and saved #{num} #{ami_id} instances.\"\n rescue Exception => e\n logger.error \"Caught exception when trying to start #{num} #{ami_id} instances!: #{e.message} #{e.backtrace}\"\n EventLog.error \"Caught exception when trying to start #{num} #{ami_id} instances!: #{e.message} #{e.backtrace}\"\n end\n end",
"def create\n @instance_type = InstanceType.new(instance_type_params)\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 action: 'show', 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 create(*args)\n post(*args)\n end",
"def create(*args)\n post(*args)\n end",
"def register_new_agent_with_instance (agent_instance)\n throw \"not an aws instance!\" if !agent_instance.is_a?AwsInstance\n url_string=\"http://#{@server_address}:#{@server_port}/agents\"\n url=URI(url_string)\n req = Net::HTTP::Post.new(url)\n agent_instance.notify \"registering new agent\"\n res=Net::HTTP.start(url.hostname,url.port) do |http|\n req.basic_auth @username,@password\n req.body=\"name=#{agent_instance.name}&ip=#{agent_instance.aws_instance_data.private_ip_address}\"\n http.request(req)\n end\n if res.code.to_i <=399\n agent_instance.notify \"registered ok! getting key\"\n client_data=JSON.parse(res.body)\n client_id=client_data['data']\n url_string=\"http://#{@server_address}:#{@server_port}/agents/#{client_id}/key\"\n url=URI(url_string)\n req = Net::HTTP::Get.new(url)\n res=Net::HTTP.start(url.hostname,url.port) do |http|\n req.basic_auth @username,@password\n http.request(req)\n end\n if res.code.to_i<=399\n agent_instance.notify \"key for agent obtained! installing on agent...\"\n client_key_data=JSON.parse(res.body)\n ssh_command=\"sudo echo \\\"y\\\" | sudo /var/ossec/bin/manage_agents -i #{client_key_data['data']}\"\n s3_client=Helpers.create_aws_S3_client\n agent_instance.notify \"loading configuration for agent...\"\n resp=s3_client.get_object({\n bucket: \"btrz-aws-automation\",\n key: \"ossec/agent/ossec.conf\"\n })\n xml_content=resp.body.read\n noko_xml=Nokogiri::XML(xml_content)\n noko_xml.css(\"ossec_config client server-ip\").first.content=@private_server_address\n agent_instance.notify \"deploying configuration to agent, server ip=#{@private_server_address}\"\n agent_instance.upload_data_to_file noko_xml.root.to_s,\"/home/ubuntu/ossec.conf\"\n agent_instance.notify \"removing old keys\"\n agent_instance.run_ssh_command \"sudo rm /var/ossec/etc/client.keys\"\n agent_instance.notify \"updating configuration\"\n agent_instance.run_ssh_command \"sudo cp /home/ubuntu/ossec.conf /var/ossec/etc/ossec.conf && sudo chown root:ossec /var/ossec/etc/ossec.conf && sudo chmod 640 /var/ossec/etc/ossec.conf\"\n answer=agent_instance.run_ssh_command ssh_command\n agent_instance.notify \"restarting agent...\"\n agent_status=agent_instance.run_ssh_command \"sudo /var/ossec/bin/ossec-control restart\"\n if (answer.index( \"Added\") !=nil and agent_status.index( \"Completed\")!=nil)\n return true,{\n agent_key: client_key_data['data'],\n answer: answer,\n status: agent_status,\n }\n else\n return false,{\n agent_key: client_key_data['data'],\n answer: answer,\n status: agent_status,\n }\n end\n else\n return false, res.code\n end\n else\n agent_instance.notify \"authentication error connecting to server #{@server_address} in #{@environment}\"\n return false, res.code\n end\n end",
"def add(flavor_params)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'flavorParams', flavor_params);\n\t\t\tclient.queue_service_action_call('flavorparams', 'add', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend",
"def add(name, description, ingredients, instructions)\n recipe = Bukaresep::Recipe.new(name, description, ingredients, instructions)\n\n return false unless recipe.valid?\n\n @service.add(recipe)\n end",
"def new_run(name, options = {})\n options[:basic_auth] = @auth\n options[:body] = {\n run: {\n name: name.to_s,\n suite_ids: [@test_lodge_suite] \n }\n }\n puts options.to_s\n self.class.post('/projects/id/runs.json', options)\n end",
"def add_user(name, value)\n self.class.post(\"/users/#{name}\",\n body: value,\n headers: {\n 'Content-Type' => 'application/json; charset=UTF-8',\n Connection: 'keep-alive',\n Accept: 'application/json, text/plain, */*'\n })\n end",
"def spin_up_instance ami_name, vpc_id, key_name, security_group_id, subnet_id, instance_type = \"t2.micro\"\n resp = client.run_instances({\n dry_run: false,\n image_id: ami_name, # required\n min_count: 1, # required\n max_count: 1, # required\n key_name: key_name,\n instance_type: instance_type, # accepts t1.micro, t2.nano, t2.micro, t2.small, t2.medium, t2.large, m1.small, m1.medium, m1.large, m1.xlarge, m3.medium, m3.large, m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge, m4.16xlarge, m2.xlarge, m2.2xlarge, m2.4xlarge, cr1.8xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge, r3.8xlarge, x1.16xlarge, x1.32xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge, hi1.4xlarge, hs1.8xlarge, c1.medium, c1.xlarge, c3.large, c3.xlarge, c3.2xlarge, c3.4xlarge, c3.8xlarge, c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, cc1.4xlarge, cc2.8xlarge, g2.2xlarge, g2.8xlarge, cg1.4xlarge, p2.xlarge, p2.8xlarge, p2.16xlarge, d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge\n monitoring: {\n enabled: true, # required\n },\n network_interfaces: [\n {\n subnet_id: subnet_id,\n groups: [security_group_id],\n device_index: 0,\n associate_public_ip_address: true\n }\n ],\n\n instance_initiated_shutdown_behavior: \"stop\", # accepts stop, terminate\n })\n\n error \"Error starting EC2 instance #{resp.inspect}\" if resp.instances.nil? || resp.instances.size == 0\n\n return resp.instances[0]\n end",
"def create_server_environment(environment_name, automatic = TRUE, color = \"label-blue\")\n unless self.get_server_environment(environment_name).nil?\n return nil\n else\n new_env = RestClient.post(\n \"#{@project_url}server_environments.json\",\n {\n 'server_environment' => {\n 'name' => environment_name,\n 'branch_name' => environment_name,\n 'automatic' => automatic,\n 'color_label' => color\n }\n },\n {\n 'Content-Type' => 'application/json'\n }\n )\n new_env = JSON.parse(new_env)\n return new_env['server_environment']\n end\n end",
"def add_host(name, folder = '', options = {})\n raise ArgumentError, 'host already exists' if host_exists?(name)\n \n # Lookup the IP address of the FQDN\n # TODO: catch the exception if it doesn't exist\n in_addr = Resolv.getaddress(name)\n \n params = {\n filled_in: 'edithost',\n _transid: '-1',\n host: name,\n _change_ipaddress: 'on',\n attr_ipaddress: in_addr,\n attr_tag_agent: 'cmk-agent%7Ctcp',\n attr_tag_networking: 'lan',\n save: 'Save+%26+Finish',\n folder: folder,\n mode: 'newhost',\n _do_confirm: 'yes',\n _do_actions: 'yes',\n }\n params.merge! options\n\n response = http_request(@uri + '/wato.py', params)\n raise 'An error occured' if response =~ /div class=error/\n end",
"def create\n @instance_eni = InstanceEni.new(instance_eni_params)\n\n respond_to do |format|\n if @instance_eni.save\n format.html { redirect_to @instance_eni, notice: 'Instance eni was successfully created.' }\n format.json { render :show, status: :created, location: @instance_eni }\n else\n format.html { render :new }\n format.json { render json: @instance_eni.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_application(name, options)\n debug \"Adding application #{name} to domain #{id}\"\n\n payload = {:name => name}\n options.each{ |key, value| payload[key.to_sym] = value }\n\n cartridges = Array(payload.delete(:cartridge)).concat(Array(payload.delete(:cartridges))).map do |cart|\n if cart.is_a? String or cart.respond_to? :[]\n cart\n else\n cart.url ? {:url => cart.url} : cart.name\n end\n end.compact.uniq\n\n if cartridges.any?{ |c| c.is_a?(Hash) and c[:url] } and !has_param?('ADD_APPLICATION', 'cartridges[][url]')\n raise RHC::Rest::DownloadingCartridgesNotSupported, \"The server does not support downloading cartridges.\"\n end\n\n if client.api_version_negotiated >= 1.3\n payload[:cartridges] = cartridges\n else\n raise RHC::Rest::MultipleCartridgeCreationNotSupported, \"The server only supports creating an application with a single web cartridge.\" if cartridges.length > 1\n payload[:cartridge] = cartridges.first\n end\n\n if payload[:initial_git_url] and !has_param?('ADD_APPLICATION', 'initial_git_url')\n raise RHC::Rest::InitialGitUrlNotSupported, \"The server does not support creating applications from a source repository.\"\n end\n\n options = {:timeout => options[:scale] && 0 || nil}\n rest_method \"ADD_APPLICATION\", payload, options\n end",
"def create(name=nil, options={})\n\t\tparams = {}\n\t\tparams['app[name]'] = name if name\n\t\txml(post('/apps', params)).elements[\"//app/name\"].text\n\tend",
"def create\n seth_server_rest.post_rest(\"data\", self)\n self\n end",
"def new_entry(entry)\n BatchEntries.create(\n batch_registries_id: @current_batch_registry.id,\n payload: entry.to_json,\n complete: false,\n error: false,\n current_status: 'registered'\n )\n end",
"def create_app(name, url)\n JSON.parse((@cloudvox_api[\"/applications/create.json\"].post :call_flow => {:name => name}, :agi => {:url => url}).body)\n end",
"def create\n # Avoid double provisioning: previous url would be \"/provision/new?apps[]=vtiger&organization_id=1\"\n session.delete('previous_url')\n\n @organization = current_user.organizations.to_a.find { |o| o.id && o.id.to_s == params[:organization_id].to_s }\n authorize! :manage_app_instances, @organization\n\n app_instances = []\n params[:apps].each do |product_name|\n app_instance = @organization.app_instances.create(product: product_name)\n app_instances << app_instance\n MnoEnterprise::EventLogger.info('app_add', current_user.id, 'App added', app_instance)\n end\n\n render json: app_instances.map(&:attributes).to_json, status: :created\n end",
"def attach_to_elb(instance, elb_name, subnet = nil)\n begin\n @log.info \"\"\n @log.info \"Adding to ELB: #{elb_name}\"\n elb = AWS::ELB.new\n AWS.memoize do\n unless subnet\n # Build list of availability zones for any existing instances\n zones = { }\n zones[instance.availability_zone] = instance.availability_zone\n elb.load_balancers[elb_name].instances.each do |elb_instance|\n zones[elb_instance.availability_zone] = elb_instance.availability_zone\n end\n \n # Build list of existing zones\n existing_zones = { }\n elb.load_balancers[elb_name].availability_zones.each do |zone|\n existing_zones[zone.name] = zone\n end\n \n # Enable zones\n zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.enable(zones[zone_name])\n end\n \n # Disable zones\n existing_zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.disable(existing_zones[zone_name]) unless zones.has_key?(zone_name)\n end\n end\n \n elb.load_balancers[elb_name].instances.register(instance)\n end\n rescue StandardError => bang\n @log.error \"Error adding to load balancers: \" + bang.to_s\n end\n end",
"def create_employee(name)\n response = @db.exec_params(%Q[\n INSERT INTO employees(name)\n VALUES ($1)\n RETURNING id;\n ], [name])\n\n response.first[\"id\"]\n end",
"def cron_add(type, value)\n cmd = \"{\\\"id\\\":12,\\\"method\\\":\\\"cron_add\\\",\\\"params\\\":[#{type},#{value}]}\\r\\n\"\n request(cmd)\n end",
"def create_instance(credentials, image_id, opts)\n racks = new_client( credentials )\n hwp_id = opts[:hwp_id] || 1\n name = Time.now.to_s\n if (opts[:name]) then name = opts[:name] end\n safely do\n return convert_srv_to_instance(racks.start_server(image_id, hwp_id, name))\n end\n end",
"def add(args)\n return @client.api_helper.add(args, \"project_add\")\n end",
"def add_role(role_name)\n p = proposal\n r = Role.find_by_name role_name\n DeploymentRole.create :role_id=>r.id, :snapshot_id=>p.id\n end",
"def create\n #@instance = Instance.new(params[:instance])\n\n respond_to do |format|\n if @instance.save\n format.html { redirect_to @instance, notice: '创建成功' }\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 aws_instance_elastic_ip_create(instance)\n log \"AWS: creating ElasticIP for Instance '#{instance.id}'\"\n # get elastic ip object\n elastic_ip = aws_call('aws_elastic_ip_create')\n log \"AWS: created ElasticIP '#{elastic_ip.public_ip}'\"\n\n # this is interesting, perhaps elastic ips dont have statuses like other resources, or else why not use our helper fn?\n log \"AWS: waiting for ElasticIP '#{elastic_ip.public_ip}' to exist\"\n Timeout.timeout(360) { sleep 1 while not aws_call('aws_obj_exists?', obj: elastic_ip) }\n\n # give our NAT vm its elastic IP!\n log \"AWS: associating ElastipIP '#{elastic_ip.public_ip}' with Instance '#{instance.id}'\"\n aws_call(\n 'aws_instance_elastic_ip_associate',\n instance: instance,\n elastic_ip: elastic_ip,\n errs: { AWS::EC2::Errors::InvalidAllocationID::NotFound => 60 }\n )\n \n # update ip_address_public attribute\n self.update_attribute(:ip_address_public, elastic_ip.public_ip)\n end",
"def add_tenant_to_specified_shard(args = {}) \n post(\"/tenants.json/shard/#{args[:shardId]}\", args)\nend",
"def add_instance(instance, options={})\n features = options[:features]\n factory = case features\n when nil then Factory::FromInstance.new(instance)\n when Array then Factory::FromInstance.new(instance, *features)\n else Factory::FromInstance.new(instance, features)\n end\n add_factory_instance(factory, options)\n end",
"def add_instance(instance, options={})\n features = options[:features]\n factory = case features\n when nil then Factory::FromInstance.new(instance)\n when Array then Factory::FromInstance.new(instance, *features)\n else Factory::FromInstance.new(instance, features)\n end\n add_factory_instance(factory, options)\n end",
"def create\n @environment_type = EnvironmentType.new(params[:environment_type])\n\n respond_to do |format|\n if @environment_type.save\n format.html { redirect_to @environment_type, notice: 'Environment type was successfully created.' }\n format.json { render json: @environment_type, status: :created, location: @environment_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @environment_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def instance!(name)\n create_db(name) rescue nil\n instance(name)\n end",
"def create_application(client, options)\n if options[:name].nil? or options[:description].nil?\n puts \"Missing arguments\"\n end\n \n application = client.applications.create({\n name: options[:name],\n description: options[:description]\n })\n puts \"Application created.\"\n\n #TODO: Add exception handling\nend",
"def create\n @ec2_instance = Ec2Instance.new(ec2_instance_params)\n\n respond_to do |format|\n if @ec2_instance.save\n format.html { redirect_to @ec2_instance, notice: 'Ec2 instance was successfully created.' }\n format.json { render :show, status: :created, location: @ec2_instance }\n else\n format.html { render :new }\n format.json { render json: @ec2_instance.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n res = self.class.post('/', body: attrs)\n res.created?\n end",
"def create\n megam_rest.post_appdefn(to_hash)\n end",
"def create(params = {})\n submit(base_url, :post, params)\n end",
"def create\n @environment = current_user.environments.new(params[:environment])\n\n respond_to do |format|\n if @environment.save\n format.html { redirect_to(@environment, :notice => 'Environment was successfully created.') }\n format.xml { render :xml => @environment, :status => :created, :location => @environment }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @environment.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def register_instances_with_lb(lb_name, instance_ids)\n instances = instance_ids.map { |instance_id| { :instance_id => instance_id } }\n link = generate_request(\"RegisterInstancesWithLoadBalancer\",\n :load_balancer_name => lb_name, :instances => instances)\n request_info(link, QElbInstancesParser.new)\n rescue Exception\n on_exception\n end",
"def create\n # Submit de new, crea nueva instance en DB.\n end",
"def create(body)\n raise ArgumentError unless body.is_a?(Hash)\n\n api.post('', body, 'application/json')\n end",
"def create(body)\n raise ArgumentError unless body.is_a?(Hash)\n\n api.post('', body, 'application/json')\n end",
"def create(body)\n raise ArgumentError unless body.is_a?(Hash)\n\n api.post('', body, 'application/json')\n end",
"def create(body)\n raise ArgumentError unless body.is_a?(Hash)\n\n api.post('', body, 'application/json')\n end",
"def create_instance(name, key, type, wait=true)\n if name\n @mgr.normalize(name)\n else\n @mgr.normalize_name_parameters()\n end\n @mgr.setparam(\"key\", key)\n name, fqdn, volname, snapid, datasize, dryrun = @mgr.getparams(\"name\", \"fqdn\", \"volname\", \"snapid\", \"datasize\", \"dryrun\")\n\n # Acquire global lock before lookups - ensure if instance doesn't exist,\n # it doesn't get created by another process.\n # NOTE: unlock() will be called by either abort_instance or update_dns\n @mgr.lock()\n\n stale_dns = false\n # Catch any exceptions so we can unlock\n begin\n i, err = resolve_instance()\n if i\n msg = \"Instance #{name} already exists\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n @mgr.unlock\n return nil, msg\n end\n\n if @mgr[\"PrivateDNSId\"]\n lookup = {\n hosted_zone_id: @mgr[\"PrivateDNSId\"],\n start_record_name: fqdn,\n max_items: 1,\n }\n resp = @mgr.route53.list_record_sets(lookup)\n records = resp.resource_record_sets\n if records.size == 1 and fqdn =~ /#{records[0].name}\\.?/\n record = records[0]\n if record.type == \"CNAME\"\n @mgr.unlock()\n raise \"CNAME exists for #{fqdn}, aborting\"\n elsif record.type != \"A\"\n @mgr.unlock()\n raise \"Unable to handle record type for #{fqdn}: #{record.type}\"\n end\n raise \"Unable to handle multiple value lookup for #{fqdn}: #{record.type}\" if record.resource_records.size > 1\n private_ip = record.resource_records[0].value\n @mgr.log(:debug, \"Checking to see if #{fqdn} -> #{private_ip} is stale\")\n f = [ { name: \"private-ip-address\", values: [ private_ip ] } ]\n instances = @resource.instances(filters: f)\n raise \"Private DNS record for #{fqdn} points to existing instance #{instances.first.id}\" if instances.count() > 1\n stale_dns = true\n @mgr.log(:info, \"Found stale private DNS record #{fqdn} -> #{private_ip}, ignoring\")\n end\n end\n rescue => e\n @mgr.unlock\n raise e\n end\n\n begin\n template = @mgr.load_template(\"ec2\", type)\n rescue => e\n msg = \"Caught exception loading ec2 template #{type}: #{e.message}\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n @mgr.unlock\n return nil, msg\n end\n\n if volname and ( snapid or datasize )\n msg = \"Invalid parameters: volume provided with snapshot and/or data size\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n @mgr.unlock\n return nil, msg\n end\n\n if dryrun == \"true\" or dryrun == true\n @mgr.unlock\n dry_run = true\n else\n dry_run = false\n end\n\n begin\n if volname\n yield \"#{@mgr.timestamp()} Looking up volume: #{volname}\"\n volume, err = resolve_volume()\n unless volume\n msg = \"Error looking up given volume: #{err}\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n return nil, msg\n end\n end\n existing, err = resolve_volume(name)\n if existing\n if volume\n msg = \"Launching with volume #{volname} will create a duplicate volume name for existing volume #{name}; delete existing volume or use attach volume instead\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n return nil, msg\n else\n volume = existing\n yield \"#{@mgr.timestamp()} Found existing volume for #{name}: #{volume.id()}\"\n end\n end\n\n @mgr.symbol_keys(template[\"api_template\"])\n\n ispec = template[\"api_template\"]\n if volume\n # When re-attaching a volume, the instance needs to launch in the same\n # availability zone\n vol_az = volume.availability_zone()[-1]\n if ispec[:subnet_id]\n if ispec[:subnet_id].match(/#[FL0-9a-j?]/)\n @mgr.log(:debug, \"Setting instance location to ##{vol_az} to match the existing volume\")\n ispec[:subnet_id] = ispec[:subnet_id].sub(/#[FL0-9a-j?]/,\"##{vol_az}\")\n end\n elsif ispec[:network_interfaces][0][:subnet_id]\n if ispec[:network_interfaces][0][:subnet_id].match(/#[FL0-9a-j?]/)\n @mgr.log(:debug, \"Setting instance location to ##{vol_az} to match the existing volume\")\n ispec[:network_interfaces][0][:subnet_id] = ispec[:network_interfaces][0][:subnet_id].sub(/#[FL0-9a-j?]/,\"##{vol_az}\")\n end\n else\n @mgr.log(:warn, \"Unable to identify a location specifier in the instance subnet_id, launching without updating instance location to match the volume\")\n end\n end\n\n if ispec[:block_device_mappings]\n ispec[:block_device_mappings].delete_if() do |dev|\n if dev[:device_name].end_with?(\"a\")\n false\n elsif dev[:device_name].end_with?(\"a1\")\n false\n elsif volume\n true\n else\n e=dev[:ebs]\n if snapid\n e.delete(:encrypted)\n snapshot, err = resolve_snapshot(snapid)\n unless snapshot\n yield \"#{@mgr.timestamp()} Error resolving snapshot: #{snapid}\"\n return nil\n end\n sname = get_tag(snapshot, \"Name\")\n stime = snapshot.start_time.getlocal.strftime(\"%F|%R\")\n yield \"#{@mgr.timestamp()} Launching with data volume from snapshot #{snapshot.id()} for #{sname} created: #{stime}\"\n e[:snapshot_id] = snapshot.id()\n else\n e.delete(:snapshot_id)\n end\n e.delete(:iops) unless e[:volume_type] == \"io1\"\n false\n end\n end\n end\n if ispec[:block_device_mappings] && ispec[:block_device_mappings].size == 0\n ispec.delete(:block_device_mappings)\n end\n\n @mgr.normalize_name_parameters()\n\n @mgr.resolve_vars(template, \"api_template\")\n @mgr.resolve_vars(template, \"tags\")\n\n # Set up tags for private_sg\n cfgtags = @mgr.tags\n name = @mgr.getparam(\"name\")\n cfgtags[\"Name\"] = name\n cfgtags[\"Domain\"] = @mgr[\"DNSDomain\"]\n sgtags = cfgtags.apitags()\n cfgtags.add(template[\"tags\"]) if template[\"tags\"]\n itags = cfgtags.apitags()\n cfgtags[\"InstanceName\"] = @mgr.getparam(\"name\")\n vtags = cfgtags.apitags()\n\n # Create a private security group for this instance?\n if template[\"private_sg\"] == true\n begin\n if ispec[:network_interfaces][0][:subnet_id]\n vpc_id = @resource.subnet(ispec[:network_interfaces][0][:subnet_id]).vpc.id\n elsif ispec[:subnet_id]\n vpc_id = @resource.subnet(ispec[:subnet_id]).vpc.id\n else\n raise \"Unable to identify a subnet/VPC for creating instance private security group\"\n end\n existing = @resource.security_groups({\n filters: [\n { name: \"vpc-id\",\n values: [ vpc_id ] },\n { name: \"group-name\",\n values: [ name ] },\n ]\n })\n if existing.count() == 1\n @mgr.log(:info, \"Deleting orphaned private security group #{name}\")\n existing.first.delete()\n end\n @mgr.log(:debug, \"Creating private security group #{name}\")\n private_sg = @resource.create_security_group({\n description: \"Private security group for #{name}\",\n group_name: name,\n vpc_id: vpc_id\n })\n @resource.create_tags(\n resources: [ private_sg.id() ],\n tags: sgtags\n )\n if ispec[:network_interfaces][0][:subnet_id]\n ispec[:network_interfaces][0][:groups] << private_sg.id()\n elsif ispec[:subnet_id]\n ispec[:security_group_ids] << private_sg.id()\n end\n rescue => e\n @mgr.unlock()\n raise \"Error creating instance private security group #{name}: #{e.message}\"\n end\n end\n\n if ispec[:user_data]\n ispec[:user_data] = Base64::encode64(ispec[:user_data])\n end\n\n yield \"#{@mgr.timestamp()} Dry run, creating: #{ispec}\" if dry_run\n\n interfaces = []\n if template[:additional_interfaces]\n @mgr.resolve_vars(template, :additional_interfaces)\n template[:additional_interfaces].each() do |iface|\n interfaces << @resource.create_network_interface(iface)\n end\n end\n unless @mgr.govcloud\n ispec[:tag_specifications] = [\n {\n resource_type: \"instance\",\n tags: itags,\n },\n {\n resource_type: \"volume\",\n tags: vtags,\n }\n ]\n end\n rescue => e\n @mgr.unlock\n raise e\n end\n # puts \"Creating: #{ispec}\"\n\n begin\n instances = @resource.create_instances(ispec)\n rescue => e\n msg = \"Caught exception creating instance: #{e.message}\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n @mgr.unlock\n abort_instance(nil, interfaces, wait, false)\n return nil, msg\n end\n instance = nil\n unless dry_run\n instance = instances.first()\n yield \"#{@mgr.timestamp()} Created instance #{name} (id: #{instance.id()}), waiting for it to enter state running ...\"\n instance.wait_until_running()\n yield \"#{@mgr.timestamp()} Running\"\n if interfaces.size > 0\n iface_index = 1\n interfaces.each() do |iface|\n yield \"#{@mgr.timestamp()} Attaching additional interface ##{iface_index} to #{instance.id()}\"\n attach = iface.attach({ instance_id: instance.id(), device_index: iface_index })\n iface.modify_attribute({ attachment: { attachment_id: attach.attachment_id, delete_on_termination: true } })\n iface_index += 1\n end\n end\n\n begin\n msg = nil\n if volume\n if volume.state == \"available\"\n msg = \"Used existing volume\"\n yield \"#{@mgr.timestamp()} Attaching data volume: #{volume.id()}\"\n begin\n instance.attach_volume({\n volume_id: volume.id(),\n device: \"/dev/sdf\",\n })\n rescue => e\n msg = \"Unable to attach volume, aborting\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n abort_instance(instance, [], wait, true) { |s| yield s }\n return nil, msg\n end\n @client.wait_until(:volume_in_use, volume_ids: [ volume.id() ])\n else\n msg = \"Data volume not in state 'available', aborting\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n abort_instance(instance, [], wait, true) { |s| yield s }\n return nil, msg\n end\n end\n\n # Need to refresh to get attached volumes\n instance = @resource.instance(instance.id())\n if @mgr.govcloud\n tag_instance(instance, itags, vtags) { |s| yield s }\n end\n\n if @mgr[\"PrivateDNSId\"] and not stale_dns\n rr = @mgr.route53.lookup(@mgr[\"PrivateDNSId\"])\n if rr.size != 0\n msg = \"DNS record for #{name} created during launch\"\n yield \"#{@mgr.timestamp()} #{msg}\"\n abort_instance(instance, [], wait, true) { |s| yield s }\n return nil, msg\n end\n end\n\n update_dns(nil, wait, instance, true) { |s| yield s }\n rescue => e\n @mgr.unlock\n raise e\n end\n\n # @mgr.unlock() - called by update_dns as soon as records are added\n return instance, msg\n else\n return nil, nil\n end\n end",
"def add(name)\n response = JSON.parse(CrateAPI::Base.call(\"#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}\", :post, {:body => {:name => name}}))\n raise CrateLimitReachedError, response[\"message\"] unless response[\"status\"] != \"failure\"\n end",
"def create params = {}, body = {}\n @connection.request(method: :post, path: build_path(\"/containers/create\", params), headers: {\"Content-Type\": \"application/json\"}, body: body.to_json)\n end",
"def create_cluster instance_id, cluster_id, cluster\n cluster.location = location_path cluster.location unless cluster.location == \"\"\n\n instances.create_cluster parent: instance_path(instance_id), cluster_id: cluster_id, cluster: cluster\n end",
"def associate_elastic_ip_address_with_instance(\n ec2_client,\n allocation_id,\n instance_id\n)\n response = ec2_client.associate_address(\n allocation_id: allocation_id,\n instance_id: instance_id,\n )\n return response.association_id\nrescue StandardError => e\n puts \"Error associating Elastic IP address with instance: #{e.message}\"\n return \"Error\"\nend"
] | [
"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.49228546",
"0.48994046",
"0.4878036",
"0.48772147",
"0.4869446",
"0.48652267",
"0.48628402",
"0.48609197",
"0.4857092",
"0.48537868",
"0.48364326",
"0.48331898",
"0.48254997",
"0.4814997",
"0.479951",
"0.4794463",
"0.47756156",
"0.4772736",
"0.47649673",
"0.4764935",
"0.47644123",
"0.47606325",
"0.4747525",
"0.4745633",
"0.4745633",
"0.47426468",
"0.47387272",
"0.47382304",
"0.47326893",
"0.47163272",
"0.47161442",
"0.4712647",
"0.47032505",
"0.470266",
"0.46889645",
"0.46865502",
"0.46828872",
"0.46775365",
"0.46704006",
"0.46446517",
"0.4639708",
"0.46364835",
"0.46274987",
"0.4626636",
"0.46218735",
"0.46189204",
"0.46163565",
"0.46126628",
"0.46114826",
"0.46031344",
"0.46031344",
"0.4602709",
"0.46018523",
"0.45976734",
"0.4594417",
"0.4591159",
"0.4590244",
"0.4584539",
"0.4583967",
"0.4580531",
"0.45779642",
"0.4575027",
"0.45743915",
"0.45743915",
"0.45743915",
"0.4568115",
"0.4564581",
"0.45607656",
"0.45583797",
"0.45539805"
] | 0.74952036 | 0 |
Gets an instance's Amazon ID by its "id" attribute as reported by AWSM. When an instance is added via the API, the JSON that's returned contains an "id" attribute for that instance. Developers may save that ID so they can later discover an instance's Amazon ID. This is because, when an instance object is first created (see add_instance above), its Amazon ID isn't yet known. The object is created, and then later provisioned, so you can't get an Amazon ID until after provisioning has taken place. This method allows you to send an ID to it, and then returns the instance object that corresponds to that ID, which will have an Amazon ID with it if the instance has been provisioned at the time the environment information was read. Note that the ID passed in must be an integer. Usage example: api = EY::CloudClient.new(token: 'token') env = api.environment_by_name('my_env') env.instance_by_id(12345) => | def instance_by_id(id)
instances.detect { |x| x.id == id } # ID should always be unique
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def lookup_instance_id\n metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'\n instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )\n end",
"def get_instance_by_id(id)\n get_instances_description.select {|a| a.instance_id == id}[0] rescue nil\n end",
"def instance_id\n return ec2_meta_data('instance-id')\n end",
"def get_instance_id(instance_info)\n # puts \"look up instanceId in #{instance_info.inspect}\"\n instance_info['instancesSet']['item'][0]['instanceId']\n end",
"def get_instance instance_id\n instances.get_instance name: instance_path(instance_id)\n end",
"def instance_id\n data[:instance_id]\n end",
"def my_instance_id\n Net::HTTP.get(URI('http://169.254.169.254/1.0/meta-data/instance-id'))\n end",
"def id\n @instance.id\n end",
"def get_instance(id)\n begin\n instance = @ec2.instance(id)\n if instance.exists?\n return instance\n else\n raise RuntimeError.new(\"Instance #{id} does not exist\")\n end\n rescue => e\n raise e\n end\n end",
"def ostack_get_instance_id ()\n # The instance id is kept in @passthrough[:instance] or\n # can be obtained from @instance_data which has all instance\n # details.\n if ! @instance_data.nil? and ! @instance_data.id.nil?\n return @instance_data.id # we already know the id\n elsif @passthrough.has_key?(:instance)\n return @passthrough[:instance] # we know the id we want\n else\n @logger.debug(sprintf('unable to determine id from instance_data[%s] or passthrough specification[%s]', @instance_data, @passthrough))\n return nil # we don't have an id yet, likely a up() call\n end\n end",
"def aws_instance_get(opts)\n AWS::EC2.new.instances[opts[:instance_id]]\n end",
"def instance(instance_id)\n instances([instance_id])[0]\n end",
"def get_instance instance_id\n execute do\n instances.get_instance(\n instance_path(instance_id)\n )\n end\n end",
"def me\n require 'open-uri'\n begin\n instance_id = open('http://169.254.169.254/latest/meta-data/instance-id').read\n instance instance_id\n rescue OpenURI::HTTPError => e\n nil\n end\n end",
"def ec2_instance(instance_id)\n EC2Instance.new(instance_id)\n end",
"def ec2_instance(instance_id)\n EC2Instance.new(instance_id)\n end",
"def instance_id\n `curl --connect-timeout 1 #{aws_url} 2>&1`.chomp\n end",
"def id( )\n return @instances.map{ |i| i[:aws_instance_id] }\n end",
"def instance instance_id\n ensure_service!\n grpc = service.get_instance instance_id\n Instance.from_grpc grpc, service\n rescue Google::Cloud::NotFoundError\n nil\n end",
"def get_by_id(id)\n self.class.get(\"/aldebaran-instances/instances/#{id}\", :basic_auth => @auth)\n end",
"def id\n raise MissingID if not defined?(@id)\n @id.to_i\n end",
"def aws_find_instance( iprops )\n if iprops[:id]\n @aws_instances.find do |r|\n r[:id] == iprops[:id] && r[:region] == iprops[:region]\n end\n else\n [ :internet_name, :internet_ip, :name ].inject( nil ) do |found, key|\n found || @aws_instances.find { |r| r[key] == iprops[key] }\n end\n end\n end",
"def id\n object[\"id\"]\n end",
"def get_aws_instance_id_by_config_id(configuration_id, node_name)\n return nil unless configured?\n\n found_instance = instances_list.find do |instance|\n instance[:node_name] == node_name &&\n instance[:configuration_id] == configuration_id\n end\n found_instance.nil? ? nil : found_instance[:instance_id]\n end",
"def get_id(id)\n return unless id\n id = id['id'] || id[:id] if id.is_a?(Hash)\n id\n end",
"def id\n @obj['id']\n end",
"def id\n read_attr :id, :to_sym\n end",
"def get_aws_instance_id_by_node_name(node_name)\n return nil unless configured?\n\n found_instance = instances_list.find { |instance| instance[:node_name] == node_name }\n found_instance.nil? ? nil : found_instance[:instance_id]\n end",
"def id\n get_val(:id)\n end",
"def id\n return @args[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n @attributes[:id]\n end",
"def id\n attributes.key?(:id) ? attributes[:id] : nil\n end",
"def id\n read_attr :id\n end",
"def id\n @attributes['id']\n end",
"def describe_instance(id=nil)\n describe_instances.select {|a| a[:name] == id}[0] rescue nil\n end",
"def id_instance_attributes(instance_id)\n @id_instance_attributes ||= {}\n @id_instance_attributes[instance_id] ||= InstanceAttributes.new(instance_id)\n end",
"def id\n @values[:id]\n end",
"def id\n @hash[\"id\"]\n end",
"def id\n @values[:id]\n end",
"def id\n @values[:id]\n end",
"def id\n key?(:id) ? method_missing(:id) : nil\n end",
"def id\n @id ||= @response['id']\n end",
"def get_id\n params[:id]\n end",
"def find_by_id(id)\n id = id.to_i\n\n @id_hash[id]\n end",
"def id\n @hash['id']\n end",
"def current_vm_id\n @metadata_lock.synchronize do\n return @current_vm_id if @current_vm_id\n\n http_client = HTTPClient.new\n http_client.connect_timeout = METADATA_TIMEOUT\n # Using 169.254.169.254 is an EC2 convention for getting\n # instance metadata\n uri = \"http://169.254.169.254/latest/meta-data/instance-id/\"\n\n response = http_client.get(uri)\n unless response.status == 200\n cloud_error(\"Instance metadata endpoint returned \" \\\n \"HTTP #{response.status}\")\n end\n\n @current_vm_id = response.body\n end\n\n rescue HTTPClient::TimeoutError\n cloud_error(\"Timed out reading instance metadata, \" \\\n \"please make sure CPI is running on EC2 instance\")\n end",
"def current_vm_id\n @metadata_lock.synchronize do\n return @current_vm_id if @current_vm_id\n\n http_client = HTTPClient.new\n http_client.connect_timeout = METADATA_TIMEOUT\n # Using 169.254.169.254 is an EC2 convention for getting\n # instance metadata\n uri = \"http://169.254.169.254/latest/meta-data/instance-id/\"\n\n response = http_client.get(uri)\n unless response.status == 200\n cloud_error(\"Instance metadata endpoint returned \" \\\n \"HTTP #{response.status}\")\n end\n\n @current_vm_id = response.body\n end\n\n rescue HTTPClient::TimeoutError\n cloud_error(\"Timed out reading instance metadata, \" \\\n \"please make sure CPI is running on EC2 instance\")\n end",
"def id\n data[:id]\n end",
"def id\n @attributes[\"#{self.class.to_s.split('::').last.underscore.downcase}_id\".to_sym]\n end",
"def get_id()\n return @id\n end",
"def id\n attributes[:id] \n end",
"def id\n @attributes.fetch('id', nil)\n end",
"def id\n @attributes.fetch('id', nil)\n end",
"def id\n @attributes.fetch('id', nil)\n end",
"def id\n self[:id]\n end",
"def id\n data[:id]\n end",
"def get_instance(id)\n CloudDB::Instance.new(self,id)\n end",
"def get_instance(id)\n CloudDB::Instance.new(self,id)\n end",
"def set_ec2_instance\n @ec2_instance = Ec2Instance.find(params[:id])\n end",
"def id\n read_attribute(self.class.primary_key)\n end",
"def id\n read_attribute(self.class.primary_key)\n end",
"def get_pvm_instance(instance_id)\n get(\"cloud-instances/#{guid}/pvm-instances/#{instance_id}\")\n end",
"def current_vm_id\n # xxxx = coreCloud.current_vm_id()\n # process xxxx based on version\n # return based on version\n\n return @current_vm_id if @current_vm_id\n\n http_client = HTTPClient.new\n http_client.connect_timeout = METADATA_TIMEOUT\n headers = {}\n\n # Using 169.254.169.254 is an EC2 convention for getting\n # instance metadata\n response = http_client.put('http://169.254.169.254/latest/api/token', nil, { 'X-aws-ec2-metadata-token-ttl-seconds' => '300' })\n if response.status == 200\n headers['X-aws-ec2-metadata-token'] = response.body #body consists of the token\n end\n\n response = http_client.get('http://169.254.169.254/latest/meta-data/instance-id/', nil, headers)\n unless response.status == 200\n cloud_error('Instance metadata endpoint returned ' \\\n \"HTTP #{response.status}\")\n end\n\n @current_vm_id = response.body\n rescue HTTPClient::TimeoutError\n cloud_error('Timed out reading instance metadata, ' \\\n 'please make sure CPI is running on EC2 instance')\n end",
"def id\n attr_name = self.class.primary_key\n c = column_for_attribute(attr_name)\n define_read_method(:id, attr_name, c) if self.class.generate_read_methods\n read_attribute(attr_name)\n end",
"def id\n self['id']\n end",
"def id\n self['id']\n end",
"def id\n attributes[self.class.primary_key]\n end",
"def get_id(options)\r\n id = options[:id]\r\n\r\n id\r\n end",
"def id\n attribute('id', 'id')\n end",
"def id\n attributes.fetch(:id)\n end",
"def id\n attributes.fetch(:id)\n end",
"def id\n attributes.fetch(:id)\n end",
"def id\n _id rescue nil\n end",
"def id(id, &block)\n return get_metrics([\"id\", id], &block)\n end",
"def id\n @attributes[:ID]\n end",
"def set_instance\n if Instance.exists?(params[:id])\n @instance = Instance.find(params[:id])\n else\n render json: { error: 'No se ejecuto nada con ese id', codigo: 707 }\n end\n end",
"def set_instance\n @instance = Instance.find(params[:id])\n end",
"def set_instance\n @instance = Instance.find(params[:id])\n end",
"def set_instance\n @instance = Instance.find(params[:id])\n end",
"def set_instance\n @instance = Instance.find(params[:id])\n end",
"def set_instance\n @instance = Instance.find(params[:id])\n end",
"def set_instance\n @instance = Instance.find(params[:id])\n end",
"def get_id()\n return @id\n end",
"def find_by_id(id)\n find_by_attributes(:id => id).first\n end",
"def id\n @attributes[:_id]\n end",
"def id\n object.id.to_i\n end",
"def id\n self[:identifier]\n end",
"def get_id()\n @id\n end",
"def get_id()\n @id\n end",
"def getAWSInfo\n begin\n Timeout::timeout(10) do\n aws_metadata = open('http://169.254.169.254/2014-11-05/dynamic/instance-identity/document'){ |io| data = io.read }\n aws_JSON_Information = JSON.parse(aws_metadata)\n return \"#{aws_JSON_Information['instanceId']}_#{aws_JSON_Information['region']}_#{aws_JSON_Information['accountId']}\"\n end\n rescue\n Chef::Log.warn('Unable to get AWS instance ID, Timeout while reading') \n return ''\n end\nend",
"def id\n @params[\"id\"]\n end"
] | [
"0.7058864",
"0.6903498",
"0.6760356",
"0.6712818",
"0.65552324",
"0.6551474",
"0.64552534",
"0.64234865",
"0.64192617",
"0.64016587",
"0.6384004",
"0.6369302",
"0.62412006",
"0.61051005",
"0.60986656",
"0.60986656",
"0.6096984",
"0.60841715",
"0.6081782",
"0.6020195",
"0.5969741",
"0.59675443",
"0.59479266",
"0.59303343",
"0.59055495",
"0.588927",
"0.58209234",
"0.57901454",
"0.5770768",
"0.57680243",
"0.5762517",
"0.5762517",
"0.5762517",
"0.5762517",
"0.5762517",
"0.5762517",
"0.5762517",
"0.5762517",
"0.5762517",
"0.5762517",
"0.57479304",
"0.56750244",
"0.56396645",
"0.5631674",
"0.5612545",
"0.5612005",
"0.5607754",
"0.56019497",
"0.56019497",
"0.5578511",
"0.55761194",
"0.55573237",
"0.5554457",
"0.5544184",
"0.5542661",
"0.5542661",
"0.5536362",
"0.5530653",
"0.55293477",
"0.55255973",
"0.55233437",
"0.55233437",
"0.55233437",
"0.550947",
"0.5507504",
"0.54986656",
"0.54986656",
"0.5495696",
"0.54891837",
"0.54891837",
"0.54889953",
"0.548624",
"0.5476146",
"0.5469213",
"0.5469213",
"0.5462841",
"0.5452047",
"0.54456604",
"0.54452837",
"0.54452837",
"0.54452837",
"0.5428254",
"0.541985",
"0.5417638",
"0.5416745",
"0.54134345",
"0.54134345",
"0.54134345",
"0.54134345",
"0.54134345",
"0.54134345",
"0.54083645",
"0.5401852",
"0.5380394",
"0.5378155",
"0.5374862",
"0.5369768",
"0.5369768",
"0.5358793",
"0.5356748"
] | 0.6362426 | 12 |
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",
"def aws_terminate_instance_and_ebs_volumes( iprops )\n ec2 = AWS::EC2.new.regions[ iprops[ :region ] ]\n inst = ec2.instances[ iprops[ :id ] ]\n unless inst.exists?\n raise \"Instance #{iprops[:id]} does not exist in #{iprops[:region]}\"\n end\n\n ebs_volumes = inst.block_devices.map do |dev|\n ebs = dev[ :ebs ]\n if ebs && dev[:device_name] =~ /dh\\d+$/ && !ebs[:delete_on_termination]\n ebs[ :volume_id ]\n end\n end.compact\n\n inst.terminate\n wait_until( \"termination of #{inst.id}\", 2.0 ) { inst.status == :terminated }\n\n ebs_volumes = ebs_volumes.map do |vid|\n volume = ec2.volumes[ vid ]\n if volume.exists?\n volume\n else\n puts \"WARN: #{volume} doesn't exist\"\n nil\n end\n end.compact\n\n ebs_volumes.each do |vol|\n wait_until( \"deletion of vol #{vol.id}\" ) do\n vol.status == :available || vol.status == :deleted\n end\n vol.delete if vol.status == :available\n end\n\n found = aws_find_instance( iprops )\n if found\n aws_instance_removed( found )\n aws_write_instances\n end\n end",
"def terminateinstances\n if not checkRequirements([\"thezone\",\"theserver\"])\n return false\n end\n checkToken(@thezone)\n submit = queryGCE(:path => '/compute/v1beta15/projects/#{@thezone.name}/zones/#{@theserver.azone.name}/instances/#{@theserver.serial}', :method => 'delete', :options => '', :access_token => @thezone.token )\n checkQuery(:type => 'zone', :token => @thezone.token, :projectname => @thezone.name, :zonename => @theserver.azone.name, :operationname => submit[\"name\"] )\n end",
"def delete_d_b_instance(d_b_instance_id, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DeleteDBInstance'\n\t\targs[:query]['DBInstanceId'] = d_b_instance_id\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :client_token\n\t\t\targs[:query]['ClientToken'] = optional[:client_token]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def cleanup(vpc_id, client, asg, elbv1, elbv2, region)\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Error: vpc_id [#{vpc_id}] does not exist... exiting.\"\n puts \"Make sure you passed the correct region on the command-line if it's not in the default us-west-2\"\n exit 0\n end\n\n # 1) Delete Auto Scaling group\n begin\n asg.delete_auto_scaling_group(auto_scaling_group_name: 'asg-nginx_auto', force_delete: true)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n sleep 2\n # TODO: properly wait here until ASG is fully deleted before proceeding...\n begin\n asg.delete_launch_configuration(launch_configuration_name: 'lc-nginx_auto')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n\n # 2) instance handling\n term_error = 0\n instances_to_term = []\n terminate_states = %w[pending running shutting-down stopping stopped]\n puts 'Checking for nginx and nat instances, of all states...'\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #1: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n instances_to_term.push(instance.instance_id) if terminate_states.include? instance.state.name\n end\n end\n\n if instances_to_term.any? # If array has content, proceed.\n term_error = 0\n instance_cnt = instances_to_term.length # TODO: Check before/after termination attempts and ensure = 0\n before_terminate = Time.now\n begin\n client.wait_until(:instance_terminated,instance_ids: instances_to_term) do |wait|\n wait.interval = 8 # Seconds between polling attempts. Same as wait.delay\n wait.max_attempts = 15 # Polling attempts before giving up. Wait time is 15*8=120 seconds.\n puts \"Attempting to terminate [#{instance_cnt}] instance(s), please wait up to 120 seconds...\"\n begin\n client.terminate_instances(instance_ids: instances_to_term)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n end\n rescue Aws::Waiters::Errors::WaiterFailed => error\n term_error = 1 # TODO: Do something more reliable if this ever occurs.\n puts \"Exception: failed waiting for instance running: #{error.message}\"\n end\n puts \"#{Time.now - before_terminate.to_time} seconds elapsed while terminating.\" if term_error.zero?\n end\n\n if term_error.zero?\n # Debug with final instance check... this shouldn't print anything aside from terminated instances.\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #2: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n end\n end\n end\n\n puts 'Sleeping for 5 seconds...'\n sleep 5\n\n # 3) Delete listeners\n printf 'Deleting ALB listeners... '\n begin\n response = elbv2.describe_load_balancers(names: ['AutoALB'])\n alb_arn = response.load_balancers[0].load_balancer_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n begin\n response = elbv2.describe_listeners(load_balancer_arn: alb_arn)\n listener_arn = response.listeners[0].listener_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_listener(listener_arn: listener_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n puts 'done.'\n\n # 4) Delete target groups\n printf 'Deleting ALB target groups... '\n begin\n response = elbv2.describe_target_groups(names: ['AutoALBTargetGroup'])\n target_group_arn = response.target_groups[0].target_group_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_target_group(target_group_arn: target_group_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 5\n puts 'done.'\n\n # 5) Delete load balancers\n printf 'Deleting application and classic load balancers... '\n begin\n elbv1.delete_load_balancer(load_balancer_name: 'AutoCLB')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_load_balancer(load_balancer_arn: alb_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n puts 'done.'\n\n puts 'Sleeping for 120 seconds, enough time for the ASG to fully disappear before deleting subnets.'\n sleep 120\n\n # 6) subnets\n begin\n response = client.describe_subnets(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.subnets.each do |sn|\n printf \"Removing subnet: #{sn.subnet_id}, #{sn.vpc_id}, #{sn.cidr_block}, #{sn.availability_zone}; \"\n client.delete_subnet(subnet_id: sn.subnet_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 7) security groups\n begin\n response = client.describe_security_groups(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.security_groups.each do |sg|\n next if sg.group_name == 'default' # This name is reserved by aws and cannot be removed.\n printf \"Removing security group: #{sg.group_id}, #{sg.vpc_id}, #{sg.group_name}, Desc='#{sg.description}'; \"\n client.delete_security_group(group_id: sg.group_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 8) Internet gateway\n begin\n response = client.describe_internet_gateways(filters: [{name: 'attachment.vpc-id', values: [vpc_id]}])\n response.internet_gateways.each do |igw|\n printf \"Detaching Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.detach_internet_gateway(internet_gateway_id: igw.internet_gateway_id, vpc_id: igw.attachments[0].vpc_id)\n printf \"Removing Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.delete_internet_gateway(internet_gateway_id: igw.internet_gateway_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 9) Route tables\n begin\n response = client.describe_route_tables(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.route_tables.each do |rtl|\n if rtl.associations[0] != nil\n if rtl.associations[0].route_table_association_id != nil\n puts \"Skipping #{rtl.associations[0].route_table_association_id}, causes exception.\"\n end\n next\n end\n printf \"Removing route table: #{rtl.route_table_id}, #{rtl.vpc_id}; \"\n client.delete_route_table(route_table_id: rtl.route_table_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 10) Delete VPC\n begin\n puts \"Attempting to delete VPC [#{vpc_id}]\"\n client.delete_vpc(vpc_id: vpc_id)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Deletion of vpc_id=[#{vpc_id}] was a success.\"\n exit 0\n end\n\n # Shouldn't get here, but sometimes does due to the ASG taking too long to\n # release subnet dependencies, or if running a cleanup before a launch has\n # fully completed, etc.\n puts 'Oops. Termination sometimes fails for various reasons.'\n puts 'Note: running this twice usually clears up any lingering dependencies.'\n puts ' With that said, there is still work to be done. Execute again.'\n exit 0\nend",
"def delete_vm_instance(name, namespace)\n @conn.vminstances.destroy(name, namespace)\n end",
"def delete_vm(instance_id)\n with_thread_name(\"delete_vm(#{instance_id})\") do\n logger.info(\"Deleting instance '#{instance_id}'\")\n @instance_manager.find(instance_id).terminate(fast_path_delete?)\n end\n end",
"def delete_vm(instance_id)\n with_thread_name(\"delete_vm(#{instance_id})\") do\n logger.info(\"Deleting instance '#{instance_id}'\")\n @instance_manager.find(instance_id).terminate(fast_path_delete?)\n end\n end",
"def dissociate(instance_id)\n conn.service 'get', 'DissociateEips',\n :instance => instance_id,\n :'eips.1' => id\n promise(timeout:60){ wait_for :available }\n end",
"def destroy_instance(instance)\n tenant = @identity.find_tenant(instance.tenant_id)\n fog_options = @fog_options[:storage].merge(:hp_tenant_id => tenant.id)\n\n storage = VCAP::Services::Swift::Storage.new(@logger, fog_options)\n storage.delete_account\n\n @logger.debug \"Account meta data (should be 'Recently deleted'): \" + storage.get_account_meta_data.body.to_s\n\n @identity.delete_users_by_tenant_id(instance.tenant_id, @fog_options[:name_suffix])\n @identity.delete_tenant(instance.tenant_id)\n raise SwiftError.new(SwiftError::SWIFT_DESTROY_INSTANCE_FAILED, instance.inspect) unless instance.destroy\n end",
"def destroy\n @app_instance.destroy\n respond_to do |format|\n format.html { redirect_to app_instances_url }\n format.json { head :no_content }\n end\n end",
"def delete_instance_from_dashboard(appid, location)\n begin\n host, port = location.split(\":\")\n instance_info = [{\n 'appid' => appid,\n 'host' => host,\n 'port' => Integer(port)\n }]\n\n url = URI.parse(\"https://#{get_login.public_ip}:\" +\n \"#{AppDashboard::LISTEN_SSL_PORT}/apps/stats/instances\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n request = Net::HTTP::Delete.new(url.path)\n request.body = JSON.dump(instance_info)\n response = http.request(request)\n Djinn.log_debug(\"Done sending instance info to AppDashboard!\")\n Djinn.log_debug(\"Instance info is: #{instance_info.inspect}\")\n Djinn.log_debug(\"Response is #{response.body}\")\n rescue Exception => exception\n # Don't crash the AppController because we weren't able to send over\n # the instance info - just continue on.\n Djinn.log_warn(\"Couldn't delete instance info to AppDashboard because\" +\n \" of a #{exception.class} exception.\")\n end\n end",
"def remove\n get_credentials\n begin\n response = resource[\"/remove/#{app}\"].post(:apikey => @credentials[1])\n rescue RestClient::InternalServerError\n display \"An error has occurred.\"\n end\n display response.to_s\n end",
"def destroy\n #@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 destroy\n compute.delete_flavor(params[:id])\n \n\n respond_to do |format|\n format.html { redirect_to flavors_path }\n format.json { head :ok }\n end\n end",
"def remove_service\n service = Service.find(params[:service_id])\n version = Version.find(params[:version_id])\n @deployment.versions.delete(version)\n render :edit\n end",
"def delete_instance_profile(instance_profile_name)\n request(\n 'Action' => 'DeleteInstanceProfile',\n 'InstanceProfileName' => instance_profile_name,\n :parser => Fog::Parsers::AWS::IAM::Basic.new\n )\n end",
"def immediate_shutdown_pvm_instance(instance_id)\n post(\n \"cloud-instances/#{guid}/pvm-instances/#{instance_id}/action\",\n {\"action\" => \"immediate-shutdown\"}.to_json\n )\n end",
"def delete_vm(instance_id)\n with_thread_name(\"delete_vm(#{instance_id})\") do\n logger.info(\"Deleting instance '#{instance_id}'\")\n\n @cloud_core.delete_vm(instance_id) do |instance_id|\n @registry.delete_settings(instance_id)\n end\n end\n end",
"def terminate_instance_by_config_id(configuration_id, node_name)\n return unless configured?\n\n terminate_instance(get_aws_instance_id_by_config_id(configuration_id, node_name))\n end",
"def remove_environment (environment_id)\n\n #ldebug { \"remove_environment() #{environment_id.to_debug_s}\" }\n\n env, fei = fetch(environment_id)\n\n return unless env\n #\n # env already unbound and removed\n\n env.unbind\n\n onotify(:remove, environment_id)\n end",
"def terminate(instance, decrement=false)\n Log.log \"Detaching #{instance.instance_id.light_yellow} from ASG\"\n client.detach_instances(\n instance_ids: [ instance.instance_id ],\n auto_scaling_group_name: asg_name,\n should_decrement_desired_capacity: false)\n\n # need to describe the instance status in the asg here so that we wait till connections have drained.\n count = 0\n Log.log \"Awaiting connection draining... \", newline: false\n while present?(instance.instance_id) && count < 120\n sleep 1\n count += 1\n end\n Log.log \"done\", timestamp: false\n\n Log.log \"Terminating #{instance.instance_id.light_red}... \", newline: false\n ec2_client.terminate_instances(instance_ids: [ instance.instance_id ])\n Log.log \"done\", timestamp: false\n end",
"def unprovision\n cfg = ServiceConfig.find_by_user_id_and_name(user.id, params['id'])\n raise CloudError.new(CloudError::SERVICE_NOT_FOUND) unless cfg\n raise CloudError.new(CloudError::FORBIDDEN) unless cfg.provisioned_by?(user)\n\n cfg.unprovision\n\n render :json => {}\n end",
"def delete_server!(conn, server_name, delete_volumes = false)\n server = conn.servers.find{ |i| i.name == server_name }\n if server\n @log.info \"Deleting instance with name: #{server_name}\"\n # check and delete any floating ip addresses associated with instance\n server.all_addresses.each do |address|\n if address['ip']\n begin\n @log.info \"Disassociating floating ip address associated with instance: #{server.name}\"\n conn.disassociate_address(server.id, address['ip'])\n @log.info \"Releasing floating ip address: #{address['ip']}\"\n conn.release_address(conn.addresses.find {|a| a.ip == address['ip']}.id)\n rescue Exception => ex\n @log.debug \"Error encountered releasing floating ip, reason: #{ex}\"\n # continue\n end\n end\n end\n server.destroy\n if delete_volumes\n volume_service = Fog::Volume::OpenStack.new(\n :openstack_api_key => @os_password,\n :openstack_username => @os_username,\n :openstack_auth_url => @os_auth_url,\n :openstack_tenant => @os_tenant,\n )\n vols_to_del = volume_service.volumes.find{|v| v.display_name =~ /#{server_name}/}\n if vols_to_del\n vols_to_del.each do |vol|\n @log.info \"Waiting for volume to detach from instance: #{server_name}\"\n wait_for_vol(volume_service, vol.id)\n vol.destroy\n end\n else\n @log.info \"No volumes attached for the instance #{server_name}\"\n end\n end\n end\n end",
"def lookup_instance_id\n metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'\n instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )\n end",
"def destroy\n @instance_type = InstanceType.find(params[:id])\n @instance_type.destroy\n\n respond_to do |format|\n format.html { redirect_to instance_types_url }\n format.json { head :no_content }\n end\n end",
"def delete(instance) # rubocop:disable Metrics/AbcSize\n authcookie = ComputeBase.new\n authcookie = authcookie.authenticate(id_domain, user, passwd, restendpoint)\n url = restendpoint + @function + instance\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port, @proxy_addr, @proxy_port) # Creates a http object\n http.use_ssl = true # When using https\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Delete.new(uri.request_uri)\n request.add_field 'accept', 'application/oracle-compute-v3+json'\n request.add_field 'Cookie', authcookie\n http.request(request)\n end",
"def delete\n ensure_service!\n service.delete_instance path\n true\n end",
"def destroy(state)\n info(\"Destroying instance #{instance.name}\")\n return if state[:server_id].nil?\n instance.transport.connection(state).close\n domain = load_domain(state[:server_id])\n destroy_domain(domain) unless domain.nil?\n info(\"Libvirt instance #{state[:server_id]} destroyed.\")\n state.delete(:server_id)\n state.delete(:hostname)\n end",
"def destroy!\n destroy_instance(_id)\n end",
"def destroy\n return if @name.nil?\n delete_rest \"vservers/#{@name}\"\n end",
"def destroy\n @instance.destroy\n respond_to do |format|\n format.html { redirect_to instances_url, notice: 'Instance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @instance.destroy\n respond_to do |format|\n format.html { redirect_to instances_url, notice: 'Instance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @aws_elastic_ip.destroy\n respond_to do |format|\n format.html { redirect_to aws_elastic_ips_url, notice: 'Aws elastic ip was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def terminate(server_name, access_key, secret, snapshot_removal = true, force = false)\n ##############################\n # Initialize AWS and create EC2 connection\n ##############################\n initialize_aws(access_key, secret)\n ec2 = AWS::EC2.new\n\n ##############################\n # Find instance\n ##############################\n instance = nil\n AWS.memoize do\n instances = ec2.instances.filter(\"tag:Name\", server_name)\n instances.each do |i|\n unless i.status == :shutting_down || i.status == :terminated\n instance = i\n break\n end # unless status\n end # instance loop\n end # memoize\n\n if instance\n environment_name = nil\n AWS.memoize do\n environment_name = instance.tags[\"environment\"].strip if instance.tags[\"environment\"]\n end\n\n ##############################\n # ENVIRONMENT\n ##############################\n if environment_name.nil? && ! force\n @log.fatal \"No environment tag found for host. Use the --force option to override and terminate.\"\n exit 3\n end\n\n if (! @environments.has_key?(environment_name)) && (! force)\n @log.fatal \"Environment not found: '#{environment_name}'\"\n exit 2\n end\n @environment = @environments[environment_name] if environment_name\n\n ##############################\n # Create Route53 connection\n ##############################\n aws_route53 = nil\n if @environment && @environment.route53_zone_id\n aws_route53 = AWS::Route53.new\n route53 = EC2Launcher::Route53.new(aws_route53, @environment.route53_zone_id, @log)\n end\n\n ##############################\n # EBS Volumes\n ##############################\n # Find EBS volumes\n attachments = nil\n AWS.memoize do\n attachments = instance.block_device_mappings.values\n\n # Remove snapshots\n remove_snapshots(ec2, attachments) if snapshot_removal\n\n # Remove volumes, if necessary\n remove_volumes(ec2, attachments)\n end\n\n private_ip_address = instance.private_ip_address\n \n run_with_backoff(30, 1, \"terminating instance: #{server_name} [#{instance.instance_id}]\") do\n instance.terminate\n end\n\n if route53\n @log.info(\"Deleting A record from Route53: #{server_name} => #{private_ip_address}\")\n route53.delete_record_by_name(server_name, 'A')\n end\n\n @log.info(\"Deleting node/client from Chef: #{server_name}\")\n node_result = `echo \"Y\" |knife node delete #{server_name}`\n client_result = `echo \"Y\" |knife client delete #{server_name}`\n @log.debug(\"Deleted Chef node: #{node_result}\")\n @log.debug(\"Deleted Chef client: #{client_result}\")\n else\n @log.error(\"Unable to find instance: #{server_name}\")\n end\n end",
"def destroy\n @deployment = current_user.deployments.find(params[:id])\n @deployment.undeploy!\n\n respond_to do |format|\n format.html { redirect_back_or_default(@deployment.app, :notice => 'Application was successfully undeployed.') }\n format.xml { head :ok }\n end\n end",
"def terminate_instances(parameters, secret)\n if @secret != secret\n return BAD_SECRET_RESPONSE\n end\n\n TERMINATE_INSTANCES_REQUIRED_PARAMS.each { |required_param|\n if parameters[required_param].nil? or parameters[required_param].empty?\n return {\"success\" => false, \"reason\" => \"no #{required_param}\"}\n end\n }\n\n Thread.new {\n HelperFunctions.set_creds_in_env(parameters['credentials'], \"1\")\n HelperFunctions.terminate_vms(parameters['instance_ids'], \n parameters['infrastructure'])\n }\n\n return SUCCESSFUL_TERMINATE_RESPONSE\n end",
"def destroy\n @environment = current_user.environments.find(params[:id])\n @environment.destroy\n\n respond_to do |format|\n format.html { redirect_to(environments_path, :notice => 'Environment was successfully deleted.') }\n format.xml { head :ok }\n end\n end",
"def delete_vm(server_id)\n with_thread_name(\"delete_vm(#{server_id})\") do\n @logger.info(\"Deleting server `#{server_id}'...\")\n server = @openstack.with_openstack { @openstack.compute.servers.get(server_id) }\n if server\n server_tags = metadata_to_tags(server.metadata)\n @logger.debug(\"Server tags: `#{server_tags}' found for server #{server_id}\")\n destroy_server(server, server_tags)\n else\n @logger.info(\"Server `#{server_id}' not found. Skipping.\")\n end\n end\n end",
"def delete_vapp(id)\n fog_service_interface.delete_vapp(id)\n end",
"def destroy\n @instance_action = InstanceAction.find(params[:id])\n @instance_action.destroy\n\n respond_to do |format|\n format.html { redirect_to instance_actions_url }\n format.json { head :no_content }\n end\n end",
"def teardown(environment_options, client, region = 'AWS_REGION')\r\n super\r\n api_id = get_id_for_api(@api_name)\r\n if api_id\r\n delete_stage(api_id, environment_options.name)\r\n else\r\n puts \"API Gateway Object #{@api_name} not found. No environment to tear down.\"\r\n end\r\n true\r\n end",
"def destroy\n @dungeon_instance = @current_user.dungeon_instances.find(params[:id])\n @dungeon_instance.destroy\n respond_to do |format|\n format.html { redirect_to dungeon_instances_url, notice: 'Dungeon instance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def erase_app_instance_info\n uac = UserAppClient.new(@userappserver_private_ip, @@secret)\n app_list = uac.get_all_apps()\n my_public = my_node.public_ip\n\n Djinn.log_info(\"All apps are [#{app_list.join(', ')}]\")\n app_list.each { |app|\n if uac.does_app_exist?(app)\n Djinn.log_debug(\"App #{app} is enabled, so stopping it.\")\n hosts = uac.get_hosts_for_app(app)\n Djinn.log_debug(\"[Stop appengine] hosts for #{app} is [#{hosts.join(', ')}]\")\n hosts.each { |host|\n Djinn.log_debug(\"[Stop appengine] deleting instance for app #{app} at #{host}\")\n ip, port = host.split(\":\")\n uac.delete_instance(app, ip, port)\n }\n\n Djinn.log_info(\"Finished deleting instances for app #{app}\")\n else\n Djinn.log_debug(\"App #{app} wasnt enabled, skipping it\")\n end\n }\n end",
"def terminate_instance!(id=nil)\n raise RemoteException.new(:method_not_defined, \"terminate_instance!\")\n end",
"def destroy\n @game_instance = GameInstance.find(params[:id])\n @game_instance.destroy\n\n respond_to do |format|\n format.html { redirect_to game_instances_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @instance_fault = InstanceFault.find(params[:id])\n @instance_fault.destroy\n\n respond_to do |format|\n format.html { redirect_to instance_faults_url }\n format.json { head :no_content }\n end\n end",
"def terminate_instance_by_name(node_name)\n return unless configured?\n\n terminate_instance(get_aws_instance_id_by_node_name(node_name))\n end",
"def remove_agent_by_instance(agent_instance)\n remove_agent_by_name agent_instance.name\n end",
"def aws_instance_get(opts)\n AWS::EC2.new.instances[opts[:instance_id]]\n end",
"def openvz_fog_test_server_destroy\n server = openvz_service.servers.find { |s| s.ctid == '104' }\n server.destroy if server\nend",
"def destroy\n @battle_environment = BattleEnvironment.find(params[:id])\n @battle_environment.destroy\n\n respond_to do |format|\n format.html { redirect_to(battle_environments_url) }\n format.xml { head :ok }\n end\n end",
"def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity)\n request({\n 'Action' => 'TerminateInstanceInAutoScalingGroup',\n 'InstanceId' => instance_id,\n 'ShouldDecrementDesiredCapacity' => should_decrement_desired_capacity.to_s,\n :parser => Fog::Parsers::AWS::AutoScaling::TerminateInstanceInAutoScalingGroup.new\n })\n end",
"def ec2_instance(instance_id)\n EC2Instance.new(instance_id)\n end",
"def ec2_instance(instance_id)\n EC2Instance.new(instance_id)\n end",
"def reserved_instance(reserved_instance_id)\n reserved_instances(reserved_instance_id)[0]\n end",
"def delete(id)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'id', id);\n\t\t\tclient.queue_service_action_call('flavorparams', 'delete', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend",
"def delete_image(image_id)\n delete(\"cloud-instances/#{guid}/images/#{image_id}\")\n end",
"def destroy\n @synthinstance = Synthinstance.find(params[:id])\n @synthinstance.destroy\n\n respond_to do |format|\n format.html { redirect_to(synthinstances_url) }\n format.xml { head :ok }\n end\n end",
"def delete_stage(api_id, env)\r\n @client.delete_stage(rest_api_id: api_id, stage_name: env)\r\n puts 'Deleted API gateway stage ' + env\r\n rescue Aws::APIGateway::Errors::NotFoundException\r\n puts 'API Gateway stage ' + env + ' does not exist. Nothing to delete.'\r\n end",
"def my_instance_id\n Net::HTTP.get(URI('http://169.254.169.254/1.0/meta-data/instance-id'))\n end",
"def remove(object)\n full_name = extract_full_name object\n post 'api/remove', { :id => full_name, :api_type => :json }\n end",
"def remove_item(id)\n return nil if self.class.mode == :sandbox\n\n query = { \"type\" => \"delete\", \"id\" => id.to_s, \"version\" => Time.now.to_i }\n doc_request query\n end",
"def destroy(state)\n return if state[:vm_name].nil?\n\n # Reset resource pool, as it's not needed for the destroy action but might be a remnant of earlier calls to \"connect\"\n # Temporary fix until setting cluster + resource_pool at the same time is implemented (lines #64/#187)\n config[:resource_pool] = nil\n\n save_and_validate_parameters\n connect\n\n vm = get_vm(state[:vm_name])\n unless vm.nil?\n vm_api = VSphereAutomation::VCenter::VMApi.new(api_client)\n raise_if_unauthenticated vm_api, \"connecting to VM API\"\n\n # shut the machine down if it is running\n if vm.power_state == \"POWERED_ON\"\n power = VSphereAutomation::VCenter::VmPowerApi.new(api_client)\n power.stop(vm.vm)\n end\n\n # delete the vm\n vm_api.delete(vm.vm)\n end\n end",
"def destroy\n @environment = @project.environments.find_by_slug!(params[:id])\n @environment.destroy\n\n respond_to do |format|\n format.html { redirect_to project_environments_url(@project) }\n format.json { head :no_content }\n end\n end",
"def remove_tags_from_resource(d_b_instance_id, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'RemoveTagsFromResource'\n\t\targs[:query]['DBInstanceId'] = d_b_instance_id\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :client_token\n\t\t\targs[:query]['ClientToken'] = optional[:client_token]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :proxy_id\n\t\t\targs[:query]['proxyId'] = optional[:proxy_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :tag_1_key\n\t\t\targs[:query]['Tag.1.key'] = optional[:tag_1_key]\n\t\tend\n\t\tif optional.key? :tag_1_value\n\t\t\targs[:query]['Tag.1.value'] = optional[:tag_1_value]\n\t\tend\n\t\tif optional.key? :tag_2_key\n\t\t\targs[:query]['Tag.2.key'] = optional[:tag_2_key]\n\t\tend\n\t\tif optional.key? :tag_2_value\n\t\t\targs[:query]['Tag.2.value'] = optional[:tag_2_value]\n\t\tend\n\t\tif optional.key? :tag_3_key\n\t\t\targs[:query]['Tag.3.key'] = optional[:tag_3_key]\n\t\tend\n\t\tif optional.key? :tag_3_value\n\t\t\targs[:query]['Tag.3.value'] = optional[:tag_3_value]\n\t\tend\n\t\tif optional.key? :tag_4_key\n\t\t\targs[:query]['Tag.4.key'] = optional[:tag_4_key]\n\t\tend\n\t\tif optional.key? :tag_4_value\n\t\t\targs[:query]['Tag.4.value'] = optional[:tag_4_value]\n\t\tend\n\t\tif optional.key? :tag_5_key\n\t\t\targs[:query]['Tag.5.key'] = optional[:tag_5_key]\n\t\tend\n\t\tif optional.key? :tag_5_value\n\t\t\targs[:query]['Tag.5.value'] = optional[:tag_5_value]\n\t\tend\n\t\tself.run(args)\n\tend",
"def delete\n unless exists?\n return Response.new :code => 1, :message => 'VM does not exist'\n end\n\n running_response = running?\n return running_response unless running_response.successful?\n\n if running_response.data\n message = 'The VM must not be running in order to delete it.'\n return Response.new :code => 1, :message => message\n end\n\n FileUtils.rm_rf path\n Metadata.delete_vm_info path\n\n Response.new :code => 0\n end",
"def destroy_instances_if_ami_changed\n self.instances.each { |i| i.destroy } if self.ami_id_changed?\n end",
"def delete_cluster instance_id, cluster_id\n instances.delete_cluster name: cluster_path(instance_id, cluster_id)\n end",
"def delete\n execute(\"unregistervm\", @uuid, \"--delete\")\n end",
"def shutdown()\n \n #shutdown all the instances we have.\n ids = id()\n \n @ec2.terminate_instances(ids)\n \n # wait for them to shut down for a couple of minutes\n attempts = 0\n stats = state_code()\n while (stats.any? {|s| s<=16 }) do\n if attempts > 6 \n raise CaTPAWS::EC2::Error::InstanceShutdown, \"Instances still running after a long wait. Check your EC2 account manually?\"\n end\n puts \"Terminating instances, please wait...\"\n sleep(10)\n attempts+=1\n get_instances(true)\n stats = state_code()\n end\n \n #and delete the associated security group\n @ec2.delete_security_group(@group_name)\n \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.5619318",
"0.56066954",
"0.5606409",
"0.560083",
"0.5581384",
"0.5576232",
"0.5576232",
"0.5568171",
"0.5549944",
"0.55380183",
"0.5517195",
"0.5507666",
"0.5478971",
"0.54788786",
"0.5462547",
"0.5460449",
"0.543737",
"0.5436167",
"0.54192483",
"0.54150707",
"0.54023546",
"0.53711593",
"0.53473455",
"0.5336583",
"0.5317631",
"0.53175044",
"0.53162456",
"0.5310523",
"0.5306012",
"0.5297575",
"0.5292169",
"0.52918845",
"0.5266046",
"0.5253087",
"0.52528733",
"0.5245292",
"0.52381545",
"0.5236044",
"0.52272457",
"0.5218776",
"0.52102685",
"0.52039784",
"0.5201913",
"0.5192944",
"0.5190482",
"0.51870495",
"0.51685005",
"0.51655877",
"0.5162266",
"0.51563495",
"0.51552916",
"0.51479656",
"0.5131633",
"0.5131633",
"0.5127113",
"0.51254195",
"0.51222694",
"0.5105082",
"0.5099503",
"0.509388",
"0.5084334",
"0.50781393",
"0.50749373",
"0.50741196",
"0.5071457",
"0.5071246",
"0.5069024",
"0.5067069",
"0.5062164",
"0.5048261"
] | 0.76562095 | 0 |
Creating an AppEnvironment will come back and call add_app_environment (above) to associate this model with the AppEnvironment. (that's why we don't save anything here.) | def set_apps(apps_attrs)
(apps_attrs || []).each do |app|
AppEnvironment.from_hash(api, {'app' => app, 'environment' => self})
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"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 set_app_environment_resource\n @app_environment_resource = AppEnvironmentResource.find(params[:id])\n end",
"def create\n @environment = current_user.environments.new(params[:environment])\n\n respond_to do |format|\n if @environment.save\n format.html { redirect_to(@environment, :notice => 'Environment was successfully created.') }\n format.xml { render :xml => @environment, :status => :created, :location => @environment }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @environment.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @environment = Environment.new(environment_params)\n @environment.suite = @suite\n\n respond_to do |format|\n if @environment.save\n format.html { redirect_to [@suite, @environment], notice: 'Environment was successfully created.' }\n format.json { render :show, status: :created, location: @environment }\n else\n format.html { render :new }\n format.json { render json: @environment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_environment environment\n @environments.merge! environment\n self\n end",
"def create\n # Avoid double provisioning: previous url would be \"/provision/new?apps[]=vtiger&organization_id=1\"\n session.delete('previous_url')\n\n @organization = current_user.organizations.to_a.find { |o| o.id && o.id.to_s == params[:organization_id].to_s }\n authorize! :manage_app_instances, @organization\n\n app_instances = []\n params[:apps].each do |product_name|\n app_instance = @organization.app_instances.create(product: product_name)\n app_instances << app_instance\n MnoEnterprise::EventLogger.info('app_add', current_user.id, 'App added', app_instance)\n end\n\n render json: app_instances.map(&:attributes).to_json, status: :created\n end",
"def create\n @environment = @project.environments.new(params[:environment])\n\n respond_to do |format|\n if @environment.save\n format.html { redirect_to @environment, notice: 'Environment 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\n params[:environment][:name].strip! if params[:environment][:name]\n @environment = Environment.new(params[:environment])\n @lists = List.all\n respond_to do |format|\n if @environment.save\n Machine.reset_env_lists\n flash[:notice] = 'Environment was successfully created.'\n format.html { redirect_to environments_path }\n format.xml { render :xml => @environment, :status => :created, :location => @environment }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @environment.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_application\n unless self.has_current_application?\n Application.create_for_student self\n end\n end",
"def add_environment(env)\n @environments << env\n end",
"def create\n @environment = @committee.environments.new(environment_params)\n\n respond_to do |format|\n if @environment.save\n format.html do\n redirect_to [:edit, @committee, @environment],\n notice: t(:environment_successfully_created)\n end\n format.json { render :show, status: :created, location: @environment }\n else\n format.html do\n redirect_to [:edit, @committee], alert: @environment.errors.full_messages.to_sentence\n end\n format.json { render json: @environment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_app app_name, dev_name, dev_email\n data[:app_name] = app_name\n data[:dev_name] = dev_name\n data[:dev_email] = dev_email\n end",
"def create\n @app = App.new(app_params)\n\n if @app.save\n render json: @app, status: :created, location: @app\n else\n render json: @app.errors, status: :unprocessable_entity\n end\n end",
"def create\n @application = Application.new(application_params)\n @application.offer = current_user.offers.find(params.require(:offer)[:id])\n\n # @application.company = Company.new(company_params)\n # @application.contact = Contact.new(contact_params)\n # @application.agent = Agent.find_by(agent_params)\n #\n respond_to do |format|\n if @application.save\n # current_user.applications << @application\n format.html { redirect_to action: :index, notice: 'Application was successfully created.' }\n format.json { render :show, status: :created, location: @application }\n else\n format.html { render :new }\n format.json { render json: @application.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_environment_attribute(key, value, options = {})\n @environment_attributes << { key: key, value: value, options: options }\n end",
"def save\n\t\t\tsuper\n\t\t\t@@env = self\n\t\tend",
"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\n @environment_type = EnvironmentType.new(params[:environment_type])\n\n respond_to do |format|\n if @environment_type.save\n format.html { redirect_to @environment_type, notice: 'Environment type was successfully created.' }\n format.json { render json: @environment_type, status: :created, location: @environment_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @environment_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\t\t@app \t\t\t\t= find_deployable_application_by(\"public_token\", params[:deployment][:deployable_application_id])\n\n\t\t# Chech if the branch and the environment are correct, otherwise kill the request with raise HTTPUnauthorized\n\t\tvalidate_branch_and_environment(@app, params)\n\n\n\t\t# CREATE NEW RAKE DEPLOY\n\t\t@deployment \t\t= @app.deployments.create!(deployment_params)\n\n\t\tRakeInvoker.run(pull_requests: :fetch_for_app, PUBLIC_TOKEN: @app.public_token, APP_ID: @app.id, DEPLOYMENT_ID: @deployment.id)\n\n\t\t# @deployment.user \t= User.first\n\n\t\tif @deployment.save\n\t\t\trender :json => \"Done\"\n\t\telse\n\t\t\trender :json => \"Errors\"\n\t\tend\n\tend",
"def create\n\t\tbegin\n\t\t\tActiveRecord::Base.transaction do\n\t\t\t\t@application = Application.create!(name: params[:name])\n end\n rescue => e #ActiveRecord::RecordNotUnique\n p e.message\n p e.backtrace\n\t\t\tActiveRecord::Rollback\n\t\t\trender plain: e.message, status: :unprocessable_entity and return\n end\n render json:\" Application created with token = #{@application.token}\", status: :created\n end",
"def create\n @execution_environment = ExecutionEnvironment.new(execution_environment_params)\n\n respond_to do |format|\n if @execution_environment.save\n format.html { redirect_to @execution_environment, notice: 'Execution environment was successfully created.' }\n format.json { render :show, status: :created, location: @execution_environment }\n else\n format.html { render :new }\n format.json { render json: @execution_environment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save(*args)\n if @new_record && !self.is_?(App)\n self.app_name = HesCentral.application_repository_name\n end\n super(*args)\n end",
"def create\n @admin_app = App.new(admin_app_params)\n\n respond_to do |format|\n if @admin_app.save\n format.html { redirect_to [:admin, @admin_app], notice: 'App was successfully created.' }\n format.json { render :show, status: :created, location: [:admin, @admin_app] }\n else\n format.html { render :new }\n format.json { render json: [:admin, @admin_app].errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @admin_environment_type = Admin::EnvironmentType.new(admin_environment_type_params)\n\n respond_to do |format|\n if @admin_environment_type.save\n format.html { redirect_to @admin_environment_type, notice: 'Environment type was successfully created.' }\n format.json { render :show, status: :created, location: @admin_environment_type }\n else\n format.html { render :new }\n format.json { render json: @admin_environment_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_application(application_entity)\n # handle runtimes / cartridges\n fail_with(:only_one_runtime) if application_entity[:runtimes].length > 1\n fail_with(:must_have_runtime) if application_entity[:runtimes].empty?\n application_entity[:cartridge] = cartridge(application_entity.delete(:runtimes)[0])\n\n # updates the application with a valid region identity\n retrieve_region(application_entity) if application_entity.key?(:region)\n\n # enable application scaling by default\n application_entity[:scale] = true unless application_entity.key?(:scale)\n created_application = post(\"/domains/#{app_domain}/applications\", body: application_entity).body\n # now make sure we keep at least 2 deployments, allows proper identification of application state\n updated_application = put(\"/application/#{created_application[:data][:id]}\",\n body: { keep_deployments: 2, auto_deploy: false }).body\n to_nucleus_app(updated_application[:data])\n end",
"def new_deployment(attrs)\n Deployment.from_hash(api, attrs.merge(:app_environment => self))\n end",
"def create(*args)\n if !self.is_?(App)\n self.app_name = HesCentral.application_repository_name\n end\n super(*args)\n end",
"def create\n @app = App.new(app_params)\n @app.count = 0\n @app.uid = SecureRandom.uuid\n respond_to do |format|\n if @app.save\n format.html { redirect_to app_path(uid: @app.uid), notice: 'App was successfully created.' }\n format.json { render :show, status: :created, location: @app }\n else\n format.html { render :new }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @app = current_user.apps.new(params[:app])\n\n respond_to do |format|\n if @app.save\n format.html { redirect_to @app, :notice => \"The application app was successfully created\" }\n format.xml { render :xml => @app, :status => :created, :location => @app }\n else\n format.html { render :action => :new }\n format.xml { render :xml => @app.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def env=(environment); end",
"def env=(environment); end",
"def create\n @project_environment = @project.project_environments.new(project_environment_params)\n\n respond_to do |format|\n if @project_environment.save\n format.html { redirect_to @project, notice: 'Project environment was successfully created.' }\n format.json { render :show, status: :created, location: @project_environment }\n else\n format.html { render 'projects/edit', project_environment: @project_environment }\n format.json { render json: @project_environment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_app()\n app = OpenShift::TestApplication.new(self)\n\n $logger.info(\"Created new application #{app.name} for account #{@name}\")\n\n @apps << app\n app\n end",
"def create\n authorize! :create, @app\n @app = App.new(app_params)\n\n respond_to do |format|\n if @app.save\n format.html { redirect_to @app, notice: 'App was successfully created.' }\n format.json { render :show, status: :created, location: @app }\n else\n format.html { render :new }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @app = App.new(app_params)\n #added code for realizers list\n\t#@developers = Developer.where(:id => params[:realizers])\n #logger.debug \"DEVELOPER: #{@developers.inspect} \\n\"\n\t#@app.developers << @developers \n #logger.debug \"DEVELOPERS: #{@app.developers.inspect} \\n\"\n\t#end code\n\n respond_to do |format|\n if @app.save\n @app.developers << current_dev \n format.html { redirect_to @app, notice: 'App was successfully created.' }\n format.json { render :show, status: :created, location: @app }\n else\n format.html { render :new }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save_env; end",
"def create\n @job = Job.find(params[:job_id])\n @application = Application.new(application_params)\n @application.job = @job\n @application.user = current_user\n\n if @application.save\n redirect_to developers_applications_path\n else\n redirect_to job_path(@job)\n end\n end",
"def create\n @app = App.new(params[:app])\n\n respond_to do |format|\n if @app.save\n format.html { redirect_to @app, notice: 'App was successfully created.' }\n format.json { render json: @app, status: :created, location: @app }\n else\n format.html { render action: \"new\" }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def dup_environment\n\n env = fetch_environment\n env = env.dup\n env.fei = @fei.dup\n env.fei.expression_name = EN_ENVIRONMENT\n @environment_id = env.fei\n\n env.store_itself\n end",
"def create\n @app = App.new(app_params)\n\n respond_to do |format|\n if @app.save\n format.html { redirect_to @app, notice: 'App was successfully created.' }\n format.json { render :show, status: :created, location: @app }\n else\n format.html { render :new }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @app = App.new(app_params)\n\n respond_to do |format|\n if @app.save\n format.html { redirect_to @app, notice: 'App was successfully created.' }\n format.json { render :show, status: :created, location: @app }\n else\n format.html { render :new }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @application = Application.new(application_params)\n\n if @application.save\n render json: @application, status: :created, location: api_application_path(@application)\n else\n render json: @application.errors.full_messages.join(', '), status: :unprocessable_entity\n end\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 app_state_environment\n app_state[:environment] ||= Mash.new\n end",
"def create\n authorize @application, policy_class: Oauth::ApplicationPolicy\n @application = Doorkeeper::Application.new(application_params)\n @application.owner = current_user if T.unsafe(Doorkeeper).configuration.confirm_application_owner?\n if @application.save\n flash[:notice] = I18n.t(:notice, scope: [:doorkeeper, :flash, :applications, :create])\n redirect_to oauth_application_url(@application)\n else\n render :new\n end\n end",
"def environment(app)\n choose do |menu|\n puts Rainbow(\"Step 2. Adding the Rails environment\").foreground(:green)\n\n menu.prompt = \"Which environment?\"\n\n menu.choice \"production\" do\n Bundler.with_clean_env do\n system(\"heroku config:set RACK_ENV=production RAILS_ENV=production --app #{app}\")\n end\n end\n\n menu.choice \"staging\" do\n Bundler.with_clean_env do\n system(\"heroku config:set RACK_ENV=staging RAILS_ENV=staging --app #{app}\")\n system(\"cp config/environments/production.rb config/environments/staging.rb\")\n end\n end\n end\n end",
"def set_app_environment_credential\n @app_environment_credential = AppEnvironmentCredential.find(params[:id])\n end",
"def create\n\t\t@application = Application.new(params[:application])\n\n\t\tif @application.save\n\t\t\tflash[:developer] = \"Yay! Your application has been registered!\"\n\t\t\tcurrent_developer.applications << @application\n\t\t\t# Randomizer as in http://goo.gl/qpI5Rv\n\t\t\taccess_token = Array.new(32){rand(36).to_s(36)}.join\n\t\t\tkey = ApiKey.create(:access_token => access_token)\n\t\t\tkey.application = @application\n\t\t\tkey.save\n\t\t\tredirect_to developer_home_path\n\t\telse\n\t\t\trender :action => 'register'\n\t\tend\n\tend",
"def create\n @application = Application.new(application_params)\n\n respond_to do |format|\n if @application.save\n format.html { redirect_to \"/applications/#{@application.id}/step2\", notice: 'Application was successfully created.' }\n format.json { render :show, status: :created, location: @application }\n else\n format.html { render :new }\n format.json { render json: @application.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @application = Application.new(application_params)\n\n respond_to do |format|\n if @application.save\n current_user.application = @application\n current_user.save\n format.html { redirect_to @application, notice: 'Application successfully sent in.' }\n format.json { render :show, status: :created, location: @application }\n else\n format.html { render :new }\n format.json { render json: @application.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_application_record\n template \"application_record.rb\", application_record_file_name\n end",
"def add_environment_relation(client, env_id, name)\n\n self.info(\"Adding environment relation to target'#{name}'..\")\n\n # add environment relation to target\n csv_string = CSV.generate do |csv|\n csv << [\"system_environment.system_id\", \"system_deployment_target.system_name\"]\n csv << [env_id, name]\n end\n\n message = { \"username\" => @resource[:connection]['username'], \"password\" => @resource[:connection]['password'], \"mainType\" => \"EnvironmentDeploymentTargetRelation\", \"failOnError\" => true, \"fomat\" => \"CSV\", \"data\" => csv_string}\n response = client.call(:import, message: message)\n\n status = response.body[:import_response][:import_result][:status].to_i \n \n token = response.body[:import_response][:import_result][:token]\n\n self.debug(\"Got token: #{token}\")\n \n #while status == 0\n # sleep 1\n # response = client.call(:get_status, message: { \"token\" => token } )\n # status = response.body[:get_status_response][:get_status_result][:status].to_i \n #end\n\n error = response.body[:import_response][:import_result][:error] \n\n if status < 0\n self.info(\"Unsuccessfully add environment id #{env_id} to target #{name}\")\n if not error.nil? and not error.empty?\n self.info(\"Error detail: \" + error.to_s)\n end\n return\n end\n \n self.info(\"Environment update finished\")\n end",
"def create_appplication_key\n\t\t# set guid key for current application_id\n\t\t# self.application_id = Admin::Guid.new.key\n\t\t@application_id = Admin::Guid.new.key\n\tend",
"def create\n session[:application_params].deep_merge!(params[:application]) if params[:application]\n @application = Application.new(session[:application_params]) \n @application.current_step = session[:application_step]\n @application.job_id = params[:application][:job_id]\n @application.trade_id = params[:application][:trade_id]\n if params[:previous_button]\n @application.previous_step\n elsif @application.last_step? \n @application.save\n else\n @application.next_step\n end\n\n session[:application_step] = @application.current_step\n if @application.new_record?\n render :new\n else\n session[:application_step] = session[:application_params] = nil\n flash[:notice] = \"Application saved\"\n redirect_to @application\n end\n end",
"def app_environment_resource_params\n params.require(:app_environment_resource).permit(:app_environment_id, :app_resource_id, :count, :ami_id, :instance_type)\n end",
"def setup_environment; end",
"def write_build_environments(path)\n r = Chef::Resource::File.new(::File.join(path, \"#{new_resource.chef_environment}.json\"), run_context)\n r.content(Chef::Environment.load(new_resource.chef_environment).to_json)\n r.run_action(:create)\n end",
"def create\n @application = Oread::Application.new(application_params)\n @application.owner = current_user\n respond_to do |format|\n if @application.save\n format.html { redirect_to settings_admin_oread_applications_path, notice: 'Application was successfully created.' }\n format.json { render :show, status: :created, location: @application }\n else\n format.html { render :new }\n format.json { render json: @application.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @application = Doorkeeper::Application.new(application_params)\n @application.uid = SecureRandom.hex(4)\n @application.owner = current_user if Doorkeeper.configuration.confirm_application_owner?\n\n if @application.save\n flash[:notice] = I18n.t(:notice, scope: [:doorkeeper, :flash, :applications, :create])\n redirect_to oauth_application_url(@application)\n else\n render :new\n end\n end",
"def create\n params[:app][:user_id] = current_user.id\n @app = App.create(params[:app])\n if @app.save\n redirect_to source_app_path(@app), notice: 'app was successfully created.'\n else\n render :new\n end\n end",
"def create\n if params[:create] == 'existing'\n @app = App.new(app_params)\n origin = @apps.find(params[:origin])\n\n @app.runtime = origin.runtime.dup\n @app.android_config = origin.android_config.dup\n @app.ios_config = origin.ios_config.dup\n @app.android_icon = origin.android_icon.dup\n @app.ios_icon = origin.ios_icon.dup\n\n @app.splash = origin.splash.dup\n\n @app.android_config['origin'] = origin.id\n @app.ios_config['origin'] = origin.id\n @app.android_config.delete('bundle_id')\n @app.ios_config.delete('bundle_id')\n\n @app.duplicate_files(origin)\n else\n @app = App.new(app_params)\n end\n\n @app.user = current_user\n\n if @app.save\n if origin\n origin.assets.each do |item|\n asset = Asset.new\n asset.app_id = @app.id\n asset.slug = item.slug\n asset.duplicate_file(item)\n asset.save!\n end\n end\n end\n\n respond_modal_with @app, location: @app\n end",
"def create\n @application = Doorkeeper::Application.new(application_params)\n @application.uid = SecureRandom.hex(4)\n @application.owner = current_user if Doorkeeper.configuration.confirm_application_owner?\n\n if @application.save\n flash[:notice] = I18n.t(:notice, scope: %i[doorkeeper flash applications create])\n redirect_to oauth_application_url(@application)\n else\n render :new\n end\n end",
"def create\n @application = Application.new(application_params)\n # @application.job_id = params[:id]\n @application.user_id = current_user.id\n respond_to do |format|\n if @application.save\n format.html { redirect_to @application, notice: 'Application was successfully created.' }\n format.json { render :show, status: :created, location: @application }\n else\n format.html { render :new }\n format.json { render json: @application.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n create_params = application_params\n if applicant_signed_in?\n create_params[:applicant_id] = current_applicant.id\n end\n @application = Application.new(create_params)\n\n respond_to do |format|\n if @application.save\n format.html { redirect_to @application, notice: \"Application was successfully created.\" }\n format.json { render :show, status: :created, location: @application }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @application.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @app_instance = AppInstance.new(app_instance_params)\n\n respond_to do |format|\n if @app_instance.save\n format.html { redirect_to @app_instance, notice: 'App instance was successfully created.' }\n format.json { render action: 'show', status: :created, location: @app_instance }\n else\n format.html { render action: 'new' }\n format.json { render json: @app_instance.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n megam_rest.post_marketplaceapp(to_hash)\n end",
"def create\n megam_rest.post_marketplaceapp(to_hash)\n end",
"def environment(name, options = {})\n @environments << Environment.new(name, options)\n end",
"def environment(environment); end",
"def create\n @app = App.new app_params\n @app.user = current_user\n \n if @app.valid?\n\n openid_client = Services::OpenIdConnectionService.new(@app).register\n\n\n if openid_client[\"client_id\"].present?\n @app.openid_client_id = openid_client[\"client_id\"]\n @app.openid_client_secret = openid_client[\"client_secret\"]\n @app.openid_client_access_token = openid_client[\"registration_access_token\"]\n @app.save\n end\n end\n\n respond_to do |format|\n if @app.persisted?\n format.html { redirect_to app_path(@app), notice: 'App was successfully created.' }\n format.json { render :show, status: :created, location: @app }\n else\n format.html { render :new }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @app = App.new(app_params)\n\n respond_to do |format|\n if @app.save\n flash[:success] = 'App was successfully saved.'\n format.html { redirect_to @app }\n format.json { render :show, status: :created, location: @app }\n else\n flash[:danger] = 'There was a problem creating the App Catalog Page.'\n format.html { render :new }\n format.json { render json: @app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def initialize_environment\n end",
"def initialize_environment\n end",
"def save_app_stack full_info\n ActiveRecord::Base.transaction do\n app = save_app build_app_attrs(full_info)\n\n save_versions app, build_versions_attrs(full_info)\n save_video app, build_video_attrs(full_info)\n save_recommend_apps app, build_recommend_apps_attrs(full_info)\n\n developer = save_developer build_developer_attrs(full_info)\n app.developer = developer if developer && developer.id\n\n category = save_category build_category_attrs(full_info)\n app.category = category if category && category.id\n\n source = save_source build_source_attrs(full_info)\n app.source = source if source && source.id\n\n tags = save_tags build_tags_attrs(full_info)\n app.tags = tags if tags.any?\n\n display_tags = save_display_tags build_display_tags_attrs(full_info)\n app.display_tags = display_tags if display_tags.any?\n\n app.not_available_count = 0 #reset not_available_count\n\n app.save!\n app\n end\n end",
"def create\n @application = Application.new(application_params)\n\n if @application.save\n @application.status = Application.where(nursery_id: @application.nursery_id, date: @application.date, status: :appointed).count < @application.nursery.capacity ? :appointed : :waiting\n @application.save\n render :show, status: :created, location: @application\n else\n render json: @application.errors, status: :unprocessable_entity\n end\n end",
"def app_environment\n os = host_os\n if os.nil?\n Applitools::EyesLogger.info 'No OS set, checking for mobile OS...'\n if driver.mobile_device?\n platform_name = nil\n Applitools::EyesLogger.info 'Mobile device detected! Checking device type..'\n if driver.android?\n Applitools::EyesLogger.info 'Android detected.'\n platform_name = ANDROID\n elsif driver.ios?\n Applitools::EyesLogger.info 'iOS detected.'\n platform_name = IOS\n else\n Applitools::EyesLogger.warn 'Unknown device type.'\n end\n # We only set the OS if we identified the device type.\n unless platform_name.nil?\n platform_version = driver.platform_version\n if platform_version.nil?\n os = platform_name\n else\n # Notice that Ruby's +split+ function's +limit+ is the number of elements, whereas in Python it is the\n # maximum splits performed (which is why they are set differently).\n major_version = platform_version.split('.', 2)[0]\n os = \"#{platform_name} #{major_version}\"\n end\n Applitools::EyesLogger.info \"Setting OS: #{os}\"\n end\n else\n Applitools::EyesLogger.info 'No mobile OS detected.'\n end\n end\n\n # Create and return the environment object.\n Applitools::Base::Environment.new(os, host_app, viewport_size, inferred_environment)\n end",
"def create\n @app_condition = AppCondition.new(app_condition_params)\n\n respond_to do |format|\n if @app_condition.save\n format.html { redirect_to @app_condition, notice: 'App condition was successfully created.' }\n format.json { render :show, status: :created, location: @app_condition }\n else\n format.html { render :new }\n format.json { render json: @app_condition.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_environment\n @environment = @suite.environments.find(params[:id])\n end",
"def create\n @parent_app = ParentApp.new(parent_app_params)\n\n respond_to do |format|\n if @parent_app.save\n format.html { redirect_to @parent_app, notice: 'Parent app was successfully created.' }\n format.json { render action: 'show', status: :created, location: @parent_app }\n else\n format.html { render action: 'new' }\n format.json { render json: @parent_app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @app = App.new(params[:app])\n \n # This is not right. I should write a dashboard view that talks to the controllers restfully\n if @app.auto_generate_database || !@app.snapshot_id.empty?\n # when valid? is call, self-generated app attibues are populated\n if @app.valid?\n if generate_database\n @app.save\n redirect_to @app, notice: 'App was successfully created.' \n end\n else\n render action: \"new\" \n end\n else\n if @app.save\n redirect_to @app, notice: 'App was successfully created.' \n else\n render action: \"new\" \n end\n end\n end",
"def setup_appengine_application(app, is_new_app)\n initialize_scaling_info_for_app(app)\n uac = UserAppClient.new(@userappserver_private_ip, @@secret)\n app_data = uac.get_app_data(app)\n loop {\n Djinn.log_info(\"Waiting for app data to have instance info for app named #{app}: #{app_data}\")\n\n app_data = uac.get_app_data(app)\n if app_data[0..4] != \"Error\"\n break\n end\n Kernel.sleep(5)\n }\n\n my_public = my_node.public_ip\n my_private = my_node.private_ip\n app_language = app_data.scan(/language:(\\w+)/).flatten.to_s\n \n if is_new_app and @app_info_map[app].nil?\n @app_info_map[app] = {}\n @app_info_map[app]['language'] = app_language\n end\n\n shadow = get_shadow\n shadow_ip = shadow.private_ip\n ssh_key = shadow.ssh_key\n app_dir = \"/var/apps/#{app}/app\"\n app_path = \"/opt/appscale/apps/#{app}.tar.gz\"\n FileUtils.mkdir_p(app_dir)\n \n # First, make sure we can download the app, and if we can't, throw up a\n # dummy app letting the user know there was a problem.\n if !copy_app_to_local(app)\n place_error_app(app, \"ERROR: Failed to copy app: #{app}\")\n app_language = \"python27\"\n end\n\n # Next, make sure their app has an app.yaml or appengine-web.xml in it,\n # since the following code assumes it is present. If it is not there\n # (which can happen if the scp fails on a large app), throw up a dummy\n # app.\n if !HelperFunctions.app_has_config_file?(app_path)\n place_error_app(app, \"ERROR: No app.yaml or appengine-web.xml for app \" +\n app)\n app_language = \"python27\"\n end\n\n HelperFunctions.setup_app(app)\n\n if is_new_app\n maybe_start_taskqueue_worker(app)\n end\n\n if is_new_app\n if @app_info_map[app]['nginx'].nil?\n @app_info_map[app]['nginx'] = find_lowest_free_port(Nginx::START_PORT)\n @app_info_map[app]['haproxy'] = find_lowest_free_port(\n HAProxy::START_PORT)\n @app_info_map[app]['nginx_https'] = Nginx.get_ssl_port_for_app(\n @app_info_map[app]['nginx'])\n end\n\n @app_info_map[app]['appengine'] = []\n end\n\n # Only take a new port for this application if there's no data about\n # this app. Use the existing port if there is info about it.\n nginx_port = @app_info_map[app]['nginx']\n https_port = @app_info_map[app]['nginx_https']\n proxy_port = @app_info_map[app]['haproxy']\n\n port_file = \"/etc/appscale/port-#{app}.txt\"\n if my_node.is_login?\n HelperFunctions.write_file(port_file, \"#{@app_info_map[app]['nginx']}\")\n Djinn.log_debug(\"App #{app} will be using nginx port #{nginx_port}, \" +\n \"https port #{https_port}, and haproxy port #{proxy_port}\")\n\n @nodes.each { |node|\n if node.private_ip != my_node.private_ip\n HelperFunctions.scp_file(port_file, port_file, node.private_ip,\n node.ssh_key)\n end\n }\n else\n loop {\n if File.exists?(port_file)\n Djinn.log_debug(\"Got port file for app #{app}\")\n break\n else\n Djinn.log_debug(\"Waiting for port file for app #{app}\")\n Kernel.sleep(5)\n end\n }\n end\n\n # TODO(cgb): Make sure we don't add the same cron lines in twice for the same\n # app, and only start xmpp if it isn't already started\n if my_node.is_shadow?\n CronHelper.update_cron(my_public, nginx_port, app_language, app)\n start_xmpp_for_app(app, nginx_port, app_language)\n end\n\n # We only need a new full proxy config file for new apps, on the machine\n # that runs the login service (but not in a one node deploy, where we don't\n # do a full proxy config).\n login_ip = get_login.private_ip\n if my_node.is_login?\n begin\n static_handlers = HelperFunctions.parse_static_data(app)\n Djinn.log_run(\"chmod -R +r #{HelperFunctions.get_cache_path(app)}\")\n rescue Exception => e\n # This specific exception may be a json parse error\n error_msg = \"ERROR: Unable to parse app.yaml file for #{app}.\" + \\\n \" Exception of #{e.class} with message #{e.message}\" \n place_error_app(app, error_msg)\n static_handlers = []\n end\n\n Nginx.write_fullproxy_app_config(app, nginx_port, https_port, my_public,\n my_private, proxy_port, static_handlers, login_ip)\n\n loop {\n Kernel.sleep(5)\n success = uac.add_instance(app, my_public, nginx_port)\n Djinn.log_debug(\"Add instance returned #{success}\")\n if success\n # tell ZK that we are hosting the app in case we die, so that\n # other nodes can update the UserAppServer on its behalf\n ZKInterface.add_app_instance(app, my_public, nginx_port)\n break\n end\n }\n end\n\n if my_node.is_appengine?\n # send a warmup request to the app to get it loaded - can shave a\n # number of seconds off the initial request if it's java or go\n # go provides a default warmup route\n # TODO: if the user specifies a warmup route, call it instead of /\n warmup_url = \"/\"\n\n app_manager = AppManagerClient.new(my_node.private_ip)\n # TODO(cgb): What happens if the user updates their env vars between app\n # deploys?\n if is_new_app\n @num_appengines.times { |index|\n appengine_port = find_lowest_free_port(STARTING_APPENGINE_PORT)\n Djinn.log_info(\"Starting #{app_language} app #{app} on \" +\n \"#{HelperFunctions.local_ip}:#{appengine_port}\")\n\n xmpp_ip = get_login.public_ip\n\n pid = app_manager.start_app(app, appengine_port,\n get_load_balancer_ip(), app_language, xmpp_ip,\n [Djinn.get_nearest_db_ip()], HelperFunctions.get_app_env_vars(app))\n\n if pid == -1\n place_error_app(app, \"ERROR: Unable to start application \" + \\\n \"#{app}. Please check the application logs.\")\n end\n\n # Tell the AppController at the login node (which runs HAProxy) that a\n # new AppServer is running.\n acc = AppControllerClient.new(get_login.private_ip, @@secret)\n loop {\n result = acc.add_appserver_to_haproxy(app, my_node.private_ip,\n appengine_port)\n if result == NOT_READY\n Djinn.log_info(\"Login node is not yet ready for AppServers to \" +\n \"be added - trying again momentarily.\")\n Kernel.sleep(5)\n else\n Djinn.log_info(\"Successfully informed login node about new \" +\n \"AppServer for #{app} on port #{appengine_port}.\")\n break\n end\n }\n }\n else\n Djinn.log_info(\"Restarting AppServers hosting old version of #{app}\")\n result = app_manager.restart_app_instances_for_app(app)\n end\n\n if is_new_app\n # now doing this at the real end so that the tools will\n # wait for the app to actually be running before returning\n done_uploading(app, app_path, @@secret)\n end\n end\n\n APPS_LOCK.synchronize {\n if @app_names.include?(\"none\")\n @apps_loaded = @apps_loaded - [\"none\"]\n @app_names = @app_names - [\"none\"]\n end\n\n if is_new_app\n @apps_loaded << app\n else\n @apps_to_restart.delete(app)\n end\n }\n end",
"def create\n @app = App.new(params[:app])\n\n respond_to do |format|\n if @app.save\n flash[:notice] = 'App was successfully created.'\n format.html { redirect_to app_activities_path(@app) }\n format.xml { render :xml => @app, :status => :created, :location => @app }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @app.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @application = Application.new(application_params)\n\n respond_to do |format|\n if @application.save\n format.html { redirect_to @application, notice: 'Application was successfully created.' }\n format.json { render :show, status: :created, location: @application }\n else\n format.html { render :new }\n format.json { render json: @application.errors, status: :unprocessable_entity }\n end\n end\n\n end",
"def create_model\n app = options[:app]\n return unless valid_model_for?(app)\n\n include_component_module_for(:test)\n migration_name = \"create_#{name.pluralize.underscore}\"\n apply_default_fields fields\n create_model_file(name, :fields => fields, :app => app)\n generate_model_test(name) if test?\n create_model_migration(migration_name, name, fields) unless options[:skip_migration]\n end",
"def create\n @regionenvironment = Regionenvironment.new(regionenvironment_params)\n\n respond_to do |format|\n if @regionenvironment.save\n format.html { redirect_to @regionenvironment, notice: 'Regionenvironment was successfully created.' }\n format.json { render :show, status: :created, location: @regionenvironment }\n else\n format.html { render :new }\n format.json { render json: @regionenvironment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @test_app = TestApp.new(test_app_params)\n\n respond_to do |format|\n if @test_app.save\n format.html { redirect_to @test_app, notice: \"Test app was successfully created.\" }\n format.json { render :show, status: :created, location: @test_app }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @test_app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def activate_app\n key = Key.new\n key.host = params[:data][:host]\n key.app_dataset_id = params[:data][:app_dataset_id]\n key.api_key = params[:data][:api_key]\n key.app_name = params[:controller]\n\n existing_job_board = JobBoard.find_by(app_dataset_id: params[:data][:app_dataset_id])\n unless existing_job_board.present?\n JobBoard.create(app_dataset_id: params[:data][:app_dataset_id])\n end\n\n respond_to do |format|\n format.json { render json: { success: key.save }}\n end\n end",
"def create_app(opts)\n app = nil\n scope = select_scope(opts[:scope])\n\n assets = Asset.accessible_by_user(user).\n where(\n state: Asset::STATE_CLOSED,\n uid: opts[:ordered_assets],\n )\n\n App.transaction do\n app_series = create_app_series(opts[:name], scope)\n release = opts.fetch(:release, UBUNTU_16)\n revision = app_series.latest_revision_app.try(:revision).to_i + 1\n\n applet_dxid = new_applet(\n opts.slice(\n :input_spec,\n :output_spec,\n :code,\n :instance_type,\n :packages,\n :internet_access,\n ),\n release,\n )\n\n app_dxid = new_app(\n opts.slice(\n :name,\n :title,\n :internet_access,\n :readme,\n ).merge(\n applet_dxid: applet_dxid,\n asset_dxids: assets.map(&:dxid),\n revision: revision,\n scope: scope,\n ),\n )\n\n api.project_remove_objects(project, [applet_dxid])\n\n app = App.create!(\n dxid: app_dxid,\n version: nil,\n revision: revision,\n title: opts[:title],\n readme: opts[:readme],\n entity_type: opts[:entity_type] || App::TYPE_REGULAR,\n user: user,\n scope: scope,\n app_series: app_series,\n input_spec: opts[:input_spec],\n output_spec: opts[:output_spec],\n internet_access: opts[:internet_access],\n instance_type: opts[:instance_type],\n ordered_assets: opts[:ordered_assets],\n packages: opts[:packages],\n code: opts[:code].strip,\n assets: assets,\n release: release,\n )\n\n app_series.update!(latest_revision_app: app)\n app_series.update!(latest_version_app: app) if Space.valid_scope?(scope)\n app_series.update!(deleted: false) if app_series.deleted?\n\n Event::AppCreated.create_for(app, user)\n end\n\n app\n end",
"def create\n if @environment\n attributes = params.delete(:data)\n attributes[:timestamp] = params[:event].delete(:timestamp).to_s\n attributes[:environment_id] = @environment.id\n attributes.merge!(params[:event])\n\n @event = Event.new(attributes.slice(*Event.attribute_names))\n\n if @event.error? && send_error_notifications?\n notify_honeybadger_event(@event, attributes)\n end\n\n respond_to do |format|\n if @event.save\n format.html { redirect_to @event, notice: 'Event was successfully created.' }\n format.json { render json: @event, status: :created, location: @event }\n else\n format.html { render action: \"new\" }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n else\n render nothing: true\n end\n end",
"def new_environment (initial_vars=nil)\n\n @environment_id = @fei.dup\n @environment_id.expression_name = EN_ENVIRONMENT\n\n parent_fei = nil\n parent = nil\n\n parent, _fei = get_expression_pool.fetch(@parent_id) \\\n if @parent_id\n\n parent_fei = parent.environment_id if parent\n\n env = Environment.new_env(\n @environment_id, parent_fei, nil, @application_context, nil)\n\n env.variables.merge!(initial_vars) if initial_vars\n\n env[@fei.wfname] = self.raw_representation \\\n if (not @parent_id) and (self.is_a?(RawExpression))\n #\n # keeping track of the raw representation\n # of the top expression (for top recursion)\n\n env.store_itself\n\n env\n end",
"def create\n manifest = JSON.parse(params[:manifest])\n manifest['provider'] = params[:provider]\n puts \"Repository type: #{params[:repository_type]}\"\n @client.app_create(params[:id], params[:repository_type])\n @client.app_add_manifest(params[:id], manifest)\n\n respond_to do |format|\n format.html { redirect_to app_path(params[:id]), notice: 'App was successfully created.' }\n #if @client.app_create(params[:id], manifest)\n # format.html { redirect_to app_path(params[:id]), notice: 'App was successfully created.' }\n # # FIXME format.json { render json: @app, status: :created, location: app_path(params[:id]) } \n #else\n # format.html { render action: \"new\" }\n # format.json { render json: @app.errors, status: :unprocessable_entity } # FIXME\n #end\n end\n end",
"def addApplication(appContext)\n super(appContext)\n self.eachNode { |n|\n n.addApplication(appContext)\n }\n end",
"def set_app()\n self.is_app = 1\n save()\n end",
"def create\n @second_rails_app = SecondRailsApp.new(params[:second_rails_app])\n\n respond_to do |format|\n if @second_rails_app.save\n format.html { redirect_to @second_rails_app, notice: 'Second rails app was successfully created.' }\n format.json { render json: @second_rails_app, status: :created, location: @second_rails_app }\n else\n format.html { render action: \"new\" }\n format.json { render json: @second_rails_app.errors, status: :unprocessable_entity }\n end\n end\n end",
"def appctrl_create( model )\n return appctrl_not_permitted() if ( @current_user.restricted? )\n @record = model.constantize.new( params[ model.downcase ], @current_user )\n\n if ( @record.save )\n view_context.apphelp_flash(\n :notice,\n :added,\n ApplicationController,\n :name => @record.class.model_name.human\n )\n\n redirect_to( send( \"#{ model.downcase.pluralize }_path\" ) )\n else\n render( :action => 'new' )\n end\n end",
"def create_app(name, url)\n JSON.parse((@cloudvox_api[\"/applications/create.json\"].post :call_flow => {:name => name}, :agi => {:url => url}).body)\n end",
"def environment=(env)\n @environment = env\n end",
"def create\n @app = App.new(params[:app])\n\n respond_to do |format|\n if @app.save\n format.html { redirect_to(@app, :notice => 'App was successfully created.') }\n format.xml { render :xml => @app, :status => :created, :location => @app }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @app.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @app = App.new(params[:app])\n\n respond_to do |format|\n if @app.save\n format.html { redirect_to(@app, :notice => 'App was successfully created.') }\n format.xml { render :xml => @app, :status => :created, :location => @app }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @app.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @application = Application.new(params[:application])\n @application.job = Job.find(params[:id])\n respond_to do |format|\n if @application.save\n format.html { redirect_to '/', notice: 'Application was received.' }\n format.json { render json: @application, status: :created, location: @application }\n else\n @job = Job.find(params[:id])\n @company = @job.company.name\n @title = @job.title\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end"
] | [
"0.65256363",
"0.6304114",
"0.6261735",
"0.62174433",
"0.610232",
"0.59940475",
"0.5989094",
"0.5982823",
"0.588807",
"0.5872824",
"0.58559215",
"0.581713",
"0.57413065",
"0.5702332",
"0.5695882",
"0.56542456",
"0.5649217",
"0.56359166",
"0.5634262",
"0.5627825",
"0.55960923",
"0.5577305",
"0.554596",
"0.5538563",
"0.5516032",
"0.5515796",
"0.54861283",
"0.54708207",
"0.5443348",
"0.5433303",
"0.5433303",
"0.5429086",
"0.5424108",
"0.5421337",
"0.5418701",
"0.5418489",
"0.5405572",
"0.5404647",
"0.5403725",
"0.53849435",
"0.53849435",
"0.537715",
"0.5372628",
"0.53612363",
"0.53538764",
"0.53421855",
"0.5338601",
"0.5328986",
"0.53197175",
"0.5315175",
"0.530743",
"0.5304811",
"0.530055",
"0.529911",
"0.5294994",
"0.52834237",
"0.5278332",
"0.5265168",
"0.52630174",
"0.5254373",
"0.5239725",
"0.523292",
"0.52204335",
"0.5219011",
"0.5215433",
"0.52021384",
"0.52021384",
"0.5201673",
"0.5200452",
"0.5194334",
"0.5188959",
"0.51805234",
"0.51805234",
"0.5177466",
"0.5162409",
"0.51586235",
"0.5152692",
"0.515088",
"0.514762",
"0.5144027",
"0.5136796",
"0.5135369",
"0.5131654",
"0.5130932",
"0.5128152",
"0.51178145",
"0.51168036",
"0.5115909",
"0.51157826",
"0.51150876",
"0.51143086",
"0.51016426",
"0.5099984",
"0.509052",
"0.50903773",
"0.5088209",
"0.50846744",
"0.5079909",
"0.5079909",
"0.5079073"
] | 0.5359012 | 44 |
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",
"def get_max_updated_at\r\n @summary.max_updated_at\r\n end",
"def last_update\n request = <<-STRING\n SELECT max(updated_at) FROM\n (SELECT updated_at FROM schools WHERE id = #{id}\n UNION\n SELECT updated_at FROM teachers WHERE school_id = #{id}\n UNION\n SELECT updated_at FROM addresses WHERE school_id = #{id}\n UNION\n SELECT c.updated_at FROM courses c, addresses a WHERE a.school_id = #{id} AND c.address_id = a.id\n UNION\n SELECT p.updated_at FROM properties p, courses c, addresses a WHERE a.school_id = #{id} AND c.address_id = a.id AND p.course_id = c.id) as subquery\n STRING\n return ActiveRecord::Base.connection.execute(request).first[\"max\"]\n end",
"def latest_restorable_time\n data[:latest_restorable_time]\n end",
"def latest_restorable_time\n data[:latest_restorable_time]\n end",
"def last_updated\n [updated_at, book_updated_at, photo_updated_at].compact.max\n end",
"def last_refresh\n @dt\n end",
"def last_refresh\n @dt\n end",
"def last_refresh\n @dt\n end",
"def updated_at\n @gapi[\"updated\"]\n end",
"def latest\n #zypper can only get a list of *all* available packages?\n output = zypper \"list-updates\"\n\n if output =~ /#{Regexp.escape @resource[:name]}\\s*\\|.*?\\|\\s*([^\\s\\|]+)/\n return $1\n else\n # zypper didn't find updates, pretend the current\n # version is the latest\n return @property_hash[:ensure]\n end\n end",
"def last_updated_at\n @last_updated_at\n end",
"def last_update() (last_answer = answers.last) ? last_answer.time_stamp : created_at end",
"def last_updated(version = nil)\n version ||= current_version\n return @last_update[version] if @last_update[version]\n\n metadata = JSON.parse(json_pathname(version).read)['metadata']\n @last_update[version] = Date.parse(metadata['release_date'])\n end",
"def latest\n #rug can only get a list of *all* available packages?\n output = rug \"list-updates\"\n\n if output =~ /#{Regexp.escape @resource[:name]}\\s*\\|\\s*([^\\s\\|]+)/\n return $1\n else\n # rug didn't find updates, pretend the current\n # version is the latest\n return @property_hash[:ensure]\n end\n end",
"def last_polled_at\n Time.now\n end",
"def currentMaxTemp(weather_info)\n\tweather_info[\"daily\"][\"data\"][0][\"temperatureMax\"].to_i\nend",
"def last_edited\n self.latest_update.to_date\n end",
"def fetch_weather\n\t response = HTTParty.get(\"http://api.wunderground.com/api/cdb75d07a23ad227/#{date}/q/#{location}/#{cityfixed}.xml\")\n\t parse_response(response)\n\tend",
"def last_edited\n\t\tself.latest_update.to_date\n\tend",
"def last_synchronize\n last_update\n end",
"def updated_last_price\n return StockQuote::Stock.quote(self.ticker).latest_price\n end",
"def latest_update\n last = t('ddf.news.updates').keys.last\n t('ddf.news.updates')[last].html_safe\n rescue\n nil\n end",
"def find_last_updated_mir\n @max_updated_at = @swimmer.meeting_individual_results.exists? ? @swimmer.meeting_individual_results.sort_by_updated_at('DESC').first.updated_at : 0\n end",
"def last_update(window = 30, status_type = equipment_statuses)\n status_type.updated_after(updated_at - window).last\n end",
"def updated\n return @poco_data[:updated] unless @poco_data == nil\n upd = pick_first_node(@poco.xpath('./poco:updated'))\n if upd != nil\n DateTime.parse(upd)\n end\n end",
"def last_updated\n f = Folder.where(:id => params['id']).first\n render json: f.nil? ? \"unknown\" : f.updated_at\n end",
"def updated\n updated_at.utc.strftime(\"%F %T\") if updated_at\n end",
"def last_updated\n repo = Grit::Repo.init_bare_or_open(File.join(path , '.git'))\n repo.commits.first.commited_date\n end",
"def updated\n DateTime.parse(@json['project']['meta']['updated'])\n end",
"def last_api_use_at\n @attributes[:last_api_use_at]\n end",
"def get_weather_main\n get_weather[0][\"main\"]\n end",
"def latest_stat\n stat_for_progress(latest_key)\n end",
"def current_weather_data\r\n response = self.get_data\r\n\r\n # next steps: error handling in case the call breaks outright and returns nothing / no error code / a socketerror\r\n return unless response.response.code == \"200\"\r\n\r\n data_points = JSON.parse(response.body)[\"list\"]\r\n weather_hash = {}\r\n\r\n # loop through the data points and then add to a list of points for each individual day\r\n data_points.map { |data_point|\r\n forecast_time = DateTime.strptime(data_point[\"dt\"].to_s,'%s').in_time_zone(\"Central Time (US & Canada)\")\r\n forecast_date = forecast_time.strftime(\"%B %-e\")\r\n weather_hash[forecast_date] = [] if weather_hash[forecast_date].blank?\r\n\r\n temperature = data_point[\"main\"][\"temp\"]\r\n weather_text = data_point[\"weather\"].first[\"description\"]\r\n icon = data_point[\"weather\"].first[\"icon\"]\r\n\r\n weather_hash[forecast_date] << {temperature: temperature, weather: weather_text, icon: icon}\r\n }\r\n\r\n weather_hash.keys.each do |key|\r\n weather_hash[key] = daily_weather(weather_hash[key])\r\n end\r\n\r\n # sometimes the way that the forecast looks out, we end up with extra days' worth of content\r\n # I'd check with the PO to see if we only want to consider full days of weather data\r\n # but for now I'm going to focus on the first five soonest days we have data for, and ignore the bits of day 6 that might creep into the feed\r\n return engagement_data(weather_hash).first(5)\r\n end",
"def last_modified_date()\n\t\tmax_update = @database.execute(\"SELECT MAX(updated) as maxmodified FROM invoices;\")\n\t\tif (DBCHOICE == 'sqlite3') then\n\t\t\treturn max_update[0][0]\n\t\telsif (DBCHOICE == 'mysqltest' || DBCHOICE == 'mysql') then\n\t\t\t# structure is hash of hashes, look for the maxmodified key in 1st record and return\n\t\t\tmax_update.each do |row|\n\t\t\t\treturn row['maxmodified']\n\t\t\tend # max_update.each\n\t\tend\n\tend",
"def last_updated_at\n [ self.calendar_items.accessible.maximum('nodes.created_at'), self.updated_at ].compact.max\n end",
"def last_line_modified_date()\n\t\tmax_update = @database.execute(\"SELECT MAX(updated) as maxmodified FROM invoice_lines;\")\n\t\tif (DBCHOICE == 'sqlite3') then\n\t\t\treturn max_update[0][0]\n\t\telsif (DBCHOICE == 'mysqltest' || DBCHOICE == 'mysql') then\n\t\t\t# structure is hash of hashes, look for the maxmodified key in 1st record and return\n\t\t\tmax_update.each do |row|\n\t\t\t\treturn row['maxmodified']\n\t\tend # max_update.each\n\tend\nend",
"def find_last_updated_mir\n @team.meeting_individual_results.exists? ? @team.meeting_individual_results.sort_by_updated_at('DESC').first.updated_at : 0\n end",
"def get_weather\n location_id = params[:location_id].to_i\n date = Date.parse(params[:date])\n location = Location.find(location_id)\n current_time = Time.now\n weather_obs_list = Observation.where(location_id: location_id)\n latest_weather = weather_obs_list.last\n\n if (latest_weather.updated_at - current_time).to_i.abs > 30*60\n current_temp = \"Null\"\n else\n current_temp = latest_weather.temperature\n end\n\n current_cond = \"sunny\"\n if latest_weather.rainfall == 0\n current_cond = \"sunny\"\n else\n current_cond = \"raining\"\n end\n\n @hash = {}\n @hash[\"date\"] = date\n @hash[\"current_temp\"] = current_temp\n @hash[\"current_cond\"] = current_cond\n\n measurements = Array.new\n weather_obs_list.each do |weather|\n if weather.timestamp.to_date == date\n measurement_hash = Hash.new\n measurement_hash[\"time\"] = weather.updated_at\n measurement_hash[\"temp\"] = weather.temperature\n measurement_hash[\"precip\"] = weather.rainfall\n measurement_hash[\"wind_direction\"] = weather.wind_dir\n measurement_hash[\"wind_speed\"] = weather.wind_speed\n measurements << measurement_hash\n end\n end\n @hash[\"measurements\"] = measurements\n end",
"def latest\n @latest = apiQuery(\"items(first:1, order:UPDATED_DESC, include:[PUBLISHED,EMBARGOED]) { nodes { updated } }\").\n dig(\"items\", \"nodes\", 0, \"updated\")\n end",
"def previous_forecast\n self.class.get_forecast( { location: prev_location, days: prev_days } )\n end",
"def last_modified\n @metadata[:last_modified] || Time.now.utc\n end",
"def last_modified\n stat.mtime\n end",
"def ukextremes_latest_observations\n query('txt/wxobs/ukextremes/json/latest')\n end",
"def latest\n upd = latest_info\n unless upd.nil?\n # FIXME: there could be more than one update for a package\n # because of multiarch\n return \"#{upd[:epoch]}:#{upd[:version]}-#{upd[:release]}\"\n else\n # Yum didn't find updates, pretend the current\n # version is the latest\n raise Puppet::DevError, \"Tried to get latest on a missing package\" if properties[:ensure] == :absent\n return properties[:ensure]\n end\n end",
"def latest\n upd = latest_info\n unless upd.nil?\n # FIXME: there could be more than one update for a package\n # because of multiarch\n return \"#{upd[:epoch]}:#{upd[:version]}-#{upd[:release]}\"\n else\n # Yum didn't find updates, pretend the current\n # version is the latest\n raise Puppet::DevError, \"Tried to get latest on a missing package\" if properties[:ensure] == :absent\n return properties[:ensure]\n end\n end",
"def get_weather\t\n\t\t# get weather for location\n\t\t# Vancouver, BC (CAXX0518)\n\t\t# Washington, DC (USDC0001)\n\t @weather = YahooWeather::Client.new.lookup_location('CAXX0518', 'c')\n\t\t# GOOGLE WEATHER gives a 4 day forecast (including today)\n\t\t@forecast = GoogleWeather.new(\"Vancouver,BC\") \n\tend",
"def getlastmodified\n if !record.nil? and record.respond_to? :updated_at\n record.updated_at.httpdate\n end\n end",
"def _state_resorts_last_update(state_id)\n get('region', state_id, 'resorts/lastupdate', options: { type: :array })\n end",
"def updated\n if @updated.nil?\n updated_string = FeedTools::XmlHelper.try_xpaths(self.channel_node, [\n \"atom10:updated/text()\",\n \"atom03:updated/text()\",\n \"atom:updated/text()\",\n \"updated/text()\",\n \"atom10:modified/text()\",\n \"atom03:modified/text()\",\n \"atom:modified/text()\",\n \"modified/text()\",\n \"lastBuildDate/text()\"\n ], :select_result_value => true)\n unless updated_string.blank?\n @updated = Time.parse(updated_string).gmtime rescue nil\n else\n @updated = nil\n end\n end\n return @updated\n end",
"def current_temperature(weather_info)\n\tweather_info[\"currently\"][\"temperature\"].to_i\nend",
"def latest_observations\n path = 'stations/%s/observations/latest' % [@id]\n get(path)['properties']\n end",
"def last_sighted\n sightings.order(:updated_at).last.updated_at\n end",
"def getLatest()\n return Gesellschafter.get(self.Mnr)\n end",
"def updated_at\n Time.at @updated rescue nil\n end",
"def getWeatherData\n @tempModel = Temp\n current_date = Date.today.strftime \"%Y-%m-%d\"\n \n response = RestClient.get(\"http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=#{ENV['WEATHER_API_KEY']}&q=30.404251,-97.849442&date=2020-06-05&enddate=#{current_date}&format=json\n \", headers={})\n jsonified_response = JSON.parse(response)\n \n # API response is parsed and inserted into DB by the model method postWeatherData\n @tempModel.postWeatherData(jsonified_response);\n puts current_date\n end",
"def get_last_modified(feed)\n\t\t\t#assume, that first entry is newest\n\t\t\tfeed.last_modified || (feed.entries[0] && feed.entries[0].published) || Time.now\n\t\tend",
"def most_recent\n self.stats.first\n end",
"def updated\n DateTime.parse(@json['user']['meta']['updated'])\n end",
"def updated_at\n @updated_at ||= begin\n updated_dates = [self[:updated_at] || self[:created_at] || Date.null_date.to_time]\n updated_dates += self.captions.collect{|c| c.updated_at }\n \n updated_dates.compact.max\n end\n end",
"def city_weather\n self.class.get(\"/data/2.5/forecast\", @options)\n end",
"def last_fetch\n datetime_from(\"sf:last_fetch\")\n end",
"def update_weather\r\n # Update weather graphic\r\n @weather.type = $game_screen.weather_type\r\n @weather.max = $game_screen.weather_max\r\n @weather.update\r\n end",
"def getWeather(location)\n\tinfo = HTTParty.get(\"https://api.forecast.io/forecast/#{API_KEY}/#{location}\")\n\treturn info\nend",
"def outdated_last_reboot\n BOOT_TIME\n end",
"def get_weather_description\n get_weather[0][\"description\"]\n end",
"def windSpeed(weather_info)\n\tweather_info[\"currently\"][\"windSpeed\"]\nend",
"def updated_at\n @udpated_at ||=\n Utilities.utc_to_localtime(@ldap_entry[:whenchanged].first)\n end",
"def currentMinTemp(weather_info)\n\tweather_info[\"daily\"][\"data\"][0][\"temperatureMin\"].to_i\nend",
"def get_current_temp\n result = HTTParty.get( @tstat_ip + '/tstat/temp', :headers => @headers) \n \n degrees = result['temp']\n\n if @units == :c || @units == :celsius\n degrees = ( degrees - 32 ) * 5 / 9\n end\n\n return degrees\n end",
"def last_downtime\n send_message!(Protocol::Device::GetInfo.new,\n wait_for: Protocol::Device::StateInfo) do |payload|\n payload.downtime.to_f / NSEC_IN_SEC\n end\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.6436162",
"0.6429892",
"0.6419333",
"0.6419333",
"0.64105886",
"0.64053506",
"0.64053506",
"0.64053506",
"0.64004356",
"0.6388318",
"0.638489",
"0.6356806",
"0.63460505",
"0.6344087",
"0.6336283",
"0.63326037",
"0.6319967",
"0.6319779",
"0.6314708",
"0.6305152",
"0.62910557",
"0.6282346",
"0.62789077",
"0.6253142",
"0.62326103",
"0.6231921",
"0.623178",
"0.61885005",
"0.6173457",
"0.6154381",
"0.6144767",
"0.6132872",
"0.61158067",
"0.61116225",
"0.6107721",
"0.61041677",
"0.6099178",
"0.6092561",
"0.6090676",
"0.60873127",
"0.60843354",
"0.60816294",
"0.6075832",
"0.6046291",
"0.6046291",
"0.60412055",
"0.6040714",
"0.6040701",
"0.60395503",
"0.6033242",
"0.6027731",
"0.6023631",
"0.60229844",
"0.60060513",
"0.6005674",
"0.5996371",
"0.59958255",
"0.5982333",
"0.5979513",
"0.5974441",
"0.59710133",
"0.597039",
"0.5970296",
"0.5955118",
"0.59536254",
"0.593723",
"0.59304625",
"0.59299797",
"0.592608",
"0.59201753"
] | 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?(user=@session.user)\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",
"def custom_permissions_read(_notebook, _user, _use_admin=false)\n true\n end",
"def access_rights_for_permission(perm)\n sym = Lockdown.get_symbol(perm)\n\n permissions[sym]\n rescue \n raise SecurityError, \"Permission requested is not defined: #{sym}\"\n end",
"def allowed_to_read_other_users\n return @allowed_to_read_other_users\n end",
"def access_text()\n result = case access\n when Codegen::Access::RW then \"read/write\"\n when Codegen::Access::RO then \"read only\"\n when Codegen::Access::IA then \"inaccessible\"\n end\n result = \"open\" if public\n result\n end",
"def device_privates(id)\n get(\"/devices/#{id}/privates\")\n end",
"def privileged_access?\n connected? || PrismicService.access_token\n end",
"def everyone(read, write)\n apply(PUBLIC, read, write)\n permissions[PUBLIC]\n end",
"def getAccessInfo()\n @accessInfo\n end",
"def read_permitted?\n true\n end",
"def index\n @rubidevices = Rubidevice.accessible_by(current_ability)\n end",
"def read_only\n true\n end",
"def accessible\n accessible_for(Aurita.user)\n end",
"def peek_at_priv_read1; priv_read1; end",
"def list_authorized?\n authorized_for?(:crud_type => :read)\n end",
"def list_authorized?\n authorized_for?(:crud_type => :read)\n end",
"def standard_authorized_user_rights\n public_access + protected_access \n end",
"def available_for_read?; end",
"def read_only_recommended\n @read_only = 2\n end",
"def access_level\n config[:access] || 'private'\n end",
"def read\n iface = Qt::DBusInterface.new(SERVICE_NAME, READ_PATH, \"\", Qt::DBusConnection.sessionBus)\n raise \"D-BUS Interface Error : #{Qt::DBusConnection.sessionBus.lastError.message}\" unless iface.valid?\n msg = iface.call(Qt::DBus::BlockWithGui, \"read\", url)\n reply = Qt::DBusReply.new(msg)\n raise \"D-BUS Reply Error : #{reply.error.message}\" unless reply.valid?\n reply.value\n end",
"def custom_read_check(user, use_admin=false)\n Revision.custom_permissions_read(self, user, use_admin)\n end",
"def allowed_to_read_bitlocker_keys_for_owned_device\n return @allowed_to_read_bitlocker_keys_for_owned_device\n end",
"def guest_access\n client.api.get_room_guest_access(id)[:guest_access].to_sym\n end",
"def read_host_only_interfaces\n end",
"def show\n authorize! :show, @characteristic\n end",
"def can_access user\n list = List.find(self.list_id)\n\n return list.can_access user\n end",
"def readable_by?(user)\n user.in_session?(resource) || user.admin_for?(resource.course)\n end",
"def has_access?\n true\n end",
"def has_access?\n true\n end",
"def can_read?(user)\n (self.user == user) || course.can_edit?(user)\n end",
"def canBeReadBy? 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 if user.isAdmin == 1\n return true\n elsif user.name == @user\n if @userRights >= 4\n return true\n else\n return false\n end\n elsif isIncludedIn? user.groups, @group\n if @groupRights >= 4\n return true\n else\n return false\n end\n else\n if @othersRights >= 4\n return true\n else\n return false\n end\n end\n end",
"def allow_access_by_any_user\n @attributes[:allow_access_by_any_user]\n end",
"def permissions\n attribute_prop(5)\n end",
"def device_sharing_allowed\n return @device_sharing_allowed\n end",
"def [](name)\n handle = system.run(:search, \"user\", name, nil, @keyring)\n return nil if handle == -1\n\n system.get(:read, handle)\n end",
"def listings\n authorize! :read, @user\n end",
"def peek_at_priv_read3_via_protected_access_BAD; self.priv_read3; end",
"def read_only?; end",
"def read_only?; end",
"def required_resource_access\n return @required_resource_access\n end",
"def can_read?(resource)\n scope_name = resource.class.to_s.downcase.pluralize\n self.send(\"readable_#{scope_name}\").where(\"`permissions`.resource_type = ? AND `permissions`.resource_id = ?\", resource.class.to_s, resource.id).exists?\n end",
"def can_read?(folder_id)\n administrator? or\n permissions.for_read.exists? :folder_id => folder_id\n end",
"def index\n @devices = current_user.devices\n end",
"def can_access?\n allows_current_user_access_to? :access\n end",
"def discovery_permissions\n @discovery_permissions ||= %w[edit read]\n end",
"def is_reader?(user)\n public || permitted?(readers_join_table, user)\n end",
"def check_write_access(obj)\n return obj unless LinkedData.settings.enable_security\n if obj.is_a?(LinkedData::Models::Base) && obj.write_restricted?\n writable = obj.writable?(env[\"REMOTE_USER\"])\n error 403, \"Access denied for this resource\" unless writable\n end\n end",
"def index\n @users = User.select{ |_| can? :read, _ }\n end",
"def read_only\n false\n end",
"def check_read_access(ven, plan_id = nil)\r\n usr = current_user\r\n check_read_access_helper(ven, plan_id, usr)\r\n end",
"def readwrite_user\n super\n end",
"def readable?(_user)\n true\n end",
"def can_access?(space = object)\n space.accessible_by_user?(current_user)\n end",
"def privileged?\n get_mode == :privileged\n end",
"def discovery_permissions\n @discovery_permissions ||= %w[edit discover read]\n end",
"def discovery_permissions\n @discovery_permissions ||= [\"edit\",\"discover\",\"read\"]\n end",
"def permission\n Ricer::Irc::Permission.by_permission(self.permissions, authenticated?)\n end",
"def show\r\n authorize! :read, @pb_areainfo\r\n end",
"def show\n authorize! :show, @characteristic_value\n end",
"def index\n @devices = current_user.devices\n end",
"def read_only?\n @read_only\n end",
"def has_access(developer)\r\n current_user.id == developer.id\r\n end",
"def user_access_control\n bot = Bot.find(params[:id])\n\n if current_user.admin?\n @bot = User.find(bot.account.user_id).admin? ? current_user.bots.find(params[:id]) : bot\n else\n @bot = current_user.bots.find(params[:id])\n end\n\n rescue\n response_access_denied\n end",
"def show\r\n authorize! :read, @operation_player\r\n end",
"def get_patient(id)\n current_resource_owner.viewable_patients.find_by(id: id)\n end",
"def read_only?\n @read_only\n end",
"def user()\n return @data[\"access\"][\"user\"]\n end",
"def index\n \t@users = User.accessible_by(current_ability)\n \tauthorize! :read, User\n end",
"def has_access? c\n access_rights[controller2right c] == '1'\n end",
"def read_persons(pid)\n read_individual_field = Hydra.config[:permissions][:read][:individual]\n doc = permissions_doc(pid)\n rp = edit_persons(pid) | ((doc == nil || doc.fetch(read_individual_field,nil) == nil) ? [] : doc.fetch(read_individual_field,nil))\n logger.debug(\"[CANCAN] read_persons: #{rp.inspect}\")\n return rp\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.5884657",
"0.5860012",
"0.5850873",
"0.5846021",
"0.58295643",
"0.58200467",
"0.5812308",
"0.57999575",
"0.5797886",
"0.5796574",
"0.5794419",
"0.5784625",
"0.5768124",
"0.57651055",
"0.57651055",
"0.57607967",
"0.5755121",
"0.57349527",
"0.57341033",
"0.5730969",
"0.57305694",
"0.5730479",
"0.57289886",
"0.5723686",
"0.5723625",
"0.57163525",
"0.56930166",
"0.56882674",
"0.56882674",
"0.56667966",
"0.5664554",
"0.56628585",
"0.56533426",
"0.5651492",
"0.56399125",
"0.56339246",
"0.56320995",
"0.5626183",
"0.5626183",
"0.5625882",
"0.5623667",
"0.56221867",
"0.5620626",
"0.5618528",
"0.560839",
"0.5603218",
"0.56022674",
"0.5600038",
"0.55966043",
"0.5591049",
"0.55888814",
"0.5586979",
"0.55807287",
"0.55797297",
"0.55787975",
"0.55727947",
"0.5572572",
"0.55714494",
"0.5564409",
"0.5549788",
"0.55492735",
"0.55452186",
"0.55353034",
"0.5532018",
"0.5518504",
"0.5512564",
"0.55052054",
"0.5503882",
"0.54942673",
"0.54931736"
] | 0.7119225 | 0 |
def select_category_from_projects "SELECT category FROM projects;" end Make sure each ruby method returns a string containing a valid SQL statement. | def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name
'select p.title, sum(pl.amount) from projects p
LEFT JOIN pledges pl
where p.id = pl.project_id
group by p.title
order by p.title;'
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def select_category_from_projects\n\"SELECT category FROM projects;\"\nend",
"def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category\n\"SELECT projects.category, pledges.amount\nFROM pledges\nINNER JOIN projects\nON projects.id = pledges.project_id\nWHERE projects.category = 'music';\n\"\nend",
"def current_categories(db)\r\n\tretrieve_categories = '\r\n\tSELECT name FROM categories'\r\n\tcategories = db.execute(retrieve_categories)\r\nend",
"def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category\n\"SELECT projects.category, SUM(pledges.amount)\nFROM pledges\nINNER JOIN projects\nON pledges.project_id = projects.id \nWHERE projects.category = 'books';\"\nend",
"def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category\n\"SELECT Projects.category, SUM(Pledges.amount) FROM Projects JOIN Pledges ON Pledges.project_id = Projects.id WHERE Projects.category = 'books';\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"Write your SQL query Here\"\nend",
"def categories()\n db = connect()\n db.execute('SELECT * FROM categories')\n end",
"def category()\n sql = \"SELECT * FROM categories WHERE id = $1 ORDER BY name;\"\n values = [@category_id]\n sql_result = SqlRunner.run(sql, values)\n return Category.new(sql_result[0])\n end",
"def get_category_name(category_id)\n db = SQLite3::Database.new \"#{$script_dir}/cfps.db\"\n category = db.get_first_value(\"select name from category where id = ?\", [category_id])\n\n return categor\nend",
"def projects\n where(:_type => ProjectCategory.name)\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"Write your SQL query Here\"\n \"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title ORDER BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"Write your SQL query Here\"\n \"SELECT projects.title, SUM(amount) FROM projects\n INNER JOIN pledges ON project_id = projects.id\n GROUP BY title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(amount)\nFROM projects\nINNER JOIN pledges\nON projects.id = pledges.project_id\nGROUP BY title\nORDER BY title\"\n\n# FROM owners\n# INNER JOIN cats_owners\n# ON owners.id = cats_owners.owner_id\n# JOIN cats ON cats_owners.cat_id = cats.id\n# WHERE cats_owners.owner_id = 2;\n\nend",
"def current_categorized_expenses(db, user_name)\r\n\tretrieve_categorized_expenses = '\r\n\tSELECT categories.name, amount FROM expenses\r\n\tJOIN users ON expenses.user_id = users.id\r\n\tJOIN categories ON expenses.category_id = categories.id\r\n\tWHERE users.name = ?'\r\n\tcategorized_expenses = db.execute(retrieve_categorized_expenses, [user_name])\r\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"Write your SQL query Here\"\n\"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY(projects.title) ;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n sql = <<-SQL\n SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON pledges.project_id = projects.id GROUP BY projects.title;\n SQL\n\nend",
"def getCategories(_, _, _)\n @db.categories\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n <<-SQL\n SELECT projects.title , sum(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY pledges.project_id\n ORDER BY projects.title\n SQL\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"Write your SQL query Here\"\n \n\"SELECT projects.title, SUM(amount) \nFROM pledges \nINNER JOIN projects \nON pledges.project_id = projects.id GROUP BY projects.title;\"\nend",
"def category(id)\n db = connect()\n return db.execute('SELECT Id,Title FROM discussions WHERE CatId=?', id), db.execute('SELECT * FROM categories WHERE Id=?', id)\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"Write your SQL query Here\"\n \"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON pledges.project_id = projects.id GROUP BY projects.title ORDER BY title\"\nend",
"def list_projects # :nologin:\n query = create_query(:Project, :all, :by => :title)\n show_selected_projects(query)\n end",
"def get_category_id(category)\n db = SQLite3::Database.new \"#{$script_dir}/cfps.db\"\n category_id = db.get_first_value(\"select id from category where name = ?\", [category])\n\n return category_id\nend",
"def select(db); end",
"def select(db); end",
"def get_records_for_category categ\n if categ.nil? or categ == \"\"\n #return @records\n get_data \"select * from todo\"\n else\n #return @records.select { |row| row[0] == categ }\n get_data \"select * from todo where categ = '#{categ}' \"\n end\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n <<-SQL \n SELECT projects.title, SUM(pledges.amount)\n FROM projects \n INNER JOIN pledges on projects.id = pledges.project_id \n GROUP BY projects.title\n ORDER BY projects.title\n SQL\nend",
"def project_statement\n project_clauses = []\n active_subprojects_ids = []\n\n active_subprojects_ids = project.descendants.active.map(&:id) if project\n if active_subprojects_ids.any?\n if has_filter?(\"subproject_id\")\n case operator_for(\"subproject_id\")\n when '='\n # include the selected subprojects\n ################\n # Smile specific : [project.id] + removed\n ids = values_for(\"subproject_id\").map(&:to_i)\n project_clauses << \"#{Project.table_name}.id IN (%s)\" % ids.join(',')\n when '!'\n # exclude the selected subprojects\n\n ################\n # Smile specific : [project.id] + removed\n ids = active_subprojects_ids - values_for(\"subproject_id\").map(&:to_i)\n project_clauses << \"#{Project.table_name}.id IN (%s)\" % ids.join(',')\n when '!*'\n # main project only\n project_clauses << \"#{Project.table_name}.id = %d\" % project.id\n else\n # all subprojects\n project_clauses << \"#{Project.table_name}.lft >= #{project.lft} AND #{Project.table_name}.rgt <= #{project.rgt}\"\n end\n elsif Setting.display_subprojects_issues?\n project_clauses << \"#{Project.table_name}.lft >= #{project.lft} AND #{Project.table_name}.rgt <= #{project.rgt}\"\n else\n project_clauses << \"#{Project.table_name}.id = %d\" % project.id\n end\n elsif project\n project_clauses << \"#{Project.table_name}.id = %d\" % project.id\n end\n project_clauses.any? ? project_clauses.join(' AND ') : nil\n end",
"def select(sql, name = nil)\n raise NotImplementedError, \"select is an abstract method\"\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n<<-SQL\n SELECT projects.title, SUM(pledges.amount)\n FROM projects\n JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title;\nSQL\nend",
"def index\n\n # @sql = \"Projects.name ILIKE '#{'%'+params[:name]+'%'}' \" if params[:name].present?\n @sql = params[:name].present? ? \"Projects.name ILIKE '#{'%'+params[:name]+'%'}' \" : \"Projects.name ILIKE '%' \"\n @sql += \"OR Projects.description ILIKE '#{'%'+params[:name]+'%'}' \" if params[:name].present?\n\n @sql += \"and Projects.category ILIKE '#{'%'+params[:categorysdigital]+'%'}' \" if params[:categorysdigital].present?\n if params[:categorysdigital].present?\n @sql += \"or Projects.category ILIKE '#{'%'+params[:categorysmarketing]+'%'}' \" if params[:categorysmarketing].present?\n else\n @sql += \"And Projects.category ILIKE '#{'%'+params[:categorysmarketing]+'%'}' \" if params[:categorysmarketing].present?\n end\n\n if params[:categorysdigital].present? || params[:categorysmarketing].present?\n @sql += \"or Projects.category ILIKE '#{'%'+params[:categorysdesign]+'%'}' \" if params[:categorysdesign].present?\n else\n @sql += \"And Projects.category ILIKE '#{'%'+params[:categorysdesign]+'%'}' \" if params[:categorysdesign].present?\n end\n\n @sql += \"and Projects.progress = #{params[:progresspropose].to_i} \" if params[:progresspropose].present?\n if params[:progresspropose].present?\n @sql += \"or Projects.progress = #{params[:progressselected].to_i} \" if params[:progressselected].present?\n else\n @sql += \"and Projects.progress = #{params[:progressselected].to_i} \" if params[:progressselected].present?\n end\n\n if params[:progressselected].present?\n @sql += \"or Projects.progress = #{params[:progressclose].to_i} \" if params[:progressclose].present?\n else\n @sql += \"and Projects.progress = #{params[:progressclose].to_i} \" if params[:progressclose].present?\n end\n\n # @sql += \"ORDER progress\"\n @projects = Project.where(@sql).order(:progress)\n @count = @projects.count\n @count_tt = Project.count\n end",
"def projects_countries(site, category_id = nil)\n if category_id.present? && category_id.to_i > 0\n if site.navigate_by_cluster?\n category_join = \"inner join clusters_projects as cp on cp.project_id = p.id and cp.cluster_id = #{category_id}\"\n else\n category_join = \"inner join projects_sectors as pse on pse.project_id = p.id and pse.sector_id = #{category_id}\"\n end\n end\n\n Country.find_by_sql(\n<<-SQL\nselect c.id,c.name,count(ps.*) as count from countries as c\n inner join countries_projects as pr on c.id=pr.country_id\n inner join projects as p on p.id=pr.project_id\n inner join projects_sites as ps on p.id=ps.project_id and ps.site_id=#{site.id}\n #{category_join}\n where p.primary_organization_id=#{self.id}\n group by c.id, c.name order by count DESC\nSQL\n ).map do |r|\n [r, r.count.to_i]\n end\n end",
"def projects_countries(site, category_id = nil)\n if category_id.present?\n if site.navigate_by_cluster?\n category_join = \"inner join clusters_projects as cp on cp.project_id = p.id and cp.cluster_id = #{category_id}\"\n else\n category_join = \"inner join projects_sectors as pse on pse.project_id = p.id and pse.sector_id = #{category_id}\"\n end\n end\n\n Country.find_by_sql(\n<<-SQL\nselect c.id,c.name,count(ps.*) as count from countries as c\n inner join countries_projects as pr on c.id=pr.country_id\n inner join projects as p on p.id=pr.project_id and (p.end_date is null OR p.end_date > now())\n inner join projects_sites as ps on p.id=ps.project_id and ps.site_id=#{site.id}\n #{category_join}\n where p.primary_organization_id=#{self.id}\n group by c.id, c.name order by count DESC\nSQL\n ).map do |r|\n [r, r.count.to_i]\n end\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM pledges\nINNER JOIN projects \nON pledges.project_id = projects.id\nGROUP BY project_id\nORDER BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n# Select projects title column and the sum of the pledges amount column\n# from the projects database,\n# join the pledges (Join table)\n# with projects.id and the pledges project id. Match these numbers\n# Group the tables together by Projects title and then\n# sort by projects.title\n\"SELECT Projects.title, SUM(Pledges.amount)\n FROM Projects\n JOIN Pledges\n ON Projects.id = Pledges.project_id\n GROUP BY Projects.title\n ORDER BY Projects.title;\n\"\nend",
"def get_project_name(id)\n con = PG::Connection.connect(\"localhost\",5432,nil,nil,\"aaa\",\"admin\")\n sql = \"SELECT name \"\n sql += \"FROM projects \"\n sql += \"WHERE id='#{id}' \"\n res = con.exec(sql)\n con.close\n name = \"NA\"\n name = res[0]['name'] if res.num_tuples > 0\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n<<-SQL\n SELECT DISTINCT title ,SUM(amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id\n GROUP BY projects.title\n SQL\nend",
"def sql\n <<-SQL\n -- Search learning paths\n SELECT DISTINCT\n c.id,\n c.name,\n c.course_code,\n c.settings,\n cc.content,\n 'learning_path' AS content_type,\n c.id AS learning_path_id,\n 0 AS learning_objective_id\n FROM courses c\n LEFT OUTER JOIN fearless_taggings ts\n ON ts.taggable_id = c.id AND ts.taggable_type = 'LearningPath'\n LEFT OUTER JOIN fearless_tags t\n ON t.id = ts.tag_id\n LEFT OUTER JOIN fearless_custom_contents cc\n ON cc.contentable_id = c.id AND cc.contentable_type = 'LearningPath'\n WHERE 0=0\n #{construct_account_clause}\n #{construct_course_worklow_clause}\n #{construct_name_sql}\n #{construct_all_tags_search('t', 'name')}\n UNION ALL\n -- Search learning objectives\n SELECT DISTINCT\n cm.id,\n cm.name,\n c.course_code,\n c.settings,\n cc.content,\n 'learning_objective' AS content_type,\n cm.context_id::bigint AS learning_path_id,\n cm.id::bigint AS learning_objective_id\n FROM context_modules cm\n INNER JOIN courses c\n ON c.id = cm.context_id\n AND cm.context_type = 'Course'\n LEFT OUTER JOIN fearless_taggings ts\n ON ts.taggable_id = cm.id AND ts.taggable_type = 'LearningObjective'\n LEFT OUTER JOIN fearless_tags t\n ON t.id = ts.tag_id\n LEFT OUTER JOIN fearless_custom_contents cc\n ON cc.contentable_id = cm.id AND cc.contentable_type = 'LearningObjective'\n WHERE 0=0\n #{construct_account_clause}\n #{construct_generic_workflow_clause('cm')}\n #{construct_name_sql('cm')}\n #{construct_all_tags_search('t', 'name')}\n UNION ALL\n -- Search learning learning_event\n SELECT DISTINCT\n ct.id,\n ct.title AS name,\n c.course_code,\n c.settings,\n cc.content,\n 'learning_event' AS content_type,\n ct.context_id::bigint AS learning_path_id,\n ct.context_module_id::bigint AS learning_objective_id\n FROM content_tags ct\n INNER JOIN courses c\n ON c.id = ct.context_id\n AND ct.context_type = 'Course'\n LEFT OUTER JOIN fearless_taggings ts\n ON ts.taggable_id = ct.id AND ts.taggable_type = 'LearningEvent'\n LEFT OUTER JOIN fearless_tags t\n ON t.id = ts.tag_id\n LEFT OUTER JOIN fearless_custom_contents cc\n ON cc.contentable_id = ct.id AND cc.contentable_type = 'LearningEvent'\n WHERE 0=0\n #{construct_account_clause}\n #{construct_generic_workflow_clause('ct')}\n #{construct_name_sql('ct', 'title')}\n #{construct_all_tags_search('t', 'name')}\n SQL\n end",
"def get_category_name\n Category.find(:first, :select => ['name'],:conditions=>['has_complexity=?',false]).name rescue ''\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"\nSELECT \nProjects.title,\nSUM(Pledges.amount)\nFROM Pledges\nINNER JOIN Projects\nON Pledges.project_id = Projects.id\nGROUP BY Projects.title\nORDER BY Projects.title\n\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT Projects.title, SUM(pledges.amount) \nFROM projects \nJOIN pledges \nON Projects.id = pledges.project_id \nGROUP BY title\"; \nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM projects\nINNER JOIN pledges \nON projects.id=pledges.project_id\nGROUP BY projects.id\nORDER BY projects.title;\"\nend",
"def makeQueryTableAll(tableName)\n #sql = \"SELECT * FROM [\" << tableName << \"]\"\n sql = \"SELECT * FROM [\" << tableName << \"]\" << \" WHERE id < 3\"\n #puts(sql) #debug\n return sql\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, sum_pledges FROM (SELECT pledges.project_id, SUM(pledges.amount) AS sum_pledges FROM pledges GROUP BY pledges.project_id) INNER JOIN projects ON projects.id = project_id ORDER BY projects.title\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n<<-SQL\nSELECT projects.title, SUM(pledges.amount) \nFROM projects \nINNER JOIN pledges on projects.id = pledges.project_id\nGROUP BY (pledges.project_id)\nORDER BY projects.title;\nSQL\nend",
"def category_totals(db, user_name, number)\r\n\tretrieve_totals = '\r\n\tSELECT categories.name, SUM(amount) FROM expenses\r\n\tJOIN users ON expenses.user_id = users.id\r\n\tJOIN categories ON expenses.category_id = categories.id\r\n\tWHERE categories.id = ?\r\n\tAND users.name = ?'\r\n\ttotals = db.execute(retrieve_totals, [number, user_name])[0]\r\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\r\n\"SELECT title, SUM(pledges.amount) FROM projects\r\nJOIN pledges ON projects.id = pledges.project_id\r\nGROUP BY projects.id\r\nORDER BY title ASC\"\r\nend",
"def add_category(db, category)\r\n\tnew_category = '\r\n\tINSERT INTO categories (name)\r\n\tVALUES (?)'\r\n\tdb.execute(new_category, [category])\r\nend",
"def select_category\n #Parbauda vai ekrans ir redzams\n @screens.screen_create_filter.visible?\n #Pievieno kategoriju no filtra datiem\n @screens.screen_create_filter.select_row(@filter_data.category)\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"Select title, amount from projects, pledges where projects.id = pledges.id order by title ASC;\"\nend",
"def projects_countries(site, category_id = nil, organization_id = nil, location_id = nil)\n if category_id.present? && category_id.to_i > 0\n if site.navigate_by_cluster?\n category_join = \"inner join clusters_projects as cp on cp.project_id = p.id and cp.cluster_id = #{category_id}\"\n else\n category_join = \"inner join projects_sectors as pse on pse.project_id = p.id and pse.sector_id = #{category_id}\"\n end\n end\n\n if organization_id.present? && organization_id.to_i > 0\n organization_filter = \"and p.primary_organization_id = #{organization_id}\"\n end\n\n if location_id.present?\n location_filter = \"and c.id IN (#{location_id})\"\n end\n\n Country.find_by_sql(\n<<-SQL\nselect c.id,c.name,count(ps.*) as count from countries as c\n inner join countries_projects as pr on c.id=pr.country_id #{location_filter}\n inner join projects as p on p.id=pr.project_id and (p.end_date is null OR p.end_date > now()) #{organization_filter}\n inner join projects_sites as ps on p.id=ps.project_id and ps.site_id=#{site.id}\n inner join donations as dn on dn.project_id = p.id\n #{category_join}\n where dn.donor_id = #{self.id}\n group by c.id, c.name order by count DESC\nSQL\n ).map do |r|\n [r, r.count.to_i]\n end\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n\"SELECT projects.title, SUM(pledges.amount) FROM pledges INNER JOIN projects ON projects.id=pledges.project_id GROUP BY projects.title;\"\n## FROM - where are they talking to each other - where is the scotch tape\nend",
"def select(componentName, text, componentInfo=nil)\n $marathon.select(ComponentId.new(componentName, componentInfo), text.to_s)\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n \"SELECT projects.title,\n SUM(pledges.amount)\n FROM pledges\n INNER JOIN projects\n ON projects.id = pledges.project_id\n GROUP BY projects.title;\"\n\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, \nSUM(pledges.amount) \nFROM projects\nJOIN pledges ON pledges.project_id = projects.id\nGROUP BY projects.title\nORDER BY projects.title ASC;\"\nend",
"def select_all(sql, name = nil) end",
"def select\n @pds_projects = PdsProject.includes(:company).where('ProjectID in (?)', PROJECT_LIST)\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, sum(amount) AS pledge_amount\nFROM pledges\nJOIN projects\nWHERE pledges.project_id = projects.id\nGROUP BY project_id\nORDER BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n <<-SQL\n SELECT\n title, sum(amount)\n FROM\n projects\n JOIN pledges\n ON pledges.project_id = projects.id\n GROUP BY\n title\n ORDER BY\n title\n SQL\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount )\nFROM projects \nJOIN pledges\nON projects.id = pledges.project_id \nGROUP BY projects.title \nORDER BY projects.title \";\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title,(SELECT SUM(pledges.amount))\n FROM projects\n INNER JOIN pledges ON projects.id = pledges.project_id\n GROUP BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n \"SELECT projects.title, sum(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY pledges.project_id\n ORDER BY projects.title ASC;\n \"\nend",
"def db_fetch\n \"SELECT *\" + from_table_where + sql_match_conditions\n end",
"def get_category(cate, limitl, limitr)\n return Product.find_by_sql(\"select * from products where tag like '%#{cate}%' order by id limit #{limitl}, #{limitr}\")\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n\"SELECT projects.title, SUM(pledges.amount) FROM pledges INNER JOIN projects ON projects.id = pledges.project_id GROUP BY projects.title ORDER BY projects.title \"\nend",
"def select_project\n @projects = Project.find(:all)\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n\"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(amount)\nFROM projects\nINNER JOIN pledges\nON projects.id = pledges.project_id\nGROUP BY projects.title\nORDER BY projects.title;\"\nend",
"def sql_statement_find\n @sql_statement_find ||=\n <<-SQL\n SELECT\n applications.id AS id,\n teams.name AS team_name,\n projects.name AS project_name,\n (application_data -> :project_id)::int AS project_id,\n application_data -> :project_plan AS project_plan,\n application_data -> :why_selected_project AS why_selected_project,\n application_data -> :signed_off_at AS signed_off_at,\n (application_data -> :signed_off_by)::int AS signed_off_by,\n application_data -> :mentor_fav AS mentor_fav,\n CASE WHEN :project_id::text = 'project1_id' THEN 1 ELSE 2 END AS choice,\n hstore_to_json_loose(slice(application_data, ARRAY[:student0_attrs])) AS student0,\n hstore_to_json_loose(slice(application_data, ARRAY[:student1_attrs])) AS student1\n FROM applications\n INNER JOIN teams\n ON teams.id = applications.team_id\n INNER JOIN projects\n ON projects.id::text = applications.application_data -> :project_id\n WHERE (application_data -> :project_id)::int IN (:project_ids)\n AND applications.season_id = :season_id\n AND applications.id = :id;\n SQL\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n\"SELECT Projects.title, SUM(Pledges.amount)\n FROM projects\n JOIN pledges\n ON Projects.id = Pledges.project_id\n GROUP BY project_id\n ORDER BY Projects.title\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\n FROM pledges\n INNER JOIN projects\n ON pledges.project_id = projects.id\n GROUP BY projects.title\n ORDER BY projects.title\n\"\nend",
"def select(componentName, text, componentInfo=nil)\n $marathon.select(ComponentId.new(componentName, componentInfo), text.to_s)\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM projects\nJOIN pledges\nON projects.id = pledges.project_id\nGROUP BY projects.title;\"\nend",
"def sql\n @sql ||= begin\n bind_params = []\n 1.upto(selector_keys.length + setter_keys.length) { |i| bind_params << \"$#{i}\" }\n %{SELECT #{name}(#{bind_params.join(', ')})}\n end\n end",
"def getCat \n\t\tputs ''\n\t\tputs 'Fetching categories . . '\n\t\t@page.css('ul.dropdown li a').each do |cat|\n\t\t\tarr=[]\n\t\t\tarr.push cat.text\n\t\t\tarr.push cat['href']\n\t\t\t@arr_cat.push arr\n\t\t\tprint '. '\n\t\tend\n\t\ti=0\n\t\t@arr_cat.each do |pair|\n\t\t\t@db.execute 'insert into category values (?, ? ,?)', i, pair[0], pair[1]\n \t\t\ti +=1\n \t\tend\n\tend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM (pledges.amount)\nFROM projects\nINNER JOIN pledges\nON projects.id = pledges.project_id\nGROUP BY title\nORDER BY title ASC;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT Projects.title, SUM(Pledges.amount) FROM Projects JOIN Pledges ON Pledges.project_id = Projects.id GROUP BY Projects.title;\"\nend",
"def add_project_name_to_jql jql_string\n unless jql_string.empty?\n jql_string.insert(0, \"project=#{@project} AND \")\n else\n \"project=#{@project}\"\n end\n end",
"def search(category, query_term)\nresult = @conn.exec(\"SELECT * FROM students WHERE #{category} = '#{query_term}';\");\n puts student\n result.each do |student|\n puts \"#{k}: #{v}\"\n end\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(amount) FROM pledges INNER JOIN projects ON projects.id = pledges.project_id GROUP BY projects.id ORDER BY title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n\"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON pledges.project_id = projects.id\n GROUP BY(projects.title);\"\nend",
"def show_categories(html_dsl)\r\n categories = Category.where(\"user_id = #{session[:user_id]} and category_id is null\").order('name ASC')\r\n category_html = create_category_table(categories)\r\n html_dsl.inject(category_html)\r\n end",
"def show_categories(html_dsl)\r\n categories = Category.where(\"user_id = #{session[:user_id]} and category_id is null\").order('name ASC')\r\n category_html = create_category_table(categories)\r\n html_dsl.inject(category_html)\r\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, sum(pledges.amount) FROM projects INNER JOIN pledges on pledges.project_id=projects.id group by pledges.project_id ORDER BY projects.title ASC\"\nend",
"def selects_all_female_bears_return_name_and_age\n <<-SQL \n SELECT \n bears.name, \n bears.age \n FROM bears \n WHERE sex='F';\n SQL\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n \"SELECT projects.title, SUM(pledges.amount) FROM projects\n JOIN pledges ON projects.id = pledges.project_id\n GROUP BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON pledges.project_id=projects.id GROUP BY projects.title ORDER BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM projects\nINNER JOIN pledges\nON projects.id = pledges.project_id GROUP BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n # SELECT titles, amounts FROM projects, pledges ORDER BY titles ASC\n #SELECT titles.projects, pledges.amounts ORDER BY titles ASC\n \"SELECT projects.title, SUM(pledges.amount) FROM projects\n JOIN pledges \n ON pledges.project_id = projects.id \n GROUP BY(pledges.project_id)\n ORDER BY projects.title ASC\n \";\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n JOIN pledges ON pledges.project_id = projects.id\n GROUP BY title\n ORDER BY title ASC;\"\nend",
"def sql_statement_all\n @sql_statement_all ||=\n <<-SQL\n SELECT\n applications.id AS id,\n teams.name AS team_name,\n projects.name AS project_name,\n (application_data -> :project_id)::int AS project_id,\n application_data -> :signed_off_at AS signed_off_at,\n (application_data -> :signed_off_by)::int AS signed_off_by,\n application_data -> :mentor_fav AS mentor_fav,\n CASE WHEN :project_id::text = 'project1_id' THEN 1 ELSE 2 END AS choice\n FROM applications\n INNER JOIN teams\n ON teams.id = applications.team_id\n INNER JOIN projects\n ON projects.id::text = applications.application_data -> :project_id\n WHERE (application_data -> :project_id)::int IN (:project_ids)\n AND applications.season_id = :season_id;\n SQL\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title ORDER BY projects.title ASC;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"select\nprojects.title,\nsum(pledges.amount) as sum_all_pledges\nfrom projects\ninner join pledges\non projects.id = pledges.project_id\ngroup by projects.title\norder by projects.title;\n\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts\n \"SELECT projects.title, SUM(pledges.amount) \n FROM projects\n JOIN pledges\n ON pledges.project_id = projects.id\n GROUP BY projects.title;\"\nend",
"def category_selection(category)\n category = Public_apis.find_by_name(category)\n #goes over list item array . find method to find item\n\n \n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM projects\nLEFT JOIN pledges\nON projects.id=pledges.project_id\nGROUP BY projects.title\nORDER BY projects.title;\"\nend",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n #SELECT title, SUM(quantity) FROM groceries GROUP BY aisle ORDER BY SUM(quantity);\n\n \"SELECT projects.title, sum( pledges.amount)\nFROM projects\nJOIN pledges\nwhere projects.id=pledges.project_id\ngroup by projects.title order by projects.title\n;\"\n\nend",
"def frey_example\n # Find all the cats that are the same color as the cat named 'Freyja'.\n # Including 'Freyja' in the results.\n # DO NOT USE A SUBQUERY\n\n execute(<<-SQL)\n SELECT\n color_cats.name\n FROM\n cats AS freyja_cats\n JOIN\n cats AS color_cats ON freyja_cats.color = color_cats.color\n WHERE\n freyja_cats.name = 'Freyja';\n SQL\nend",
"def select &blck\n @projects.select(&blck)\n end",
"def select &blck\n @projects.select(&blck)\n end",
"def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT p.title, SUM(pl.amount) FROM pledges pl INNER JOIN projects p ON pl.project_id = p.id GROUP BY pl.project_id ORDER BY p.title\"\nend"
] | [
"0.9197428",
"0.70681554",
"0.69905895",
"0.6650687",
"0.6622008",
"0.65134215",
"0.6487074",
"0.63231736",
"0.60595876",
"0.59397984",
"0.5938012",
"0.59359765",
"0.59009475",
"0.58821595",
"0.58702105",
"0.58538514",
"0.5852772",
"0.58400726",
"0.58187836",
"0.5783952",
"0.5781836",
"0.5699433",
"0.56956494",
"0.56917065",
"0.56917065",
"0.5690233",
"0.5682429",
"0.5678716",
"0.56345487",
"0.562825",
"0.56200427",
"0.5618499",
"0.5614793",
"0.5589031",
"0.5582006",
"0.5574134",
"0.55731916",
"0.5572146",
"0.55663043",
"0.5543936",
"0.55408674",
"0.55273974",
"0.54872346",
"0.5480151",
"0.54790336",
"0.5477612",
"0.5475731",
"0.54650974",
"0.5460519",
"0.5458991",
"0.5450393",
"0.54474175",
"0.543396",
"0.5430399",
"0.54298806",
"0.5428744",
"0.5424535",
"0.54231083",
"0.54223335",
"0.5415754",
"0.5407502",
"0.5392763",
"0.5385772",
"0.53838485",
"0.53815895",
"0.53814566",
"0.5380899",
"0.53729725",
"0.5361706",
"0.5351655",
"0.5351099",
"0.53493774",
"0.53478605",
"0.5347711",
"0.53405917",
"0.534054",
"0.533232",
"0.5331863",
"0.53221244",
"0.53216356",
"0.531914",
"0.53109",
"0.53109",
"0.53063357",
"0.5299247",
"0.52962613",
"0.5290562",
"0.5286517",
"0.5284508",
"0.5284136",
"0.5283787",
"0.52830637",
"0.5276121",
"0.5273314",
"0.527148",
"0.5268409",
"0.52644026",
"0.5259888",
"0.5257563",
"0.5257563",
"0.52546746"
] | 0.0 | -1 |
given a decimal amount, returns an array with coins for that amount | def make_change(amount)
amount = amount * 100
change = []
@currency.each do |key, value|
num_coins, amount = coins_per_amount(value, amount)
change << [key] * num_coins
end
change.flatten
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def changer(amount)\n\n coins = []\n\n [25, 10, 5, 1].each do |denomination|\n coins = amount / denomination\n returned_coins += [denomination] * coins\n amount -= coins * denomination\n end\n returned_coins\nend",
"def coinConverter(num, coins)\n coinArray = []\n\n coins.each do |coin|\n while (num - coin >= 0)\n coinArray.push(coin)\n num -= coin\n end\n end\n\n coinArray.each do |coin|\n puts coin\n end\nend",
"def change(amount, coins)\n dp = Array.new(amount + 1,0)\n dp[0] = 1\n (1..coins.size).each do |i|\n (1..amount).each do |j|\n if coins[i - 1] <= j\n dp[j] = dp[j] + dp[j - coins[i-1]]\n end\n end\n end\n dp[amount]\nend",
"def greedy_make_change(cents,coins = [25,10,5,1])\n return [cents] if coins.include?(cents)\n arr = Array.new\n coins.each do |coin|\n if coin < cents\n arr << coin\n break\n end\n end\n greedy_make_change(cents-arr.first,coins).each {|coin| arr << coin}\n return arr\nend",
"def make_change( amount )\n #REMOVED IN REFACTOR: coins = changer( pull_cents( f ), COINS )\n #REMOVED IN REFACTOR: bills = changer( pull_bills( f ), BILLS )\n coins = changer( pull_currency( amount ){ | s, idx | currency = s[ idx + 1..-1 ] }, COINS )\n bills = changer( pull_currency( amount ){ | s, idx | currency = s[ 0...idx ] }, BILLS )\n [ bills, coins ]\n end",
"def calc_change(amount)\n remaining_amount = (amount * 100).round(2).to_i\n change = COIN_MAPPER.dup\n VALUES_IN_CENTS.each do |value|\n number_coins = remaining_amount / value\n next if number_coins == 0\n string_coin = (value / 100.to_f).to_s\n raise_no_change_available! if @money[string_coin] - number_coins < 0\n change[string_coin] += number_coins\n remaining_amount -= number_coins * value\n end\n change\n end",
"def possible_coins\n @possible_coins ||= @denominations.select {|d| d <= @total }\n end",
"def make_change_iterative(amount, coins = [25, 10, 5, 1])\n change = []\n coins.each do |coin|\n count = amount / coin # how many of that coin I can use\n count.times { change << coin }\n amount -= count * coin\n end\n \n change\nend",
"def coin_change2(coins, amount)\n coins_needed = Hash.new do |hash, key|\n coins_needed_after_one = coins.select {|coin_value| coin_value <= key}.map {|coin_value| hash[key-coin_value]}\n .reject {|coins_needed| coins_needed == -1}.min\n hash[key] = if coins_needed_after_one == nil then -1 else 1 + coins_needed_after_one end\n end.update(0 => 0)\n \n #This is just to prevent stack overflow. If you tried to directly calculate amount you might have too many calls down.\n (1..amount).each {|current| coins_needed[current]}\n \n coins_needed[amount]\nend",
"def make_change_it(amount, coins = [25, 10, 5, 1])\n #iterative version to make sure can get it \n change = []\n i = 0\n while amount > 0\n #as long as money is greater than zero there's a coin that we can give back\n while amount >= coins[i]\n #compare money that you have to the biggest coin\n amount -= coins[i]\n change << coins[i]\n p change\n end\n i += 1\n end\nend",
"def coin_change(coins, amount)\n coins = coins.sort\n\n return -1 if coins.empty?\n return -1 if coins[0] > amount\n\n current_coin = coins.pop\n change = []\n sum = 0\n\n loop_coins(coins, amount ,current_coin, change, sum)\nend",
"def greedy_make_change(amount, coins = [25, 10, 5, 1])\n return [] if amount == 0\n change = []\n sorted_coins = coins.sort\n largest_coin = sorted_coins.pop\n\n large_coins = amount / largest_coin\n large_coins.times {change << largest_coin}\n\n new_amount = amount - change.sum\n \n change += greedy_make_change(new_amount, sorted_coins)\n\n change\nend",
"def make_change(amount, coins = [25, 10 ,5, 1])\n biggest_fit_coin = coins.detect { |val| amount >= val }\n\n if biggest_fit_coin == amount\n [biggest_fit_coin]\n else\n [biggest_fit_coin] + make_change(amount - biggest_fit_coin)\n end\nend",
"def make_change(amount)\n\tcoin_values = [25, 10, 5, 1]\n\tcoins = []\n\n\tcoin_values.each do |value|\n\t\twhile amount >= value\n\t\t\tcoins.push(value)\n\t\t\tamount -= value\n\t\tend\n\tend\n\n\t# while (amount - 25) >= 0\n\t# \tcoins.push(25)\n\t# \tamount -= 25\n\t# end\n\n\t# while (amount - 10) >= 0\n\t# \tcoins.push(10)\n\t# \tamount -= 10\n\t# end\n\n\n\t# while (amount - 5) >= 0\n\t# \tcoins.push(5)\n\t# \tamount -= 5\n\t# end\n\n\t# while (amount - 1) >= 0\n\t# \tcoins.push(1)\n\t# \tamount -= 1\n\t# end\n\tcoins\nend",
"def current_coin_total\n @coins.map(&:value).reduce { |sum, num| sum += num }\n end",
"def greedy_make_change(amount, coins = [25, 10, 5, 1])\n #debugger\n return [amount] if amount == 1\n return [] if coins.min > amount\n\n collected_coins = []\n\n coins.each do |coin|\n divided_amount = amount / coin\n\n if divided_amount > 0\n new_amount = amount - (coin * divided_amount)\n if new_amount == 0\n return collected_coins\n end\n\n divided_amount.times do\n collected_coins << coin\n end\n\n collected_coins += greedy_make_change(new_amount, coins)\n #elsif divided_amount ==\n\n end\n end\n\n collected_coins\nend",
"def change_in_coins(change)\n return [] if change.zero?\n supported_nominals.reverse_each do |coin|\n next if (change - coin).negative? || !coin_available?(coin)\n remove_change_coin(coin)\n next unless (sum = change_in_coins(change - coin))\n return sum + [coin]\n end\n nil\n end",
"def change(amount, coins)\n return 0 if coins.empty?\n\n # TO make zero, there is one way. Dont give anything.\n ways = Array.new(amount + 1, 0)\n ways[0] = 1\n coins.each do |coin|\n (coin..amount).each do |amt|\n ways[amt] += ways[amt - coin]\n end\n end\n ways[-1]\nend",
"def coin_array; end",
"def combinations_of_money_count(amount, denominations = [0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 1, 2, 5, 10, 20, 50, 100], memo = [])\n amount = (amount * 100).to_i\n denominations = denominations.sort.map { |n| (n * 100).to_i }\n\n combinations_counts = Array.new(amount * 100 + 1, 0)\n combinations_counts[0] = 1\n\n denominations.each do |denomination|\n denomination.upto(amount) do |i|\n combinations_counts[i] += combinations_counts[i - denomination]\n end\n end\n\n combinations_counts[amount]\nend",
"def wonky_coins(coin)\n return 1 if coin == 0\n return wonky_coins(coin / 2) + wonky_coins(coin / 3) + wonky_coins(coin / 4)\nend",
"def make_change( amount, coins=[25,10,5,1], avoid_pennies=true, recursing=false )\n # Don't sort in place, in case the user wants to preserve the coin array\n coins = coins.sort_by{ |coin| -coin }\n owed = amount\n change = []\n coins.each{ |coin|\n while owed >= coin\n owed -= coin\n change << coin\n end\n }\n change = nil unless owed == 0\n\n if recursing\n change\n else\n answers = [ change ]\n while coins.shift\n answers << make_change( amount, coins, avoid_pennies, true )\n end\n answers.compact.sort_by{ |answer|\n [\n answer.length,\n -answer.send( avoid_pennies ? :last : :first )\n ]\n }.first\n end\nend",
"def make_greedy_change(amount, bank = [25,10,5,1])\n return [] if amount == 0\n\n bank.each_with_index do |coin, idx|\n next if coin > amount\n\n remainder = amount - coin\n return [coin] + make_greedy_change(remainder, bank)\n end\nend",
"def return_coins(remaining_coins,target_amount)\n # 1. loop through coins, if any one of it is == target_amount, return it.\n # 2. if coins < target_amount, minus the coin from target_amount and save it in a variable.\n return [] if remaining_coins.sum < target_amount\n return [1] if target_amount == 1\n return [] if remaining_coins == []\nfor i in remaining_coins\n return i if i == target_amount\n\n if i == target_amount/3 && !(i < target_amount) \n testcase10 = remaining_coins.select{|x|x==(target_amount/3)}\n return testcase10\n elsif i < target_amount \n save = i\n temporary = target_amount - save\n end\nend \n# remaining_coins.delete_at(remaining_coins.index(remaining_coins[-1]))\nremaining_coins.delete_at(remaining_coins.find_index(save))\nfinal = [save] + [return_coins(remaining_coins,temporary)]\nreturn final.flatten.sort\nend",
"def find_solutions_dp\n solutions = Array.new(@amount+1).map {|i| 0 }\n solutions[0] = 1\n\n @coins.each do |coin|\n for i in coin..@amount\n solutions[i] = solutions[i] + solutions[i-coin]\n end\n end\n\n solutions[@amount]\n end",
"def coin_change(coins, total)\n\n coins = coins.unshift(0)\n\n # set up table\n table = Array.new(coins.length) { Array.new(total + 1, 0) }\n table.each { |row| row[0] = 1 }\n\n result = 0\n\n x = 1\n while x < coins.length\n break if coins[x] > total\n\n y = 1\n while y <= total\n\n val1 = table[x][y - coins[x]]\n val2 = table[x - 1][y]\n table[x][y] = val1 + val2\n result = table[x][y]\n\n y += 1\n end\n x += 1\n end\n\n table.each { |row| p row }\n return result\nend",
"def coins(n, demoninations = [1, 5, 10, 25])\n change_table = []\n\n \n\nend",
"def greedy_make_change(value, coins)\n return [] if value == 0 || coins.empty?\n num_coin = value / coins.first\n remaining_value = value % coins.first\n [coins.first] * num_coin + greedy_make_change(remaining_value, coins.drop(1))\nend",
"def make_change(num)\n\t\n\tarray = []\n\n\tamount = num\n\tquaters = amount/25\n\t# puts quaters \n\tamount_left= num - (quaters * 25 )\n\tdime = amount_left/10\n\t# puts dime\n\tamount_left2 = num - (quaters*25+dime*10)\n\tnickel = amount_left2/5\n\t# puts nickel\n\tamount_left3 = num - (quaters*25+dime*10+nickel*5)\n\tpenny = amount_left3/1\n\t# puts penny\n\tarray.push((quaters*25),(dime*10),(nickel*5),penny)\n\tarray\n\n\t# coins = []\n\n\t# while (amount-25) >= 0\n\t# \tcoins.push(25)\n\t# \tamount -=25\n\t# end\n\n\n\n\nend",
"def given(array = [])\n i = cur_val = 0\n until array[i].nil?\n cur_val += array[i] * VALS[i]\n i += 1 \n end\n return [array] if cur_val == GOAL_VAL\n combos = []\n if VALS[i] > 1\n (0..((GOAL_VAL - cur_val) / VALS[i])).each do |num_coins|\n combos += given( array + [num_coins] )\n end\n return combos\n else\n return [array + [GOAL_VAL - cur_val] ]\n end\nend",
"def make_change(amt, coins, coin_cache = { 0 => 0 })\n return coin_cache[amt] if coin_cache[amt]\n return 0.0 / 0.0 if amt < coins[0]\n\n ans = 0.0 / 0.0\n coins.each do |coin|\n break if coin > amt\n num_coins = 1 + make_change(amt - coin, coins, coin_cache)\n ans = num_coins unless ans.is_a?(Integer) && num_coins > ans\n end\n\n coin_cache[amt] = ans.is_a?(Integer) ? ans : 0.0 / 0.0\n end",
"def list_of_amount\n lines = array_of_lines(transaction_path)\n lines.each_with_object(Hash.new(0.00)) do |line, result|\n name = line.split(' ').first\n paid = line[/(\\d+[.,]\\d+)|(\\d+)/].to_f.round(2)\n result[name] = result.key?(name) ? (result[name] + paid).round(2) : paid\n end\n end",
"def coin_denominaitons(money, denom)\n\tcount = 0\n\tresult = []\n\t#M = money\n\t#D = denom.reverse\n\tdef denominate (mm, dd)\n\t\tsubresult = []\n\t\t#while m > 0\n\t\t\tdd.each do |d|\n\t\t\t\twhile mm >= d\n\t\t\t\t\tsubresult << \"#{d}c\"\n\t\t\t\t\tmm - d\n\t\t\t\tend\n\t\t\tend\n\t\t#end\n\t\tputs subresult\n\t\tresult << subresult\n\t\tcount += 1\n\t\tdd.shift\n\t\tdenominate(mm, dd)\n\tend\t\n\tdenominate(money,denom)\n\tputs \"Number of ways to make #{M}: #{count}\"\n\tputs result\nend",
"def greedy_make_change(total, coin_values)\n return [] if total == 0\n\n coin = coin_values.find { |cn| cn <= total }\n\n [coin] + greedy_make_change(total - coin, coin_values)\nend",
"def coin_sum_ways(coins, amount)\n solution = Array.new(coins.size + 1) { Array.new(amount + 1, 0) }\n\n # if amount = 0, we have 1 way (empty set) to make this\n (coins.size + 1).times do |row|\n solution[row][0] = 1\n end\n\n (1..coins.size).each do |row|\n (1..amount).each do |col|\n coin = coins[row - 1]\n # if coin value is <= sum\n if coin <= col\n solution[row][col] = solution[row - 1][col] + solution[row][col - coin]\n else\n # copy val from row above\n solution[row][col] = solution[row - 1][col]\n end\n end\n end\n\n solution[coins.size][amount]\nend",
"def make_better_change(amount, coin_denoms)\n return [amount] if coin_denoms.include?(amount)\n return [] if amount <= 0\n\n coin_denoms.sort.reverse!\n all_possible_arr = []\n\n coin_denoms.each do |value|\n change_arr = []\n change_arr << value\n change_arr.concat(make_better_change(amount - value, coin_denoms))\n all_possible_arr << change_arr if change_arr.inject(:+) == amount\n end\n\n all_possible_arr.min_by { |arr| arr.length }\n\nend",
"def list_coins\n endpoint = \"#{HOST}/v1/cryptocurrency/map\"\n get(endpoint)\n end",
"def round_to_coin(coin)\n coef = 1.0/coin\n val = (cents * coef).floor / coef\n Money.new(val, currency)\n end",
"def change1(total, denominations)\n breakdowns = []\n\n denominations.each_with_index do |coin, index|\n next if total/coin == 0\n\n subtotal = total\n set = []\n count = subtotal / coin\n\n if count > 0\n count.times { set << coin }\n subtotal -= (coin * count)\n end\n\n if subtotal > 0\n set += change1(subtotal, denominations[index+1..-1])\n end\n breakdowns << set.flatten\n end\n breakdowns\nend",
"def balance\n res = dollars\n\n fund_transactions.each do |tran|\n res += tran.dollars\n end\n\n return res\n end",
"def greedy_make_change(total, coins)\n return [] if total == 0\n change = []\n # sort coins largest to smallest\n coins.sort!{|a,b| b <=> a}\n # remove first coin from array\n coin = coins.shift\n # calculate how many fit into total \n coin_count = total / coin\n # add coin to change as many times as calculated above\n coin_count.times { change << coin}\n # current coin change and recursive call to remaining total using remaining coins\n change + greedy_make_change(total-(coin * coin_count), coins)\nend",
"def balance\n sum = 0\n @money.each do |k, v|\n sum += k * v\n end\n sum\n end",
"def split(num)\n raise ArgumentError, \"need at least one party\" if num < 1\n low = Money.new(cents / num)\n high = Money.new(low.cents + 1)\n\n remainder = cents % num\n result = []\n\n num.times do |index|\n result[index] = index < remainder ? high : low\n end\n\n return result\n end",
"def split(num)\n raise ArgumentError, \"need at least one party\" if num < 1\n low = Money.new(cents / num)\n high = Money.new(low.cents + 1)\n\n remainder = cents % num\n result = []\n\n num.times do |index|\n result[index] = index < remainder ? high : low\n end\n\n return result\n end",
"def change2(amount, denominations)\n denomination_breakdown = Array.new(amount + 1, 0)\n denomination_breakdown[0] = 1\n\n denominations.each do |denomination|\n (denomination..amount).each do |higher_amount|\n remainder = higher_amount - denomination\n denomination_breakdown[higher_amount] += denomination_breakdown[remainder]\n end\n end\n\n denomination_breakdown[amount]\nend",
"def recursive_greedy_make_change(amount, coins = [25, 10, 5, 1])\n return [] if amount == 0\n\n if amount >= coins.first\n new_amount = amount - coins.first\n return [coins.first] + recursive_greedy_make_change(new_amount, coins)\n else\n return recursive_greedy_make_change(amount, coins[1..-1])\n end\nend",
"def greedy_change(amount, coins)\n return {} if amount <= 0\n coins_count = {}\n coins_count[coins.max] = amount / coins.max\n remainder = amount % coins.max\n coins.delete(coins.max)\n coins_count.merge(greedy_change(remainder, coins))\nend",
"def creditCoins(amount)\r\n @betESSCoins += amount\r\n end",
"def prepare_amount amount\n BigDecimal.new(amount)/100\n end",
"def balance_to_decimal(balance)\n balance.chars.reverse.map.with_index do |i, index|\n (i == 'T' ? -1 : i.to_i) * (3**index)\n end.sum\nend",
"def minimum_coins(value, amount)\n coin_count = 0\n while value.count > 0\n amount = amount - value.last\n if value.last > amount \n value.pop\n end\n coin_count += 1\n end\n puts \"Coin count is: #{coin_count}\"\nend",
"def coin_combos(total)\n coins = [1, 5, 10, 25, 50, 100]\n counter ||= 0\n if total == 0\n counter += 1\n p \"#{counter} is counter\"\n return\n elsif total > 0\n coins.reverse.each do |integer|\n if integer < total\n coin_combos(total - integer)\n end\n end\n end\nend",
"def wonky_coins(n)\n return 1 if n == 0\n\n coins = []\n coins << n/2 << n/2 << n/4 if n != 0\n\n coin_total = 0\n\n coins.each do |coin|\n \tcoin_total += wonky_coins(coin) if coin > 0\n \tcoin_total += 1 if coin == 0\n end\n\n return coin_total\nend",
"def cents(amount)\n (amount * 100).to_i\n end",
"def least_coins(cents)\n#Code your answer here!\ncoins = {\n :quarters => 0,\n :dimes => 0,\n :nickels => 0,\n :pennies => 0\n}\n\nquarters = cents/25\nif quarters == 0\n coins[:quarters] = 0\nelsif quarters != 0\n coins[:quarters] = quarters\n cents = cents - quarters * 25\nend\n\ndimes = cents/10\nif dimes == 0\n coins[:dimes] = 0\nelsif dimes != 0\n coins[:dimes] = dimes\n cents = cents - dimes * 10\nend\n\nnickels = cents/5\nif nickels == 0\n coins[:nickels] = 0\nelsif nickels != 0\n coins[:nickels] = nickels\n cents = cents - coins * 5\nend\n\npennies = cents\nif pennies == 0\n coins[:pennies] = 0\nelsif pennies != 0\n coins[:pennies] = pennies\nend\n\nputs coins\n\ncoins\n\n\nend",
"def make_change(amount, coins = [10, 7, 1])\n return [] if amount == 0\n return nil if coins.none? { |coin| coin <= amount }\n\n coins = coins.sort.reverse\n best_change = nil\n coins.each_with_index do |coin, index|\n next if coin > amount\n remainder = amount - coin\n \n best_remainder = make_change(remainder, coins.drop(index))\n \n next if best_remainder.nil?\n \n this_change = [coin] + best_remainder\n \n if best_change.nil? || (this_change.count < best_change.count)\n best_change = this_change\n end \n end\n \n best_change\nend",
"def get_deposited_coin(transaction)\n deposited_coin = @user.coins.find(transaction.coin_id) if @user\n return deposited_coin\n end",
"def money(amount)\n Money.new((amount * 100).to_i)\n end",
"def greedy_change(num, coins)\n return [] if num <= 0\n\n result = []\n new_coin = coins.select { |coin| num - coin >= 0 }.max\n #p new_coin\n result << new_coin\n #p result\n #p greedy_change(num - new_coin, coins)\n result + greedy_change(num - new_coin, coins)\nend",
"def change(amount, coin_arr, index)\n\tif amount == 0\n\t\treturn 1\n\tend\n\tif index >= coin_arr.length\n\t\treturn 0\n\tend\n\n\tamount_with_coin = 0\n\tways = 0\n\n\twhile amount_with_coin <= amount\n\t\tremainder = amount - amount_with_coin\n\t\tways += change(remainder, coin_arr, index+1)\n\t\tamount_with_coin += coin_arr[index]\n\tend\n\tways\nend",
"def greedy_make_change(target, coins=[25,10,5,1])\nend",
"def make_better_change(value, coins)\n check_coins = coins.select { |el| el <= value }\n return nil if check_coins.empty?\n\n solutions = []\n check_coins.sort.reverse.each do |coin|\n remain = value - coin\n\n if remain > 0\n remain = make_better_change(remain, coins)\n solutions << [coin] + remain unless remain.nil?\n else\n solutions << [coin]\n end\n end\n solutions.sort_by! { |arr| arr.length }.first\n\n end",
"def change(amount, arr)\n changes = [[]] + Array.new(amount, Array.new(amount))\n\n 1.upto(amount) do |i|\n arr.each do |coin|\n next if coin > i\n\n changes[i] = changes[i - coin] + [coin] if changes[i].size > (changes[i - coin] + [coin]).size\n end\n end\n\n changes[amount]\nend",
"def net_amount\n ((transaction_value - 0.2) / 1.034).floor_with_two_decimal_places\n end",
"def make_change(value,coins)\n return nil if value < coins.min\n best = nil\n coins.each do |coin|\n if value < coin\n next\n elsif value == coin\n return [coin]\n else\n # Try finding a combination of coins that will sum to value - coin.\n # Then you can get a combination of coins for value by adding the\n # current coin.\n candidate = [coin] + make_change(value - coin, coins)\n \n if candidate != nil && (best.nil? || candidate.size < best.size)\n best = [coin] + make_change(value - coin, coins)\n end\n end\n end\n best\nend",
"def balance_delta\n prepared.map(&:amount_with_sign).reduce(:+)\n end",
"def make_change(amt, coins, coin_cache = {0 => 0})\n return coin_cache[amt] if coin_cache[amt]\n return 0.0/0.0 if amt < coins[0]\n\n min_change = amt\n way_found = false\n idx = 0\n while idx < coins.length && coins[idx] <= amt\n num_change = 1 + make_change(amt - coins[idx], coins, coin_cache)\n if num_change.is_a?(Integer)\n way_found = true\n min_change = num_change if num_change < min_change\n end\n idx += 1\n end\n\n if way_found\n coin_cache[amt] = min_change\n else\n coin_cache[amt] = 0.0/0.0\n end\n end",
"def make_change(amount, denominations = DENOMINATIONS)\n change = {} \n denominations.each{|coin, value|\n num, amount = amount.divmod(value)\n change[coin] = num if num > 0\n }\n # print \" \"\n change\nend",
"def valid_coin(coin_input)\n coins = [1,5,10,25]\n if coins.include?(coin_input)\n puts \"Total inserted: #{coin_input}\"\n else\n \"Not a valid coin.\"\n end\n end",
"def make_change(change, coins)\n return [] if change == 0\n return nil if coins.count == 0 && change != 0\n\n current_coin = coins.first\n if change / current_coin >= 1\n results = [current_coin] + make_change(change - current_coin, coins)\n next_results = make_change(change - current_coin, coins.shift)\n greedy_results = [current_coin] + next_results unless next_results == nil\n results = greedy_results if greedy_results.length < results.length \n else\n coins.shift\n results = make_change(change, coins)\n end\nend",
"def eth_portfolio\n return @@client.accounts[1].balance.amount.to_f\n end",
"def balance\n transactions.inject(0) do |sum, transaction|\n sum + transaction.amount\n end\n end",
"def make_change(amt, coins, coin_cache = {0 => 0})\n return coin_cache[amt] if coin_cache[amt]\n return 0.0/0.0 if amt < coins[0]\n\n min = amt\n change_possible = false\n coins.each do |coin|\n next if coin > amt\n\n test_change = make_change(amt - coin, coins, coin_cache) + 1\n if test_change.integer? && test_change < min\n change_possible = true\n min = test_change\n end\n end\n\n min = 0.0/0.0 unless change_possible\n coin_cache[amt] = min\n\n min\n end",
"def get_coins\n get(\"/getcoins\")\n end",
"def inspect_input_coins(coins, valid_denominations)\n return_hash = {\n valid: {\n coins: {},\n total_value: 0\n },\n invalid: {}\n }\n coins.each do |coin|\n unless valid_denominations.include? coin\n if return_hash[:invalid].key? coin\n return_hash[:invalid][coin] += 1\n else\n return_hash[:invalid][coin] = 1\n end\n next\n end\n if return_hash[:valid][:coins].key? coin\n return_hash[:valid][:coins][coin] += 1\n else\n return_hash[:valid][:coins][coin] = 1\n end\n end\n return_hash[:valid][:coins].each do |k, v|\n return_hash[:valid][:total_value] += k.to_i * v.to_i\n end\n return_hash\n end",
"def min_coins(total)\n result = 0\n result = (total/5).to_i\n total = total % 5\n result += (total/3).to_i\n total = total % 3\n result += total\n\n puts result\nend",
"def make_change_for_amount(amount, check = false)\n remaining_returns = amount\n\n change = []\n\n @coins.each do |coin, count|\n num_coins = count\n\n while num_coins > 0 && ((remaining_returns - @@coin_value_by_details[coin]) >= 0)\n # remove amount we need less\n remaining_returns -= @@coin_value_by_details[coin]\n change << @@coin_value_by_details[coin]\n\n num_coins -= 1\n end\n\n @coins[coin] = num_coins unless check\n\n break if remaining_returns == 0\n end\n\n change\n end",
"def make_better_change(amount, coins = [25, 10, 5, 1])\n\treturn [] if amount < 1\n\tsmallest_change = nil\n\n\tcoins.sort.reverse.each.with_index do |coin, i|\n\t\tunless coin > amount\n\t\t\tchange = [coin] + make_better_change(amount - coin, coins.drop(i))\n\t\t\tif smallest_change == nil || change.count < smallest_change.count\n\t\t\t\tsmallest_change = change\n\t\t\tend\n\t\tend\n\tend\n\n\tsmallest_change\nend",
"def min_change_sum(coins, total)\n totals = Array.new(total + 1, 1000000000000)\n totals[0] = 0\n\n (1..total).each do |i|\n coins.each do |coin|\n if coin <= i && (totals[i-coin] + 1 < totals[i])\n totals[i] = totals[i-coin] + 1\n end\n end\n end\n\n totals[total]\nend",
"def money(amount)\n number_to_currency amount.to_s, {:unit => 'R ', :delimiter => ',', :seperator => '.'}\n end",
"def cents\n (amount * 100).to_i\n end",
"def wonky_coins(n)\n\nend",
"def balance\n transactions.inject(:+)\n end",
"def calculate_change(amount, coin_array = nil)\n # ignore coins higher than the target amount\n @status = :no_change\n avail_coins = get_available_coins(coin_array, amount)\n return status unless avail_coins.any?\n required_quantity = amount / avail_coins[0].value\n return status unless coins_are_available(avail_coins, required_quantity)\n residual = amount % avail_coins[0].value\n return @status = :success if residual.zero?\n calculate_change(residual, avail_coins[1..-1])\n end",
"def make_better_change(amount, coins)\n stack = [amount]\n until stack.empty?\n coins.each do |coin|\n break if amount - coin == 0\n stack << amount - coin if amount >= coin\n make_better_change(amount-coin, coins)\n end\n end\nend",
"def make_better_change(value, coins)\n return nil if coins.empty?\n return [] if value == 0\n\n change = []\n coins = coins.sort.reverse.select{|coin| coin <= value}\n coins.each do |coin|\n remainder = value - coin\n if remainder > 0\n best_remainder = make_better_change(remainder, coins)\n change << [coin] + best_remainder unless best_remainder.nil?\n else\n change << [coin]\n end\n end\n change.sort_by!{|arr| arr.size}.first\nend",
"def make_better_change(value, coins)\n return nil if coins.empty?\n return [] if value == 0\n\n change = []\n coins = coins.sort.reverse.select{|coin| coin <= value}\n coins.each do |coin|\n remainder = value - coin\n if remainder > 0\n best_remainder = make_better_change(remainder, coins)\n change << [coin] + best_remainder unless best_remainder.nil?\n else\n change << [coin]\n end\n end\n change.sort_by!{|arr| arr.size}.first\nend",
"def coin_combos(target_value, coin_values)\n coin_values.sort!\n _coin_combos(target_value, coin_values)\nend",
"def coin_to_satoshi(coin)\n BigDecimal(coin) * BigDecimal(100000000)\n end",
"def make_change(amt, coins)\n return Float::INFINITY if amt < 0\n return @change_hash[amt] if @change_hash[amt]\n min_so_far = Float::INFINITY\n coins.each do |coin|\n num_coins = make_change(amt - coin, coins) + 1\n min_so_far = num_coins if num_coins < min_so_far\n end\n @change_hash[amt] = min_so_far\n min_so_far\n end",
"def make_change(amt, coins)\n return Float::INFINITY if amt < 0\n @cache[0] = 0\n\n return @cache[amt] if @cache[amt]\n minimum = Float::INFINITY\n\n coins.each do |coin|\n attempt = make_change(amt - coin, coins) + 1\n minimum = attempt unless minimum.is_a?(Integer)\n minimum = attempt if attempt < minimum\n end\n\n @cache[amt] = minimum\n end",
"def possibilities (target, coins)\n return 1 if target == 0\n return 0 if target < 0 || coins . length == 0\n\n sum = 0\n for i in 0 .. (target / coins [0]) . to_i do\n sum += possibilities(target - i * coins [0], coins [1 .. -1])\n end\n\n return sum\nend",
"def change(amount, arr)\n arr.reverse.each_with_object([]) do |coin, change|\n until coin > amount\n amount -= coin\n change << coin\n end\n end\nend",
"def spend\n amounts = []\n orders.where(order_status_id: 4).each do |order|\n amounts << order.subtotal\n end\n return amounts.inject(:+)\n end",
"def amount_in_cents(amount)\n (100 * amount).to_i\n end",
"def account_cash_balance(investor)\n cash_balance = 0\n @hash_row_array.each do |hash|\n price = hash[\"TXN_PRICE\"]\n price[0] = ''\n price_float = price.to_f\n cash_total = price_float * hash[\"TXN_SHARES\"].to_f\n if hash[\"INVESTOR\"] == investor && hash[\"TXN_TYPE\"] == \"BUY\"\n cash_balance += cash_total\n end\n end\n return cash_balance.round(2)\nend",
"def get_user_coin_transactions\n user_coin_transactions = Transaction.where(user_id: @user.id, coin_id: @user_coin.id) if @user\n return user_coin_transactions;\n end",
"def total_coins_value\n json_response({:total_coins_value => @total_coins_val, :status => true, :message => 'calculated'})\n end",
"def available_coins\n coins.select { |coin, quantity| quantity > 0 }.keys\n .map { |coin| Components::Coin.new(coin) }\n .reverse\n end",
"def largestcoin(amount, coins)\n\ti = 0\n\tbest_coin = coins[i]\n\tfor coin in coins\n\t\tif (coin <= amount) && (coin > best_coin)\n\t\t\tbest_coin = coin\n\t\telse\n\t\tcoins[i+=1]\t\n\t\tend\n\tend\n\tbest_coin\nend"
] | [
"0.73457354",
"0.6974007",
"0.6707121",
"0.659889",
"0.65441865",
"0.6542102",
"0.6515395",
"0.6466573",
"0.64550436",
"0.64414227",
"0.6422158",
"0.64182836",
"0.6365127",
"0.63566446",
"0.6352055",
"0.6340109",
"0.63165",
"0.6303894",
"0.6264675",
"0.62573713",
"0.62111396",
"0.620652",
"0.61902815",
"0.6186297",
"0.61800975",
"0.6169406",
"0.6166867",
"0.61525667",
"0.6140577",
"0.61300814",
"0.61224824",
"0.6083455",
"0.6077178",
"0.6072798",
"0.60715663",
"0.60543495",
"0.60453093",
"0.6041671",
"0.6034065",
"0.60207427",
"0.6020742",
"0.60097843",
"0.60056025",
"0.60056025",
"0.5996893",
"0.59814924",
"0.5969565",
"0.5949173",
"0.593681",
"0.59345245",
"0.59134007",
"0.5908927",
"0.588836",
"0.5886052",
"0.5873881",
"0.5853822",
"0.5853647",
"0.58467966",
"0.58453536",
"0.5826514",
"0.58071345",
"0.58015543",
"0.579169",
"0.578218",
"0.5777335",
"0.5771238",
"0.5769467",
"0.5767957",
"0.5765705",
"0.5764571",
"0.5764293",
"0.57449925",
"0.5742613",
"0.5730438",
"0.57304317",
"0.57293606",
"0.5719908",
"0.5719722",
"0.5710595",
"0.570971",
"0.5708014",
"0.57079434",
"0.5686602",
"0.56845146",
"0.5683736",
"0.56835276",
"0.56835276",
"0.56781036",
"0.5671494",
"0.56562734",
"0.5655184",
"0.5651599",
"0.56515104",
"0.5651047",
"0.5641777",
"0.5633179",
"0.56279653",
"0.56268716",
"0.56250983",
"0.5622087"
] | 0.6947926 | 2 |
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",
"def show\n @album2photo = Album2photo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album2photo }\n end\n end",
"def show\n @album = Album.find(params[:id])\n @albums_count = Album.count\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album }\n end\n end",
"def show\n @user_album = UserAlbum.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user_album }\n end\n end",
"def index\n @albums = Album.all\n render json: @albums\n end",
"def show\n @album_owned = AlbumOwned.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album_owned }\n end\n end",
"def show\n @genres = Genre.find(:all)\n @genre = Genre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @genre }\n end\n end",
"def show\n @genre = Genre.find(params[:id])\n end",
"def show\n @program_genre = ProgramGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @program_genre }\n end\n end",
"def index\n @albums = Album.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @albums }\n end\n end",
"def show\n @gallery = Gallery.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @gallery }\n end\n end",
"def show\n @gallery = Gallery.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @gallery }\n end\n end",
"def show\n @photo = Photo.find(params[:id])\n\t@album = Album.find(@photo.album_id)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @photo }\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 movie_data\n response = RestClient.get(\"critics.api.mks.io/movie-genres\")\n JSON.parse(response)\nend",
"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 show\n @images = @galleries_album.galleries\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 show\n # Pull the selected photo album.\n @photo_tag = PhotoTag.find(params[:id])\n\n respond_to do |format|\n format.json do\n render json: @photo_tag\n end\n end\n end",
"def show\n @genotype = Genotype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @genotype }\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 @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 show\n render json: @web_car_gallery\n end",
"def show\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n format.html {render json: @gig, status: :ok}\n format.json { render json: @gig, status: :ok }\n end\n end",
"def index\n @genres = Genre.all\n end",
"def index\n @genres = Genre.all\n end",
"def show\r\n @photo = Photo.find(params[:id])\r\n\r\n @albums = Album.all\r\n @albums_map = {}\r\n @albums.each do |album| \r\n @albums_map[album.TITLE] = album.ID\r\n end\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @photo }\r\n end\r\n end",
"def index\n respond_with Genre.all\n end",
"def list_genres_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: GenreApi.list_genres ...\"\n end\n if @api_client.config.client_side_validation && !opts[:'page'].nil? && opts[:'page'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page\"]\" when calling GenreApi.list_genres, must be greater than or equal to 0.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'limit'].nil? && opts[:'limit'] > 50\n fail ArgumentError, 'invalid value for \"opts[:\"limit\"]\" when calling GenreApi.list_genres, must be smaller than or equal to 50.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'limit'].nil? && opts[:'limit'] < 1\n fail ArgumentError, 'invalid value for \"opts[:\"limit\"]\" when calling GenreApi.list_genres, must be greater than or equal to 1.'\n end\n\n if @api_client.config.client_side_validation && opts[:'order_direction'] && !['asc', 'desc'].include?(opts[:'order_direction'])\n fail ArgumentError, 'invalid value for \"order_direction\", must be one of asc, desc'\n end\n # resource path\n local_var_path = \"/genres\"\n\n # query parameters\n query_params = {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'parent_id'] = opts[:'parent_id'] if !opts[:'parent_id'].nil?\n query_params[:'program_id'] = opts[:'program_id'] if !opts[:'program_id'].nil?\n query_params[:'broadcast_id'] = opts[:'broadcast_id'] if !opts[:'broadcast_id'].nil?\n query_params[:'limit'] = opts[:'limit'] if !opts[:'limit'].nil?\n query_params[:'order-by'] = opts[:'order_by'] if !opts[:'order_by'].nil?\n query_params[:'order-direction'] = opts[:'order_direction'] if !opts[:'order_direction'].nil?\n query_params[:'_external_station_id'] = opts[:'_external_station_id'] if !opts[:'_external_station_id'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['API Key']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'GenreResults')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: GenreApi#list_genres\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show\n @gallery = Gallery.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gallery }\n end\n end",
"def index\n render json: Album.find(params[:album_id]).reviews\n end",
"def show\n \n @album = @user.albums.find(params[:id])\n\n respond_to do |format|\n \n format.html # show.html.erb\n format.js { render 'show'}\n format.json { render json: @album }\n end\n end",
"def index\n @musical_genres = MusicalGenre.all\n end",
"def genre_search(opts={})\r\n Rakuten::Request.get(\"https://app.rakuten.co.jp/services/api/IchibaGenre/Search/20120723\", Rakuten::Api.merge(opts))\r\n end",
"def show\n require 'open-uri' #for screen scraping\n \n @album = Album.find(params[:id])\n @artists = @album.artists\n @sources = @album.sources\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @album }\n end\n \n #adding in automation functionality\n # if @album.catalognumber.blank? == true \n # url = @album.reference\n # if url.split('/')[2] == \"vgmdb.net\"\n # doc = Nokogiri::HTML(open(url))\n # @catalognum = doc.xpath(\"//table[@id='album_infobit_large']//tr[1]//td[2]\").text\n # @album.catalognumber = @catalognum.split(' ')[0]\n # @album.save\n # end\n # end\n\n end",
"def genre_ranking\n ranked_albums = SortCollection.sort_albums('genre')\n render json: ranked_albums.sort_by(&:last).reverse.to_h, status: 200\n end",
"def show\n @albums = Artist.find(params[\"id\"]).albums\n end",
"def index\n if params[:album_id]\n @artists = Album.resolve(params[:album_id]).artist\n else\n @artists = Artist.order(:name)\n end\n\n render json: @artists\n end",
"def index\n @game_genres = GameGenre.all\n end",
"def get_genre_by_id_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: GenreApi.get_genre_by_id ...\"\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling GenreApi.get_genre_by_id\"\n end\n if @api_client.config.client_side_validation && id < 0\n fail ArgumentError, 'invalid value for \"id\" when calling GenreApi.get_genre_by_id, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = \"/genres/{id}\".sub('{' + 'id' + '}', id.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'_external_station_id'] = opts[:'_external_station_id'] if !opts[:'_external_station_id'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['API Key']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'GenreResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: GenreApi#get_genre_by_id\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\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 @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 show\n respond_to do |format|\n format.html { redirect_to action: 'edit', id: @album.id }\n format.json do\n render json: { rows: (@album.nil? ? [] : [@album.marshall]),\n status: (@album.nil? ? 404 : 200),\n total: (@album.nil? ? 0 : 1) }\n end\n end\n end",
"def genres\n songs.map{|song| song.genre} # giving back all the genres under that particular artist. artists can have nmany genres and calling of theirmany genres.\n # Song.all.map{|ind_song| ind_song.genre} #giving back all the different genres from the collection of song array. giving back all the genres of the songs\n # binding.pry\n end",
"def index\n # # if page value a param, use that, else ...\n # page = 3\n # request_url = MOVIE_DB_URL + \"&api_key=#{ENV[\"API_KEY\"]}\"\n genre_request_url = GENRE_URL + \"&api_key=#{ENV[\"API_KEY\"]}\"\n # request_url += \"&page=#{page}\"\n # if sort by release date\n # request_url += RELEASE_DATE_DESC_URL\n # if sort by title\n # request_url += RELEASE_DATE_DESC_URL;\n # @movies = Unirest.get(request_url).body[\"results\"]\n @genres = Unirest.get(genre_request_url).body[\"genres\"]\n # puts @genres\n end",
"def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gallery }\n end\n end",
"def show\n # @photo = @gallery.photos.build\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gallery }\n end\n end",
"def show\n @album = Album.find(params[:id])\n if @album.artist != nil\n @songs = get_songs_from_album @album.artist.name, @album.name\n @song_list = []\n if @songs\n @songs.each do |song|\n entry = Hash.new\n entry['rank'] = song['rank']\n entry['title'] = song['name']\n entry['artist'] = @album.artist.name\n song_in_db = lookup_song song['name'], @album.artist.name\n if song_in_db != nil\n entry['available'] = true\n entry['song_id'] = song_in_db.id\n else\n entry['available'] = false\n end\n entry['duration'] = seconds_to_duration(song['duration'].to_i)\n @song_list << entry\n end\n end\n @album_cover = get_album_cover @album.artist.name, @album.name\n @description = get_description_from_album @album.artist.name, @album.name\n end\n\n @songs = [] if @songs == nil\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album }\n end\n end",
"def serv_json\n \"http://api.dribbble.com/shots/popular?page=1\"\n end",
"def show\n respond_with genre\n end",
"def genre_search(opts={})\r\n opts[:version] = '2010-11-18' unless opts.key?(:version)\r\n opts[:operation] = 'ProductGenreInfo' unless opts.key?(:operation)\r\n opts[:developerId] = Rakuten::Api.options[:applicationId] unless opts.key?(:developerId)\r\n Rakuten::Request.get(\"http://api.rakuten.co.jp/rws/3.0/json\", Rakuten::Api.merge(opts))\r\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gallery }\n end\n end",
"def index\n @web_car_galleries = WebCarGallery.all\n\n render json: @web_car_galleries\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 index\n @galleries = Gallery.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @galleries }\n end\n end",
"def index\n @galleries = Gallery.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @galleries }\n end\n end",
"def index\n @galleries = Gallery.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @galleries }\n end\n end",
"def show\n @album = Album.find_by_slug(params[:album_id])\n @album_item = @album.album_items.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album_item }\n end\n end",
"def albums( options=nil )\n params = default_params.merge( \n :method => 'smugmug.albums.get',\n :heavy => 1\n ) \n\n params = params.merge( options ) if( options )\n xml = RestClient.post BASE, params\n \n Smile::Album.from_xml( xml, session_id )\n rescue\n nil\n end",
"def show\n @photo = @allbum.photos.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @photo }\n end\n end",
"def index\n\t\tparams[:search] ? @genres=Genre.search(params[:search]) : @genres=Genre.where(\"user_id = ?\", current_user.id).order(\"name\")\n\t\t@genres = @genres.paginate(page: params[:page], per_page: 18) if @genres\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.json { render json: @genres }\n\t\t\tformat.js\n\t\tend\n\tend",
"def set_galleries_album\n @galleries_album = Galleries::Album.find(params[:id])\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 index\n @pictures = @album.pictures.all\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 show\n @image_gallery = ImageGallery.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @image_gallery }\n end\n end",
"def show\n if !session[:access_token]\n redirect_to :controller => 'sessions', :action => 'connect'\n end\n\n pmocampo = \"30792403\"\n client = Instagram.client(:access_token => session[:access_token])\n \n @user = client.user(pmocampo)\n \n @album = Album.find(params[:id])\n @photos = client.user_recent_media(pmocampo)\n @photos = @photos.select {|p| p.tags.include?(@album.tag)}\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 @galleries = Gallery.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @galleries }\n end\n end",
"def index\n\t\t@genres = Genre.all\n\tend",
"def genres\n Song.all.collect{|song|song.genre}\n end",
"def genres\n MusicImporter.new(path).print_genres\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.65035653",
"0.6500866",
"0.646696",
"0.6444016",
"0.64328647",
"0.64206445",
"0.6413037",
"0.64088887",
"0.64027137",
"0.63997585",
"0.6398128",
"0.6389876",
"0.6387977",
"0.63851166",
"0.63814044",
"0.6380751",
"0.63803834",
"0.6379188",
"0.6368869",
"0.635036",
"0.635036",
"0.63468647",
"0.6328422",
"0.63184524",
"0.63184524",
"0.631473",
"0.6314255",
"0.6313201",
"0.6311487",
"0.6308484",
"0.62962264",
"0.6295454",
"0.62929755",
"0.6291176",
"0.6275449",
"0.62714",
"0.62662214",
"0.6260893",
"0.6255443",
"0.6251715",
"0.6246924",
"0.6245855",
"0.6245701",
"0.62402916",
"0.62398267",
"0.62279785",
"0.62195235",
"0.6211572",
"0.6205866",
"0.62050354",
"0.6200388",
"0.6187794",
"0.61868006",
"0.6185156",
"0.6185156",
"0.6185156",
"0.61800843",
"0.6176101",
"0.617263",
"0.6166176",
"0.6164583",
"0.6164179",
"0.6158594",
"0.61552787",
"0.61481595",
"0.6135042",
"0.6133574",
"0.6128763",
"0.6125269",
"0.6124133"
] | 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",
"def new\n @program_genre = ProgramGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @program_genre }\n end\n end",
"def new\n \n @album = @user.albums.new\n respond_to do |format|\n format.js { render 'new' }\n format.html # show.html.erb\n end\n end",
"def create\n\t\t@genre = Genre.new(genre_params)\n\t\t@genre.user_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 new\n @song = Song.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @song }\n end\n end",
"def new\n @song = Song.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @song }\n end\n end",
"def new\n @song = Song.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @song }\n end\n end",
"def new\n @song = Song.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @song }\n end\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 new\n @generator = Generator.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @generator }\n end\n end",
"def new\n @album = Album.new\n\n 3.times do\n @album.tracks.build\n end\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 @album.album_photos.build\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 @picture = @museum.pictures.new #Picture.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @picture }\n end\n end",
"def create\n @book_genre = BookGenre.new(params[:book_genre])\n\n respond_to do |format|\n if @book_genre.save\n format.html { redirect_to @book_genre, notice: 'Book genre was successfully created.' }\n format.json { render json: @book_genre, status: :created, location: @book_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @album = Album.new\n end",
"def new\n @album = Album.new\n end",
"def new \n @album = Album.new(params[:album])\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 @artists = Artist.find(:all)\n @features = Feature.find(:all)\n @album = Album.new\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 @song = current_user.songs.build\n # @genres = Genre.all.map { |c| [c.name, c.id] }\n end",
"def new\n @song = Song.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @song }\n end\n end",
"def new\n @song = Song.new\n\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 1.upto(3) { @album.photos.build }\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @album }\n end\n end",
"def new\n @gitem = Gitem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gitem }\n end\n end",
"def new\n @generation = Generation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @generation }\n end\n end",
"def new\n @impgen = Impgen.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @impgen }\n end\n end",
"def new\r\n @album = Album.new\r\n end",
"def new\n @album = current_account.albums.new\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 @gopy = Gopy.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gopy }\n end\n end",
"def new\r\n @photo = Photo.new\r\n \r\n if params[:id] != nil\r\n @album = Album.find(params[:id])\r\n if @album != nil\r\n @photo.ALBUM_ID = @album.ID\r\n end\r\n end\r\n\r\n @albums = Album.all\r\n @albums_map = {}\r\n @albums.each do |album| \r\n @albums_map[album.TITLE] = album.ID\r\n end\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @photo }\r\n end\r\n end",
"def new\n @gist = Gist.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gist }\n end\n end",
"def new\n @artist = Artist.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @artist }\n end\n end",
"def new\n\n @gig = Gig.new\n\n # get a list of all songs (for the songs selection dropddown)\n @song_list = Song.order(:Song).collect{|s| [s.full_name, s.SONGID]}\n\n save_referrer\n\n end",
"def new\n @genre = Genre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @genre }\n end\n end",
"def new\n @album = Album.new\n render :new\n end",
"def new\n @gig_request = GigRequest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gig_request }\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 new\n @category = Category.new\n \n # Get params\n # @genre_id = params[':genre_id']\n @genre_id = params[:genre_id]\n \n if @genre_id != nil\n @category.genre_id = @genre_id\n end\n \n # @genres = Genre.all\n# \n # @genre_names = []\n# \n # @genres.each do |item|\n # @genre_names.push(item.name)\n # end\n# \n # # reset_id\n# \n # @cats = Category.find_all_by_genre_id(2)\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @category }\n end\n end",
"def new\n @gid2name = Gid2name.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gid2name }\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 do\n render json: { rows: (@album.nil? ? [] : [@album.marshall]),\n status: (@album.nil? ? 404 : 200),\n total: (@album.nil? ? 0 : 1) }\n end\n end\n end",
"def new\n @gallery = current_user.galleries.build\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 @album = Album.new\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 @album = Album.new\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 @album = Album.new\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 @album = Album.new\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 @pic = Pic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pic }\n end\n end",
"def new\n @image_gallery = ImageGallery.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @image_gallery }\n end\n end",
"def new\n @grm = Grm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @grm }\n end\n end",
"def new\n @gallery = Gallery.new(:public => true)\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 @generator_info = GeneratorInfo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @generator_info }\n end\n end",
"def new\n @photographer = Photographer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @photographer }\n end\n end",
"def create\n @gen = Gen.new(params[:gen])\n\n respond_to do |format|\n if @gen.save\n format.html { redirect_to @gen, notice: 'Gen was successfully created.' }\n format.json { render json: @gen, status: :created, location: @gen }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gen.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 new\n @photographer = Photographer.new\n\n respond_to do |format|\n # format.html # new.html.erb\n format.json { render json: @photographer }\n end\n end",
"def new\n @guitar = Guitar.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @guitar }\n end\n end",
"def new\n @artist = Artist.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @artist }\n end\n end",
"def new\n @photoid = Photoid.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @photoid }\n end\n end",
"def new\n @genre = Genre.new\n end",
"def create\n @game_genre = GameGenre.new(game_genre_params)\n\n respond_to do |format|\n if @game_genre.save\n format.html { redirect_to @game_genre, notice: 'Game genre was successfully created.' }\n format.json { render :show, status: :created, location: @game_genre }\n else\n format.html { render :new }\n format.json { render json: @game_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @grm_grappt = GrmGrappt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @grm_grappt }\n end\n end",
"def new\n @gig = Gig.new()\n @gig.build_attachment\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gig }\n end\n end",
"def new\n @grm_dog = GrmDog.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @grm_dog }\n end\n end",
"def new\n @music = Music.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @music }\n end\n end",
"def new\n @music = Music.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @music }\n end\n end",
"def new\n @music = Music.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @music }\n end\n end",
"def new\n @galeria = Galeria.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @galeria }\n end\n end",
"def create\n @genrecreate = Genrecreate.new(genrecreate_params)\n\n respond_to do |format|\n if @genrecreate.save\n format.html { redirect_to @genrecreate, notice: 'Genrecreate was successfully created.' }\n format.json { render :show, status: :created, location: @genrecreate }\n else\n format.html { render :new }\n format.json { render json: @genrecreate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @gallery = Gallery.new\n \n respond_to do |format|\n format.html{ redirect_to edit_portfolio_project_path(params[:project_id])+\"?new_gallery=1\" }\n format.json { render json: @gallery }\n end\n end",
"def new\n @gasto = Gasto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gasto }\n end\n end",
"def new\n @girltype = Girltype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @girltype }\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.6933972",
"0.69150853",
"0.6897846",
"0.6869266",
"0.6869266",
"0.6869266",
"0.6869266",
"0.6847777",
"0.6846194",
"0.68382496",
"0.683795",
"0.68366575",
"0.68232393",
"0.6820583",
"0.6820583",
"0.68179476",
"0.6812753",
"0.6812389",
"0.6812177",
"0.6812177",
"0.6811698",
"0.6800979",
"0.6793891",
"0.67932016",
"0.67725146",
"0.67597616",
"0.6759449",
"0.67589974",
"0.6755207",
"0.67548656",
"0.6752516",
"0.6745622",
"0.67453605",
"0.67351186",
"0.6734182",
"0.67227376",
"0.6721749",
"0.67216337",
"0.67191356",
"0.6719004",
"0.6719004",
"0.6719004",
"0.6719004",
"0.6716097",
"0.6713204",
"0.6712433",
"0.6705171",
"0.6704796",
"0.6702239",
"0.6698522",
"0.66953695",
"0.66953695",
"0.66953695",
"0.66899335",
"0.66868436",
"0.66826254",
"0.66765964",
"0.666706",
"0.66649336",
"0.6656638",
"0.66517025",
"0.6643277",
"0.6639405",
"0.6639405",
"0.6639405",
"0.66351503",
"0.66335195",
"0.6624271",
"0.66219425",
"0.66215307"
] | 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\t@genre.user_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",
"def to_api_json\n Jbuilder.encode do |json|\n json.albums do\n json.array! @albums do |album|\n json.call(album, :name, :uuid)\n json.set!(:artist, album.artist_name)\n json.set!(:artist_twitter_screen_name, twitter_screen_name(album))\n json.set!(:thumbnail_url, album.image || album.thumbnail)\n json.set!(:release_date, album.release_date.in_time_zone.to_i)\n json.set!(:release_date_string, album.release_date.to_s)\n json.set!(:age, album.anniversary.count)\n json.set!(:day_of_week, album.anniversary.current.strftime('%A'))\n json.set!(:anniversary, album.anniversary.current.in_time_zone.to_i)\n json.set!(:anniversary_string, album.anniversary.current.to_s)\n json.set!(:review_link, album.link)\n json.set!(:rating, album.rating)\n json.set!(:generated_fun_fact_description, album.generated_fun_fact_description)\n json.set!(:fun_fact_description, album.fun_fact_description)\n json.set!(:fun_fact_source, album.fun_fact_source)\n json.set!(:link, \"/albums/#{album.slug}\")\n json.set!(:update, \"/v1/admin/albums/#{album.id}\")\n end\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 group_url(@album.group), 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(album_params)\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to action: 'index', notice: 'Album was successfully created.' }\n format.json { render action: 'index', status: :created, location: @album }\n else\n format.html { render action: 'index' }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @album = Album.new\n\n 3.times do\n @album.tracks.build\n end\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 @game_genre = GameGenre.new(game_genre_params)\n\n respond_to do |format|\n if @game_genre.save\n format.html { redirect_to @game_genre, notice: 'Game genre was successfully created.' }\n format.json { render :show, status: :created, location: @game_genre }\n else\n format.html { render :new }\n format.json { render json: @game_genre.errors, status: :unprocessable_entity }\n end\n end\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 create\n\t\tgenre = Genre.create(genre_params)\n\n\t\tif !genre.errors.any?\n\t\t\trender json: genre\n\t\telsif genre.errors.messages[:name][0] == \"has already been taken\"\n\t\t\trender json: {message: \"Genre already exists\"}\n\t\telse\n\t\t\trender json: {message: \"Error occurred\"}\n\t\tend\n\tend",
"def create\n @album = current_user.albums.new(album_params)\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'El album a sido creado satisfactoriamente.' }\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 @musical_genre = MusicalGenre.new(musical_genre_params)\n\n respond_to do |format|\n if @musical_genre.save\n format.html { redirect_to @musical_genre, notice: 'Musical genre was successfully created.' }\n format.json { render :show, status: :created, location: @musical_genre }\n else\n format.html { render :new }\n format.json { render json: @musical_genre.errors, status: :unprocessable_entity }\n end\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 create\n @galleries_gallery = @galleries_album.galleries.new(galleries_gallery_params)\n @galleries_gallery.user = current_user\n respond_to do |format|\n if @galleries_gallery.save\n format.html { redirect_to galleries_album_gallery_path(@galleries_gallery), notice: 'Gallery was successfully created.' }\n # format.json { render :show, status: :created, location: @galleries_gallery }\n format.json { render json: {files: [@galleries_gallery.to_jq_upload] }, status: :created}\n\n else\n format.html { render :new }\n format.json { render json: @galleries_gallery.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @book_genre = BookGenre.new(params[:book_genre])\n\n respond_to do |format|\n if @book_genre.save\n format.html { redirect_to @book_genre, notice: 'Book genre was successfully created.' }\n format.json { render json: @book_genre, status: :created, location: @book_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @genre = Genre.new(params[:genre])\n @genre.save\n redirect_to @genre\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 genre_params\n params.require(:genre).permit(:name)\n end",
"def genre_params\n\t\t\tparams.require(:genre).permit(:name, :cover_page, :user_id)\n\t\tend",
"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 create\n @album = current_user.albums.new(params[:album])\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'You created a #Album. Now share your #album around the internets' }\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 @user_album = UserAlbum.new(params[:user_album])\n\n respond_to do |format|\n if @user_album.save\n format.html { redirect_to @user_album, notice: 'User album was successfully created.' }\n format.json { render json: @user_album, status: :created, location: @user_album }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @album = Album.new(album_params)\n respond_to do |format|\n if @album.save\n flash[:success] = 'The album was successfully created.'\n format.html { redirect_to albums_path }\n format.json { render json: { rows: [@album.marshall], status: 200, total: 1 } }\n else\n @albums = Album.all\n notice = \"An error occured while creating the album. #{@album.errors.full_messages.to_sentence}.\"\n flash[:error] = notice\n format.html { render action: 'index', alert: notice }\n format.json { render json: { errors: @album.errors, status: :unprocessable_entity } }\n end\n end\n end",
"def create\n @web_car_gallery = WebCarGallery.new(web_car_gallery_params)\n\n if @web_car_gallery.save\n render json: @web_car_gallery, status: :created, location: @web_car_gallery\n else\n render json: @web_car_gallery.errors, status: :unprocessable_entity\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 @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 = Album.new(params[:album])\n \n respond_to do |format|\n images = [params[:images]].flatten\n @album.images << Image.find(images) unless images[0].nil?\n \n if @album.save\n format.html { redirect_to(albums_path, :notice => 'Album was successfully created.') }\n format.xml { render :xml => albums_path, :status => :created, :location => @album }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @album.errors, :status => :unprocessable_entity }\n end\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 create\n @album = current_user.albums.build(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 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 @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 create\n @sub_genre = SubGenre.new(params[:sub_genre])\n\n respond_to do |format|\n if @sub_genre.save\n format.html { redirect_to @sub_genre, notice: 'Sub genre was successfully created.' }\n format.json { render json: @sub_genre, status: :created, location: @sub_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sub_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @album = Album.new(album_params)\n\n not_blank_photos = @album.photos.select do |photo|\n ! photo.title.blank?\n end\n @album.photos = not_blank_photos\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 @omdb_genre = OmdbGenre.new(omdb_genre_params)\n\n respond_to do |format|\n if @omdb_genre.save\n format.html { redirect_to @omdb_genre, notice: 'Omdb genre was successfully created.' }\n format.json { render action: 'show', status: :created, location: @omdb_genre }\n else\n format.html { render action: 'new' }\n format.json { render json: @omdb_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def genre_params\n params.require(:genre).permit(:name, :description, :slug)\n end",
"def create\n redirect_to new_album_path, alert: \"You have to select at least one artist.\" and return if params[:album][:album_artists].size == 1 && params[:album][:album_artists][0].empty? # TODO: Find a better way to do this, it does not play nicely with json and xml\n @album = Album.new(album_params)\n album_artists\n album_cover if params[:search_online]\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 format.xml { render xml: @album, status: :created }\n else\n format.html { render :new }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n format.xml { render xml: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\t\talbum = Album.create(album_params)\n\n\t\tif !album.errors.any?\n\t\t\trender json: album\n\t\telse\n\t\t\trender json: {message: \"Error occurred\"}\n\t\tend\n\tend",
"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 @subgenre = Subgenre.new(subgenre_params)\n\n respond_to do |format|\n if @subgenre.save\n format.html { redirect_to @subgenre, 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 new_album = Album.new\n new_album.title = params[:title]\n new_album.artist = params[:artist]\n new_album.year = params[:year]\n new_album.album_art = params[:album_art]\n new_album.save\n end",
"def album_params\n params.require(:album).permit(:title, :description, images: [])\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 genre_params\n\t\t params.require(:genre).permit(:name)\n\t\tend",
"def create_movie(response)\n movie = Movie.new(title: response[\"title\"],\n release_date: response[\"release_date\"],\n description: response[\"overview\"],\n poster: response[\"poster_path\"])\n genres = response[\"genres\"]\n genres.each do |genre|\n movie_genre = Genre.find_or_create_by(genre: genre[\"name\"])\n movie.genres << movie_genre\n end\n movie.save!\n movie\n end",
"def create\n @genrecreate = Genrecreate.new(genrecreate_params)\n\n respond_to do |format|\n if @genrecreate.save\n format.html { redirect_to @genrecreate, notice: 'Genrecreate was successfully created.' }\n format.json { render :show, status: :created, location: @genrecreate }\n else\n format.html { render :new }\n format.json { render json: @genrecreate.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: 'Albumi loomine õnnestus.' }\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_owned = AlbumOwned.new(params[:album_owned])\n\n respond_to do |format|\n if @album_owned.save\n format.html { redirect_to @album_owned, notice: 'Album owned was successfully created.' }\n format.json { render json: @album_owned, status: :created, location: @album_owned }\n else\n format.html { render action: \"new\" }\n format.json { render json: @album_owned.errors, status: :unprocessable_entity }\n end\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 genre_params\n params.require(:genre).permit(:name)\n end",
"def genre_params\n params.require(:genre).permit(:name)\n end",
"def create\n \n @album = Album.new(params[:album])\n #params[:artist] if statement\n params[\"artistnames\"].each do |each|\n if each.empty? == false\n @artistexists = Artist.find_by_name(each)\n if @artistexists.nil? == true\n @album.artists.build(:name => each)\n else\n @album.artists << Artist.find_by_name(each)\n end\n end\n end\n params[\"sourcenames\"].each do |each|\n if each.empty? == false\n @artistexists = Source.find_by_name(each)\n if @artistexists.nil? == true\n @album.sources.build(:name => each)\n else\n @album.sources << Source.find_by_name(each)\n end\n end\n end\n \n if params[:album][:catalognumber].blank? == true \n url = params[:album][:reference]\n if url.split('/')[2] == \"vgmdb.net\"\n doc = Nokogiri::HTML(open(url))\n @catalognum = doc.xpath(\"//table[@id='album_infobit_large']//tr[1]//td[2]\").text\n @album.catalognumber = @catalognum.split(' ')[0]\n end\n end\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 if params[:title] == \"new\"\n format.js { js_redirect_to(album_path(@album))}\n else\n format.js {} \n end\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @album.errors, :status => :unprocessable_entity }\n format.js {}\n end\n end\n end",
"def create\n @song = Song.new(song_params)\n\n respond_to do |format|\n if @song.save\n album_id = params[\"album\"]\n \n if not album_id.nil?\n album = Album.find_by(id: album_id)\n if not album.nil?\n album.songs << @song\n album.save\n\n artist = album.artist\n\n if not artist.nil?\n artist_id = artist.id\n if not artist_id.nil?\n artist.songs << @song\n artist.save\n end\n end\n end\n end\n\n format.html { redirect_to @song, notice: 'Song was successfully created.' }\n format.json { render :show, status: :created, location: @song }\n else\n format.html { render :new }\n format.json { render json: @song.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n respond_to do |format|\n @album.user = current_user\n if @album.save\n format.html { redirect_to artist_album_path(@artist,@album), notice: 'album was successfully created.' }\n format.json { render action: 'show', status: :created, location: artist_album_path(@artist,@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 = Pagealbum.new(album_params)\n @images=album_params[:images_attributes].values.map {|x| Image.new(x)} rescue []\n\n respond_to do |format|\n if @album.save\n page=Page.first\n page.albums << @album\n format.html { redirect_to my_album_page_path(id: @album.id), notice: \"Pagealbum 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 \n @album = Album.new(params[:album])\n \n respond_to do |format|\n if @album.save\n flash[:notice] = 'Album was successfully created.'\n format.html { redirect_to(@album) }\n format.xml { render :xml => @album, :status => :created, :location => @album }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @album.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def genre_params\n params.require(:genre).permit(:genretitle)\n end",
"def create\n\n artist_id = artist_exist_or_new(params[:artist_name])\n\n album_id = album_exist_or_new(params[:album_name], params[:genre], artist_id)\n\n @song = Song.new(song_params)\n @song.album_id = album_id\n\n respond_to do |format|\n if @song.save\n format.html { render '/shared/created'}\n format.json { render action: 'show', 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 destroy\n @album_genre = AlbumGenre.find(params[:id])\n @album_genre.destroy\n\n respond_to do |format|\n format.html { redirect_to album_genres_url }\n format.json { head :no_content }\n end\n end",
"def new\n @album = Album.new\n @album.album_photos.build\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 @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 create\n @album = Album.new(params[:album])\n respond_to do |format|\n if @user.albums << @album\n flash[:notice] = 'Album was successfully created.'\n format.html { redirect_to user_albums_path(@user) }\n format.xml { render :xml => @album, :status => :created, :location => @album }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @album.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def albums( options=nil )\n params = default_params.merge( \n :method => 'smugmug.albums.get',\n :heavy => 1\n ) \n\n params = params.merge( options ) if( options )\n xml = RestClient.post BASE, params\n \n Smile::Album.from_xml( xml, session_id )\n rescue\n nil\n end",
"def album_params\n #params[:album]\n params.require(:album).permit(:title,:release_date,:price,:genre,\n :image_path,:artist_id)\n end",
"def create\n @albumfife = Albumfive.new(albumfife_params)\n\n respond_to do |format|\n if @albumfife.save\n format.html { redirect_to @albumfife, notice: 'Albumfive was successfully created.' }\n format.json { render :show, status: :created, location: @albumfife }\n else\n format.html { render :new }\n format.json { render json: @albumfife.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @album = Album.new\n 1.upto(3) { @album.photos.build }\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @album }\n end\n end",
"def album_params\n params.require(:album).permit(:name, :creation_date, :cover)\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 create\n @photoalbum = Photoalbum.new(params[:photoalbum])\n\n respond_to do |format|\n if @photoalbum.save\n format.html { redirect_to edit_photoalbum_path @photoalbum, notice: 'Photoalbum was successfully created.' }\n format.json { render json: @photoalbum, status: :created, location: @photoalbum }\n else\n format.html { render 'new' }\n format.json { render json: @photoalbum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def album_create_params\n params.permit(album: [:artist, :title, :label_code]) # artist and title are in album, which is in params\n end",
"def album_params\n params.require(:album).permit(:id, :artist_id, :project_id, :album_id, :title, :release_date, :cover_art, :remove_cover_art, :genre, :genre_list, :tag_list)\n end",
"def create\n @album = Album.new(album_params)\n @album.user_id = current_user.id\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album erfolgreich erstellt.' }\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 @gen = Gen.new(params[:gen])\n\n respond_to do |format|\n if @gen.save\n format.html { redirect_to @gen, notice: 'Gen was successfully created.' }\n format.json { render json: @gen, status: :created, location: @gen }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gen.errors, status: :unprocessable_entity }\n end\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"
] | [
"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.6076714",
"0.6069994",
"0.6055152",
"0.60501057",
"0.6050009",
"0.6017909",
"0.60131955",
"0.6012266",
"0.6010317",
"0.60064924",
"0.5998026",
"0.5997576",
"0.59916806",
"0.5991132",
"0.59850013",
"0.5981674",
"0.59796864",
"0.5977463",
"0.5975245",
"0.5966586",
"0.5954992",
"0.59445953",
"0.59445953",
"0.5942602",
"0.5938309",
"0.59382206",
"0.5932128",
"0.59227204",
"0.5917711",
"0.5916156",
"0.5912129",
"0.59112847",
"0.5906369",
"0.59041005",
"0.58971274",
"0.58838147",
"0.5877918",
"0.5874719",
"0.58731234",
"0.5870326",
"0.58679384",
"0.58675605",
"0.5860716",
"0.5858192",
"0.58476317",
"0.5845029",
"0.5845029",
"0.5839785",
"0.58309907",
"0.5816071",
"0.5812746",
"0.58074266",
"0.5804685",
"0.58026534",
"0.5791992",
"0.5791468",
"0.579124",
"0.5784699",
"0.5783526",
"0.57782704",
"0.5777616",
"0.57763183",
"0.57760394",
"0.576964",
"0.57692635",
"0.5762595",
"0.5759846",
"0.5739924",
"0.57373875",
"0.5735536"
] | 0.70034546 | 1 |
PUT /album_genres/1 PUT /album_genres/1.json | def update
@album_genre = AlbumGenre.find(params[:id])
respond_to do |format|
if @album_genre.update_attributes(params[:album_genre])
format.html { redirect_to @album_genre, notice: 'Album genre was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
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 update\n @album.genre_id = params[:genre_id]\n \n\n if @album.update(album_params)\n redirect_to album_path(@album)\n else\n render 'edit'\n end\n end",
"def update\n @song = Song.find(params[:id])\n # Hack? How to do this better...\n params[:song][:genre] = Genre.find(params[:song][:genre_id])\n params[:song].delete(:genre_id)\n\n respond_to do |format|\n if @song.update_attributes(params[:song])\n format.html { redirect_to [@artist, @song], notice: 'Song was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @song.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n artist_id = update_artist_exist_or_new(params[:artist_name])\n\n album_id = update_album_exist_or_new(params[:album_name], params[:genre], artist_id)\n\n respond_to do |format|\n\n @song.album_id = album_id\n a = @song.album\n a.artist_id = artist_id\n a.save\n\n if @song.update(song_params)\n format.html { redirect_to @song, notice: 'Song was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @song.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @galleries_album.update(galleries_album_params)\n format.html { redirect_to @galleries_album, notice: 'Album was successfully updated.' }\n format.json { render :show, status: :ok, location: @galleries_album }\n else\n format.html { render :edit }\n format.json { render json: @galleries_album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n ActiveRecord::Base.transaction do\n @album.update!(name: params[:name])\n @album.album_images.destroy_all\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 album\n album = Album.find(params[:id])\n render json: album\n end",
"def update\n @song_genre = SongGenre.find(params[:id])\n\n respond_to do |format|\n if @song_genre.update_attributes(params[:song_genre])\n format.html { redirect_to @song_genre, notice: 'Song genre was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @song_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @song.update(song_params)\n album_id = params[\"album\"]\n \n if not album_id.nil?\n album = Album.find_by(id: album_id)\n if not album.nil?\n album.songs << @song\n album.save\n\n artist = album.artist\n\n if not artist.nil?\n artist_id = artist.id\n if not artist_id.nil?\n artist.songs << @song\n artist.save\n end\n end\n end\n end\n \n format.html { redirect_to @song, notice: 'Song was successfully updated.' }\n format.json { render :show, status: :ok, location: @song }\n else\n format.html { render :edit }\n format.json { render json: @song.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @genre.update(genre_params)\n format.html { redirect_to @genre, notice: 'Genre was successfully updated.' }\n format.json { render :show, status: :ok, location: @genre }\n else\n format.html { render :edit }\n format.json { render json: @genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_galleries_album\n @galleries_album = Galleries::Album.find(params[:id])\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { render :show, status: :ok, location: @album }\n else\n format.html { render :edit }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { render :show, status: :ok, location: @album }\n else\n format.html { render :edit }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { render :show, status: :ok, location: @album }\n else\n format.html { render :edit }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def album_params\n params.require(:album).permit(:id, :title, :description, :artist, :image, :genre_id)\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: \"Album was successfully updated.\" }\n format.json { render :show, status: :ok, location: @album }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @album = Album.find(params[:id])\n\n respond_to do |format|\n if @album.update_attributes(params[:album])\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def update\n @album = Album.find(params[:id])\n \n respond_to do |format|\n if @album.update_attributes(params[:album])\n @album.images.clear\n @album.images << Image.find([params[:images]].flatten)\n @album.save!\n format.html { redirect_to(albums_path, :notice => 'Album was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @album.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @genre = Genre.friendly.find(params[:id])\n respond_to do |format|\n if @genre.update(genre_params)\n format.html { redirect_to @genre, notice: 'Genre was successfully updated.' }\n format.json { render :show, status: :ok, location: @genre }\n else\n format.html { render :edit }\n format.json { render json: @genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_song\n @song = Song.find(params[:genre_name])\n end",
"def update\n @album = Album.find(params[:id])\n\n respond_to do |format|\n if @album.update_attributes(params[:album])\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @album = Album.find(params[:id])\n\n respond_to do |format|\n if @album.update_attributes(params[:album])\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @genrecreate.update(genrecreate_params)\n format.html { redirect_to @genrecreate, notice: 'Genrecreate was successfully updated.' }\n format.json { render :show, status: :ok, location: @genrecreate }\n else\n format.html { render :edit }\n format.json { render json: @genrecreate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @genre = Genre.find(params[:id])\n\n respond_to do |format|\n if @genre.update_attributes(params[:genre])\n flash[:notice] = \"Genre '#{@genre}' was successfully updated.\"\n format.html { redirect_to genre_url(@genre) }\n format.xml { head :ok }\n format.js { render :template => 'music/genres/success' }\n else\n format.html { render :action => :edit }\n format.xml { render :xml => @genre.errors.to_xml }\n format.js { render :template => 'music/genres/error' }\n end\n end\n end",
"def update\n @album = Album.find(album_params[:id])\n respond_to do |format|\n if @album.update_attributes(album_params)\n flash[:success] = 'The album was successfully updated.'\n format.html { redirect_to edit_album_url(@album.id) }\n format.json { render json: { rows: [@album.marshall], status: 200, total: 1 } }\n else\n base = 'Failed to save the album. '\n flash[:error] = 'An error occured while updating the album.'\n format.html { render action: 'edit', alert: base + @album.errors.full_messages.to_sentence + '.' }\n format.json { render json: { errors: @album.errors, status: :unprocessable_entity } }\n end\n end\n end",
"def update\n #@song.genre_id = params[:genre_id]\n if @song.update(song_params)\n redirect_to song_path(@song)\n else\n render 'edit'\n end\n end",
"def update\n respond_to do |format|\n if @omdb_genre.update(omdb_genre_params)\n format.html { redirect_to @omdb_genre, notice: 'Omdb genre was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @omdb_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @genre = Genre.find(params[:id])\n @genre.update_attributes(params[:genre])\n redirect_to @genre\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'El album a sido actualizado satisfactoriamente.' }\n format.json { render :show, status: :ok, location: @album }\n else\n format.html { render :edit }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(name, artist, year, genre)\n self.name = name.length > 0 ? name : self.name\n self.artist = artist.length > 0 ? artist : self.artist\n self.year = year.length > 0 ? year : self.year\n self.genre = genre.length > 0 ? genre : self.genre\n @@albums[self.id] = Album.new(self.name, self.artist, self.year, self.genre, self.id)\n end",
"def update\n @album = current_user.albums.find(params[:id])\n\n respond_to do |format|\n if @Album.update_attributes(params[:album])\n format.html { redirect_to @album, notice: 'album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @Album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @albumsix.update(albumsix_params)\n format.html { redirect_to @albumsix, notice: 'Albumsix was successfully updated.' }\n format.json { render :show, status: :ok, location: @albumsix }\n else\n format.html { render :edit }\n format.json { render json: @albumsix.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @album.update_attributes(params[:album])\n format.html { redirect_to album_url(@album), notice: 'Album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def upload\n @album = Album.find( params[:album_id].to_i)\n end",
"def set_album\n @album = Admin::Album.find(params[:id])\n end",
"def set_album\n @album = Admin::Album.find(params[:id])\n end",
"def update\n respond_to do |format|\n if @album.update(allowed_params_album)\n format.html { redirect_to @album, notice: 'Album was successfully updated.' }\n format.json { render :show, status: :ok, location: @album }\n else\n format.html { render :edit }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\t\t@set_def_avt=params[:genre][:default_avatar]\n\t\t@genre.cover_page.destroy if @set_def_avt\n\n\t\trespond_to do |format|\n\t\t\tif @genre.update(genre_params)\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[:info]= 'Genre was successfully updated.' }\n\t\t\t\tformat.json { render :show, status: :ok, location: @genre }\n\t\t\t\tformat.js\n\t\t\telse\n\t\t\t\tformat.html { render :edit }\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_params\n params.require(:album).permit(:gn_id, :artist, :title, :release_date, :track_count, :genre, :url)\n end",
"def album_params\n params.require(:album).permit(:name, :artist, :year, :genre)\n end",
"def update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to artist_album_url(@artist,@album), notice: 'album was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\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 set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def set_album\n @album = Album.find(params[:id])\n end",
"def update\n respond_to do |format|\n if @musical_genre.update(musical_genre_params)\n format.html { redirect_to @musical_genre, notice: 'Musical genre was successfully updated.' }\n format.json { render :show, status: :ok, location: @musical_genre }\n else\n format.html { render :edit }\n format.json { render json: @musical_genre.errors, status: :unprocessable_entity }\n end\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 update_album(person_id,album_id, caption, location='', privacy='Everyone')\n @restv9.update_album(person_id,album_id, caption, location, privacy)\n end",
"def destroy\n @album_genre = AlbumGenre.find(params[:id])\n @album_genre.destroy\n\n respond_to do |format|\n format.html { redirect_to album_genres_url }\n format.json { head :no_content }\n end\n end",
"def set_album\n @album = Album.find(params[:album_id])\n end",
"def set_album\n @album = Album.find(params[:album_id])\n end",
"def update\n @album = Album.find(params[:id])\n\n respond_to do |format|\n if @album.update_attributes(params[:album])\n flash[:notice] = 'Album was successfully updated.'\n format.html { redirect_to @album }\n format.json { head :no_content }\n else\n format.html { render action = \"edit\" }\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 update\n respond_to do |format|\n if @album.update(album_params)\n format.html { redirect_to @album, notice: 'アルバム情報を更新しました。' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @albumone.update(albumone_params)\n format.html { redirect_to @albumone, notice: 'Albumone was successfully updated.' }\n format.json { render :show, status: :ok, location: @albumone }\n else\n format.html { render :edit }\n format.json { render json: @albumone.errors, status: :unprocessable_entity }\n end\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 update\n @album = Album.find(params[:id])\n\n respond_to do |format|\n if @album.update_attributes(params[:album])\n format.html { redirect_to @album, notice: 'Albumi uuendamine õnnestus' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @album.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 update\n @book_genre = BookGenre.find(params[:id])\n\n respond_to do |format|\n if @book_genre.update_attributes(params[:book_genre])\n format.html { redirect_to @book_genre, notice: 'Book genre was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @book_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def resource\n\t\t@album\n\tend",
"def update\n \n # genre = []\n # genre_ids = book_params[:genre_ids]\n # genre_ids.size.times do |n|\n # if book_params[:genre_ids][n].to_i == 0\n # nil\n # else\n # genre << Genre.find_by(id: book_params[:genre_ids][n].to_i)\n # end\n # end\n \n\n respond_to do |format|\n\n if @book.update(book_params)\n format.html { redirect_to @book, notice: 'Book was successfully updated.' }\n format.json { render :show, status: :ok, location: @book }\n else\n format.html { render :edit }\n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @image = @album.images.find(params[:id])\n @image.update(image_params)\n redirect_to album_path(@image.album.id)\n end",
"def update\n respond_to do |format|\n if @game_genre.update(game_genre_params)\n format.html { redirect_to @game_genre, notice: 'Game genre was successfully updated.' }\n format.json { render :show, status: :ok, location: @game_genre }\n else\n format.html { render :edit }\n format.json { render json: @game_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_album\n begin\n @album = Album.find(params[:id])\n rescue ActiveRecord::RecordNotFound => e\n render :json => {error: 'record not found'}, status: :not_found\n end\n end",
"def update\n @gallery = Gallery.find(params[:id])\n @gallery.update_attributes(params[:gallery])\n respond_with(@gallery, :status => :updated)\n end",
"def set_album\n @album = Album.find_by(id: params[:id])\n end",
"def set_genre\n @genre = Genre.find(params[:id])\n end",
"def set_genre\n @genre = Genre.find(params[:id])\n end",
"def set_album\n @image = Album.find(params[:album_id])\n end",
"def update\n @movie = @catalogue.movies.find(params[:id])\n data = params[:movie]\n if(data.has_key?(\"genres\"))\n\t\tids = Genre.get_ids(data[:genres])\n\t\tdata.delete(\"genres\")\n\tend\n\t@movie.enable_dirty_associations do\n\t\tunless ids == nil\n\t\t\t@movie.genre_ids = ids\n\t end\n\n\t respond_to do |format|\n\t if @movie.update_attributes(data)\n\t format.html { redirect_to(@movie, :notice => 'Movie was successfully updated.') }\n\t format.xml { head :ok }\n\t format.json { render :json => {:success => true} }\n\t else\n\t format.html { render :action => \"edit\" }\n\t format.xml { render :xml => @movie.errors, :status => :unprocessable_entity }\n\t format.json { render :json => {:success => false, :errors => @movie.errors} }\n\t end\n\t end\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 album_params\n params.require(:album).permit(:title, :description, :genre, :cover, :artists)\n end",
"def updateartists\n @album = Album.find(params[:id])\n album_param = params[:albums]\n @album.artists.delete_all \n album_param[:artists].each do |artist_id|\n artist = Artist.find(artist_id)\n @album.artists << artist \n end \n respond_to do |format|\n format.html { redirect_to(:action => :show) }\n format.xml { head :ok }\n end \n end",
"def update\n @track_file = TrackFile.find(params[:id])\n\n if @track_file.update(track_file_params)\n @album = Album.find(@track_file.track.album.id)\n render json: @album\n else\n render json: @track_file.errors.full_messages, status: 422\n end\n end"
] | [
"0.7517497",
"0.6779685",
"0.6500512",
"0.64261913",
"0.6375227",
"0.6329442",
"0.630047",
"0.6285673",
"0.62521976",
"0.62448126",
"0.6172432",
"0.61572176",
"0.61572176",
"0.61572176",
"0.6157158",
"0.61494976",
"0.6118786",
"0.6111482",
"0.6111482",
"0.6111482",
"0.6111482",
"0.6111482",
"0.61038446",
"0.6094934",
"0.6092889",
"0.60778564",
"0.60778564",
"0.60685325",
"0.6067725",
"0.6067725",
"0.6067725",
"0.60664666",
"0.6045209",
"0.60440373",
"0.6042754",
"0.6035911",
"0.6025194",
"0.60231036",
"0.60205275",
"0.6018736",
"0.6012314",
"0.6004544",
"0.6003387",
"0.6003387",
"0.59952646",
"0.5991905",
"0.5990001",
"0.59886754",
"0.59841764",
"0.5979965",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.5979164",
"0.597812",
"0.5975486",
"0.5969425",
"0.5962586",
"0.59616834",
"0.59616834",
"0.595469",
"0.5929754",
"0.59259063",
"0.5921755",
"0.59075534",
"0.5907343",
"0.58919287",
"0.5880483",
"0.5872422",
"0.5861274",
"0.58456147",
"0.58448684",
"0.5842804",
"0.58364636",
"0.5835891",
"0.58331496",
"0.58331496",
"0.583088",
"0.58234936",
"0.58230424",
"0.5814386",
"0.5810787",
"0.5806204"
] | 0.6718243 | 2 |
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 album=@photo.album\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",
"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 @albumseven.destroy\n respond_to do |format|\n format.html { redirect_to albumsevens_url, notice: 'Albumseven was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @private_album.destroy\n respond_to do |format|\n format.html { redirect_to private_albums_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album = current_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 @albumfour.destroy\n respond_to do |format|\n format.html { redirect_to albumfours_url, notice: 'Albumfour was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user_album = UserAlbum.find(params[:id])\n @user_album.destroy\n\n respond_to do |format|\n format.html { redirect_to user_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, notice: \"Pagealbum was successfully destroyed.\" }\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.xml { head :ok }\n end\n end",
"def destroy\n @album_owned = AlbumOwned.find(params[:id])\n @album_owned.destroy\n\n respond_to do |format|\n format.html { redirect_to album_owneds_url }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @album = Album.find(params[:id])\r\n @album.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to user_albums_path(session[:user_id]),:notice => \"Your Album has been successfully Deleted\" }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @albumfife.destroy\n respond_to do |format|\n format.html { redirect_to albumfives_url, notice: 'Albumfive was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @photo = Photo.find(params[:id])\n\t@album = Album.find(@photo.album_id)\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to album_path(@album) }\n format.json { head :ok }\n end\n end",
"def destroy\n @item_album.destroy\n respond_to do |format|\n format.html { redirect_to(:back) }\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.xml { head :ok }\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.xml { head :ok }\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.xml { head :ok }\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.xml { head :ok }\n end\n end",
"def destroy\n @album_item = AlbumItem.find(params[:id])\n @album_item.destroy\n\n respond_to do |format|\n format.html { redirect_to album_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\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 format.xml { head :no_content }\n end\n end",
"def destroy\n @genre.destroy\n respond_to do |format|\n format.html { redirect_to genres_url, notice: 'Genre was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album2photo = Album2photo.find(params[:id])\n @album2photo.destroy\n\n respond_to do |format|\n format.html { redirect_to album2photos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @sub_genre = SubGenre.find(params[:id])\n @sub_genre.destroy\n\n respond_to do |format|\n format.html { redirect_to sub_genres_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n alb=@photo.album\n @photo.destroy\n respond_to do |format|\n format.html { redirect_to alb, notice: 'Фотография успешно удалена.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @photo.destroy\n @album = @photo.album\n\n respond_to do |format|\n format.html { redirect_to @album, notice: \"写真を削除しました。\" }\n format.json { head :ok }\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(@album) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @album = Album.find(params[:id])\n @album.destroy\n redirect_to root_url\n end",
"def destroy\n @album = Album.find(params[:id])\n @album.destroy\n # Dir.chdir(\"public/images\")\n Dir.delete(@album['directory'])\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 @book_genre = BookGenre.find(params[:id])\n @book_genre.destroy\n\n respond_to do |format|\n format.html { redirect_to book_genres_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @genre = Genre.find(params[:id])\n @genre.destroy\n\n respond_to do |format|\n format.html { redirect_to(genres_url) }\n format.xml { head :ok }\n end\n end",
"def delete_album album_id\n delete(\"/albums/#{album_id}\", code: 204)\n end",
"def destroy\n @photo = Photo.find(params[:id])\n @album = @photo.album_id\n @photo.destroy\n respond_to do |format|\n format.html { redirect_to album_photos_path, notice: \"Photo was successfully destroyed.\" }\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 user_albums_path(@user) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @private_album_image.destroy\n respond_to do |format|\n format.html { redirect_to private_album_images_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album_photo.destroy\n respond_to do |format|\n format.html { redirect_to album_photos_url, notice: 'Album photo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_album\n @album = Album.find(params[:id])\n @album.destroy\n \n respond_to do |format|\n format.js\n end\n end",
"def destroy\n @foto_album = FotoAlbum.find(params[:id])\n @foto_album.destroy\n\n respond_to do |format|\n format.html { redirect_to(foto_albums_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @photo_album.destroy\n\n respond_to do |format|\n format.html { redirect_to(photo_albums_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @musical_genre.destroy\n respond_to do |format|\n format.html { redirect_to musical_genres_url, notice: 'Musical genre was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @picture = @album.pictures.find(params[:id]) #JRD111115\n @picture.destroy\n respond_to do |format|\n format.html { redirect_to album_pictures_url(@album), notice: 'Picture was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @genotype = Genotype.find(params[:id])\n @genotype.destroy\n\n respond_to do |format|\n format.html { redirect_to genotypes_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @grm_pic = GrmPic.find(params[:id])\n @grm_pic.destroy\n\n respond_to do |format|\n format.html { redirect_to grm_pics_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album_follow.destroy\n respond_to do |format|\n format.html { redirect_to album_follows_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @gallery.destroy\n respond_to do |format|\n format.html { redirect_to galleries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @gallery.destroy\n respond_to do |format|\n format.html { redirect_to galleries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album = current_account.albums.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to(albums_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @galleries_gallery.destroy\n respond_to do |format|\n format.html { redirect_to galleries_album_galleries_path(@galleries_album), notice: 'Gallery was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n respond_to do |format|\n if @album.destroy\n format.html { redirect_to artist_albums_url, notice: 'album was successfully destroyed.' }\n format.json { head :no_content }\n else\n format.html { render action: 'delete' }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @musica.audios.purge\n @musica.destroy\n respond_to do |format|\n format.html { redirect_to musicas_url, notice: 'Álbum apagado com sucesso!' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @photo_album = PhotoAlbum.find(params[:id])\n @photo_album.destroy\n\n respond_to do |format|\n format.html { redirect_to(photo_albums_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @subgenre.destroy\n respond_to do |format|\n format.html { redirect_to subgenres_url, notice: 'Subgenre was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album = Album.find(params[:id])\n \n album_path = ALBUMS_ROOT + @album.name\n if(File.exists?(album_path))\n FileUtils.remove_dir(album_path)\n end\n\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to(albums_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @admin_gallery.destroy\n respond_to do |format|\n format.html { redirect_to galleries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @gallery = Gallery.find(params[:id])\n @gallery.destroy\n respond_with(@gallery, :status => :deleted, :location => galleries_url)\n end",
"def destroy\n @interior_album.destroy\n respond_to do |format|\n format.html { redirect_to interior_albums_url, notice: 'Interior design album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @photo = Photo.find(params[:id])\n gallery = @photo.gallery\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to gallery_path(gallery) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album_information.destroy\n respond_to do |format|\n format.html { redirect_to album_informations_url, notice: 'Album information was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @genre_type = GenreType.find(params[:id])\n @genre_type.destroy\n\n respond_to do |format|\n format.html { redirect_to genre_types_url }\n format.json { head :no_content }\n end\n end",
"def delete()\n sql = \"DELETE FROM albums\n WHERE id = $1;\"\n values = [@id]\n SqlRunner.run( sql, values )\n end",
"def destroy\n # authorize\n authorize! :delete, @album\n @album.destroy\n \n render nothing:true\n flash[:notice] = 'Xóa album thành công.'\n end",
"def destroy\n @gen = Gen.find(params[:id])\n @gen.destroy\n\n respond_to do |format|\n format.html { redirect_to gens_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @song = Song.find(params[:id])\n #@song.remove_file_path!\n @song.destroy\n\n respond_to do |format|\n format.html { redirect_to songs_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @palbum = Palbum.find(params[:id])\n @palbum.destroy\n \n end",
"def destroy\n @genrecreate.destroy\n respond_to do |format|\n format.html { redirect_to genrecreates_url, notice: 'Genrecreate was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @genre = Genre.find(params[:id])\n @genre.destroy\n redirect_to genres_path\n end",
"def destroy\n @photo = @allbum.photos.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to allbum_photos_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @game_genre.destroy\n respond_to do |format|\n format.html { redirect_to game_genres_url, notice: 'Game genre was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @image_gallery = ImageGallery.find(params[:id])\n @image_gallery.destroy\n\n respond_to do |format|\n format.html { redirect_to image_galleries_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @gallery = Gallery.find(params[:id])\n @gallery.destroy\n respond_to do |format|\n format.html { redirect_to galleries_url, notice: 'Gallery was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album.destroy\n redirect_to albums_url, notice: 'Альбом успешно удалён.'\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.7127969",
"0.7123693",
"0.7110159",
"0.710699",
"0.7102042",
"0.70978814",
"0.7080313",
"0.7075107",
"0.70685923",
"0.7065805",
"0.70653856",
"0.70509446",
"0.7047738",
"0.7047238",
"0.7038412",
"0.7038412",
"0.7038412",
"0.7038412",
"0.70277333",
"0.7024768",
"0.70146155",
"0.7001839",
"0.6994271",
"0.6978213",
"0.6977254",
"0.6975983",
"0.69708157",
"0.69589376",
"0.694823",
"0.6939707",
"0.6938253",
"0.69357175",
"0.6932316",
"0.69241065",
"0.6918914",
"0.69051844",
"0.6896128",
"0.68906766",
"0.6883582",
"0.6880344",
"0.6877186",
"0.6876313",
"0.68740636",
"0.68723875",
"0.68723875",
"0.6860451",
"0.68549347",
"0.6840361",
"0.68322545",
"0.6810981",
"0.6808764",
"0.68033314",
"0.680223",
"0.67753714",
"0.67739975",
"0.67727226",
"0.6768485",
"0.67682713",
"0.67637813",
"0.6753519",
"0.6748392",
"0.6747896",
"0.67433155",
"0.67337203",
"0.6732992",
"0.6728993",
"0.67259955",
"0.67250425",
"0.6723469",
"0.6716294"
] | 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",
"def initialize(requirement_price:, discount:)\n\t\t@requirement_price = requirement_price\n\t\t@discount = discount\n\tend",
"def initialize\n @codigo =\n @total = 0\n @productos = []\n @fecha_creacion = Time.now\n @fecha_entrega = Faker::Date.forward(days: 2)\n @estado = \"preparando\"\n end",
"def initialize(amount, currency)\n set_amount(amount)\n set_currency(currency)\n end",
"def initialize(name, price, currency, shares)\n @name = name\n @price = price\n @currency = currency.upcase\n @shares = shares\n convert_curr\n shares_totals\n end",
"def initialize\n\tget_the_bill\n\tget_the_tip_percent\n\tget_the_num_people\nend",
"def initialize(discount=0)\n @total = 0\n @discount = discount\n @items = []\n @last_transaction = {}\n end",
"def initialize(name = \"\", price = 0, weight = 0)\n self.name = name\n self.price = price\n self.weight = weight\n @quantity = 0\n @description = \"\"\n @@ship_price_per_oz = 1.2\n end",
"def initialize(discount = nil)\n @total = 0 \n @discount = discount\n @items = []\n end",
"def initialize(discount = 0) # optional discount upon initialization\n @discount = discount\n @total = 0 # initialize total at 0\n @items = []\n end",
"def initialize\r\n ## The corrupt elite establishes a new government\r\n ## this is the commitment of the corrupt Elite - everything that can not be saved from a crash\r\n @profit_from_crash = msg.value ## type uint public\r\n @corrupt_elite = msg.sender ## type address public\r\n @last_time_of_new_credit = block.timestamp ## type uint public\r\n\r\n @creditor_addresses = [] ## type address[] public\r\n @creditor_amounts = [] ## type uint[] public\r\n @buddies = Mapping.of( Address => Money ) ## type mapping (address => uint) buddies\r\n\r\n @round = 0 ## type uint8 public\r\n @last_creditor_paid_out = 0 ## type uint32 public\r\n end",
"def initialize\n @money = STARTING_MONEY\n @grid = Grid.new(WIDTH, LENGTH)\n end",
"def initialize\n @gold = 1000\n @lumber = 500\n @food = 80\n @health_points = 500\n end",
"def initialize\n self.applied_discount = 0\n end",
"def setDefault\n self.monthlyCost ||= 0.0 # will set the default value only if it's nil\n self.annualCost ||= 0.0\n end",
"def initialize(company, symbol, price_per_share, currency, quantity)\n @company = company\n @symbol = symbol\n @price_per_share = price_per_share.to_i\n @currency = currency\n @quantity = quantity\n end",
"def initialize()\n\t\t@sum = 0 \n\tend",
"def initialize\n @base_price = 3\n @ingredients = [ ]\n end",
"def initialize(type, x, y)\n @x = x\n @y = y\n @type = type\n\n @cost = 0\n @g = 0\n @h = 0\n @f = 0\n end",
"def initialize(isbn2, price2) # It also eliminates 7 lines of code from the previous method above...\n @isbn2 = isbn2 # because we dont have to def isbn, and price.\n @price2 = Float(price2) # In this case, the two methods are simply returning the values of the two instance variables\n end",
"def initialize(params)\n\t\t@income = params[:income]\n\t\t@zipcode = params[:zipcode]\n\t\t@age = params[:age] \n\t\traise TypeError unless @income.is_a?(Numeric)\n\t\traise TypeError unless @:zipcode.is_a?(Numeric)\n\t\traise TypeError unless @:age.is_a?(Numeric)\n\t\t@base_url = params.fetch(:base_url, 'http://internal.leapfrogonline.com/customer_scoring')\n\tend",
"def initialize\n @balance = 0 # software won't be as pure with exposed balance\n @transactions = [] # object calisthenics? primitive obsession -> array is suspect, some sort of collection object\n # store as hash instead?\n end",
"def initialize\n @sheet1_b10 = 1.0\n @sheet1_b1 = 1000.0\n @sheet1_b5 = 5.0\n @sheet1_b8 = 0.1\n @sheet1_b4 = 0.5\n @sheet1_b3 = 20.0\n @sheet1_b7 = 1.0\n @sheet1_b2 = 100.0\n @sheet1_b6 = 10.0\n @sheet1_b12 = 1.0\n @sheet1_a20 = \"Discounted cost\"\n @sheet1_a21 = \"Discounted output\"\n end",
"def initialize()\n\t\t# @name = name\n\t\t# @price = price \n\tend",
"def initialize(make, model, year, color)\n @make = make\n @model = model\n @year = year\n @color = color\n @miles = 0\nend",
"def initialize(discount=0)\n @total = 0\n @discount = discount\n @all_items = []\n\n end",
"def initialize(end_date, data_amount)\n @end_date = end_date\n @data_amount = data_amount\n calculate_start_date\n end",
"def calculo \n self.minutos_reales = 5 * 480 #cantidad de OPERARIOS * Jornada de Trabajo(Turnos)\n self.costo_minuto = 89 #Costo Real por minuto\n self.otros_costos = 540 * 89 #Tiempo Total(Minutos) * Costo Real por Minutos\n self.costo_mano_obra = 420 * 5 * 89 # Jornada Minutos * Cantidad Operarios * Costo Real por minutos \n self.manoObraPlaneada = 650.000 * 5 # Salario Total * Cantidad de operarios \n end",
"def initialize(total, items, return_url, cancel_url) #options={}\n\t\tself.total = total\n\t\tself.items = items #productos\n\t\tself.return_url = return_url #options[:return_url]\n\t\tself.cancel_url = cancel_url #options[:cancel_url]\n\t\tself.payment = nil \n\t\t#{return_url: \"/checkout\", cancel_url: \"/carrito\", opcion: 2}\n\t\t#options.each {|clave, valor| instance_variable_set(\"@#{clave}\", valor)}\n\tend",
"def initialize(make, model, make_year, origin_price)\n @make = make\n @model = model\n @make_year = make_year\n @origin_price = origin_price\n @current_value = current_value\n @dealer_price = current_value + dealer_markup\n end",
"def initialize(feeds, manager)\n @feeds = feeds\n @manager = manager\n @base_symbol = nil\n @spread = {}\n @opt_param = []\n \n @total_trades = 0\n @win_trades = 0\n @lose_trades = 0\n @maximum_profit = 0\n @profit = 0\n @drawdown = 0\n end",
"def initialize(discount = 0)\n @total = 0\n @discount = discount\n @items = []\n end",
"def initialize(discount = 0)\n @total = 0\n @discount = discount\n @items = []\n end",
"def initialize(args)\n @old_loan_amount = args[:old_loan_amount].to_f\n @periods = args[:periods].to_f\n @new_interest_rate = args[:new_interest_rate].to_f / 12\n @new_interest_rate_cash_out = args[:new_interest_rate_cash_out] / 12\n @lender_credit = args[:lender_credit].to_f\n @lender_credit_cashout = args[:lender_credit_cashout].to_f\n @estimated_closing_costs = args[:estimated_closing_costs].to_f\n @estimated_closing_costs_cash_out = args[:estimated_closing_costs_cash_out].to_f\n @current_home_value = args[:current_home_value].to_f\n @original_loan_date = args[:original_loan_date]\n @old_interest_rate = args[:old_interest_rate] / 12\n @start_due_date = (Time.zone.now + 2.months).beginning_of_month\n end",
"def initialize(hash)\n hash.each do |key, value|\n attribute = ATTRIBUTE_MAP[key.to_s]\n send(\"#{attribute}=\", value) if (attribute && respond_to?(attribute))\n end\n make_prices_negative if pricing.downcase == 'variable'\n end",
"def initialize(price_per_unit, discount_price_per_unit, bulk_minimum_units)\n @price_per_unit = price_per_unit\n @discount_price_per_unit = discount_price_per_unit\n @bulk_minimum_units = bulk_minimum_units\n end",
"def initialize(nodes_v, nodes_s)\n @nodes_v = nodes_v\n @nodes_s = nodes_s\n @cost = nil\n end",
"def initialize(saldo)\n self.saldo = saldo\n end",
"def initialize price, time_limit\n self.time_limit = time_limit\n self.price = price \n end",
"def initialize(name, price) #function to initialize variables.\n @name = name\n @price = price\n end",
"def initialize(price, title)\n @price = price\n @title = title\n end",
"def initialize(hash = {})\n hash.delete_if { |k, v| v.nil? }\n hash = defaults.merge(hash)\n\n @category = hash[:category]\n @item_name = hash[:item_name]\n @unit_cost = hash[:unit_cost]\n @cost_units = hash[:cost_units]\n @item_quantity = hash[:item_quantity]\n @total_cost = hash[:total_cost]\n\n # initialize class variables @@validator and @@schema\n @@validator ||= Validator.new\n @@schema ||= @@validator.schema\n end",
"def initialize(factor, type, product_code, discount)\n @offer_factor = factor\n @offer_type = type\n @product_code = product_code\n @offer_discount = discount\n end",
"def calculate_costs\n self.amount = self.transaction.shipping_cost + self.transaction.value\n self.shipping_cost = self.transaction.shipping_cost\n self.commission_rate = self.buyer.account.commission_rate || SiteVariable.get(\"global_commission_rate\").to_f # Calculate commission rate, if neither exist commission is set to 0\n self.commission = Money.new((commission_rate * self.transaction.value.cents).ceil) # Calculate commision as commission_rate * item value (without shipping), round up to nearest cent\n end",
"def initialize\r\n ## The corrupt elite establishes a new government\r\n ## this is the commitment of the corrupt Elite - everything that can not be saved from a crash\r\n @profit_from_crash = msg.value ## type uint public\r\n @corrupt_elite = msg.sender ## type address public\r\n @last_time_of_new_credit = block.timestamp ## type uint public\r\n\r\n @creditor_addresses = [] ## type address[] public\r\n @creditor_amounts = [] ## type uint[] public\r\n @buddies = Hash.new(0) ## type mapping (address => uint) buddies\r\n\r\n @round = 0 ## type uint8 public\r\n @last_creditor_paid_out = 0 ## type uint32 public\r\n\r\n @balance = 0 ## keep track of contract balance \"by hand\" for now (todo/fix: make it \"automatic/builtin\")\r\n end",
"def initialize\n # Call function to generate the account number\n account_number_gen\n # Initialize instance variables\n @checking_account_balance = 0\n @saving_account_balance = 0\n @@total_accounts += 1\n @interest_rate = 0.01\n end",
"def initialize(stap=5,aantal=34)\n @stap = stap\n @monte_carlos = []\n aantal.times do |x|\n van = x*stap\n tot = (x+1)*stap-1\n @monte_carlos[tot] = MonteCarlo.from_db(van,tot)\n end\n end",
"def initialize\n @gold = 1000\n @food = 80\n @health_points = 500\n end",
"def set_secured_constants\n @pur_balance = 500.0 #revolving purchase balance\n @cash_balance = 0.0 #cash balance balance\n @duration = 8.0 #number of months someone keeps the secured car, ad decimal so not integer \n end",
"def initialize(title, amount)\n @title = title\n @amount = amount\n end",
"def initialize(items, total_price, total_sales_tax)\n @items = items\n @total_price = '%.2f' % total_price\n @total_sales_tax = '%.2f' % total_sales_tax\n end",
"def initialize(name, ordered, retail_price, cost_of_sale)\r\n @name = name # String. The name of the drink type, e.g. \"Beers\".\r\n @ordered = ordered # Integer. The number of orders pending for this drink.\r\n @retail_price = retail_price # Numeric. What the customer pays for the drink.\r\n @cost_of_sale = cost_of_sale # Numeric. What it costs the business to sell this drink.\r\n end",
"def initialize(isbn, price)\n #Instance variables start with @\n @isbn = isbn\n @price = Float(price)\n end",
"def revenue\n end",
"def initialize(d, n, a, t)\n\n @date = d.to_s #storing data as string\n @payee = n.to_s #storing payee as string\n @amount = a.to_f #storing amount as float\n @type = t.to_c #storing type as char\n @currBalance = 0.0 #setting current balance as zero just to initilize as float\n\n end",
"def initialize(table, *profit) # metodo de clase\n @table = table\n @profit = profit.map(&:to_i)\n end",
"def initialize prev_data=nil\n @totals = {}\n @results = {}\n end",
"def initialize(buyer, price, amount)\n @buyer = buyer\n @bid_price = price\n @desired_amount = amount\n @bought_amount = 0\n end",
"def initialize(meal_cost:, group:, tip_percentage: 0.18)\n @meal_cost = meal_cost.to_f\n @group = group.to_f\n self.get_tip_amount(tip_percentage, meal_cost)\n end",
"def initialize(discount = nil)\n @total = 0\n if discount != nil\n @discount = discount\n end\n\n @items = []\n\n end",
"def initialize (amount, currency)\n\n #Amount is stored in BigDecimal for better precision in currency operations\n @amount_bigdecimal = BigDecimal.new(amount,0)\n\n @currency = currency\n\n end",
"def initialize(outlets:, total_items_quantity:, beverages:)\n self.outlets = outlets\n self.total_items_quantity = total_items_quantity\n self.beverages = beverages\n self.beverage_log = []\n self.items_running_low = {}\n self.beverage_failure_reason = {}\n end",
"def initialize(cents, currency = nil, bank = nil)\n @cents = cents.to_i\n @currency = (currency || Money.default_currency).upcase\n @bank = bank || Money.default_bank\n end",
"def initialize(principal, *rates, &block)\n @principal = principal.to_d\n @rates = rates\n @block = block\n \n # compute the total duration from all of the rates.\n @periods = (rates.collect { |r| r.duration }).sum\n @period = 0\n\n compute\n end",
"def initialize(hash, cancellation_factor, sale_amount_factor)\n @hash = hash\n @cancellation_factor = cancellation_factor\n @sale_amount_factor = sale_amount_factor\n end",
"def initialize(args=nil)\n @unit_of_measure = \"PCS\"\n @vat_rate = 0\n @vat_included = true\n return if args.nil?\n args.each do |k,v|\n instance_variable_set(\"@#{k}\", v) unless v.nil?\n end\n end",
"def initialize(name, price, alcohol_content)\n @name = name\n @price = price\n @abv = alcohol_content\nend",
"def initialize(name, years, restaurant)\n @name = name\n @years = years\n @restaurant = restaurant\n end",
"def initialize(items, total, return_url, cancel_url, options={})\n self.items = items\n self.total = total\n self.return_url = return_url\n self.cancel_url = cancel_url\n options.each {|clave,valor| instance_variable_set(\"@#{clave}\",valor)}\n end",
"def initialize(details, quantity = nil)\n @quantity = quantity || details.max_quantity\n @item_id = details.item_id\n @item_type = details.item_type\n @sale_value = 0\n @sell_locked = details.sell_locked || false\n @replenishment_rate = details.repl_rate\n @rpg_article = details\n end",
"def initialize (banco, numero_cuenta, saldo_cuenta = 0)\n @banco = banco\n @numero_cuenta = numero_cuenta\n @saldo_cuenta = saldo_cuenta\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.61994565",
"0.6193303",
"0.6190612",
"0.6178824",
"0.617875",
"0.61727846",
"0.6171335",
"0.61467403",
"0.61458063",
"0.61456215",
"0.6142722",
"0.6128468",
"0.6125855",
"0.6119814",
"0.6119171",
"0.61177355",
"0.6106364",
"0.6096059",
"0.60935646",
"0.609189",
"0.6086866",
"0.6085652",
"0.60783356",
"0.6078111",
"0.6076346",
"0.60737735",
"0.60708976",
"0.60697794",
"0.60684884",
"0.60639024",
"0.6060739",
"0.6060739",
"0.6056238",
"0.605576",
"0.60548526",
"0.6048008",
"0.6047581",
"0.6045962",
"0.60362065",
"0.603578",
"0.6035486",
"0.60302436",
"0.60257924",
"0.6023024",
"0.60186553",
"0.6014509",
"0.6009154",
"0.60075545",
"0.60040915",
"0.60010064",
"0.6000968",
"0.59936845",
"0.5993493",
"0.5988549",
"0.59866595",
"0.5980672",
"0.5967274",
"0.59662014",
"0.5962226",
"0.59621644",
"0.5961401",
"0.59545153",
"0.59479207",
"0.59450084",
"0.59406424",
"0.5938495",
"0.593543",
"0.5923574",
"0.59212804",
"0.59206605"
] | 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",
"def cc_purchase (person, cc_number, amount)\r\n\t\tif @bank_listing[person.id_number][:cc_spent] < @bank_listing[person.id_number][:cc_limit] && cc_number == @bank_listing[person.id_number][:cc_number]\r\n\t\t\t@bank_listing[person.id_number][:cc_spent]+=amount\r\n\t\t\tputs \"#{@bank_name}: Card accepted.\"\r\n\t\telse\r\n\t\t\tputs \"#{@bank_name}: Card has been declined.\"\r\n\t\tend\r\n\tend",
"def credit(money, credit_card, options = {})\n standard_response\n end",
"def credit(amount, payment_method, options = {})\n post = {}\n add_invoice(post, amount, options)\n add_order_number(post, options)\n add_payment_method(post, payment_method)\n add_customer_data(post, options)\n add_soft_descriptors(post, options)\n add_customer_reference(post, options)\n\n commit('refund', post)\n end",
"def credit(transaction_id, amount)\n params = {\n transaction_amount: amount,\n transaction_id: transaction_id,\n operation: 'CREDIT'\n }\n\n process_response params\n end",
"def create_credit(order)\n credit = order.promotion_credits.build({\n :adjustment_source_id => self.id,\n :adjustment_source_type => self.class.name,\n :description => I18n.t(name)\n })\n credit\n end",
"def ventas_comprobantecredito_subtotal(*args)\n entry,referencia = args\n \n entry.details.build do |dt|\n dt.account_id = referencia.account_id \n dt.description = __method__.to_s.humanize + ' rc' + self.numero.to_s\n\n dt.credit = referencia.debita? ? 0 : self.importe\n dt.debit = referencia.debita? ? self.importe : 0 \n end\n end",
"def credit(money, authorization, options = {})\r\n request = RocketGate::GatewayRequest.new\r\n response = RocketGate::GatewayResponse.new\r\n service = RocketGate::GatewayService.new\r\n if test? # Test transaction?\r\n service.SetTestMode(true) # Set internal test mode\r\n end\r\n\r\n#\r\n#\tAdd the details of the transaction to the request.\r\n#\r\n add_merchant_data(request, options) # Add merchant information\r\n add_financial_data(request, money, options)\r\n request.Set(RocketGate::GatewayRequest::TRANSACT_ID, authorization)\r\n request.Set(RocketGate::GatewayRequest::IPADDRESS, options[:ip])\r\n\r\n#\r\n#\tPeform the transaction and return a response.\r\n#\r\n service.PerformCredit(request, response)\r\n return create_response(response)\r\n end",
"def credit(money_cents, _source, response_code, _gateway_options)\n protected_request do\n result = braintree.transaction.refund(\n response_code,\n dollars(money_cents)\n )\n Response.build(result)\n end\n end",
"def credit= value\n #if prepaid?\n # raise \"Cannot set credit for prepaid user\"\n if User.current and User.current.currency\n c = value == -1 ? -1 : (value.to_d / User.current.currency.exchange_rate.to_d).to_d\n else\n c = value\n end\n write_attribute(:credit, c)\n end",
"def credit_params\n @credit_params ||= params.require(:credit).permit(\n :amount, :amount_in_cents\n ).to_h\n end",
"def add_trivia(amount)\n if amount < 10\n @credits = @credits + amount * 2\n else\n @credits = @credits + 20\n end\n end",
"def expect_credit\n expect(balanced_account).to receive(:credit).\n with(amount: 4242,\n appears_on_statement_as: market.on_statement_as,\n description: description).\n and_return(credit)\n expect(payment).to receive(:update_column).with(:balanced_uri, credit.uri).and_return(payment)\n end",
"def pay_amount(user, amount)\r\n if(self.credits>= amount)\r\n self.credits= self.credits-amount\r\n user.receive_credits(amount)\r\n else\r\n return 'suddenly you dont have enough money'\r\n end\r\n end",
"def withdraw amount, month, day\n raise ArgumentError, 'Insufficient credit!' if amount + @balance > MAX_CREDIT\n # create transaction entry\n @transactions[month] << Line.new(day, month, amount)\n @balance += amount\n end",
"def add_credit_card\n\n get_balanced_key\n card_uri = params[:card_uri]\n\n company_name = \"Mindfire Solutions\"\n customer = Balanced::Customer.new({name: company_name}).save\n customer_uri = customer.href\n get_customer = Balanced::Customer.fetch(customer_uri)\n card = Balanced::Card.fetch(card_uri)\n card.associate_to_customer(customer_uri)\n \n\n amount_in_dollars = params[:amount].to_i\n #amount_in_dollars * 100 convert into cents\n\n debit = card.debit(:amount => amount_in_dollars * 100, appears_on_statement_as: \"Debit Amount\")\n \n ##You can save the response in your db for future use\n #debit.transaction_number\n #debit.amount\n #debit.statusdebit.created_at\n \n #get the balanced market place\n marketplace = Balanced::Marketplace.my_marketplace\n \n credit = get_marketplace_bank_account.credit(:amount => debit.amount, appears_on_statement_as: \"Credit Amount\")\n\n\n return render json: {success: [\"Debit Transaction:: #{debit.attributes}\", \"Credit Transaction:: #{credit.attributes}\"] }\n\n end",
"def capture amount=nil, appears_on_statement_as=nil, meta={}, description=nil\n amount ||= self.amount\n self.account.debit(amount, appears_on_statement_as, self.uri, meta, description)\n end",
"def credit_params\n params.require(:credit).permit(:amount, :content, :created_user_id, :credit, :completed)\n end",
"def console_add_money(amount)\n credits.create!(amount: amount, note: \"Admin added #{amount} cents\")\n end",
"def fCreditCoinsTo (email, amount)\n @users.creditCoinsTo(email,amount)\n end",
"def credit_account\n if @invoice.amount\n result = @invoice.bank_account.credit_account(seller_amount) rescue false\n else\n false\n end\n end",
"def purchase(money, _, options={})\n requires!(options, :collectdate, :customeraccountname, :customerbic, :customeriban, :description, :invoicenumber, :mandatedate, :mandatereference)\n buckaroo_validate(money, options)\n\n mandatereference = options[:mandatereference]\n mandatereference = \"#{@options[:sepa_mandate_prefix]}-#{mandatereference}\" if @options[:sepa_mandate_prefix]\n\n post_params = {\n brq_amount: money,\n brq_channel: \"CALLCENTER\",\n brq_culture: options[:culture] ? options[:culture] : \"EN\",\n brq_currency: options[:currency] ? options[:currency] : \"EUR\",\n brq_description: options[:description],\n brq_invoicenumber: options[:invoicenumber],\n brq_payment_method: \"simplesepadirectdebit\",\n brq_service_simplesepadirectdebit_action: \"Pay\",\n brq_service_simplesepadirectdebit_collectdate: options[:collectdate].strftime(\"%Y-%m-%d\"),\n brq_service_simplesepadirectdebit_customeraccountname: options[:customeraccountname],\n brq_service_simplesepadirectdebit_customerbic: options[:customerbic],\n brq_service_simplesepadirectdebit_customeriban: options[:customeriban],\n brq_service_simplesepadirectdebit_mandatedate: options[:mandatedate].strftime(\"%Y-%m-%d\"),\n brq_service_simplesepadirectdebit_mandatereference: mandatereference,\n brq_startrecurrent: true,\n brq_websitekey: @options[:websitekey]\n }.merge(options.select {|k, *| k.to_s.start_with?(\"add_\") })\n\n BuckarooBPE3Toolbox.call(\"TransactionRequest\", post_params, @options[:secretkey], true)\n end",
"def admin_credit_params\n params.require(:credit).permit(:sum, :period, :status)\n end",
"def take(who)\n raise ArgumentError, 'Вызываю полицию' unless who == 'Bank'\n @cash = Money.new(0)\n \"Проведена инкассация\"\n end",
"def create_revenue_transfers\n # the share for invested readers before\n amount = total * READER_RATIO\n\n # payment maybe swapped\n revenue_asset_id = payment.swap_order&.fill_asset_id || payment.asset_id\n\n # the present orders\n _orders =\n item.orders\n .where('id < ? and created_at < ?', id, created_at)\n\n # total investment\n sum = _orders.sum(:total)\n\n # create reader transfer\n _distributed_amount = 0\n _orders.each do |_order|\n # ignore if amount is less than minium amout for Mixin Network\n _amount = (amount * _order.total / sum).round(8)\n next if (_amount - MINIMUM_AMOUNT).negative?\n\n transfers.create_with(\n wallet: payment.wallet,\n transfer_type: :reader_revenue,\n opponent_id: _order.buyer.mixin_uuid,\n asset_id: revenue_asset_id,\n amount: _amount.to_f.to_s,\n memo: \"读者收益来自文章《#{item.title}》\".truncate(140)\n ).find_or_create_by!(\n trace_id: PrsdiggBot.api.unique_conversation_id(trace_id, _order.trace_id)\n )\n\n _distributed_amount += _amount\n end\n\n # create prsdigg transfer\n _prsdigg_amount = (total * PRSDIGG_RATIO).round(8)\n if payment.wallet.present?\n transfers.create_with(\n wallet: payment.wallet,\n transfer_type: :prsdigg_revenue,\n opponent_id: PrsdiggBot.api.client_id,\n asset_id: revenue_asset_id,\n amount: _prsdigg_amount.to_f.to_s,\n memo: \"article uuid: #{item.uuid}》\".truncate(140)\n ).find_or_create_by!(\n trace_id: payment.wallet.mixin_api.unique_conversation_id(trace_id, PrsdiggBot.api.client_id)\n )\n end\n\n # create author transfer\n transfers.create_with(\n wallet: payment.wallet,\n transfer_type: :author_revenue,\n opponent_id: item.author.mixin_uuid,\n asset_id: revenue_asset_id,\n amount: (total - _distributed_amount - _prsdigg_amount).round(8),\n memo: \"#{payment.payer.name} #{buy_article? ? '购买' : '赞赏'}了你的文章《#{item.title}》\".truncate(140)\n ).find_or_create_by!(\n trace_id: PrsdiggBot.api.unique_conversation_id(trace_id, item.author.mixin_uuid)\n )\n end",
"def reward\n business.add_to_balance(amount)\n end",
"def chargecredit\n @user = User.find_by_username(params[0][:username])\n user=User.authenticate(params[0][:username],params[0][:password])\n if user\n\t# make sure we charge at least 1 credit \n\tif params[0][:module_cost] < 1 \n\t params[0][:module_cost] = 1\n\tend\n @user.credits -= params[0][:module_cost]\n if @user.save\n render :amf => { :id => \t@user.id,\n\t\t\t:firstname => \t@user.firstname, \n\t\t\t:lastname => \t@user.lastname, \n\t\t\t:credits => \t@user.credits, \n\t\t\t:company => \t@user.company\n\t\t}\n\t @userhistory=UserHistory.new\n\t @userhistory.userid\t\t\t=user.id\n\t @userhistory.module\t\t\t=params[0][:module]\n\t @userhistory.credits_spent\t\t=params[0][:module_cost]\n\t @userhistory.credits_remaining\t=@user.credits\n\t @userhistory.save\t\n else\n\t render :amf => \"Not enough credits to complete transaction\"\n\tend\n else\n render :amf => \"Login Failed\"\n end\n end",
"def build_credit_request(transaction_type, money, transaction_id, card)\n build_xml_request(transaction_type, transaction_id) do |xml|\n add_credit_card(xml, card) if card\n xml.tag! 'TotalAmount', amount(money)\n\n xml.target!\n end\n end",
"def creditCoins(amount)\r\n @betESSCoins += amount\r\n end",
"def credit_params\n params.require(:credit).permit(:date, :name, :cost, :status, :product_name, :product_num)\n end",
"def initialize_account\n self.credits = 0\n end",
"def rob(cash)\n\nend",
"def charge_renter(rental)\n # make debit operation on balanced\n balanced.debit(rental)\n\n # account it on subledger\n subledger.debit(rental)\n end",
"def cashRegister(price, cash)\n\nend",
"def use_budget(cost_line)\n bud = budget\n case cost_line.funding_source\n when 'Costo de actividades'\n bud.activities_cost_used += cost_line.real_amount\n when 'Reserva de actividades'\n bud.activities_reserve_used += cost_line.real_amount\n when 'Reserva de contingencias'\n bud.contingency_reserve_used += cost_line.real_amount\n when 'Reserva de gestión'\n bud.managment_reserve_used += cost_line.real_amount\n end\n bud.save \n end",
"def test_purchase_and_non_referenced_credit\n assert credit = @gateway.credit(100, @credit_card, @options)\n assert_success credit\n end",
"def set_credit\n @credit = Credit.find(params[:id])\n end",
"def credit(money, creditcard_or_credit_card_id, options = {})\n post = {}\n add_address(post, options)\n add_custom(post, options)\n add_invoice(post, options)\n add_payment_source(post, creditcard_or_credit_card_id, options)\n\n commit(post[:userprofileid] ? :profile_credit : :ns_credit, money, post)\n end",
"def set_credit\r\n @credit = Credit.find(params[:id])\r\n end",
"def credit(amount, options = {})\n transaction do\n begin\n Transaction.credit(self, amount, options)\n self.balance += amount\n rescue ActiveRecord::StatementInvalid\n self.balance -= amount\n end\n end\n self.save!\n self.balance\n end",
"def set_credit\n @credit = Credit.find(params[:id])\n end",
"def credit(transaction_id, amount)\n params = {\n :query => {\n :amount => amount,\n :transactionId => transaction_id,\n :operation => \"CREDIT\"\n }\n }\n\n Responses::CreditResponse.new(self.class.get(\"/Netaxept/Process.aspx\", params).parsed_response)\n end",
"def set_credit\n @credit = Credit.find(params[:id])\n end",
"def add_club_cash(agent, amount = 0, description = nil, set_expire_date = false)\n answer = { code: Settings.error_codes.club_cash_transaction_not_successful, message: \"Could not save club cash transaction\" }\n begin\n if not club.allow_club_cash_transaction?\n answer = { message: I18n.t(\"error_messages.club_cash_not_supported\"), code: Settings.error_codes.club_does_not_support_club_cash }\n elsif amount.to_f == 0\n answer[:message] = I18n.t(\"error_messages.club_cash_transaction_invalid_amount\")\n answer[:errors] = { amount: \"Invalid amount\" } \n elsif !is_drupal?\n ClubCashTransaction.transaction do\n begin\n if (amount.to_f < 0 and amount.to_f.abs <= self.club_cash_amount) or amount.to_f > 0\n cct = ClubCashTransaction.new(amount: amount, description: description)\n self.club_cash_transactions << cct\n raise \"Could not save club cash transaction\" unless cct.valid? and self.valid?\n self.club_cash_amount = self.club_cash_amount + amount.to_f\n self.club_cash_expire_date = Time.current.to_date + 1.year if set_expire_date\n self.save(validate: false)\n message = \"#{cct.amount.to_f.abs} club cash was successfully #{ amount.to_f >= 0 ? 'added' : 'deducted' }.\"+(description.blank? ? '' : \" Concept: #{description}\")\n if amount.to_f > 0\n Auditory.audit(agent, cct, message, self, Settings.operation_types.add_club_cash)\n elsif amount.to_f < 0 and amount.to_f.abs == club_cash_amount \n Auditory.audit(agent, cct, message, self, Settings.operation_types.reset_club_cash)\n elsif amount.to_f < 0 \n Auditory.audit(agent, cct, message, self, Settings.operation_types.deducted_club_cash)\n end\n answer = { message: message, code: Settings.error_codes.success }\n else\n answer[:message] = \"You can not deduct #{amount.to_f.abs} because the user only has #{self.club_cash_amount} club cash.\"\n answer[:errors] = { amount: \"Club cash amount is greater that user's actual club cash.\" }\n end\n rescue Exception => e\n answer[:errors] = cct.errors_merged(self) unless cct.nil?\n Auditory.report_issue('Club cash Transaction', e, { answer_message: answer[:message], user: self.id, amount: amount, description: description, club_cash_transaction: cct.try(:id) })\n answer[:message] = I18n.t('error_messages.airbrake_error_message')\n raise ActiveRecord::Rollback\n end\n end\n elsif not api_id.nil?\n Drupal::UserPoints.new(self).create!({amount: amount, description: description})\n message = last_sync_error || \"Club cash processed at drupal correctly. Amount: #{amount}. Concept: #{description}\"\n auditory_code = Settings.operation_types.remote_club_cash_transaction_failed\n if self.last_sync_error.nil?\n auditory_code = Settings.operation_types.remote_club_cash_transaction\n answer = { message: message, code: Settings.error_codes.success }\n else\n answer = { message: last_sync_error, code: Settings.error_codes.club_cash_transaction_not_successful }\n end\n answer[:message] = I18n.t('error_messages.drupal_error_sync') if message.blank?\n Auditory.audit(agent, self, answer[:message], self, auditory_code)\n end\n rescue Exception => e\n Auditory.report_issue('Club cash Transaction', e, { answer_message: answer[:message], user: self.id, amount: amount, description: description })\n answer[:message] = I18n.t('error_messages.airbrake_error_message')\n answer[:errors] = { amount: \"There has been an error while adding club cash amont.\" }\n end\n answer\n end",
"def purchase(money, creditcard, options = {})\n post = {}\n add_invoice(post, options)\n add_creditcard(post, creditcard)\n add_address(post, options)\n add_customer_data(post, options)\n add_duplicate_window(post)\n\n commit('AUTH_CAPTURE', money, post)\n end",
"def credit_params\r\n params.require(:credit).permit(:nro_tarjeta, :cuentum_id, :personal_id, :estado)\r\n end",
"def revenue_account_for_journal\n revenue_account\n end",
"def credit(money, creditcard_or_reference, options = {})\n setup_address_hash(options)\n commit(build_credit_request(money, creditcard_or_reference, options), :credit, money, options)\n end",
"def initialize(turn, amount, corporate_bonus)\n super(turn)\n @amount = amount\n @corporate_bonus = corporate_bonus\n end",
"def create\n respond_with client, @_resource = CreditContractService.new.create(client, credit_contract_params)\n end",
"def new_credit_card\n # populate new card with some saved values\n ActiveMerchant::Billing::CreditCard.new(\n :first_name => user.first_name,\n :last_name => user.last_name,\n # :address etc too if we have it\n :brand => cc_type\n )\n end",
"def create\n\n params[:account_receivable][:credit] = params[:account_receivable][:credit].gsub(\",\",\"\")\n params[:account_receivable][:debit] = params[:account_receivable][:debit].gsub(\",\",\"\")\n p params[:account_receivable][:credit]\n parent = AccountReceivable.find(params[:account_receivable][:parent_id]) if params[:account_receivable][:parent_id]\n @account_receivables = AccountReceivable.where(parent_id: parent.id) if params[:account_receivable][:parent_id]\n @debit = params[:debit].eql?(\"true\") ? true : false\n @account_receivable = AccountReceivable.new(params[:account_receivable])\n\n @sisa = parent.credit.to_i - @account_receivables.sum(&:debit).to_i if params[:account_receivable][:parent_id]\n\n\n\n if params[:account_receivable][:parent_id] and params[:account_receivable][:debit].to_i > @sisa.to_i\n flash.now[:error] = \"Debit lebih besar dari credit.!\"\n render action: \"new\", :credit => true\n else\n respond_to do |format|\n if @account_receivable.save\n\n format.html { redirect_to account_receivable_path(@account_receivable.parent ? @account_receivable.parent : @account_receivable), notice: 'Account receivable was successfully created.' }\n format.json { render json: @account_receivable, status: :created, location: @account_receivable }\n else\n format.html { render action: \"new\" }\n format.json { render json: @account_receivable.errors, status: :unprocessable_entity }\n end\n end\n end\n end",
"def charge(type, amount, opts = {}) # roster_id, contest_id, invitation_id, referred_id\n case type.to_sym\n when :balance\n self.customer_object.decrease_account_balance(amount, opts)\n when :monthly_entry\n self.customer_object.increase_monthly_contest_entries!(amount, opts)\n when :monthly_winnings\n self.customer_object.decrease_monthly_winnings(amount, opts)\n else\n raise \"Type must be one of [balance, monthly_entry, monthly_winnings]\" unless [:balance, :monthly_entry, :monthly_winnings].include?(type.to_sym)\n end\n end",
"def donate_credit\n @donation_credit = DonationCredit.new(donation_credit_params)\n @sender = User.find(@donation_credit.user_id)\n @donation_credit.pot = @pot\n @donation_credit.user = @sender\n @pot.credits_collected = @pot.credits_collected + @donation_credit.quantity\n\n respond_to do |format|\n if @donation_credit.save && @pot.save\n format.json\n else\n format.json { render json: @donation_credit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def credit(money, identification, options = {})\n body = credentials\n body[:ssl_transaction_type] = :ccreturn\n\n body[:ssl_amount] = (money.to_money/100.0).to_s\n body[:ssl_txn_id] = identification\n\n body_text = xmlize({:txn => body})\n\n logger.error 'REQUEST: ' + body_text\n response = RestClient.post(url, body_text) {|response, request, result| response }\n logger.error 'RESPONSE: ' + response\n\n doc = JSON.parse(Hash.from_xml(response).to_json,:symbolize_names=>true)[:txn]\n\n #logger.error body_text\n #logger.error response.to_s\n\n return request_failed_response(doc) if request_failed?(doc)\n\n ActiveMerchant::Billing::Response.new(\n doc[:ssl_result].to_s == '0',\n doc[:ssl_result_message], {},\n :authorization => doc[:ssl_txn_id],\n :request => body_text,\n :response => doc.to_json)\n end",
"def pay_with_credits\n @reservation = current_user.reservations.new(params[:reservation])\n\n respond_to do |format|\n if @reservation.save\n current_user.update_attributes(credits: current_user.credits-@reservation.meal.price)\n format.html { redirect_to @reservation, notice: 'Reservation was successfully created.' }\n format.json { render \"reservations/show\", success: true, status: :created, location: @reservation }\n else\n format.html {\n @menu_items = MenuItem.of_the_next_seven_days.includes(:restaurant)\n @restaurants = @menu_items.collect { |menu_item| menu_item.restaurant }\n render action: \"new\"\n }\n format.json {\n render json: @reservation.errors, status: :unprocessable_entity\n }\n end\n end\n end",
"def initialize(balance, account_holder_name)\n @interest_rate = 1.00001\n @balance = balance\n @account_holder_name = account_holder_name\n end",
"def initialize(amount, currency)\n set_amount(amount)\n set_currency(currency)\n end",
"def create\n @buy = Buy.new(buy_params)\n @tarjetas= Card.all\n @numero= @buy.numero_de_tarjeta \n #@tarjeta=@tarjetas.first\n @tarjeta = @tarjetas.find_by(numero: @numero)\n @precio_total= @buy.cantidad * 50\n unless @tarjeta.nil?\n if @tarjeta.credito >= @precio_total\n @buy.precio_actual=50\n @buy.precio_total=@precio_total\n @tarjeta.credito= @tarjeta.credito - @precio_total \n \n @buy.user_id=current_user.id\n current_user.creditos=current_user.creditos + @buy.cantidad\n \n respond_to do |format|\n if @buy.save and current_user.save and @tarjeta.save\n format.html { redirect_to @buy, notice: 'Se ha realizado la compra con éxito.' }\n format.json { render :show, status: :created, location: @buy }\n else\n format.html { render :new }\n format.json { render json: @buy.errors, status: :unprocessable_entity }\n end\n end\n else\n respond_to do |format|\n format.html { redirect_to '/buys/new', notice: 'Crédito insuficiente.' }\n end\n end\n else\n respond_to do |format|\n format.html { redirect_to '/buys/new', notice: 'Tarjeta invalida.' }\n end\n end\nend",
"def credit! amount, options\n if hpp_payment? || adyen_cc_payment?\n process { payment_method.credit(amount, response_code, options) }\n else\n fail NotImplementedError, \"Spree::Payment does not implement credit!\"\n end\n end",
"def credit! amount, options\n if hpp_payment? || adyen_cc_payment?\n process { payment_method.credit(amount, response_code, options) }\n else\n fail NotImplementedError, \"Spree::Payment does not implement credit!\"\n end\n end",
"def charge_credit_invoice\n @invoice = Invoice.find(params[:id])\n Stripe.api_key = \"\"\n total_invoice_stripe = Money.new(@invoice.total_due, \"USD\")\n \n charge = Stripe::Charge.create(\n :amount => total_invoice_stripe.cents,\n :currency => \"usd\",\n :card => params[:invoice][:stripe_card_token],\n :description => @invoice.invoice_number\n )\n \n @invoice.stripe_card_token = charge.id\n if(@invoice.save!)\n @invoice.payment_received = true\n @invoice.save!\n redirect_to invoice_path(@invoice.id)\n else\n redirect_to root_path\n end\n end",
"def fDebitCoinsFrom (email, amount)\n @users.debitCoinsFrom(email, amount)\n end",
"def payment\n {\n :credit_card => credit_card\n }\n end",
"def test_purchase_and_credit_for_check_with_differing_amounts\n assert purchase = @gateway.purchase(10000, @check, @options)\n assert_success purchase\n assert_approved purchase\n \n assert void = @gateway.credit(500, purchase.authorization, @options)\n assert_success void\n assert_not_equal 'Approved', void.message\n end",
"def test_credit \n bob = customers(:bob)\n # Base state, nothing\n assert_equal(0.0, bob.credit)\n assert_nil(bob.account_credit)\n\n # subtract account credit from zero: doesn't count, doesn't throw\n bob.subtract_account_credit(0.0)\n assert_equal(0.0, bob.credit)\n\n begin\n bob.subtract_account_credit(1.0)\n assert false, \"should have thrown\"\n rescue\n assert true\n end\n assert_equal(0.0, bob.credit)\n\n assert_equal(0.0, bob.reload.credit)\n\n # Single basic credit\n bob.add_account_credit(10.0)\n assert_equal(10.0, bob.credit)\n assert_not_nil(bob.account_credit)\n assert_equal(1, bob.account_credit.account_credit_transactions.size)\n assert_equal('CashCredit', bob.account_credit.account_credit_transactions[0].transaction_type)\n assert_nil(bob.account_credit.account_credit_transactions[0].gift_certificate)\n # Second credit\n bob.add_account_credit(15.0)\n assert_equal(25.0, bob.credit)\n assert_not_nil(bob.account_credit)\n assert_equal(2, bob.account_credit.account_credit_transactions.size)\n # Debit!\n bob.add_account_credit(-3.0)\n assert_equal(22.0, bob.credit)\n assert_not_nil(bob.account_credit)\n assert_equal(3, bob.account_credit.account_credit_transactions.size)\n # Get fancy, use a gift certificate\n GiftCertificate.create(:code => 'haha', :amount => 22.00)\n gc = GiftCertificate.find_by_code('haha')\n assert(!gc.used?)\n bob.add_account_credit(gc)\n assert(gc.used?)\n assert_equal(44.00, bob.credit)\n assert_equal(4, bob.account_credit.account_credit_transactions.size)\n assert_equal(gc, bob.account_credit.account_credit_transactions[3].gift_certificate)\n assert_equal('GiftCertificate', bob.account_credit.account_credit_transactions[3].transaction_type)\n gc.reload\n assert_equal(bob, gc.account_credit_transaction.account_credit.customer)\n assert_equal(bob, gc.used_by_customer)\n # Make sure everything was saved ok\n bob.reload\n assert_equal(44.00, bob.credit)\n # Try to use the same gift certificate again\n gc = GiftCertificate.find_by_code('haha')\n bob.add_account_credit(gc)\n assert_equal(44.00, bob.credit)\n assert_equal(4, bob.account_credit.account_credit_transactions.size)\n end",
"def donation_credit_params\n params.require(:donation_credit).permit(:user_id, :quantity)\n end",
"def get_asset\n asset = self.money\n sell_hash = {}\n #make has whose key is id of security and value is quantity that user bought\n LineShare.where(user_id: self.id, available: true).each do |lineshare|\n key = lineshare.security_id.to_s.to_sym\n #because this is the hash for selling, qunatity will be negative\n value = - linesecurity.quantity\n sell_hash[key] = value\n end\n asset += Security.get_cost(sell_hash)\n asset.round(4)\n end",
"def debit *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 appears_on_statement_as = args[1] || options.fetch(:appears_on_statement_as) { nil }\n meta = args[2] || options.fetch(:meta) { nil }\n description = args[3] || options.fetch(:description) { nil }\n\n self.account.debit(\n :amount => amount,\n :appears_on_statement_as => appears_on_statement_as,\n :meta => meta,\n :description => description,\n :source_uri => self.uri\n )\n end",
"def revenue\n end",
"def credit(money, authorization, options={})\n deprecated CREDIT_DEPRECATION_MESSAGE\n refund(money, authorization, options)\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.60237193",
"0.60157335",
"0.601211",
"0.6008063",
"0.59971064",
"0.5992034",
"0.598488",
"0.5981882",
"0.5978034",
"0.59597975",
"0.59478146",
"0.5946205",
"0.5936267",
"0.5929973",
"0.59292364",
"0.5908084",
"0.59019345",
"0.58959764",
"0.5888736",
"0.58774406",
"0.58734316",
"0.5870204",
"0.5867335",
"0.58429766",
"0.58393306",
"0.58384055",
"0.5836963",
"0.5830677",
"0.58276296",
"0.58233464",
"0.5817222",
"0.58092433",
"0.57784516",
"0.57685333",
"0.5767065",
"0.5751661",
"0.5749144",
"0.57406276",
"0.57376",
"0.5735204",
"0.57345957",
"0.5734419",
"0.5732458",
"0.57280606",
"0.57139146",
"0.5711691",
"0.5704268",
"0.57030267",
"0.57025266",
"0.5695285",
"0.56801146",
"0.5679142",
"0.5675931",
"0.5672391",
"0.5661303",
"0.5660426",
"0.5646248",
"0.56432843",
"0.5636268",
"0.5636268",
"0.5633673",
"0.5630742",
"0.5628886",
"0.5616671",
"0.5606699",
"0.5605896",
"0.55997914",
"0.55956095",
"0.5592385",
"0.5585833"
] | 0.74697095 | 0 |
include ActiveMerchant::Billing::Integrations require 'crypto42' require 'money' GET /users GET /users.xml | def index
@users = User.find(:all, :conditions => ["company = ?", session[:company].id])
p 'users index'; y session #debug
@thiscompany = Company.find(session[:company_id])
puts "\n\n\n @thiscompany.id = " + @thiscompany.id.to_s ##debug
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def merchant_end_point; end",
"def billing\n request('billing', :get)\n end",
"def merchant_endpoint; end",
"def billing\n user_agent = request.env['HTTP_USER_AGENT']\n billing_request_body = Billing.request_body(@session)\n parameter = Parameter.first\n\n request = Typhoeus::Request.new(parameter.billing_url, followlocation: true, body: billing_request_body, headers: {Accept: \"text/xml\", :'Content-length' => billing_request_body.bytesize, Authorization: \"Basic base64_encode('NGSER-MR2014:NGSER-MR2014')\", :'User-Agent' => user_agent})\n\n#=begin\n request.on_complete do |response|\n if response.success?\n result = response.body\n elsif response.timed_out?\n result = Error.timeout(@screen_id)\n elsif response.code == 0\n result = Error.no_http_response(@screen_id)\n else\n result = Error.non_successful_http_response(@screen_id)\n end\n end\n\n request.run\n#=end\n #response_body\n #@xml = Nokogiri.XML(Billing.response_body).xpath('//methodResponse//params//param//value//struct//member')\n @xml = Nokogiri.XML(result).xpath('//methodResponse//params//param//value//struct//member') rescue nil\n #render text: Billing.response_body.bytesize\n end",
"def billing\n user_agent = request.env['HTTP_USER_AGENT']\n #parameter = Parameter.first\n transaction_id = DateTime.now.to_i\n\n request = Typhoeus::Request.new(\"http://37.0.73.3:3778\", followlocation: true, params: {transaction_id: transaction_id, msisdn: @account.msisdn, price: \"50\"})\n\n#=begin\n request.on_complete do |response|\n if response.success?\n result = response.body\n elsif response.timed_out?\n result = Error.timeout(@screen_id)\n elsif response.code == 0\n result = Error.no_http_response(@screen_id)\n else\n result = Error.non_successful_http_response(@screen_id)\n end\n end\n\n request.run\n#=end\n return ((result.strip rescue nil) == \"1\" ? true : false)\n end",
"def provider_class\n ActiveMerchant::Billing::Integrations::Europabank\n end",
"def show\n @payment = Payment.new\n @creditcard = ActiveMerchant::Billing::CreditCard.new\n \n end",
"def initialize_active_merchant\n require 'active_merchant'\n\n ::ActiveMerchant::Billing::Gateway.logger = @@logger\n\n am_config = @@glob_config[@@gateway_name.to_sym]\n if am_config.is_a?(Array)\n default_gateway_config = {}\n am_config.each_with_index do |gateway_config, idx|\n gateway_account_id = gateway_config[:account_id]\n if gateway_account_id.nil?\n @@logger.warn \"Skipping config #{gateway_config} -- missing :account_id\"\n else\n default_gateway_config = gateway_config if idx == 0 || gateway_account_id == :default\n end\n end\n am_config = default_gateway_config\n end\n am_config ||= {\n # Sane defaults\n :test => true\n }\n\n if am_config[:test]\n ::ActiveMerchant::Billing::Base.mode = :test\n end\n\n if am_config[:log_file]\n ::ActiveMerchant::Billing::Gateway.wiredump_device = File.open(am_config[:log_file], 'w')\n else\n log_method = am_config[:quiet] ? :debug : :info\n ::ActiveMerchant::Billing::Gateway.wiredump_device = ::Killbill::Plugin::ActiveMerchant::Utils::KBWiredumpDevice.new(@@logger, log_method)\n end\n ::ActiveMerchant::Billing::Gateway.wiredump_device.sync = true\n\n ::ActiveMerchant::Billing::Gateway.open_timeout = am_config[:open_timeout] unless am_config[:open_timeout].nil?\n ::ActiveMerchant::Billing::Gateway.read_timeout = am_config[:read_timeout] unless am_config[:read_timeout].nil?\n ::ActiveMerchant::Billing::Gateway.retry_safe = am_config[:retry_safe] unless am_config[:retry_safe].nil?\n ::ActiveMerchant::Billing::Gateway.ssl_strict = am_config[:ssl_strict] unless am_config[:ssl_strict].nil?\n ::ActiveMerchant::Billing::Gateway.ssl_version = am_config[:ssl_version] unless am_config[:ssl_version].nil?\n ::ActiveMerchant::Billing::Gateway.max_retries = am_config[:max_retries] unless am_config[:max_retries].nil?\n ::ActiveMerchant::Billing::Gateway.proxy_address = am_config[:proxy_address] unless am_config[:proxy_address].nil?\n ::ActiveMerchant::Billing::Gateway.proxy_port = am_config[:proxy_port] unless am_config[:proxy_port].nil?\n\n # Configure the ActiveMerchant HTTP backend\n connection_type = (@@glob_config[:active_merchant] || am_config)[:connection_type]\n if connection_type == :typhoeus\n require 'killbill/ext/active_merchant/typhoeus_connection'\n end\n end",
"def user_request_withdrawal(currency, amount, address, opts = {})\n if Configuration.debugging\n Configuration.logger.debug \"Calling API: UserApi#user_request_withdrawal ...\"\n end\n\n # verify the required parameter 'currency' is set\n fail \"Missing the required parameter 'currency' when calling user_request_withdrawal\" if currency.nil?\n\n # verify the required parameter 'amount' is set\n fail \"Missing the required parameter 'amount' when calling user_request_withdrawal\" if amount.nil?\n\n # verify the required parameter 'address' is set\n fail \"Missing the required parameter 'address' when calling user_request_withdrawal\" if address.nil?\n\n # resource path\n path = \"/user/requestWithdrawal\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = ['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = ['application/json', 'application/x-www-form-urlencoded']\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n form_params[\"currency\"] = currency\n form_params[\"amount\"] = amount\n form_params[\"address\"] = address\n form_params[\"otpToken\"] = opts[:'otp_token'] if opts[:'otp_token']\n form_params[\"fee\"] = opts[:'fee'] if opts[:'fee']\n\n # http body (model)\n post_body = nil\n\n\n auth_names = []\n result = @api_client.call_api(:POST, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Transaction')\n if Configuration.debugging\n Configuration.logger.debug \"API called: UserApi#user_request_withdrawal. Result: #{result.inspect}\"\n end\n return result\n end",
"def create\n \n if params[:user][:app] == \"instainvoice\"\n options = {:body => {:user => {\n :email => params[:user][:email], :password => params[:user][:password], \n :referrer => params[:user][:referrer], :source => \"InstaInvoice\"}\n }\n \n }\n resp = HTTParty.post(\"http://billing.breeasy.com/api/v1/users.json\", options)\n #raise resp.body.inspect\n retval = JSON.parse(resp.body)\n elsif params[:user][:app] == \"bfsb\"\n \n options = {:body => {:user => {:email => params[:user][:email], :password => params[:user][:password],\n :first_name => params[:user][:first_name], :last_name => params[:user][:last_name],\n :title => params[:user][:title],\n :username => params[:user][:username],:refferal_code => params[:user][:referral_code]}\n },\n :query => {:plan_id => params[:plan_id]}\n }\n resp = HTTParty.post(\"http://app.breeasy.com/api/v1/users.json\", options)\n retval = JSON.parse(resp.body)\n \n end\n # user = User.find 35\n \n respond_to do |format|\n format.json { render :json => retval } # note, no :location or :status options\n end\n end",
"def show\n client = Square::Client.new(\n access_token: Figaro.env.square_api_key,\n environment: 'production'\n )\n\n result = client.customers.retrieve_customer(\n customer_id: params[:id]\n )\n \n if result.success?\n # determine membership level\n if result.data[0][:groups].any? {|g| g[:name] === \"Wine Club gold\"}\n membership = \"Gold\"\n else\n membership = \"Platinum\"\n end\n # organize desired data from Square response\n square_data = {\n \"square_id\": result.data[0][:id],\n \"created_at\": result.data[0][:created_at],\n \"given_name\": result.data[0][:given_name],\n \"family_name\": result.data[0][:family_name],\n \"email\": result.data[0][:email_address],\n \"phone_number\": result.data[0][:phone_number],\n \"membership_level\": membership\n }\n\n transactions = client.orders.search_orders(\n body: {\n location_ids: [\n \"EBB8FHQ6NBGA8\"\n ],\n query: {\n filter: {\n customer_filter: {\n customer_ids: [\n square_data[:square_id]\n ]\n }\n }\n }\n }\n )\n if transactions.success?\n t_data = []\n transactions.data && transactions.data[0].each do |t|\n # logic to make sure transaction contains bottle purchase\n # bottle line items always start with \"20\", e.g. \"2017 Syrah\"\n if t[:line_items] && t[:line_items].any? {|li| li[:name] && li[:name].start_with?(\"20\")}\n items = t[:line_items].reject{|li| !li[:name].start_with?(\"20\")}.map { |li| { uid: li[:uid],\n catalog_object_id: li[:catalog_object_id], quantity: li[:quantity], name: li[:name]} }\n end\n \n t_obj = {\n id: t[:id],\n created_at: t[:created_at],\n line_items: items,\n }\n t_data << t_obj\n end\n elsif transactions.error?\n warn transactions.errors\n end\n\n # look up user in our DB\n currentUser = User.find {|u| u.square_id === result.data[0][:id]}\n\n member_data = {\n \"square\": square_data,\n \"db\": {\n \"id\": currentUser.id,\n \"commit_count\": currentUser.commit_count,\n \"commit_adjustments\": currentUser.commit_adjustments\n },\n \"transactions\": t_data\n }\n\n render json: member_data.to_json\n elsif result.error?\n warn result.errors\n end\n end",
"def chargeUser(msisdn,amount,userToken)\n \tcontent = open('https://devapi.globelabs.com.ph/payments/2307').read\n\tjson = JSON.parse(content)\n\tincrement = json['result'].first['reference_code'].to_i+1\n\turi = URI.parse(\"https://devapi.globelabs.com.ph/payment/v1/transactions/amount/\")\n uri.query = \"access_token=#{userToken}\"\n response = HTTParty.post(uri,\n\t:body => {:description => 'desc', :endUserId => msisdn, :amount => amount, :referenceCode => 91131000001,\n\t:transactionOperationStatus => 'charged'})\n output(response)\n response.code.eql?(201) ? (Transaction.successful(msisdn,amount) ; sendSms(msisdn,amount,userToken)) : (Transaction.failed(msisdn,amount))\n end",
"def buyer\n @line_item = current_member.line_items.find(params[:id])\n @current_item = \"my_purchases\"\n @active_tab = \"shop_tab\"\n shop_navigation\n \n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @line_item.to_xml }\n end\n end",
"def purchase billing, number\r\n # the base uri for api requests\r\n query_builder = Configuration.BASE_URI.dup\r\n\r\n # prepare query string for API call\r\n query_builder << \"/tns/{number}\"\r\n\r\n # process optional query parameters\r\n query_builder = APIHelper.append_url_with_template_parameters query_builder, {\r\n \"number\" => number,\r\n }\r\n\r\n # validate and preprocess url\r\n query_url = APIHelper.clean_url query_builder\r\n\r\n # prepare headers\r\n headers = {\r\n \"user-agent\" => \"Flowroute SDK 1.0\",\r\n \"content-type\" => \"application/json; charset=utf-8\"\r\n }\r\n\r\n response = CustomAuthUtility.append_custom_auth_params method:'PUT',\r\n query_url:query_url,\r\n body:\"{\\\"billing_method\\\": #{billing.to_json}}\",\r\n headers:headers\r\n\r\n # Error handling using HTTP status codes\r\n if response.code == 401\r\n raise APIException.new \"NOT AUTHORIZED\", 401, response.raw_body\r\n elsif response.code == 500\r\n raise APIException.new \"APPLICATION/SERVER ERROR\", 500, response.raw_body\r\n elsif !(response.code.between?(200,206)) # [200,206] = HTTP OK\r\n raise APIException.new \"HTTP Response Not OK\", response.code, response.raw_body\r\n end\r\n\r\n response.body\r\n end",
"def checkout\n user = User.find(params[:id])\n\n render json: {\n cost: user.checkout,\n transaction: 'success'\n }\n\n\n end",
"def purchase\n if express_token.include?(\"paykey=AP\")\n\n else\n\n #processes payment for express payment and on site with credit card.\n response = process_purchase\n #creates a transaction to store info from express payment and paywith Credit card\n transactions.create!(:action => \"purchase\", :amount => price_in_cents, :response => response)\n #cart.update_attribute(:purchased_at, Time.now) if response.success?\n response.success?\n end\n end",
"def process_with_payu\n process_purchase\n end",
"def getwalletinfo\n @api.request 'getwalletinfo'\n end",
"def index\n\n @soaps = Soap.find(:all)\n @user = User.find(:first)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @purchase }\n end\n end",
"def sale(params = {})\r\n @PARAM_HASH['TRANSACTION_TYPE'] = 'SALE'\r\n @PARAM_HASH['AMOUNT'] = params[:amount]\r\n @PARAM_HASH['RRNO'] = params[:trans_id] || ''\r\n @PARAM_HASH['CUST_TOKEN'] = params[:customer_token] if params[:customer_token]\r\n @api = \"bp10emu\"\r\n end",
"def show\n response = @account_api.find(params[:id])\n @account = response[:account]\n # @user = RubyBank::CustomerApi.new(session[:token]).find(@account.customer_id)[:user]\n end",
"def show\n @sale = Sale.find(params[:id])\n gateway = ActiveMerchant::Billing::LitleGateway.new\n \n amount = @sale.amount\n \n\n options = { \n\t\t:billToAddress => {\n\t\t\t \t :name => [@sale.firstname, @sale.lastname].compact.join(' '),\n\t\t\t\t :address1 => @sale.address1,\n\t\t\t\t :city => @sale.city,\n\t\t\t\t :state => @sale.state,\n\t\t\t\t :country => ('US' or @sale.country),\n\t\t\t\t :zip => @sale.zip,\n\t\t\t\t :email => @sale.email}\t\n\t\t}\n credit_card = ActiveMerchant::Billing::CreditCard.new(\n :first_name => @sale.firstname,\n :last_name => @sale.lastname,\n :number => @sale.cardnumber,\n :month => @sale.cardmonth,\n :year => @sale.cardyear,\n :verification_value => @sale.cvv)\n\n \nif credit_card.valid?\n response = gateway.purchase(amount,credit_card,options)\n\n if response.success?\n @post = \"Successfully charged an amount of $#{sprintf(\"%.2f\", amount.to_f / 100)} to the credit card #{credit_card.display_number}\"\n @litletxnid = response.params['litleOnlineResponse'].saleResponse.litleTxnId \n else\n @message=response.message\n render :action => 'error2'\n end\nelse\nrender :action => 'error1' \nend\nend",
"def index\n user_coin_transactions = get_user_coin_transactions\n if user_coin_transactions\n json_response(user_coin_transactions)\n else \n json_response({:status => false, :message => 'no transaction'})\n end\n end",
"def index\n @all_products = Product.all.as_json\n @all_currencies = ExchangeRateService.valid_currencies\n @base_url = Rails.env.development? ? 'http://localhost:3000' : 'http://cabifycheckout.com'\n end",
"def show\n if current_user.user_id.nil?\n @merchant = Merchant.new({:store_name => \"\", :store_type => \"\",\n :introduction => \"\", :address => \"\"})\n @merchant.save(validate: false)\n #current_user.update_attribute(:user_id, @merchant.id)\n current_user.update_attribute(:user_id, @merchant.id)\n current_user.update_attribute(:user_type, \"Merchant\")\n @account = @merchant.account\n else\n unless params.has_key?(:format)\n @merchant = current_user.user\n else\n @merchant = Merchant.find(params[:format])\n end\n @account = @merchant.account\n end\n end",
"def buyer\n response = JSON.parse(@client.get(\"items/#{send(:id)}/buyers\").body)\n Promisepay::User.new(@client, response['users'])\n end",
"def buyer\n response = JSON.parse(@client.get(\"items/#{send(:id)}/buyers\").body)\n Promisepay::User.new(@client, response['users'])\n end",
"def buyer\n response = JSON.parse(@client.get(\"items/#{send(:id)}/buyers\").body)\n Promisepay::User.new(@client, response['users'])\n end",
"def setupCoinbase\n if ENV['RACK_ENV'] == \"development\"\n secrets_json = File.read('secrets.json')\n secrets_hash = JSON.parse( secrets_json )\n key = secrets_hash['key']\n secret = secrets_hash['secret']\n else\n key = ENV[\"CB_KEY\"]\n secret = ENV[\"CB_SECRET\"]\n end\n\n @@client = Coinbase::Wallet::Client.new(api_key: key, api_secret: secret)\n @@account = @@client.primary_account\n\nend",
"def purchase\n response = GATEWAY.purchase(price_in_cents, credit_card, purchase_options)\n transactions.create!(:action => \"purchase\", :amount => price_in_cents, :response => response)\n #UserMailer.ordered(\"google.com\", response.params.to_s, User.find(cart.user_id), cart).deliver\n cart.update_attribute(:purchased_at, Time.now) if response.success?\n response.success?\n end",
"def show\n unless @merchant\n render_404\n return\n end\n\n return if !authorize_merchant\n # if merchant_id is same as logged in\n @products = @merchant.products\n # orders\n @paid = @merchant.order_items.where(status: \"paid\")\n @complete = @merchant.order_items.where(status: \"complete\")\n @canceled = @merchant.order_items.where(status: \"canceled\")\n\n @purchases = @merchant.user.orders\n\n end",
"def user_get_deposit_address(opts = {})\n if Configuration.debugging\n Configuration.logger.debug \"Calling API: UserApi#user_get_deposit_address ...\"\n end\n\n # resource path\n path = \"/user/depositAddress\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n query_params[:'currency'] = opts[:'currency'] if opts[:'currency']\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = ['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = ['application/json', 'application/x-www-form-urlencoded']\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n\n\n auth_names = []\n result = @api_client.call_api(:GET, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'String')\n if Configuration.debugging\n Configuration.logger.debug \"API called: UserApi#user_get_deposit_address. Result: #{result.inspect}\"\n end\n return result\n end",
"def bill_user(user)\n active_merchant_stubs_payeezy\n Time.zone = user.club.time_zone\n diff_between_next_bill_date_and_today = user.next_retry_bill_date - Time.zone.now\n next_bill_date = user.next_retry_bill_date + user.terms_of_membership.installment_period.days\n user.update_attribute(:next_retry_bill_date, Time.zone.now)\n\n Time.zone = 'UTC'\n answer = user.reload.bill_membership\n Time.zone = user.club.time_zone\n user.update_attribute(:next_retry_bill_date, user.next_retry_bill_date + diff_between_next_bill_date_and_today)\n assert (answer[:code] == Settings.error_codes.success), answer[:message]\n\n visit show_user_path(partner_prefix: user.club.partner.prefix, club_prefix: user.club.name, user_prefix: user.id)\n within('#table_membership_information') do\n find('#td_mi_next_retry_bill_date', text: I18n.l(next_bill_date, :format => :only_date))\n assert page.has_content?(I18n.l user.active_credit_card.last_successful_bill_date, :format => :only_date)\n end\n\n within('.nav-tabs') { click_on 'Operations' }\n within('#operations') { assert page.has_content?(\"Member billed successfully $#{user.terms_of_membership.installment_amount}\") }\n\n within('.nav-tabs') { click_on 'Transactions' }\n within('#transactions') do\n assert page.has_selector?('#transactions_table')\n Transaction.all.each do |transaction|\n assert(page.has_content?('Transaction Normal - Approved with Stub') || page.has_content?('Sale : This transaction has been approved with stub'))\n end\n assert page.has_content?(user.terms_of_membership.installment_amount.to_s)\n end\n\n within('#transactions_table') { assert page.has_selector?('#refund') }\n user.transactions.where('operation_type = 101').order(:created_at).last\n end",
"def account(params = {})\n make_get_request('/account', params)\n end",
"def request\n result = {}\n req_xml.blank? ? xml = '' : xml = req_xml\n doc = Hpricot.XML(xml)\n (doc/:RequestAuth/:UserPass/:User).inner_html = 'XXXXXXXX'\n (doc/:RequestAuth/:UserPass/:Password).inner_html = 'XXXXXXXX'\n result[:xml] = ErpHelper.xml2html(doc.to_s)\n result[:street] = (doc/:BillTo/:Address/:Street).inner_text\n result[:city] = (doc/:BillTo/:Address/:City).inner_text\n result[:state] = (doc/:BillTo/:Address/:State).inner_text\n result[:zip] = (doc/:BillTo/:Address/:Zip).inner_text\n result[:country] = (doc/:BillTo/:Address/:Country).inner_text\n result[:amount] = (doc/:PayData/:Invoice/:TotalAmt).inner_text\n result[:safe_cc_number] = (doc/:Tender/:Card/:CardNum).inner_text\n result[:expiration_date] = (doc/:Tender/:Card/:ExpDate).inner_text\n result[:expiration_year] = result[:expiration_date][-4,2]\n result[:expiration_month] = result[:expiration_date][-2,2]\n return result\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 user_transactions\n user_deposits = get_user_deposits\n user_withdrawals = get_user_withdrawals\n json_response({:user_transactions => @user_transactions, :user_deposits => user_deposits, :user_withdrawals => user_withdrawals})\n end",
"def transactionByUser\n results = HTTParty.get(\"http://192.168.99.101:4050/by_user_id?userid=\" + (@current_user[\"id\"]).to_s)\n render json: results.parsed_response, status: results.code\n end",
"def fetch_accounts\n log 'fetch_accounts'\n data = get(PRODUCTS_ENDPOINT, fields: { carteras: false,listaSolicitada: 'TODOS',indicadorSaldoPreTarj: false })\n cuentas = data['datosSalidaCuentas']['cuentas'].zip(data['datosSalidaCodIban']['datosIban'])\n cuentas.map{ |data| build_account(data) }\n end",
"def auth(params ={})\r\n @PARAM_HASH['TRANSACTION_TYPE'] = 'AUTH'\r\n @PARAM_HASH['AMOUNT'] = params[:amount]\r\n @PARAM_HASH['RRNO'] = params[:trans_id] || ''\r\n @api = \"bp10emu\"\r\n end",
"def thank_you\n user = session[:user]\n user.zip = params[:zip]\n \n start_date = Date.today\n start_date += 61\n \n response = create_autorrecuring_subscription(start_date, user, params[:card_number], params[:month], params[:year], \n params[:cvc], params[:card_type], params[:city], params[:state],\n params[:billing_address_1], params[:billing_address_2])\n if response.success?\n session[:errors] = nil\n session[:user] = nil\n user.arb_subscription_id = response.subscription_id\n user.arb_status = AuthorizeNet::ARB::Subscription::Status::ACTIVE\n user.billing_information_id = user.add_billing_information(params[:fullname], params[:billing_address_1] ,\n params[:billing_address_2], params[:city], params[:state],\n params[:zip]).id\n user.save\n else\n puts \"Failed to make purchase. \" + response.response_reason_code + \" - \" + response.response_reason_text\n user.errors.clear()\n user.errors.add(:transaction, response.response_reason_text)\n session[:errors] = user.errors\n redirect_to admin_signup_step3_path\n end \n\n \n end",
"def sale(params = {})\r\n @PARAM_HASH['TRANSACTION_TYPE'] = 'SALE'\r\n @PARAM_HASH['AMOUNT'] = params[:amount]\r\n @PARAM_HASH['RRNO'] = params[:trans_id] || ''\r\n @api = \"bp10emu\"\r\n end",
"def purchase(money, creditcard, options = {})\n\n body = credentials\n body[:ssl_transaction_type] = :ccsale\n body[:ssl_amount] = '%.2f' % (money / 100.0)\n\n if options[:ssl_token].present?\n body[:ssl_token] = options[:ssl_token]\n else\n body[:ssl_card_number] = creditcard.card_number\n body[:ssl_exp_date] = ('%02d' % creditcard.expiration_month.to_i)+('%02d' % (creditcard.expiration_year.to_i % 1000))\n body[:ssl_first_name] = creditcard.first_name[0..19] if creditcard.first_name.present?\n body[:ssl_last_name] = creditcard.last_name[0..19] if creditcard.last_name.present?\n\n if creditcard.cid.present?\n body[:ssl_cvv2cvc2] = creditcard.cid\n body[:ssl_cvv2cvc2_indicator] = 1\n end\n\n billing_address = options[:billing_address]\n\n if billing_address.present?\n body[:ssl_avs_zip] = billing_address[:zip]\n body[:ssl_avs_address] = billing_address[:address1]\n body[:ssl_city] = billing_address[:city]\n body[:ssl_state] = billing_address[:state]\n body[:ssl_country] = billing_address[:country]\n end\n end\n\n body_text = xmlize({:txn => body})\n\n # for logging\n safe_request = xmlize({:txn => sanitize_body(body)})\n logger.error 'REQUEST: ' + safe_request\n\n response = RestClient.post(url, body_text) {|response, request, result| response }\n \n logger.error 'RESPONSE: ' + response\n doc = JSON.parse(Hash.from_xml(response).to_json,:symbolize_names=>true)[:txn]\n\n return request_failed_response(doc) if request_failed?(doc)\n\n ActiveMerchant::Billing::Response.new(\n doc[:ssl_result] == '0',\n doc[:ssl_result_message], {},\n :authorization => doc[:ssl_txn_id],\n :auth_code => doc[:ssl_approval_code],\n :avs_result => doc[:ssl_avs_response],\n :cvv_result => doc[:ssl_cvv2_response],\n :request => safe_request,\n :response => doc.to_json\n )\n end",
"def show\n @account = @user.account\n @transactions = @account.transactions\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @account }\n end\n end",
"def activate\n\n # load two modified/updated files for active merchant\n require File.join(Protx3dsGatewayExtension.root, \"lib\", \"active_merchant\", \"billing\", \"gateways\", \"protx.rb\")\n require File.join(Protx3dsGatewayExtension.root, \"lib\", \"active_merchant\", \"billing\", \"gateways\", \"protx3ds.rb\")\n\n # NOTE: monkey patch the extended gateway interface into place\n Creditcard.class_eval do\n # add gateway methods to the creditcard so we can authorize, capture, etc.\n # this needs to be loaded after the standard gateway\n include Spree::PaymentGatewayForProtx3ds\n\n # request that a card payment to use 3ds\n attr_accessor :use_3ds\n end\n\n # can't do auto captures here, since payment mech isn't necess simple - rethink\n unless Spree::Config[].nil?\n Spree::Config.set(:auto_capture => false)\n end\n\n Checkout.class_eval do\n # can't do auto captures here, since payment mech isn't necess simple - rethink\n # monkey-patched in directly, since there's an issue with including a private mthd via module ...\n private\n def authorize_creditcard\n # not doing any card authorization\n end\n end\n\n # add in the actions for the 3ds particulars\n CheckoutsController.class_eval do \n # import the new operations\n include Spree::UpdateMethod\n include Spree::Protx3dsController\n ssl_required :enter_3dsecure, :complete_3dsecure, :callback_3dsecure\n protect_from_forgery :except => :callback_3dsecure\n end\n\n # NOTE: monkey patch until spree master catches up\n Order.class_eval do \n # need this to allow updates later on\n attr_protected :vtx_code\n\n # register a new creditcard payment sequence, returning the actual transaction added\n def new_payment(card, taken_amount, auth_amount, auth_code, txn_type)\n payment = creditcard_payments.create(:amount => taken_amount, :creditcard => card)\n # create a transaction to reflect the authorization\n transaction = CreditcardTxn.new( :amount => auth_amount,\n :response_code => auth_code,\n :txn_type => txn_type )\n payment.creditcard_txns << transaction\n transaction\n end\n end\n end",
"def getaccount(bitcoinaddress)\n @api.request 'getaccount', bitcoinaddress\n end",
"def test_purchase_and_credit_for_check\n assert purchase = @gateway.purchase(1000, @check, @options)\n assert_success purchase\n assert_approved purchase\n \n assert void = @gateway.credit(1000, purchase.authorization, @options)\n assert_success void\n assert_approved void\n end",
"def show\n bill = @bill\n paramz = params\n c = current_company\n result = Billme.bill do\n number bill.name\n filename \"Bill printout\"\n\n company do\n logo \"logo.png\"\n\n company_name c.name\n company_address c.address\n company_city c.city\n company_country c.country\n company_phone c.phone\n company_email c.email\n vat c.vat\n iban c.iban\n swift c.swift\n end\n\n client do\n # project_name \"Battle engagement\"\n name bill.client.name\n date bill.date.try(:in_time_zone, c.time_zone)\n due_date bill.due_date.try(:in_time_zone, c.time_zone)\n bill_date bill.created_at.try(:in_time_zone, c.time_zone)\n address bill.client.address\n email bill.client.email\n vat bill.client.vat\n end\n\n services do\n tax c.tax\n currency bill.currency\n bill.services.each do |s|\n service do\n name s.name\n description s.description\n unit s.amount.round_money\n quantity s.quantity\n end\n end\n end\n\n other do\n notice bill.convertion_rate.present? ? \"1 #{bill.currency} = #{bill.convertion_rate} HRK | TOTAL(HRK): #{(bill.services.reduce(0){|sum, service| sum + service.amount * service.quantity } * bill.convertion_rate).round(2) } #{bill.notice}\" : bill.notice\n footer bill.footer\n payment_method paramz[:locale] == 'hr' ? \"Transakcijski racun\" : \"Transactional account\"\n operator c.operator\n pay_number bill.name\n end\n end\n render inline: result\n end",
"def activemerchant_amount\n (amount * 100).to_i\n end",
"def show\n # @user = current_user.id\n @stripe_account = StripeAccount.find(params[:id])\n\n @stripe_account_bank = Stripe::Account.retrieve((current_user || current_affiliate).stripe_account.acct_id){\n :id\n\n @bank_account = @stripe_account_bank.external_accounts.retrieve(id)\n }\n end",
"def account\n AccountInfoParser.parse(post(\"money/info\"))\n end",
"def purchase\n\n response = GATEWAY.purchase(price_in_cents, credit_card, purchase_options)\n \n #create_card_transaction(action: \"purchase\", amount: price_in_cents, response: response)\n \n #@registration.update_attribute(:purchased_at, Time.now) if response.success?\n #response.success?\n end",
"def purchase\n if user_signed_in?\n \n card = current_user.card\n #テーブルからpayjpの顧客IDを検索\n @user = User.find(@item.seller_id)\n unless @item.seller_id == @item.buyer_id\n redirect_to root_path\n else\n end\n \n if card.blank?\n #登録された情報がない場合にカード登録画面に移動\n redirect_to controller: \"card\", action: \"new\"\n else\n Payjp.api_key = ENV[\"PAYJP_PRIVATE_KEY\"]\n #保管した顧客IDでpayjpから情報取得\n customer = Payjp::Customer.retrieve(card[\"customer_id\"])\n #保管したカードIDでpayjpから情報取得、カード情報表示のためインスタンス変数に代入\n @default_card_information = customer.cards.retrieve(card.card_id)\n @card_brand = @default_card_information.brand\n @card_src = \"Visa.png\"\n end\n\n else\n redirect_to new_user_session_path\n end\n\n end",
"def users\n\n @response = CompanyApi::Request::Economy.new(\n CompanyApi::Response::Formatter::Economy,\n request.cookies,\n {\"User-Agent\" => http_user_agent}\n ).fetch_user_details\n\n # Check if error present or not?\n unless @response.success?\n render_error_response(@response)\n return\n end\n\n @presenter_obj = ::WebPresenter::Economy::User.new(@response, params)\n unless @presenter_obj.client_token.step_three_done?\n redirect_to :planner, status: GlobalConstant::ErrorCode.temporary_redirect\n return\n end\n\n end",
"def show\n @account = current_user.accounts.find(params[:id])\n load_balance(@account)\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @account }\n end\n end",
"def add_bank_account\n\n get_balanced_key\n\n account_uri = params[:account_uri]\n company_name = \"Mindfire Solutions\"\n\n ##You can set your customer business / company name here \n customer = Balanced::Customer.new({name: company_name}).save\n customer_uri = customer.href\n get_customer = Balanced::Customer.fetch(customer_uri)\n \n bank_account = Balanced::BankAccount.fetch(account_uri)\n bank_account.associate_to_customer(customer_uri)\n \n ##befor debiting your customer you need to verify their bank account as per balanced payment\n bank_account = Balanced::BankAccount.fetch(account_uri)\n verify_bank_account = bank_account.verify\n verification = Balanced::BankAccountVerification.fetch(verify_bank_account.href)\n verification.confirm(\n amount_1 = 1,\n amount_2 = 1\n )\n \n amount_in_dollars = params[:amount].to_i\n #amount_in_dollars * 100 convert into cents\n debit = bank_account.debit(:amount => amount_in_dollars * 100, appears_on_statement_as: \"Debit Amount\")\n \n ##You can save the response in your db for future use\n #debit.transaction_number\n #debit.amount\n #debit.statusdebit.created_at\n \n #get your balanced marketplace\n marketplace = Balanced::Marketplace.my_marketplace\n \n credit = get_marketplace_bank_account.credit(:amount => debit.amount, appears_on_statement_as: \"Credit Amount\")\n\n \n return render json: {success: [\"Debit Transaction:: #{debit.attributes}\", \"Credit Transaction:: #{credit.attributes}\"] }\n\n end",
"def show\n @user = User.find(params[:user_id])\n @purchased_item = @user.purchased_items.find(params[:id])\n json_response(@purchased_item)\n end",
"def merchant_endpoint=(_arg0); end",
"def getaccount(namecoin_address)\n request :getaccount, namecoin_address\n end",
"def test_add_system\n billcoin = BillCoin::new\n user = 'SYSTEM'\n billcoin.add_user user\n refute_includes billcoin.user_totals.keys, user\n end",
"def gateway\n puts \"Params: \" + params.inspect\n # Grab SAML message passed from IPP\n saml_response = params['SAMLResponse']\n\n # Decode SAML response and pass into Saml helper to decrypt\n saml = Intuit::Saml.new(:saml_xml => Base64.decode64(saml_response), :private_key => PRIVATE_KEY)\n\n # use the IPP Web API call API_GetIDSRealm to find the realm which is required for IDS\n options = {\n :act => 'API_GetIDSRealm',\n :ticket => saml.ticket,\n :apptoken => APP_TOKEN\n }\n response = HTTParty.get(\"https://workplace.intuit.com/db/#{DB_ID}?\" + build_query(options))\n realm = Hpricot.XML(response.body).at('realm').inner_text\n\n # Setup the post to query customers from IDS\n body = '<CustomerQuery xmlns=\"http://www.intuit.com/sb/cdm/xmlrequest\" />'\n auth_header = %(INTUITAUTH intuit-app-token=\"#{APP_TOKEN}\",intuit-token=\"#{saml.ticket}\")\n path = \"https://services.intuit.com/sb/customer/v1/#{realm}\"\n options = {\n :headers => { 'Authorization' => auth_header, 'Content-Type' =>'text/xml' },\n :body => body,\n :format => :donotparse\n }\n\n # Make call to IDS and receive the XML payload\n response = HTTParty.post(path, options)\n\n puts \"Query Response: \" + response.inspect\n\n # Hpricot payload and pull out customer names for display\n doc = Hpricot.XML(response)\n @customers = []\n doc.search('Customer').each do |node|\n @customers << OpenStruct.new(:name => (node/'cmo:Name').inner_text)\n end\n\n @customers \n end",
"def test_make_payment()\n @customer4.make_payment(10)\n assert_equal(190, @customer4.wallet)\n end",
"def test_successful_purchase_with_emv_credit_card_in_us\n assert response = @gateway.purchase(@amount, @emv_credit_cards[:us], @options)\n assert_success response\n assert_equal 'charge', response.params['object']\n assert response.params['paid']\n assert_match CHARGE_ID_REGEX, response.authorization\n end",
"def get_coins\n get(\"/getcoins\")\n end",
"def card_buy\n @page_title = _('Buy_Card')\n @page_icon = 'money.png'\n\n @email = params[:email]\n @real_price = @card.balance + @cg.get_tax.count_tax_amount(@card.balance)\n @send_invoice = params[:send_invoice]\n @total_tax_name = Confline.get_value('Total_tax_name')\n @description = params[:description].to_s\n end",
"def verify_charge(id)\n\n response = get_request(\"#{base_url}/transactions/#{id}/verify\")\n return response\nend",
"def getContractBy_user_id( user_id)\n params = Hash.new\n params['user_id'] = user_id\n return doCurl(\"get\",\"/contract/by_user_id\",params)\n end",
"def get_skus()\n\tputs \"Getting skus\"\n\tresponse = request_get(\"/api/sku\")\n\tputs response.body\nend",
"def provider_class\n ActiveMerchant::Billing::LipishaGateway\n end",
"def test_successful_purchase_without_address_check2\n @solo.number = '633499110000000003'\n\n response = @gateway.purchase(@amount, @solo, @params)\n assert_success response\n end",
"def show\n @user = User.find_by_urlname(params[:id])\n @active = 'my_account' if @user == current_user\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { @user.to_xml }\n end\n end",
"def index\n authorize User\n @users = User.order(admin: :desc).order(active: :desc).order(:plan_id).order(first_name: :asc).order(last_name: :asc).includes(:plan).all.page(params[:page] || 0).per(20)\n\n @stripe_total = 0\n\n User.includes(:plan).each do |user|\n if user.plan\n @stripe_total += user.plan.stripe_plan_amount\n end\n end\n\n end",
"def test_successful_purchase_with_a_canadian_bank_account_full_number\n bank_account = check({ account_number: '4100', routing_number: '011000015' })\n @options[:currency] = 'CAD'\n assert response = @gateway.purchase(10000, bank_account, @options)\n assert_successful_response(response)\n end",
"def eurocrats\n customer = Eurocrats::Customer.new customer_params\n\n request.eurocrats Eurocrats.default_supplier, customer\n request.eurocrats['billing_address'] = billing_address_params\n end",
"def add_credit_card\n\n get_balanced_key\n card_uri = params[:card_uri]\n\n company_name = \"Mindfire Solutions\"\n customer = Balanced::Customer.new({name: company_name}).save\n customer_uri = customer.href\n get_customer = Balanced::Customer.fetch(customer_uri)\n card = Balanced::Card.fetch(card_uri)\n card.associate_to_customer(customer_uri)\n \n\n amount_in_dollars = params[:amount].to_i\n #amount_in_dollars * 100 convert into cents\n\n debit = card.debit(:amount => amount_in_dollars * 100, appears_on_statement_as: \"Debit Amount\")\n \n ##You can save the response in your db for future use\n #debit.transaction_number\n #debit.amount\n #debit.statusdebit.created_at\n \n #get the balanced market place\n marketplace = Balanced::Marketplace.my_marketplace\n \n credit = get_marketplace_bank_account.credit(:amount => debit.amount, appears_on_statement_as: \"Credit Amount\")\n\n\n return render json: {success: [\"Debit Transaction:: #{debit.attributes}\", \"Credit Transaction:: #{credit.attributes}\"] }\n\n end",
"def gateway\n ActiveMerchant::Billing::Base.mode = :test\n\n @gateway ||= \n ActiveMerchant::Billing::PaypalRecurringGateway.new(\n :login => 'nk_tes_1218714620_biz_api1.mail.ru',\n :password => '1218714626',\n :signature => 'An5ns1Kso7MWUdW4ErQKJJJ4qi4-A-b1ANj9g14qW6XOboBut7nnhDdn'\n )\n @gateway\n end",
"def show\n @user = User.find( params[:id] )\n @plans = Stripe::Plan.all\n @coupons = Stripe::Coupon.all\n end",
"def index\n @customers = current_user.customers.paginate(:per_page => 20, :page => params[:page], :order => 'name', :include => :transactions)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @customers }\n end\n end",
"def credit\n handle_response(get(\"/credit.json\"))\n end",
"def configure_contracts\n # configure accounts for eosdactokens\n\nend",
"def show\n @merchant = Merchant.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @merchant }\n end\n end",
"def credit(money, identification, options = {})\n body = credentials\n body[:ssl_transaction_type] = :ccreturn\n\n body[:ssl_amount] = (money.to_money/100.0).to_s\n body[:ssl_txn_id] = identification\n\n body_text = xmlize({:txn => body})\n\n logger.error 'REQUEST: ' + body_text\n response = RestClient.post(url, body_text) {|response, request, result| response }\n logger.error 'RESPONSE: ' + response\n\n doc = JSON.parse(Hash.from_xml(response).to_json,:symbolize_names=>true)[:txn]\n\n #logger.error body_text\n #logger.error response.to_s\n\n return request_failed_response(doc) if request_failed?(doc)\n\n ActiveMerchant::Billing::Response.new(\n doc[:ssl_result].to_s == '0',\n doc[:ssl_result_message], {},\n :authorization => doc[:ssl_txn_id],\n :request => body_text,\n :response => doc.to_json)\n end",
"def eurocrats\n customer = Eurocrats::Customer.new\n customer.vat_number = vat_number_param if vat_number_param\n\n request.eurocrats Eurocrats.default_supplier, customer\n request.eurocrats['billing_address'] = billing_address_param\n end",
"def auth(params ={})\r\n @PARAM_HASH['TRANSACTION_TYPE'] = 'AUTH'\r\n @PARAM_HASH['AMOUNT'] = params[:amount]\r\n @PARAM_HASH['RRNO'] = params[:trans_id] || ''\r\n @PARAM_HASH['CUST_TOKEN'] = params[:customer_token] if params[:customer_token]\r\n @api = \"bp10emu\"\r\n \r\n if params[:new_customer_token] && params[:new_customer_token] != false\r\n @PARAM_HASH['NEW_CUST_TOKEN'] = params[:new_customer_token] == true ? SecureRandom.hex(8) : params[:new_customer_token]\r\n end\r\n end",
"def users(params = {})\n make_get_request('/account/users', params)\n end",
"def index\n @purchases = Purchase.find_all_by_user_id(current_user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @purchases }\n end\n end",
"def customer_account_amount\n token = request.headers[\"HTTP_X_API_POP_KEY\"]\n puts request.headers[\"HTTP_X_API_POP_KEY\"]\n\n if Customer.exists?(authentication_token: token)\n @customer = Customer.find_by_authentication_token(token)\n if @customer.account.present?\n # customer have an account\n render json: {\n status: true,\n message: @customer.account.amount.round(2)\n }\n else\n render json: {\n status: false,\n message: \"Account not activated\"\n }\n end\n else\n render json: {\n status: false,\n message: \"Unknow user\"\n }\n end\n end",
"def account\n\t\t@email = params[:vitalsource][:email]\n\t\t@password = params[:vitalsource][:password]\n\t\tdoc = Builder::XmlMarkup.new(:target => out_string = \"\", :indent =>2)\n\t\t#----------user login request body------------------------------------------------------------------------\n\t\tdoc.credentials{\n\t\t\tdoc.credential(\"email\" => @email, \"password\" => @password)\n\t\t}\n\t\t#user login request url\n\t\trequest_url = \"/v3/credentials.xml\"\n\t\t# #return: \n\t\t# #{\"credentials\"=>{\"credential\"=>{\"access_token\"=>\"4e2503801317d29a915895b17d560c54\", \"reference\"=>\"\", \"guid\"=>\"B2EY7AGYKNNMER76H56M\", \"email\"=>\"lemon_victor@hotmail.com\", \"__content__\"=>\"\\n \"}}}\n\t\t@request = out_string\n\t\turi = URI.parse(\"https://api.vitalsource.com\")\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\thttp.use_ssl = true\n\t\thttp.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\t\trequest = Net::HTTP::Post.new(request_url)\t\t\n\t\trequest.add_field('X-VitalSource-API-Key', 'YNBWZXTN743PWCZG')\n\t\trequest.body = out_string\n\t\tresponse = http.request(request)\n\t\tbody = Hash.from_xml(response.body)\n\t\tif(!body.has_key?(\"error\"))\n\t\t\t@err = body[\"credentials\"][\"error\"]\n\t\tend\n\t\tif(!body.has_key?(\"credential\"))\n\t\t\t@user = body[\"credentials\"][\"credential\"]\n\t\tend\n\tend",
"def get_transactions(*params); raise('Stub or mock required.') end",
"def get_balance (opts={})\n query_param_keys = []\n headerParams = {}\n\n \n \n # set default values and merge with input\n options = {\n \n }.merge(opts)\n\n #resource path\n path = \"/get-balance.json\".sub('{format}','json')\n \n # pull querystring keys from options\n queryopts = options.select do |key,value|\n query_param_keys.include? key\n end\n\n # header parameters\n headers = {}\n\n _header_accept = 'application/json'\n if _header_accept != ''\n headerParams['Accept'] = _header_accept\n end \n _header_content_type = ['application/x-www-form-urlencoded']\n headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'\n\n \n \n headers[:'Authorization'] = @api_key_secret\n\n # http body (model)\n post_body = nil\n \n # form parameters\n form_parameter_hash = {}\n \n \n \n Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make\n \n \n end",
"def credit\n handle_response(self.class.get(\"/credit.json\"))\n end",
"def create\n @user = User.new(user_params)\n respond_to do |format|\n if @user.save and @user.payment == \"paypal\"\n response = EXPRESS_GATEWAY.setup_purchase(@user.calculate_total_in_cents,\n :ip => request.remote_ip,\n :return_url => new_order_url,\n :cancel_return_url => orders_url,\n :currency => \"USD\",\n :description => \"Sms affirmation service - $#{\"%.2f\" % (@user.calculate_total_in_cents / 100 ) }\",\n )\n\n @user.update(:payment_token => response.token)\n redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token) and return\n format.html { redirect_to new_user_path, notice: 'Your SMS Subscription has been activated.' }\n format.json { render action: 'show', status: :created, location: @user }\n else\n @user.terms = false\n\n format.html { render action: 'new' }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_successful_purchase_with_emv_credit_card_in_uk\n assert response = @gateway.purchase(@amount, @emv_credit_cards[:uk], @options)\n assert_success response\n assert_equal 'charge', response.params['object']\n assert response.params['paid']\n assert_match CHARGE_ID_REGEX, response.authorization\n end",
"def show\n @token = Token.find(params[:id])\n gateway = ActiveMerchant::Billing::LitleGateway.new\n \n credit_card = ActiveMerchant::Billing::CreditCard.new(\n :first_name => @token.firstname,\n :last_name => @token.lastname,\n :number => @token.cardnumber,\n :month => @token.cardmonth,\n :year => @token.cardyear,\n :verification_value => @token.cvv)\n \n options = { \n :billToAddress => {\n :name => [@token.firstname, @token.lastname].compact.join(' '),\n :address1 => @token.address1,\n :city => @token.city,\n :state => @token.state,\n :country => ('US' or @token.country),\n :zip => @token.zip,\n :email => @token.email} \n }\n if credit_card.valid?\n response = gateway.store(credit_card,options)\n \n if response.success?\n @post = \"Successfully stored token:\" \n @tokenid = response.params['litleOnlineResponse'].registerTokenResponse.litleToken \n \n else\n @message = response.message\n render :action => 'error2' \n end\n \n else\n render :action =>'error1' \n end\n \n end",
"def get_accounts()\n http_get(accounts_url)\n end",
"def get_all_orders() \n\tputs \"Getting all orders\"\n\tresponse = request_get(\"/api/order\")\n\tputs response.body\nend",
"def charge(billing_key, amount, user = nil)\n a = ActiveMerchantCall.new(:login => username, :password => password, :user => user)\n a.interact('create_customer_profile_transaction', :transaction => {\n\t :customer_profile_id => user.customer_profile_id,\n\t :customer_payment_profile_id => billing_key,\n\t :type => :auth_capture,\n\t\t\t\t\t:validation_mode => validation_mode,\n\t :amount => (amount.cents/100.0)\n\t })\n\t\t\t\treturn FreemiumTransaction.new(:billing_key => billing_key, :amount => amount, :success => a.response.success?, :gateway_message => a.response.message)\n end",
"def user_payment_callback\n @user = User.find_by(bill_id: params[:id])\n @user.skip_icpassport_validation = true\n @last_ezi = User.all.where.not(:ezi_id => nil).order(:ezi_id).last.ezi_id.gsub(/[^0-9]/, '').to_i\n @ezi_id = @last_ezi + 1\n @ezi_id_string = \"Q\" + @ezi_id.to_s.rjust(4,'0')\n @expiry = @user.package * 365\n response = BillplzReg.check_status(@user.id)\n if (response['paid'] == true) && (response['state']=='paid')\n @user.update_attributes(status: 1, :ezi_id => @ezi_id_string, :expiry => @expiry.days.from_now)\n render body: nil\n end\n end",
"def pay!\n #soap_server = VendorPayment.generate_soap_server\n #token = VendorPayment.generate_usa_epay_security_token\n #custNum = observed.vendor_payment_period.store.id\n #paymentMethodID = nil\n #parameters = generate_transaction_request\n #response = soap_server.runCustomerTransaction(token, custNum, paymentMethodID, parameters)\n #\n if self.vendor_payment_period.store.usa_epay_customer_number.blank?\n self.errors['usa_epay_customer_number'] = \"The USA ePay custNum must be set before a payment can be made.\"\n return\n end\n gateway = VendorPayment.gateway\n payment_methods_response = gateway.get_customer_payment_methods(:customer_number => self.vendor_payment_period.store.usa_epay_customer_number)\n monthly_transfer_method = nil\n items = if payment_methods_response.params['get_customer_payment_methods_return']\n payment_methods_response.params['get_customer_payment_methods_return']['item']\n else\n []\n end\n \n if items.is_a?(Hash)\n items = [items]\n end\n \n items.each do |payment_method|\n if payment_method['method_name'].strip == 'Monthly ACH Transfer'\n monthly_transfer_method = payment_method\n end\n end\n \n if monthly_transfer_method\n response = gateway.run_customer_transaction(:customer_number => self.vendor_payment_period.store.usa_epay_customer_number,\n :command => 'CheckCredit',\n # USA ePay does pennies for the amount, so it needs to be\n # multiplied by 100\n :payment_method_id => monthly_transfer_method['method_id'],\n :amount => self.amount * 100)\n \n \n self.state = if response.message['result_code'].strip == 'A'\n VendorPayment.status_codes[response.message['status_code']]\n else\n VendorPayment.status_codes[\"E\"]\n end\n self.response_data = YAML::dump(response)\n if !response.message['ref_num'].blank?\n self.response_code = response.message['ref_num']\n save\n else\n save\n self.errors['transaction'] = \"State: #{self.state}. There was an error with code #{response.message['error_code']}, while trying to make the payment. Check USA ePay for reference number #{response.message['ref_num']} if necessary.\\n\\nFull Message: #{response.message.inspect}\"\n end\n self.vendor_payment_period.update_payment_total!\n self.vendor_payment_period.update_state!\n else\n self.errors['payment_method'] = \"There is no payment method on the vendor called 'Monthly ACH Transfer'\"\n end\n end",
"def customers\n ShopifyAPI::Customer.all\n end",
"def index\n # this whole process is updating the users coins with the currnet price from the api. pulls the users coins and if a coin matches then update the price in usd. and return the coin.\n coins = HTTParty.get(BASE_URL) # this will bring back the top 100 coins in an array\n user_coins = current_user.coins\n user_coins.each do |coin|\n res_coin = coins.find { |c| c['id'] == coin.cmc_id }\n coin.update(price: res_coin['price_usd']) if res_coin \n end \n render json: current_user.coins # if we don't authenticate_user before then we cant user current_user. it is a built in devise function\n end"
] | [
"0.6329442",
"0.6167065",
"0.6106312",
"0.60678077",
"0.59957707",
"0.59438646",
"0.5920874",
"0.5914747",
"0.58899504",
"0.5880816",
"0.58687776",
"0.58658886",
"0.58092993",
"0.5776161",
"0.57417345",
"0.57306224",
"0.571197",
"0.57082313",
"0.5689404",
"0.56693846",
"0.5665563",
"0.5632421",
"0.5629386",
"0.5605222",
"0.5580845",
"0.5578548",
"0.5578548",
"0.5578548",
"0.5575181",
"0.55718243",
"0.5561651",
"0.55592555",
"0.55433816",
"0.5539922",
"0.5538632",
"0.5537909",
"0.5514252",
"0.5511269",
"0.5510878",
"0.5503002",
"0.5499178",
"0.5496697",
"0.5485326",
"0.5464505",
"0.54630893",
"0.54575497",
"0.54433066",
"0.54366827",
"0.54312724",
"0.5421811",
"0.5419741",
"0.5418698",
"0.54070467",
"0.5404613",
"0.54042625",
"0.53946215",
"0.5394",
"0.53902406",
"0.5387847",
"0.5386507",
"0.538292",
"0.5379011",
"0.53744334",
"0.53699946",
"0.5366417",
"0.5362113",
"0.5361781",
"0.5357447",
"0.5352354",
"0.5332716",
"0.5332647",
"0.53228784",
"0.531074",
"0.5305729",
"0.5305126",
"0.5303221",
"0.53012663",
"0.52880543",
"0.52875525",
"0.52790457",
"0.52787113",
"0.5277127",
"0.52767915",
"0.5272142",
"0.5265322",
"0.526234",
"0.52603287",
"0.5259319",
"0.52589434",
"0.52564114",
"0.5250693",
"0.52503407",
"0.5244556",
"0.52432626",
"0.52363396",
"0.5224647",
"0.5218702",
"0.5217872",
"0.5214682",
"0.5214642",
"0.5209849"
] | 0.0 | -1 |
GET /users/1 GET /users/1.xml | def show
# puts "\n\n\n DEBUG: @thiscompany.id = " + @thiscompany.id.to_s ##debug
@user = User.find(params[:id])
y session #debug
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @user }
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @users = LinkedData::Client::Models::User.all\n respond_to do |format|\n format.html\n format.xml { render xml: @users.to_xml }\n end\n end",
"def me\n users(request(\"users/authenticate.xml\", :auth => true))\n end",
"def index\n @users = User.all\n render :xml => @users\n end",
"def list_users\n self.class.get('/users')\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render xml: @users }\n end\n end",
"def index\r\n @users = User.find(:all)\r\n \r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.xml { render :xml => @users.to_xml }\r\n end\r\n end",
"def index\n @users = User.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @title = \"All users\"\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users.to_xml(:except => [:password_digest, :remember_token])}\n end\n end",
"def index\n @users = User.find(:all)\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @users.to_xml }\n end\n end",
"def index\n @users = User.find(:all)\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @users.to_xml }\n end\n end",
"def show\n @user = User.find(params[:id])\n render :xml => @user\n rescue\n render :nothing => true, :status => :not_found\n end",
"def index\n @users = User.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def show\n @user = User.find(params[:id])\n usr = prepare_user(@user);\n respond_to do |format|\n format.xml { render :xml => usr.to_xml }\n end\n end",
"def index\n @users = User.find(:all, :order => 'name ASC')\n respond_to do |format|\n format.html \n format.xml { @users.to_xml }\n end\n end",
"def users(args = {})\n get(\"/users.json\",args)\n end",
"def index\n users = get_collection(User) || return\n\n respond_to do |format|\n format.xml { render xml: users.to_xml(only: DEFAULT_FIELDS, root: 'users', skip_types: 'true') }\n format.json { render json: users.to_json(only: DEFAULT_FIELDS) }\n end\n end",
"def show\n @user = User.find(params[:id])\n render :xml => @user.to_xml(:except => [ :password ])\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def show\n @users = User.find(params[:id])\n if @users\n respond_to do |format|\n format.json { render :json => @users }\n format.xml { render :xml => @users }\n end\n else\n head :not_found\n end\n end",
"def index\n @users = User.all(:order=>:name)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users.to_xml(\n :dasherize => false, :only => [:id, :name,\n :created_at, :updated_at]) }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def index\n @users = User.all()\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def list_users(api_object)\r\n puts \"Current Users:\"\r\n doc = Nokogiri::XML.parse api_object.read\r\n names = doc.xpath('users').collect {|e| e.text }\r\n puts names.join(\", \")\r\n puts \"\"\r\nend",
"def index3\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def show\n @user = nil\n id_or_name = params[:id]\n begin\n @user = User.find(id_or_name)\n rescue\n @user = User.find_by_name(id_or_name)\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml {\n xml = Builder::XmlMarkup.new(:indent => 2)\n xml.instruct! directive_tag=:xml, :encoding=> 'utf-8'\n render :xml => xml.user {|u|\n u.id(@user.id)\n u.name(@user.name)\n u.statuses {|ss|\n @user.statuses.each {|stat|\n ss.status {|s|\n s.id(stat.id)\n s.user_id(stat.user_id)\n s.text(stat.text)\n s.geo_tag(stat.geo_tag)\n s.created_at(stat.created_at)\n }\n }\n }\n }\n }\n end\n end",
"def index\n if params[:single]\n\t url = \"#{API_BASE_URL}/users/#{params[:id]}.json\"\n\t response = RestClient.get(url)\n\t @user = JSON.parse(response.body)\n\telse\n\t url = \"#{API_BASE_URL}/users.json\"\t \n response = RestClient.get(url)\n @users = JSON.parse(response.body)\t\t \n\tend\n end",
"def users\n get('get_users')\n end",
"def fetch_one_user_data\n get_url(\"/api/v1/users/#{@filter}\")\n end",
"def show\n @user = V1::User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show \n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def index\n\t\t@users = User.all\n\t\t\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.xml\t{ render :xml => @users }\n\t\tend\n\tend",
"def index\n @user = current_user\n @title = \"Account\"\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def users(params = {})\n make_get_request('/account/users', params)\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @user.to_xml }\n end\n end",
"def users\n \n @users = User.where(:enabled => true)\n @users = @users.where(:role => params[:role].upcase) if params[:role]\n @users = @users.where(:id => params[:id]) if params[:id]\n respond_to do |format|\n format.xml { render :xml => @users.to_xml }\n end\n \n end",
"def index\n authorize! :read, User\n @users = User.find(:all)\n @users ||= []\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @users.to_xml }\n end\n end",
"def GetUsers params = {}\n\n params = params.merge(path: 'users.json')\n APICall(params)\n\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render xml: @user }\n end\n end",
"def query_users(options={}) path = \"/api/v2/users\"\n get(path, options, AvaTax::VERSION) end",
"def show\n respond_to do |format|\n format.html\n format.xml { render :xml => @user }\n end\n end",
"def index\n @users = User.all\n respond_to do |format|\n format.html\n format.xml { render :xml => @users }\n format.json { render :json => @users }\n end\n end",
"def show\n\t\t@user = User.find(params[:id])\n\t\t\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml\t{ render :xml => @user }\n\t\tend\n\tend",
"def show\n @user = User.find(params[:id])\n @title = @user.username\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user.to_xml(:except => [:password_digest, :remember_token])}\n end\n end",
"def show\n @user = User.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id]) or raise ActiveRecord::RecordNotFound\n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @user.to_xml }\n end\n end",
"def index\n users = get_collection(visible_users) || return\n\n respond_to do |format|\n format.xml { render xml: users.to_xml(only: DEFAULT_FIELDS, root: :users, skip_types: true) }\n format.json { render json: users.to_json(only: DEFAULT_FIELDS) }\n end\n end",
"def users_get_info_response_xml\n <<-XML\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <users_getInfo_response xmlns=\"\" xmlns:xsi=\"\" xsi:schemaLocation=\"\" list=\"true\">\n\t<user>\n\t <uid>kangtk</uid>\n\t <nickname>康泰克</nickname>\n\t <facebig>http://userface3.51.com/ce/25/kangtk_130.gif?v=20071208033821</facebig>\n\t <sex>1</sex>\n\t <vip>3</vip>\n\t <isconfirm>1</isconfirm>\n\t</user>\n </users_getInfo_response>\n XML\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @user = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end"
] | [
"0.7207758",
"0.71160614",
"0.7054628",
"0.70484746",
"0.6916555",
"0.6916146",
"0.6915502",
"0.6890011",
"0.68641984",
"0.68633956",
"0.6853434",
"0.68511736",
"0.68511736",
"0.68511736",
"0.6828291",
"0.68280435",
"0.68278646",
"0.68065727",
"0.6801009",
"0.6786165",
"0.676656",
"0.6737866",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67323196",
"0.67162997",
"0.67162997",
"0.67162997",
"0.67147905",
"0.6709973",
"0.67093414",
"0.66771376",
"0.6676199",
"0.6673456",
"0.66601056",
"0.66483146",
"0.66351426",
"0.66298765",
"0.6601779",
"0.65742964",
"0.6568273",
"0.6567998",
"0.6548836",
"0.6534059",
"0.65334934",
"0.65303916",
"0.6528084",
"0.651673",
"0.6510219",
"0.6503691",
"0.6500449",
"0.6470068",
"0.646801",
"0.6465945",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248",
"0.6463248"
] | 0.0 | -1 |
GET /users/new GET /users/new.xml | def new
@user = User.new
@user.credits = 0 ## Stop form from complaining that "credits" is not a number.
@thiscompany = session[:company]
puts "\n\n\n @thiscompany.id = " + @thiscompany.id.to_s ##debug
y session #debug
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def new\n logger.debug(\"Create a new user\")\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.xml { render xml: @user}\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @user }\n end\n end",
"def new\n @user = User.new\n get_list\n respond_to do |format|\n format.html # new.html.haml\n format.xml { render :xml => @user }\n end\n end",
"def new\n # When a http GET request to '/users/new' is received, have it render:\n # a view file with an empty form to create a new user.\n end",
"def new\n\tputs \"\\n\\t\\t in new\\n\"\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n render :xml => @user\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new \n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new()\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = V1::User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n respond_to do |format|\n format.html\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n respond_to do |format|\n format.html\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n respond_to do |format|\n\tformat.html # new.html.erb\n\tformat.xml { render :xml => @user }\n end\nend",
"def new\n @user_name = UserName.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_name }\n end\n end",
"def new\n @usr = Usr.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @usr }\n end\n end",
"def new\n @user = User.new\n @title = \"Sign Up\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n logger.info 'huyen anh'\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n\t\t@user = User.new\n\t\t@addresses = Address.all\n\t\t@address = Address.new\n\t\t\n\t\twidok = 'new'\n\t\twidok = 'user_new' if !(admin_logged_in?)\n\t\t\n\t\trespond_to do |format|\n\t\t\tformat.html { render widok } # new.html.erb\n\t\t\tformat.xml\t{ render :xml => @user }\n\t\tend\n\tend",
"def new\n @user = User.new\n @title = \"Signup to Studyers\"\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html { render :layout=>false}\n format.xml { render :xml => @user }\n end\n end",
"def new\n\t\t@user = User.new\n\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.xml { render :xml => @user }\n\t\tend\n\tend",
"def new\n\t\t@user = User.new\n\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.xml { render :xml => @user }\n\t\tend\n\tend",
"def new\n @user = User.new :step => '1'\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n @page_title = '创建新用户'\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n @users = @firm.users.all\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @users = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @users }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.haml\n format.json { render_for_api :public, :json => @user }\n format.xml { render_for_api :public, :xml => @user }\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.xml { render :xml => @user }\n format.js #new.js.rjs\n end\n end",
"def new\n respond_to do |format|\n format.json { render :json => @user } \n format.xml { render :xml => @user }\n format.html\n end\n end",
"def new\n @newuser = Newuser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newuser }\n end\n end",
"def new\n @userinfo = Userinfo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @userinfo }\n end\n end",
"def new\n @user = User.new\n @action = \"new\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def newAdmin\n @user = User.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @users = User.find(:all)\n @invoice = Invoice.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @invoice }\n end\n end",
"def new\n @user = user.new\n\t\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def new\n @usernew = Usernew.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @usernew }\n end\n end",
"def new\n @database = Database.new\n @users = User.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @database }\n end\n end",
"def new\n @user_addon = UserAddon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_addon }\n end\n end",
"def new2\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def new\n @user = User.new\n\n #respond_to do |format|\n # format.html # new.html.erb\n # format.xml { render :xml => @user }\n # end\n end",
"def new\n @users = User.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def new\n @email_user = Email::User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @email_user }\n end\n end",
"def new\n @user_template = UserTemplate.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_template }\n end\n end",
"def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @online_retailer_user }\n end\n end",
"def new\n @usuario = Usuario.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @usuario }\n end\n end",
"def new\n @usuario = Usuario.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @usuario }\n end\n end",
"def new\n @user = User.new\n @user.stats = Stats.new\n @stats = @user.stats\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @user }\n end\n end",
"def new\n @user = User.new\n @roles = Role.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end"
] | [
"0.77330446",
"0.7697235",
"0.7628986",
"0.75933844",
"0.7592385",
"0.75490505",
"0.7536828",
"0.7530958",
"0.7530958",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7508645",
"0.7507901",
"0.7507901",
"0.7507901",
"0.7507901",
"0.7507901",
"0.7464288",
"0.7458749",
"0.7437645",
"0.74308515",
"0.7425612",
"0.7281308",
"0.7226895",
"0.71805024",
"0.71609145",
"0.71551806",
"0.7135706",
"0.71148974",
"0.71052235",
"0.70312554",
"0.70312554",
"0.7030487",
"0.70140064",
"0.7013169",
"0.7012782",
"0.69945866",
"0.69914556",
"0.6990106",
"0.69833785",
"0.69761634",
"0.6966175",
"0.6945618",
"0.6940041",
"0.69285053",
"0.6927652",
"0.69193554",
"0.6912061",
"0.6878826",
"0.6872577",
"0.68450326",
"0.6814593",
"0.68106794",
"0.6797799",
"0.67911136",
"0.6781481",
"0.6778547",
"0.6764598"
] | 0.0 | -1 |
POST /users POST /users.xml | def create
@user = User.new(params[:user])
@thiscompany = Company.find(session[:company_id])
puts "\n\n\n @thiscompany.id = " + @thiscompany.id.to_s ##debug
y session #debug
respond_to do |format|
if @user.save
flash[:notice] = 'User was successfully created.'
format.html { redirect_to(@user) }
format.xml { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def post_users(users)\n self.class.post('https://api.yesgraph.com/v0/users', {\n :body => users.to_json,\n :headers => @options,\n })\n end",
"def post body=nil, headers={}\n @connection.post \"users.json\", body, headers\n end",
"def CreateUser params = {}\n \n APICall(path: 'users.json',method: 'POST',payload: params.to_json)\n \n end",
"def create\n @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.json { render json: @user }\n format.xml { render xml: @user }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity }\n format.xml { render xml: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_user(name, value)\n self.class.post(\"/users/#{name}\",\n body: value,\n headers: {\n 'Content-Type' => 'application/json; charset=UTF-8',\n Connection: 'keep-alive',\n Accept: 'application/json, text/plain, */*'\n })\n end",
"def create_user(params:)\n parse(JSON.parse(connection.post(\"users\", params.to_json).body))\n end",
"def publish_to_users\n data = { users: users }.merge!(payload)\n client.post('publishes/users', data)\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(users_url, :notice => \"User #{@user.name} was successfully created.\") }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create(options = {})\n request(:post, '/users.json', default_params(options))\n end",
"def create(name=\"Default Name\", age=\"50\")\r\n xml_req =\r\n \"<?xml version='1.0' encoding='UTF-8'?>\r\n <person>\r\n <name>#{name}</name>\r\n <age>#{age}</age>\r\n </person>\"\r\n \r\n request = Net::HTTP::Post.new(@url)\r\n request.add_field \"Content-Type\", \"application/xml\"\r\n request.body = xml_req\r\n \r\n http = Net::HTTP.new(@uri.host, @uri.port)\r\n response = http.request(request)\r\n response.body \r\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.xml { render xml: @user}\n end\n end",
"def create\n @users = User.new(params[:user])\n\n respond_to do |format|\n if @users.save\n format.html { redirect_to @users, notice: 'Regist was successfully created.' }\n format.json { render json: @users, status: :created, location: @users }\n else\n format.html { render action: \"new\" }\n format.json { render json: @users.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(:users, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n respond_to do |format|\n if @user.save\n format.html { render :json => {:success => true} }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :json => ( (@user.errors.full_messages.join(\".<br />\").to_s + \".\").to_json ) } unless @user.errors.empty?\n format.html { render :json => {:success => false} }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def append_user_info(username, xml); end",
"def create\n @user = V1::User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'V1::User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\r\n @user = User.new(params[:user])\r\n \r\n respond_to do |format|\r\n if @user.save\r\n flash[:notice] = 'User was successfully created.'\r\n format.html { redirect_to user_url(@user) }\r\n format.xml { head :created, :location => user_url(@user) }\r\n else\r\n format.html { render :action => \"new\" }\r\n format.xml { render :xml => @user.errors.to_xml }\r\n end\r\n end\r\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(:root) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\", :layout=>false }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_user(body)\n post 'create_user', body\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to user_url(@user) }\n format.xml { head :created, :location => user_url(@user) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors.to_xml }\n end\n end\n end",
"def createuserxml(useremail, username, roleid, restrictionid, groupids)\n userxml = Document.new\n userxml.add_element(\"user\")\n email = Element.new(\"email\")\n email.text= useremail\n userxml.root.add_element(email)\n name = Element.new(\"name\")\n name.text = username\n userxml.root.add_element(name)\n role = Element.new(\"roles\")\n role.text = roleid\n userxml.root.add_element(role)\n restriction_id = Element.new(\"restriction_id\")\n restriction_id.text = restrictionid\n userxml.root.add_element(restriction_id)\n groups = Element.new(\"groups\")\n userxml.root.add_element(groups, {\"type\" => \"array\"})\n # we can have or more of the groupIds\n groupids.each { |groupid|\n group = Element.new(\"group\")\n group.text = groupid\n groups.add_element(group)\n }\n\n return userxml # need to explicitly return in in this case because we want to return the entire xml we just built\n end",
"def create\n r = @api.create_user(user_params)\n respond_to do |format|\n if r.code == 201\n format.html { redirect_to users_url, notice: 'User was successfully created.' }\n else\n response = JSON.parse(r.body)\n format.html { redirect_to users_url, alert: response['message']}\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_user(attributes)\n post(\"/v1/users\", attributes)\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to user_url(@user) }\n format.xml { head :created, :location => user_url(@user) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'Firm was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n\t\tparams.permit!\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(users_url,\n :notice => \"User #{@user.name} was successfully created.\") }\n format.xml { render :xml => @user,\n :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors,\n :status => :unprocessable_entity }\n end\n end\n end",
"def postUser( email, user_id, first_name, last_name, active, trust, creation_date, user_type, social_network, social_network_id, reseller_admin_masheryid, group_id, admin_upgrader)\n params = Hash.new\n params['email'] = email\n params['user_id'] = user_id\n params['first_name'] = first_name\n params['last_name'] = last_name\n params['active'] = active\n params['trust'] = trust\n params['creation_date'] = creation_date\n params['user_type'] = user_type\n params['social_network'] = social_network\n params['social_network_id'] = social_network_id\n params['reseller_admin_masheryid'] = reseller_admin_masheryid\n params['group_id'] = group_id\n params['admin_upgrader'] = admin_upgrader\n return doCurl(\"post\",\"/user\",params)\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'user was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n result = access_token.post('/api/v1/users/create', {:email=>params[:email],:psw=>params[:password],:psw_conf=>params[:password_conf],:inbox=>params[:inbox]})\n display_api_response result\n respond_with(\"\",:location => :back)\n end",
"def create\n @user = current_restaurant.users.new(params[:user])\n\n respond_to do |format|\n if @user.signup!(params)\n @user.deliver_invited_activation_instructions!(current_restaurant)\n current_restaurant.users << @user\n current_restaurant.save\n flash[:notice] = t('users.create.success')\n format.html { redirect_to(@user) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def post_users(users, opts = {})\n data, _status_code, _headers = post_users_with_http_info(users, opts)\n data\n end",
"def append_user_info(username, xml)\n end",
"def create\n @user = User.new(params[:user])\n get_list\n\n respond_to do |format|\n if @user.save\n flash[:notice] = \"User #{@user.fname} #{@user.lname} was successfully created.\"\n format.html { redirect_to(:action => :index) }\n format.xml { head :ok }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(:action=>\"index\") }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n if !current_user || is_admin?\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(:root, :notice => 'Registration successfull.') }\n #format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n #format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n else\n redirect_to :root\n end\n end",
"def create\n @user = User.new(params[:user])\n respond_to do |format|\n if @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(:action => :index) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\n @users = LinkedData::Client::Models::User.all\n respond_to do |format|\n format.html\n format.xml { render xml: @users.to_xml }\n end\n end",
"def create_user\n params = {\n :client_id => Swiftype.platform_client_id,\n :client_secret => Swiftype.platform_client_secret\n }\n post(\"users.json\", params)\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new_user(username, password, full_name, email)\n representation = form_encoded({ \"user[name]\" => username,\n \"user[password]\" => password,\n \"user[full_name]\" => full_name,\n \"user[email]\" => email }) \n puts representation\n begin\n response = open(@service_root + '/users', :method => :post, \n :body => representation)\n puts \"User #{username} created at #{response.meta['location']}\"\n rescue OpenURI::HTTPError => e\n response_code = e.io.status[0].to_i\n if response_code == \"409\" # Conflict\n puts \"Sorry, there's already a user called #{username}.\"\n else\n raise e\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n if @user.save\n respond_to do |format|\n format.json { render :json => @user.to_json, :status => 200 }\n format.xml { head :ok }\n format.html { redirect_to :action => :index }\n end\n else\n respond_to do |format|\n format.json { render :text => \"Could not create user\", :status => :unprocessable_entity } # placeholder\n format.xml { head :ok }\n format.html { render :action => :new, :status => :unprocessable_entity }\n end\n end\n end",
"def create_user(options = {})\n post \"/users\", options\n end",
"def save_user\n client = create_db_client\n client.query(\"INSERT INTO users(name, email, password, bio) VALUES('#{@name}', '#{@email}', '#{@password}', '#{@bio}')\")\n \n id = client.last_id\n rawData = client.query(\"SELECT * FROM users WHERE id='#{id}'\")\n users = Array.new\n rawData.each do |data|\n user = {:id => data[\"id\"], :name => data[\"name\"] ,:email => data[\"email\"], :password => data[\"password\"], :bio => data[\"bio\"]}\n users << user\n end\n response = Response.new('success', 'success input user', users)\n return response.response_api\n end",
"def index\n @users = User.all\n render :xml => @users\n end",
"def create_users(accountId, model) path = \"/api/v2/accounts/#{accountId}/users\"\n post(path, model, {}, AvaTax::VERSION) end",
"def create\n @user = User.new(user_params)\n @user.save\n respond_with @user\n end",
"def create\n\t\t@user = User.new(users_params)\n\t\tif @user.save\n\t\t\tjson_response(@user, \"User is created Successfully.\")\n\t\telse\n\t\t\trender json: {message: @user.errors.full_messages.join(\" \")}, status: 400\n\t\tend\t\t\n\tend",
"def create\n @user = User.new(params[:user])\n puts params[:user]\n respond_to do |format|\n if @user.save\n format.html { redirect_to :users, notice: 'Registration successful.' }\n format.json { render json: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create(name=\"Default name\")\n xml_req =\n \"<?xml version='1.0' encoding='UTF-8'?>\n <customer>\n <name>#{name}</name>\n </customer>\"\n\n request = Net::HTTP::Post.new(@url)\n request.add_field \"Content-Type\", \"application/xml\"\n request.body = xml_req\n\n http = Net::HTTP.new(@uri.host, @uri.port)\n response = http.request(request)\n\n response.body\n end",
"def user_create(username, email, password, tenant_id)\n\t\n\t\tuser = {\"user\" => {\"name\" => username, \"email\" => email, \"enabled\" => true, \"password\" => password, \"tenantid\" => tenant_id}}\n\t\n\t\tjson_string = JSON.generate(user)\n\t\n\t\tpost_call = Curl::Easy.http_post(\"#{@ip_address}:#{@port_2}/v2.0/users\", json_string\n\t\t) do |curl|\n\t\t\tcurl.headers['x-auth-token'] = @token\n\t\t\tcurl.headers['Content-Type'] = 'application/json'\n\t\tend\n\t\t\t\t\t\t\t\t\t \n\t\tparsed_json = JSON.parse(post_call.body_str)\n\t\t\n\t\tputs parsed_json\n\t\treturn parsed_json\n\tend",
"def post_users_with_http_info(users, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UsersApi.post_users ...'\n end\n # verify the required parameter 'users' is set\n if @api_client.config.client_side_validation && users.nil?\n fail ArgumentError, \"Missing the required parameter 'users' when calling UsersApi.post_users\"\n end\n # resource path\n local_var_path = '/users'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] || @api_client.object_to_http_body(users) \n\n # return_type\n return_type = opts[:return_type] || 'User' \n\n # auth_names\n auth_names = opts[:auth_names] || ['Bearer']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UsersApi#post_users\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def create\n @user = @application.users.create(user_params)\n\n if @user.valid?\n render json: @user, status: :created, location: api_application_user_path(@application,@user)\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n respond_with(@user, location: users_url, notice: 'User was successfully created.')\n else\n respond_with(@user)\n end\n end",
"def parseUserData(doc, params)\n \n real_name = (doc.find_first('//xmpp2rest/user/real_name')) ? doc.find_first('//xmpp2rest/user/real_name').content : nil\n password = (doc.find_first('//xmpp2rest/user/password')) ? doc.find_first('//xmpp2rest/user/password').content : nil\n \n if not real_name or not password\n raise Exception.new(\"Missing elements data for creating new user!\")\n end \n \n params.merge!({:real_name => real_name})\n params.merge!({:password => password})\n \n return params\n end",
"def new\n @user = User.new\n render :xml => @user\n end",
"def create\n @user = User.new(user_params)\n @user.admin = false\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to(root_url, notice: 'User was successfully created.') }\n format.xml { render xml: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.xml { render xml: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_user(attributes = {})\n elektron_identity.post(\"users\") { { user: attributes } }.body[\"user\"]\n end",
"def create_user(options = {})\n post :create, {:user => { :name => 'quire', :point_value => \"2\", :login => 'quire', :email => 'quire@example.com',\n :password => 'quire', :password_confirmation => 'quire' }.merge(options)}, {:user_id => \"1\"}\n end",
"def create\n @user = User.new(form_params)\n\n respond_to do |format|\n if @user.save\n format.json { render json: { users: @user }, status: :created }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_should_create_invite_via_API_XML\r\n get \"/logout\"\r\n post \"/invites.xml\", :api_key=>'testapikey',\r\n :invite => {:message => 'API Invite 1',\r\n :accepted => false,\r\n :email => 'test@email.com',\r\n :user_id => 1 }\r\n assert_response :created\r\n end",
"def create\n @user = User.new(params[:user])\n\trecipe_list = RecipeList.create\n\t@user.recipe_list = recipe_list\n respond_to do |format|\n if @user.save\n format.html { redirect_to(root_url, :notice => 'Registration successful') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n\tputs \"\\n \\t\\tin create\\n\" + params[:user].inspect\n @user = User.new(params[:user])\n\n\tputs @user.inspect\n respond_to do |format|\n if @user.save\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n logger.debug(\"AAA \" + params[:user][:password])\n\n @user = User.new(params[:user])\n respond_to do |format|\n if @user.save\n format.html { redirect_to(users_path, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n doc = Nokogiri::XML(request.body.read)\n bNode = doc.xpath('elwak/benutzer')\n\n @benutzer = Benutzer.new(benutzer_params(bNode))\n if @benutzer.save\n if bNode.xpath('objekt_zuordnungs').length > 0\n objekt_ids = bNode.xpath('objekt_zuordnungs/objekt_id').map{|oz| oz.text.to_s.to_i}\n @benutzer.setze_objekt_zuordnungen(objekt_ids)\n end\n success(@benutzer.id)\n else\n error(@benutzer.errors)\n end\n end",
"def users(name, args={})\n query = \"/?client_id=#{@client_id}&format=#{format.to_s}&name#{name}\"\n path = __method__.to_s\n http_post(path, query)\n end",
"def users\n\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n Mailer.deliver_registration_confirmation(@user)\n format.html { redirect_to( admin_users_path, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => admin_users_path }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => admin_users_path.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def me\n users(request(\"users/authenticate.xml\", :auth => true))\n end",
"def api_v11_users_post(opts = {})\n api_v11_users_post_with_http_info(opts)\n return nil\n end",
"def create\n @user = User.new(params[:user])\n @user.admin = params[:user].delete(:admin)\n respond_to do |format|\n if (@user.confirmed_at = Time.now) && @user.save\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to admin_users_path(:anchor => dom_id(@user)) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :new }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create user_name\n response = @client.action \"RegisterUser\", \"Name\" => user_name\n\n Response::User.new response.body['RegisterUserResponse']\n end",
"def index\n @users = User.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render xml: @users }\n end\n end",
"def list_users\n self.class.get('/users')\n end",
"def new\n @user = User.new\n @users = @firm.users.all\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def create\n puts 'Holaaaaaaaaaaaaaaaaaaaaaaaa'\n puts user_params\n @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: @user }\n puts @users\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n users = get_collection(User) || return\n\n respond_to do |format|\n format.xml { render xml: users.to_xml(only: DEFAULT_FIELDS, root: 'users', skip_types: 'true') }\n format.json { render json: users.to_json(only: DEFAULT_FIELDS) }\n end\n end",
"def userRegisterPost(email, name, password, password_confirmation)\n post register_path, params: {user: {email: email, name: name,\n password: password, password_confirmation: password_confirmation}}\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @user }\n end\n end",
"def create\n\t\t@user = User.new(params[:user])\n\n\t\trespond_to do |format|\n\t\t\tif @user.save\n\t\t\t\tformat.html { redirect_to(@user, :notice => 'User was successfully created.') }\n\t\t\t\tformat.xml { render :xml => @user, :status => :created, :location => @user }\n\t\t\telse\n\t\t\t\tformat.html { render :action => \"new\" }\n\t\t\t\tformat.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def create\n @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.html do\n redirect_to users_url,\n notice: I18n.t('activerecord.attributes.user.messages.created', name: @user.name)\n end\n format.json { render :show, status: :created, location: @user }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n flash[:notice] = \"User created!\"\n session[:current_user] = @user.name\n session[:current_user_id] = @user.id\n format.html { redirect_to(@user, :notice => 'User was successfully created.') }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n flash[:error] = \"Create user failed!\"\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\r\n @users = User.find(:all)\r\n \r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.xml { render :xml => @users.to_xml }\r\n end\r\n end"
] | [
"0.71678036",
"0.6338476",
"0.6224363",
"0.61548346",
"0.6088076",
"0.6079892",
"0.60536397",
"0.60094374",
"0.5940851",
"0.59352076",
"0.59313804",
"0.59236705",
"0.59006655",
"0.58788294",
"0.5857175",
"0.58492076",
"0.58427423",
"0.58262956",
"0.58248377",
"0.5821217",
"0.58131135",
"0.58091503",
"0.5792528",
"0.5791521",
"0.57853204",
"0.57838213",
"0.578127",
"0.5780058",
"0.57784057",
"0.57784057",
"0.57784057",
"0.57784057",
"0.57784057",
"0.57784057",
"0.57784057",
"0.57784057",
"0.5767466",
"0.5758253",
"0.5755529",
"0.5750517",
"0.5750517",
"0.5750517",
"0.5750517",
"0.5750517",
"0.5750517",
"0.5750517",
"0.5750517",
"0.5750517",
"0.5743413",
"0.5733758",
"0.57335615",
"0.5728242",
"0.57248116",
"0.57197785",
"0.5716902",
"0.57165825",
"0.5698319",
"0.56964135",
"0.56722647",
"0.5670073",
"0.56568635",
"0.5647387",
"0.5637585",
"0.56305486",
"0.56242114",
"0.5610217",
"0.5608538",
"0.5606493",
"0.5599364",
"0.55989724",
"0.55964243",
"0.5595968",
"0.559136",
"0.5588281",
"0.5558225",
"0.5552007",
"0.5551258",
"0.5536655",
"0.5524534",
"0.5517971",
"0.5517697",
"0.5511685",
"0.55057925",
"0.5502942",
"0.5494358",
"0.5492615",
"0.5491333",
"0.5485237",
"0.5477793",
"0.5476153",
"0.54688483",
"0.54683477",
"0.54633856",
"0.54598165",
"0.54497695",
"0.54471266",
"0.5444897",
"0.54437274",
"0.5440441",
"0.5440341",
"0.5436465"
] | 0.0 | -1 |
PUT /users/1 PUT /users/1.xml | def update
@user = User.find(params[:id])
# puts "\n\n\n @thiscompany.id = " + @thiscompany.id.to_s ##debug
y session #debug
respond_to do |format|
if @user.update_attributes(params[:user])
flash[:notice] = 'User was successfully updated.'
format.html { redirect_to(@user) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update\n @user = V1::User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'V1::User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update!\n @authorize = nil\n update_plan! &&\n resp = put(\"/users/#{username}.xml\", {\n :user_key => apikey,\n \"user[first_name]\" => first_name,\n \"user[last_name]\" => last_name\n })\n end",
"def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post 'update', opts\n end",
"def UpdateUser params = {}\n \n APICall(path: 'users.json',method: 'PUT',payload: params.to_json)\n \n end",
"def update(id, name= \"Updated Name\")\n xml_req =\n \"<?xml version='1.0' encoding='UTF-8'?>\n <customer>\n <id type='integer'>#{id}</id>\n <name>#{name}</name>\n </customer>\"\n\n request = Net::HTTP::Put.new(\"#{@url}/#{id}.xml\")\n request.add_field \"Content-Type\", \"application/xml\"\n request.body = xml_req\n\n http = Net::HTTP.new(@uri.host, @uri.port)\n response = http.request(request)\n\n # no response body will be returned\n case response\n when Net::HTTPSuccess\n return \"#{response.code} OK\"\n else\n return \"#{response.code} ERROR\"\n end\n end",
"def update(id, name=\"Updated Name\", age=\"55\")\r\n xml_req =\r\n \"<?xml version='1.0' encoding='UTF-8'?>\r\n <person>\r\n <id type='integer'>#{id}</id>\r\n <name>#{name}</name>\r\n <age>#{age}</age> \r\n </person>\"\r\n request = Net::HTTP::Put.new(\"#{@url}/#{id}.xml\")\r\n request.add_field \"Content-Type\", \"application/xml\"\r\n request.body = xml_req\r\n http = Net::HTTP.new(@uri.host, @uri.port)\r\n response = http.request(request)\r\n # no response body will be returned\r\n case response\r\n when Net::HTTPSuccess\r\n return \"#{response.code} OK\"\r\n else\r\n return \"#{response.code} ERROR\"\r\n end\r\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(users_url, :notice => \"User #{@user.name} was successfully updated.\") }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(users_url,:notice => \"User #{@user.name} was successfully updated.\") }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find_by_urlname(params[:id])\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = \"Account updated successfully\"\n format.html { redirect_to user_path(@user) }\n format.xml { head :ok }\n else\n flash[:error] = \"There were problems updating the profile\"\n format.html { render :action => 'edit' }\n format.xml { @user.errors.to_xml }\n end\n end\n end",
"def put(uri, xml)\r\n req = Net::HTTP::Put.new(uri)\r\n req[\"content-type\"] = \"application/xml\"\r\n req.body = xml\r\n request(req)\r\n end",
"def update_user(options)\n patch(\"/user\", options, 3)\n end",
"def modify_user(user)\n query_api_object Model::User, '/rest/user', user.to_hash, 'PUT'\n end",
"def test_should_update_invite_via_API_XML\r\n get \"/logout\"\r\n put \"/invites/1.xml\", :invite => {:message => 'API Invite 1',\r\n :accepted => false,\r\n :email => 'test@email.com',\r\n :user_id => 1 }\r\n assert_response 401\r\n end",
"def modify_user(user)\n query_api_object User, \"/rest/user\", user.dump(), \"PUT\"\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(root_path, :notice => 'Usuario alterado com sucesso.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def put user_id, options={}, headers={}\n @connection.put \"users/#{user_id}.json\", options, headers\n end",
"def updateUser\n options = {\n :body => params.to_json,\n :headers => {\n 'Content-Type' => 'application/json',\n 'Authorization' => request.headers['Authorization']\n }\n }\n results = HTTParty.put(\"http://192.168.99.101:4051/users/\"+@current_user[\"id\"].to_s, options)\n render json: results.parsed_response, status: results.code\n end",
"def update_user(id, accountId, model) path = \"/api/v2/accounts/#{accountId}/users/#{id}\"\n put(path, model, {}, AvaTax::VERSION) end",
"def update\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash.now[:notice] = 'Successfully updated.'\n format.html { render :action => \"edit\" }\n format.xml { head :ok }\n else\n flash.now[:error] = 'Could not update. Please see errors below...'\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(users_url, :notice => 'User has been updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to user_url(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors.to_xml }\n end\n end\n end",
"def update(context, name, should)\n res = context.transport.put_request(context, \"security/users/#{name}\", keys_to_camelcase(should))\n\n context.err(name, res.body) unless res.success?\n end",
"def update_user(user, options = {})\n put \"/users/#{user}\", options\n end",
"def update(id, params = {})\n request(:put, \"/users/#{id}\", body: params)\n end",
"def update_current_logged_in_user(args = {}) \n put(\"/users.json/current\", args)\nend",
"def update\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(users_path) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to root_url }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(:action => :index) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n #@user = User.find_by_id(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def rest_update(uri, method: Net::HTTP::Put)\n request = Net::HTTP::Get.new uri\n request.add_field(\"Accept\",\"application/xml\")\n auth_admin(request)\n \n Net::HTTP.start(uri.host, uri.port) do |http|\n response = http.request request\n response.value\n\n doc = REXML::Document.new response.body\n \n doc = strip_class_attributes(yield doc)\n \n request2 = method.new uri\n request2.content_type = 'application/xml'\n auth_admin(request2)\n\n request2.body=doc.to_s\n \n response2 = http.request request2\n response.value\n\n end\n \nend",
"def update\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find_by_id(params[:id])\n if @user.nil?\n redirect_back_or_default('/')\n end\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = t('users.updated')\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = current_org.users.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to @user, notice: 'user was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n user = User.find(params[:id])\n\n user.attributes = {\n name: params[:name]\n }\n\n user_save user\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to :action => :index }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n \n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(home_url()) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = \"User #{@user.username} was successfully updated.\"\n format.html { redirect_to(:action =>'show', :id => @user.id) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n head :ok\n else\n render :xml => @user.errors, :status => :unprocessable_entity\n end\n rescue\n render :nothing => true, :status => :not_found\n end",
"def update\n @user = User.find(params[:id])\n @user.update_attributes(params[:user])\n respond_with @user\n end",
"def update\n @user = User.find(params[:id])\n @user.update_attributes(params[:user])\n respond_with @user\n end",
"def update\n @user = User.find(params[:id])\n logger.info 'ffffff'\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def update_user\n end",
"def update\n @user = User.find(params[:id])\n \n respond_to do |format|\n if @user == current_user && @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def test_should_update_link_via_API_XML\r\n get \"/logout\"\r\n put \"/links/1.xml\", :link => {:user_id => 1,\r\n :title => 'API Link 1',\r\n :url => 'http://www.api.com'}\r\n assert_response 401\r\n end",
"def update\n render json: Users.update(params[\"id\"], params[\"user\"])\n end",
"def update\n @user_name = UserName.find(params[:id])\n\n respond_to do |format|\n if @user_name.update_attributes(params[:user_name])\n format.html { redirect_to(@user_name, :notice => 'User name was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user_name.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n user = @user_service.update_user(params[:id])\n render json: user, status: :ok\n end",
"def update_user\n @user = User.find(params[:id])\n @user.update(params[:user])\n redirect \"/users/#{@user.id}\"\nend",
"def update_user(id, attributes)\n elektron_identity.put(\"users/#{id}\") { { user: attributes } }.body[\n \"user\"\n ]\n end",
"def update\n if current_user.is_admin?\n @user = User.find(params[:id])\n @user.update_attributes!(params[:user])\n respond_to do |format|\n format.xml { render :xml => @user.to_xml }\n end\n else \n respond_to do |format|\n format.xml { render :text => \"error\" }\n end\n end\n rescue ActiveRecord::RecordInvalid\n respond_to do |format|\n format.xml do\n unless @user.errors.empty?\n render :xml => @user.errors.to_xml_full\n else\n render :text => \"error\"\n end\n end\n end\n end",
"def append_user_info(username, xml); end",
"def update(args)\n builder.update_rest(type, ref, args, username, password)\n self.elements(true)\n end",
"def update\n @user = User.find(self.current_user)\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:success] = 'You Have Successfully Updated Your Details'\n format.html { redirect_to user_url(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors.to_xml }\n end\n end\n end",
"def update\n @user = User.find(params[:id]) \n \n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to users_url, notice: 'User #{@user.name} was successfully created.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to @user, notice: 'User was successfully updated.' }\n format.xml { head :no_content }\n else\n format.html { render action: 'edit' }\n format.xml { render xml: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(admin_users_path, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = current_user\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(root_url, :notice => 'Successfully updated profile.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'Page was successfully updated.'\n format.html { redirect_to user_url(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors.to_xml }\n end\n end\n end",
"def update\n @user = @current_user\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to(@user, notice: 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :edit }\n format.xml { render xml: @user.errors, status: :unprocessable_entity }\n #render action: :edit\n end\n end\n end",
"def update\n @userinfo = Userinfo.find(params[:id])\n\n respond_to do |format|\n if @userinfo.update_attributes(params[:userinfo])\n flash[:notice] = 'Userinfo was successfully updated.'\n format.html { redirect_to(@userinfo) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @userinfo.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def append_user_info(username, xml)\n end",
"def update\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to([:admin, @user], notice: 'User was successfully updated.') }\n format.xml { head :ok }\n website.add_log(user: current_user, action: \"Updated user #{@user.name}\")\n else\n format.html { render action: \"edit\" }\n format.xml { render xml: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @email_user = Email::User.find(params[:id])\n\n respond_to do |format|\n if @email_user.update_attributes(params[:email_user])\n format.html { redirect_to(@email_user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @email_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def test_should_update_project_via_API_XML\r\n get \"/logout\"\r\n put \"/projects/1.xml\", :project => {:user_id => 1,\r\n :url => 'http://www.apiproject.com',\r\n :name => 'API Project',\r\n :description => 'API Project Desc' }\r\n assert_response 401\r\n end",
"def update\n @user = User.find(params[:id])\n get_list\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = \"User #{@user.fname} #{@user.lname} was successfully updated.\"\n format.html { redirect_to(:action => :index) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = @current_user\n respond_to do |format|\n if @user.update_attributes(user_params)\n format.html { redirect_to(@user, notice: 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render action: \"edit\" }\n format.xml { render xml: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_put_invoices_1_xml\n @parameters = {:invoice => {:number => 'NewNumber'}}\n \n Redmine::ApiTest::Base.should_allow_api_authentication(:put,\n '/invoices/1.xml',\n {:invoice => {:number => 'NewNumber'}},\n {:success_code => :ok})\n \n assert_no_difference('Invoice.count') do\n put '/invoices/1.xml', @parameters, credentials('admin')\n end\n \n invoice = Invoice.find(1)\n assert_equal \"NewNumber\", invoice.number\n \n end",
"def update\n @user = User.find(params[:id])\n \n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n format.html { redirect_back_or_default('/home') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @item.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n render json: User.update(params[\"id\"], params[\"user\"])\n end",
"def update_user(user_name:, user:)\n validate_user_name(:user_name, user_name)\n response = wrap_response(@connection.put(user_path(user_name), user))\n\n response.fmap { |r| SftpgoClient::ApiResponse.new(r.body) }\n end",
"def update\n respond_to do |format|\n if @v1_user.update(v1_user_params)\n format.html { redirect_to @v1_user, notice: 'User was successfully updated.' }\n format.json { render :show, status: :ok, location: @v1_user }\n else\n format.html { render :edit }\n format.json { render json: @v1_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update_attributes(params[:user])\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update_attributes(params[:user])\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n if @api_v1_user.update(api_v1_user_params)\n head :no_content\n else\n render json: @api_v1_user.errors, status: :unprocessable_entity\n end\n end",
"def update\n authorize! :edit, User\n @user = User.find(params[:id])\n return_url = users_url(:use_session => true)\n respond_to do |format|\n if @user.update_attributes(params[:user])\n do_extra_actions\n format.html { redirect_to return_url }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors.to_xml }\n end\n end\n end"
] | [
"0.66364235",
"0.6546457",
"0.63642347",
"0.62584895",
"0.62213796",
"0.6219046",
"0.6173277",
"0.61331743",
"0.6132418",
"0.6126342",
"0.61099374",
"0.6105844",
"0.61055833",
"0.6056526",
"0.603532",
"0.60333353",
"0.60158837",
"0.6012399",
"0.60051805",
"0.59823406",
"0.59800035",
"0.59730464",
"0.59730464",
"0.59730464",
"0.59730464",
"0.59730464",
"0.59730464",
"0.59730464",
"0.59730464",
"0.59730464",
"0.59730464",
"0.5965429",
"0.5960257",
"0.5959941",
"0.59444934",
"0.5942521",
"0.59408915",
"0.5936848",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.5930155",
"0.59300447",
"0.58786863",
"0.58632463",
"0.5861312",
"0.5858547",
"0.585658",
"0.58385205",
"0.58367634",
"0.58354694",
"0.58339876",
"0.5833853",
"0.58327675",
"0.5822188",
"0.5822188",
"0.5821609",
"0.58106184",
"0.58106184",
"0.5793121",
"0.57722884",
"0.5769284",
"0.5765553",
"0.5753685",
"0.57435024",
"0.57320344",
"0.5727437",
"0.57250416",
"0.57249486",
"0.5720997",
"0.5718121",
"0.57165307",
"0.57165015",
"0.5711656",
"0.5704572",
"0.570175",
"0.570125",
"0.56859815",
"0.5683272",
"0.56708294",
"0.5670272",
"0.5670232",
"0.56657696",
"0.5664049",
"0.56455255",
"0.5637211",
"0.5629555",
"0.56263584",
"0.56097674",
"0.5605429",
"0.5605429",
"0.56001157",
"0.55988777"
] | 0.0 | -1 |
DELETE /users/1 DELETE /users/1.xml | def destroy
@user = User.find(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to(users_url) }
format.xml { head :ok }
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def delete\n @user = User.find(params[:id])\n @user.rvsps.delete_all()\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def delete_users\n delete(users_path)\n end",
"def destroy\n @user = V1::User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @users = Users.find(params[:id])\n @users.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find_by_urlname(params[:id])\n @user.destroy\n \n respond_to do |format|\n flash[:notice] = \"User deleted from the system\"\n format.html { redirect_to users_path }\n format.xml { head :ok }\n end\n end",
"def destroy\n user = User.get(params[:id])\n user.destroy if user\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n #@user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url }\n format.xml { head :no_content }\n end\n end",
"def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(scriptwords_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(:first, :conditions => [\"id = ?\", params[:id]])\n @user.destroy\n respond_to do |format|\n format.html { redirect_to(users_path) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\nend",
"def destroy\r\n @user.destroy\r\n \r\n respond_to do |format|\r\n format.html { redirect_to users_url }\r\n format.xml { head :ok }\r\n end\r\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n respond_to do |format|\n format.html { redirect_to(admin_users_path) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @usuario = User.find(params[:id])\n @usuario.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n #@user = User.find_by_login(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def delete(context, name)\n res = context.transport.delete_request(context, \"security/users/#{name}\")\n\n context.err(name, res.body) unless res.success?\n end",
"def delete_user(id)\n elektron_identity.delete(\"users/#{id}\")\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end",
"def delete(id)\n request(:delete, \"/users/#{id}.json\")\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n website.add_log(user: current_user, action: \"Deleted user #{@user.name}\")\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n \n flash[:notice] = \"User #{@user.login} deleted\"\n \n respond_to do |format|\n format.html { redirect_to(space_users_path(@space)) }\n format.xml { head :ok }\n format.atom { head :ok }\n end\n end",
"def remove_user\n query_api '/rest/user', nil, 'DELETE'\n end",
"def destroy\n\t\tparams.permit!\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def user_delete(user_id)\n\t\tdelete_call = Curl::Easy.http_delete(\"#{@ip_address}:#{@port_2}/v2.0/users/#{user_id}\"\n\t\t) do |curl|\n\t\t\tcurl.headers['x-auth-token'] = @token\n\t\t\tcurl.headers['userId'] = user_id\n\t\tend\n\t\n\tend",
"def destroy\n redirect_to(:action=>\"index\") if session[:user_id] != params[:id].to_i\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user_name = UserName.find(params[:id])\n @user_name.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_names_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find_by_id(params[:id])\n if @user.nil?\n redirect_back_or_default('/')\n end\n\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n flash[:notice] = 'User was successfully deleted.'\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n end",
"def delete()\n response = send_post_request(@xml_api_delete_path)\n response.is_a?(Net::HTTPSuccess) or response.is_a?(Net::HTTPRedirection)\n end",
"def destroy\n @user = User.find(params[:id])\n if (session[:user] && session[:user].admin == 1)\n User.destroyCascade(@user)\n end\n \n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def delete_user\n end",
"def destroy\n @user = @current_user\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_back_or_default(users_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def delete_user_for_tenant(args = {}) \n delete(\"/tenants.json/#{args[:tenantId]}/users/#{args[:userId]}\", args)\nend",
"def destroy\n @email_user = Email::User.find(params[:id])\n @email_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(email_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n if current_user == @user\n @user.destroy\n \n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n else\n flash[:error] = \"Naughty naughty. You can't delete other people.\"\n end\n end",
"def destroy\n @usertogo = User.find(params[:id])\n @usertogo.destroy\n \n respond_to do |format|\n flash[:success] = \"User destroyed.\"\n format.html { redirect_to(root_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @userinfo = Userinfo.find(params[:id])\n @userinfo.destroy\n\n respond_to do |format|\n format.html { redirect_to(userinfos_url) }\n format.xml { head :ok }\n end\n end",
"def delete_user(userid) \n $db.execute('DELETE FROM users WHERE userid=?', userid)\n end",
"def delete_user(uid)\n begin\n RestClient.delete construct_url(\"user/#{uid}\")\n true\n rescue RestClient::BadRequest => e\n @last_error = e.http_body\n @last_error_code = e.http_code\n false\n end \n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_path) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def delete\n @user.destroy\n respond_to do |format|\n format.html { redirect_to v1_resources_users_all_path, notice: 'User was deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find_by_id(params[:id])\n @user.destroy\n #reset_session\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n User.cascade_delete(@user)\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :ok }\n end\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend"
] | [
"0.7177572",
"0.7172003",
"0.70611066",
"0.70607454",
"0.7031703",
"0.70033735",
"0.69609874",
"0.68964374",
"0.68964374",
"0.68916017",
"0.68899393",
"0.68882316",
"0.6878408",
"0.6876417",
"0.68727493",
"0.6872259",
"0.6872259",
"0.6872259",
"0.686118",
"0.6858945",
"0.6841222",
"0.6818538",
"0.6785725",
"0.6777712",
"0.6769458",
"0.6765244",
"0.6765244",
"0.6722511",
"0.66939366",
"0.6676845",
"0.66544235",
"0.66541135",
"0.6642127",
"0.6621156",
"0.6598033",
"0.65879655",
"0.65866137",
"0.65792215",
"0.65769917",
"0.6571811",
"0.655682",
"0.65493405",
"0.65440935",
"0.6540844",
"0.6532693",
"0.65297073",
"0.65224296",
"0.65177613",
"0.65102684",
"0.64982027",
"0.6494584",
"0.6494342",
"0.64921266",
"0.64917856",
"0.64766866",
"0.6475187",
"0.6466928",
"0.6459465",
"0.6459465"
] | 0.6912414 | 48 |
These methods are to be called via RubyAMF only (params[0][:whatever]) | def chargecredit
@user = User.find_by_username(params[0][:username])
user=User.authenticate(params[0][:username],params[0][:password])
if user
# make sure we charge at least 1 credit
if params[0][:module_cost] < 1
params[0][:module_cost] = 1
end
@user.credits -= params[0][:module_cost]
if @user.save
render :amf => { :id => @user.id,
:firstname => @user.firstname,
:lastname => @user.lastname,
:credits => @user.credits,
:company => @user.company
}
@userhistory=UserHistory.new
@userhistory.userid =user.id
@userhistory.module =params[0][:module]
@userhistory.credits_spent =params[0][:module_cost]
@userhistory.credits_remaining =@user.credits
@userhistory.save
else
render :amf => "Not enough credits to complete transaction"
end
else
render :amf => "Login Failed"
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params; end",
"def params=(_arg0); end",
"def params=(_arg0); end",
"def parse_parameters; end",
"def param; end",
"def param; end",
"def parsed_params\n \n end",
"def parameters=(_arg0); end",
"def get_parameters; end",
"def get_parameters; end",
"def params=(_); end",
"def parameters; end",
"def parameters; end",
"def parameters; end",
"def parameters; end",
"def parameters; end",
"def parameters; end",
"def parameters; end",
"def parameters; end",
"def query_params=(_arg0); end",
"def params(*); {}; end",
"def atk; param(2); end",
"def parameters=(_); end",
"def request_params; end",
"def params=(value); end",
"def request_parameters; end",
"def apis=(_arg0); end",
"def parse_input(params, resource); end",
"def query_parameters; end",
"def params() request.params end",
"def request=(_arg0); end",
"def request=(_arg0); end",
"def request=(_arg0); end",
"def a_param\n if @params.size > 1\n return @params[1]\n end\n return @params[0]\n end",
"def param\n params[0]\n end",
"def query_params; end",
"def parslet; end",
"def parslet; end",
"def parslet; end",
"def parslet; end",
"def params=(hash); end",
"def params=(hash); end",
"def params\n raise NotImplementedError\n end",
"def all_params; end",
"def raw_params(auth); end",
"def valid_params_request?; end",
"def preflight=(_arg0); end",
"def pha; sparam(3); end",
"def mig; bparam(0); end",
"def filter_parameters=(_arg0); end",
"def filter_parameters=(_arg0); end",
"def agi; param(6); end",
"def check_params; true; end",
"def method(p0) end",
"def probers=(_arg0); end",
"def stubbed_params=(_arg0); end",
"def query_parameters\n end",
"def unsolved_params\n \n end",
"def mhp; param(0); end",
"def first_argument(method)\n\n\n\n # 215:7: argument[method]\n argument(method)\n\n\n\n\n end",
"def signature=(_arg0); end",
"def signature=(_arg0); end",
"def signature=(_arg0); end",
"def signature=(_arg0); end",
"def params\n {}\n end",
"def amphibian_params\n base_params\n end",
"def api_only=(_arg0); end",
"def request(*args); end",
"def test_Method_InstanceMethods_parameters\n\t\tdef m(a,b=1,*c,&d); end\n\t\t# TODO, assert_equal([[:req,:a],[:opt,:b],[:rest,:c],[:block,:d]], method(:m).parameters)\n\tend",
"def params() @param_types end",
"def attributes=(_arg0); end",
"def arguments; end",
"def arguments; end",
"def arguments; end",
"def args(*) end",
"def endpoint=(_arg0); end",
"def valid_params?; end",
"def arguments=(_arg0); end",
"def payload=(_arg0); end",
"def auth_param; end",
"def spec=(_arg0); end",
"def filter_parameters; end",
"def filter_parameters; end",
"def type_params; end",
"def type_params; end"
] | [
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.70036066",
"0.6961356",
"0.6961356",
"0.6866602",
"0.6795609",
"0.6795609",
"0.6707428",
"0.6706965",
"0.66871923",
"0.66871923",
"0.6686437",
"0.65615684",
"0.65615684",
"0.65615684",
"0.65615684",
"0.65615684",
"0.65615684",
"0.65615684",
"0.65615684",
"0.64912546",
"0.64176077",
"0.63366956",
"0.6254684",
"0.6245591",
"0.6226085",
"0.6157957",
"0.6144796",
"0.6143703",
"0.6142303",
"0.6118162",
"0.61068493",
"0.61068493",
"0.61068493",
"0.6046092",
"0.60162747",
"0.601228",
"0.6009844",
"0.6009844",
"0.6009844",
"0.6009844",
"0.6006899",
"0.6006899",
"0.6004065",
"0.5989638",
"0.59649724",
"0.59546024",
"0.59438217",
"0.5910795",
"0.59104383",
"0.5887541",
"0.5887541",
"0.587835",
"0.5877713",
"0.5860623",
"0.58522725",
"0.58499366",
"0.58287275",
"0.5827407",
"0.5818337",
"0.5803667",
"0.57969034",
"0.57969034",
"0.57969034",
"0.57969034",
"0.57728624",
"0.5753313",
"0.5728136",
"0.5723459",
"0.5722021",
"0.5714996",
"0.5713755",
"0.57042986",
"0.57042986",
"0.57042986",
"0.5694672",
"0.56942",
"0.5688429",
"0.5685635",
"0.568514",
"0.56768525",
"0.56644326",
"0.5642434",
"0.5642434",
"0.5641624",
"0.5641624"
] | 0.0 | -1 |
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",
"def created_appointments\n Appointment.all(created_by: to_s)\n end",
"def my_appointments \n #look through all the appointments \n my_appointments == Appointment.all.select do |apt|\n apt.doctor == self \n end \n end",
"def patients\napps = []\nAppointment.all.each do |x|\n if x.doctor == self\n apps << x.patient\n end\nend\napps\nend",
"def appointments\nAppointment.all.select{|x| x.doctor == self}\nend",
"def appointments_on(date)\n appointments.starts_on(date).to_a\n end",
"def index\n @appointments = current_user.fetch_appointments\n end",
"def index\n @app_appointments = AppAppointment.all\n end",
"def approval\n @appointments = Appointment.in_clinic(@admin).requests.\n order_by_time.includes(:doctor, :patient).not_past\n end",
"def patients\n self.appointments.collect do |appointment|\n appointment.patient\n end\n end",
"def overview\n @my_appointments = current_user.appointments \n @my_user_hours = current_user.user_hours \n @recipient_appointment = RecipientAppointment.new \n end",
"def set_appointments\n @appointments = []\n latest_message = Message.order('created_at').last\n lines = latest_message.message_lines.where(order: params[:Body].split(' ').map(&:to_i))\n lines.each do |line|\n @appointments << line.appointment\n end\n end",
"def show\n @upcoming_appointments = Appointment.where('resident_id = ?', @resident.id)\n end",
"def test_has_many_appointments\r\n patient_appointment_count = @patient.appointments.count\r\n appointment_count = Appointment.count\r\n assert_not_equal(0, patient_appointment_count, \"No Appointment found for this patient.\")\r\n end",
"def appointments\n\n Appointment.all.select {|appointment| appointment.doctor == self}\n # binding.pry\n # [1,2,3,4,5].select { |num| num.even? }\n end",
"def index\n @appointments = Appointment.all\nend",
"def index\r\n @appointments = current_member.appointment\r\n end",
"def add_appointment(appointment)\n @appointments << appointment\n appointment.patient = self\n end",
"def appointments(params = {})\n scope 'user_schedule'\n get('schedule/appointments/', params)\n end",
"def index\n @appointments = Appointment.all\n end",
"def index\n @appointments = Appointment.all\n end",
"def index\n @appointments = Appointment.all\n end",
"def index\n @appointments = Appointment.all\n end",
"def index\n @appointments = Appointment.all\n end",
"def index\n @appointments = Appointment.all\n end",
"def index\n @appointments = Appointment.all\n end",
"def patients\n appointments.collect { |appt| appt.patient }\n end",
"def update_associated_appointments()\n if self.is_payed? # When the receipt is flagged as 'payed', make sure all appointments are too:\n # [Steve, 20100501] The added check on the structure of Appointments is\n # needed to be compliant with the previous version of the structure of the\n # table, otherwise the migration from older DB version fails.\n Appointment.update_all( \"is_payed=1\", ['receipt_id = ?', self.id] ) if Appointment.new.attributes.include?('receipt_id')\n end\n end",
"def load_appointments\n # Appointment\n return unless current_user\n @appointments = current_user.appointments\n\n clean_open_appointments = sanatize_open_appointments(current_user.open_appointments)\n @pending_requests = clean_open_appointments.group_by do |d|\n start_date = set_in_timezone(d.start_date, current_user.id)\n start_date.strftime('%A %B %d')\n end\n\n @in_progress_appointments = current_user\n .in_progress_appointments.group_by do |d|\n start_date = set_in_timezone(d.start_date, current_user.id)\n start_date.strftime('%A %B %d')\n end\n @scheduled_appointments = current_user.scheduled_appointments\n .group_by do |d|\n start_date = set_in_timezone(d.start_date, current_user.id)\n start_date.strftime('%A %B %d')\n end\n\n @past_appointments = past_appointments.group_by do |d|\n start_date = set_in_timezone(d.start_date, current_user.id)\n start_date.strftime('%A %B %d')\n end\n\n @appointments = current_user.appointments\n\n # Appointment Packs\n @appointment_packs = active_appointment_packs\n @past_appointment_packs = past_appointment_packs\n end",
"def associated_with_client\n self.contact_types = [ContactType.cliente.id]\n end",
"def patients\n self.appointments.collect do |a|\n a.patient\n end\n end",
"def show\n @customer = Customer.where(:id => params[:id], :company_id => current_user.company.id).first\n @appointments = Appointment.where(:company_id => current_user.company.id, :customer_id => @customer.id).order('starts_at DESC').paginate(:page => params[:page])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @customer }\n end\n end",
"def appointments\n Appointment.all.select do |appointment|\n appointment.patient == self\n #binding.pry\n end\n end",
"def patients\n self.appointments.collect do |appointment|\n appointment.patient\n end\n end",
"def patients\n self.appointments.collect do |appointment|\n appointment.patient\n end\n end",
"def index\n @appointments = current_user.appointments.order(\"booked_time\").includes(:patients)\n end",
"def patients\r\n appointments.map { |s|s.patient }\r\n end",
"def show\n @patient = Patient.find(params[:id])\n @appointments = Appointment.where(patient_id: @patient.id)\n end",
"def doctors\n self.appointments.map do |appointment|\n appointment.doctor\n end\n end",
"def add_appointment(appointment)\n @appointments << appointment\n appointment.patient = self\n #when you create an appt for a patient, you assign the appointment.patient attribute to the current instance of the patient\n end",
"def index\n if @laboratory\n @appointments = @laboratory.appointments.where(user_id: @user.id)\n else\n @appointments = @user.appointments.all\n end\n end",
"def client_tasks\n self.all(:conditions => {:client_task => true})\n end",
"def show\n #add appointments to the patients controller where patient_id is patient id ordered descending\n @appointments = Appointment.where(patient_id: @patient.id).order(\"created_at DESC\")\n end",
"def index\n @next_appointments = NextAppointment.all\n end",
"def patients\n appointments.map do |appointment|\n appointment.patient\n end\n end",
"def doctors\n appointments.map do |appointment|\n appointment.doctor\n end\nend",
"def new_appointment(doctor, date)\n Appointment.new(date, self, doctor)\nend",
"def index\n p \">>INICIO >>>>>>>>\"\n @appointments= Appointment.all\n p \">>>>>>>>>>\"\n y @appointments[0]\n if current_user.role.eql? \"Paciente\"\n #@appointments.where(:id => current_user.id, :user => @appointments.name)\n #p \">>>>>>>>>>\" + @appointments\n @user = current_user.name\n #----------- has_and_belongs_to_many\n #p @appointment << @appointment.find(params[:user=>@user])\n else\n @appointments = Appointment.all\n end\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @appointments }\n end\n end",
"def find_owner_appointments\n owner_appointments = Appointment.all.select { |appointment| appointment.owners.include?(self) || appointment.owner_id == id } \n if !owner_appointments.empty?\n owner_appointments\n else\n nil\n end\n end",
"def initialize(name)\n @name = name\n @appointments = []\n end",
"def initialize(name)\n @name = name\n @appointments = []\n end",
"def initialize(name)\n @name = name\n @appointments = []\n end",
"def initialize(name)\n @name = name\n @appointments = []\n end",
"def initialize(name)\n @name = name\n @appointments = []\n end",
"def doctors\n appointments.map do |appt|\n appt.doctor\n end\n end",
"def new_appointment(doctor, date)\n Appointment.new(date, self, doctor)\nend",
"def doctors \n self.appointments.collect do |a|\n a.doctor\n end\nend",
"def patients\n @appointments.collect do |appt|\n appt.patient\n end\n end",
"def get_appts\n @user = current_user\n @appointments = @user.appointments.actual.includes(:status, :address, :assignments, {:subscription => :subscriptionable}, :employees, :team)\n # filter by the datetime object via params from fullcalendar\n filter_show = ActiveSupport::JSON.decode(params[:filter_show])\n appointments_in_range = @appointments.where(\"appointments.start_time >= :start_time AND appointments.start_time <= :end_time\", {:start_time => Time.at(params['start'].to_i), :end_time => Time.at(params['end'].to_i)} )\n events = []\n appointments_in_range.each do |appointment|\n if appointment_is_allowed?(appointment, filter_show)\n customer = appointment.subscription.subscriptionable\n eventHash = {:id => appointment.id, :title => calendar_title(appointment, customer), :start => \"#{appointment.start_time.iso8601}\", :end => \"#{appointment.end_time.iso8601}\", :allDay => false, :recurring => appointment.subscription.repeat }\n\n eventHash[:backgroundColor] = event_background_color(appointment, params[:event_color])\n eventHash[:borderColor] = eventHash[:backgroundColor]\n\n events << eventHash\n # optional day view\n #events << {:id => event.id, :title => @customer_name, :url => \"/appointments/\"+event.id.to_s+\"/edit\", :description => \"Description here\", :start => \"#{event.start_time.iso8601}\", :end => \"#{event.end_time.iso8601}\", :allDay => true}\n end\n end\n render :json => events\n end",
"def clients\n @clients = Vendor.find(params[:id]).clients\n end",
"def doctors\n appointments.map do |appointment| appointment.doctor end\n end",
"def index\n @appointment = Appointment.new\n @appointments = Appointment.all\n end",
"def associations; end",
"def doctors\n appointments.map do |appointment|\n appointment.doctor\n end\n end",
"def doctors\n appointments.map do |appointment|\n appointment.doctor\n end\n end",
"def remaining_appointments_today\n Appointment.today.with_doctor(doctor_id).\n where(appointment_time: appointment_time+1.minute...DateTime.tomorrow)\n end",
"def attendees\n EventAttendee.find_all_by_event_id(self.id) \n end",
"def appointment_session\n @session.appointment\n end",
"def show\n\t\t#@today = DateTime.now.to_i\n\t\t@appointment = Appointment.find(params[:id])\n\t\t@client = Client.where(:client => @appointment.client).where(:profile => @appointment.profile).first\n\n\t\ttoday_start = @appointment.start\n\t\ttoday_end = today_start.end_of_day\n\t\t@day = today_start\n\n\t\t@schedule= [];\n\t\t\n\t\t@day_openings = Opening.where(:user => @user).where(\"start >= ? AND start <= ?\",today_start, today_end).order(:start)\n \t@day_client_appointments = Appointment.where(:client => @user).where(\"start >= ? AND start <= ?\",today_start, today_end).order(:start)\n \t@day_owner_appointments = Appointment.where(:owner => @user).where(\"start >= ? AND start <= ?\",today_start, today_end).order(:start)\n\t\t@schedule = @day_openings + @day_client_appointments + @day_owner_appointments\n\n\t\t@schedule.sort_by! do |item|\n\t item[:start]\n\t end\n\tend",
"def clients\n Client.all.select {|client| client.trainer == self}\n end",
"def patients\n self.appointments.map do |doctors_appts|\n doctors_appts.patient\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.60996526",
"0.6099143",
"0.60757154",
"0.6011403",
"0.59404504",
"0.59213334",
"0.5882427",
"0.58762264",
"0.5873757",
"0.58548284",
"0.58359104",
"0.5820886",
"0.58174855",
"0.5810769",
"0.5783",
"0.5772445",
"0.57662356",
"0.57565695",
"0.5749997",
"0.5749997",
"0.5749997",
"0.5749997",
"0.5749997",
"0.5749997",
"0.5749997",
"0.57363045",
"0.5718857",
"0.5713549",
"0.5702849",
"0.5681447",
"0.5665799",
"0.5659891",
"0.5657405",
"0.56568915",
"0.56474394",
"0.56422675",
"0.56220657",
"0.5605713",
"0.5561308",
"0.5557936",
"0.5544523",
"0.55351436",
"0.55292845",
"0.5527728",
"0.551663",
"0.55150664",
"0.5512474",
"0.5508787",
"0.5507772",
"0.5507772",
"0.5507772",
"0.5507772",
"0.5507772",
"0.54979557",
"0.5486849",
"0.5485448",
"0.54815483",
"0.5476392",
"0.54596466",
"0.54552466",
"0.54487354",
"0.54188526",
"0.540178",
"0.540178",
"0.53539884",
"0.5350925",
"0.53358793",
"0.5335108",
"0.5316523",
"0.5303096"
] | 0.74405485 | 1 |
The root frame maintains a cache of inflected element names. | def inflect element_name
@inflected[element_name] ||= Inflection.ruby_name(element_name).to_sym
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def naming_context\n @naming_context ||= blank_context(:this => self) do\n def method_missing(sym, *args)\n @this.element_names[sym] = *args\n end\n end\n end",
"def element_names\n @element_names ||= { }\n end",
"def element_root\n name.demodulize.underscore.pluralize\n end",
"def element_name; end",
"def available_element_names\n @_available_element_names ||= available_element_definitions.map { |e| e['name'] }\n end",
"def update_unique_names_of_children\n unless root?\n self.descendants.each do |descendant|\n descendant.update_unique_name\n end\n end\n end",
"def name\n @elements[:name]\n end",
"def element_parse_naming\n XML_ELEMENT_PARSE_NAMING\n end",
"def extract_localisedstrings(elem)\n elem.xpath(\"./string\").each do |s|\n s.name = elem.name\n end\n elem.replace(elem.children)\n end",
"def names\n @lock.synchronize do\n @root_objects.keys\n end\n end",
"def element_name() @stag.element_name end",
"def element_render_naming\n XML_ELEMENT_RENDER_NAMING\n end",
"def element_name\n @element_name ||= Utils.string_underscore(Utils.string_demodulize(name))\n end",
"def set_root_elements(root_elements, options={})\r\n @root_elements = root_elements \r\n @elements = options[:elements]\r\n @index = options[:index]\r\n @unresolved_refs = options[:unresolved_refs]\r\n @resolved_refs = nil \r\n # new unresolved refs, reset removed_urefs\r\n @removed_urefs = nil\r\n @changed = false\r\n end",
"def fix_names(context)\n fix_occurs\n @complexType.each { |x| x.fix_names(context) }\n\n # Process the four kinds of element declaration:\n # type and name; ref, complexType and name; empty and name\n\n if @type != nil\n raise 'internal error' if ! @name\n @type_ns, @type_local = XSD.lookup_QName(context, @type)\n @internal_name = ncname_to_element_method_name(@name)\n\n elsif @ref != nil\n raise 'internal error' if @name\n # TODO\n @ref_ns, @ref_local = XSD.lookup_QName(context, @ref)\n @internal_name = \"ref_to_#{@ref}\" # TODO: lookup ref's real name\n\n elsif 1 == @complexType.length\n raise 'internal error' if ! @name\n @internal_name = ncname_to_element_method_name(@name)\n\n elsif 0 == @complexType.length\n raise 'internal error' if ! @name\n\n else\n raise\n end\n\n if @name\n # Name is an ncname, so the namespace is always the current one\n @name_ns = context.current.namespace\n end\n\n # Check\n\n if @ref && @complexType.length != 0 ||\n @type && @complexType.length != 0 ||\n @ref && @type\n raise \"internal error: element with multiple ref, type or complexType\"\n end\n end",
"def root\n @elements[@root_name]\n end",
"def reload_name!\n clear_name_cache\n end",
"def parse_names(elem)\n nameList = elem.following_siblings()[0] #data_section.at(\"ul\")\n names = nameList.search(\"li\")\n @names = []\n names.each { |name|\n name = name.inner_html\n name.gsub! /\\s{2,}/, \" \"\n @names << name \n } \n end",
"def reset_names\n @names = {}\n compiler.reset_regs\n end",
"def get_html_name_attribute_value(tree)\n first = tree.delete_at(0)\n root_name = first[0]\n name = []\n prev = nil\n tree.each do |elem| \n if elem[1] == DefaultRepresentation || elem[1] == TimeWithZoneRepresentation || prev == AssociationsRepresentation\n name.push \"[#{elem[0]}]\"\n else\n name.push \"[#{elem[0]}_attributes]\"\n end\n prev = elem[1]\n end\n name.unshift(root_name)\n end",
"def element_render_naming\n OBJ_ELEMENT_RENDER_NAMING\n end",
"def element_parse_naming\n OBJ_ELEMENT_PARSE_NAMING\n end",
"def known_child_frames\n rules[:children].keys.map {|name| build_child_frame(name) }\n end",
"def start_element(name)\n # p \"#{@stack.last} #{@elements.last}\"\n @stack.push(name)\n @elements.push(Hash.new)\n # p \"#{name} started\"\n # p @stack\n\n case name\n when :cvList\n @cv_list = []\n when :cv\n @cv_list << @elements.last\n end\n end",
"def names \n all_forms\n end",
"def names #:nodoc:\n all_forms\n end",
"def avoid_duplicate_image_names(content)\n nodes = content.xpath(\"//draw:frame[@draw:name]\")\n nodes.each_with_index do |node, i|\n node.attribute('name').value = \"pic_#{i}\"\n node.xpath(\".//draw:image\").each do |draw_image|\n if !draw_image.attribute('href').nil?\n href = draw_image.attribute('href').value\n end\n unless href.to_s.empty?\n @global_image_paths_set.add(href) \n end\n end\n end\n end",
"def __elements\n @__elements ||= {}\n end",
"def research\n @name_parts.each_with_index do |name_part, index|\n @name_builtup << name_part\n\n # The last part should be the attribute name.\n if index == @name_parts.length - 1\n attribute_result = attribute_by_builtup\n next unless attribute_result\n\n @attribute = attribute_result.fetch(:name)\n break\n end\n\n # Try next - maybe next key need to be added? (which is common!)\n reflection_result = reflection_by_builtup\n next unless reflection_result\n\n @name_builtup = []\n reflection = reflection_result.fetch(:reflection)\n\n @current_clazz = reflection.klass\n @generated_name_classes << {clazz: @current_clazz, reflection: reflection}\n end\n end",
"def all_names; end",
"def all_names; end",
"def expand_name\n return [ name ] if root?\n return parent.expand_name.push( name )\n end",
"def element_render_naming\n JSON_ELEMENT_RENDER_NAMING\n end",
"def name\n @root\n end",
"def elements; @feature['elements'] ||= [] end",
"def element_name\n adapter.element_name\n end",
"def root(name)\n self._root = name\n end",
"def research\n @name_parts.each_with_index do |name_part, index|\n @name_builtup << name_part\n\n # The last part should be the attribute name.\n if index == @name_parts.length - 1\n if attribute_result = attribute_by_builtup\n puts \"Attribute was: #{attribute_result[:name]}\" if @debug\n @attribute = attribute_result[:name]\n break\n else\n puts \"Not found: #{@name_builtup.join(\"_\")}\" if @debug\n next\n end\n end\n\n # Try next - maybe next key need to be added? (which is common!)\n next unless reflection_result = reflection_by_builtup\n\n @name_builtup = []\n name = reflection_result[:name]\n reflection = reflection_result[:reflection]\n\n puts \"Name: #{name}\" if @debug\n puts \"Reflection: #{reflection}\" if @debug\n\n @current_clazz = reflection.klass\n @generated_name_classes << {clazz: @current_clazz, reflection: reflection}\n end\n end",
"def frame_locals(frame)\n #This is a stub, used for indexing\n end",
"def refresh_attributes\n self.name = name\n self.symbol = symbol\n self.label = label\n self.j_science = j_science\n end",
"def assign_names\n @nodes.select{|n| n.is_a? MFInput}.each { |n| assign_arc_name n}\n @nodes.select{|n| n.is_a? Output}.each { |n| assign_arc_name n}\n @nodes.select{|n| n.is_a? MFCallResult}.each { |n| assign_arc_name n}\n # by now, all assigned literals (loop variables) should be named\n @nodes.select{|n| n.is_a? MFIntLit}.each { |n| assign_arc_name n}\n @nodes.select{|n| n.is_a? MFStringLit}.each { |n| assign_arc_name n} # TODO combine with other lits\n end",
"def all_child_names\n get_all_child_lists\n return @all_child_names\n end",
"def get_elements_array\n element_names\n end",
"def qualified_name() element_name.qualified_name end",
"def reload\r\n translated_attribute_names.each { |name| @attributes.delete(name.to_s) }\r\n globalize.reset\r\n super\r\n end",
"def name\n @root_name\n end",
"def load_elements_global\n elements_array = self.get_elements\n\n modified_elements_array = Array.new\n elements_array.each_with_index do |element_object, index|\n #Get params for individual element, given the index\n element_configuration = self.get_individual_configuration(index, self.configuration)\n\n element_object_options = {\n :framework_object => self.framework_object,\n :screen_object => self.screen_object,\n :driver_object => self.driver_object,\n :blue_prints => element_configuration,\n :screen_name => self.screen_name,\n :element_name => (self.element_name + \"(#{index})\"),\n :element_object => element_object\n }\n\n new_element = AutomationObject::Element.new(element_object_options)\n\n this = self\n new_element.on :hook do |args|\n this.emit :hook, args\n end\n\n modified_elements_array.push(new_element)\n end\n\n self.elements_loaded = true\n return modified_elements_array\n end",
"def root_name\n return unless document.root\n\n document.root.name\n end",
"def reset!\n @root = Root.new(self)\n @request_methods_specified = Set.new\n @routes = []\n @named_routes = {}\n @variable_names = Set.new\n end",
"def elem_name\n elem_name = self.class.to_s.split('::').last.gsub(/([a-z])([A-Z])/, '\\1_\\2').downcase\n end",
"def element_parse_naming\n JSON_ELEMENT_PARSE_NAMING\n end",
"def initialize\n @name\n @@all << self\n end",
"def index\n authorize RegisteredElement\n institution = current_institution\n @elements = RegisteredElement.where(institution: institution).order(:name)\n @unaccounted_prefixes = institution.registered_element_prefixes -\n institution.element_namespaces.map(&:prefix)\n end",
"def set_xml_root_name(root_name)\n self.xml_root_name = root_name\n end",
"def children_names; @children.keys; end",
"def reset!\n @root = class_for_root.new(self, request_methods)\n @named_routes = {}\n @routes = []\n @grapher = Grapher.new(self)\n @priority_lookups = false\n @parser = Util::Parser.new(self, valid_regex)\n end",
"def root_menu_item_names\r\n root_menu_items.collect {|menu_item| menu_item.name}\r\n end",
"def lookup_model_names #:nodoc:\n @lookup_model_names ||= begin\n child_index = options[:child_index]\n names = object_name.to_s.scan(/(?!\\d)\\w+/).flatten\n names.unshift('locomotive')\n names.delete(child_index) if child_index\n names.each { |name| name.gsub!('_attributes', '') }\n names.freeze\n end\n end",
"def get_elements\n @current_page[:elements] = {}\n if @current_page[:page_data].user_data.has_key?('elements')\n @current_page[:page_data].user_data['elements'].each do |k, locator|\n @current_page[:elements][k] = @driver.find_element(locator).text\n end\n end \n end",
"def root\n @elements[@root]\n end",
"def elements\r\n return @elements if @elements\r\n @elements = []\r\n @root_elements.each do |e|\r\n @elements << e\r\n @elements.concat(e.eAllContents)\r\n end\r\n @elements\r\n end",
"def name(force_refresh = false)\n if @name && !force_refresh\n @name\n else\n @name = document.at('h1').text.strip rescue nil\n end\n end",
"def deep_symbolize!\n @name = @name.to_sym\n @children.each(&:deep_symbolize!)\n self\n end",
"def elements(elements = {})\n elements.each do |k,v|\n define_accessor(k.underscore, v)\n end\n @class_elements = elements\n end",
"def element_definitions\n @_element_definitions ||= element_definitions_by_name(element_definition_names)\n end",
"def render_descendants(name_counts)\n\n name_counts.each { |key, value| puts \"\\t<#{key}> = #{value}\"}\n return\n\n end",
"def name\n @doc.css('map').attr('name').value\n end",
"def append_name\n self.name = self.content\n end",
"def names\n @names ||= []\n end",
"def defined_names\n @defined_names ||= DefinedNames.new\n end",
"def initialize\n @base = ''\n @namehash = {}\n end",
"def all\n Hash[all_names.map {|name| [name, Global.send(name)]}]\n end",
"def get_root name\n\troot = name.dup\n\t%w{ _[^_]*bundle\n\t\t_prototype _demo _promo _game _core\n\t\t_(no_)?soundtrack(_only)? withsoundtrack _only_audio _audio _score\n\t\t_android_and_pc _android _linux _mac _windows _win _pc\n\t\t_freesong _song _remix\n\t\t_free _text _comic\n\t\t_goty _directorscut _alldlc\n\t\t_book _ebook _coloringbook _pdf _makingof _papercraft _artbook\n\t\t_excerpt _dlc _?premium _deluxe _asm}.each do |sfx|\n\t\troot.sub!(Regexp.new(sfx), '')\n\tend\n\troot.sub!(/_((vol|issue)\\d+)/, '/\\1')\n\t[\n\t\t[ /^aaaaaa_?/, 'aaaaaa' ],\n\t\t[ /^amnesia_/, 'amnesia' ],\n\t\t[ /^anomaly/, 'anomaly' ],\n\t\t[ /^bittrip/, 'bittrip' ],\n\t\t[ /^trine2_?/, 'trine2' ],\n\t\t[ /^trine_enhanced/, 'trine' ],\n\t\t[ /^kingdomrush?/, 'kingdomrush' ], # yes, there's one with a missing h\n\t\t[ /^(the)?blackwell/, 'blackwell' ],\n\t\t[ /^ftlfasterthanlight(_ae)?/, 'ftl' ],\n\t\t[ /^talisman_?/, 'talisman' ],\n\t\t[ /^catan_?/, 'catan' ],\n\t\t[ /^shadowgrounds_?/, 'shadowgrounds' ],\n\t\t[ /^theinnerworld_?/, 'theinnerworld' ],\n\t\t[ /^peteseeger_?/, 'peteseeger' ],\n\t\t[ /^tothemoon_?/, 'tothemoon' ],\n\t\t[ /^preteniousgame_?/, 'pretentiousgame' ],\n\t\t[ /^la[-_]mulana_?/, 'lamulana' ],\n\t\t[ /^oddworld_strangerswrath_?/, 'oddworld/strangerswrath'],\n\t]. each do |pair|\n\t\trx = pair.first\n\t\tbase = pair.last\n\t\troot = File.join(base, root.sub(rx,'')) if rx.match root\n\tend\n\troot.gsub!('_', '-')\n\treturn root\nend",
"def reset!\n @root = Node::Root.new(self, request_methods)\n @named_routes = {}\n @routes = []\n @grapher = Grapher.new(self)\n @priority_lookups = false\n end",
"def used_names; end",
"def document_root_element; end",
"def get_set_names\n page = agent.get \"file:\" + File.join(directory, \"sitemap.html\")\n\n\n rows = page.parser.css(SET_LINK_MATCHER % {element: \"small\"})\n values = rows.collect(&:text)\n self.set_names = values\n end",
"def identify doc = @doc\n doc.elements.first.name.to_sym\n end",
"def reset\n @@existing_names.delete(@name)\n @name = generate_name\n end",
"def cache_root!(key=nil, options={})\n if @context.controller.perform_caching\n raise \"cache_root! can't be used after JSON structures have been defined\" if @attributes.present?\n\n @cached_root = _cache_fragment_for([ :root, key ], options) { yield; target! }\n else\n yield\n end\n end",
"def form_elements(model_name, *field_names)\n options = field_names.extract_options!\n\n patterned_elements \"\\##{model_name}_%{element_name}\", *field_names, options.slice(:element_array)\n end",
"def wikinames\n $_wikinames ||= build_wikinames\n end",
"def names=(x)\n x = x.select { |name| !name.blank? }\n\n if x.length < self.name.length\n node_count = self.name.length - x.length\n trim_nodes_from_zero(:name, node_count)\n end\n\n x.each_with_index do |name, i|\n if self.name[i].nil?\n self.insert_new_node(:name)\n end\n\n self.name(i).name_part = name\n end\n end",
"def process_xml(xml)\n\t\t\txml.elements.each(\"*/*\") do |e|\n\t\t\t\tname = \"\"\n\t\t\t\te.attributes.each do |a|\n\t\t\t\t\tif a[0] == \"name\"\n\t\t\t\t\t\tname = a[1]\n\t\t\t\t\t\t@hash[name] = Hash.new\n\t\t\t\t\telse\n\t\t\t\t\t\t@hash[name][a[0]] = a[1]\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend",
"def attribute_render_naming\n XML_ATTRIBUTE_RENDER_NAMING\n end",
"def initialize(name)\n @children={}\n if name.kind_of? String\n\t\t\t\t@node_name=name.to_sym\n\t\t\telse\n\t\t\t\t@node_name=name\n\t\t\tend\n end",
"def parent_context\n parse\n return @names.last(@names.length-1).join('.') if !@names.empty?\n nil\n end",
"def genAllStruct\n cacheAllUnits\n builder = Nokogiri::XML::Builder.new { |xml|\n xml.allStruct {\n genDivChildren(xml, \"root\", Set.new)\n }\n }\n\n allStructDir = \"/apps/eschol/erep/xtf/style/textIndexer/mapping\"\n File.open(\"#{allStructDir}/allStruct-new.xml\", \"w\") { |io|\n io.write(builder.to_xml)\n }\n File.rename(\"#{allStructDir}/allStruct-new.xml\", \"#{allStructDir}/allStruct.xml\")\nend",
"def refresh_holder_map\n @holder_map = {}\n PACKET_FLOWS.each do |target,holder_name_list|\n holders = []\n holder_name_list.each do |name|\n holder = @token_holders[name]\n if holder\n holders << holder\n else\n holders = []\n break\n end\n end\n @holder_map[target] = holders\n end\n end",
"def reload\n begin_reset_model\n clear\n\n @items_to_models = Hash.new\n @models_to_items = Hash.new\n @names_to_item = Hash.new\n @items_metadata = Hash[self => Metadata.new([], [], Set.new)]\n @resolver_from_model = Hash.new\n\n seen = Set.new\n sorted_roots = @root_models.\n sort_by(&:priority).reverse\n\n sorted_roots.each do |root_model|\n models = discover_model_hierarchy(root_model.model, root_model.categories, root_model.resolver, seen)\n models.each do |m|\n @resolver_from_model[m] = root_model.resolver\n end\n end\n\n rowCount.times do |row|\n compute_and_store_metadata(item(row))\n end\n self.horizontal_header_labels = [\"\"]\n ensure\n end_reset_model\n end",
"def root(stubborn=false)\n\n previous = nil\n current = @h\n\n exps = @context.storage.find_expressions(\n h.fei['wfid']\n ).each_with_object({}) { |exp, h|\n h[exp['fei']] = exp\n }\n\n while current && current['parent_id']\n previous = current\n current = exps[current['parent_id']]\n end\n\n current ||= previous unless stubborn\n\n current ? Ruote::Exp::FlowExpression.from_h(@context, current) : nil\n end",
"def used_names=(_arg0); end",
"def store_original_as_translation\n unless self.original_name_id.nil?\n self.tag_id = self.original_name_id\n end\n end",
"def all_names\n @__names__\n end",
"def replace_names!(former,nname)\n # Stop here if the name is redeclared.\n return if self.each_type.find {|type| type.name == former }\n return if self.each_systemT.find {|systemT| systemT.name == former }\n return if self.each_inner.find {|inner| inner.name == former }\n # Recurse on the internals.\n replace_names_subs!(former,nname)\n end",
"def locate\r\n if @how == :jssh_name\r\n @element_name = @what\r\n elsif @how == :xpath\r\n @element_name = element_by_xpath(@container, @what)\r\n else\r\n @element_name = locate_tagged_element('A', @how, @what)\r\n end\r\n @o = self\r\n end",
"def search keyword\n result = Set.new\n matched = Array.new\n @frame_tree_root_node.each{|node|\n if node.content =~ /#{keyword}/i\n matched << node.name\n end\n } \n @frame_tree_root_node.each{|node|\n if node.is_root?\n result << node.name\n elsif matched.include? node.name\n result << node.name #add id\n node.parentage.each{|item|\n result << item.name\n }\n end\n }\n @frame_tree_root_node.print_tree\n result\n end",
"def each_dynamicall_mapped_frame(&block)\n available_frames.each do |frame_name|\n if has_property?(\"#{frame_name}_frame\")\n yield(frame_name)\n end\n end\n supercall(nil, :each_dynamicall_mapped_frame, &block)\n end",
"def name\n @changed_values[:name] || @document.root.attributes[\"refObjectName\"]\n end",
"def element_names_for(page_layout)\n if definition = get(page_layout)\n definition.fetch(\"elements\", [])\n else\n Rails.logger.warn \"\\n+++ Warning: No layout definition for #{page_layout} found! in page_layouts.yml\\n\"\n []\n end\n end"
] | [
"0.6115307",
"0.5649695",
"0.5585458",
"0.5366385",
"0.5331974",
"0.52540797",
"0.5131589",
"0.51292133",
"0.5065743",
"0.5063234",
"0.50502616",
"0.5047234",
"0.49618095",
"0.4950259",
"0.49476597",
"0.49397922",
"0.4916368",
"0.4910693",
"0.49059927",
"0.4901552",
"0.48580775",
"0.48447648",
"0.48434803",
"0.4814073",
"0.480558",
"0.48040122",
"0.4792405",
"0.4743019",
"0.47157314",
"0.46889037",
"0.46889037",
"0.46823636",
"0.467012",
"0.4666511",
"0.4665149",
"0.46610442",
"0.4632471",
"0.46033186",
"0.46017477",
"0.45956263",
"0.45558485",
"0.45537207",
"0.45289764",
"0.45278764",
"0.45213798",
"0.45168474",
"0.45107964",
"0.45060205",
"0.4492329",
"0.44893363",
"0.44889426",
"0.4455717",
"0.44487172",
"0.44253975",
"0.44242668",
"0.44166505",
"0.44151935",
"0.44094142",
"0.43920854",
"0.43825933",
"0.43757153",
"0.43718413",
"0.4367065",
"0.43650648",
"0.43603656",
"0.43400005",
"0.43379495",
"0.43034682",
"0.42967728",
"0.42950413",
"0.42930052",
"0.42894712",
"0.42885187",
"0.4287908",
"0.42850164",
"0.42838132",
"0.42818236",
"0.42791277",
"0.4272099",
"0.4257841",
"0.42493996",
"0.42491487",
"0.42490163",
"0.42449993",
"0.42398927",
"0.42326188",
"0.42311832",
"0.42308775",
"0.42293644",
"0.4227752",
"0.42166343",
"0.4215208",
"0.42123976",
"0.42117",
"0.42096525",
"0.42089137",
"0.42053106",
"0.42027986",
"0.41997916",
"0.41984645"
] | 0.53718483 | 3 |
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 = (idx..@children.length-1).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",
"def index # :nodoc:\n @index ||= begin\n index = {}\n \n @tree.contents.each do |obj|\n key = obj.name\n if obj.respond_to?(:contents)\n index[key.to_sym] = obj\n else\n index[string(key)] = to_entry(obj)\n end\n end if @tree\n @tree = nil\n \n index\n end\n end",
"def each_child_index\n end",
"def index_depth\n @index_depth ||= first_record_key[/\\+*/].length\n end",
"def init_indexes\n @image_indexes = @conditions.collect.with_index { |condition, index| condition ? index : nil }\n @image_indexes.compact!\n end",
"def compute_index \n self.rewind\n r = %r{\\<scan\\snum\\=\\\"(\\d+)\\\"|\\<spectrum\\sid\\=\\\"(\\d+)\\\"}\n index = {}\n while (!self.eof) \n pos = self.pos\n if (r.match(self.readline)) then \n m = $1 ? $1 : $2\n index[m.to_i] = pos\n end\n end\n index\n end",
"def build\n # Note: @index_definitions will only contain multiple elements in case of a composite type.\n @index_definitions.each do |type_def|\n @logger.info(\"INDEXING\") { \"Building index of type #{type_def[\"type\"]}\" }\n rdf_type = type_def[\"rdf_type\"]\n number_of_documents = count_documents(rdf_type)\n @logger.info(\"INDEXING\") { \"Found #{number_of_documents} documents to index of type #{rdf_type} with allowed groups #{@search_index.allowed_groups}\" }\n batches =\n if @max_batches && (@max_batches != 0)\n [@max_batches, number_of_documents / @batch_size].min\n else\n number_of_documents / @batch_size\n end\n batches = batches + 1\n @logger.info(\"INDEXING\") { \"Number of batches: #{batches}\" }\n\n Parallel.each(1..batches, in_threads: @number_of_threads) do |i|\n batch_start_time = Time.now\n @logger.info(\"INDEXING\") { \"Indexing batch #{i}/#{batches}\" }\n failed_documents = []\n\n @sparql_connection_pool.with_authorization(@search_index.allowed_groups) do |sparql_client|\n document_builder = MuSearch::DocumentBuilder.new(\n tika: @tika,\n sparql_client: sparql_client,\n attachment_path_base: @attachment_path_base,\n logger: @logger\n )\n document_uris = get_documents_for_batch rdf_type, i\n document_uris.each do |document_uri|\n @logger.debug(\"INDEXING\") { \"Indexing document #{document_uri} in batch #{i}\" }\n document = document_builder.fetch_document_to_index(\n uri: document_uri,\n properties: type_def[\"properties\"])\n @elasticsearch.insert_document @search_index.name, document_uri, document\n rescue StandardError => e\n failed_documents << document_uri\n @logger.warn(\"INDEXING\") { \"Failed to index document #{document_uri} in batch #{i}\" }\n @logger.warn { e.full_message }\n end\n end\n @logger.info(\"INDEXING\") { \"Processed batch #{i}/#{batches} in #{(Time.now - batch_start_time).round} seconds.\" }\n if failed_documents.length > 0\n @logger.warn(\"INDEXING\") { \"#{failed_documents.length} documents failed to index in batch #{i}.\" }\n @logger.debug(\"INDEXING\") { \"Failed documents: #{failed_documents}\" }\n end\n end\n end\n end",
"def check_index_finder\n # Leave it alone\n end",
"def optimize_index!\n @domain_index.each do |key, val|\n # Sort each path/name_key pair by the longest path\n @domain_index[key].sort! { |a, b|\n b[0].size <=> a[0].size\n }.uniq!\n end\n end",
"def build_index!\n puts \"build_index!\"\n @indexes = {}\n \n @indexes = @resource_class.build_indexes(@resources)\n @indexes[:_default] ||= @default_order\n end",
"def build_current_children_and_evaluate! opts={}\n these_asserts\n @current.clear\n if (@start_offset > final_offset) # see :note3\n @done = true\n evaluate_ok!\n return nil\n end\n @ok = nil\n @done = false\n @children_productions = production.children\n @ctxt = parse_context\n (start_offset..@children.length-1).each do |idx|\n @current.push idx\n break unless build_this_child_and_keep_going?(idx, opts)\n end\n @children_productions = nil\n @ctxt = nil\n evaluate_ok!\n nil\n end",
"def add_pages_for_scan!\n @pages_for_scan = []\n @bad_pages = []\n @pages.each do |page|\n @bad_pages << page.page_url unless page.page_a_tags\n next unless page.page_a_tags\n page.home_a.each do |link|\n @pages_for_scan << link\n end\n end\n end",
"def parseIndexPage(page)\n folders = []\n # ASF main page references currently look like this: <a href=\"abdera/\">abdera/</a>\n # the Perl script looked for this match: m!> ?$dir/?<!\n links = page.scan(%r{<a href=['\"]([.a-z0-9-]+)/?['\"](?: title=['\"][.a-z0-9-]+/?['\"])?>([.a-z0-9-]+)/?</a>})\n links.each { |l|\n if l[1] == l[0]\n folders << l[1]\n end\n }\n folders\nend",
"def scan(**kw)\n result = (parse(**kw) + errors + @stack.flatten).uniq.sort_by {|e| [*e.pos, (e.message ? -1 : 0)]}\n result.each_with_index do |e, i|\n if e.event == :on_parse_error and e.tok.empty? and (pre = result[i-1]) and\n pre.pos[0] == e.pos[0] and (pre.pos[1] + pre.tok.size) == e.pos[1]\n e.tok = pre.tok\n e.pos[1] = pre.pos[1]\n result[i-1] = e\n result[i] = pre\n end\n end\n result\n end",
"def scan\n @time_cache = {}\n\n entries = parse_entries\n grouped_entries = group_entries entries\n\n doc = create_document grouped_entries\n\n @top_level.comment = doc\n\n @top_level\n end",
"def update_index\n all.nodes.each do |n|\n n.reindex!\n end\n end",
"def process(url, depth)\n @urls_indexed[url] = true\n\n page = agent.get(url)\n\n # Do not handle images etc.\n return unless page.instance_of?(Mechanize::Page)\n\n # Do the actual indexing / analytics\n @callback.call(page, url)\n\n # Process all the links\n page.links.each do |link|\n index link.href, depth + 1\n end\n end",
"def generate_indexes\n @first_page = first_page\n generate_index('index')\n generate_index('indexes')\n end",
"def search_for_selectors(search, expectedCount)\n # get all links for current page\n links = get_position_links\n # count used to put all information for 1 position in 1 array\n count = 1\n # link_index used to add the appropriate links to array\n link_index= 0\n # Sub array that will hold the information of 1 position\n job_content = []\n # Super array that holds information of all positions\n job_array = []\n @page.search(search).each do |selector|\n job_content << selector.text.strip\n if count % expectedCount == 0\n job_content << links[link_index]\n link_index += 1\n job_array << job_content\n job_content = []\n end\n count += 1\n end\n # Return super array\n job_array\n end",
"def create_index_nodes_for_children(root_element)\n self.child_nodes.keys.each do |association_name|\n association_value = send(association_name)\n\n Array(association_value).each do |child_node|\n child_node.create_index_node(root_element)\n end\n end\n end",
"def build_indices\n template_cache = RDoc::Cache.instance\n\n @info.each do |toplevel|\n @files << RDoc::Generator::File.new(template_cache, toplevel, @options,\n RDoc::Generator::FILE_DIR)\n end\n\n RDoc::TopLevel.all_classes_and_modules.each do |cls|\n build_class_list(template_cache, cls, @files[0], RDoc::Generator::CLASS_DIR)\n end\n end",
"def index_page_scrape(html, r_url, resource)\n count = Selector.where(scrape_resource_id: resource.id, top_level: true).reduce(0) do |acc, ts|\n # an array of all the top-level items for a given tag. these are nokogiri nodes\n blocks = html.css(ts.selector)\n\n blocks.each do |block| # iterates over Nokogiri nodeset for given css selector\n # logger.info \"scraping index page with block: #{block}\"\n\n # creates a model with default scrape resource info set\n # logger.info 'CREATING NEW TEMPLATE MODEL'\n new_model = ts.model.new(scrape_resource_id: resource.id,\n url: r_url.url,\n institution_id: resource.institution_id,\n public: true)\n\n iterate_children(ts, block, new_model)\n\n # saves new model and increments count if it was inputted\n acc + 1 if validate_and_save(new_model)\n end # end items iteration\n end # end selector iteration\n count\n end",
"def index(hash)\n matches_by_token = {}\n hash.each do |field_name, value|\n @tokeniser.tokens_for_value(value, field_name).each do |token|\n matches_by_token[token] ||= []\n matches_by_token[token] << Match.new(hash, field_name)\n end\n\n @field_mapping[hash['_type']] ||= Set.new\n @field_mapping[hash['_type']] << field_name\n end\n\n # Put the matches into the appropriate index depending on token type\n matches_by_token.each do |token, match_list|\n index_type = ZDSearch::BinaryTreeSearchIndex._symbol_for_type(token.class)\n index = @index_trees[index_type]\n # True/false don't support greater than/less than operators on each other. So,\n # we have to store them in the binary tree as zero/one - but they still need to be in their own\n # tree so we don't return integers when looking for bools (or vice versa)\n token = (token ? 1 : 0) if index_type == :boolean\n existing_matches = index[token] ||= []\n # Mutates existing_matches in-place to avoid having to look it up\n # in the tree again\n existing_matches.concat match_list\n end\n end",
"def crawl\n while NG_URL.where(:a_hrefs_unprocessed => { :$not => { :$size => 0}}).count > 0 do\n next_unprocessed_url\n end\n end",
"def parse\n #Target\n doc = nokogiriDoc(@target)\n \n doc.xpath(\"//#{@xmlns}spectrum_query\").each do |query|\n count = query.xpath(\".//#{@xmlns}search_hit\").length\n 1.upto(count) {|i| @matches << psm(query, \"1\", i)}\n end\n GC.start # More memory can be salvaged by placing this before the end, but speed greatly declines.\n \n #Decoy\n doc = nokogiriDoc(@decoy)\n \n doc.xpath(\"//#{@xmlns}spectrum_query\").each do |query|\n count = query.xpath(\".//#{@xmlns}search_hit\").length\n 1.upto(count) {|i| @matches << psm(query, \"-1\", i)}\n end\n GC.start\n end",
"def initialize(matching_index, pointer)\n # Matching files with other indexes than CRC\n # map< ( file_info | segment_info ), matching_pointer_info >\n # map< ( FileInfo | SegmentInfo ), MatchingIndexSinglePointer >\n @matching_files = {}\n @crc_matching_files = {}\n @score_max = compute_score_max(pointer)\n # First find CRC matching files\n if (matching_index.indexes.has_key?(:crc))\n matching_index.indexes[:crc].each do |data, lst_pointers|\n @crc_matching_files.concat(lst_pointers)\n end\n end\n # Then all other indexes\n matching_index.indexes.each do |index_name, index_data|\n if (index_name != :crc)\n index_data.each do |data, lst_pointers|\n lst_pointers.each do |matching_pointer|\n if (!@crc_matching_files.has_key?(matching_pointer))\n @matching_files[matching_pointer] = MatchingIndexSinglePointer.new if (!@matching_files.has_key?(matching_pointer))\n @matching_files[matching_pointer].score += COEFFS[index_name]\n @matching_files[matching_pointer].indexes[index_name] = [] if (!@matching_files[matching_pointer].indexes.has_key?(index_name))\n @matching_files[matching_pointer].indexes[index_name] << data\n end\n end\n end\n end\n end\n matching_index.segments_metadata.each do |segment_ext, segment_ext_data|\n segment_ext_data.each do |metadata_key, metadata_data|\n metadata_data.each do |metadata_value, lst_pointers|\n lst_pointers.each do |matching_pointer|\n if (!@crc_matching_files.has_key?(matching_pointer))\n @matching_files[matching_pointer] = MatchingIndexSinglePointer.new if (!@matching_files.has_key?(matching_pointer))\n @matching_files[matching_pointer].score += COEFF_SEGMENT_METADATA\n @matching_files[matching_pointer].segments_metadata[segment_ext] = {} if (!@matching_files[matching_pointer].segments_metadata.has_key?(segment_ext))\n @matching_files[matching_pointer].segments_metadata[segment_ext][metadata_key] = [] if (!@matching_files[matching_pointer].segments_metadata[segment_ext].has_key?(metadata_key))\n @matching_files[matching_pointer].segments_metadata[segment_ext][metadata_key] << metadata_value\n end\n end\n end\n end\n end\n # Find matching blocks' CRC sequences\n lst_crc = (pointer.is_a?(FileInfo) ? pointer.crc_list : pointer.segment.crc_list)\n @matching_files.each do |matching_pointer, matching_info|\n if (matching_info.indexes.has_key?(:block_crc))\n lst_common_crc = matching_info.indexes[:block_crc]\n # Get the list of blocks' CRC from the file\n lst_matching_crc = (matching_pointer.is_a?(FileInfo) ? matching_pointer.crc_list : matching_pointer.segment.crc_list)\n # Parse the original file and get to a matching CRC\n idx_crc = 0\n while (idx_crc < lst_crc.size)\n while ((idx_crc < lst_crc.size) and\n (!lst_common_crc.include?(lst_crc[idx_crc])))\n idx_crc += 1\n end\n if (idx_crc < lst_crc.size)\n first_crc = lst_crc[idx_crc]\n # We are at the beginning of a sequence in the original file.\n smallest_sequence_size = lst_crc.size - idx_crc\n # Find all the occurences of this sequence in the matching file.\n lst_matching_crc.each_with_index do |matching_crc, idx_matching_crc|\n if (matching_crc == first_crc)\n # We are at the beginning of a sequence in the matching file\n idx_sequence = 1\n # Get the matching sequence\n matching_sequence = [first_crc]\n while ((idx_crc+idx_sequence < lst_crc.size) and\n (idx_matching_crc+idx_sequence < lst_matching_crc.size) and\n (lst_crc[idx_crc+idx_sequence] == lst_matching_crc[idx_matching_crc+idx_sequence]))\n matching_sequence << lst_crc[idx_crc+idx_sequence]\n idx_sequence += 1\n end\n if (matching_sequence.size > 1)\n # There is a matching sequence\n offset = idx_crc*FileInfo::CRC_BLOCK_SIZE\n matching_info.block_crc_sequences[offset] = {} if (!matching_info.block_crc_sequences.has_key?(offset))\n matching_info.block_crc_sequences[offset][idx_matching_crc*FileInfo::CRC_BLOCK_SIZE] = matching_sequence\n smallest_sequence_size = matching_sequence.size if (matching_sequence.size < smallest_sequence_size)\n # For each successful sequence, increase the score\n matching_info.score += (COEFF_BLOCK_CRC_SEQUENCE * matching_sequence.size)\n end\n end\n end\n idx_crc += smallest_sequence_size\n end\n end\n end\n end\n end",
"def scan\n @top_level.comment = remove_private_comments(@content)\n @top_level.parser = self.class\n @top_level\n end",
"def index_pages\n debug_msg \" generating pages search index\"\n\n pages = @files.select do |file|\n file.text?\n end\n\n pages.each do |page|\n debug_msg \" #{page.page_name}\"\n record = page.search_record\n @index[:searchIndex] << search_string(record.shift)\n @index[:longSearchIndex] << ''\n record.shift\n @index[:info] << record\n end\n end",
"def get_results()\n restriction_nodes = []\n result_nodes = []\n if !(@inputs.nil? || @inputs.empty? || @inputs.first.empty?)\n input_set = @inputs.first\n restriction_nodes= input_set.nodes\n result_nodes = input_set.breadth_first_search(true){|node| node.item.text.downcase.include?(@keyword_phrase.to_s.downcase)} \n end\n \n if !@inplace\n results = @server.match_all(parse_keyword_phrase(), restriction_nodes) \n result_nodes = results.map{|item| Xplain::Node.new(item: item)}\n end\n \n result_nodes\n \n end",
"def update_index\n all.each do |n|\n n.update_index\n end\n end",
"def each_index\n return enum_for(:each_index) unless block_given?\n\n each_index_root_page_number do |page_number|\n yield index(page_number)\n end\n\n nil\n end",
"def rescan\n\n roots = MissingTypes::missing_roots\n types = MissingTypes::missing_types\n\n types.each_with_index do |missing, i|\n\n # if missing type itself contains missing items, we need to fix that root first !\n next if(MissingTypes::missing_root_key?( missing.type ) )\n\n # Clone missing type nodes as children of the composer.\n # TODO - Right now, flag no update MissingTypes and delete it from types regardless\n # if found or not to stop infinite recursion when Type never defined !\n # this is because we only check in memory - the single read_from_xsd,\n # so need better persistent mechanism to flag missing types to enable rescan\n # after another file read\n #\n clone_or_share_existing( missing.type, missing.composer, false)\n \n types.delete_at(i)\n\n # Decrement the missing root count, and delete all together once no nodes left\n roots.delete_if { |k,v| roots[k] = roots[k] - 1 if(k == missing.root); roots[k] == 0 }\n end \n \n # Try to ensure infinite loop not possible\n rescan unless(roots.nil? || roots.empty? || types.nil? || types.empty?)\n end",
"def process_hardlinks\n counter = 0\n @hardlinks.each do |file, target|\n counter += 1 \n\n # in case of recursive redirects, which shouldn't happen, but alas\n recursion = 0\n while @hardlinks[target] && recursion < 3\n recursion += 1\n target = @hardlinks[target]\n end\n\n # we'll just traverse the index and fetch the coords of the target\n sha1, firstfour = sha1_w_sub(file)\n sha1_target, firstfour_target = sha1_w_sub(target)\n\n entries = @index[firstfour_target]\n next if entries.nil?\n\n target = entries.select {|entry| entry.sha1 == sha1_target}\n\n # it really shouldn't be empty... if it is - the redirect is useless\n # anyway\n unless target.empty? \n entry = target[0].dup # so we don't overwrite the original\n\n # we just reuse the same entry, rewrite the sha1, and add it to the index\n entry.sha1 = sha1\n @index[firstfour] ||= [] \n @index[firstfour] << entry\n end\n\n end\n @hardlinks = nil # clean up some memory\n end",
"def legacy_indexes()\n arr = []\n\n # REFACTOR: make to_llo call this one\n hr_op = analysis(Analysis::HR_NAME, lead_pair_name())\n\n # GXX : 0 - 25\n op = analysis(Analysis::APS_NAME, primary_lead_name())\n arr << op.index(Index::APS_12_NAME) # 0\n arr << op.index(Index::APS_OMEGA_NAME)\n arr << op.index(Index::APS_U1_NAME)\n arr << op.index(Index::APS_U2_NAME)\n arr << op.index(Index::APS_U3_NAME)\n arr << op.index(Index::APS_U3xy_NAME) # 5\n arr << op.index(Index::APS_U4_NAME)\n arr << op.index(Index::APS_N1_NAME)\n arr << op.index(Index::APS_N3_NAME)\n arr << hr_op.index(Index::HR_S_NAME)\n arr << hr_op.index(Index::HR_SS_NAME) # 10\n arr << hr_op.index(Index::HR_F_NAME)\n arr << hr_op.index(Index::HR_FF_NAME)\n arr << op.index(Index::APS_A1_NAME)\n arr << op.index(Index::APS_A2_NAME)\n arr << op.index(Index::APS_A3_NAME) # 15\n arr << op.index(Index::APS_A4_NAME)\n arr << op.index(Index::APS_A5_NAME)\n arr << op.index(Index::APS_A55_NAME)\n arr << op.index(Index::APS_N2_NAME)\n arr << op.index(Index::APS_AA12_NAME) # 20\n arr << op.index(Index::APS_AA34_NAME)\n arr << op.index(Index::APS_AA123_NAME)\n arr << op.index(Index::APS_AA1_NAME)\n arr << op.index(Index::APS_AA4_NAME)\n arr << op.index(Index::APS_U5_NAME) # 25\n\n # GYY : 26 - 51\n op = analysis(Analysis::APS_NAME, secondary_lead_name())\n arr << op.index(Index::APS_12_NAME)\n arr << op.index(Index::APS_OMEGA_NAME)\n arr << op.index(Index::APS_U1_NAME)\n arr << op.index(Index::APS_U2_NAME)\n arr << op.index(Index::APS_U3_NAME) # 30\n arr << op.index(Index::APS_U3xy_NAME)\n arr << op.index(Index::APS_U4_NAME)\n arr << op.index(Index::APS_N1_NAME)\n arr << op.index(Index::APS_N3_NAME)\n arr << hr_op.index(Index::HR_S_NAME) # 35\n arr << hr_op.index(Index::HR_SS_NAME)\n arr << hr_op.index(Index::HR_F_NAME)\n arr << hr_op.index(Index::HR_FF_NAME)\n arr << op.index(Index::APS_A1_NAME)\n arr << op.index(Index::APS_A2_NAME) # 40\n arr << op.index(Index::APS_A3_NAME)\n arr << op.index(Index::APS_A4_NAME)\n arr << op.index(Index::APS_A5_NAME)\n arr << op.index(Index::APS_A55_NAME)\n arr << op.index(Index::APS_N2_NAME) # 45\n arr << op.index(Index::APS_AA12_NAME)\n arr << op.index(Index::APS_AA34_NAME)\n arr << op.index(Index::APS_AA123_NAME)\n arr << op.index(Index::APS_AA1_NAME)\n arr << op.index(Index::APS_AA4_NAME) # 50\n arr << op.index(Index::APS_U5_NAME)\n\n # QXY : 52 - 57\n psa_op = analysis(Analysis::PSA_NAME, lead_pair_name())\n arr << psa_op.index(Index::PSA_PPLUS_NAME)\n arr << psa_op.index(Index::PSA_PMINUS_NAME)\n arr << psa_op.index(Index::PSA_WW_NAME)\n arr << psa_op.index(Index::PSA_PWWPLUS_NAME) # 55\n arr << psa_op.index(Index::PSA_PWWMINUS_NAME)\n\n imr_op = analysis(Analysis::IMR_NAME, lead_pair_name())\n arr << imr_op.index(Index::IMR_L_NAME)\n\n # RH : 58 - 59\n op = analysis(Analysis::COH_NAME, lead_pair_name())\n arr << op.index(Index::COH_Q1_NAME)\n arr << op.index(Index::COH_Q2_NAME)\n\n # PIH : 60 -69\n arr << imr_op.index(Index::IMR_D1_NAME) # 60\n arr << imr_op.index(Index::IMR_D2_NAME)\n arr << imr_op.index(Index::IMR_f_NAME)\n arr << imr_op.index(Index::IMR_M1_NAME)\n arr << imr_op.index(Index::IMR_M3_NAME)\n arr << imr_op.index(Index::IMR_M2_NAME) # 65\n arr << imr_op.index(Index::IMR_M4_NAME)\n arr << imr_op.index(Index::IMR_M5_NAME)\n arr << imr_op.index(Index::IMR_M6_NAME)\n arr << imr_op.index(Index::IMR_ff_NAME)\n\n # HA : 70 - 77\n v5_op = analysis(Analysis::AMP_NAME, primary_lead_name())\n ii_op = analysis(Analysis::AMP_NAME, secondary_lead_name())\n arr << v5_op.index(Index::AMP_HYPER_NAME) # 70\n arr << ii_op.index(Index::AMP_HYPER_NAME)\n arr << v5_op.index(Index::AMP_HYPO_NAME)\n arr << ii_op.index(Index::AMP_HYPO_NAME)\n arr << v5_op.index(Index::AMP_NPLUS_NAME)\n arr << ii_op.index(Index::AMP_NPLUS_NAME) # 75\n arr << v5_op.index(Index::AMP_NMINUS_NAME)\n arr << ii_op.index(Index::AMP_NMINUS_NAME)\n\n # VXY : 78 - 102\n op = analysis(Analysis::CCR_NAME, lead_pair_name())\n arr << op.index(Index::CCR_rrr_NAME)\n arr << op.index(Index::CCR_RRR_NAME)\n arr << op.index(Index::CCR_r_NAME) # 80\n arr << op.index(Index::CCR_R_NAME)\n arr << op.index(Index::CCR_RR_NAME)\n arr << op.index(Index::CCR_rr_NAME)\n arr << op.index(Index::CCR_rR_NAME)\n arr << op.index(Index::CCR_RPLUS_NAME) # 85\n arr << op.index(Index::CCR_RMINUS_NAME)\n arr << op.index(Index::CCR_RwPLUS_NAME)\n arr << op.index(Index::CCR_RwMINUS_NAME)\n arr << op.index(Index::CCR_PT1_NAME)\n arr << op.index(Index::CCR_PT2_NAME) # 90\n arr << op.index(Index::CCR_pt1_NAME)\n arr << op.index(Index::CCR_pt2_NAME)\n arr << op.index(Index::CCR_Rn_NAME)\n arr << op.index(Index::CCR_RVVPLUS_NAME)\n arr << op.index(Index::CCR_RVVMINUS_NAME) # 95\n arr << op.index(Index::CCR_RCARET_NAME)\n arr << op.index(Index::CCR_NOTR_NAME)\n arr << op.index(Index::CCR_RNOT_NAME)\n arr << op.index(Index::CCR_r2_NAME)\n arr << op.index(Index::CCR_R2_NAME) # 100\n arr << op.index(Index::CCR_r22_NAME)\n arr << op.index(Index::CCR_RM_NAME)\n\n # Q : 103 - 131\n arr << psa_op.index(Index::PSA_TPLUS_NAME)\n arr << psa_op.index(Index::PSA_TMINUS_NAME)\n arr << psa_op.index(Index::PSA_UPLUS_NAME) # 105\n arr << psa_op.index(Index::PSA_UMINUS_NAME)\n arr << psa_op.index(Index::PSA_WPLUS_NAME)\n arr << psa_op.index(Index::PSA_WMINUS_NAME)\n arr << psa_op.index(Index::PSA_W_NAME)\n arr << psa_op.index(Index::PSA_PPLUS10_NAME) # 110\n arr << psa_op.index(Index::PSA_PPLUS15_NAME)\n arr << psa_op.index(Index::PSA_PPLUSGT15_NAME)\n arr << psa_op.index(Index::PSA_PMINUS10_NAME)\n arr << psa_op.index(Index::PSA_PMINUS15_NAME)\n arr << psa_op.index(Index::PSA_PMINUSGT15_NAME) # 115\n arr << psa_op.index(Index::PSA_VPLUS_NAME)\n arr << psa_op.index(Index::PSA_VMINUS_NAME)\n arr << psa_op.index(Index::PSA_XPLUSPLUS_NAME)\n arr << psa_op.index(Index::PSA_XPLUSMINUS_NAME)\n arr << psa_op.index(Index::PSA_XMINUSMINUS_NAME) # 120\n arr << psa_op.index(Index::PSA_XMINUSPLUS_NAME)\n arr << psa_op.index(Index::PSA_YPLUSPLUS_NAME)\n arr << psa_op.index(Index::PSA_YMINUSMINUS_NAME)\n arr << psa_op.index(Index::PSA_YPLUSMINUS_NAME)\n arr << psa_op.index(Index::PSA_YMINUSPLUS_NAME) # 125\n arr << psa_op.index(Index::PSA_ZPLUS1_NAME)\n arr << psa_op.index(Index::PSA_ZPLUS2_NAME)\n arr << psa_op.index(Index::PSA_ZPLUS3_NAME)\n arr << psa_op.index(Index::PSA_ZMINUS1_NAME)\n arr << psa_op.index(Index::PSA_ZMINUS2_NAME) # 130\n arr << psa_op.index(Index::PSA_ZMINUS3_NAME)\n\n arr\n end",
"def indexes(*rest) end",
"def indexes(*rest) end",
"def each_with_index(&block)\n @tree.each_with_index(&block)\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 index_children(children)\n children.each do |model|\n Logger.new($stdout).info(\"Generating indexes for #{model}\")\n model.create_indexes\n index_children(model.descendants)\n end\n end",
"def reset_index\n @index = 0\n end",
"def clean\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 29 )\n clean_start_index = @input.index\n\n success = false # flag used for memoization\n\n begin\n # rule memoization\n if @state.backtracking > 0 and already_parsed_rule?( __method__ )\n success = true\n return \n end\n # at line 308:8: ( 'C' | 'c' ) ( 'L' | 'l' ) ( 'E' | 'e' ) ( 'A' | 'a' ) ( 'N' | 'n' )\n if @input.peek( 1 ).between?( T__46, T__47 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__22, T__23 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__28, T__29 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__48, T__49 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__34, T__35 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n\n success = true\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 29 )\n memoize( __method__, clean_start_index, success ) if @state.backtracking > 0\n\n end\n \n return \n end",
"def reset_index_information\n @indexes = nil\n end",
"def indexes\n @indexes ||= []\n end",
"def create_index\n index = ''\n\n @items.each do |key, item|\n value = item.chapter == 'Y' ? '' : ' '\n index += \"<option value=\\\"#{key}\\\">#{value}#{item.title}</option>\\n\"\n end\n\n $document.at_css('#tryruby-index').inner_html = index\n $document.on(:change, '#tryruby-index') { do_goto }\n end",
"def reindex_sections\n @next_section_index = 0\n @next_section_number = 0\n @blocks.each {|block|\n if block.is_a?(Section)\n assign_index(block)\n block.reindex_sections\n end\n }\n end",
"def index_all\n puts \"Indexing everything\"\n MojoDNA::Searchable::RemoteSearchable::searcher.push( [:index_all, self.inspect.to_s, nil] )\n end",
"def keywords_for_index(_item)\n []\n end",
"def find_element_children(index, el_depth, ordering)\n\t\tchildren = Array.new\n\t\ti = index + 1\n\t\tcurr_el = get_element_in_ordering(i, ordering)\n\t\twhile (curr_el == \"PlaceHolder\") #ignore nil elements\n\t\t\ti = i+1\n\t\t\tcurr_el = get_element_in_ordering(i, ordering)\n\t\tend\n\n\t\tif curr_el.is_a?(Node)\n\t\t\tcurr_child_depth = curr_el.depth\n\t\telse #if it's a note, it can't have children, so arbitrary big depth that'll get rest on the first node\n\t\t\tcurr_child_depth = 100000\n\t\tend\n\n\t\twhile (curr_el != nil && el_depth < curr_el.depth) #until you find something of equal or lesser depth\n\t\t\t#basically, include it if it's nested deeper (therefore in this loop,) but don't go into children of what you find)\n\t\t\tif curr_el.depth <= curr_child_depth && curr_el.is_a?(Node)\n\t\t\t\tnode_and_index = { node: curr_el, index: i}\n\t\t\t\tchildren.push(node_and_index)\n\t\t\t\tcurr_child_depth = curr_el.depth\n\t\t\telsif curr_el.depth <= curr_child_depth && (curr_el.is_a?(Note) || curr_el.is_a?(LinkCollection))\n\t\t\t\tnode_and_index = { node: curr_el, index: i}\n\t\t\t\tchildren.push(node_and_index)\n\t\t\t\tcurr_child_depth = 100000 \n\t\t\tend\n\t\t\t#if there's an indented note after some nodes, it will likely get ignored\n\n\t\t\ti = i+1\n\t\t\tcurr_el = get_element_in_ordering(i, ordering)\n\t\t\twhile (curr_el == \"PlaceHolder\") #ignore nil elements\n\t\t\t\ti = i+1\n\t\t\t\tcurr_el = get_element_in_ordering(i, ordering)\n\t\t\tend\n\t\tend\n\t\treturn children\n\tend",
"def check_all_rules_for_left_recursion\n @grammar.build_nfa # make sure we have NFAs\n @grammar.attr_left_recursive_rules = HashSet.new\n list_of_recursive_cycles = ArrayList.new\n i = 0\n while i < @grammar.attr_composite.attr_rule_index_to_rule_list.size\n r = @grammar.attr_composite.attr_rule_index_to_rule_list.element_at(i)\n if (!(r).nil?)\n @visited_during_recursion_check = HashSet.new\n @visited_during_recursion_check.add(r)\n visited_states = HashSet.new\n trace_states_looking_for_left_recursion(r.attr_start_state, visited_states, list_of_recursive_cycles)\n end\n i += 1\n end\n if (list_of_recursive_cycles.size > 0)\n ErrorManager.left_recursion_cycles(list_of_recursive_cycles)\n end\n return list_of_recursive_cycles\n end",
"def build_index\n @search = RSemantic::Search.new(@documents.map(&:text), @options)\n end",
"def blank\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 12 )\n return_value = BlankReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n\n begin\n # at line 330:5: \n # AST Rewrite\n # elements: \n # token labels: \n # rule labels: return_value\n # token list labels: \n # rule list labels: \n # wildcard labels: \n if @state.backtracking == 0\n\n return_value.tree = root_0\n stream_return_value = return_value ? subtree_stream( \"rule return_value\", return_value.tree ) : subtree_stream( \"token return_value\" )\n\n root_0 = @adaptor.create_flat_list\n # 330:5: -> ^( UNDEFINED )\n # at line 330:8: ^( UNDEFINED )\n root_1 = @adaptor.create_flat_list\n root_1 = @adaptor.become_root( @adaptor.create_from_type( UNDEFINED, \"UNDEFINED\" ), root_1 )\n\n @adaptor.add_child( root_0, root_1 )\n\n\n\n return_value.tree = root_0\n\n end# - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n if @state.backtracking == 0\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 end\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__, 12 )\n\n end\n \n return return_value\n end",
"def each_child_with_index(&block) # :yields: child_node, index\n children.each_with_index(&block)\n nil\n end",
"def each_child_with_index(&block) # :yields: child_node, index\n children.each_with_index(&block)\n nil\n end",
"def match parser, index\r\n report parser.literal?(value, index)\r\n end",
"def source_elements\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 2 )\n return_value = SourceElementsReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n statement2 = nil\n statement3 = nil\n\n\n begin\n root_0 = @adaptor.create_flat_list\n\n\n # at line 256:5: statement ( statement )*\n @state.following.push( TOKENS_FOLLOWING_statement_IN_source_elements_1780 )\n statement2 = statement\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, statement2.tree )\n end\n # at line 256:15: ( statement )*\n while true # decision 2\n alt_2 = 2\n look_2_0 = @input.peek( 1 )\n\n if ( look_2_0 == GENERAL || look_2_0 == GET || look_2_0 == ARROW || look_2_0 == IF || look_2_0 == REGEX || look_2_0 == INCR || look_2_0 == BREAK || look_2_0 == RETURN || look_2_0 == IS_DEFINED || look_2_0 == LBRACE || look_2_0 == LBRACK || look_2_0.between?( SEMI, CONST ) || look_2_0.between?( SET, LET ) || look_2_0 == DDOC || look_2_0.between?( DECR, LPAREN ) || look_2_0 == DELETE || look_2_0.between?( DGENERAL, DO ) || look_2_0 == THROW || look_2_0 == TILDE || look_2_0 == TRUE || look_2_0 == TRY || look_2_0.between?( TYPEOF, NEW ) || look_2_0.between?( EACH, UNDEFINED ) || look_2_0.between?( NULL, UNLESS ) || look_2_0 == UNTIL || look_2_0 == FALSE || look_2_0 == VAR || look_2_0.between?( VOID, FOR ) || look_2_0 == WHILE || look_2_0.between?( WITH, YIELD ) || look_2_0.between?( IS_UNDEFINED, DOC ) || look_2_0.between?( T__148, T__150 ) )\n alt_2 = 1\n\n end\n case alt_2\n when 1\n # at line 256:18: statement\n @state.following.push( TOKENS_FOLLOWING_statement_IN_source_elements_1785 )\n statement3 = statement\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, statement3.tree )\n end\n\n else\n break # out of loop for decision 2\n end\n end # loop for decision 2\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n if @state.backtracking == 0\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 end\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__, 2 )\n\n end\n \n return return_value\n end",
"def handle_sectioning(elements)\n \t\t\tsections = []\n \t\t\tsection_stack = []\n\n \t\t\telements.each do |el|\n insert_element(el, sections, section_stack)\n \t\t\tend\n\n \t\t\treturn sections\n \t\tend",
"def scan\n entries = parse_entries\n grouped_entries = group_entries entries\n\n doc = create_document grouped_entries\n\n @top_level.comment = doc\n\n @top_level\n end",
"def write_tag_indexes\n if self.layouts.key? 'tag_index'\n self.tags.keys.each do |tag|\n self.write_tag_index(tag)\n end\n\n # Throw an exception if the layout couldn't be found.\n else\n throw \"No 'tag_index' layout found.\"\n end\n end",
"def write_tag_indexes\n if self.layouts.key? 'tag_index'\n self.tags.keys.each do |tag|\n self.write_tag_index(tag)\n end\n\n # Throw an exception if the layout couldn't be found.\n else\n throw \"No 'tag_index' layout found.\"\n end\n end",
"def extract_indexterms(terms)\n terms.each_with_object({}) do |t, v|\n term = t&.at(ns(\"./primary\"))&.children&.to_xml\n term2 = t&.at(ns(\"./secondary\"))&.children&.to_xml\n term3 = t&.at(ns(\"./tertiary\"))&.children&.to_xml\n index2bookmark(t)\n v[term] ||= {}\n v[term][term2] ||= {}\n v[term][term2][term3] ||= {}\n v[term][term2][term3][:xref] ||= []\n to = t[\"to\"] ? \"to='#{t['to']}' \" : \"\"\n v[term][term2][term3][:xref] << \"<xref target='#{t['id']}' #{to}pagenumber='true'/>\"\n end\n end",
"def crawl(pages, depth=2)\n depth.times do\n new_pages = Set.new\n pages.each do |page|\n begin\n doc = Hpricot(open(page))\n rescue\n printf \"Could not open %s\\n\", page\n next\n end\n \n add_to_index(page, doc)\n \n (doc/'a').each do |link|\n if link['href']\n url = URI.join(page, link['href']).to_s\n next if url =~ /'/\n url = url.split('#').first # drop the fragment\n if url[0,4] == 'http' and not is_indexed(url)\n new_pages << url\n end\n link_text = get_text_only(link)\n add_link_ref(page, url, link_text)\n end\n end\n end\n \n pages = new_pages\n end\n end",
"def all_indexes\n Chewy.eager_load!\n Chewy::Index.descendants - [Chewy::Stash::Journal, Chewy::Stash::Specification]\n end",
"def index\r\n @index ||= 0\r\n end",
"def build_tree_unsorted(array)\n array.each_index{ |index|\n\n }\nend",
"def lex(text)\n bases = [[0, Parse.new(text)]]\n done = []\n while bases.any?\n offset, parse = bases.shift\n added_any = false\n @leaves.each do |leaf|\n # can this leaf rule extract a leaf at this offset?\n next unless (md = leaf.rx.match(text, offset)) && md.begin(0) == offset\n\n e = md.end(0)\n next if leaf.preconditions.any? { |pc| pc.call(leaf.name, offset, e, text, []) == :fail }\n\n added_any = true\n new_parse = parse.add(offset, e, leaf, @do_unary_branch_check, false, leaf.boundary)\n if e == text.length\n done << new_parse\n else\n bases << [e, new_parse]\n end\n end\n next if added_any\n\n # try to eliminate trash\n trash_offset = text.length\n @leaves.each do |leaf|\n # is there a leaf like this closer to the current offset?\n next unless\n (md = leaf.rx.match(text, offset)) &&\n (b = md.begin(0)) &&\n (b < trash_offset) &&\n (e = md.end(0)) &&\n leaf.preconditions.none? { |pc| pc.call(leaf.name, b, e, text, []) == :fail }\n\n trash_offset = b\n end\n new_parse = parse.add(offset, trash_offset, trash_rule, false, true)\n if trash_offset == text.length\n done << new_parse\n else\n bases << [trash_offset, new_parse]\n end\n end\n done # an array of Parses\n end",
"def index(element); end",
"def rewrite_tree_element\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 36 )\n return_value = RewriteTreeElementReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n rewrite_tree_atom156 = nil\n rewrite_tree_atom157 = nil\n ebnf_suffix158 = nil\n rewrite_tree159 = nil\n ebnf_suffix160 = nil\n rewrite_tree_ebnf161 = nil\n\n stream_rewrite_tree = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule rewrite_tree\" )\n stream_rewrite_tree_atom = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule rewrite_tree_atom\" )\n stream_ebnf_suffix = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule ebnf_suffix\" )\n begin\n # at line 366:2: ( rewrite_tree_atom | rewrite_tree_atom ebnf_suffix -> ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree_atom EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) ) | rewrite_tree ( ebnf_suffix -> ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) ) | -> rewrite_tree ) | rewrite_tree_ebnf )\n alt_76 = 4\n alt_76 = @dfa76.predict( @input )\n case alt_76\n when 1\n root_0 = @adaptor.create_flat_list\n\n\n # at line 366:4: rewrite_tree_atom\n @state.following.push( TOKENS_FOLLOWING_rewrite_tree_atom_IN_rewrite_tree_element_2657 )\n rewrite_tree_atom156 = rewrite_tree_atom\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, rewrite_tree_atom156.tree )\n end\n\n when 2\n # at line 367:4: rewrite_tree_atom ebnf_suffix\n @state.following.push( TOKENS_FOLLOWING_rewrite_tree_atom_IN_rewrite_tree_element_2662 )\n rewrite_tree_atom157 = rewrite_tree_atom\n @state.following.pop\n if @state.backtracking == 0\n stream_rewrite_tree_atom.add( rewrite_tree_atom157.tree )\n end\n @state.following.push( TOKENS_FOLLOWING_ebnf_suffix_IN_rewrite_tree_element_2664 )\n ebnf_suffix158 = ebnf_suffix\n @state.following.pop\n if @state.backtracking == 0\n stream_ebnf_suffix.add( ebnf_suffix158.tree )\n end\n # AST Rewrite\n # elements: ebnf_suffix, rewrite_tree_atom\n # token labels: \n # rule labels: return_value\n # token list labels: \n # rule list labels: \n # wildcard labels: \n if @state.backtracking == 0\n\n return_value.tree = root_0\n stream_return_value = return_value ? subtree_stream( \"rule return_value\", return_value.tree ) : subtree_stream( \"token return_value\" )\n\n root_0 = @adaptor.create_flat_list\n # 368:3: -> ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree_atom EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) )\n # at line 368:6: ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree_atom EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) )\n root_1 = @adaptor.create_flat_list\n root_1 = @adaptor.become_root( stream_ebnf_suffix.next_node, root_1 )\n\n # at line 368:21: ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree_atom EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] )\n root_2 = @adaptor.create_flat_list\n root_2 = @adaptor.become_root( @adaptor.create( BLOCK, \"BLOCK\" ), root_2 )\n\n # at line 368:38: ^( ALT[\\\"ALT\\\"] rewrite_tree_atom EOA[\\\"EOA\\\"] )\n root_3 = @adaptor.create_flat_list\n root_3 = @adaptor.become_root( @adaptor.create( ALT, \"ALT\" ), root_3 )\n\n @adaptor.add_child( root_3, stream_rewrite_tree_atom.next_tree )\n @adaptor.add_child( root_3, @adaptor.create( EOA, \"EOA\" ) )\n\n @adaptor.add_child( root_2, root_3 )\n @adaptor.add_child( root_2, @adaptor.create( EOB, \"EOB\" ) )\n\n @adaptor.add_child( root_1, root_2 )\n\n @adaptor.add_child( root_0, root_1 )\n\n\n\n return_value.tree = root_0\n\n end\n when 3\n # at line 369:6: rewrite_tree ( ebnf_suffix -> ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) ) | -> rewrite_tree )\n @state.following.push( TOKENS_FOLLOWING_rewrite_tree_IN_rewrite_tree_element_2698 )\n rewrite_tree159 = rewrite_tree\n @state.following.pop\n if @state.backtracking == 0\n stream_rewrite_tree.add( rewrite_tree159.tree )\n end\n # at line 370:3: ( ebnf_suffix -> ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) ) | -> rewrite_tree )\n alt_75 = 2\n look_75_0 = @input.peek( 1 )\n\n if ( look_75_0 == T__74 || look_75_0.between?( T__91, T__92 ) )\n alt_75 = 1\n elsif ( look_75_0 == EOF || look_75_0 == TREE_BEGIN || look_75_0 == REWRITE || look_75_0.between?( TOKEN_REF, ACTION ) || look_75_0 == RULE_REF || look_75_0 == T__71 || look_75_0.between?( T__81, T__83 ) || look_75_0 == T__93 )\n alt_75 = 2\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n raise NoViableAlternative( \"\", 75, 0 )\n end\n case alt_75\n when 1\n # at line 370:5: ebnf_suffix\n @state.following.push( TOKENS_FOLLOWING_ebnf_suffix_IN_rewrite_tree_element_2704 )\n ebnf_suffix160 = ebnf_suffix\n @state.following.pop\n if @state.backtracking == 0\n stream_ebnf_suffix.add( ebnf_suffix160.tree )\n end\n # AST Rewrite\n # elements: ebnf_suffix, rewrite_tree\n # token labels: \n # rule labels: return_value\n # token list labels: \n # rule list labels: \n # wildcard labels: \n if @state.backtracking == 0\n\n return_value.tree = root_0\n stream_return_value = return_value ? subtree_stream( \"rule return_value\", return_value.tree ) : subtree_stream( \"token return_value\" )\n\n root_0 = @adaptor.create_flat_list\n # 371:4: -> ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) )\n # at line 371:7: ^( ebnf_suffix ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] ) )\n root_1 = @adaptor.create_flat_list\n root_1 = @adaptor.become_root( stream_ebnf_suffix.next_node, root_1 )\n\n # at line 371:21: ^( BLOCK[\\\"BLOCK\\\"] ^( ALT[\\\"ALT\\\"] rewrite_tree EOA[\\\"EOA\\\"] ) EOB[\\\"EOB\\\"] )\n root_2 = @adaptor.create_flat_list\n root_2 = @adaptor.become_root( @adaptor.create( BLOCK, \"BLOCK\" ), root_2 )\n\n # at line 371:38: ^( ALT[\\\"ALT\\\"] rewrite_tree EOA[\\\"EOA\\\"] )\n root_3 = @adaptor.create_flat_list\n root_3 = @adaptor.become_root( @adaptor.create( ALT, \"ALT\" ), root_3 )\n\n @adaptor.add_child( root_3, stream_rewrite_tree.next_tree )\n @adaptor.add_child( root_3, @adaptor.create( EOA, \"EOA\" ) )\n\n @adaptor.add_child( root_2, root_3 )\n @adaptor.add_child( root_2, @adaptor.create( EOB, \"EOB\" ) )\n\n @adaptor.add_child( root_1, root_2 )\n\n @adaptor.add_child( root_0, root_1 )\n\n\n\n return_value.tree = root_0\n\n end\n when 2\n # at line 372:5: \n # AST Rewrite\n # elements: rewrite_tree\n # token labels: \n # rule labels: return_value\n # token list labels: \n # rule list labels: \n # wildcard labels: \n if @state.backtracking == 0\n\n return_value.tree = root_0\n stream_return_value = return_value ? subtree_stream( \"rule return_value\", return_value.tree ) : subtree_stream( \"token return_value\" )\n\n root_0 = @adaptor.create_flat_list\n # 372:5: -> rewrite_tree\n @adaptor.add_child( root_0, stream_rewrite_tree.next_tree )\n\n\n\n return_value.tree = root_0\n\n end\n end\n\n when 4\n root_0 = @adaptor.create_flat_list\n\n\n # at line 374:6: rewrite_tree_ebnf\n @state.following.push( TOKENS_FOLLOWING_rewrite_tree_ebnf_IN_rewrite_tree_element_2750 )\n rewrite_tree_ebnf161 = rewrite_tree_ebnf\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, rewrite_tree_ebnf161.tree )\n end\n\n end# - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n if @state.backtracking == 0\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 end\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__, 36 )\n\n end\n \n return return_value\n end",
"def find_render_sequences\n @crawler.pages.each do |path|\n\n page = RenderItem.new(path)\n \n seq = RenderSeq.new(page)\n\n filename = File.basename(path, \".html\")\n dirname = File.dirname(path)\n\n # search in local dir for [filename].layout\n if @crawler.layouts.include?(File.join(dirname, \"#{filename}.layout\"))\n item = LayoutRenderItem.new(File.join(dirname, \"#{filename}.layout\"), nil)\n seq.layout = item\n end\n\n # search in local dir for [filename].follow.layout\n if seq.layout.nil? && @crawler.follow_layouts.include?(File.join(dirname, \"#{filename}.follow.layout\"))\n item = LayoutRenderItem.new(File.join(dirname, \"#{filename}.follow.layout\"), item)\n end\n\n # search in local dir for default.layout\n if seq.layout.nil? && @crawler.layouts.include?(File.join(dirname, \"default.layout\"))\n item = LayoutRenderItem.new(File.join(dirname, \"default.layout\"), item)\n seq.layout = item\n end\n\n # search in local dir for default.follow.layout\n if seq.layout.nil? && @crawler.follow_layouts.include?(File.join(dirname, \"default.follow.layout\"))\n item = LayoutRenderItem.new(File.join(dirname, \"default.follow.layout\"), item)\n end\n\n if seq.layout.nil?\n # search in parents for default.layout\n possible_layouts = Array.new\n @crawler.layouts.each do |layout|\n if (layout =~ /default\\.layout$/) && (dirname.include? File.dirname(layout))\n possible_layouts << layout\n end\n end\n \n possible_layouts.sort { |a, b| b.length <=> a.length }\n \n # search in parents for default.follow.layout\n possible_follow_layouts = Array.new\n @crawler.follow_layouts.each do |layout|\n if (layout =~ /default\\.follow\\.layout$/) && (dirname.include? File.dirname(layout)) && (!File.dirname(layout).include? dirname)\n possible_follow_layouts << layout\n end\n end\n \n possible_follow_layouts.sort { |a, b| b.length <=> a.length }\n\n possible_follow_layouts.each do |layout|\n if layout.length - 7 > possible_layouts[0].length\n item = LayoutRenderItem.new(layout, item)\n end\n end\n\n item = LayoutRenderItem.new(possible_layouts[0], item) unless possible_layouts.empty?\n\n end\n \n seq.layout = item if seq.layout.nil?\n \n # search for all possible snippets (in case of same name, higher level will be ignored)\n possible_snippets = Hash.new\n @crawler.snippets.each do |snippet|\n if dirname.include? File.dirname(snippet)\n name = File.basename(snippet, \".snippet\")\n if (!possible_snippets.has_key?(name)) || (possible_snippets[name].length < snippet.length)\n possible_snippets[name] = RenderItem.new(snippet)\n end\n end\n end\n\n seq.snippets = possible_snippets\n\n # search for all possible slots (in case of 'default' and specific name, the latter is used)\n possible_slots = Hash.new\n @crawler.slots.each do |slot|\n if dirname.eql? File.dirname(slot)\n if File.basename(slot, \".html\").include? filename\n name = File.basename(slot, \".html\").sub(\"#{filename}.\", '')\n possible_slots[name] = RenderItem.new(slot)\n elsif File.basename(slot, \".html\").include? 'default'\n name = File.basename(slot, \".html\").sub(\"default.\", '')\n possible_slots[name] = RenderItem.new(slot)\n end\n end\n end\n\n seq.slots = possible_slots\n \n @site.add_sequence(seq)\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 match_all(data, &block)\n return nil if @root == nil\n i=0\n while (i<data.length)\n node = @root.find_forward(data, i, data.length-i)\n if (node!=nil && node.value!=nil)\n yield Item.new(i, true, node)\n i += node.length\n else\n i += 1\n end\n end\n end",
"def index\n unless @descriptor_index\n @descriptor_index = all.inject({}) do |hash,d|\n hash[d.index_key] = d\n hash\n end\n end\n @descriptor_index\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.48649248",
"0.48627138",
"0.48620716",
"0.4800469",
"0.47913304",
"0.4785313",
"0.47848853",
"0.47655573",
"0.47074017",
"0.47028908",
"0.46858954",
"0.46767586",
"0.4669426",
"0.4669128",
"0.46631223",
"0.46564034",
"0.46493092",
"0.4647947",
"0.4633249",
"0.46281037",
"0.4628034",
"0.46179777",
"0.4602334",
"0.45980006",
"0.4592154",
"0.45748708",
"0.45716307",
"0.4566373",
"0.4564993",
"0.4557487",
"0.45537168",
"0.45497116",
"0.45449606",
"0.45440137",
"0.45440137",
"0.45400938",
"0.45395607",
"0.45288056",
"0.45279533",
"0.45229343",
"0.45219502",
"0.45208475",
"0.4519714",
"0.4519005",
"0.45171323",
"0.45045826",
"0.44979784",
"0.4494467",
"0.44920427",
"0.44836202",
"0.44775343",
"0.44775343",
"0.44749358",
"0.44733927",
"0.4471382",
"0.44711432",
"0.4467622",
"0.4467622",
"0.44675183",
"0.44671753",
"0.4464598",
"0.4460452",
"0.44554383",
"0.44554016",
"0.44532058",
"0.4445919",
"0.4445107",
"0.4444138",
"0.4443858",
"0.4441179"
] | 0.67908156 | 0 |
GT guia de tranporte lista todos los estado de GT en un select | def get_list_state
TransportGuideState.get_list_guide_state
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def select_tiporelacion\n [ \n [\"BENEFICIARIO\",\"BENEFICIARIO\"],\n [\"INTEGRANTE\",\"INTEGRANTE\"],\n [\"PROPIETARIO\",\"PROPIETARIO\"],\n [\"APODERADO\",\"APODERADO\"]\n ] \n end",
"def envia_taxones_seleccionados\n end",
"def selected_options; end",
"def selected_options; end",
"def select_list; end",
"def show_name_state\n @estados = Estado.order(:sigla)\n end",
"def estados\n\t\tdevuelto = Array.new\n\t\t@renglones_reporte.each do |renglon|\n\t\t\tdevuelto << renglon.estado\n\t\tend\n\t\tdevuelto\n\tend",
"def get_listbox_data\n @countries = current_user.company.countries.dropdown_list\n @sectors = current_user.company.sectors.order(:sector)\n @rel_types = current_user.company.rel_types.dropdown_list\n @relationgroups = current_user.company.relations.dropdown_list\n end",
"def index\n @tagging_select_tos = TaggingSelectTo.all\n if @tagging_select_tos.empty?\n TaggingSelectTo.create(name: 'Sajjad-Murtaza-Testing-Taggable')\n end\n end",
"def index\n # @gran_unidad = GranUnidad.select(:id, :nombre, :region_militar_id).order(:region_militar_id, :nombre)\n @gran_unidad = ActiveRecord::Base.connection.execute(\"SELECT gu.id, gu.nombre, rm.nombre FROM gran_unidad gu\n INNER JOIN region_militar rm ON gu.region_militar_id = rm.id\n ORDER BY rm.nombre\")\n @gu_active = 'active'\n @rm_active = ''\n @cuarteles_active = ''\n end",
"def option_select_estado(estado = nil)\n html = \"\"\n if estado\n html << \"<option value='#{ estado }'>#{ estado.uf_to_nome }</option>\"\n elsif @usuario_logado and @usuario_logado.end_estado\n html << \"<option value='#{ @usuario_logado.end_estado }'>#{ @usuario_logado.end_estado.uf_to_nome }\"\n end\n ESTADOS.each {|e| html << \"<option value='#{ e }'>#{ e.uf_to_nome }</option>\"}\n html.html_safe\n end",
"def estudiantes\n\t\t@seccion = \"Estudiantes\"\n @titulo = \"Estudiantes\"\n\t\tif params[:orden]\n\t\t\t@orden = params[:orden]\n\t\telse\n\t\t\t@orden = \"Cédula\"\n\t\tend\n\n #Guardo todos los estudiantes\n if Estudiante.all().size > 0\n case @orden\n \twhen \"Cédula\"\n \t\t@usuarios = Usuario.order('cedula').where(:id => Estudiante.all)\n \twhen \"Nombre\"\n \t\t@usuarios = Usuario.order('nombre').where(:id => Estudiante.all)\n \twhen \"Apellido\"\n \t\t@usuarios = Usuario.order('apellido').where(:id => Estudiante.all)\n \twhen \"Correo\"\n \t\t@usuarios = Usuario.order('correo').where(:id => Estudiante.all)\n \tend\n end\n\n\t\t@categorias = ['Cédula', 'Nombre', 'Apellido', 'Correo'] #Este es el orden que se mostrará en el select de la vista\n\n\t\t@estudiante_datos = [] #En este arreglo se guardan los pares \"Cedula - Nombre Apellido\" de cada usuario para mostrar en el campo de busqueda\n\t\tUsuario.order('nombre').where(:id => Estudiante.all).each do |usuario|\n\t\t\t#En este foro se agregan uno a uno los valores de cada estudiante al arreglo de la manera indicada arriba\n\t\t\t@estudiante_datos << usuario.cedula.to_s + \" - \" + usuario.nombre_y_apellido.to_s\n\t\tend\n\tend",
"def index\n @selecionados = Selecionado.all\n end",
"def select_tiposdocumemto\n [\n [\"CARTAS DE PROPIETARIOS SOLICITANDO LA VIVIENDA\",\"CARTAS DE PROPIETARIOS SOLICITANDO LA VIVIENDA\"],\n [\"CARTAS PARA CAMBIO DE VIVIENDA\",\"CARTAS PARA CAMBIO DE VIVIENDA\"],\n [\"CARTAS RECIBIDAS PARA SOLICITUD DE AUMENTO DE CANON\",\"CARTAS RECIBIDAS PARA SOLICITUD DE AUMENTO DE CANON\"],\n [\"DOCUMENTACION DE TENENCIA DE VIVIENDA EVACUADA\",\"DOCUMENTACION DE TENENCIA DE VIVIENDA EVACUADA\"],\n [\"DOCUMENTACION DE VIVIENDA PARA ARRENDAR POR PRIMERA VEZ\",\"DOCUMENTACION DE VIVIENDA PARA ARRENDAR POR PRIMERA VEZ\"],\n [\"DOCUMENTACION DE VIVIENDAS DISPONIBLES\",\"DOCUMENTACION DE VIVIENDAS DISPONIBLES\"],\n [\"DOCUMENTACION PARA CAMBIO DE VIVIENDA\",\"DOCUMENTACION PARA CAMBIO DE VIVIENDA\"],\n [\"DOCUMENTOS SOPORTES DE INGRESOS FAMILIARES\",\"DOCUMENTOS SOPORTES DE INGRESOS FAMILIARES\"],\n [\"DOCUMENTOS DE IDENTIDAD DEL GRUPO FAMILIAR\",\"DOCUMENTOS DE IDENTIDAD DEL GRUPO FAMILIAR\"],\n [\"OTROS DOCUMENTOS\",\"OTROS DOCUMENTOS\"],\n [\"PAZ Y SALVOS RECIBIDOS\",\"PAZ Y SALVOS RECIBIDOS\"]\n ]\n end",
"def list_selected_options\n list_selected_options = []\n @selected_options.each do |option|\n list_selected_options << option.type\n end\n return list_selected_options\n end",
"def list\n\t\tprintf(\"%02i.%i\\n\", @options[:monat], @options[:jahr])\n\t\t@db.execute(\"select betrag, gemeinsam, tags from ausgaben_#{@options[:name]} where jahr = #{@options[:jahr]} and monat = #{@options[:monat]} order by jahr, monat, gemeinsam desc\") do |row|\n\t\t\tprintf(\"(%s) %s EUR [%s] \\n\", row[1], sprintf(\"%.2f\",row[0]).rjust(7), row[2])\n\t\tend\n\tend",
"def set_selections( action )\n @sir_groups = Group.active_only.participants_only.collect{ |g| [ g.code_and_label, g.id ]}\n @sir_phases = PhaseCode.all.order( :code ).collect{ |p| [ p.code_and_label, p.id ]}\n end",
"def day_select_option_tags\n options_for_select DAYS.map.with_index.to_a\n end",
"def group_drop_down\n @groups = @list.map { |hash| hash[:group] }.uniq.compact\nend",
"def getSelectedItems\r\n assert_exists\r\n returnArray = []\r\n #element.log \"There are #{@o.length} items\"\r\n @o.each do |thisItem|\r\n #puts \"#{thisItem.selected}\"\r\n if thisItem.selected\r\n #element.log \"Item ( #{thisItem.text} ) is selected\"\r\n returnArray << thisItem.text \r\n end\r\n end\r\n return returnArray \r\n end",
"def selected_options\n options.select(&:selected?)\n end",
"def all_items\n \t\tall(:xpath, \"//select[@id='ctl00_LC_drop3']//option\").map { |a| a.text}\n \tend",
"def select_type\n\t\t\t@select_all_type = TypeEquipament.all\n\t\tend",
"def selected_units\n SQF.groupSelectedUnits @this\n end",
"def index\n @cuarteles = Cuartel.select(:id, :nombre).order(:nombre)\n\n # Control de los botones activos\n @gu_active = ''\n @rm_active = ''\n @cuarteles_active = 'active'\n end",
"def seleccionarCromosomas()\n #p \"--- Empieza el torneo:\"\n seleccion = []\n @tamMatingPool.times do\n competidor1 = @poblacion[Random.rand(@tamPoblacion)]\n competidor2 = @poblacion[Random.rand(@tamPoblacion)]\n evaluarCromosoma(competidor1)\n evaluarCromosoma(competidor2)\n ganador = competidor1.aptitud > competidor2.aptitud ? \n competidor1 : competidor2\n #p \"--- Ganador: #{ganador.genes}\"\n seleccion.push(ganador)\n end\n return seleccion\n end",
"def index\n @selected_options_of_pcs = SelectedOptionsOfPc.all\n end",
"def getListaTabla\n return ['form_cultivos','baciloscopia_forms','biopsias_forms','form_liquidos','form_chagas','form_malaria','form_leishmaniases','Tuberculosis','form_cancer_uterinos','form_anat_citologicas','Tuberculosis']\n end",
"def form_escolher\n lst_from.select 'London'\n lst_on.select 'December'\n lst_month.select '20'\n lst_arriving.select 'Acapulco'\n lst_returning.select 'October'\n lst_month_returning.select '21'\n check_port.click\n lst_airline.select 'Blue Skies Airlines'\n end",
"def select_options\n all.map {|e| [e.name, e.to_s] }\n end",
"def select_options\n all.map {|e| [e.name, e.to_s] }\n end",
"def selected\n @taxons = @product.taxons\n set_available\n end",
"def index\n @tareas = Tarea.all\n @tareapositivas = Tarea.where(listo: true)\n end",
"def selected_tags\n @selected_tags\n end",
"def get_tags_for_select() tag_ids.inject([]) { |l, tag_id| l << [get_tag_from_id(tag_id).label, tag_id] } end",
"def index\n @kadais = Kadai.where.not(status: [\"04_Invaild\", \"99_Close\"]).order('due_date DESC')\n @tasks = Task.where.not(status:[\"04_Invaild\", \"99_Close\"]).order(\"due_date ASC\")\n @persons_for_options = Hash.new\n Person.all.each do |person|\n @persons_for_options.store(person.name, person.name)\n end\n end",
"def select_list\n require 'pashua'\n include Pashua\n\n config = \"\n *.title = personal time tracker\n cb.type = combobox\n cb.completion = 2\n cb.width = 400\n cb.default = surfing\n cb.tooltip = Choose from the list\n db.type = cancelbutton\n db.label = Cancel\n db.tooltip = Closes this window without taking action\" + \"\\n\"\n\n # insert list of all choices\n cust = get_custom_cats || []\n cat = (cust ? cust + Categories : Categories)\n cat.each { |c| config << \"cb.option = #{c}\\n\" }\n pagetmp = pashua_run config\n exit if pagetmp['cancel'] == 1 || pagetmp['cb'] == nil\n\n choice = pagetmp['cb'].strip\n notify_change(choice)\n log(choice)\n\n unless cat.index(choice)\n cust << choice\n write_custom_cats(cust)\n end\nend",
"def selecionar_opcao\n btn_metro.click\n btn_bicicletario_vaga_verde.click\n foco(btn_vacinacao)\n end",
"def index\n @topes_legales = TopesLegale.all\n end",
"def get_choices\n puts \"Welcome to BrewStats!\"\n BrewStats::Scraper.scrape_ba\n @states = BrewStats::States.all\n end",
"def menu\n ([[0, 'Choisir l’icarien…']] + User.values_select(type_icarien => true)).in_my_select(id: 'opuser_user_id', name: 'opuser[user_id]', selected: param_opuser[:user_id])\n end",
"def selected_options\n options.select { |e| e.selected? }\n end",
"def ooc_scan_type_list(gui_active_only = false)\n scan_types =OocScanType.find_by_sql(\"select ooc_scan_type\n from hip_ooc_scan_type_v #{\"where active_in_gui = 'y'\" if gui_active_only}\n group by grouping sets ((ooc_scan_type, ooc_group_type),(ooc_group_type))\n order by ooc_group_type, ooc_scan_type\")\n array=[]\n scan_types.each do |type|\n array.push(type['ooc_scan_type']) unless type['ooc_scan_type'].blank?\n array.push('--------------') if type['ooc_scan_type'].blank?\n end\n array.pop # remove the last blank line\n return array\n end",
"def check_box_options\n [:tag_ids, Tag.order(:name), :id, :name]\n end",
"def set_form_variables\n @articles = CriminalCode.all.includes(:articles).with_translations\n @tags = Tag.includes(:translations).order(:name)\n @prisons = Prison.includes(:translations).order(:name)\n\n gon.select_charges = t('shared.actions.with_obj.select',\n obj: t('activerecord.models.charge', count: 999))\n gon.select_tags = t('shared.actions.with_obj.select',\n obj: t('activerecord.models.tag', count: 999)) \n end",
"def list_choices\n state_names = []\n @states.each do |state|\n state_names << state.name\n end\n\n prompt = TTY::Prompt.new\n @user_selection = prompt.enum_select(\"Select a state by it's number\", state_names)\n end",
"def selectReservables(val)\n #puts \"Val is: #{val}\"\n arrTable = @driver.find_elements(:tag_name, 'table')\n availabilityTable = nil\n arrTable.each do |table|\n if table.attribute('class') == 'slds-table slds-table--bordered slds-max-medium-table--stacked-horizontal'\n availabilityTable = table\n break\n end\n end\n #puts \"availabilityTable: #{availabilityTable}\"\n #puts \"availabilityTable class: #{availabilityTable.attribute('class')}\"\n #puts \"availabilityTable size: #{availabilityTable.size}\"\n tBodyEle = availabilityTable.find_element(:tag_name, 'tbody')\n\n arrRows = tBodyEle.find_elements(:tag_name, 'tr')\n #puts \"arrRows size #{arrRows.size}\"\n index = -1\n arrRows.each do |row|\n #puts \"row class: #{row.attribute('class')}\"\n row.find_elements(:tag_name, 'td').each do |col|\n #puts \"Column data lable: #{col.attribute('data-label')}\"\n if (col.attribute('data-label') == 'Unit')\n index = index + 1\n if (col.find_element(:class, 'slds-truncate').text == val)\n #puts \"Clicking on Checkbox, Index is: #{index}\"\n row.find_element(:id, \"checkbox-span:#{index}\").click\n @@selected_buildings.push(val)\n break\n end\n end\n end\n #index = index + 1\n end\n #puts \"selected_buildings: #{@@selected_buildings}\"\n @wait = Selenium::WebDriver::Wait.new(:timeout => 20)\n #return AvailabilityPage.new(@@driver)\n end",
"def projects_dropdown\n if session[:office] != '0'\n Project.where(office_id: session[:office].to_i).ser_or_tca_order_type\n elsif session[:company] != '0'\n Project.where(company_id: session[:company].to_i).ser_or_tca_order_type\n else\n session[:organization] != '0' ? Project.where(organization_id: session[:organization].to_i).ser_or_tca_order_type : Project.ser_or_tca_order_type\n end\n end",
"def selected\n tasks = []\n @widget.selection.selected_each do |model, path, iter|\n tasks << iter[0]\n end\n return tasks\n end",
"def mostrar_palabras_clave_grupos \n \n puts \"Esta operación puede tardar un poco, le rogamos tenga paciencia por favor.\"\n puts\n puts\n coleccion = @hemeroteca.palabras_clave_grupos \n coleccion.each_index do |i|\n puts \"Grupo #{i+1}:\" \n puts \"---------\"\n puts coleccion[i].join(\", \")\n puts \n puts \n end\n if coleccion.empty? then\n puts \"Lo sentimos, no se han encontrado noticias.\" \n puts\n puts\n end \n \n end",
"def select_options_for_court_sports\n @court_sports_enums = Court.where(venue_id: authorized_scope(company.venues).select(:id)).active.\n pluck('distinct sport_name')\n @court_sports = @court_sports_enums.map { |n| Court.sport_names.key(n) }\n render json: @court_sports.map { |x| { value: x, label: x.humanize } }\n end",
"def index\n @qua_trinh_cong_tacs = QuaTrinhCongTac.all\n end",
"def selected; end",
"def index\n proyecto_activo = Proyecto.find(session[:proyecto_activo]['id'])\n\n @etapas = proyecto_activo.etapas.order(:orden)\n end",
"def tecnicos_postulados\n coleccion = []\n self.request.each do |request|\n info = {}\n info[:id] = request.id\n info[:article] = request.article\n info[:servicio] = request.service.description\n info[:tecnicos] = request.proposal\n coleccion.append(info)\n end\n coleccion\n end",
"def opportunity_contract_type_select\n [\n ['Contrato a Termino Fijo.', 1],\n ['Contrato a Termino Indefinido.', 2],\n ['Contrato de Obra o Labor.', 3],\n ['Contrato de Aprendizaje.', 4],\n ['Contrato Civil por Prestación de Servicios', 5]\n ]\n end",
"def index\n @estado_notificacions = EstadoNotificacion.all\n end",
"def lister( les_cours )\n \n recup = recuperer_option \n format = recup[0]\n sep = recup[2]\n if !recup[1].nil?\n cours = les_cours.sort_by(&:sigle)\n end\n \n cours ||= les_cours.select{|c| c.actif?}\n sep ||= CoursTexte::SEPARATEUR_PREALABLES\n cours =cours.sort_by(&:sigle)\n cours.each { |e| puts e.to_s(format, sep) }\n \n return [les_cours, nil]\n \nend",
"def set_collection_select\n @facultades = Facultad.all\n @programas = Programa.all\n @grupos = Grupo.all\n @semilleros = Semillero.all\n @investigadores = Investigador.all\n end",
"def index\n @operacioncontroldetes = Operacioncontroldete.all\n end",
"def sectorsOptions(selected_id, transl, sector_set_code)\n ret = [['All', '']]\n Sector.where(:sector_set_code => sector_set_code).each do |s|\n # ret << [ transl[\"sector.#{s.code}.name\"], s.id ]\n ret << [ Translation.where(locale: @locale_code, key: s.name_key).first.value, s.id ]\n end\n return ret\n end",
"def show\n combo_producto\n combo_platillo\n end",
"def valid_times_as_select_options()\n self.valid_times.size()==0 ? \n ValidTime.default.select_options() :\n self.valid_times_sorted.inject([]){|opt,vt| opt + vt.select_options()}\n end",
"def index\n @gossip_selection = Gossip.all\n end",
"def set_listas\n #@locais = Local.all.map{|l| [l.nome,l.id]}\n @locais = Local.all\n @periodos = ['Manhã','Tarde','Noite']\n @publicos = ['Infantil','Adulto']\n end",
"def show\n #@departamento = Ubigeo.find_by_sql(\"where idDepartamento=\"+@estacionamiento.departamento.to_s)\n @serv_adicinales = ServAdicinale.all\n @departamento = Ubigeo.where(:idDepartamento => @estacionamiento.departamento).first\n @provincia = Ubigeo.where(:idProvincia => @estacionamiento.provincia).first\n @distrito = Ubigeo.where(:idDistrito => @estacionamiento.distrito).first\n @lista_departamentos = Ubigeo.find_by_sql(\"select distinct idDepartamento, Departamento from ubigeos\")\n @lista_provincias = Ubigeo.find_by_sql(\"select distinct idProvincia, Provincia from ubigeos\")\n @lista_distritos = Ubigeo.find_by_sql(\"select distinct idDistrito, Distrito from ubigeos\")\n \n end",
"def select_options(access = :deposit)\n @service.search_results(access).map do |admin_set|\n [admin_set.to_s, admin_set.id, data_attributes(admin_set)]\n end\n end",
"def selected_options\n @options.find_all { |o| o.selected? }\n end",
"def index\n @pergunta_subgrupos = QuestaoSubgrupo.all\n end",
"def index\n @selected_times = SelectedTime.all\n end",
"def subjectsOptions(selected_id, options_all=false, tree_type_id)\n if options_all\n ret = [['All', '']]\n else\n ret = []\n end\n Subject.where(\"tree_type_id = ? AND min_grade < ?\", tree_type_id, 999).order(\"max_grade desc\", \"min_grade asc\", \"code\").each do |s|\n # ret << [ @translations[\"sector.#{s.code}.name\"], s.id ]\n ret << [s.code, s.id]\n end\n return ret\n end",
"def index\n @tropas = Tropa.all\n end",
"def index\n @coleccion = DetallePedido.all\n end",
"def index\n @turmas = current_colegio.turmas\n end",
"def selection\n @tg.clear\n s1_temp = -1\n s2_temp = -1\n s1_temp = @ep.sample(@ss).max until s1_temp != -1\n s2_temp = @ep.sample(@ss).max until s2_temp != -1\n @s1 = @ep.index(s1_temp)\n @s2 = @ep.index(s2_temp)\n @tg[@s1] = @cg[@s1]\n @tg[@s2] = @cg[@s2]\n end",
"def index\n @anteproyecto_estudiantes = AnteproyectoEstudiante.all\n end",
"def resultados\n if params[:checklist] == '1'\n self.taxones = taxones.datos_arbol_con_filtros\n checklist\n else\n self.taxones = taxones.select_basico.order(:nombre_cientifico)\n return if formato == 'xlsx'\n\n self.taxones = taxones.offset(offset).limit(por_pagina)\n\n # Si solo escribio un nombre\n if params[:id].blank? && params[:nombre].present?\n taxones.each do |t|\n t.cual_nombre_comun_coincidio(params[:nombre])\n end\n end\n end # End checklist\n end",
"def index\n @plan_quirurgicos = PlanQuirurgico.where(:estatus => \"En Proceso\")\n \n end",
"def selectionneurMode(tab,unMode)\n\t\tres = Array.new\n\t\ttab.each do |joueur|\n\t\t\tif joueur.donneMode == unMode\n\t\t\t\tres.push(joueur)\n\t\t\tend\n\n\t\tend\n\t\tres\n\tend",
"def chosen_options\n Option.find_all_by_id session[:chosen_options]\n end",
"def index\n @nota_tecnicas = NotaTecnica.all\n end",
"def select_list\n @browser.div(:class => \"select-list\")\n end",
"def index\n @solicitacao_tipos = SolicitacaoTipo.all\n end",
"def show\n @tareapositivas = Tarea.where(listo: true)\n @tareas = Tarea.all\n end",
"def index\n @galleta = Galletum.all\n end",
"def index \n @t_unidad = TUnidad.all\n @organigrama = TUnidad.select(:nCodUni, :nCodUniPadre, :cDenominacion, :nIdArea, :ancestry, :norder).all.arrange({:order => 'norder'}) \n end",
"def abrir_filtro\n wait_until_btn_selecione_visible\n btn_selecione.click\n end",
"def index\n @tipo_venta = TipoVentum.all\n end",
"def index\n @grupopermissaos = Grupopermissao.all\n end",
"def simulacion\n @ordenes = Orden.where(:estado => \"Recolectada\")\n end",
"def index\n @ton_giaos = TonGiao.all\n end",
"def opportunity_select_cost_or_offer\n [\n ['Quiero poner un valor para el proyecto', Opportunity::OPTION_FOR_COST],\n ['Quiero escuchar ofertas de los estudiantes', Opportunity::OPTION_FOR_OFFER]\n ]\n end",
"def index\n @coleccion = Tabla.all\n end",
"def camposDescarga(tipo_descarga=nil)\n checkbox = ''\n campos = { x_tipo_distribucion: 'Tipo de distribución', x_cat_riesgo: 'Categorías de riesgo y comercio internacional', x_ambiente: 'Ambiente', x_nombres_comunes: 'Nombres comunes', x_bibliografia: 'Bibliografía' }\n \n case tipo_descarga\n when 'basica'\n when 'avanzada'\n campos.merge!({ x_col_basicas: 'Columnas basicas', x_taxa_sup: 'Taxonomía superior', x_url_ev: 'URL de la especie en enciclovida' })\n when 'region'\n campos = { x_num_reg: 'Número de registros' }.merge(campos.merge!({ x_col_basicas: 'Columnas basicas', x_taxa_sup: 'Taxonomía superior', x_url_ev: 'URL de la especie en enciclovida' }))\n when 'checklist'\n campos.merge!({ x_estatus: 'Solo válidos/aceptados', x_distribucion: 'Distribución (reportada en literatura)', x_residencia: 'Categoría de residencia (aves)', x_formas: 'Formas de crecimiento (plantas)', x_interaccion: 'Interacciones biológicas' }) \n end\n \n campos.each do |valor, label|\n if valor.to_s == 'x_col_basicas'\n checkbox << check_box_tag('f_desc[]', valor, true, style: 'display: none;', id: \"f_#{tipo_descarga}_#{valor}\")\n else\n checkbox << \"<div class='custom-control custom-switch'>\"\n checkbox << check_box_tag('f_desc[]', valor, false, class: \"custom-control-input\", id: \"f_#{tipo_descarga}_#{valor}\")\n checkbox << \"<label class='custom-control-label' for='f_#{tipo_descarga}_#{valor}'>#{label}</label>\"\n checkbox << \"</div>\"\n end\n\n \n end\n\n checkbox.html_safe\n end",
"def display_source_selection\n # clear t_session_src\n @multiple = false\n if (params[\"multiple\"] == \"multiple\")\n @multiple = true\n end\n result = SqlserverHelper.database_select(\"gfa_reports\", \"PARIS_REPORTER\", \"dbo\", \"t_datasources\",[\"id\",\"name\",\"type\"], nil, \"isvalid = 1\", nil)\n @choices = result.map() {|p| [ \"#{p['type']} - #{p['name']}\", p['id'] ] }\n @wid = SessionHelper.get_latest_session(\"gfa_reports\",@user.email)\n #@sessions = Workspace.where(userid: @user.email)\n #@session = @sessions.order(:id ).last\n @parts = Trx.new \n end",
"def curselection\n list(tk_send_without_enc('curselection'))\n end",
"def index\n @gastos_balanceados = GastosBalanceado.all\n end",
"def index\n @antrag_statuses = AntragStatus.all\n end",
"def get_product_dropdown_list\n @product_dropdown_list ||= lambda {\n list = []\n\n page = ::Nokogiri::HTML(firstpage)\n page.search('//div[@class=\"sb-search\"]//select[@id=\"productDropdown\"]//option').each do |product|\n option_value = product.attributes['value'].value\n option_text = product.text\n next if option_value == '-1' # This is the ALL option\n list << { option_value: option_value, option_text: option_text }\n end\n\n list\n }.call\n end",
"def index\n @coleccion = Requisito.all\n end",
"def index\n @trabajador_seccions = TrabajadorSeccion.all\n end"
] | [
"0.63645893",
"0.6325184",
"0.59422565",
"0.59422565",
"0.5866912",
"0.5832182",
"0.5787936",
"0.56868905",
"0.5631731",
"0.5596491",
"0.55846053",
"0.5493009",
"0.5490691",
"0.54853266",
"0.54208004",
"0.5347446",
"0.5342118",
"0.5326624",
"0.53191257",
"0.5318892",
"0.530465",
"0.5304011",
"0.5303366",
"0.52865106",
"0.5281001",
"0.5278128",
"0.527575",
"0.52695745",
"0.5266765",
"0.5234934",
"0.5234934",
"0.5234174",
"0.522633",
"0.52227324",
"0.5221259",
"0.5208634",
"0.5205732",
"0.5198487",
"0.5193796",
"0.5166182",
"0.5152007",
"0.5149341",
"0.5148234",
"0.513638",
"0.5133109",
"0.51302123",
"0.5125247",
"0.51227933",
"0.51209444",
"0.5115187",
"0.51092327",
"0.5102865",
"0.5097358",
"0.50934464",
"0.5090241",
"0.5072976",
"0.5072843",
"0.50589836",
"0.5057451",
"0.5054326",
"0.5050756",
"0.5050594",
"0.50461006",
"0.5041842",
"0.5040766",
"0.5040724",
"0.5037302",
"0.5034222",
"0.50334823",
"0.5018211",
"0.50129706",
"0.50106657",
"0.50105196",
"0.5004643",
"0.500137",
"0.4997674",
"0.49819008",
"0.49815443",
"0.49793372",
"0.4973114",
"0.49704653",
"0.49678248",
"0.49662313",
"0.49649027",
"0.4963507",
"0.49612197",
"0.4960907",
"0.49578977",
"0.49554363",
"0.49540693",
"0.49446917",
"0.49399808",
"0.49389225",
"0.493179",
"0.49196652",
"0.49152157",
"0.4907064",
"0.4902699",
"0.490038",
"0.48931536",
"0.48914716"
] | 0.0 | -1 |
lista todos las ciudades disponibles en un select | def get_list_cities
City.get_all_cities
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @selecionados = Selecionado.all\n end",
"def index\n @coleccion = Caracteristica.all\n end",
"def select_list; end",
"def set_collection_select\n @facultades = Facultad.all\n @programas = Programa.all\n @grupos = Grupo.all\n @semilleros = Semillero.all\n @investigadores = Investigador.all\n end",
"def for_dropdown\n ActiveRecord::Base.connection.select_all(\n select('brands.name, brands.id').group('1, 2').order('1').to_sql\n ).map { |r| [r['name'], r['id']] }\n end",
"def index\n @formularios = Formulario.search\n @select_options = Formulario.get_name_folder\n end",
"def get_all_category_select_options()\n o = []\n Category.where(:category_id => nil).each do |c|\n get_category_select_options(c).each do |c_option|\n o << c_option\n end\n end\n return o\n end",
"def index\n @ciudades = Ciudad.all\n end",
"def anulacion \n @solicitud=Solicitud.find(params[:id])\n @causal_select=CausalesAnulacionRevocatoria.find(:all,:conditions=>\"anulacion=true\",:order=>\"causa asc\")\n @width_layout = '660'\n end",
"def index\n @coleccion = Cita.all\n end",
"def select_tiporelacion\n [ \n [\"BENEFICIARIO\",\"BENEFICIARIO\"],\n [\"INTEGRANTE\",\"INTEGRANTE\"],\n [\"PROPIETARIO\",\"PROPIETARIO\"],\n [\"APODERADO\",\"APODERADO\"]\n ] \n end",
"def index\n @coleccion = Requisito.all\n end",
"def index\n @coleccion = DetallePedido.all\n end",
"def listado\n #@lista = Asignacion.listado_array\n @lista = Campo.find(:all, :include => [:area => [:contrato => [:empresa]]], :conditions => {:codigo => \"\"}) #\n end",
"def collect_tier_categories_for_select(klass, select=true)\n result = klass.find_all_categories.map {|c| [c.name, c.id]}\n result.insert(0, [\"Select...\".t, nil])\n result\n end",
"def index\n # @gran_unidad = GranUnidad.select(:id, :nombre, :region_militar_id).order(:region_militar_id, :nombre)\n @gran_unidad = ActiveRecord::Base.connection.execute(\"SELECT gu.id, gu.nombre, rm.nombre FROM gran_unidad gu\n INNER JOIN region_militar rm ON gu.region_militar_id = rm.id\n ORDER BY rm.nombre\")\n @gu_active = 'active'\n @rm_active = ''\n @cuarteles_active = ''\n end",
"def index\n @coleccionables = Coleccionable.all\n end",
"def select_options\n all.map {|e| [e.name, e.to_s] }\n end",
"def select_options\n all.map {|e| [e.name, e.to_s] }\n end",
"def set_controles\n @controles= Control.where(area_id: @consulta.ficha_nutricional_adulto.area_id, paciente_id: @consulta.ficha_nutricional_adulto.paciente_id).limit(9).order(id: :desc)\n end",
"def clinicas_todas(id)\n Usuario.find_by_datos_id(id, :conditions => \"datos_type = 'Clinica'\")\n end",
"def load_Obj\n @grupos = Grupo.all\n @nivels = Nivel.select(:id, :nombre).where(\"nombre != ?\", \"CAPITULO\" )\n# @papa = Catalogo.select(:id, :codigo, :nombre).where(\"estransaccional = ? AND activo = ? \", false, true) \n @ajuste = Catalogo.select(:id, :codigo, :nombre).where(\"estransaccional = ? AND activo = ?\", true, true )\n @laux = Libroauxiliar.select(:id, :descripcion).where(\"activo = ?\", true)\n end",
"def get_listbox_data\n @countries = current_user.company.countries.dropdown_list\n @sectors = current_user.company.sectors.order(:sector)\n @rel_types = current_user.company.rel_types.dropdown_list\n @relationgroups = current_user.company.relations.dropdown_list\n end",
"def index\n @coleccion = TipoReferenciaBase.all\n end",
"def menu\n ([[0, 'Choisir l’icarien…']] + User.values_select(type_icarien => true)).in_my_select(id: 'opuser_user_id', name: 'opuser[user_id]', selected: param_opuser[:user_id])\n end",
"def options_for_select_for_cities\n options_for_select(City.all.collect {|c| [c.name, c.id]} << [\"All Locations\", \"0\"])\n end",
"def index\n @coleccion = Etiqueta.all\n end",
"def index\n @daw_curso_comunicados = DawCursoComunicado.all\n end",
"def index\n @selected_options_of_pcs = SelectedOptionsOfPc.all\n end",
"def index\n #@ciclista = Ciclistum.all\n @ciclista = Ciclistum.where ([\"usuario_id = '%s'\", current_user.id])\n end",
"def index\n @coleccion = Columna.all\n end",
"def sectorsOptions(selected_id, transl, sector_set_code)\n ret = [['All', '']]\n Sector.where(:sector_set_code => sector_set_code).each do |s|\n # ret << [ transl[\"sector.#{s.code}.name\"], s.id ]\n ret << [ Translation.where(locale: @locale_code, key: s.name_key).first.value, s.id ]\n end\n return ret\n end",
"def index\n @coleccion = Tabla.all\n end",
"def index\n @coleccion = ReferenciaBase.all\n end",
"def index\n @veiculos = Veiculo.where(usuario_id: current_usuario)\n @abastecimentos = Abastecimento.where(:veiculo_id => @veiculos)\n end",
"def index\n @condicoes_pagamento = CondicaoPagamento.all\n end",
"def select_options_for_court_sports\n @court_sports_enums = Court.where(venue_id: authorized_scope(company.venues).select(:id)).active.\n pluck('distinct sport_name')\n @court_sports = @court_sports_enums.map { |n| Court.sport_names.key(n) }\n render json: @court_sports.map { |x| { value: x, label: x.humanize } }\n end",
"def index\n @cicadas = Cicada.all\n end",
"def index\n #@categorias = Catalogo.select(\"ctlg_categoria\").distinct.where(\"ctlg_categoria IS NOT NULL\")\n #@subcategorias = Catalogo.select(\"ctlg_subcategoria\").distinct.where(\"ctlg_subcategoria IS NOT NULL\")\n \n condiciones = []\n cadena = \"ctlg_estado_registro = 'A'\"\n \n @catalogo = Catalogo.new(catalogo_params)\n\n unless @catalogo.ctlg_categoria.blank? then\n condiciones.push(\"Upper(ctlg_categoria) = '#{@catalogo.ctlg_categoria.to_s.upcase}'\")\n end\n \n unless @catalogo.ctlg_subcategoria.blank? then\n condiciones.push(\"Upper(ctlg_subcategoria) = '#{@catalogo.ctlg_subcategoria.to_s.upcase}'\")\n end\n \n unless @catalogo.ctlg_valor_desc.blank? then\n condiciones.push(\"Upper(ctlg_valor_desc) LIKE '%#{@catalogo.ctlg_valor_desc.to_s.upcase}%'\")\n end \n \n if condiciones.any? then\n condiciones.each do |condicion|\n if condicion != nil then\n cadena = cadena + \" AND \" + condicion.to_s\n end\n end\n \n @catalogos = Catalogo.select('id, ctlg_categoria, ctlg_subcategoria, ctlg_valor_cdg, ctlg_valor_desc, ctlg_observacion, ctlg_estado_registro').where(cadena).limit(100)\n else\n @catalogos = Catalogo.none\n end\n \n end",
"def index\n @cuarteles = Cuartel.select(:id, :nombre).order(:nombre)\n\n # Control de los botones activos\n @gu_active = ''\n @rm_active = ''\n @cuarteles_active = 'active'\n end",
"def get\n @cine = Cine.find(params[:cine_id], :select => [\"nombre\",\"id\",\"direccion\",\"localidad\"])\n render :json => [ @cine, :peliculas => @cine.peliculas.select('titulo,horas,pelicula_id') ]\n end",
"def select_all; end",
"def list_viaticos\n @company = Company.find(1)\n @caja = Caja.find(params[:id])\n \n @pagetitle = \"#{@company.name} - Viaticos\"\n @filters_display = \"block\"\n \n @locations = Location.where(company_id: @company.id).order(\"name ASC\")\n @divisions = Division.where(company_id: @company.id).order(\"name ASC\")\n \n \n if(@company.can_view(current_user))\n @viaticos = Viatico.where(caja_id: params[:id]).order('id DESC').paginate(:page => params[:page])\n\n if params[:search]\n @viaticos = Viatico.where(caja_id: params[:id]).search(params[:search]).order('id DESC').paginate(:page => params[:page])\n else\n @viaticos = Viatico.where(caja_id: params[:id]).order('id DESC').paginate(:page => params[:page]) \n end\n \n else\n errPerms()\n end\n end",
"def index\n\t\t@cidades = Cidade.all\n\t\t@ccidade = params[:ccidade]\n\t\tfiltro = \"1=1\"\n\t\t\n\t\tif @ccidade != nil\n\t\t\tfiltro = filtro+\" and cidade_id = '\"+@ccidade+\"'\"\n\t\tend\n\t\t\n\t\t@causas = Causa.where(filtro).order(\"titulo\").paginate(page:\nparams[:page], per_page: 3)\n\t\t\n\t\t\n #@causas = Causa.all\n end",
"def index\n @caracteristica_propiedads = CaracteristicaPropiedad.all\n end",
"def index\n @comentariu_licentas = ComentariuLicenta.all\n end",
"def index\n @convidados = Convidado.all\n end",
"def index\r\n @electrica_consejeros = ElectricaConsejero.all\r\n end",
"def fill_select_option\n @search_by_values = QcLaboratory.get_search_values\n end",
"def politicas_cierre(id)\n ActiveRecord::Base.connection.select_all(\"select distinct j.journalized_id as \\\"#\\\", \n(select name from issue_statuses where cast(id as char(4))=(select jd.value from journal_details jd where journal_id in (select id from journals where journalized_id=#{id}) and prop_key='status_id' order by jd.id desc limit 1)) as \\\"Estado\\\",\n(select u.firstname || ' ' || u.lastname from users u where cast(id as char(4))=(select jd.value from journal_details jd where journal_id in (select id from journals where journalized_id=#{id}) and prop_key='assigned_to_id' order by jd.id desc limit 1)) as \\\"Asignado\\\",\n j.created_on as \\\"Fecha_inicio\\\"\nfrom journals j join issues i on j.journalized_id=i.id where \nj.id=(select jd.journal_id from journal_details jd where journal_id in (select id from journals where journalized_id=#{id}) and prop_key='status_id' order by jd.id desc limit 1)\norder by 1\n \")\n end",
"def index\n @kinds = Kind.create_select_options\n end",
"def filtrar_ca(reg)\n f = Sivel2Gen::Caso.accessible_by(current_ability)\n reg = reg.where(\"sivel2_gen_conscaso.caso_id in (#{f.select(:id).to_sql})\")\n reg\n end",
"def index\n @coleccion = Cliente.all\n end",
"def show\n combo_producto\n combo_platillo\n end",
"def select # BY COLLOQUE TSUI\r\n \r\n if params[:sector] == \"all\" && params[:location] == \"all\"\r\n @finances = Finance.all\r\n @status = \"We have found #{@finances.size} company(s)\"\r\n elsif params[:sector] == \"all\" && params[:location] != \"all\"\r\n @finances = Finance.where(\"location like ?\", \"%#{params[:location]}%\")\r\n @status = \"We have found #{@finances.size} company(s)\"\r\n elsif params[:sector] != \"all\" && params[:location] == \"all\"\r\n @finances = Finance.where(\"sector like ?\", \"%#{params[:sector]}%\")\r\n @status = \"We have found #{@finances.size} company(s)\"\r\n else\r\n @finances = Finance.where(\"sector like ? AND location like ?\", \"%#{params[:sector]}%\", \"%#{params[:location]}%\")\r\n @status = \"We have found #{@finances.size} company(s)\"\r\n if @finances.size == 0\r\n @status = \"No companies found\"\r\n end\r\n end\r\n @finances = @finances.order(\"name ASC\")\r\n render :layout => 'select'\r\n end",
"def setear_fijos_arbol\n # @incisos = Inciso.all\n # @partidas_principales = PartidaPrincipal.all\n # @partidas_parciales = PartidaParcial.all \n @clases = Clase.where(\"fecha_de_baja IS NULL\")\n @bienes_de_consumo = BienDeConsumo.where(\"fecha_de_baja IS NULL\")\n end",
"def set_listas\n #@locais = Local.all.map{|l| [l.nome,l.id]}\n @locais = Local.all\n @periodos = ['Manhã','Tarde','Noite']\n @publicos = ['Infantil','Adulto']\n end",
"def index\n @concedentes = Concedente.all\n end",
"def index\r\n @sivic_contabancos = SivicContabanco.where(sivic_igreja_id: current_user.sivic_pessoa.sivic_igreja_id)\r\n end",
"def filtros_iniciales\n @reinos = Especie.select_grupos_iconicos.where(nombre_cientifico: Busqueda::GRUPOS_REINOS)\n @animales = Especie.select_grupos_iconicos.where(nombre_cientifico: Busqueda::GRUPOS_ANIMALES)\n @plantas = Especie.select_grupos_iconicos.where(nombre_cientifico: Busqueda::GRUPOS_PLANTAS)\n @nom_cites_iucn_todos = Catalogo.nom_cites_iucn_todos\n @distribuciones = TipoDistribucion.distribuciones(I18n.locale.to_s == 'es-cientifico')\n end",
"def tecnicos_postulados\n coleccion = []\n self.request.each do |request|\n info = {}\n info[:id] = request.id\n info[:article] = request.article\n info[:servicio] = request.service.description\n info[:tecnicos] = request.proposal\n coleccion.append(info)\n end\n coleccion\n end",
"def index\n @cuadros= @categorium.cuadros.order(:id)\n end",
"def index\n @caracteristica_tipo_vehiculos = CaracteristicaTipoVehiculo.all\n end",
"def index\n seleccionarMenu(:juzgados)\n @juzgados = Juzgado.order(:ciudad_id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @juzgados }\n end\n end",
"def index\n @socio_dados_bancos = SocioDadosBanco.all\n end",
"def index\n @daw_comunicados = DawComunicado.all\n end",
"def option_selects\n content_profile_entries.map do |cpe|\n [cpe.description, cpe.id, {'data-description': \"#{cpe.content_type}:#{cpe.topic_type}\"} ]\n end\n end",
"def index\n @categoriafinaceiros = Categoriafinaceiro.all\n end",
"def index\n @tipo_unidads = TipoUnidad.all\n end",
"def index\n @crud_municipios = CrudMunicipio.all\n end",
"def index\n @codvendas = Codvenda.all\n end",
"def mostrar_candidatos\n \n puts \" \"\n puts \"Quantidade de votos por candidato\"\n #Buca o candidato em seu array\n for candidato in @candidato\n candidato.mostrar_dados \n end \n end",
"def index\n @dm_clinicas = DmClinica.all\n end",
"def index\n\n\n @cont = 0 # Variable para acceso al arreglo de @usuarios en la vista\n @clinicas = Clinica.all\n @usuarios = Usuario.find(:all, :conditions => \"datos_type = 'Clinica'\")\n\n\n end",
"def select_type\n\t\t\t@select_all_type = TypeEquipament.all\n\t\tend",
"def estudiantes\n\t\t@seccion = \"Estudiantes\"\n @titulo = \"Estudiantes\"\n\t\tif params[:orden]\n\t\t\t@orden = params[:orden]\n\t\telse\n\t\t\t@orden = \"Cédula\"\n\t\tend\n\n #Guardo todos los estudiantes\n if Estudiante.all().size > 0\n case @orden\n \twhen \"Cédula\"\n \t\t@usuarios = Usuario.order('cedula').where(:id => Estudiante.all)\n \twhen \"Nombre\"\n \t\t@usuarios = Usuario.order('nombre').where(:id => Estudiante.all)\n \twhen \"Apellido\"\n \t\t@usuarios = Usuario.order('apellido').where(:id => Estudiante.all)\n \twhen \"Correo\"\n \t\t@usuarios = Usuario.order('correo').where(:id => Estudiante.all)\n \tend\n end\n\n\t\t@categorias = ['Cédula', 'Nombre', 'Apellido', 'Correo'] #Este es el orden que se mostrará en el select de la vista\n\n\t\t@estudiante_datos = [] #En este arreglo se guardan los pares \"Cedula - Nombre Apellido\" de cada usuario para mostrar en el campo de busqueda\n\t\tUsuario.order('nombre').where(:id => Estudiante.all).each do |usuario|\n\t\t\t#En este foro se agregan uno a uno los valores de cada estudiante al arreglo de la manera indicada arriba\n\t\t\t@estudiante_datos << usuario.cedula.to_s + \" - \" + usuario.nombre_y_apellido.to_s\n\t\tend\n\tend",
"def index\n #@bicicleta = Bicicletum.find_by ciclista_id: current_user.id\n @bicicleta = Bicicletum.where ([\"ciclista_id = '%s'\", current_user.id])\n #@bicicleta =Bicicletum.all \n end",
"def index\n @api_v1_select_fields = Api::V1::SelectField.all\n end",
"def category_options(db)\n my_category = db.execute(\"SELECT * FROM notes\")\n options = []\n my_category.each do |category|\n options << category[1]\n end\n options.uniq!\nend",
"def getListaTabla\n return ['form_cultivos','baciloscopia_forms','biopsias_forms','form_liquidos','form_chagas','form_malaria','form_leishmaniases','Tuberculosis','form_cancer_uterinos','form_anat_citologicas','Tuberculosis']\n end",
"def select_options(access = :deposit)\n @service.search_results(access).map do |admin_set|\n [admin_set.to_s, admin_set.id, data_attributes(admin_set)]\n end\n end",
"def set_form_variables\n @articles = CriminalCode.all.includes(:articles).with_translations\n @tags = Tag.includes(:translations).order(:name)\n @prisons = Prison.includes(:translations).order(:name)\n\n gon.select_charges = t('shared.actions.with_obj.select',\n obj: t('activerecord.models.charge', count: 999))\n gon.select_tags = t('shared.actions.with_obj.select',\n obj: t('activerecord.models.tag', count: 999)) \n end",
"def index\n @ocorrencia = Ocorrencium.where(data_saida: nil, condominio_id: current_user.condominio_id)\n end",
"def index\n @tipo_unidades = TipoUnidad.all\n end",
"def index\n @lecturas = Lectura.includes(:cliente, :periodo).all\n end",
"def docentes\n\t\t@seccion = \"Docentes\"\n @titulo = \"Docentes\"\n\n if Docente.all().size > 0\n \t\tif params[:orden]\n \t\t\t@orden = params[:orden]\n \t\telse\n \t\t\t@orden = \"Cédula\"\n \t\tend\n\n \t\t#Guardo todos los docentes\n \t\tcase @orden\n \t\twhen \"Cédula\"\n \t\t\t@usuarios = Usuario.order('cedula').where(:id => Docente.all)\n \t\twhen \"Nombre\"\n \t\t\t@usuarios = Usuario.order('nombre').where(:id => Docente.all)\n \t\twhen \"Apellido\"\n \t\t\t@usuarios = Usuario.order('apellido').where(:id => Docente.all)\n \t\twhen \"Correo\"\n \t\t\t@usuarios = Usuario.order('correo').where(:id => Docente.all)\n \t\tend\n\n end\n\t\t\n\t\t @categorias = ['Cédula', 'Nombre', 'Apellido', 'Correo'] #Este es el orden que se mostrará en el select de la vista\n\n \t\t@docente_datos = [] #En este arreglo se guardan los pares \"Cedula - Nombre Apellido\" de cada usuario para mostrar en el campo de busqueda\n \t\tUsuario.order('nombre').where(:id => Docente.all).each do |usuario|\n \t\t\t#En este foro se agregan uno a uno los valores de cada docente al arreglo de la manera indicada arriba\n \t\t\t@docente_datos << usuario.cedula.to_s + \" - \" + usuario.nombre_y_apellido.to_s\n \t\tend\n\tend",
"def getListeCase()\n return @listeCase\n end",
"def asignaturas\n @seccion = \"Asignaturas\"\n @titulo = \"Asignaturas\"\n if params[:orden]\n case params[:orden]\n when \"Código\"\n @orden = \"codigo\"\n when \"Nombre\"\n @orden = \"nombre\"\n when \"Créditos\"\n @orden = \"unidades_credito\"\n when \"Tipo\"\n @orden = \"tipo\"\n else\n @orden = \"codigo\"\n end\n else\n @orden = \"codigo\"\n end\n \n @carreras = [\"Biología\", \"Computación\", \"Geoquímica\", \"Física\", \"Matemática\", \"Química\", \"Complementaria\"]\n @categorias = ['Código', 'Nombre', 'Créditos','Tipo'] #Este es el orden que se mostrará en el select de la vista\n @categoria_seleccionada = params[:orden]\n\n @asignatura_datos = [] #En este arreglo se guardan los pares \"Codigo - Nombre\" de cada asignatura para mostrar en el campo de busqueda\n Asignatura.order('nombre').all.each do |asignatura|\n #En este foro se agregan uno a uno los valores de cada asignatura al arreglo de la manera indicada arriba\n @asignatura_datos << asignatura.codigo.to_s + \" - \" + asignatura.nombre.to_s\n end\n end",
"def index\n @operaziones_cat_coltures = OperazionesCatColture.all\n end",
"def index\n @ciudads = Ciudad.all.paginate(page: params[:page], per_page: 50)\n end",
"def index\n movimiento_caja = MovimientoCaja.find(params[:movimiento_caja_id])\n @movimiento_de_cajas_detalles = movimiento_caja.movimiento_de_cajas_detalles\n end",
"def especies_filtros\n return unless tiene_filtros?\n self.taxones = Especie.select(:id).select(\"#{Scat.attribute_alias(:catalogo_id)} AS catalogo_id\").joins(:scat).distinct\n por_especie_id\n por_nombre\n #estatus\n #solo_publicos\n estado_conservacion\n tipo_distribucion\n uso\n formas_crecimiento\n ambiente\n\n #return unless por_id_o_nombre\n #categoria_por_nivel\n end",
"def index\n @contratantes = Contratante.all\n end",
"def index\n @coleccion = Revista.all\n end",
"def index\n @tipo_veiculos = TipoVeiculo.all\n end",
"def index\r\n @sivic_contcelulas = SivicContcelula.all\r\n end",
"def to_form_select(projects)\n projects.collect do |p|\n [[p.shortname, p.description].join(\" - \"), p.id]\n end\n end",
"def index\n @cargas = Carga.find_by_sql(\"select * from cargas where user_id = #{current_user.id} order by id desc\").paginate(page: params[:page], per_page: 10)\n end",
"def show\n @contatos = Contato.where(@regra.criterio)\n end",
"def _crud(for_select = true)\n fetch_array_for $_crud, for_select\n end",
"def select_options\n (first_level_options || []).map { |o| [o.name, o.id] }\n end"
] | [
"0.6396304",
"0.63183856",
"0.6278303",
"0.61796707",
"0.61702967",
"0.6152788",
"0.6144997",
"0.61194223",
"0.61095107",
"0.6108852",
"0.6096879",
"0.60926783",
"0.6042244",
"0.5979015",
"0.5973464",
"0.5929909",
"0.59114",
"0.58922",
"0.58922",
"0.5885817",
"0.5881717",
"0.5875003",
"0.58492696",
"0.5845001",
"0.58436996",
"0.5821291",
"0.5807994",
"0.5781083",
"0.57805985",
"0.57692075",
"0.5760401",
"0.57240397",
"0.57140136",
"0.57124877",
"0.5710666",
"0.5707867",
"0.5702471",
"0.56991357",
"0.5691925",
"0.5687233",
"0.568063",
"0.566915",
"0.5661263",
"0.5651599",
"0.5638907",
"0.563534",
"0.56350076",
"0.56325066",
"0.5629486",
"0.5626014",
"0.5614751",
"0.5603148",
"0.55992424",
"0.5596468",
"0.5589168",
"0.5577004",
"0.55767345",
"0.55755395",
"0.55740607",
"0.5568723",
"0.55611885",
"0.555979",
"0.5557098",
"0.55565244",
"0.5551951",
"0.5551387",
"0.5549802",
"0.5543388",
"0.55417365",
"0.55372703",
"0.55346787",
"0.55342346",
"0.5532554",
"0.55280226",
"0.55262893",
"0.5521678",
"0.5512452",
"0.5511344",
"0.5511227",
"0.5509061",
"0.5507748",
"0.5503836",
"0.55014735",
"0.5501394",
"0.54964924",
"0.54940313",
"0.54923683",
"0.54867905",
"0.54804134",
"0.54804033",
"0.547729",
"0.54767454",
"0.54747295",
"0.5474158",
"0.5473965",
"0.5470719",
"0.5469596",
"0.54691446",
"0.54656625",
"0.5464798",
"0.54642045"
] | 0.0 | -1 |
lista todos los tipo de servicios disponibles en un select | def get_list_service_types
ServiceType.get_list_service_types
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def read_service_types()\n types = []\n @client.services.each do |type|\n types << type.label\n end\n\n types\n end",
"def get_service_types\n if @servicetypes.any?\n @servicetypes.flat_map(&:servicetype).compact\n elsif @servicetype\n [@servicetype]\n else\n []\n end\n end",
"def service_types\n get_info :service_types\n end",
"def select_type\n\t\t\t@select_all_type = TypeEquipament.all\n\t\tend",
"def services\n\t\tselect {|x| x.class == Service }\n\tend",
"def index\n @tipo_de_servicios = TipoDeServicio.all\n end",
"def service_types_generated \n types = [ ServiceTypeValue[:fulltext], ServiceTypeValue[:holding], ServiceTypeValue[:table_of_contents], ServiceTypeValue[:relevant_link] ]\n \n return types\n end",
"def collect_tier_categories_for_select(klass, select=true)\n result = klass.find_all_categories.map {|c| [c.name, c.id]}\n result.insert(0, [\"Select...\".t, nil])\n result\n end",
"def select_tiporelacion\n [ \n [\"BENEFICIARIO\",\"BENEFICIARIO\"],\n [\"INTEGRANTE\",\"INTEGRANTE\"],\n [\"PROPIETARIO\",\"PROPIETARIO\"],\n [\"APODERADO\",\"APODERADO\"]\n ] \n end",
"def build_selects_from_types(order)\n select = +\"\"\n first_visible = order.find { |type| !@options[:\"discard_#{type}\"] }\n order.reverse_each do |type|\n separator = separator(type) unless type == first_visible # don't add before first visible field\n select.insert(0, separator.to_s + public_send(\"select_#{type}\").to_s)\n end\n select.html_safe\n end",
"def select\n @type = params[:type]\n @hosts = Host.all :select => \"id, name\" , :conditions => { :tenant_id => current_user.tenant_id } if @type == \"host\"\n @apps = App.all :select => \"id, name\" , :conditions => { :tenant_id => current_user.tenant_id } if @type == \"app\"\n @sites = Site.all :select => \"id, name\" , :conditions => { :tenant_id => current_user.tenant_id } if @type == \"site\"\n @devices = Device.all :select => \"id, name\" , :conditions => { :tenant_id => current_user.tenant_id } if @type == \"device\"\n end",
"def company_opportunity_select_type\n [\n ['Proyecto virtual', Opportunity::TYPE_VIRTUAL],\n ['Trabajos express', Opportunity::TYPE_SEASONAL],\n ['Empleo temporal', Opportunity::TYPE_ON_SITE],\n ['Empleo', Opportunity::TYPE_FIRST_JOB],\n ['Práctica', Opportunity::TYPE_PRACTICE]\n ]\n end",
"def list_selected_options\n list_selected_options = []\n @selected_options.each do |option|\n list_selected_options << option.type\n end\n return list_selected_options\n end",
"def opportunity_contract_type_select\n [\n ['Contrato a Termino Fijo.', 1],\n ['Contrato a Termino Indefinido.', 2],\n ['Contrato de Obra o Labor.', 3],\n ['Contrato de Aprendizaje.', 4],\n ['Contrato Civil por Prestación de Servicios', 5]\n ]\n end",
"def choose_new_type\n @types = Poll.all_types_for_select\n end",
"def build_selects_from_types(order); end",
"def service_types_generated\n [\n ServiceTypeValue['fulltext'],\n ServiceTypeValue['holding'],\n ServiceTypeValue['highlighted_link'],\n ServiceTypeValue['disambiguation'],\n ServiceTypeValue['site_message']\n ]\n end",
"def types\n [\n { value: 'bus', name: 'Bus' },\n { value: 'coach', name: 'Coach' },\n { value: 'hgv', name: 'Heavy goods vehicle' },\n { value: 'van', name: 'Van' },\n { value: 'minibus', name: 'Minibus' },\n { value: 'private_car', name: 'Car' },\n { value: 'motorcycle', name: 'Motorcycle' }\n ]\n end",
"def set_tipo_de_servicio\n @tipo_de_servicio = TipoDeServicio.find(params[:id])\n end",
"def index\n @kinds = Kind.create_select_options\n end",
"def get_select_format\n \treturn @OFFER_TYPES.map{|v| [v,v]}\n end",
"def type_of_student_select_type\n [\n ['Diurno', Student::TYPE_OF_STUDENT_DAY],\n ['Nocturno', Student::TYPE_OF_STUDENT_NIGHT],\n ['Virtual', Student::TYPE_OF_STUDENT_VIRTUAL],\n ['Esperando diploma', Student::TYPE_OF_STUDENT_DIPLOMA_PENDING],\n ['Graduado', Student::TYPE_OF_STUDENT_GRADUATE]\n ]\n end",
"def index\n @formularios = Formulario.search\n @select_options = Formulario.get_name_folder\n end",
"def list\n \n @product_types = ProductType.find(:all, :order => \"name\")\n end",
"def select(params = {})\n if params.has_key?(:path)\n path_regex = params[:path]\n path_regex = Regexp.new(path_regex.to_s) unless path_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && path_regex.match(agent.config_path) }\n notify(:msg => \"[#{@name}] Selecting all services for path #{path_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:type)\n type_regex = params[:type]\n type_regex = Regexp.new(type_regex.to_s) unless type_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && type_regex.match(agent.type) }\n notify(:msg => \"[#{@name}] Selecting all services of type #{type_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:core_type)\n core_type_regex = params[:core_type]\n core_type_regex = Regexp.new(core_type_regex.to_s) unless core_type_regex.is_a?(Regexp)\n selector = lambda {|agent| agent.config_path && core_type_regex.match(agent.core_type) }\n notify(:msg => \"[#{@name}] Selecting all services of core type #{core_type_regex.inspect}\",\n :tags => [:galaxy, :trace])\n elsif params.has_key?(:host) || params.has_key?(:hosts)\n host_names = arrayify(params[:host]) & arrayify(params[:hosts])\n selector = lambda {|agent| host_names.include?(agent.host) }\n notify(:msg => \"[#{@name}] Selecting all services for hosts #{host_names.inspect}\",\n :tags => [:galaxy, :trace])\n else\n notify(:msg => \"[#{@name}] Selecting all services\",\n :tags => [:galaxy, :trace])\n end\n command = ::Galaxy::Commands::ShowCommand.new([], @galaxy_options)\n command.report = GalaxyGatheringReport.new(@environment)\n agents = command.select_agents({})\n agents.each { |agent| agent.proxy = ::Galaxy::Transport.locate(agent.url) if agent.url }\n command.execute(agents)\n command.report.results.select {|result| selector.nil? || selector.call(result) }\n end",
"def envia_taxones_seleccionados\n end",
"def index\n @os_nivel_servicos = OsNivelServico.all\n end",
"def select_list; end",
"def type_names\n\t\ttypes_names = DATABASE.execute(\"SELECT name FROM types WHERE id='#{self.type_id[0]}' OR id='#{self.type_id[1]}';\") \t\n\t\treturn types_names\n\tend",
"def get_services (type = nil, pool = nil)\n\n # NOTE: query_for_services asks for everything, rather than using the\n # more selective resource paths provided by the discovery services.\n # This allows the user to query for all services in a given pool,\n # which is not an available resource path\n\n if !pool.nil? && type.nil?\n service_data = query_for_services()\n result = []\n\n service_data['services'].each do |service|\n if type.nil? || service['type'].eql?(type)\n result << service if pool.nil? || service['pool'].eql?(pool)\n end\n end\n\n return result\n end\n\n service_data = query_for_services(type, pool)\n return service_data[\"services\"]\n end",
"def get_tipoDoc\n typedoc = TipoDocumento.all\n tipos = []\n tipos.push(\"Otro\")\n for type in typedoc do\n tipos.push(type.descripcion)\n end\n return tipos\n end",
"def opportunity_date_ini_type_select\n [\n ['Indefinida', Opportunity::TYPE_UNDEFINED],\n ['Lo antes posible', Opportunity::TYPE_AS_SOON_AS_POSSIBLE],\n ['Fijar fecha', Opportunity::TYPE_SET_DATE_INI]\n ]\n end",
"def select_type_montant\n [\n \t['montant_ht', \"Montant Hors-Taxe\"],\n \t['montant_ttc', \"Montant TTC\"],\n \t['montant_net', \"Net à payer\"]\n ].in_select(id:'facture_montant_id', name:\"facture[montant_id]\")\nend",
"def pet_types\r\n BnetApi::make_request('/wow/data/pet/types')\r\n end",
"def index\n @tipo_veiculos = TipoVeiculo.all\n end",
"def query_for_services(type = nil, pool = nil)\n\n raise \"Type must not be nil if pool is nil\" if type.nil? && !pool.nil?\n\n @discovery_urls.each do |discovery_url|\n resource = \"/v1/service\"\n resource += \"/#{type}\" if ! type.nil?\n resource += \"/#{pool}\" if ! pool.nil?\n\n service_uri = URI.parse(discovery_url).merge(resource)\n\n @logger.debug(\"Get Request: #{service_uri.to_s}\")\n\n begin\n response = @client.get(service_uri.to_s, nil, nil)\n\n if response.status >= 200 && response.status <= 299\n service_data = JSON.parse(response.body)\n\n return service_data\n end\n\n @logger.error(\"#{service_uri.to_s}: Response Status #{response.status}\")\n @logger.error(response.body)\n\n rescue\n @logger.error(\"#{service_uri.to_s}: #{$!}\")\n end\n\n end\n\n raise \"Failed to get all services from any of [ #{@discovery_urls.join(\",\")} ]\"\n\n end",
"def select_options\n all.map {|e| [e.name, e.to_s] }\n end",
"def select_options\n all.map {|e| [e.name, e.to_s] }\n end",
"def tecnicos_postulados\n coleccion = []\n self.request.each do |request|\n info = {}\n info[:id] = request.id\n info[:article] = request.article\n info[:servicio] = request.service.description\n info[:tecnicos] = request.proposal\n coleccion.append(info)\n end\n coleccion\n end",
"def tipo_periodos\n @tipo_periodos = TipoPeriodo.all.where('id not in (?)',Periodo.all.where(nivel: params[:id]).select(:tipo_periodo_id))\n end",
"def get_listbox_data\n @countries = current_user.company.countries.dropdown_list\n @sectors = current_user.company.sectors.order(:sector)\n @rel_types = current_user.company.rel_types.dropdown_list\n @relationgroups = current_user.company.relations.dropdown_list\n end",
"def index\n @services = current_user.services.map{|s| s.becomes(s.name.constantize)}\n end",
"def new_creatable_selection\n select_tag :model_type,options_for_select(creatable_classes.collect{|c| [c.underscore.humanize,c.underscore] })\n end",
"def services\n related_objects_by_type(\"Service\")\n end",
"def index\n @option_types = OptionType.page params[:page]\n end",
"def menu_servicio\n\t\tmenu = \"Seleccione tipo de servicio\"\n\t\tmenu += \"\\n\\tDistrital\"\n\t\tmenu += \"\\n\\tInterprovincial\"\n\t\tmenu += \"\\n\\tInterdepartamental\"\n\t\treturn menu\n\tend",
"def fenix_product_options_types(p)\n values=p.option_types.to_a.map! do |ot|\n \"#{ot.presentation}\"\n end\n values.to_sentence({ words_connector: \", \", two_words_connector: \", \" })\n end",
"def fenix_product_options_types(p)\n values=p.option_types.to_a.map! do |ot|\n \"#{ot.presentation}\"\n end\n values.to_sentence({ words_connector: \", \", two_words_connector: \", \" })\n end",
"def services\n unless @services\n rows = database.view(VIEW_NAME, reduce: false, key: [1, name])['rows'] rescue []\n ids = rows.map {|row| row['value'] }\n @services = Service.all.keys(ids).to_a\n end\n @services\n end",
"def select_tiposdocumemto\n [\n [\"CARTAS DE PROPIETARIOS SOLICITANDO LA VIVIENDA\",\"CARTAS DE PROPIETARIOS SOLICITANDO LA VIVIENDA\"],\n [\"CARTAS PARA CAMBIO DE VIVIENDA\",\"CARTAS PARA CAMBIO DE VIVIENDA\"],\n [\"CARTAS RECIBIDAS PARA SOLICITUD DE AUMENTO DE CANON\",\"CARTAS RECIBIDAS PARA SOLICITUD DE AUMENTO DE CANON\"],\n [\"DOCUMENTACION DE TENENCIA DE VIVIENDA EVACUADA\",\"DOCUMENTACION DE TENENCIA DE VIVIENDA EVACUADA\"],\n [\"DOCUMENTACION DE VIVIENDA PARA ARRENDAR POR PRIMERA VEZ\",\"DOCUMENTACION DE VIVIENDA PARA ARRENDAR POR PRIMERA VEZ\"],\n [\"DOCUMENTACION DE VIVIENDAS DISPONIBLES\",\"DOCUMENTACION DE VIVIENDAS DISPONIBLES\"],\n [\"DOCUMENTACION PARA CAMBIO DE VIVIENDA\",\"DOCUMENTACION PARA CAMBIO DE VIVIENDA\"],\n [\"DOCUMENTOS SOPORTES DE INGRESOS FAMILIARES\",\"DOCUMENTOS SOPORTES DE INGRESOS FAMILIARES\"],\n [\"DOCUMENTOS DE IDENTIDAD DEL GRUPO FAMILIAR\",\"DOCUMENTOS DE IDENTIDAD DEL GRUPO FAMILIAR\"],\n [\"OTROS DOCUMENTOS\",\"OTROS DOCUMENTOS\"],\n [\"PAZ Y SALVOS RECIBIDOS\",\"PAZ Y SALVOS RECIBIDOS\"]\n ]\n end",
"def index\n @registro_servicios = Registro::Servicio.all\n end",
"def get_product_count_types\n types = CountType.where(product_id: params[:product_id]).order(\"name ASC\").map { |type| [type.id, type.name] }\n render :json => types.to_json.to_s.to_json\n end",
"def index\n @os_types = OsType.all\n end",
"def option_select_estado(estado = nil)\n html = \"\"\n if estado\n html << \"<option value='#{ estado }'>#{ estado.uf_to_nome }</option>\"\n elsif @usuario_logado and @usuario_logado.end_estado\n html << \"<option value='#{ @usuario_logado.end_estado }'>#{ @usuario_logado.end_estado.uf_to_nome }\"\n end\n ESTADOS.each {|e| html << \"<option value='#{ e }'>#{ e.uf_to_nome }</option>\"}\n html.html_safe\n end",
"def types()\n\t\t@pokemon_types = []\n\t\t@pokemon_api[\"types\"].each do |i|\n\t\t\t@pokemon_types.push(i[\"type\"][\"name\"].capitalize)\n\t\tend\n\t\treturn @pokemon_types\n\tend",
"def types\n @opt_types.values\n end",
"def load_selectors(value_type)\n selectors.active.where(value_type: value_type).to_a\n end",
"def index\n @api_v1_select_fields = Api::V1::SelectField.all\n end",
"def types\n list = Array.new\n\n if @db != nil\n is_ok = false\n\n begin\n stm = @db.prepare( 'SELECT qType FROM qryResults GROUP BY qType ORDER BY qType')\n rs = stm.execute\n\n rs.each do |row|\n list.push row['qType']\n end\n\n stm.close\n is_ok = true\n rescue ::SQLite3::Exception => e\n Maadi::post_message(:Warn, \"Repository (#{@type}:#{@instance_name}) encountered an SELECT Types error (#{e.message}).\")\n end\n end\n\n return list\n end",
"def tipo_name\n if tipo == 1 \n 'Venta'\n elsif tipo == 2\n 'Compra'\n elsif tipo == 3\n 'Renta'\n elsif tipo == 4\n 'Servicios'\n elsif tipo == 5\n 'Ofresco Trabajo'\n elsif tipo == 6\n 'Busco Trabajo'\n end\n end",
"def insert_instant_messenger_type_options(form)\n form.collection_select :type_id, InstantMessengerType.all,\n :id, :description, {}\n end",
"def index\n @servicos = Servico.all\n end",
"def index\n @grocer_service_types = GrocerServiceType.all\n end",
"def types(options={})\n select_from_hash_array(TRANSACTION_METHODS, :type, {}, options)\n end",
"def types(options={})\n select_from_hash_array(TRANSACTION_METHODS, :type, {}, options)\n end",
"def especies_filtros\n return unless tiene_filtros?\n self.taxones = Especie.select(:id).select(\"#{Scat.attribute_alias(:catalogo_id)} AS catalogo_id\").joins(:scat).distinct\n por_especie_id\n por_nombre\n #estatus\n #solo_publicos\n estado_conservacion\n tipo_distribucion\n uso\n formas_crecimiento\n ambiente\n\n #return unless por_id_o_nombre\n #categoria_por_nivel\n end",
"def select_options_for_court_sports\n @court_sports_enums = Court.where(venue_id: authorized_scope(company.venues).select(:id)).active.\n pluck('distinct sport_name')\n @court_sports = @court_sports_enums.map { |n| Court.sport_names.key(n) }\n render json: @court_sports.map { |x| { value: x, label: x.humanize } }\n end",
"def index\n @categorie_services = CategorieService.all\n end",
"def index\n @q = Servicetype.search(params[:q])\n @servicetypes = @q.result(:distinct => true).page(params[:page]).per(10)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json do\n @servicetype = Servicetype.where(\"name LIKE ?\", \"%#{params[:term]}%\")\n render :json => @servicetype.map { |servicetype| servicetype.name }\n end\n end \n end",
"def index\n @ativos = type_class.all\n end",
"def type_select object, method, label_text, options\n content_tag :div, :class => :\"type-select\" do\n attr_id = \"#{object.class.to_s.downcase}[#{method}]\".to_sym\n output = String.new\n output << content_tag(:label, label_text, :for => attr_id) unless label_text.blank?\n output << select_tag(attr_id, options)\n end\n end",
"def find_service_types(auth = '*', scope = '')\n arr = []\n\n callback = Proc.new{ |_hslp, types, err, _cookie|\n if err == SLP_OK\n arr << types\n true\n else\n false\n end\n }\n\n begin\n cookie = FFI::MemoryPointer.new(:void)\n result = SLPFindSrvTypes(@handle, auth, scope, callback, cookie)\n raise Error, \"SLPFindSrvTypes(): #{result}\" if result != :SLP_OK\n ensure\n cookie.free unless cookie.null?\n end\n\n arr\n end",
"def index\n @tipo_unidades = TipoUnidad.all\n end",
"def index\n @tb_servicios = TbServicio.all\n end",
"def list_puc_types\n\treturn if authorise_for_web(program_name?,'read') == false \n\n \tif params[:page]!= nil \n\n \t\tsession[:puc_types_page] = params['page']\n\n\t\t render_list_puc_types\n\n\t\t return \n\telse\n\t\tsession[:puc_types_page] = nil\n\tend\n\n\tlist_query = \"@puc_type_pages = Paginator.new self, PucType.count, @@page_size,@current_page\n\t @puc_types = PucType.find(:all,\n\t\t\t\t :limit => @puc_type_pages.items_per_page,\n\t\t\t\t :offset => @puc_type_pages.current.offset)\"\n\tsession[:query] = list_query\n\trender_list_puc_types\nend",
"def index\n @tipo_fornecedors = TipoFornecedor.all\n end",
"def show\n @mensalist = Mensalist.find(params[:id])\n @services = Service.select(:id, :price, :name)\n\n @selected_services = @mensalist.services.map{ |e| \n JSON.parse(e).with_indifferent_access \n }\n \n @selected_services_ids = @selected_services.map{ |e| e[\"id\"] }\n render layout: \"application\"\n end",
"def ooc_scan_type_list(gui_active_only = false)\n scan_types =OocScanType.find_by_sql(\"select ooc_scan_type\n from hip_ooc_scan_type_v #{\"where active_in_gui = 'y'\" if gui_active_only}\n group by grouping sets ((ooc_scan_type, ooc_group_type),(ooc_group_type))\n order by ooc_group_type, ooc_scan_type\")\n array=[]\n scan_types.each do |type|\n array.push(type['ooc_scan_type']) unless type['ooc_scan_type'].blank?\n array.push('--------------') if type['ooc_scan_type'].blank?\n end\n array.pop # remove the last blank line\n return array\n end",
"def index\n @clientes_servicos = ClientesServico.all\n end",
"def get_all_outypes\n path = \"/d2l/api/lp/#{$lp_ver}/outypes/\"\n _get(path)\nend",
"def get_fuel_types\n relatable_category_id = params[:car_calculator][:manufacture]\n result = CarApp.calculated_session.related_categories_from_relatable_category(relatable_category_id, \"fuel_type\") \n final_result = []\n result = result.each_pair do |key, value| \n final_result << {:name => value, :value => key}\n end\n render :json => {:options => final_result}.to_json\n end",
"def index\n @ordem_servicos = OrdemServico.all\n end",
"def index\n @ordem_servicos = OrdemServico.all\n end",
"def validar_tipo_servicio(valor)\n\t\tuntil valor == \"DISTRITAL\" or\n\t\t\t\t\tvalor == \"INTERPROVINCIAL\" or\n\t\t\t\t\tvalor == \"INTERDEPARTAMENTAL\"\n\t\t\tputs \"Por favor, elija un servicio del menú\"\n\t\t\tputs menu_servicio\n\t\t\tvalor = gets.chomp.upcase\n\t\tend\n\t\treturn valor\n\tend",
"def select_collection_types(test_data)\n types = test_data[UseOfCollections::COLLECTION_TYPE_LIST.name] || [{ UseOfCollections::COLLECTION_TYPE.name => ''}]\n prep_fieldsets_for_test_data([fieldset(UseOfCollections::COLLECTION_TYPE_LIST.name)], types)\n\n types.each_with_index do |type, index|\n wait_for_options_and_select(collection_type_input(index), collection_type_options(index), type[UseOfCollections::COLLECTION_TYPE.name])\n end\n end",
"def test_ListPlatformTypes\n\t\tcolName = 'types'\n\t\tretClass = LeanTesting::PlatformType\n\t\tresp = rcol(colName, ['_id', 'name'])\n\t\t@client.debugReturn = {'data'=> JSON.generate(resp), 'status'=> 200}\n\n\t\tcol = @client.platform.types.all\n\n\t\tassert_equal resp[colName], col.toArray\n\t\tassert_instance_of retClass, col.collection[0]\n\t\tassert_equal resp['meta']['pagination']['total'], col.total\n\t\tassert_equal resp['meta']['pagination']['total_pages'], col.totalPages\n\t\tassert_equal resp['meta']['pagination']['count'], col.count\n\tend",
"def options_html(type, is_person, super_entity, cid=\"00\", return_type=\"html\")\n sel_flag = true\n sel_str = \"\"\n\n poa_str = \" (Principal Entity) \"\n poa_str = \" (Principal Individual) \" if is_person == \"true\"\n\n array_result = []\n select_one_html = \"<option value=''>Select One...</option>\"\n result = \"\"\n\n if is_person == \"true\"\n groups = {}\n\n case type\n when \"stockholder\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"principal\"\n person_true_entities = current_user.entities_list(super_entity).where(type_: [1, 2, 4]).order(type_: :asc)\n when \"agent\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2]).where('id != ?', super_entity.principal.entity_id).order(type_: :asc)\n when \"settlor\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"trustee\"\n if super_entity.beneficiaries.select(:entity_id).map(&:entity_id).blank?\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 3, 4]).order(type_: :asc)\n else\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 3, 4]).where('id not in (?)', super_entity.beneficiaries.select(:entity_id).map(&:entity_id)).order(type_: :asc)\n end\n when \"beneficiary\"\n if super_entity.trustees.select(:entity_id).map(&:entity_id).blank?\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n else\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).where('id not in (?)', super_entity.trustees.select(:entity_id).map(&:entity_id)).order(type_: :asc)\n end\n when \"member\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"manager\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"general-partner\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"limited-partner\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"partner\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 3, 4]).order(type_: :asc)\n when \"limited-liability-partner\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 3, 4]).order(type_: :asc)\n when \"director\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 3]).order(type_: :asc)\n when \"officer\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 3]).order(type_: :asc)\n when \"tenant-in-common\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"spouse\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 3, 4]).order(type_: :asc)\n when \"joint-tenant\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1, 2, 3, 4]).order(type_: :asc)\n when \"guardian\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1]).order(type_: :asc)\n when \"ward\"\n person_true_entities = current_user.entities_list(super_entity.id).where(type_: [1]).order(type_: :asc)\n else\n person_true_entities = []\n end\n\n person_true_entities.each do |entity|\n key = \"#{MemberType.member_types[entity.type_]}\"\n key = key + poa_str if !key.match(\"ttorney\").nil?\n if groups[key].nil?\n groups[key] = [entity]\n else\n groups[key] << entity\n end\n end\n\n case type\n when \"stockholder\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Corporate Stockholder', user_id: current_user.id)\n when \"principal\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Principal', user_id: current_user.id)\n when \"agent\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Agent', user_id: current_user.id)\n when \"settlor\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Settlor', user_id: current_user.id)\n when \"trustee\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Trustee', user_id: current_user.id)\n when \"beneficiary\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Beneficiary', user_id: current_user.id)\n when \"member\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'LLC Member', user_id: current_user.id)\n when \"manager\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'LLC Outside Manager', user_id: current_user.id)\n when \"general-partner\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'LP General Partner', user_id: current_user.id)\n when \"limited-partner\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'LP Limited Partner', user_id: current_user.id)\n when \"partner\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Partner', user_id: current_user.id)\n when \"limited-liability-partner\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Limited Liability Partner', user_id: current_user.id)\n when \"director\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Corporate Director', user_id: current_user.id)\n when \"officer\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Corporate Officer', user_id: current_user.id)\n when \"tenant-in-common\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Tenant in Common', user_id: current_user.id)\n when \"spouse\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Tenant by Entirety', user_id: current_user.id)\n when \"joint-tenant\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Joint Tenant', user_id: current_user.id)\n when \"judge\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Judge', user_id: current_user.id)\n when \"guardian\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Guardian', user_id: current_user.id)\n when \"ward\"\n person_true_contacts = Contact.all.where(is_company: false, contact_type: 'Client Participant', role: 'Ward', user_id: current_user.id)\n else\n person_true_contacts = []\n end\n\n groups.each do |k,v|\n result += \"<optgroup label='#{k}'>\"\n v.each do |entity|\n if (sel_flag && \"e#{entity.id}\" == cid) || (person_true_entities.count + person_true_contacts.count == 1)\n sel_flag = false\n sel_str = \" selected='selected' \"\n else\n sel_str = \"\"\n end\n result += \"<option value='e#{entity.id}' data-type='entity' #{sel_str}>#{entity.name} </option>\"\n array_result << [entity.id, entity.name]\n end\n result += \"</optgroup>\"\n end\n\n result += \"<optgroup label='Contacts'>\"\n\n person_true_contacts.each do |contact|\n if (sel_flag && \"c#{contact.id}\" == cid) || (person_true_entities.count + person_true_contacts.count == 1)\n sel_flag = false\n sel_str = \" selected='selected' \"\n else\n sel_str = \"\"\n end\n result += \"<option value='c#{contact.id}' data-type='contact' #{sel_str}>#{contact.name}</option>\"\n array_result << [contact.id, contact.name]\n end\n\n result += \"</optgroup>\"\n if return_type == 'html'\n if array_result.length > 1\n return (select_one_html + result).html_safe\n else\n return result.html_safe\n end\n else\n return array_result\n end\n\n else\n groups = {}\n\n case type\n when \"stockholder\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [6, 10, 11, 12, 13, 14]).order(type_: :asc)\n when \"principal\"\n person_false_entities = current_user.entities_list(super_entity).where(type_: [6, 10, 11, 12, 13, 14]).order(type_: :asc)\n when \"agent\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [10, 11, 12, 13, 14]).where('id != ?', super_entity.principal.entity_id).order(type_: :asc)\n when \"trustee\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [10, 11, 12, 13, 14]).order(type_: :asc)\n when \"beneficiary\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [6]).order(type_: :asc)\n when \"member\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [6, 10, 11, 12, 13, 14]).order(type_: :asc)\n when \"manager\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [10, 11, 12, 13, 14]).order(type_: :asc)\n when \"general-partner\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [10, 11, 12, 13, 14]).order(type_: :asc)\n when \"limited-partner\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [10, 11, 12, 13, 14]).order(type_: :asc)\n when \"tenant-in-common\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [6, 10, 11, 12, 13, 14]).order(type_: :asc)\n when \"guardian\"\n person_false_entities = current_user.entities_list(super_entity.id).where(type_: [14]).order(type_: :asc)\n else\n person_false_entities = []\n end\n\n person_false_entities.each do |entity|\n key = \"#{MemberType.member_types[entity.type_]}\"\n key = key + poa_str if !key.match(\"ttorney\").nil?\n if groups[key].nil?\n groups[key] = [entity]\n else\n groups[key] << entity\n end\n end\n\n case type\n when \"stockholder\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'Corporate Stockholder', user_id: current_user.id)\n when \"principal\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'Principal', user_id: current_user.id)\n when \"agent\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'Agent', user_id: current_user.id)\n when \"trustee\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'Trustee', user_id: current_user.id)\n when \"member\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'LLC Member', user_id: current_user.id)\n when \"manager\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'LLC Outside Manager', user_id: current_user.id)\n when \"general-partner\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'LP General Partner', user_id: current_user.id)\n when \"limited-partner\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'LP Limited Partner', user_id: current_user.id)\n when \"tenant-in-common\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'Tenant in Common', user_id: current_user.id)\n when \"judge\"\n person_false_contacts = Contact.all.where(is_company: true, contact_type: 'Client Participant', role: 'Judge', user_id: current_user.id)\n else\n person_false_contacts = []\n end\n\n groups.each do |k,v|\n result += \"<optgroup label='#{k}'>\"\n v.each do |entity|\n if (sel_flag && \"e#{entity.id}\" == cid) || (person_false_entities.count + person_false_contacts.count == 1)\n sel_flag = false\n sel_str = \" selected='selected' \"\n else\n sel_str = \"\"\n end\n result += \"<option value='e#{entity.id}' data-type='entity' #{sel_str}>#{entity.name} </option>\"\n array_result << [entity.id, entity.name]\n end\n result += \"</optgroup>\"\n end\n\n result += \"</optgroup><optgroup label='Contacts '>\"\n\n person_false_contacts.each do |contact|\n if (sel_flag && \"c#{contact.id}\" == cid) || (person_false_entities.count + person_false_contacts.count == 1)\n sel_flag = false\n sel_str = \" selected='selected' \"\n else\n sel_str = \"\"\n end\n result += \"<option value='c#{contact.id}' data-type='contact' #{sel_str}>#{contact.name}</option>\"\n array_result << [contact.id, contact.name]\n end\n\n result += \"</optgroup>\"\n if return_type == 'html'\n if array_result.length > 1\n return (select_one_html + result).html_safe\n else\n return result.html_safe\n end\n else\n return array_result\n end\n\n end\n end",
"def types\n types = Question.distinct.pluck(:type)\n render json: types.to_a\n end",
"def index\n @client_types = ClientType.all\n end",
"def show\n combo_producto\n combo_platillo\n end",
"def describe_types\n [@options[:type]].flatten.join('/')\n end",
"def index\n @solicitacao_tipos = SolicitacaoTipo.all\n end",
"def index\n @q = ClientType.order(name: :asc).ransack(params[:q])\n @client_types = @q.result.page(params[:page]).per(10)\n end",
"def list_services\n @services\n end",
"def camaleon_first_list_select\n res = []\n current_site.the_post_types.decorate.each {|p| res << \"<option value='#{p.the_slug}'>#{p.the_title}</option>\" }\n res.join(\"\").html_safe\n end",
"def option_folio\n @folios = Folio.where(input_type_id: params[:input_type_id])\n end",
"def tipoDistribucionChecklist(taxon)\n if params[:f_desc].present? && params[:f_desc].include?('x_tipo_distribucion')\n taxon.tipos_distribuciones.map(&:descripcion).uniq\n end\n end",
"def cash_services \n services.select{|i| i[:btype] && i[:btype] == CASH_BILLING} rescue []\n end",
"def service_types_index\n index = {}\n ServiceType.all.each do |service_type|\n index[service_type.id] = service_type\n end\n index\n end",
"def build_select(type, select_options_as_html); end"
] | [
"0.68860745",
"0.6843919",
"0.67053306",
"0.6339248",
"0.61899334",
"0.6172209",
"0.6148775",
"0.61228436",
"0.60997295",
"0.60421866",
"0.60223836",
"0.6022306",
"0.6009809",
"0.6005978",
"0.598768",
"0.5978137",
"0.5886875",
"0.5878637",
"0.5790964",
"0.5789346",
"0.57886183",
"0.57711536",
"0.57679784",
"0.57561135",
"0.57284164",
"0.5708121",
"0.56894857",
"0.5678289",
"0.5671971",
"0.5671489",
"0.5637919",
"0.5634625",
"0.56313914",
"0.56228596",
"0.5618036",
"0.5612285",
"0.5605889",
"0.5605889",
"0.56039244",
"0.5582413",
"0.5578089",
"0.55769706",
"0.5570496",
"0.55685085",
"0.55299056",
"0.54962516",
"0.5478753",
"0.5478753",
"0.5466879",
"0.54654",
"0.54554546",
"0.5435365",
"0.5429708",
"0.54230314",
"0.5414048",
"0.5413492",
"0.5405496",
"0.54054725",
"0.5399776",
"0.53919595",
"0.53889126",
"0.5383965",
"0.53796864",
"0.53774065",
"0.53774065",
"0.53742176",
"0.5372657",
"0.536085",
"0.5355663",
"0.53466356",
"0.5346267",
"0.5345397",
"0.53376293",
"0.53368324",
"0.5331602",
"0.5316253",
"0.5315983",
"0.5314093",
"0.53121895",
"0.53076327",
"0.53044087",
"0.53039134",
"0.53039134",
"0.53014106",
"0.52938527",
"0.52895963",
"0.5289536",
"0.5288732",
"0.52882016",
"0.52827364",
"0.52803993",
"0.527972",
"0.5270536",
"0.5269177",
"0.5268179",
"0.52650106",
"0.52602196",
"0.52536297",
"0.52487725",
"0.5246398"
] | 0.6650234 | 3 |
lista todos las formas de pagos disponibles en un select | def get_list_payments_methods
PaymentMethod.get_list_payment_methods
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @formularios = Formulario.search\n @select_options = Formulario.get_name_folder\n end",
"def index\n @formasdepagos = current_user.empresa.formasdepagos.page params[:page]\n end",
"def index\n @option_types = OptionType.page params[:page]\n end",
"def forms_fields(form, action)\n section_fields = []\n form.form_sections.each do |section|\n if section['permissions'][\"#{current_user.role.short_name}\"][action] == '1'\n section_fields << section.section_fields.map do |field|\n if field.field_type.field_type.start_with?('select') && field.field_type.options['multivalue'] == '1'\n { field.id.to_s.to_sym => [] }\n else\n field.id.to_s.to_sym\n end\n end\n end\n end\n section_fields\n end",
"def pages_for_select(pages = nil, selected = nil, prompt = \"Bitte wählen Sie eine Seite\")\n result = [[prompt, \"\"]]\n if pages.blank?\n pages = Page.find_all_by_language_and_public(session[:language], true)\n end\n pages.each do |p|\n result << [p.send(:name), p.send(:urlname)]\n end\n options_for_select(result, selected)\n end",
"def index\n @elevator_forms = ElevatorForm.paginate(page: params[:page]).per_page(10)\n end",
"def index\n @forms = Form.where(hidden: false).page params[:page]\n end",
"def index\n @api_v1_select_fields = Api::V1::SelectField.all\n end",
"def pages_for_select(pages = nil, selected = nil, prompt = \"\", page_attribute = :id)\n result = [[prompt.blank? ? _t('Choose page') : prompt, \"\"]]\n if pages.blank?\n pages = Page.with_language(session[:language_id]).published.order(:lft)\n pages.each do |p|\n result << [(\" \" * (p.level - 1) + p.name).html_safe, p.send(page_attribute).to_s]\n end\n else\n pages.each do |p|\n result << [p.name, p.send(page_attribute).to_s]\n end\n end\n options_for_select(result, selected.to_s)\n end",
"def per_page_options_for_select\n return [] if blacklight_config.per_page.blank?\n\n blacklight_config.per_page.map do |count|\n [t(:'blacklight.search.per_page.label', count: count).html_safe, count]\n end\n end",
"def index\n @pessel_forms = PesselForm.all\n end",
"def pages_for_select(pages = nil, selected = nil, prompt = \"Choose page\", page_attribute = :id)\n values = [[_t(prompt), \"\"]]\n pages ||= begin\n nested = true\n Page.with_language(session[:language_id]).published.order(:lft)\n end\n values += pages_attributes_for_select(pages, page_attribute, nested)\n options_for_select(values, selected.to_s)\n end",
"def pages_for_select(pages = nil, selected = nil, prompt = \"Choose page\", page_attribute = :id)\n values = [[_t(prompt), \"\"]]\n pages ||= begin\n nested = true\n Language.current.pages.published.order(:lft)\n end\n values += pages_attributes_for_select(pages, page_attribute, nested)\n options_for_select(values, selected.to_s)\n end",
"def index\n @admin_forms = Admin::Form.all.order('id DESC').page(params[:page])\n end",
"def list_pages(doc)\n # Search for nodes by css\n pages = []\n doc.xpath(\"//select[@id='pageMenu']/option\").each do |page|\n pages << page.text.to_i\n end\n end",
"def index\n (@filterrific = initialize_filterrific(\n Form.cpuproduced_form,\n params[:filterrific],\n select_options: {\n sorted_by: Form.options_for_sorted_by\n },\n )) || return\n @forms = @filterrific.find.page(params[:page])\n\n respond_to do |format|\n format.html\n format.js\n end\n end",
"def per_page_select_html\n \n options = [10,20,50,100,250].collect{|x| [\n \"#{x} per page\", \n url_for(params.merge(:per_page => x))\n ]}\n \n current_selected = url_for(params.merge(:per_page => per_page))\n \n select_tag \"per_page\", options_for_select(options, current_selected)\n \n end",
"def index\n @formaspagamentos = Formaspagamento.all\n end",
"def index\n @formapagamentos = Formapagamento.all\n end",
"def index\n @formapagtos = Formapagto.all\n end",
"def list_page(type, opts={})\n page do\n form_attr = form_attributes(opts[:form] || {:action=>url_for(type)})\n Forme.form(form_attr, form_opts) do |f|\n input_opts = {:name=>'id', :id=>'id', :label=>model.class_name}\n if model.autocomplete_options_for(type, request)\n input_type = :text\n input_opts.merge!(:class=>'autoforme_autocomplete', :attr=>{'data-type'=>type})\n else\n input_type = :select\n input_opts.merge!(:options=>model.select_options(type, request), :add_blank=>true)\n end\n f.input(input_type, input_opts)\n f.button(:value=>type.to_s.capitalize, :class=>\"btn btn-#{type == :delete ? 'danger' : 'primary'}\")\n end\n end\n end",
"def forms\n option_sets.collect{|os| os.questionings.collect(&:form)}.flatten.uniq\n end",
"def form_select\n if Contact.order(\"last_name ASC, first_name ASC\").collect.present?\n Contact.order(\"last_name ASC, first_name ASC\").collect {|p| [ p.last_name + ', ' + p.first_name, p.id ] }\n end\n end",
"def index\n #formatear las fechas\n if defined? params[:q][:fecha_generado_lt]\n setupFechas\n end\n\n resultados_pedidos(true)\n end",
"def index\n # prepare data for select tag filter\n @list_options = load_list_options\n @previously_selected_type = params[\"form_type\"]\n\n # get workshops\n workshops = Workshop.all(:id => params[\"workshop\"])\n if workshops.length == 0 \n if params[\"workshop\"] == 'all'\n workshops = Workshop.all\n elsif not Workshop.last.nil?\n workshops = [Workshop.last]\n end\n end\n\n # get registrations for selected workshops\n registrations = []\n workshops.each do |w|\n Registration.all.each do |r| \n if r.form\n if r.form.workshop\n registrations << r if r.form.workshop.id == w.id\n end\n end\n end\n end\n\n # filter registrations by type\n if params[\"form_type\"] == \"participant\"\n registrations = registrations.select { |r| r.form_type == \"ParticipantForm\" }\n elsif params[\"form_type\"] == \"coach\"\n registrations = registrations.select { |r| r.form_type == \"CoachForm\" }\n end\n\n @participant_registrations = []\n @participant_structure = nil\n @coach_registrations = []\n @coach_structure = nil\n\n # prepare registrations data and structure for selected workshop\n if workshops.length == 1\n @previously_selected_workshop = workshops[0].id\n\n # prepare participant data \n if workshops[0].participant_form?\n filtered_data = parse_structure(workshops[0].participant_form.structure, registrations.select { |r| r.form_type == \"ParticipantForm\" })\n @participant_registrations = filtered_data[0]\n @participant_structure = filtered_data[1]\n end\n\n # prepare coach data \n if workshops[0].coach_form?\n filtered_data = parse_structure(workshops[0].coach_form.structure, registrations.select { |r| r.form_type == \"CoachForm\" })\n @coach_registrations = filtered_data[0]\n @coach_structure = filtered_data[1]\n end\n\n # for all workshops: only prepare the immutable attributes\n else\n @participant_structure = [\n {\"caption\"=>\"Firstname\", \"name\"=>\"firstname\"},\n {\"caption\"=>\"Lastname\", \"name\"=>\"lastname\"},\n {\"caption\"=>\"E-Mail\", \"name\"=>\"email\"}\n ]\n\n @participant_registrations = parse_structure(@participant_structure.to_json, registrations)[0]\n end\n\n respond_to do |format|\n format.html\n format.csv\n format.xls\n end\n end",
"def index\n @promulher_forms = PromulherForm.all\n end",
"def get_listbox_data\n @countries = current_user.company.countries.dropdown_list\n @sectors = current_user.company.sectors.order(:sector)\n @rel_types = current_user.company.rel_types.dropdown_list\n @relationgroups = current_user.company.relations.dropdown_list\n end",
"def prepara_form\n @enderecos = Endereco.order :rua\n end",
"def show\n @fields = FormularioField.where \"formulario_id =?\", @formulario.id\n end",
"def getListaTabla\n return ['form_cultivos','baciloscopia_forms','biopsias_forms','form_liquidos','form_chagas','form_malaria','form_leishmaniases','Tuberculosis','form_cancer_uterinos','form_anat_citologicas','Tuberculosis']\n end",
"def index\n @form_fields = FormField.all\n end",
"def select_list; end",
"def index\n @forms = Form.page(params[:page]).per(30)\n\n if params[:entry_form_type_chooser]\n render :template => \"forms/chooser.html.erb\"\n return\n end\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @forms }\n end\n end",
"def index\n params[:limit] = DEFAULT_LIMIT unless params[:limit].present?\n @video_marketing_campaign_forms = VideoMarketingCampaignForm.order(created_at: :desc).page(params[:page]).per(params[:limit])\n end",
"def especies_por_pagina(opc={})\n return unless resp[:estatus]\n self.por_pagina = params[:por_pagina] || ESPECIES_POR_PAGINA\n self.pagina = params[:pagina].present? ? params[:pagina].to_i : 1\n offset = (pagina-1)*por_pagina\n limit = (pagina*por_pagina)-1\n\n if tiene_filtros?\n ids = taxones.map(&:catalogo_id) & resp[:resultados].keys\n idcats = ids.map{ |id| [id, resp[:resultados][id]] }.sort_by(&:last).reverse\n else # es la primera pagina\n idcats = resp[:resultados].to_a\n end\n \n self.totales = idcats.length\n self.num_ejemplares = idcats.sum {|r| r[1] }\n \n if totales > 0\n if opc[:especies_excel] || opc[:especies_guia]\n self.resp[:resultados] = idcats.to_h\n else\n self.resp[:resultados] = idcats[offset..limit].to_h\n end\n else\n self.resp[:resultados] = {}\n end\n end",
"def format_forms(page)\n ret = {}\n page.forms.each do |form|\n ret[form.name] = []\n form.fields.each do |n|\n ret[form.name] << n.name\n end\n end\n return ret\nend",
"def page_select(id, params={})\n type = params[:type]\n p_class = params[:p_class]\n description = params[:description] || id.to_s.titleize\n model = params[:model]\n default_id = params[:default_id]\n skip_id = params[:skip_id]\n\n f = \"<p #{p_class.nil? ? '' : 'class=\"' + attr_h(p_class) + '\"'}>\"\n f << \"<label for=\\\"#{id}\\\">#{description}</label>\"\n f << \"<select name=\\\"#{id}\\\" id=\\\"#{id}\\\">\"\n f << \"<option value=\"\">/</option>\"\n CortexReaver::Page.top.order(:title).all.each do |page|\n f << page_select_helper(page, default_id, skip_id)\n end\n f << \"</select></p>\"\n end",
"def index\n @formularios = Formulario.all\n end",
"def index\n @formularios = Formulario.all\n end",
"def select_tiposdocumemto\n [\n [\"CARTAS DE PROPIETARIOS SOLICITANDO LA VIVIENDA\",\"CARTAS DE PROPIETARIOS SOLICITANDO LA VIVIENDA\"],\n [\"CARTAS PARA CAMBIO DE VIVIENDA\",\"CARTAS PARA CAMBIO DE VIVIENDA\"],\n [\"CARTAS RECIBIDAS PARA SOLICITUD DE AUMENTO DE CANON\",\"CARTAS RECIBIDAS PARA SOLICITUD DE AUMENTO DE CANON\"],\n [\"DOCUMENTACION DE TENENCIA DE VIVIENDA EVACUADA\",\"DOCUMENTACION DE TENENCIA DE VIVIENDA EVACUADA\"],\n [\"DOCUMENTACION DE VIVIENDA PARA ARRENDAR POR PRIMERA VEZ\",\"DOCUMENTACION DE VIVIENDA PARA ARRENDAR POR PRIMERA VEZ\"],\n [\"DOCUMENTACION DE VIVIENDAS DISPONIBLES\",\"DOCUMENTACION DE VIVIENDAS DISPONIBLES\"],\n [\"DOCUMENTACION PARA CAMBIO DE VIVIENDA\",\"DOCUMENTACION PARA CAMBIO DE VIVIENDA\"],\n [\"DOCUMENTOS SOPORTES DE INGRESOS FAMILIARES\",\"DOCUMENTOS SOPORTES DE INGRESOS FAMILIARES\"],\n [\"DOCUMENTOS DE IDENTIDAD DEL GRUPO FAMILIAR\",\"DOCUMENTOS DE IDENTIDAD DEL GRUPO FAMILIAR\"],\n [\"OTROS DOCUMENTOS\",\"OTROS DOCUMENTOS\"],\n [\"PAZ Y SALVOS RECIBIDOS\",\"PAZ Y SALVOS RECIBIDOS\"]\n ]\n end",
"def select_per_page(classe = 'perpage')\n container = %()\n container << \"<ul class='#{classe}'>\"\n container << \"<li>#{link_to 'itens por página','javascript:void(0);',:title => 'selecione a quantidade de itens por página'}\"\n container << \"<ul>\"\n container << \"<li>#{link_to 'exibir 15 itens','javascript:void(0);',:title => 'exibir 15 itens',:rel => 15}</li>\"\n container << \"<li>#{link_to 'exibir 30 itens','javascript:void(0);',:title => 'exibir 30 itens',:rel => 30}</li>\"\n container << \"<li>#{link_to 'exibir 50 itens','javascript:void(0);',:title => 'exibir 50 itens',:rel => 50}</li>\"\n container << \"<li>#{link_to 'exibir 100 itens','javascript:void(0);',:title => 'exibir 100 itens',:rel => 100}</li>\"\n container << \"</ul></li></ul>\"\n container.html_safe\n end",
"def index\n @tbl_form_fields = TblFormField.all\n end",
"def index\n @controldepagogts = Controldepagogt.all\n end",
"def field_select_pays\n @options ||= Hash.new\n @options.merge! values: PAYS_ARR_SELECT\n field_select\n end",
"def index\n @sort = params[:sort] || 'name'\n @sort_id = @sort.to_i\n @filled_forms = @form.visible_filled_forms(current_user)\n if @sort\n if @sort_id <= 0\n @filled_forms = @filled_forms.reorder(@sort + ' ASC')\n else\n @filled_forms = @filled_forms.includes(:filled_fields).\n where('filled_fields.form_field_id = ?', @sort_id).\n reorder('filled_fields.value').references(:filled_fields)\n end\n end\n \n @payable_forms = @filled_forms.for_user(current_user).\n where(:payment_id => nil)\n \n if @form.parent\n @parent_value_form_fields = @form.parent.form_fields.valued\n @parent_columns = @form.parent.columns\n end\n \n @value_form_fields = @form.form_fields.valued\n @columns = @form.columns\n \n @sort_options = @value_form_fields.map{|ff| [ff.name, ff.id]}\n @sort_options << ['date', 'updated_at']\n @sort_options << ['version']\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @filled_forms }\n format.csv # index.csv.erb\n format.xls # index.xls.erb\n end\n end",
"def paginating_select_result(collection, field, options= {}, paginating_options= {}, remote_options={})\n if collection.empty?\n h options[:empty_text] || \"No Records Found\"\n else\n @object ||= options[:object]\n @method ||= options[:method]\n radios = collection.map {|col| tag(:input, :type => \"radio\", :name => @method, :value => \"#{col[field.to_sym].nil? ? col.method(field).call : col[field.to_sym]}\", :onclick => \"$('#{@object}_#{@method}').value = this.value;#{remote_options.empty? ? '' : remote_function(:url => remote_options[:url].merge(:return => (col[field.to_sym].nil? ? col.method(field).call : col[field.to_sym])), :loading => \"Element.hide('\"+ remote_options[:partial] + \"');\" + remote_options[:loading], :loaded => \"Element.show('\"+ remote_options[:partial] + \"');\" + remote_options[:loaded])}\") + (col[field.to_sym].nil? ? col.method(field).call : col[field.to_sym]) + tag(\"br\")}\n\n content_tag(\"div\", :style => \"float:right;\") do\n link_to_function image_tag('close.gif', :plugin => 'paginating_select', :style => 'margin-top:0px;'), \"Element.hide('#{@method}_div');\"\n end +\n\n content_tag(\"div\", radios) +\n if (collection.count < collection.per_page) && (paginating_options[:page] != collection.per_page.to_s)\n add_radio_button_setter(@object, @method) \n else\n add_radio_button_setter(@object, @method) + \n add_pagination(collection, paginating_options, \"#{@method}_options\") \n end\n end\n end",
"def pago_params\n params.require(:pago).permit(:farmacia_id, :numcomprobante, :verificado)\n end",
"def nested_forms\n []\n end",
"def index\n # @myPat = Pat.includes(:for_select)\n # @q = @myPat.search(params[:q])\n @q = Pat.search(params[:q]) \n @pats = @q.result.page(params[:page]).per(15)\n\n @totNumber = Pat.all.count\n @searchNumber = @q.result.count\n\n # Generate the 2d array needed for grouped select in view\n @grouped_options = Pat.GroupedSelect('ward', ForSelect)\n\n\n respond_to do |format|\n format.html { render action: 'index' }\n format.js {}\n end\n end",
"def index\n @condicoes_pagamento = CondicaoPagamento.all\n end",
"def index\n @payment_forms = @paymentService.all()\n end",
"def selects(option_text, options = {})\n if options[:from]\n select = find_select_list_by_name_or_label(options[:from])\n return flunk(\"Could not find select list #{options[:from].inspect}\") if select.nil?\n option_node = find_option_by_value(option_text, select)\n return flunk(\"Could not find option #{option_text.inspect}\") if option_node.nil?\n else\n option_node = find_option_by_value(option_text)\n return flunk(\"Could not find option #{option_text.inspect}\") if option_node.nil?\n select = option_node.parent\n end\n add_form_data(select, option_node.attributes[\"value\"] || option_node.innerHTML)\n # TODO - Set current form\n end",
"def options\n @session_user = User.find(session[:user_id])\n @page = @session_user.page\n options = Array.new\n for panel in @page.panels.order(:created_at)\n if panel.type == 'MSelectpanel' || panel.type == 'SSelectpanel'\n if panel.options\n for option in panel.options.order(:created_at)\n options.push(option)\n end\n end \n end \n end\n render json: options\n end",
"def get_product_dropdown_list\n @product_dropdown_list ||= lambda {\n list = []\n\n page = ::Nokogiri::HTML(firstpage)\n page.search('//div[@class=\"sb-search\"]//select[@id=\"productDropdown\"]//option').each do |product|\n option_value = product.attributes['value'].value\n option_text = product.text\n next if option_value == '-1' # This is the ALL option\n list << { option_value: option_value, option_text: option_text }\n end\n\n list\n }.call\n end",
"def per_page_dropdown\n # there is a config setting for admin_products_per_page, only for the orders page\n if @products && per_page_default = Spree::Config.admin_products_per_page\n per_page_options = []\n 5.times do |amount|\n per_page_options << (amount + 1) * Spree::Config.admin_products_per_page\n end\n else\n per_page_default = 15\n per_page_options = %w{5 15 30 45 60}\n end\n\n select_tag(:per_page,\n options_for_select(per_page_options, params['per_page'] || per_page_default),\n { class: \"form-control pull-right js-per-page-select\" })\n end",
"def index\n @phone_types = PhoneType.order(:id).all.paginate(page: params[:page], per_page: 15)\n end",
"def index\n @form_laboratorios = FormLaboratorio.all\n end",
"def index\n #@unitarios = Unitario.all\n #@grupos_unitarios = GruposUnitario.all\n @filterrific = initialize_filterrific(\n InscripcionDiplomado,\n params[:filterrific],\n select_options: {\n with_grupos_unitario_id: GruposDiplomado.seleccion_curso_nombre,\n with_documentos_validados: InscripcionDiplomado.options_for_documentos_validados\n },\n ) or return\n @inscripcion_diplomados = @filterrific.find.page(params[:pagina])\n\n respond_to do |format|\n format.html\n format.js\n end\n\n rescue ActiveRecord::RecordNotFound => e\n # There is an issue with the persisted param_set. Reset it.\n puts \"Se restablecieron los parámetros: #{ e.message }\"\n redirect_to(reset_filterrific_url(format: :html)) and return\n end",
"def index\n @selecionados = Selecionado.all\n end",
"def index\n\n sql = \"select pagos.id, pagos.numcomprobante, pagos.verificado,pagos.farmacium_id, farmacia.nombre from pagos, farmacia where pagos.farmacium_id = farmacia.id\"\n @pagos = Pago.paginate_by_sql(sql, :page => params[:page], :per_page => 9)\n end",
"def build_selects_from_types(order)\n select = +\"\"\n first_visible = order.find { |type| !@options[:\"discard_#{type}\"] }\n order.reverse_each do |type|\n separator = separator(type) unless type == first_visible # don't add before first visible field\n select.insert(0, separator.to_s + public_send(\"select_#{type}\").to_s)\n end\n select.html_safe\n end",
"def set_collection_select\n @facultades = Facultad.all\n @programas = Programa.all\n @grupos = Grupo.all\n @semilleros = Semillero.all\n @investigadores = Investigador.all\n end",
"def show\n combo_producto\n combo_platillo\n end",
"def index\n @valores_de_pagos = ValoresDePago.all\n end",
"def index\n @template_form_fields = TemplateFormField.all\n end",
"def index\n @site_options = SiteOption.page params[:page]\n end",
"def set_form_variables\n @articles = CriminalCode.all.includes(:articles).with_translations\n @tags = Tag.includes(:translations).order(:name)\n @prisons = Prison.includes(:translations).order(:name)\n\n gon.select_charges = t('shared.actions.with_obj.select',\n obj: t('activerecord.models.charge', count: 999))\n gon.select_tags = t('shared.actions.with_obj.select',\n obj: t('activerecord.models.tag', count: 999)) \n end",
"def index\n @pit_forms = PitForm.all\n end",
"def index\n @paginas = Pagina.iniciais(@produto.id)\n end",
"def all_forms\n plural_form.blank? ? [name] : [plural_form.name, name].sort\n end",
"def parse_fields(opts, name, page, *fields)\n fields.each do |field|\n lmnt = page.send(*[field, name].compact)\n var = opts.nil? ? instance_variable_get(\"@#{field}\") : opts[field]\n lmnt.class.to_s == 'Watir::Select' ? lmnt.pick!(var) : lmnt.fit(var)\n end\n end",
"def names \n all_forms\n end",
"def fill_in_form(fields)\n fields.each do |field, value|\n f = send(\"#{field}_field\")\n f.set(value) || Array(value).each { |val| f.select(val) }\n end\n end",
"def forms_with_password\n @pages.map { |p| p.forms.select { |f| f.requires_password? } }.flatten\n end",
"def farmacias_verificadas\n @farmacia = Farmacium.paginate(:page => params[:page], :per_page => 7)\n sql = 'SELECT id, nombre,\"cedulaJur\", sucursal, direccion,cant_lab, telefono1, telefono2, correo, cant_lab from Farmacia where verificado = true order by nombre'\n @farmacia = Farmacium.paginate_by_sql(sql, :page => params[:page], :per_page => 7)\n render :template => \"farmacia/verificada\"\n end",
"def index\n @form = Form.find(params[:form_id])\n @pupils = @form.pupils.order(:surname)\n end",
"def index\n @periodistas = Periodista.listado(params[:page],params[:buscar], params[:departamento],params[:tipo_medio_id] , params[:institucion_periodistica_id])\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @periodistas }\n format.print{ @periodistas = Periodista.find(:all, :order => \"idDepartamento, nombre\"); render :layout => 'imprimir' }\n end\n end",
"def all_forms\n\t\t\tretval = []\n\t\t\tGENDERS.each do |gender|\n\t\t\t\t[true, false].each do |animate|\n\t\t\t\t\tNUMBERS.each do |number|\n\t\t\t\t\t\tCASES.each do |gram_case|\n\t\t\t\t\t\t\tform = {:case => gram_case, :number => number, :gender => gender}\n\t\t\t\t\t\t\tif gender == MASCULINE\n\t\t\t\t\t\t\t\tretval << form.merge({:animate => animate})\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tretval << form if animate\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tretval\n\t\tend",
"def index\n @obras = Obra.all\n\n @filterrific = initialize_filterrific(\n Obra,\n params[:filterrific]\n ) or return\n\n @filterrific.select_options = {\n sorted_by: Obra.options_for_sorted_by\n }\n\n @obras = @filterrific.find.page(params[:page]).per(20)\n \n respond_to do |format|\n format.html\n format.js\n end\n end",
"def fields_on_form() #:nodoc:\r\n fields = []\r\n if @form['form']['fields']\r\n# read only field elements (key is Fixnum)\r\n @form['form']['fields'].each {|key,options| fields << options if key.class == Fixnum }\r\n else\r\n @form['form']['tabs'].keys.each do |tab|\r\n @form['form']['tabs'][tab].each {|key,options| fields << options if key.class == Fixnum }\r\n end \r\n end\r\n fields\r\nend",
"def index\n\t@form_primarios = FormPrimario.where('emailUsuario = ?', current_usuario.email)\n end",
"def index\n @selected_options_of_pcs = SelectedOptionsOfPc.all\n end",
"def index\n @filterrific = initialize_filterrific(\n ItInscripcionRegistro,\n params[:filterrific],\n select_options:{\n sorted_by: ItInscripcionRegistro.options_for_sorted_by,\n with_grupo_id: Grupo.where(estado: \"Abierto\").options_for_select,\n with_documentos_validados: ItInscripcionRegistro.options_for_documentos_validados,\n with_curso: CursoNombre.options_for_select\n },\n ) or return\n @it_inscripcion_registros = @filterrific.find.order(\"created_at DESC\").page(params[:pagina])\n\n respond_to do |format|\n format.html\n format.js\n end\n\n rescue ActiveRecord::RecordNotFound => e\n # There is an issue with the persisted param_set. Reset it.\n puts \"Se tuvieron que restablecer los valores: #{ e.message }\"\n redirect_to(reset_filterrific_url(format: :html)) and return\n\n end",
"def form_escolher\n lst_from.select 'London'\n lst_on.select 'December'\n lst_month.select '20'\n lst_arriving.select 'Acapulco'\n lst_returning.select 'October'\n lst_month_returning.select '21'\n check_port.click\n lst_airline.select 'Blue Skies Airlines'\n end",
"def fill_select_option\n @search_by_values = QcLaboratory.get_search_values\n end",
"def buscar(url,columnas)\n form_tag url, class: 'navbar-form navbar-right',method: 'get',role: \"search\" do \n\t content_tag :div , class: \"form-group form-group-sm\" do |div|\n\t \tarray = [] \n\t \tarray << text_field_tag(:search, params[:search], class:\"form-control\", style:\"width:inherid\",placeholder: \"Buscar\") \n\t \tarray << select_tag(:sort ,options_for_select(columnas,params[:sort]), class: \"form-control\",style: \"width:100px;\")\n\t array << submit_tag(\"Buscar\",class: 'btn btn-default btn-sm', :name => nil) \n\t array.join.html_safe\n\t end \n end \n end",
"def index\n @paginas = Pagina.all\n end",
"def show\r\n\r\n relatorio_id = params[:relatorio_id]\r\n asFormAcads = FormAcad.where(relatorio_id: relatorio_id);\r\n osEgressos = Egresso.none\r\n asFormAcads.each do |aFormAcad|\r\n oEgresso = Egresso.where(id: aFormAcad.egresso_id)\r\n if not(oEgresso.first.cpf.present?)||not(oEgresso.first.email_princ.present?)||not(aFormAcad.data_fim.present?)\r\n osEgressos += oEgresso\r\n end\r\n end\r\n @osEgressos= Egresso.where(id: osEgressos.map(&:id)).paginate(page: params[:page], per_page: 5).order(\"id\")\r\n end",
"def index\n @formaenvios = Formaenvio.all\n end",
"def index\n @coleccion = Requisito.all\n end",
"def valores_de_pago_params\n params.require(:valores_de_pago).permit(:monto_por_forma_pago)\n end",
"def index\n @substancias = Substancia.paginate page: params[:page]\n end",
"def index\n @firmen = Firma.paginate(page: params[:page], per_page: 20)\n end",
"def index\n @tipo_paradas = TipoParada.all\n end",
"def index\n @farmaceuticos = Farmaceutico.paginate page: params[:page]\n end",
"def index\n @bus_types = BusType.paginate(:page => params[:page], :per_page => PER_PAGE).order(:name)\n end",
"def search_form objs_type, searches\n\t\t\n\t\tdates = [\"date\",\"created_at\",\"updated_at\"]\n\t\ttimes = [\"depart_time\",\"arrive_time\",\"return_time\"]\n\t\tselections = [\"trip_id\",\"destination_id\"]\n\t\t\n\t\thtml = \"\"\n\t\t\n\t\thtml << '<table><tr><th></th><th></th><th></th></tr>'.html_safe\n\t\t\n\t\tsearches.each do |search|\n\t\t\n\t\t\thtml << '<form accept-charset=\"UTF-8\" action=\"/'.html_safe + objs_type + '\" method=\"get\">'.html_safe\n\t\t\thtml << '<tr><td>'.html_safe\n\t\t\n\t\t\tif dates.include? search\n\t\t\t\thtml << (label_tag(search + \"1\", \"Search for \" + objs_type + \" with \" + search + \" between \")).html_safe\n\t\t\t\thtml << '</td><td>'.html_safe\n\t\t\t\thtml << (date_select(search, \"1\")).html_safe\n\t\t\t\thtml << (label_tag(search + \"2\", \" and \")).html_safe\n\t\t\t\thtml << (date_select(search, \"2\")).html_safe\n\t\t\telse\n\t\t\t\thtml << (label_tag(search, \"Search for \" + objs_type + \" with \" + search + \": \")).html_safe\n\t\t\t\thtml << '</td><td>'.html_safe\n\t\t\t\thtml << (text_field_tag(search)).html_safe\n\t\t\tend\n\t\t\t\n\t\t\thtml << '</td><td>'.html_safe\n\t\t\thtml << (submit_tag(\"Search\")).html_safe\n\t\t\thtml << '</td>'.html_safe\n\t\t\t\n\t\t\thtml << '</tr>'.html_safe\n\t\t\thtml << '</form>'.html_safe\n\t\tend\n\t\t\n\t\thtml << '</table>'.html_safe\n\t\t\n\t\thtml.html_safe\n\tend",
"def index\n authorize Formation\n @filterrific = initialize_filterrific(\n Formation,\n params[:filterrific],\n persistence_id: :formations_filter,\n select_options: {\n sorted_by: Formation.options_for_sorted_by,\n with_status: Formation.options_for_status\n }\n ) or return\n @formations = @filterrific.find.page(params[:page]).per_page(15)\n end",
"def list_viaticos\n @company = Company.find(1)\n @caja = Caja.find(params[:id])\n \n @pagetitle = \"#{@company.name} - Viaticos\"\n @filters_display = \"block\"\n \n @locations = Location.where(company_id: @company.id).order(\"name ASC\")\n @divisions = Division.where(company_id: @company.id).order(\"name ASC\")\n \n \n if(@company.can_view(current_user))\n @viaticos = Viatico.where(caja_id: params[:id]).order('id DESC').paginate(:page => params[:page])\n\n if params[:search]\n @viaticos = Viatico.where(caja_id: params[:id]).search(params[:search]).order('id DESC').paginate(:page => params[:page])\n else\n @viaticos = Viatico.where(caja_id: params[:id]).order('id DESC').paginate(:page => params[:page]) \n end\n \n else\n errPerms()\n end\n end",
"def index\n @ocs_generadas = OcsGenerada.order(id: :desc).page(params[:page]).per(300)\n end",
"def index\n @graus_formacao = GrauFormacao.all\n end"
] | [
"0.70502144",
"0.65846807",
"0.62755746",
"0.62076336",
"0.60679555",
"0.5987666",
"0.59851193",
"0.59438115",
"0.5889661",
"0.58763105",
"0.58543265",
"0.5821864",
"0.5809577",
"0.5808571",
"0.58028024",
"0.579181",
"0.5764639",
"0.5684009",
"0.5683008",
"0.5647019",
"0.56229764",
"0.5601349",
"0.5593117",
"0.55906844",
"0.5584291",
"0.5565353",
"0.55647844",
"0.5551916",
"0.5535113",
"0.5533066",
"0.55231184",
"0.5510211",
"0.54971975",
"0.5485736",
"0.54753006",
"0.54658455",
"0.54648566",
"0.54568344",
"0.54568344",
"0.54557425",
"0.54550254",
"0.54406005",
"0.5430642",
"0.5429845",
"0.542709",
"0.54251707",
"0.5418762",
"0.54087204",
"0.5406818",
"0.5404577",
"0.54040456",
"0.54002553",
"0.5398695",
"0.539529",
"0.5394781",
"0.53944916",
"0.5378373",
"0.5377663",
"0.53758556",
"0.5373315",
"0.5362617",
"0.5358265",
"0.5354442",
"0.5346661",
"0.5340425",
"0.5317741",
"0.5316215",
"0.5313519",
"0.5313471",
"0.53128767",
"0.5302535",
"0.5302473",
"0.5299099",
"0.5293655",
"0.5290973",
"0.52909523",
"0.52901644",
"0.52798104",
"0.52797556",
"0.5279624",
"0.5277354",
"0.52740306",
"0.52717984",
"0.5270489",
"0.5270249",
"0.5270206",
"0.5264503",
"0.5263165",
"0.52601314",
"0.5259124",
"0.52520156",
"0.52519363",
"0.52432555",
"0.5239193",
"0.5239185",
"0.5235624",
"0.5235478",
"0.5229724",
"0.5228506",
"0.5222303",
"0.5220604"
] | 0.0 | -1 |
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\t@tag1s.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('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",
"def fd_produtotrocacombo_params\n params.require(:fd_produtotrocacombo).permit(:fd_produtos_id, :fd_produtocombos_id)\n end",
"def bundles_changes(notification)\n if notification.userInfo[:changed_bundle].productIdentifier == @productIdentifier\n @installed = notification.userInfo[:status] == :added\n NSNotificationCenter.defaultCenter.postNotificationName('ShopBundleStatusChanged',\n object:nil)\n\n end\n end",
"def inject_combo_for_name_column(c)\n netzke_attrs = config[:owner].data_class.netzke_attributes.map{ |a| a[:name] }\n c.merge(:editor => {:xtype => :combo, :store => netzke_attrs, :force_selection => true})\n end",
"def marketing_variety_commodity_group_code_search_combo_changed\n\tcommodity_group_code = get_selected_combo_value(params)\n\tsession[:marketing_variety_search_form][:commodity_group_code_combo_selection] = commodity_group_code\n\t@commodity_codes = MarketingVariety.find_by_sql(\"Select distinct commodity_code from marketing_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('marketing_variety','commodity_code',@commodity_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_marketing_variety_commodity_code'/>\n\t\t<%= observe_field('track_indicator_commodity_code',:update => 'marketing_variety_code_cell',:url => {:action => session[:marketing_variety_search_form][:commodity_code_observer][:remote_method]},:loading => \"show_element('img_marketing_variety_commodity_code');\",:complete => session[:marketing_variety_search_form][:commodity_code_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def addons_combo_params\n params.require(:addons_combo).permit(:addon_id, :combo_id, :quantity, :price, :active)\n end",
"def standard_size_count_commodity_code_search_combo_changed\n\tcommodity_code = get_selected_combo_value(params)\n\tsession[:standard_size_count_search_form][:commodity_code_combo_selection] = commodity_code\n\t@standard_size_count_values = StandardSizeCount.find_by_sql(\"Select distinct standard_size_count_value from standard_size_counts where commodity_code = '#{commodity_code}'\").map{|g|[g.standard_size_count_value]}\n\t@standard_size_count_values.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('standard_size_count','standard_size_count_value',@standard_size_count_values)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_standard_size_count_standard_size_count_value'/>\n\t\t<%= observe_field('standard_size_count_standard_size_count_value',:update => 'basic_pack_code_cell',:url => {:action => session[:standard_size_count_search_form][:standard_size_count_value_observer][:remote_method]},:loading => \"show_element('img_standard_size_count_standard_size_count_value');\",:complete => session[:standard_size_count_search_form][:standard_size_count_value_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def mapping_source_combo_box_item_state_changed(event)\n if(event.getStateChange == ItemEvent::SELECTED )\n puts \"IN MappingTabController : ITEM STATE #{event.getItem} : CHANGE STATE [#{event.getStateChange}]\"\n update_model(view_state.model, :mapping_source)\n signal :mapping_source_changed\n end\n\n end",
"def set_fd_produtotrocacombo\n @fd_produtotrocacombo = FdProdutotrocacombo.find(params[:id])\n end",
"def build_inventory_code_form(inventory_code,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[:inventory_code_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 => 'inventory_code'}\n\n\tfield_configs[1] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'inventory_name'}\n\n\tbuild_form(inventory_code,field_configs,action,'inventory_code',caption,is_edit)\n\nend",
"def ripe_point_treatment_code_search_combo_changed\n\ttreatment_code = get_selected_combo_value(params)\n\tsession[:ripe_point_search_form][:treatment_code_combo_selection] = treatment_code\n\t@cold_store_type_codes = RipePoint.find_by_sql(\"Select distinct cold_store_type_code from ripe_points where treatment_code = '#{treatment_code}'\").map{|g|[g.cold_store_type_code]}\n\t@cold_store_type_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('ripe_point','cold_store_type_code',@cold_store_type_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_ripe_point_cold_store_type_code'/>\n\t\t<%= observe_field('ripe_point_cold_store_type_code',:update => 'pc_code_code_cell',:url => {:action => session[:ripe_point_search_form][:cold_store_type_code_observer][:remote_method]},:loading => \"show_element('img_ripe_point_cold_store_type_code');\",:complete => session[:ripe_point_search_form][:cold_store_type_code_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def build_gtin_form(gtin,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[:gtin_form]= Hash.new\n\tmark_codes = Mark.find_by_sql('select distinct mark_code from marks').map{|g|[g.mark_code]}\n\tmark_codes.unshift(\"<empty>\")\n\tgrade_codes = Grade.find_by_sql('select distinct grade_code from grades').map{|g|[g.grade_code]}\n\tgrade_codes.unshift(\"<empty>\")\n\t#generate javascript for the on_complete ajax event for each combo for fk table: standard_size_counts\n\tcombos_js_for_standard_size_counts = gen_combos_clear_js_for_combos([\"gtin_commodity_code\",\"gtin_old_pack_code\",\"gtin_actual_count\"])\n\t#Observers for combos representing the key fields of fkey table: standard_size_count_id\n\tshort_descriptions = Organization.find_by_sql('select distinct short_description from organizations').map{|g|[g.short_description]}\n\tshort_descriptions.unshift(\"<empty>\")\n\ttarget_market_names = TargetMarket.find_by_sql('select distinct target_market_name from target_markets').map{|g|[g.target_market_name]}\n\ttarget_market_names.unshift(\"<empty>\")\n\t\n\ton_complete_js = \"\\n img = document.getElementById('img_gtin_organization_code');\"\n\ton_complete_js += \"\\n if(img != null)img.style.display = 'none';\"\n\t\n\t#Observers for search combos\n\torg_observer = {:updated_field_id => \"ajax_distributor_cell\",\n\t\t\t\t\t :remote_method => 'gtin_org_combo_changed',\n\t\t\t\t\t :on_completed_js => on_complete_js}\n\t\n\tcommodity_code_observer = {:updated_field_id => \"old_pack_code_cell\",\n\t\t\t\t\t :remote_method => 'gtin_commodity_code_changed',\n\t\t\t\t\t :on_completed_js => combos_js_for_standard_size_counts[\"gtin_commodity_code\"]}\n\n\tsession[:gtin_form][:commodity_code_observer] = commodity_code_observer\n\n\told_pack_code_observer = {:updated_field_id => \"actual_count_cell\",\n\t\t\t\t\t :remote_method => 'gtin_old_pack_code_changed',\n\t\t\t\t\t :on_completed_js => combos_js_for_standard_size_counts [\"gtin_old_pack_code\"]}\n\n\tsession[:gtin_form][:old_pack_code_observer] = old_pack_code_observer\n\t\n\t\n\tjs = \"\\n img = document.getElementById('img_gtin_mark_code');\"\n\tjs += \"\\n if(img != null)img.style.display = 'none';\"\n\t\n\tmark_observer = {:updated_field_id => \"brand_code_cell\",\n\t\t\t\t\t :remote_method => 'mark_code_changed',\n\t\t\t\t\t :on_completed_js => js}\n\n#\tcombo lists for table: standard_size_counts\n\n\tcommodity_codes = nil \n\told_pack_codes = nil \n\tactual_counts = nil \n\tmarketing_variety_codes = nil\n\ttarget_markets = nil\n\tinventory_codes = nil\n \n\tcommodity_codes = Gtin.get_all_commodity_codes\n\tcommodity_codes.unshift(\"<empty>\")\n\tif gtin == nil||is_create_retry\n\t\t old_pack_codes = [\"Select a value from commodity_code\"]\n\t\t actual_counts = [\"Select a value from old_pack_code\"]\n\t\t marketing_variety_codes = [\"Select a value from commodity code\"]\n\t\t target_markets = [\"Select a value from organization code\"]\n\t\t inventory_codes = [\"Select a value from organization code\"]\n\telse\n\t\told_pack_codes = Gtin.old_pack_codes_for_commodity_code(gtin.commodity_code)\n\t\tactual_counts = Gtin.actual_counts_for_old_pack_code_and_commodity_code(gtin.old_pack_code, gtin.commodity_code)\n\t marketing_variety_codes = MarketingVariety.find_all_by_commodity_code(gtin.commodity_code).map{|c|[c.marketing_variety_code]}\n\t target_markets = TargetMarket.get_all_by_org(gtin.organization_code)\n\t inventory_codes = InventoryCode.get_all_by_org(gtin.organization_code)\n\tend\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 => 'gtin_code'}\n\n\tfield_configs[1] = {:field_type => 'DateField',\n\t\t\t\t\t\t:field_name => 'date_from'}\n\n\tfield_configs[2] = {:field_type => 'DateField',\n\t\t\t\t\t\t:field_name => 'date_to'}\n\n# ----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (organization_id) on related table: organizations\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[3] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'organization_code',\n\t\t\t\t\t\t:settings => {:list => short_descriptions,\n\t\t\t\t\t\t :label_caption => \"org code\"},\n\t\t\t\t\t\t:observer => org_observer}\n\n\tfield_configs[4] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'target_market_code',\n\t\t\t\t\t\t:settings => {:list => target_markets}}\n\n\tfield_configs[5] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'inventory_code',\n\t\t\t\t\t\t:settings => {:list => inventory_codes}}\n\n\n\tfield_configs[6] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'transaction_number'}\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (mark_id) on related table: marks\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[7] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'mark_code',\n\t\t\t\t\t\t:settings => {:list => mark_codes},\n\t\t\t\t\t\t:observer => mark_observer}\n \n field_configs[8] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'brand_code'}\n\t\t\t\t\t\t\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (grade_id) on related table: grades\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[9] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'grade_code',\n\t\t\t\t\t\t:settings => {:list => grade_codes}}\n \n\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (standard_size_count_id) on related table: standard_size_counts\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[10] = {: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\t\t\t\t\t\t:observer => commodity_code_observer}\n\t\t\t\t\t\t\n\tfield_configs[11] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'marketing_variety_code',\n\t\t\t\t\t\t:settings => {:list => marketing_variety_codes}}\n \n\tfield_configs[12] = {: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\t\t\t\t\t\t:observer => old_pack_code_observer}\n \n\tfield_configs[13] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'actual_count',\n\t\t\t\t\t\t:settings => {:list => actual_counts}}\n \n field_configs[14] = {: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(gtin,field_configs,action,'gtin',caption,is_edit)\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([{:commodity_code => self.commodity_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_commodity\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def validate \n#\tfirst check whether combo fields have been selected\n if(self.rmt_product_type_code.to_s.upcase == \"PRESORT\")\n self.treatment_type_code = \"PRESORT\"\n elsif self.rmt_product_type_code == \"orchard_run\"\n self.product_class_code = \"OR\"\n self.treatment_type_code = \"PRE_HARVEST\"\n else\n self.treatment_type_code = \"PACKHOUSE\"\n end\n\n #self.size_code = \"UNS\" if !self.size_code\n if !self.size_code\n self.size_code = \"UNS\" \n\t self.size_id = Size.find_by_size_code(self.size_code).id\t\t \n end\n \n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:ripe_point_code => self.ripe_point_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_ripe_point\n\t end\n\t \n\t\n\tif is_valid && self.rmt_product_type_code != \"orchard_run\" && self.rmt_product_type_code.to_s.upcase != \"PRESORT\"\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:size_code => self.size_code}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid && self.rmt_product_type_code != \"orchard_run\" && self.rmt_product_type_code.to_s.upcase != \"PRESORT\"\n\t\t is_valid = set_size\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:product_class_code => self.product_class_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_product_class\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:commodity_group_code => self.commodity_group_code},{:commodity_code => self.commodity_code},{:variety_code => self.variety_code}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_variety\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:treatment_code => self.treatment_code}],self) \n\tend\n\t\n\tif is_valid && self.rmt_product_type_code != \"orchard_run\" && self.rmt_product_type_code.to_s.upcase != \"PRESORT\"\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:bin_type => self.bin_type}],self) \n\tend\n\t\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_treatment\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t #is_valid = ModelHelper::Validations.validate_combos([{:commodity_code => self.commodity_code}],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_spray_program_result\n\t end\nend",
"def rmt_variety_commodity_group_code_search_combo_changed\n\tcommodity_group_code = get_selected_combo_value(params)\n\tsession[:rmt_variety_search_form][:commodity_group_code_combo_selection] = commodity_group_code\n\t@commodity_codes = RmtVariety.find_by_sql(\"Select distinct commodity_code from rmt_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('rmt_variety','commodity_code',@commodity_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_rmt_variety_commodity_code'/>\n\t\t<%= observe_field('rmt_variety_commodity_code',:update => 'rmt_variety_code_cell',:url => {:action => session[:rmt_variety_search_form][:commodity_code_observer][:remote_method]},:loading => \"show_element('img_rmt_variety_commodity_code');\",:complete => session[:rmt_variety_search_form][:commodity_code_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def variety_commodity_group_code_changed\n\tcommodity_group_code = get_selected_combo_value(params)\n\tsession[:variety_form][:commodity_group_code_combo_selection] = commodity_group_code\n\t@commodity_codes = Variety.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('variety','commodity_code',@commodity_codes)%>\n <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_variety_commodity_code'/>\n\t\t<%= observe_field('variety_commodity_code',:update => 'ajax_distributor_cell',:url => {:action => session[:variety_form][:commodity_code_observer][:remote_method]},:loading => \"show_element('img_variety_commodity_code');\",:complete => session[:variety_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([{:vessel_code => self.vessel_code}],self)\n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_vessel\n\t end\nend",
"def update\n respond_to do |format|\n if @product_pack.update(product_pack_params)\n format.html { redirect_to @product_pack, notice: 'Product pack was successfully updated.' }\n format.json { render :show, status: :ok, location: @product_pack }\n else\n format.html { render :edit }\n format.json { render json: @product_pack.errors, status: :unprocessable_entity }\n end\n end\n end",
"def validate \nputs \"in IPC validate\"\n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\n ModelHelper::Validations.validate_combos([{:size_ref => self.size_ref}],self,true)\n self.size_ref = \"NOS\" if !self.size_ref\n\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:product_class_code => self.product_class_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_product_class\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:grade_code => self.grade_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_grade\n\t end\n\t \n\tif is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:treatment_code => self.treatment_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_treatment\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:commodity_group_code => self.commodity_group_code},{:commodity_code => self.commodity_code},{:marketing_variety_code => self.marketing_variety_code}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_marketing_variety\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:cosmetic_code => self.cosmetic_code_name}],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_cosmetic_code\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:commodity_code => self.commodity_code},{:basic_pack_code => self.basic_pack_code},{:standard_size_count_value => self.standard_size_count_value}],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_standard_size_count\n\t end\n\t \n\t if !self.size_ref\n\t self.size_ref = \"NOS\"\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\n\nend",
"def size_commodity_code_search_combo_changed\n\tcommodity_code = get_selected_combo_value(params)\n\tsession[:size_search_form][:commodity_code_combo_selection] = commodity_code\n\t@size_codes = Size.find_by_sql(\"Select distinct size_code from sizes where commodity_code = '#{commodity_code}'\").map{|g|[g.size_code]}\n\t@size_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('size','size_code',@size_codes)%>\n\n\t\t}\nend",
"def build_commodity_form(commodity,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[:commodity_form]= Hash.new\n\tcommodity_group_codes = CommodityGroup.find_by_sql('select distinct commodity_group_code from commodity_groups').map{|g|[g.commodity_group_code]}\n\tcommodity_group_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 => 'commodity_code'}\n\n\tfield_configs[1] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'commodity_description_long'}\n\n\tfield_configs[2] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'commodity_description_short'}\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (commodity_group_id) on related table: commodity_groups\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[3] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'commodity_group_code',\n\t\t\t\t\t\t:settings => {:list => commodity_group_codes}}\n\n field_configs[4] = {:field_type => 'CheckBox',\n\t\t\t\t\t\t:field_name => 'grower_commitment_required'}\n \n\tbuild_form(commodity,field_configs,action,'commodity',caption,is_edit)\n\nend",
"def size_ref_commodity_code_search_combo_changed\n\tcommodity_code = get_selected_combo_value(params)\n\tsession[:size_ref_search_form][:commodity_code_combo_selection] = commodity_code\n\t@size_ref_codes = SizeRef.find_by_sql(\"Select distinct size_ref_code from size_refs where commodity_code = '#{commodity_code}'\").map{|g|[g.size_ref_code]}\n\t@size_ref_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('size_ref','size_ref_code',@size_ref_codes)%>\n\n\t\t}\n\nend",
"def set_addons_combo\n @addons_combo = AddonsCombo.find(params[:id])\n end",
"def bins_tipped_production_schedule_name_search_combo_changed\n production_schedule_name = get_selected_combo_value(params)\n session[:bins_tipped_search_form][:production_schedule_name_combo_selection] = production_schedule_name\n @production_run_codes = BinsTipped.find_by_sql(\"select distinct production_run_code from production_runs where production_schedule_name = '#{production_schedule_name}'\").map { |p| [p.production_run_code] }\n @production_run_codes.unshift(\"<empty>\")\n query = \"SELECT track_indicator_code FROM public.production_schedules, public.rmt_setups\n WHERE rmt_setups.production_schedule_id = production_schedules.id AND public.production_schedules.production_schedule_name = '#{production_schedule_name}'\"\n @track_indicator_code = Carton.connection.select_one(query)['track_indicator_code']\n puts \"HELLO KK\"\n\n render :inline => %{\n <%= select('bin_tipped','production_run_code',@production_run_codes)%>\n <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_bin_tipped_production_run_code'/>\n\t\t <%= observe_field('bin_tipped_production_run_code',:update => 'line_code_cell',:url => {:action => session[:bins_tipped_search_form][:production_run_code_observer][:remote_method]},:loading => \"show_element('img_bin_tipped_production_run_code');\",:complete => session[:bins_tipped_search_form][:production_run_code_observer][:on_completed_js])%>\n\n <script>\n <%=\n update_element_function(\"track_indicator_code_cell\",\n :action=>:update,\n :content=> @track_indicator_code)\n %>\n </script>\n }\n\n end",
"def inventory_receipt_party_type_name_search_combo_changed\n party_type_name = get_selected_combo_value(params)\n session[:inventory_receipt_form][:party_type_name_combo_selection] = party_type_name\n @party_names = PartiesRole.find_by_sql(\"select distinct party_name from parties where party_type_name='#{party_type_name}'\").map{|g|[g.party_name]}\n\t@party_names.unshift(\"<empty>\")\n\trender :inline=>%{\n\t <%=select('inventory_receipt','party_name',@party_names) %>\n\t <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_inventory_receipt_party_name'/>\n <%= observe_field('inventory_receipt_party_name', :update=>'parties_role_name_cell', :url => {:action=>session[:inventory_receipt_form][:party_name_observer][:remote_method]}, :loading=>\"show_element('img_inventory_receipt_party_name');\", :complete=>session[:inventory_receipt_form][:party_name_observer][:on_completed_js])%>\n\t}\n end",
"def product_pack_params\n params.require(:product_pack).permit(:quantity, :price)\n end",
"def activate\n OptionValue.class_eval do\n belongs_to :tariff\n end\n\n Variant.additional_fields = []\n\n Variant.class_eval do\n after_create :assign_tariff_option\n #before_validation :calc_price\n\n def tariff\n @tariff ||= option_values.first.try(:tariff)\n end\n\n def tariff=(tariff)\n @tariff = tariff\n end\n\n# def package_price\n# if price == -1\n# tariff.eval_package_price(product)\n# else\n# price\n# end\n# end\n\n def assign_tariff_option\n if @tariff\n tariff_option_value = OptionValue.find_by_tariff_id(@tariff.id)\n option_values << tariff_option_value \n end\n end\n\n\n def check_price\n price = if cost_price == -1\n tariff.eval_package_price(product)\n else\n cost_price\n end\n\n price = 0 if price < 0\n end\n\n end\n\n\n Product.class_eval do\n\n named_scope :tariffable, :conditions => { :is_tariffable => true }\n \n\n def init_tariff_packages\n option_types = [OptionType.find_by_name('tariff_package')]\n\n Tariff.all.each do |tariff|\n variant = variants.build(:cost_price => '-1')\n variant.tariff = tariff\n variant.save\n end\n end\n end\n\n\n# ProductsController.class_eval do\n# alias_method :orig_load_data, :load_data\n#\n# def load_data\n# orig_load_data\n#\n# filled_out_tariffs = []\n# @tariff_packages = []\n# @product.variants.each do |variant|\n# tariff = variant.option_values.first.try(:tariff)\n# continue if tariff.nil?\n# @tariff_packages << tariff.attributes.merge({ \n# 'operator_name' => tariff.operator.name,\n# 'package_price' => variant.price})\n#\n# filled_out_tariffs << tariff.id\n# end\n#\n# Tariff.published.each do |tariff|\n# unless filled_out_tariffs.include?(tariff.id)\n# @tariff_packages << tariff.attributes.merge({\n# 'operator_name' => tariff.operator.name,\n# 'package_price' => tariff.eval_package_price(@product)})\n# end\n# end\n# end\n# end\n\n # make your helper avaliable in all views\n # Spree::BaseController.class_eval do\n # helper YourHelper\n # end\n end",
"def set_combo\n @combo = Combo.find(params[:id])\n end",
"def ensure_variant_and_color_code\n flush_variants\n if product_code\n variant_ids = ProductProduct.search([['default_code', 'ilike', \"FN-#{product_code.split(\"-\")[0]}\"]])\n variant_codes = ProductProduct.find(variant_ids).collect(&:default_code)\n\n variant_codes.each_with_index do |code, index|\n product_variants.create(openerpid: variant_ids[index], \n default_code: code,\n color_code_id: ensure_color_code(code)) \n end\n end\n end",
"def create\n @pack = Pack.new(params[:pack])\n\n if @pack.save\n redirect_to(edit_pack_path(@pack), :notice => 'Product Mixed was successfully created.')\n else\n render :action => \"new\"\n end\n end",
"def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:puc_type_code => self.puc_type_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_puc_type\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def extended_fg_fg_code_search_combo_changed\n\tfg_code = get_selected_combo_value(params)\n\tsession[:extended_fg_search_form][:fg_code_combo_selection] = fg_code\n\t@fg_mark_codes = ExtendedFg.find_by_sql(\"Select distinct fg_mark_code from extended_fgs where fg_code = '#{fg_code}'\").map{|g|[g.fg_mark_code]}\n\t@fg_mark_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('extended_fg','fg_mark_code',@fg_mark_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_extended_fg_fg_mark_code'/>\n\t\t<%= observe_field('extended_fg_fg_mark_code',:update => 'units_per_carton_cell',:url => {:action => session[:extended_fg_search_form][:fg_mark_code_observer][:remote_method]},:loading => \"show_element('img_extended_fg_fg_mark_code');\",:complete => session[:extended_fg_search_form][:fg_mark_code_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def rmt_variety_qc_level_id_search_combo_changed\n\tid = get_selected_combo_value(params)\n\tsession[:rmt_variety_qc_level_search_form][:id_combo_selection] = id\n\t@season_ids = RmtVarietyQcLevel.find_by_sql(\"Select distinct season_id from rmt_variety_qc_levels where id = '#{id}'\").map{|g|[g.season_id]}\n\t@season_ids.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('rmt_variety_qc_level','season_id',@season_ids)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_rmt_variety_qc_level_season_id'/>\n\t\t<%= observe_field('rmt_variety_qc_level_season_id',:update => 'rmt_variety_id_cell',:url => {:action => session[:rmt_variety_qc_level_search_form][:season_id_observer][:remote_method]},:loading => \"show_element('img_rmt_variety_qc_level_season_id');\",:complete => session[:rmt_variety_qc_level_search_form][:season_id_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def set_pack_material_product\n\n\tpack_material_product = PackMaterialProduct.find_by_pack_material_product_code_and_id(self.pack_material_product_code,self.id)\n\t if pack_material_product != nil \n\t\t self.pack_material_product = pack_material_product\n\t\t return true\n\t else\n\t\terrors.add_to_base(\"combination of: 'pack_material_product_code' and 'id' is invalid- it must be unique\")\n\t\t return false\n\tend\nend",
"def build_size_form(size,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\ton_complete_js = \"\\n img = document.getElementById('img_size_commodity_code');\"\n\ton_complete_js += \"\\n if(img != null)img.style.display = 'none';\"\n\t\n commodity_observer = {:updated_field_id => \"ajax_distributor_cell\",\n\t\t\t\t\t :remote_method => 'size_commodity_code_changed',\n\t\t\t\t\t :on_completed_js => on_complete_js }\n\t\t\t\t\t \n\tcount_codes = nil\n\tif size == nil||is_create_retry\n\t count_codes = [\"select a value from commodity code\"]\t \n\telse\n\t count_codes = StandardCount.find_all_by_commodity_code(size.commodity_code).map{|c|[c.standard_count_value]}\n\t count_codes.unshift(\"-1\")\n\tend\n\t\n\tcommodity_codes = Commodity.find_by_sql('select distinct commodity_code from commodities').map{|g|[g.commodity_code]}\n\tcommodity_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 => 'size_code'}\n\n\tfield_configs[1] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'size_description'}\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (commodity_id) on related table: commodities\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[2] = {: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\t\t\t\t\t\t:observer => commodity_observer}\n \n\tfield_configs[3] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'equivalent_count_from',\n\t\t\t\t\t\t:settings => {:list => count_codes}}\n\n\tfield_configs[4] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'equivalent_count_to',\n\t\t\t\t\t\t:settings => {:list => count_codes}}\n\t\t\t\t\t\t\n\tfield_configs[5] = {: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(size,field_configs,action,'size',caption,is_edit)\n\nend",
"def update\n if params[:id].to_i == 0 and ['featured','clearance','whats_new'].include? params[:id]\n @products = Product.send(params[:id])\n @products.each do |product|\n product.send(params[:id] + '_position=', params[params[:id]].index(product.id.to_s))\n product.save\n end\n render :nothing => true and return\n end\n if params.has_key? :product\n @editable_params[:category_ids].uniq! if @editable_params.has_key? :category_ids\n end\n @product.send(params[:event]) if params.has_key? :event\n if params.has_key? :product and @product.update_attributes(@editable_params)\n @product_section = 'overview'\n render :template => 'manage/products/show' and return\n elsif !params.has_key? :product\n @product_section = 'overview'\n render :template => 'manage/products/show' and return\n else\n @product_section = 'info'\n render :template => 'manage/products/edit' and return\n end\n end",
"def validate \n#\tfirst check whether combo fields have been selected\n is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:port_id => self.port_id}],self,nil,true)\n set_port if is_valid\n end\n\n\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:voyage_port_type_id => self.voyage_port_type_id}],self,nil,true)\n \n\n\t\nend",
"def load_products\n @products_type[\"watermelon\"] = Creator.createProduct(:watermelon, \"watermelon\")\n @products_type[\"watermelon\"].add_pack(3, 6.99)\n @products_type[\"watermelon\"].add_pack(5, 8.99)\n\n @products_type[\"pineapple\"] = Creator.createProduct(:pineapple, \"pineapple\")\n @products_type[\"pineapple\"].add_pack(2, 9.95)\n @products_type[\"pineapple\"].add_pack(5, 16.95)\n @products_type[\"pineapple\"].add_pack(8, 24.95)\n\n @products_type[\"rockmelon\"] = Creator.createProduct(:rockmelon, \"rockmelon\")\n @products_type[\"rockmelon\"].add_pack(3, 5.95)\n @products_type[\"rockmelon\"].add_pack(5, 9.95)\n @products_type[\"rockmelon\"].add_pack(9, 16.99)\n end",
"def puc_puc_type_code_search_combo_changed\n\tpuc_type_code = get_selected_combo_value(params)\n\tsession[:puc_search_form][:puc_type_code_combo_selection] = puc_type_code\n\t@puc_codes = Puc.find_by_sql(\"Select distinct puc_code from pucs where puc_type_code = '#{puc_type_code}'\").map{|g|[g.puc_code]}\n\t@puc_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('puc','puc_code',@puc_codes)%>\n\n\t\t}\n\nend",
"def create\n @addons_combo = AddonsCombo.new(addons_combo_params)\n\n respond_to do |format|\n if @addons_combo.save\n format.html { redirect_to @addons_combo, notice: 'Addons combo was successfully created.' }\n format.json { render :show, status: :created, location: @addons_combo }\n else\n format.html { render :new }\n format.json { render json: @addons_combo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def validate \n # first check whether combo fields have been selected\n#\t is_valid = true\n#\t if is_valid\n#\t is_valid = ModelHelper::Validations.validate_combos([{:stock_type_code => self.stock_type_code}],self)\n#\t end\n#\t if is_valid\n#\t is_valid = set_stock_type\n#\t end\n#\n#\t if is_valid\n#\t is_valid = ModelHelper::Validations.validate_combos([{:location_code => self.location_code}],self)\n#\t end\n#\t if is_valid\n#\t is_valid = set_location\n#\t end\n#\n#\t #if is_valid\n#\t # is_valid = ModelHelper::Validations.validate_combos([{:party_name => self.party_name}],self)\n#\t #end\n#\t #if is_valid\n#\t # is_valid = set_party\n#\t #end\n#\n#\t if is_valid\n#\t is_valid = set_parties_role\n#\t end\n#\n#\t #if is_valid\n#\t # is_valid = set_current_location\n#\t #end\n#\n# if is_valid\n# is_valid = set_status\n# end\n\t \n end",
"def update\n # Solo el admin puede crear y editar productos, asique no tiene mucho sentido validar estas acciones\n # (se le da poder total al admin, no tiene sentido restringirlo)\n ProductCategory.create(product_id: @product.id, category_id: association_changes[:add_category]).id unless association_changes[:add_category].blank?\n ProductCategory.where(category_id: association_changes[:remove_category], product_id: @product.id).delete_all unless association_changes[:remove_category].blank?\n\n ProductTag.create(product_id: @product.id, tag_id: association_changes[:add_tag]).id unless association_changes[:add_tag].blank?\n ProductTag.where(tag_id: association_changes[:remove_tag], product_id: @product.id).delete_all unless association_changes[:remove_tag].blank?\n\n respond_to do |format|\n if @product.update(product_params)\n format.html { redirect_to @product, notice: 'Product was successfully updated.' }\n format.json { render :show, status: :ok, location: @product }\n else\n format.html { render :edit }\n format.json { render json: @product.errors, status: :unprocessable_entity }\n end\n end\n end",
"def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:commodity_code => self.commodity_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_commodity\n\t end\n\t \n\tif is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:equivalent_count_from => self.equivalent_count_from}],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_equivalent_count_from\n\t end\n\t \n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:equivalent_count_to => self.equivalent_count_to}],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_equivalent_count_to\n\t end\n\t \n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def index\n @addons_combos = AddonsCombo.all\n end",
"def inventory_issue_party_type_name_search_combo_changed\n party_type_name = get_selected_combo_value(params)\n session[:inventory_issue_form][:party_type_name_combo_selection] = party_type_name\n @party_names = PartiesRole.find_by_sql(\"select distinct party_name from parties where party_type_name='#{party_type_name}'\").map{|g|[g.party_name]}\n\t@party_names.unshift(\"<empty>\")\n\trender :inline=>%{\n\t <%=select('inventory_issue','party_name',@party_names) %>\n\t <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_inventory_issue_party_name'/>\n <%= observe_field('inventory_issue_party_name', :update=>'parties_role_name_cell', :url => {:action=>session[:inventory_issue_form][:party_name_observer][:remote_method]}, :loading=>\"show_element('img_inventory_issue_party_name');\", :complete=>session[:inventory_issue_form][:party_name_observer][:on_completed_js])%>\n\t}\n end",
"def tableViewSelectionDidChange(notification)\n\t\tif notification.object == @items_table\n\t\t\t@copy_info_box.setStringValue(\"\")\n\t\t\t@info_box.setStringValue(\"\")\n\t\t @copies_table.deselectAll_ nil\n\t\t\tif @items_table.selectedRow < 0\n\t\t\t\t@copies = nil\n\t\t\t\t@customers = nil\n\t\t\t\t@item_add_button.setEnabled_(false)\n\t\t\t\t@item_edit_button.setEnabled_(false)\n\t\t\t\t@item_del_button.setEnabled_(false)\n \t @copy_add_button.setEnabled_(false)\n\t\t\telse\n\t\t\t\titem_id = @items[@items_table.selectedRow].id\n\t\t\t\t@copies = Copy.find_by_item_id(item_id) \n\t\t\t\t@item_add_button.setEnabled_(false)\n\t\t\t\t@item_edit_button.setEnabled_(true)\n\t\t\t\t@item_del_button.setEnabled_(true)\n \t @copy_add_button.setEnabled_(true)\n\t\t\t\t\n\t\t\t\t# Set the fields to the values of the selected row\n\t\t\t\t@title.setStringValue(@items[@items_table.selectedRow].title)\n\t\t\t\t@year.setStringValue(@items[@items_table.selectedRow].year)\n\t\t\t\t@genre.setStringValue(@items[@items_table.selectedRow].genre)\t\t\t\t\n\t\t\tend\n\t\t\t@copies_table.reloadData\n\t\telsif notification.object == @copies_table\n\t\t if @copies_table.selectedRow < 0\t\t\t \n \t @copy_add_button.setEnabled_(true)\n\t\t\t\t@copy_edit_button.setEnabled_(false)\n\t\t\t\t@copy_del_button.setEnabled_(false)\n\t\t\telse\n \t @copy_add_button.setEnabled_(false)\n\t\t\t\t@copy_edit_button.setEnabled_(true)\n\t\t\t\t@copy_del_button.setEnabled_(true)\n\t\t\t\t\n\t\t\t\t# Set the fields to the values of the selected row\n\t\t\t\t@copy_type.setStringValue(@copies[@copies_table.selectedRow].copy_type)\n\t\t\t\t@section_name.setStringValue(@copies[@copies_table.selectedRow].section_name)\n\t\t\t\t@wholesale_price.setStringValue(@copies[@copies_table.selectedRow].wholesale_price)\n\t\t\t\t@sale_price.setStringValue(@copies[@copies_table.selectedRow].sale_price)\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\tend\n\t\tend\n\tend",
"def order_pack_item_params\n params.require(:order_pack_item).permit(:quantity, :stock_id, :order_id)\n end",
"def get_packs_parameter_of(pack, param)\n pack = pack.id if pack.is_a? ProductPack\n @_packs_parameters = [] unless @_packs_parameters\n if @_packs_parameters[pack].nil?\n relation = self.ingridients_packs_relations.\n where(product_pack_id: pack).\n limit(1).first\n raise Errors::UnprocessableEntity if relation.nil?\n @_packs_parameters[pack] = { price: relation.price, weight: relation.weight }\n end\n @_packs_parameters[pack][param]\n end",
"def build_ripe_point_form(ripe_point,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[:ripe_point_form]= Hash.new\n\tcold_store_type_codes = ColdStoreType.find_by_sql('select distinct cold_store_type_code from cold_store_types').map{|g|[g.cold_store_type_code]}\n\tcold_store_type_codes.unshift(\"<empty>\")\n\tpc_codes = PcCode.find_by_sql('select distinct pc_code from pc_codes').map{|g|[g.pc_code]}\n\tpc_codes.unshift(\"<empty>\")\n\t#generate javascript for the on_complete ajax event for each combo for fk table: treatments\n\tcombos_js_for_treatments = gen_combos_clear_js_for_combos([\"ripe_point_treatment_type_code\",\"ripe_point_treatment_code\"])\n\t#Observers for combos representing the key fields of fkey table: treatment_id\n\ttreatment_type_code_observer = {:updated_field_id => \"treatment_code_cell\",\n\t\t\t\t\t :remote_method => 'ripe_point_treatment_type_code_changed',\n\t\t\t\t\t :on_completed_js => combos_js_for_treatments [\"ripe_point_treatment_type_code\"]}\n\n\tsession[:ripe_point_form][:treatment_type_code_observer] = treatment_type_code_observer\n\t\n\tcombos_js_for_treatments2 = gen_combos_clear_js_for_combos([\"ripe_point_treatment2_type_code\",\"ripe_point_treatment2_code\"])\n\ttreatment2_type_code_observer = {:updated_field_id => \"treatment2_code_cell\",\n\t\t\t\t\t :remote_method => 'ripe_point_treatment2_type_code_changed',\n\t\t\t\t\t :on_completed_js => combos_js_for_treatments2[\"ripe_point_treatment2_type_code\"]}\n\n#\tcombo lists for table: treatments\n\n\ttreatment_type_codes = nil \n\ttreatment_codes = nil \n treatment2_codes = nil\n \n ripe_times = RipeTime.find(:all).map {|r|r.ripe_code}\n\tripe_times.unshift(\"<empty>\")\n \n\ttreatment_type_codes = RipePoint.get_all_treatment_type_codes\n\ttreatment_type_codes.unshift(\"<empty>\")\n\tif ripe_point == nil||is_create_retry\n\t\t treatment_codes = [\"Select a value from treatment_type_code\"]\n\t\t treatment2_codes = [\"Select a value from treatment_type_code\"]\n\telse\n\t treatment_codes = RipePoint.treatment_codes_for_treatment_type_code(ripe_point.treatment.treatment_type_code)\n\t\ttreatment2_codes = RipePoint.treatment_codes_for_treatment_type_code(ripe_point.treatment2_type_code)\n\tend\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 => 'ripe_point_code'}\n\n\n\tfield_configs[1] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'ripe_point_description'}\n\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (pc_code_id) on related table: pc_codes\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[2] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'pc_code_code',\n\t\t\t\t\t\t:settings => {:list => pc_codes,:label_caption => \"pc_code\"}}\n \n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (cold_store_type_id) on related table: cold_store_types\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[3] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'cold_store_type_code',\n\t\t\t\t\t\t:settings => {:list => cold_store_type_codes}}\n \n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (treatment_id) on related table: treatments\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[4] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'treatment_type_code',\n\t\t\t\t\t\t:settings => {:list => treatment_type_codes},\n\t\t\t\t\t\t:observer => treatment_type_code_observer}\n \n\tfield_configs[5] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'treatment_code',\n\t\t\t\t\t\t:settings => {:list => treatment_codes}}\n\t\t\t\t\t\t\n\tfield_configs[6] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'treatment2_type_code',\n\t\t\t\t\t\t:settings => {:list => treatment_type_codes},\n\t\t\t\t\t\t:observer => treatment2_type_code_observer}\n \n\tfield_configs[7] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'treatment2_code',\n\t\t\t\t\t\t:settings => {:list => treatment2_codes}}\n\t\t\t\t\t\t\n\tfield_configs[8] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'ripe_code',\n\t\t\t\t\t\t:settings => {:list => ripe_times,\n\t\t\t\t\t\t :label_caption => \"ripe_time\"}}\n \n\tbuild_form(ripe_point,field_configs,action,'ripe_point',caption,is_edit)\n\n end",
"def show\n @product_combobox = ProductCombobox.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @product_combobox }\n end\n end",
"def fill_catalogue()\n @@products.clear\n add_product(Fruit.new(\"Apples\", 10))\n add_product(Fruit.new(\"Oranges\", 5))\n add_product(Fruit.new(\"Banana\", 20))\n add_product(Fruit.new(\"Watermelon\", 1))\n add_product(Houseware.new(\"Vacuum cleaner\", 150))\n add_product(Product.new(\"Anchovies\",2))\n end",
"def load_container_stack_type_code_changed\n stack_type_code = get_selected_combo_value(params)\n session[:load_container_form][:stack_type_code_combo_selection] = stack_type_code\n @ids = LoadContainer.ids_for_stack_type_code(stack_type_code)\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n render :inline => %{\n\t\t<%= select('load_container','id',@ids)%>\n\n\t\t}\n\n end",
"def update\n respond_to do |format|\n if @addons_combo.update(addons_combo_params)\n format.html { redirect_to @addons_combo, notice: 'Addons combo was successfully updated.' }\n format.json { render :show, status: :ok, location: @addons_combo }\n else\n format.html { render :edit }\n format.json { render json: @addons_combo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_commands_for_products_to_be_added!\n end",
"def build_load_voyage_form(load_voyage, 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 session[:load_voyage_form]= Hash.new\n\n \n\n\n# trading_partners = PartiesRole.find_by_sql(\"SELECT id, party_name FROM parties_roles WHERE role_name = 'TRADING_PARTNER'\").map { |g| [g.party_name, g.id] }\n exporter_party_role_ids = PartiesRole.find_by_sql(\"SELECT DISTINCT id,party_name FROM public.parties_roles WHERE parties_roles.role_name = 'EXPORTER'\").map { |g| [g.party_name, g.id] }\n\n\n shipper_party_role_ids = PartiesRole.find_by_sql(\"SELECT DISTINCT id,party_name FROM public.parties_roles WHERE parties_roles.role_name = 'SHIPPER'\").map { |g| [g.party_name, g.id] }\n\n\n shipping_agent_party_role_ids = PartiesRole.find_by_sql(\"SELECT DISTINCT id,party_name FROM public.parties_roles WHERE parties_roles.role_name = 'SHIPPING AGENT'\").map { |g| [g.party_name, g.id] }\n\n\n shipping_line_party_role_ids = PartiesRole.find_by_sql(\"SELECT DISTINCT id,party_name FROM public.parties_roles WHERE parties_roles.role_name = 'SHIPPING LINE'\").map { |g| [g.party_name, g.id] }\n\n loads = Load.find_by_sql(\"SELECT DISTINCT id,load_number FROM loads where upper(load_status) = 'LOAD_CREATED'\").map {|s|[s.load_number,s.id]}\n\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n field_configs = Array.new\n#\t----------------------------------------------------------------------------------------------------\n#\tCombo field to represent foreign key (load_id) on related table: loads\n#\t-----------------------------------------------------------------------------------------------------\n\n if is_edit == true\n field_configs[field_configs.length()] = {:field_type => 'LabelField',\n :field_name => 'load_number'}\n \n else \n\n field_configs[field_configs.length()] = {:field_type => 'DropDownField',\n :field_name => 'load_id',\n :settings => {:label_caption=>'load_number',\n :list => loads}}\n end\n\n\n field_configs[field_configs.length()] = {:field_type => 'TextField', :field_name => 'customer_reference'}\n\n field_configs[field_configs.length()] = {:field_type => 'TextField', :field_name => 'booking_reference'}\n\n field_configs[field_configs.length()] = {:field_type => 'TextField', :field_name => 'exporter_certificate_code'}\n\n field_configs[field_configs.length()] = {:field_type => 'DropDownField',\n :field_name=> 'exporter_party_role_id',\n :settings => {:label_caption => 'exporter',:show_label=> true,\n :list => exporter_party_role_ids}}\n\n field_configs[field_configs.length()] = {:field_type => 'DropDownField',\n :field_name => 'shipper_party_role_id',\n :settings => {:label_caption=>'shipper',:show_label=> true,\n :list => shipper_party_role_ids}}\n\n field_configs[field_configs.length()] = {:field_type => 'DropDownField',\n :field_name => 'shipping_agent_party_role_id',\n :settings => {:label_caption=>'shipping_agent',:show_label => true,\n :list => shipping_agent_party_role_ids}}\n \n field_configs[field_configs.length()] = {:field_type => 'DropDownField',\n :field_name => 'shipping_line_party_id',\n :settings => {:label_caption=>'shipping_line',:show_label=> true,\n :list => shipping_line_party_role_ids}}\n\n field_configs[field_configs.length()] = {:field_type => 'TextArea', :field_name => 'memo_pad'}\n\n\n build_form(load_voyage, field_configs, action, 'load_voyage', caption, is_edit)\n\n end",
"def before_save\n changed_fields?\n if(@changed_fields && @changed_fields.keys.include?('rmt_product_id') && ((bins = Bin.find_all_by_delivery_id(self.id)).length>0))\n raise \"sorry cannot change rmt_product of this delivery , #{bins.length} bin(s) have already been scanned for this delivery\"\n end\n puts\n end",
"def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\n\n\t puts \"VALID: \" + is_valid.to_s\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:system_name => self.system_name},{:subsystem_name => self.subsystem_name}],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_subsystem\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:affected_object_type_name => self.affected_object_type_name}],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_affected_object_type\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def change_supplier(supp_id=nil)\n return if supp_id.nil?\n self.update_attribute(:supplier_id, supp_id)\n\n #if having combis\n combis = OrderProcessing.where(\"combi_id = ?\", self.id)\n unless combis.empty?\n combis.each{|op| op.update_attribute(:supplier_id, supp_id) }\n end\n \n #if having splits\n splitted = OrderProcessing.where(\"parent_order_id = ?\", self.order_id)\n unless splitted.empty?\n splitted.each{|op| op.update_attribute(:supplier_id, supp_id) }\n end\n end",
"def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:artist_name => self.artist_name}],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_artist\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def relation_method\n :product\n end",
"def on_prepare_commit(unit, aggregates, events); end",
"def contact_methods_party_party_type_name_search_combo_changed\n\tparty_type_name = get_selected_combo_value(params)\n\tsession[:contact_methods_party_search_form][:party_type_name_combo_selection] = party_type_name\n\t@party_names = ContactMethodsParty.find_by_sql(\"Select distinct party_name from contact_methods_parties where party_type_name = '#{party_type_name}'\").map{|g|[g.party_name]}\n\t@party_names.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('contact_methods_party','party_name',@party_names)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_contact_methods_party_party_name'/>\n\t\t<%= observe_field('contact_methods_party_party_name',:update => 'contact_method_type_code_cell',:url => {:action => session[:contact_methods_party_search_form][:party_name_observer][:remote_method]},:loading => \"show_element('img_contact_methods_party_party_name');\",:complete => session[:contact_methods_party_search_form][:party_name_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def update_products_details; end",
"def build_composite\n return if authorise_for_web(program_name?,'edit')== false \n\t id = params[:id]\n\t if id && @product = Product.find(id)\n\t session[:root_composite]= @product\n\t\trender :inline => %{\n\t\t<% @content_header_caption = \"'build composite pack material product'\"%> \n\n\t\t<% @tree_script = build_composite_tree(@product)%>\n\n\t\t}, :layout => 'tree'\n\n\t end\n\t \nend",
"def build_standard_count_form(standard_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_count_form]= Hash.new\n\t\n\tcommodity_codes = Commodity.find_by_sql('select distinct commodity_code from commodities').map{|g|[g.commodity_code]}\n\tcommodity_codes.unshift(\"<empty>\")\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n\t field_configs = Array.new\n#\t----------------------------------------------------------------------------------------------\n#\tCombo fields to represent foreign key (commodity_id) on related table: commodities\n#\t----------------------------------------------------------------------------------------------\n\tfield_configs[0] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'standard_count_value'}\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\t\t\t\t\t\t\t\t\t\t\t\n\tfield_configs[2] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'size_count_description'}\n\n\n\tfield_configs[3] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'minimum_size_mm'}\n\n\tfield_configs[4] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'maximum_size_mm'}\n\n\tfield_configs[5] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'average_size_mm'}\n\n\tfield_configs[6] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'minimum_weight_gm'}\n\n\tfield_configs[7] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'maximum_weight_gm'}\n\n\tfield_configs[8] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'average_weight_gm'}\n\n\tfield_configs[9] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'count_interval_group'}\n\n\tfield_configs[10] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'marketing_size_range_mm'}\n\n\tfield_configs[11] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'marketing_weight_range'}\n\n\tfield_configs[12] = {:field_type => 'DateField',\n\t\t\t\t\t\t:field_name => 'date_from'}\n\n\tfield_configs[13] = {:field_type => 'DateField',\n\t\t\t\t\t\t:field_name => 'date_to'}\n\n\t\n\tbuild_form(standard_count,field_configs,action,'standard_count',caption,is_edit)\n\nend",
"def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def set_product\n \n end",
"def build_cartons_grid(data_set, is_multi_select = nil)\n\n column_configs = Array.new\n\n\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'carton_number', :col_width => 120}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'pallet_number', :col_width => 150}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'rw_receipt_unit'} if is_multi_select\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'production_run_code', :col_width => 158}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'fg_product_code', :col_width => 294}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'fg_mark_code', :col_width => 170}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => \"attributes['farm_code']\", :column_caption => \"farm_code\", :col_width => 76}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'puc', :col_width => 76}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'fg_code_old', :col_width => 161}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'organization_code', :col_width => 40}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'grade_code', :col_width => 40}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'inventory_code', :col_width => 140}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'target_market_code', :col_width => 130}\n\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'extended_fg_code', :col_width => 516}\n\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => \"attributes['line_code']\", :column_caption => \"line_code\", :col_width => 47}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'order_number', :col_width => 150}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'pack_date_time', :col_width => 162}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'pick_reference', :col_width => 56}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'is_inspection_carton', :col_width => 45}\n\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'carton_fruit_nett_mass', :col_width => 60,:column_caption => 'mass'}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'id'}\n column_configs[column_configs.length()] = {:field_type => 'text', :field_name => 'bin_id'}\n\n if !@multi_select\n column_configs[column_configs.length()] = {:field_type => 'action', :field_name => 'carton',\n :settings =>\n {:link_text => 'view_carton',\n :target_action => 'view_carton',\n :id_column => 'id'}}\n end\n\n\n key_based_access = true\n key_based_access = @key_based_access if @key_based_access\n\n\n return get_data_grid(data_set, column_configs, nil, key_based_access)\n\n end",
"def validate \n#\tfirst check whether combo fields have been selected\n\t is_valid = true\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:commodity_code => self.commodity_code},{:rmt_variety_code => self.rmt_variety_code}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_rmt_variety\n\t end\n\t if is_valid\n\t\t is_valid = ModelHelper::Validations.validate_combos([{:season_code => self.season_code},{:id => self.id}],self) \n\tend\n\t#now check whether fk combos combine to form valid foreign keys\n\t if is_valid\n\t\t is_valid = set_season\n\t end\n\t#validates uniqueness for this record\n\t if self.new_record? && is_valid\n\t\t validate_uniqueness\n\t end\nend",
"def cpc_changed\n\n session[:selected_cpc]= get_selected_combo_value(params)\n set_calculated_mass\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.4982876",
"0.49658042",
"0.49647874",
"0.49569634",
"0.49330974",
"0.4927405",
"0.49268207",
"0.49176392",
"0.49007976",
"0.48974144",
"0.48895624",
"0.48881936",
"0.48872328",
"0.4870539",
"0.48614633",
"0.48525912",
"0.48449165",
"0.4840583",
"0.48055333",
"0.47882557",
"0.47837484",
"0.4775639",
"0.47751254",
"0.4769096",
"0.47652352",
"0.47610506",
"0.47597352",
"0.47272205",
"0.47269034",
"0.47259003",
"0.4717123",
"0.46988693",
"0.46952155",
"0.46937904",
"0.46884707",
"0.46710995",
"0.46690786",
"0.46633875",
"0.46625915",
"0.46616668",
"0.46610343",
"0.46589297",
"0.46550032",
"0.46547833",
"0.4644219",
"0.463865",
"0.46367115",
"0.46323332",
"0.46269476",
"0.46245572",
"0.4618591",
"0.4613061",
"0.4599831",
"0.45965692",
"0.45943937",
"0.45823985",
"0.45790073",
"0.45786548",
"0.4573747",
"0.4562586",
"0.45574102",
"0.45444214",
"0.45443597",
"0.45255747",
"0.4524988",
"0.45229083",
"0.45226565",
"0.45221114",
"0.4520019",
"0.4512711"
] | 0.6645778 | 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.